-
Notifications
You must be signed in to change notification settings - Fork 2
/
main.go
112 lines (89 loc) · 2.15 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
110
111
112
package main
import (
"fmt"
"os"
"github.com/arrow2nd/gomi-rename/generator"
"github.com/spf13/pflag"
)
type exitCode int
func (e exitCode) getInt() int {
return int(e)
}
const (
exitCodeOK exitCode = iota
exitCodeParseErr
exitCodeArgErr
exitCodeGenErr
exitCodeReadFileErr
exitCodeRenameErr
)
var (
appName = "gomi-rename"
appDesc = "CLI tool for renaming to hellish file names"
appVersion = "develop"
flags = pflag.NewFlagSet(appName, pflag.ContinueOnError)
)
func init() {
flags.IntP("number", "n", 5, "number of decorations to add to file name")
flags.BoolP("dryrun", "d", false, "show execution results")
flags.BoolP("version", "v", false, "show version")
flags.BoolP("help", "h", false, "show help")
}
func main() {
// パース
if err := flags.Parse(os.Args[1:]); err != nil {
exitErr(err.Error(), exitCodeParseErr)
}
// ヘルプ表示
if help, _ := flags.GetBool("help"); help {
exitHelp()
}
// バージョン表示
if ver, _ := flags.GetBool("version"); ver {
fmt.Printf("%s v.%s\n", appName, appVersion)
os.Exit(exitCodeOK.getInt())
}
// 引数不足
if flags.NArg() <= 0 {
exitErr("please specify one or more file names", exitCodeArgErr)
}
num, _ := flags.GetInt("number")
isDryRun, _ := flags.GetBool("dryrun")
for _, path := range flags.Args() {
// ファイル名を生成
newFileName, err := generator.Gen(path, num)
if err != nil {
exitErr(err.Error(), exitCodeGenErr)
}
fmt.Println(newFileName)
// ドライランなら処理を中断
if isDryRun {
continue
}
// ファイルの存在確認
if f, err := os.Stat(path); os.IsNotExist(err) || f.IsDir() {
exitErr(
fmt.Sprintf("file does not exist or is a directory: %s", path),
exitCodeReadFileErr,
)
}
// リネーム
if err := os.Rename(path, newFileName); err != nil {
exitErr(err.Error(), exitCodeRenameErr)
}
fmt.Println(" -> Done!")
}
}
func exitErr(s string, c exitCode) {
fmt.Fprintln(os.Stderr, s)
os.Exit(c.getInt())
}
func exitHelp() {
helpFormat := `%s
Usage:
%s [flags] <filepath...>
Flags:
%s`
fmt.Printf(helpFormat, appDesc, appName, flags.FlagUsages())
os.Exit(exitCodeOK.getInt())
}