-
Notifications
You must be signed in to change notification settings - Fork 0
/
rename.go
51 lines (46 loc) · 1.17 KB
/
rename.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
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
package cmd
import (
"io/ioutil"
"os"
"path"
"regexp"
"github.com/spf13/cobra"
)
func runRename(dirPath string, pattern *regexp.Regexp, replacement string) error {
items, err := ioutil.ReadDir(dirPath)
if err != nil {
return err
}
for _, info := range items {
if info.IsDir() {
err = runRename(path.Join(dirPath, info.Name()), pattern, replacement)
if err != nil {
return err
}
}
newName := pattern.ReplaceAllString(info.Name(), replacement)
if newName != info.Name() {
err = os.Rename(path.Join(dirPath, info.Name()), path.Join(dirPath, newName))
if err != nil {
return err
}
}
}
return nil
}
var renameCmd = &cobra.Command{
Use: "rename <pattern> <replacement> <file or directory>",
Short: "replace occurrences of pattern in file and directory names with replacement.",
RunE: func(cmd *cobra.Command, args []string) error {
if len(args) != 3 {
return cmd.Usage()
}
pattern, err := regexp.Compile(args[0])
if err != nil {
return err
}
return runRename(args[2], pattern, args[1])
},
}