/
cli.go
298 lines (260 loc) · 7.56 KB
/
cli.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
package main
import (
"strings"
"bufio"
"fmt"
"os"
"io"
"regexp"
"unicode/utf8"
flags "github.com/jessevdk/go-flags"
//"github.com/k0kubun/pp"
)
// Exit codes are int values that represent an exit code for a particular error.
const (
ExitCodeOK int = 0
ExitCodeError int = 1 + iota
)
// CLI is the command line object
type CLI struct {
// outStream and errStream are the stdout and stderr
// to write message from the CLI.
outStream, errStream io.Writer
}
type CronDetail struct {
commentOutLines []string
titleLines []string
authorLines []string
paramLines []string
cronLines []string
envLines []string
}
var cronFormat = []string{"min", "hour", "day", "month", "day week"}
type cmdOptions struct {
// tFilePath string `short:"f" long:"file"`
Stdin bool `short:"s" long:"stdin"`
Format string `long:"format"`
Version bool `short:"v" long:"version"`
Help bool `short:"h" long:"help"`
}
// Run invokes the CLI with the given arguments.
func (cli *CLI) Run(args []string) int {
//get args,opt
opts := &cmdOptions{}
p := flags.NewParser(opts, flags.PrintErrors)
p.Name = Name
args, err := p.Parse()
if err != nil {
fmt.Print("Opt Parse Error\n")
return ExitCodeError
}
if len(args) > 0 || opts.Stdin{
var lines[] string
//from stdin
if opts.Stdin {
lines = GetCronLines("")
}
//from file
if len(args) > 0 {
filePath := args[0]
// if(filePath != "/etc/crontab"){
// cronFormat = cronFormat[0:5]
// }
lines = GetCronLines(filePath)
}
//parse crontab
cronDetails, commentOutDetails := ParseLines(lines)
//TODO other format
OutputMarkDown(cronDetails, commentOutDetails)
return ExitCodeOK
}
//version
if opts.Version {
fmt.Print(GetVersion())
return ExitCodeOK
}
//help
if opts.Help {
fmt.Print(GetHelp())
return ExitCodeOK
}
fmt.Print(GetHelp())
return ExitCodeOK
}
//get crontab
func GetCronLines(filePath string) []string {
var scanner *bufio.Scanner
//file or Stdin
if len(filePath) > 0 {
var fp *os.File
var err error
//exist filapath
_, err = os.Stat(filePath)
if err != nil {
fmt.Fprintf(os.Stderr, "File %s not exist: %v\n", filePath, err)
os.Exit(1)
}
//read file
fp, err = os.Open(filePath)
if err != nil {
fmt.Fprintf(os.Stderr, "File %s could not read: %v\n", filePath, err)
os.Exit(1)
}
defer fp.Close()
scanner = bufio.NewScanner(fp)
}else{
//read stdin
scanner = bufio.NewScanner(os.Stdin)
}
lines := make([]string, 100)
for scanner.Scan() {
lines = append(lines, scanner.Text())
}
if err := scanner.Err(); err != nil {
fmt.Fprintf(os.Stderr, "scan error: %v\n", err)
panic(err)
}
return lines
}
//crontab parse
func ParseLines(lines []string) ([]CronDetail, []CronDetail) {
cronDetails := [] CronDetail{}
commentOutDetails := [] CronDetail{}
tmpLines := make([]string, 0)
for i, _ := range lines {
tmpLine := strings.TrimSpace(lines[i])
if utf8.RuneCountInString(tmpLine) <= 0 {
// To the group until Line break
if len(tmpLines) > 0 {
cronDetail := MakeCronDetail(tmpLines)
if len(cronDetail.cronLines) > 0 || len(cronDetail.envLines) > 0 {
cronDetails = append(cronDetails, cronDetail)
}else{
commentOutDetails = append(commentOutDetails, cronDetail)
}
tmpLines = make([]string, 0)
}
}else{
tmpLines = append(tmpLines, tmpLine)
}
}
return cronDetails, commentOutDetails
}
func MakeCronDetail(tmpLines []string) CronDetail {
var cronDetail CronDetail
for i, _ := range tmpLines {
bool, _ := regexp.MatchString("^#", strings.TrimSpace(tmpLines[i]))
if bool {
boolTitle, _ := regexp.MatchString("@title", tmpLines[i])
boolAuthor, _ := regexp.MatchString("@author", tmpLines[i])
boolParam, _ := regexp.MatchString("@param", tmpLines[i])
//Divided into each tag
if boolTitle {
cronDetail.titleLines = append(cronDetail.titleLines, tmpLines[i])
} else if boolAuthor {
cronDetail.authorLines = append(cronDetail.authorLines, tmpLines[i])
}else if boolParam{
cronDetail.paramLines = append(cronDetail.paramLines, tmpLines[i])
}else{
cronDetail.commentOutLines = append(cronDetail.commentOutLines, tmpLines[i])
}
}else if boolEnv, _ := regexp.MatchString("(^SHELL|^PATH|^MAILTO|^HOME)", strings.TrimSpace(tmpLines[i])); boolEnv {
cronDetail.envLines = append(cronDetail.envLines, tmpLines[i])
}else{
cronDetail.cronLines = append(cronDetail.cronLines, tmpLines[i])
}
}
return cronDetail
}
func OutputMarkDown(cronDetails []CronDetail, commentOutDetails []CronDetail){
fmt.Print("# effective crontab\n\n")
MarkDownCronDoc(cronDetails)
fmt.Print("# commentout crontab\n\n")
MarkDownCronDoc(commentOutDetails)
fmt.Print("\n\ngenerated by crondoc")
}
func MarkDownCronDoc(cronDetails []CronDetail ) {
for i, _ := range cronDetails {
//title line
for j, _ := range cronDetails[i].titleLines {
pos := strings.Index(cronDetails[i].titleLines[j], "@title") + len("@title")
fmt.Printf("## %s\n\n", strings.TrimSpace(cronDetails[i].titleLines[j][pos:]))
}
//author line
for j, _ := range cronDetails[i].authorLines {
pos := strings.Index(cronDetails[i].authorLines[j], "@author") + len("@author")
fmt.Printf("- Author : %s\n", strings.TrimSpace(cronDetails[i].authorLines[j][pos:]))
}
//param line
for j, _ := range cronDetails[i].paramLines {
pos := strings.Index(cronDetails[i].paramLines[j], "@param") + len("@param")
fmt.Printf("- Param : %s\n", strings.TrimSpace(cronDetails[i].paramLines[j][pos:]))
}
//comment outed
if len(cronDetails[i].commentOutLines) > 0 {
for j, _ := range cronDetails[i].commentOutLines {
rep := regexp.MustCompile(`^#+`)
cronDetails[i].commentOutLines[j] = rep.ReplaceAllString(cronDetails[i].commentOutLines[j], "")
fmt.Printf(" - %s\n", strings.TrimSpace(cronDetails[i].commentOutLines[j]))
}
}
//env setting
if len(cronDetails[i].envLines) > 0 {
fmt.Print("### Environment variable\n\n")
for j, _ := range cronDetails[i].envLines {
fmt.Printf(" - %s\n", strings.TrimSpace(cronDetails[i].envLines[j]))
}
}
//cron setting
if len(cronDetails[i].cronLines) > 0 {
//command header
var tmpFormat string
for _, val := range cronFormat {
tmpFormat = tmpFormat + val + "|"
}
fmt.Printf("\n| %scommand |\n", tmpFormat)
fmt.Print("|:---|:---|:---|:---|:---|:---|\n")
for j, _ := range cronDetails[i].cronLines {
//fmt.Printf("%s\n", strings.TrimSpace(cronDetails[i].cronLines[j]))
rep := regexp.MustCompile(`( |\t)+`)
arrCommand := rep.Split(strings.TrimSpace(cronDetails[i].cronLines[j]), 6)
for k, _ := range arrCommand {
if len(cronFormat) > k {
if k == 4 {
//day of week
resStr := ReplaceDayOfWeek(arrCommand[k])
fmt.Printf("| %s", strings.TrimSpace(resStr))
}else{
fmt.Printf("| %s", strings.TrimSpace(arrCommand[k]))
}
}else{
fmt.Printf("| `%s` |\n", strings.TrimSpace(arrCommand[k]))
}
}
}
}
fmt.Print("\n\n***\n\n")
}
}
// replace number -> day of week
func ReplaceDayOfWeek(str string) string {
r := strings.NewReplacer("0","Sun", "1", "Mon", "2", "Tue", "3", "Wed", "4", "Thu", "5", "Fri", "6", "Sat", "7", "Sun")
resStr := r.Replace(str)
return resStr
}
func GetHelp() string {
helpText := `
usage: crondoc [OPTIONS] <args> crontab_path
argument
generate crontab document from <args> crontab_path
Available options are:
-v --version print versions
-h --help print help
-s --stdin generate crontab document from stdin
`
return strings.TrimSpace(helpText)
}
func GetVersion() string {
versionText := Name + " version " + Version
return strings.TrimSpace(versionText)
}