github.com/gagliardetto/golang-go@v0.0.0-20201020153340-53909ea70814/cmd/go/testdata/savedir.go (about) 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 // +build ignore 6 7 // Savedir archives a directory tree as a txtar archive printed to standard output. 8 // 9 // Usage: 10 // 11 // go run savedir.go /path/to/dir >saved.txt 12 // 13 // Typically the tree is later extracted during a test with tg.extract("testdata/saved.txt"). 14 // 15 package main 16 17 import ( 18 "flag" 19 "fmt" 20 "io/ioutil" 21 "log" 22 "os" 23 "path/filepath" 24 "strings" 25 "unicode/utf8" 26 27 "../internal/txtar" 28 ) 29 30 func usage() { 31 fmt.Fprintf(os.Stderr, "usage: go run savedir.go dir >saved.txt\n") 32 os.Exit(2) 33 } 34 35 const goCmd = "vgo" 36 37 func main() { 38 flag.Usage = usage 39 flag.Parse() 40 if flag.NArg() != 1 { 41 usage() 42 } 43 44 log.SetPrefix("savedir: ") 45 log.SetFlags(0) 46 47 dir := flag.Arg(0) 48 49 a := new(txtar.Archive) 50 dir = filepath.Clean(dir) 51 filepath.Walk(dir, func(path string, info os.FileInfo, err error) error { 52 if path == dir { 53 return nil 54 } 55 name := info.Name() 56 if strings.HasPrefix(name, ".") { 57 if info.IsDir() { 58 return filepath.SkipDir 59 } 60 return nil 61 } 62 if !info.Mode().IsRegular() { 63 return nil 64 } 65 data, err := ioutil.ReadFile(path) 66 if err != nil { 67 log.Fatal(err) 68 } 69 if !utf8.Valid(data) { 70 log.Printf("%s: ignoring invalid UTF-8 data", path) 71 return nil 72 } 73 a.Files = append(a.Files, txtar.File{Name: strings.TrimPrefix(path, dir+string(filepath.Separator)), Data: data}) 74 return nil 75 }) 76 77 data := txtar.Format(a) 78 os.Stdout.Write(data) 79 }