1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16 package main
17
18 import (
19 "flag"
20 "fmt"
21 "io/fs"
22 "log"
23 "os"
24 "path/filepath"
25 "strings"
26 "unicode/utf8"
27
28 "golang.org/x/tools/txtar"
29 )
30
31 func usage() {
32 fmt.Fprintf(os.Stderr, "usage: go run savedir.go dir >saved.txt\n")
33 os.Exit(2)
34 }
35
36 const goCmd = "vgo"
37
38 func main() {
39 flag.Usage = usage
40 flag.Parse()
41 if flag.NArg() != 1 {
42 usage()
43 }
44
45 log.SetPrefix("savedir: ")
46 log.SetFlags(0)
47
48 dir := flag.Arg(0)
49
50 a := new(txtar.Archive)
51 dir = filepath.Clean(dir)
52 filepath.WalkDir(dir, func(path string, info fs.DirEntry, err error) error {
53 if path == dir {
54 return nil
55 }
56 name := info.Name()
57 if strings.HasPrefix(name, ".") {
58 if info.IsDir() {
59 return filepath.SkipDir
60 }
61 return nil
62 }
63 if !info.Type().IsRegular() {
64 return nil
65 }
66 data, err := os.ReadFile(path)
67 if err != nil {
68 log.Fatal(err)
69 }
70 if !utf8.Valid(data) {
71 log.Printf("%s: ignoring invalid UTF-8 data", path)
72 return nil
73 }
74 a.Files = append(a.Files, txtar.File{Name: strings.TrimPrefix(path, dir+string(filepath.Separator)), Data: data})
75 return nil
76 })
77
78 data := txtar.Format(a)
79 os.Stdout.Write(data)
80 }
81
View as plain text