task/1.13
1//go:build ignore
2
3// Command tools/vendor/pack.go creates `vendor.tar.gz` from the current
4// project `vendor` directory. Intended for use as a build support tool.
5package main
6
7import (
8 "archive/tar"
9 "compress/gzip"
10 "fmt"
11 "io"
12 "io/fs"
13 "log/slog"
14 "os"
15 "path/filepath"
16 "runtime"
17)
18
19// vendor.tar.gz pack
20func main() {
21 const (
22 archiveName = "vendor.tar.gz"
23 vendorDir = "vendor"
24 vendorDirMode = 0o755
25 )
26
27 // discover this file's location
28 _, callerFilepath, _, callerFound := runtime.Caller(0)
29 if !callerFound {
30 slog.Error("failed to find caller location")
31 return
32 }
33 archivePath := filepath.Join(filepath.Dir(callerFilepath), archiveName)
34
35 archiveFile, err := os.Create(archivePath)
36 if err != nil {
37 slog.Error("failed to create output tarball",
38 slog.String("err", err.Error()),
39 slog.String("path", archivePath))
40 return
41 }
42 defer func() { _ = archiveFile.Close() }()
43
44 gzw := gzip.NewWriter(archiveFile)
45 defer func() { _ = gzw.Close() }()
46
47 tw := tar.NewWriter(gzw)
48 defer func() { _ = tw.Close() }()
49
50 err = filepath.WalkDir(
51 vendorDir,
52 func(path string, d fs.DirEntry, err error) error {
53 if err != nil {
54 return fmt.Errorf("failed to walk vendor dir path=%q: %w", path, err)
55 }
56 relPath, err := filepath.Rel(vendorDir, path)
57 if err != nil {
58 return fmt.Errorf("failed to create relative path path=%q: %w", path, err)
59 }
60 if relPath == "." {
61 return nil
62 }
63 info, err := d.Info()
64 if err != nil {
65 return fmt.Errorf("failed to get file info path=%q: %w", path, err)
66 }
67 if info.Mode()&os.ModeSymlink != 0 {
68 return nil
69 }
70 header, err := tar.FileInfoHeader(info, "")
71 if err != nil {
72 return fmt.Errorf("failed to create tar header path=%q: %w", path, err)
73 }
74 header.Name = relPath
75 err = tw.WriteHeader(header)
76 if err != nil {
77 return fmt.Errorf("failed to write tar header path=%q: %w", path, err)
78 }
79 if info.IsDir() {
80 return nil
81 }
82 vendorFile, err := os.Open(path)
83 if err != nil {
84 return fmt.Errorf("failed to open vendor file path=%q: %w", path, err)
85 }
86 _, err = io.Copy(tw, vendorFile)
87 if err != nil {
88 return fmt.Errorf("failed to write vendor file to tar path=%q: %w", path, err)
89 }
90 return nil
91 })
92 if err != nil {
93 slog.Error("failed to package vendor directory",
94 slog.String("err", err.Error()))
95 }
96}