-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathmain.go
More file actions
217 lines (177 loc) · 5.84 KB
/
main.go
File metadata and controls
217 lines (177 loc) · 5.84 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
package main
import (
"fmt"
"io/ioutil"
"os"
"path/filepath"
"text/template"
"github.com/spf13/cobra"
)
func main() {
// Создание командной строки
var rootCmd = &cobra.Command{Use: "gencli.exe"}
// Создание нового файла
var createFileCmd = &cobra.Command{
// Передаем информацию о команде для использования в консоли
Use: "createfile [file-name]",
Short: "Create a new file in the current directory",
Args: cobra.ExactArgs(1),
Run: func(cmd *cobra.Command, args []string) {
fileName := args[0]
// Получаем путь к директории, где находится исполняемый файл
exePath, err := os.Executable()
if err != nil {
fmt.Printf("Failed to get executable path: %s\n", err)
return
}
// Извлекаем директорию из пути к исполняемому файлу
projectDir := filepath.Dir(exePath)
// Создаем новый файл в директории проекта
filePath := filepath.Join(projectDir, fileName)
file, err := os.Create(filePath)
if err != nil {
fmt.Printf("Failed to create file: %s\n", err)
return
}
defer file.Close()
fmt.Printf("Created file: %s\n", filePath)
},
}
// Добавляем команду в консоль
rootCmd.AddCommand(createFileCmd)
// Создание новой директории
var createDirCmd = &cobra.Command{
Use: "createdir [dir-name]",
Short: "Create a new directory in the current directory",
Args: cobra.ExactArgs(1),
Run: func(cmd *cobra.Command, args []string) {
dirName := args[0]
exePath, err := os.Executable()
if err != nil {
fmt.Printf("Failed to get executable path: %s\n", err)
return
}
projectDir := filepath.Dir(exePath)
dirPath := filepath.Join(projectDir, dirName)
if err := os.Mkdir(dirPath, os.ModePerm); err != nil {
fmt.Printf("Failed to create directory: %s\n", err)
return
}
fmt.Printf("Created directory: %s\n", dirPath)
},
}
rootCmd.AddCommand(createDirCmd)
// Удаление файла
var deleteFileCmd = &cobra.Command{
Use: "deletefile [file-name]",
Short: "Delete a file in the current directory",
Args: cobra.ExactArgs(1),
Run: func(cmd *cobra.Command, args []string) {
fileName := args[0]
exePath, err := os.Executable()
if err != nil {
fmt.Printf("Failed to get executable path: %s\n", err)
return
}
projectDir := filepath.Dir(exePath)
filePath := filepath.Join(projectDir, fileName)
if err := os.Remove(filePath); err != nil {
fmt.Printf("Failed to delete file: %s\n", err)
return
}
fmt.Printf("Deleted file: %s\n", filePath)
},
}
rootCmd.AddCommand(deleteFileCmd)
// Удаление директории
var deleteDirCmd = &cobra.Command{
Use: "deletedir [dir-name]",
Short: "Delete a directory in the current directory",
Args: cobra.ExactArgs(1),
Run: func(cmd *cobra.Command, args []string) {
dirName := args[0]
exePath, err := os.Executable()
if err != nil {
fmt.Printf("Failed to get executable path: %s\n", err)
return
}
projectDir := filepath.Dir(exePath)
dirPath := filepath.Join(projectDir, dirName)
if err := os.RemoveAll(dirPath); err != nil {
fmt.Printf("Failed to delete directory: %s\n", err)
return
}
fmt.Printf("Deleted directory: %s\n", dirPath)
},
}
rootCmd.AddCommand(deleteDirCmd)
// Генерация кода по шаблону
var generateCmd = &cobra.Command{
Use: "generate [template] [output] --name [name]",
Short: "Generate code based on template",
Args: cobra.ExactArgs(2),
Run: func(cmd *cobra.Command, args []string) {
templateName := args[0]
outputFileName := args[1]
name, _ := cmd.Flags().GetString("name")
exePath, err := os.Executable()
if err != nil {
fmt.Printf("Failed to get executable path: %s\n", err)
return
}
executableDir := filepath.Dir(exePath)
templatePath := filepath.Join(executableDir, "templates", templateName)
outputPath := filepath.Join(executableDir, outputFileName)
// Загрузить содержимое шаблона из файла
templateContent, err := ioutil.ReadFile(templatePath)
if err != nil {
fmt.Printf("Failed to read template file: %s\n", err)
return
}
// Создать шаблон и вставить значение в него
tmpl, err := template.New("codeTemplate").Parse(string(templateContent))
if err != nil {
fmt.Printf("Failed to parse template: %s\n", err)
return
}
data := struct {
Name string
}{
Name: name,
}
// Создать выходной файл и записать в него результат
outputFile, err := os.Create(outputPath)
if err != nil {
fmt.Printf("Failed to create output file: %s\n", err)
return
}
defer outputFile.Close()
if err := tmpl.Execute(outputFile, data); err != nil {
fmt.Printf("Failed to generate code: %s\n", err)
return
}
fmt.Printf("Generated code from template %s to %s\n", templatePath, outputPath)
},
}
generateCmd.Flags().String("name", "", "Name to insert into the template")
rootCmd.AddCommand(generateCmd)
// Получение информации о текущей директории
var currentDirCmd = &cobra.Command{
Use: "currentdir",
Short: "Show the current working directory",
Run: func(cmd *cobra.Command, args []string) {
currentDir, err := os.Getwd()
if err != nil {
fmt.Printf("Failed to get current directory: %s\n", err)
return
}
fmt.Printf("Current working directory: %s\n", currentDir)
},
}
rootCmd.AddCommand(currentDirCmd)
// Если в консоль введены неверные аргументы
if err := rootCmd.Execute(); err != nil {
fmt.Println(err)
os.Exit(1)
}
}