Debian Codegraph @

cmd/txtar-c/savedir.go

raw symbols SCIP
1 // Copyright 2018 The Go Authors. All rights reserved.
2 // Use of this source code is governed by a BSD-style
3 // license that can be found in the LICENSE file.
4
5 // The txtar-c command archives a directory tree as a txtar archive printed to standard output.
6 //
7 // Usage:
8 //
9 // txtar-c /path/to/dir >saved.txtar
10 //
11 // See https://godoc.org/golang.org/x/tools/txtar for details of the format
12 // and how to parse a txtar file.
13 package main
14
15 import (
16 "bytes"
17 "flag"
18 "fmt"
19 "log"
20 "os"
21 "path/filepath"
22 "strings"
23 "unicode/utf8"
24
25 "github.com/rogpeppe/go-internal/txtar"
26 )
27
28 func usage() {
29 fmt.Fprintf(os.Stderr, "usage: txtar-c dir >saved.txtar\n")
30 flag.PrintDefaults()
31 os.Exit(2)
32 }
33
34 var (
35 quoteFlag = flag.Bool("quote", false, "quote files that contain txtar file markers instead of failing")
36 allFlag = flag.Bool("a", false, "include dot files too")
37 )
38
39 func main() {
40 flag.Usage = usage
41 flag.Parse()
42 if flag.NArg() != 1 {
43 usage()
44 }
45
46 log.SetPrefix("txtar-c: ")
47 log.SetFlags(0)
48
49 dir := flag.Arg(0)
50
51 a := new(txtar.Archive)
52 dir = filepath.Clean(dir)
53 if err := filepath.Walk(dir, func(path string, info os.FileInfo, err error) error {
54 if err != nil {
55 return err
56 }
57 if path == dir {
58 return nil
59 }
60 name := info.Name()
61 if strings.HasPrefix(name, ".") && !*allFlag {
62 if info.IsDir() {
63 return filepath.SkipDir
64 }
65 return nil
66 }
67 if !info.Mode().IsRegular() {
68 return nil
69 }
70 data, err := os.ReadFile(path)
71 if err != nil {
72 return err
73 }
74 if !utf8.Valid(data) {
75 log.Printf("%s: ignoring file with invalid UTF-8 data", path)
76 return nil
77 }
78 if len(data) > 0 && !bytes.HasSuffix(data, []byte("\n")) {
79 log.Printf("%s: adding final newline", path)
80 data = append(data, '\n')
81 }
82 filename := strings.TrimPrefix(path, dir+string(filepath.Separator))
83 if txtar.NeedsQuote(data) {
84 if !*quoteFlag {
85 log.Printf("%s: ignoring file with txtar marker in", path)
86 return nil
87 }
88 data, err = txtar.Quote(data)
89 if err != nil {
90 log.Printf("%s: ignoring unquotable file: %v", path, err)
91 return nil
92 }
93 a.Comment = append(a.Comment, []byte("unquote "+filename+"\n")...)
94 }
95 a.Files = append(a.Files, txtar.File{
96 Name: filepath.ToSlash(filename),
97 Data: data,
98 })
99 return nil
100 }); err != nil {
101 log.Fatal(err)
102 }
103
104 data := txtar.Format(a)
105 os.Stdout.Write(data)
106 }