Source file src/cmd/go/testdata/savedir.go

     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  //go:build ignore
     6  // +build ignore
     7  
     8  // Savedir archives a directory tree as a txtar archive printed to standard output.
     9  //
    10  // Usage:
    11  //
    12  //	go run savedir.go /path/to/dir >saved.txt
    13  //
    14  // Typically the tree is later extracted during a test with tg.extract("testdata/saved.txt").
    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