WriteScriptsToFiles writes scripts defined in devbox.json into files inside .devbox/gen/scripts. Scripts (and hooks) are persisted so that we can easily call them from devbox run (inside or outside shell).
(devbox devboxer)
| 39 | // WriteScriptsToFiles writes scripts defined in devbox.json into files inside .devbox/gen/scripts. |
| 40 | // Scripts (and hooks) are persisted so that we can easily call them from devbox run (inside or outside shell). |
| 41 | func WriteScriptsToFiles(devbox devboxer) error { |
| 42 | defer debug.FunctionTimer().End() |
| 43 | err := os.MkdirAll(filepath.Join(devbox.ProjectDir(), scriptsDir), 0o755) // Ensure directory exists. |
| 44 | if err != nil { |
| 45 | return errors.WithStack(err) |
| 46 | } |
| 47 | |
| 48 | // Read dir contents before writing, so we can clean up later. |
| 49 | entries, err := os.ReadDir(filepath.Join(devbox.ProjectDir(), scriptsDir)) |
| 50 | if err != nil { |
| 51 | return errors.WithStack(err) |
| 52 | } |
| 53 | |
| 54 | // Write all hooks to a file. |
| 55 | written := map[string]struct{}{} // set semantics; value is irrelevant |
| 56 | // always write it, even if there are no hooks, because scripts will source it. |
| 57 | err = writeRawInitHookFile(devbox, devbox.Config().InitHook().String()) |
| 58 | if err != nil { |
| 59 | return errors.WithStack(err) |
| 60 | } |
| 61 | written[HooksFilename] = struct{}{} |
| 62 | |
| 63 | // Write scripts to files. |
| 64 | for name, body := range devbox.Config().Scripts() { |
| 65 | scriptBody, err := ScriptBody(devbox, body.String()) |
| 66 | if err != nil { |
| 67 | return errors.WithStack(err) |
| 68 | } |
| 69 | err = WriteScriptFile(devbox, name, scriptBody) |
| 70 | if err != nil { |
| 71 | return errors.WithStack(err) |
| 72 | } |
| 73 | written[name] = struct{}{} |
| 74 | } |
| 75 | |
| 76 | // Delete any files that weren't written just now. |
| 77 | for _, entry := range entries { |
| 78 | scriptName := strings.TrimSuffix(entry.Name(), ".sh") |
| 79 | if _, ok := written[scriptName]; !ok && !entry.IsDir() { |
| 80 | err := os.Remove(ScriptPath(devbox.ProjectDir(), scriptName)) |
| 81 | if err != nil { |
| 82 | slog.Debug("failed to clean up script file %s, error = %s", entry.Name(), err) // no need to fail run |
| 83 | } |
| 84 | } |
| 85 | } |
| 86 | |
| 87 | return nil |
| 88 | } |
| 89 | |
| 90 | func writeRawInitHookFile(devbox devboxer, body string) (err error) { |
| 91 | script, err := createScriptFile(devbox, HooksFilename) |
no test coverage detected