-
Notifications
You must be signed in to change notification settings - Fork 1
/
main.go
109 lines (99 loc) · 2.16 KB
/
main.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
package main
import (
"flag"
"fmt"
"log"
"os"
)
func main() {
flag.Usage = func() {
fmt.Fprint(os.Stderr, helpMess)
}
log.SetFlags(0) // hide timestamp
// to read arg by flag, we must parse first
flag.Parse()
err := execCommand()
if err != nil {
log.Fatal(err)
}
}
func execCommand() error {
command := getArg(0, helpMess)
switch command {
case "info":
path := getArg(1, "Enter path")
fileInfo, err := os.Stat(path)
if err != nil {
return err
}
fmt.Printf("Name: %s\nSize: %d\nMode: %s,\nIsDir: %t\nModification: %s\n",
fileInfo.Name(),
fileInfo.Size(),
fileInfo.Mode(),
fileInfo.IsDir(),
fileInfo.ModTime(),
)
case "ls": // list file
files, err := os.ReadDir(".")
if err != nil {
return err
}
for _, file := range files {
fmt.Printf("%s ", file.Name())
}
fmt.Println()
case "rm": // delete file
path := getArg(1, "Enter path")
return os.RemoveAll(path)
case "pwd": // current path
currentPath, err := os.Getwd()
if err != nil {
return err
}
fmt.Println(currentPath)
case "mv": // move file
path1 := getArg(1, "Enter path 1")
path2 := getArg(2, "Enter path 2")
return os.Rename(path1, path2)
case "mkdir": // create dir
path := getArg(1, "Enter Dir")
return os.MkdirAll(path, 0777)
case "cat":
path := getArg(1, "Enter path")
data, err := os.ReadFile(path)
if err != nil {
return err
}
os.Stdout.Write(data)
case "touch": // create empty file
path := getArg(1, "Enter path")
_, err := os.Create(path)
return err
case "cp": // copy file
// path old file
path1 := getArg(1, "Enter path 1")
// path new file
path2 := getArg(2, "Enter path 2")
data, err := os.ReadFile(path1)
if err != nil {
return err
}
return os.WriteFile(path2, data, 0777)
case "echo": // add content to file
content := getArg(1, "Enter content")
path := getArg(2, "Enter path")
return os.WriteFile(path, []byte(content), 0777)
default:
fmt.Print(helpMess)
}
return nil
}
// this function must get arg
// if user not enter arg , it will break and show error
func getArg(indexArg int, mess string) string {
val := flag.Arg(indexArg)
if val == "" {
log.Fatal(mess)
}
return val
}