| 1 | package cli |
| 2 | |
| 3 | import ( |
| 4 | "context" |
| 5 | "errors" |
| 6 | "fmt" |
| 7 | "io" |
| 8 | "os" |
| 9 | "path/filepath" |
| 10 | "regexp" |
| 11 | "strings" |
| 12 | |
| 13 | "golang.org/x/term" |
| 14 | |
| 15 | "github.com/sylvinus/agent-vm/internal/env" |
| 16 | "github.com/sylvinus/agent-vm/internal/gitx" |
| 17 | "github.com/sylvinus/agent-vm/internal/paths" |
| 18 | "github.com/sylvinus/agent-vm/internal/vmname" |
| 19 | ) |
| 20 | |
| 21 | var keyRe = regexp.MustCompile(`^[A-Za-z_][A-Za-z0-9_]*$`) |
| 22 | |
| 23 | |
| 24 | |
| 25 | type envFile struct { |
| 26 | path, top string |
| 27 | } |
| 28 | |
| 29 | func (f envFile) read() ([]byte, error) { |
| 30 | if f.top != "" { |
| 31 | return env.ReadIn(f.top, strings.TrimPrefix(f.path, strings.TrimSuffix(f.top, "/")+"/")) |
| 32 | } |
| 33 | fi, err := os.Stat(f.path) |
| 34 | if errors.Is(err, os.ErrNotExist) || err == nil && !fi.Mode().IsRegular() { |
| 35 | return nil, env.ErrNoFile |
| 36 | } |
| 37 | return os.ReadFile(f.path) |
| 38 | } |
| 39 | |
| 40 | |
| 41 | func (f envFile) write(data []byte) error { |
| 42 | if f.top != "" { |
| 43 | return env.WriteIn(f.top, strings.TrimPrefix(f.path, strings.TrimSuffix(f.top, "/")+"/"), data) |
| 44 | } |
| 45 | if err := os.MkdirAll(filepath.Dir(f.path), 0o755); err != nil { |
| 46 | return err |
| 47 | } |
| 48 | tmp, err := os.CreateTemp(filepath.Dir(f.path), filepath.Base(f.path)+".") |
| 49 | if err != nil { |
| 50 | return err |
| 51 | } |
| 52 | _, werr := tmp.Write(data) |
| 53 | if err := errors.Join(werr, tmp.Chmod(0o600), tmp.Close()); err != nil { |
| 54 | os.Remove(tmp.Name()) |
| 55 | return err |
| 56 | } |
| 57 | if err := os.Rename(tmp.Name(), f.path); err != nil { |
| 58 | os.Remove(tmp.Name()) |
| 59 | return err |
| 60 | } |
| 61 | return nil |
| 62 | } |
| 63 | |
| 64 | |
| 65 | |
| 66 | |
| 67 | |
| 68 | |
| 69 | func (e *app) envVerb(verb string, f envFile, args []string) int { |
| 70 | stderr := e.io.Stderr |
| 71 | usage := fmt.Sprintf("Usage: agent-vm %s {set KEY [VALUE]|get KEY|has KEY|unset KEY|list}", verb) |
| 72 | action, key := "list", "" |
| 73 | if len(args) > 0 { |
| 74 | action = args[0] |
| 75 | } |
| 76 | if len(args) > 1 { |
| 77 | key = args[1] |
| 78 | } |
| 79 | switch action { |
| 80 | case "set", "get", "has", "unset": |
| 81 | if key == "" { |
| 82 | fmt.Fprintf(stderr, "Error: 'agent-vm %s %s' needs a KEY.\n", verb, action) |
| 83 | return 1 |
| 84 | } |
| 85 | if !keyRe.MatchString(key) { |
| 86 | fmt.Fprintf(stderr, "Error: '%s' is not a valid environment variable name.\n", key) |
| 87 | return 1 |
| 88 | } |
| 89 | case "list": |
| 90 | default: |
| 91 | fmt.Fprintln(stderr, usage) |
| 92 | return 1 |
| 93 | } |
| 94 | |
| 95 | maxArgs := map[string]int{"set": 3, "list": 1}[action] |
| 96 | if maxArgs == 0 { |
| 97 | maxArgs = 2 |
| 98 | } |
| 99 | if len(args) > maxArgs { |
| 100 | fmt.Fprintf(stderr, "Error: too many arguments for 'agent-vm %s %s'. Quote a value with spaces.\n", verb, action) |
| 101 | fmt.Fprintln(stderr, usage) |
| 102 | return 1 |
| 103 | } |
| 104 | |
| 105 | |
| 106 | |
| 107 | value := "" |
| 108 | if action == "set" { |
| 109 | if len(args) == 3 { |
| 110 | value = args[2] |
| 111 | } else if in, ok := e.io.Stdin.(*os.File); ok && term.IsTerminal(int(in.Fd())) { |
| 112 | fmt.Fprintf(stderr, "Value for %s (not shown): ", key) |
| 113 | b, err := term.ReadPassword(int(in.Fd())) |
| 114 | fmt.Fprintln(stderr) |
| 115 | if err == nil { |
| 116 | value = string(b) |
| 117 | } |
| 118 | } else { |
| 119 | b, _ := io.ReadAll(e.io.Stdin) |
| 120 | value = strings.TrimSuffix(string(b), "\n") |
| 121 | } |
| 122 | if len(args) < 3 && value == "" { |
| 123 | fmt.Fprintf(stderr, "Error: 'agent-vm %s set %s' needs a VALUE, as an argument or on stdin.\n", verb, key) |
| 124 | return 1 |
| 125 | } |
| 126 | } |
| 127 | |
| 128 | content, err := f.read() |
| 129 | have := true |
| 130 | switch { |
| 131 | case err == nil: |
| 132 | case errors.Is(err, env.ErrNoFile): |
| 133 | have = false |
| 134 | case errors.Is(err, env.ErrUnsafe): |
| 135 | fmt.Fprintf(stderr, "Error: %s is a symlink, is reached through one, or is not a regular file.\n", f.path) |
| 136 | fmt.Fprintln(stderr, " agent-vm follows no link in the project, which the VM can write. Replace it with a plain file.") |
| 137 | return 2 |
| 138 | default: |
| 139 | fmt.Fprintf(stderr, "Error: could not read %s\n", f.path) |
| 140 | return 2 |
| 141 | } |
| 142 | |
| 143 | switch action { |
| 144 | case "set", "unset": |
| 145 | if action == "unset" && !have { |
| 146 | return 0 |
| 147 | } |
| 148 | next := env.Drop(string(content), key) |
| 149 | if action == "set" { |
| 150 | next += fmt.Sprintf("%s='%s'\n", key, env.SQEscape(value)) |
| 151 | } |
| 152 | |
| 153 | |
| 154 | if err := f.write([]byte(next)); err != nil { |
| 155 | fmt.Fprintf(stderr, "Error: could not write %s\n", f.path) |
| 156 | return 1 |
| 157 | } |
| 158 | case "get", "has": |
| 159 | if !have { |
| 160 | return 1 |
| 161 | } |
| 162 | |
| 163 | v, st := env.Lookup(string(content), key) |
| 164 | switch st { |
| 165 | case env.NotFound: |
| 166 | return 1 |
| 167 | case env.Refused: |
| 168 | fmt.Fprintf(stderr, "Error: %s in %s uses, or comes after, shell syntax agent-vm does not evaluate\n", key, f.path) |
| 169 | fmt.Fprintf(stderr, " ($, backquotes, backslashes, ~, ;, | ...). Rewrite it with 'agent-vm %s set'.\n", verb) |
| 170 | return 2 |
| 171 | } |
| 172 | if action == "get" { |
| 173 | fmt.Fprintln(e.io.Stdout, v) |
| 174 | } |
| 175 | case "list": |
| 176 | if !have { |
| 177 | return 0 |
| 178 | } |
| 179 | seen := map[string]bool{} |
| 180 | for _, n := range env.Names(string(content)) { |
| 181 | if !seen[n] { |
| 182 | seen[n] = true |
| 183 | fmt.Fprintln(e.io.Stdout, n) |
| 184 | } |
| 185 | } |
| 186 | } |
| 187 | return 0 |
| 188 | } |
| 189 | |
| 190 | func (e *app) sharedEnvCmd(args []string) int { |
| 191 | return e.envVerb("env", envFile{path: e.state.Path("env")}, args) |
| 192 | } |
| 193 | |
| 194 | func (e *app) projectEnvCmd(ctx context.Context, args []string) int { |
| 195 | wd, err := vmname.AbsDir("") |
| 196 | if err != nil { |
| 197 | fmt.Fprintf(e.io.Stderr, "Error: %v\n", err) |
| 198 | return 1 |
| 199 | } |
| 200 | f := envFile{path: env.ProjectEnvFile(wd)} |
| 201 | if rel, ok := env.ProjectRel(wd, f.path); ok { |
| 202 | f = envFile{path: wd + "/" + rel, top: wd} |
| 203 | } |
| 204 | if st := e.envVerb("project-env", f, args); st != 0 { |
| 205 | return st |
| 206 | } |
| 207 | |
| 208 | |
| 209 | if len(args) > 0 && args[0] == "set" { |
| 210 | e.warnUnignored(ctx, f.path) |
| 211 | } |
| 212 | return 0 |
| 213 | } |
| 214 | |
| 215 | |
| 216 | |
| 217 | func (e *app) warnUnignored(ctx context.Context, file string) { |
| 218 | if !gitx.Have() { |
| 219 | return |
| 220 | } |
| 221 | out, err := gitx.Untrusted(ctx, "-C", filepath.Dir(file), "rev-parse", "--show-toplevel").Output() |
| 222 | top := strings.TrimSuffix(string(out), "\n") |
| 223 | if err != nil || top == "" { |
| 224 | return |
| 225 | } |
| 226 | |
| 227 | |
| 228 | |
| 229 | if phys, err := filepath.EvalSymlinks(file); err == nil { |
| 230 | file = phys |
| 231 | } |
| 232 | |
| 233 | rel, ok := paths.CutPrefix(filepath.ToSlash(file), filepath.ToSlash(top)+"/") |
| 234 | if !ok { |
| 235 | |
| 236 | return |
| 237 | } |
| 238 | qTop, qRel := env.SQEscape(top), env.SQEscape(rel) |
| 239 | if gitx.Untrusted(ctx, "-C", top, "ls-files", "--error-unmatch", file).Run() == nil { |
| 240 | fmt.Fprintf(e.io.Stderr, "Warning: %s is tracked by git: its contents are in the repository.\n", rel) |
| 241 | fmt.Fprintf(e.io.Stderr, " git -C '%s' rm --cached '%s' && echo '/%s' >> '%s/.gitignore'\n", qTop, qRel, qRel, qTop) |
| 242 | return |
| 243 | } |
| 244 | err = gitx.Untrusted(ctx, "-C", top, "check-ignore", "-q", file).Run() |
| 245 | var ee interface{ ExitCode() int } |
| 246 | if errors.As(err, &ee) && ee.ExitCode() == 1 { |
| 247 | fmt.Fprintf(e.io.Stderr, "Warning: %s is not ignored by git: it can be committed by accident.\n", rel) |
| 248 | fmt.Fprintf(e.io.Stderr, " echo '/%s' >> '%s/.gitignore'\n", qRel, qTop) |
| 249 | } |
| 250 | } |