-
Notifications
You must be signed in to change notification settings - Fork 0
/
commands.go
455 lines (389 loc) · 10.9 KB
/
commands.go
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
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
package main
import (
"fmt"
"io"
"io/fs"
"log/slog"
"os"
"path"
"path/filepath"
"sync"
"time"
"github.com/BarunW/headstart/assert"
"gopkg.in/ini.v1"
)
type Command string
type SubCommand string
type FlagsAndDescrip map[Command]string
type SubCommandsAndDescrip map[SubCommand]string
type FileType string
const (
LINK Command = "link"
GEN Command = "gen"
//Copy Content
CopyContent Command = "cc"
Delete Command = "delete"
)
// first arg for subcommand
const (
FILE FileType = "file"
DIR FileType = "dir"
)
// ALL sections
type Section string
const (
SECTION_COMMANDS Section = "Commands"
SECTION_TYPES Section = "LINK_TYPE"
)
const CONFIG_FILE string = "config.ini"
type UserCommand map[SubCommand]string
type HSCommands struct {
configFilePath string
}
// This parameter
func (hs *HSCommands) createCONFIG_FILE(s ...string) {
var configFile string = CONFIG_FILE
if s != nil && len(s) > 0{
configFile = s[0]
}
fh := NewFileHandler()
exPath, err := fh.GetExecutablePath()
if err != nil {
os.Exit(1)
}
exPath = path.Join(filepath.Dir(exPath), configFile)
var f = func(error) {
if os.IsNotExist(err) {
cfg := ini.Empty()
if err := cfg.SaveTo(exPath); err != nil {
slog.Error("Unable to setup", "DETAILS", err.Error())
os.Exit(1)
}
hs.configFilePath = path.Join(exPath, configFile)
return
}
slog.Error("Failed to open the file", "DETAILS", err.Error())
os.Exit(1)
}
_, err = ini.Load(exPath)
if err != nil {
f(err)
}
// fmt.Println(exPath)
hs.configFilePath = exPath
}
func NewHSCommands(filePath ...string) HSCommands {
hs := HSCommands{}
hs.createCONFIG_FILE(filePath...)
return hs
}
func checkLength(expectedLength, theLength int) bool {
if theLength != expectedLength {
fmt.Printf("%d arguments expected", expectedLength)
return false
}
return true
}
func isFile(filePath string) error {
fs, err := os.Stat(filePath)
if err != nil {
slog.Error("Please provide a file", filePath, err.Error())
return err
}
isFile := fs.Mode().IsRegular()
if !isFile {
return fmt.Errorf("This is not a file")
}
return nil
}
func isFolder(dirPath string) error {
fs, err := os.Stat(dirPath)
if err != nil {
slog.Error("Please provide a file", dirPath, err.Error())
return err
}
_isDir := fs.IsDir()
if !_isDir {
return fmt.Errorf("This is not a dir")
}
return nil
}
// this function produce a side effect that exit on err on failing
// certain condition
func (hs HSCommands) handleLinkCommand(fType FileType, subcmd ...string) {
var (
cfg *ini.File
err error
commandSection *ini.Section
linkSection *ini.Section
linkPath string
)
linkPath, err = filepath.Abs(subcmd[0])
if err != nil {
slog.Error("Unable to convert to abs path", "Details", err.Error())
os.Exit(1)
}
// fmt.Println("LINK PATH", linkPath)
cfg, err = ini.Load(hs.configFilePath)
if err != nil {
slog.Error("Unable to load the file", "DETAILS", err.Error())
os.Exit(1)
}
// Create the neccessary section in the config file
commandSection = cfg.Section(string(SECTION_COMMANDS))
linkSection = cfg.Section(string(SECTION_TYPES))
// key that associate with a link file
cmdKey := subcmd[1]
// check the input key is already exist or !exist
// if exist throw error
if commandSection.HasKey(cmdKey) {
slog.Error("This key is already link")
os.Exit(1)
}
// if !exist link with the input command key
commandSection.NewKey(cmdKey, linkPath)
linkSection.NewKey(cmdKey, string(fType))
if err := cfg.SaveTo(hs.configFilePath); err != nil {
slog.Error("Failed to save the file", "DETAILS", err.Error())
os.Exit(1)
}
fmt.Println("Sucessfully Linked")
return
}
// this function have a side effect of panic if file aren't able to close
func handleFileGeneration(desPath string, srcPath string) error {
fh := NewFileHandler()
f2W, err := fh.OpenDezzFile(desPath)
if err != nil {
slog.Error("Unable to open the input file", "DETAILS", err.Error())
return err
}
f2R, err := fh.OpenDezzReadFile(srcPath)
if err != nil {
slog.Error("Unable to get the file that links to the command", "DETAILS", err.Error())
os.Exit(1)
}
defer func() {
if err := f2W.Close(); err != nil {
panic(err)
}
if err := f2R.Close(); err != nil {
panic(err)
}
}()
_, err = io.Copy(f2W, f2R)
if err != nil {
slog.Error("Failed to write the file", "DETAILS", err.Error())
return err
}
return nil
}
func handleDirGeneration(srcPath string, destPath string) error {
now := time.Now()
fileSystem := os.DirFS(srcPath)
wg := sync.WaitGroup{}
var HandleFileFn = func(src fs.File, des os.File) {
defer func() { src.Close(); des.Close() }()
_, err := io.Copy(&des, src)
if err != nil {
wg.Done()
return
}
wg.Done()
}
err := fs.WalkDir(fileSystem, ".", func(fpath string, d fs.DirEntry, err error) error {
if d.IsDir() {
if err := os.Mkdir(path.Join(destPath, fpath), os.ModePerm); err != nil {
slog.Error("Unable to create the dir", "DETAILS", err.Error())
return err
}
}
if d.Type().IsRegular() {
src, err := fileSystem.Open(fpath)
if err != nil {
slog.Error("Unable to open the source file", "DETAILS", err.Error())
return err
}
des, err := os.Create(path.Join(destPath, fpath))
if err != nil {
slog.Error("Unable to create the destination file", "DETAILS", err.Error())
return err
}
wg.Add(1)
go HandleFileFn(src, *des)
}
return nil
})
wg.Wait()
if err != nil {
slog.Error("Unable to execute the command", "DETATILS", err.Error())
return err
}
fmt.Println(time.Since(now))
return nil
}
func(hs HSCommands) searchKey(key, section string ) (string, error){
cfg, err := ini.Load(hs.configFilePath)
if err != nil {
return "", err
}
// cmdkey is command key that is linked in the config file
iniKey := cfg.Section(section).Key(key)
if iniKey.Value() == ""{
return "", fmt.Errorf("%s Key not found in %s Section Please link before use", key, section)
}
return iniKey.Value(), nil
}
func (hs HSCommands) handleCopyContent(subcmd ...string){
filePath, err := hs.searchKey(subcmd[0], string(SECTION_COMMANDS))
if err != nil {
slog.Error("Failed to Load config file", "DETAILS", err.Error())
os.Exit(1)
}
// cmdkey is command key that is linked in the config file
fileType, err := hs.searchKey(subcmd[0], string(SECTION_TYPES))
if err != nil {
slog.Error("Failed to Load config file", "DETAILS", err.Error())
os.Exit(1)
}
if FileType(fileType) != FILE{
slog.Error("Copy Content Works only for file", "Details", "Please provide a file")
os.Exit(1)
}
if err := handleFileGeneration(subcmd[1], filePath); err != nil{
slog.Error("Failed to copy content", "DETAILS", err.Error())
os.Exit(1)
}
}
func (hs HSCommands) handlGenCommand(subcmd ...string) {
filePath, err := hs.searchKey(subcmd[0], string(SECTION_COMMANDS))
if err != nil {
slog.Error("Failed to Load config file", "DETAILS", err.Error())
os.Exit(1)
}
// cmdkey is command key that is linked in the config file
fileType, err := hs.searchKey(subcmd[0], string(SECTION_TYPES))
if err != nil {
slog.Error("Failed to Load config file", "DETAILS", err.Error())
os.Exit(1)
}
switch FileType(fileType) {
case FILE:
// strip out the extension of the file
ext := path.Ext(filePath)
// add to the destination file
destPath := subcmd[1] + ext
srcPath := filePath
if err := handleFileGeneration(destPath, srcPath); err != nil {
os.Exit(1)
}
case DIR:
handleDirGeneration(filePath, subcmd[1])
}
}
func GetData(configPath string) *Data {
d, err := NewData(configPath)
if err != nil {
assert.Assert("While calling NewData()", "commands.go/GetData()", true)
os.Exit(1)
}
return d
}
func (hs HSCommands) DeleteLink(key string){
cfg, err := ini.Load(hs.configFilePath)
if err != nil {
slog.Error("Unable to load the config.ini file", "Reason", err.Error())
os.Exit(1)
}
fmt.Println(key)
// cmdkey is command key that is linked in the config file
cfg.Section(string(SECTION_COMMANDS)).DeleteKey(key)
cfg.Section(string(SECTION_TYPES)).DeleteKey(key)
if err := cfg.SaveTo(hs.configFilePath); err != nil{
slog.Error("Unable to save the config.ini file", "Reason", err.Error())
os.Exit(1)
}
fmt.Println("Sucessfully delete the link")
}
// it is growing need to refactor
func (hc HSCommands) processCommandWithSubcmd(cmd Command, subcmd ...string) {
switch cmd {
case LINK:
if isValid := checkLength(2, len(subcmd)); !isValid {
assert.Assert("There should be 2 subcommands", "user error", false)
return
}
if err := isFile(subcmd[0]); err == nil {
hc.handleLinkCommand(FILE, subcmd...)
} else if dErr := isFolder(subcmd[0]); dErr == nil {
hc.handleLinkCommand(DIR, subcmd...)
}
case GEN:
if isValid := checkLength(2, len(subcmd)); !isValid {
assert.Assert("There should be 3 subcommands", "user error", false)
return
}
hc.handlGenCommand(subcmd...)
case CopyContent:
if isValid := checkLength(2, len(subcmd)); !isValid {
assert.Assert("There should be 3 subcommands", "user error", false)
return
}
hc.handleCopyContent(subcmd...)
case Delete:
if isValid := checkLength(1, len(subcmd)); !isValid {
assert.Assert("There should be 3 subcommands", "user error", false)
return
}
hc.DeleteLink(subcmd[0])
default:
if cmd != "" && len(subcmd) == 1 {
txtEditor := NewExecuteCommand(*GetData(hc.configFilePath))
txtEditor.OpenTextEditor(string(cmd), subcmd[0])
}
}
}
func (hs *HSCommands) ShowAllCommands() {
fh := NewFileHandler()
cfg, err := fh.OpenConfigFile(hs.configFilePath)
if err != nil {
slog.Error("Unable to open config file", "Details", err.Error())
os.Exit(1)
}
cmdSecton := cfg.Section(string(SECTION_COMMANDS))
keys := cmdSecton.Keys()
keysString := cmdSecton.KeyStrings()
for i := 0; i < len(keysString); i++ {
fmt.Println(keysString[i], " = ", keys[i].Value())
}
}
func (hs *HSCommands) LinkOutPut(cmd string){
fh := NewFileHandler()
cfg, err := fh.OpenConfigFile(hs.configFilePath)
if err != nil {
slog.Error("Unable to open config file", "Details", err.Error())
os.Exit(1)
}
iniKey, err := cfg.Section(string(SECTION_COMMANDS)).GetKey(cmd)
if err != nil || iniKey.String() == ""{
slog.Error("Unable to find the get the link from config file", "Details", err.Error())
os.Exit(1)
}
_, err = fmt.Fprint(os.Stdout, iniKey.String())
if err != nil{
slog.Error("Unable to give the output", "Details", err.Error())
os.Exit(1)
}
}
func (hs *HSCommands) CommandsForDisplay() FlagsAndDescrip {
var c FlagsAndDescrip = make(FlagsAndDescrip)
// add the command in the lookup table
c[LINK] = "link with either module/dir/folder or file"
c[GEN] = "do code gen"
return c
}
func (hs *HSCommands) SubCommandsForDisplay() SubCommandsAndDescrip {
var s SubCommandsAndDescrip = make(SubCommandsAndDescrip)
// add the command in the lookup table
return s
}