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  package main
    16  
    17  import (
    18  	"cmd/go/internal/str"
    19  	"flag"
    20  	"fmt"
    21  	"internal/txtar"
    22  	"io/fs"
    23  	"log"
    24  	"os"
    25  	"path/filepath"
    26  	"strings"
    27  	"unicode/utf8"
    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.WalkDir(dir, func(path string, info fs.DirEntry, 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.Type().IsRegular() {
    63  			return nil
    64  		}
    65  		data, err := os.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: str.TrimFilePathPrefix(path, dir), Data: data})
    74  		return nil
    75  	})
    76  
    77  	data := txtar.Format(a)
    78  	os.Stdout.Write(data)
    79  }
    80  

View as plain text