| 1 | package main |
| 2 | |
| 3 | import ( |
| 4 | "fmt" |
| 5 | "io/fs" |
| 6 | "os" |
| 7 | "path/filepath" |
| 8 | "strings" |
| 9 | ) |
| 10 | |
| 11 | // skipped are the directories a copy for a gate never needs. |
| 12 | var skipped = map[string]bool{".git": true, "node_modules": true, |
| 13 | "releases": true} |
| 14 | |
| 15 | // copyRepository copies the repository's files into dir. |
| 16 | func copyRepository(from, dir string) error { |
| 17 | return filepath.WalkDir(from, func(path string, entry fs.DirEntry, |
| 18 | err error) error { |
| 19 | if err != nil { |
| 20 | return err |
| 21 | } |
| 22 | if entry.IsDir() && skipped[entry.Name()] { |
| 23 | return filepath.SkipDir |
| 24 | } |
| 25 | target := filepath.Join(dir, path) |
| 26 | if entry.IsDir() { |
| 27 | return os.MkdirAll(target, 0o700) |
| 28 | } |
| 29 | data, err := os.ReadFile(path) |
| 30 | if err != nil { |
| 31 | return err |
| 32 | } |
| 33 | return os.WriteFile(target, data, 0o600) |
| 34 | }) |
| 35 | } |
| 36 | |
| 37 | // mutateFile applies one edit to a copied file, in place. |
| 38 | func mutateFile(path string, change edit) error { |
| 39 | source, err := os.ReadFile(path) |
| 40 | if err != nil { |
| 41 | return err |
| 42 | } |
| 43 | if count := strings.Count(string(source), change.from); count != 1 { |
| 44 | return fmt.Errorf("%s: the text to break occurs %d times, not once", |
| 45 | change.file, count) |
| 46 | } |
| 47 | mutated := strings.Replace(string(source), change.from, change.to, 1) |
| 48 | return os.WriteFile(path, []byte(mutated), 0o600) |
| 49 | } |
| 50 | |