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
|
// Copyright 2018 The Go Authors. All rights reserved.
// Use of this source code is governed by a BSD-style
// license that can be found in the LICENSE file.
// The txtar-c command archives a directory tree as a txtar archive printed to standard output.
//
// Usage:
//
// txtar-c /path/to/dir >saved.txtar
//
// See https://godoc.org/golang.org/x/tools/txtar for details of the format
// and how to parse a txtar file.
package main
import (
"bytes"
"flag"
"fmt"
"log"
"os"
"path/filepath"
"strings"
"unicode/utf8"
"github.com/rogpeppe/go-internal/txtar"
)
func usage() {
fmt.Fprintf(os.Stderr, "usage: txtar-c dir >saved.txtar\n")
flag.PrintDefaults()
os.Exit(2)
}
var (
quoteFlag = flag.Bool("quote", false, "quote files that contain txtar file markers instead of failing")
allFlag = flag.Bool("a", false, "include dot files too")
)
func main() {
flag.Usage = usage
flag.Parse()
if flag.NArg() != 1 {
usage()
}
log.SetPrefix("txtar-c: ")
log.SetFlags(0)
dir := flag.Arg(0)
a := new(txtar.Archive)
dir = filepath.Clean(dir)
if err := filepath.Walk(dir, func(path string, info os.FileInfo, err error) error {
if err != nil {
return err
}
if path == dir {
return nil
}
name := info.Name()
if strings.HasPrefix(name, ".") && !*allFlag {
if info.IsDir() {
return filepath.SkipDir
}
return nil
}
if !info.Mode().IsRegular() {
return nil
}
data, err := os.ReadFile(path)
if err != nil {
return err
}
if !utf8.Valid(data) {
log.Printf("%s: ignoring file with invalid UTF-8 data", path)
return nil
}
if len(data) > 0 && !bytes.HasSuffix(data, []byte("\n")) {
log.Printf("%s: adding final newline", path)
data = append(data, '\n')
}
filename := strings.TrimPrefix(path, dir+string(filepath.Separator))
if txtar.NeedsQuote(data) {
if !*quoteFlag {
log.Printf("%s: ignoring file with txtar marker in", path)
return nil
}
data, err = txtar.Quote(data)
if err != nil {
log.Printf("%s: ignoring unquotable file: %v", path, err)
return nil
}
a.Comment = append(a.Comment, []byte("unquote "+filename+"\n")...)
}
a.Files = append(a.Files, txtar.File{
Name: filepath.ToSlash(filename),
Data: data,
})
return nil
}); err != nil {
log.Fatal(err)
}
data := txtar.Format(a)
os.Stdout.Write(data)
}
|