-
Notifications
You must be signed in to change notification settings - Fork 4
/
Copy pathoneify.go
82 lines (67 loc) · 1.11 KB
/
oneify.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
package main
import (
"flag"
"fmt"
"io/fs"
"log"
"os"
"path/filepath"
)
var (
recursive = flag.Bool("r", false, "recursive")
topdir = "."
chosen []byte
)
func main() {
log.SetFlags(0)
log.SetPrefix("oneify: ")
flag.Usage = usage
flag.Parse()
var err error
switch flag.NArg() {
case 2:
topdir = flag.Arg(1)
fallthrough
case 1:
chosen, err = os.ReadFile(flag.Arg(0))
check(err)
default:
usage()
}
if !filepath.IsAbs(topdir) {
cwd, err := os.Getwd()
check(err)
topdir = filepath.Join(cwd, topdir)
}
topdir = filepath.Clean(topdir)
filepath.Walk(topdir, walk)
}
func walk(path string, info fs.FileInfo, err error) error {
if err != nil {
return err
}
if !*recursive {
dir := filepath.Dir(path)
if len(dir) > len(topdir) {
return filepath.SkipDir
}
}
if !info.IsDir() {
fmt.Println("Replacing", path)
err = os.WriteFile(path, chosen, 0644)
if err != nil {
fmt.Println(err)
}
}
return nil
}
func usage() {
fmt.Println("usage: [options] file [path]")
flag.PrintDefaults()
os.Exit(2)
}
func check(err error) {
if err != nil {
log.Fatal(err)
}
}