repositories / dotfiles

dotfiles

bugabingas dorkfiles

owned by bugabinga

chore: use java shell for mise tasks

362ced6058a0c461ecf13fd3469dff80635a39db

Oliver Jan Krylow <oliver@bugabinga.net> ·

unsigned

Browse filesCompare with HEAD

Changed files (5)

AGENTS.md

Modified
4 4 # Dotfiles
6 6 Dorkfiles repo.
7 7 Preserve unrelated dirty work.
8 8 Check `git status --short` before edits.
9 9 Prefer repo paths (`pi/agent/...`) over `$HOME` paths.
10 -Use `mise` tasks; host bootstrap assumes Git + mise, then mise supplies Java/Nushell.
10 +Use `mise` tasks; host bootstrap assumes Git + mise, then mise supplies Java.
11 +Root `mise.toml` tools are dorkfiles bootstrap deps only; other apps come from system/package manager.
12 +Root mise task shell is `scripts/mise_shell.java`, not Nushell/Bash.
11 13 `mise run test` also needs host Podman; its Fedora container installs Git/mise, then mise supplies Java.
12 14 Never print decrypted secrets.
13 15 Do not delete noisy research/cache/untracked files unless explicitly asked.

bootstripper.java

Modified
449 449 var target_path = expand_target(target);
450 450 if (Files.exists(target_path, LinkOption.NOFOLLOW_LINKS)) {
451 451 if (Files.isSymbolicLink(target_path)) {
452 + var raw_actual = symlink_target_path(target_path);
453 + if (!inside_home(raw_actual))
454 + throw fail("Target symlink points outside HOME: {0} -> {1}. Move it manually.", target_path, raw_actual);
452 455 if (!Files.exists(target_path)) {
453 456 log("\nRELINK {0}: broken symlink.", emphasize_global(target_path.toString()));
454 457 remove_owned_symlink(target_path);
510 + static Path symlink_target_path(Path target_path) throws IOException {
511 + var link = Files.readSymbolicLink(target_path);
512 + var resolved = link.isAbsolute() ? link : target_path.getParent().resolve(link);
513 + return resolved.toAbsolutePath().normalize();
507 516 static Path sibling_backup_path(Path target_path) throws Throwable {
508 517 return sibling_path(target_path, "backup");

mise.toml

Modified
1 1 [tools]
2 -"aqua:nushell/nushell" = "latest"
3 2 java = "temurin"
5 4 [settings]
6 -unix_default_inline_shell_args = "nu -c"
7 -windows_default_inline_shell_args = "nu -c"
5 +unix_default_inline_shell_args = "java scripts/mise_shell.java"
6 +windows_default_inline_shell_args = "java scripts/mise_shell.java"
9 8 [tasks.default]
10 9 description = "List tasks"
11 10 hide = true
12 -run = "mise tasks ls"
11 +run = 'run("mise", "tasks", "ls");'
14 13 [tasks.check]
15 14 description = "Verify crypto, hooks, secrets, and symlink manifests"
16 -run = "java bootstripper.java check"
15 +run = 'run("java", "bootstripper.java", "check");'
18 17 [tasks.test]
19 18 description = "Run Podman integration test"
20 -run = "java ./scripts/dotfiles_integration_test.java"
19 +run = 'run("java", "./scripts/dotfiles_integration_test.java");'
22 21 [tasks.test-inside]
23 22 description = "Run Podman container checks"
24 23 hide = true
25 -run = "java ./scripts/dotfiles_integration_test.java --inside"
24 +run = 'run("java", "./scripts/dotfiles_integration_test.java", "--inside");'
27 26 [tasks.link]
28 27 description = "Link dorkfiles into HOME"
29 -run = [
30 - "java bootstripper.java bootstrap",
31 - "java scripts/fix_permissions.java",
32 -]
28 +run = '''
29 +run("java", "bootstripper.java", "bootstrap");
30 +run("java", "scripts/fix_permissions.java");
31 +'''
34 33 [tasks.clean]
35 34 description = "Remove managed dorkfiles links from HOME"
36 -run = "java bootstripper.java clean"
35 +run = 'run("java", "bootstripper.java", "clean");'
38 37 [tasks.init]
39 38 description = "Create initial crypto salt"
40 39 hide = true
41 -run = "java bootstripper.java init-crypto"
40 +run = 'run("java", "bootstripper.java", "init-crypto");'
43 42 [tasks.hook]
44 43 description = "Install Git hooks"
45 44 hide = true
46 -run = "java bootstripper.java install-hooks"
45 +run = 'run("java", "bootstripper.java", "install-hooks");'
48 47 [tasks.fix]
49 48 description = "Fix local file permissions"
50 49 hide = true
51 -run = "java scripts/fix_permissions.java"
50 +run = 'run("java", "scripts/fix_permissions.java");'

scripts/dotfiles_integration_test.java

Modified
66 66 ok("deps");
67 67 System.out.println(run(root, "git", "--version").trim());
68 68 System.out.println(run(root, "mise", "--version").trim());
69 + var miseTools = run(root, "mise", "ls", "--current").toLowerCase(Locale.ROOT);
70 + if (miseTools.contains("nushell")) fail("root-mise-nushell-tool");
69 71 System.out.println(run(root, "java", "-version").lines().findFirst().orElse("java"));
71 73 run(root, "mise", "run", "hook");

scripts/mise_shell.java

Added
new file mode 100644
1 +import jdk.jshell.*;
2 +import java.util.*;
4 +/// Tiny Java shell for mise inline tasks.
5 +///
6 +/// Mise passes each task command as one argv item. This evaluates that item as
7 +/// JShell snippets in the local JVM and exits non-zero on Java errors or thrown exceptions.
8 +void main(String[] args) throws Exception
9 +{
10 + if (args.length != 1)
11 + {
12 + System.err.println("expected one mise task snippet arg, got " + args.length);
13 + System.exit(64);
14 + }
16 + var failed = false;
17 + try (var jshell = JShell.builder().executionEngine("local").out(System.out).err(System.err).build())
18 + {
19 + failed |= !evalAll(jshell, startup(), true);
20 + if (!failed)
21 + failed |= !evalAll(jshell, args[0], false);
22 + }
23 + if (failed)
24 + System.exit(1);
27 +/// Evaluate a possibly multi-snippet Java task.
28 +///
29 +/// Reason: `JShell.eval(...)` only reliably evaluates one complete snippet at a
30 +/// time. Mise tasks are often multi-line blocks, so this uses JShell's parser to
31 +/// split complete snippets before execution.
32 +///
33 +/// Usage: first evaluate `startup()` with `startup = true`, then the task body
34 +/// with `startup = false`.
35 +///
36 +/// Pitfall: state lives only inside this Java process. A mise `run = [...]` array
37 +/// starts separate shell processes, so variables and `cd(...)` do not cross array
38 +/// entries.
39 +boolean evalAll(JShell jshell, String input, boolean startup)
41 + var ok = true;
42 + var rest = input;
43 + while (!rest.isBlank())
44 + {
45 + var info = jshell.sourceCodeAnalysis().analyzeCompletion(rest);
46 + if (!info.completeness().isComplete())
47 + {
48 + System.err.println((startup ? "startup: " : "") + "incomplete snippet: " + info.completeness());
49 + return false;
50 + }
51 + if (!evalOne(jshell, info.source(), startup))
52 + {
53 + ok = false;
54 + break;
55 + }
56 + rest = info.remaining();
57 + }
58 + return ok;
61 +/// Evaluate one complete JShell snippet and translate JShell status into exit status.
62 +///
63 +/// Reason: the `jshell` CLI exits `0` for some rejected snippets. Mise tasks need
64 +/// hard failure on compiler errors and thrown exceptions.
65 +///
66 +/// Usage: called by `evalAll(...)` after completeness analysis.
67 +///
68 +/// Pitfall: diagnostics point at JShell's synthetic snippet, not a physical
69 +/// `mise.toml` line number. Keep tasks short and direct.
70 +boolean evalOne(JShell jshell, String code, boolean startup)
72 + var ok = true;
73 + for (var event : jshell.eval(code))
74 + {
75 + if (event.exception() != null)
76 + {
77 + var message = event.exception().getMessage();
78 + System.err.println(message == null ? event.exception().toString() : message);
79 + ok = false;
80 + }
81 + var status = event.status();
82 + if (status == Snippet.Status.REJECTED || status == Snippet.Status.RECOVERABLE_NOT_DEFINED)
83 + {
84 + jshell.diagnostics(event.snippet()).forEach(d -> System.err.println((startup ? "startup: " : "") + d.getMessage(Locale.ROOT)));
85 + ok = false;
86 + }
87 + }
88 + return ok;
91 +/// Built-in imports and shell-like helpers exposed to every mise task.
92 +///
93 +/// Reason: root dorkfiles tasks should stay Java, terse, and cross-platform
94 +/// without depending on Bash/Nushell syntax.
95 +///
96 +/// Usage: task bodies can call helpers directly, e.g.
97 +/// `run("java", "bootstripper.java", "check");`.
98 +///
99 +/// Pitfall: this is startup source code for JShell. Syntax errors here break
100 +/// every task before the task body runs.
101 +String startup()
103 + return """
104 +import java.io.*;
105 +import java.nio.charset.*;
106 +import java.nio.file.*;
107 +import java.util.*;
108 +import java.util.regex.*;
109 +import java.util.stream.*;
111 +Path CWD = Path.of("").toAbsolutePath().normalize();
112 +Map<String, String> ENV = new HashMap<>(System.getenv());
114 +/// Captured process result.
115 +///
116 +/// Reason: `run(...)` is fail-fast and streams output. Some tasks need captured
117 +/// text or an exit code instead.
118 +///
119 +/// Usage:
120 +/// `var r = result("git", "status", "--short");`
121 +/// `if (r.code() != 0) throw new RuntimeException(r.out());`
122 +///
123 +/// Pitfall: stdout and stderr are merged, matching typical task logs but not
124 +/// preserving separate streams.
125 +record Result(int code, String out)
127 + /// Return captured process output unchanged.
128 + ///
129 + /// Reason: terse alias when reading command output.
130 + ///
131 + /// Usage: `IO.print(result("git", "status").text());`.
132 + ///
133 + /// Pitfall: includes trailing newlines exactly as emitted.
134 + String text() { return out; }
136 + /// Return captured output stripped of leading/trailing whitespace.
137 + ///
138 + /// Reason: common for command substitutions like `git rev-parse`.
139 + ///
140 + /// Usage: `var head = result("git", "rev-parse", "HEAD").trimmed();`.
141 + ///
142 + /// Pitfall: stripping can destroy meaningful whitespace; use `text()` for raw data.
143 + String trimmed() { return out.strip(); }
145 + /// Return captured output split into lines.
146 + ///
147 + /// Reason: Java replacement for shell pipelines that iterate line output.
148 + ///
149 + /// Usage: `for (var file : result("git", "ls-files").lines()) IO.println(file);`.
150 + ///
151 + /// Pitfall: uses Java `String.lines()`, so line terminators are removed.
152 + List<String> lines() { return out.lines().toList(); }
155 +/// Return the task working directory.
156 +///
157 +/// Reason: `cd(...)` is local state inside this Java shell, not OS process state.
158 +/// This exposes that state clearly.
159 +///
160 +/// Usage: `IO.println(pwd());`.
161 +///
162 +/// Pitfall: mise `dir = "..."` sets the initial process directory before this
163 +/// shell starts; `pwd()` reports that effective directory.
164 +Path pwd()
166 + return CWD;
169 +/// Resolve a path against `pwd()`.
170 +///
171 +/// Reason: shell tasks constantly need repo-relative paths. This avoids string
172 +/// concatenation and normalizes `.` / `..`.
173 +///
174 +/// Usage: `Files.exists(path("scripts", "mise_shell.java"));`.
175 +///
176 +/// Pitfall: absolute `first` values stay absolute because `Path.resolve(...)`
177 +/// follows Java NIO rules. Prefer relative paths in repo tasks.
178 +Path path(String first, String... more)
180 + return CWD.resolve(Path.of(first, more)).toAbsolutePath().normalize();
183 +/// Change this shell's working directory.
184 +///
185 +/// Reason: Java cannot change the OS parent process directory, but this wrapper
186 +/// can keep a `CWD` used by `run(...)` and file helpers.
187 +///
188 +/// Usage: `cd("pi"); run("mise", "run", "check");`.
189 +///
190 +/// Pitfall: state lasts only for the current mise command. It does not cross
191 +/// separate `run = [...]` entries or dependent tasks.
192 +void cd(String dir)
194 + var next = path(dir);
195 + if (!Files.isDirectory(next))
196 + throw new IllegalArgumentException("not a directory: " + next);
197 + CWD = next;
200 +/// Read a task environment variable from this shell's environment map.
201 +///
202 +/// Reason: tasks need access to mise `env = { ... }` values without shell syntax.
203 +///
204 +/// Usage: `IO.println(env("HOSTNAME"));`.
205 +///
206 +/// Pitfall: returns `null` when absent; check required values explicitly.
207 +String env(String name)
209 + return ENV.get(name);
212 +/// Set an environment variable for future child processes launched by helpers.
213 +///
214 +/// Reason: Java cannot mutate the parent environment, but tasks often need to
215 +/// pass config to later `run(...)` calls.
216 +///
217 +/// Usage: `export("HOSTNAME", "desktop"); run("java", "bootstripper.java", "check");`.
218 +///
219 +/// Pitfall: affects only child processes launched after the call, not the
220 +/// already-running Java shell itself.
221 +void export(String name, String value)
223 + ENV.put(name, value);
226 +/// Build a configured `ProcessBuilder`.
227 +///
228 +/// Reason: centralizes `CWD` and `ENV` application for process helpers.
229 +///
230 +/// Usage: prefer `run(...)`, `result(...)`, `out(...)`, or `code(...)`; use this
231 +/// only when a task needs custom redirects.
232 +///
233 +/// Pitfall: mutating the returned builder does not mutate global helper state.
234 +ProcessBuilder process(String... cmd)
236 + var pb = new ProcessBuilder(cmd).directory(CWD.toFile());
237 + pb.environment().clear();
238 + pb.environment().putAll(ENV);
239 + return pb;
242 +/// Run a command, stream its IO, and fail on non-zero exit.
243 +///
244 +/// Reason: this is the Java replacement for a normal shell command line. The
245 +/// shell runs snippets with JShell's local execution engine so inherited child IO
246 +/// reaches mise output live.
247 +///
248 +/// Usage: `run("java", "bootstripper.java", "check");`.
249 +///
250 +/// Pitfall: no shell expansion, globbing, pipes, aliases, or quoting. Pass each
251 +/// argv item separately. Use Java helpers for file work.
252 +void run(String... cmd) throws Exception
254 + var code = process(cmd).inheritIO().start().waitFor();
255 + if (code != 0)
256 + throw new RuntimeException("command failed (" + code + "): " + String.join(" ", cmd));
259 +/// Run a command and capture merged stdout/stderr.
260 +///
261 +/// Reason: command substitution is sometimes needed, but should be explicit.
262 +///
263 +/// Usage: `var status = result("git", "status", "--short");`.
264 +///
265 +/// Pitfall: does not fail on non-zero exit; inspect `code()` or use `out(...)`.
266 +Result result(String... cmd) throws Exception
268 + var p = process(cmd).redirectErrorStream(true).start();
269 + var out = new String(p.getInputStream().readAllBytes(), StandardCharsets.UTF_8);
270 + return new Result(p.waitFor(), out);
273 +/// Run a command and return output, failing on non-zero exit.
274 +///
275 +/// Reason: terse command substitution for required commands.
276 +///
277 +/// Usage: `var root = out("git", "rev-parse", "--show-toplevel").strip();`.
278 +///
279 +/// Pitfall: output is buffered until the command exits; use `run(...)` for long
280 +/// commands or progress output.
281 +String out(String... cmd) throws Exception
283 + var r = result(cmd);
284 + if (r.code() != 0)
285 + throw new RuntimeException(r.out());
286 + return r.out();
289 +/// Run a command and return only its exit code.
290 +///
291 +/// Reason: direct replacement for shell tests like `cmd >/dev/null || ...`.
292 +///
293 +/// Usage: `if (code("git", "diff", "--quiet") != 0) IO.println("dirty");`.
294 +///
295 +/// Pitfall: output is captured and discarded. Use `result(...)` if diagnostics matter.
296 +int code(String... cmd) throws Exception
298 + return result(cmd).code();
301 +/// Read a UTF-8-ish text file using Java defaults.
302 +///
303 +/// Reason: common task file reads should not shell out to `cat`.
304 +///
305 +/// Usage: `var text = read("mise.toml");`.
306 +///
307 +/// Pitfall: path resolves against `pwd()`, not necessarily the repo root after `cd(...)`.
308 +String read(String file) throws Exception
310 + return Files.readString(path(file));
313 +/// Write text to a file, creating parent directories.
314 +///
315 +/// Reason: common task file writes should not shell out to `mkdir`/redirects.
316 +///
317 +/// Usage: `write("target/out.txt", "ok");`.
318 +///
319 +/// Pitfall: overwrites existing content. Use `Files.writeString(...)` directly
320 +/// when append/open options matter.
321 +void write(String file, String text) throws Exception
323 + var p = path(file);
324 + var parent = p.getParent();
325 + if (parent != null)
326 + Files.createDirectories(parent);
327 + Files.writeString(p, text);
330 +/// Create a directory and missing parents.
331 +///
332 +/// Reason: terse Java replacement for `mkdir -p`.
333 +///
334 +/// Usage: `mkdir("build/classes");`.
335 +///
336 +/// Pitfall: succeeds if the directory already exists; fails if a path component
337 +/// is a normal file.
338 +void mkdir(String dir) throws Exception
340 + Files.createDirectories(path(dir));
343 +/// Guard destructive helpers against catastrophic targets.
344 +///
345 +/// Reason: `rm(...)` convenience is useful, but deleting HOME, filesystem roots,
346 +/// or the current task directory is never acceptable for dorkfiles tasks.
347 +///
348 +/// Usage: internal helper used by `rm(...)`, `rmdir(...)`, and `rmTree(...)`.
349 +///
350 +/// Pitfall: this is a safety floor, not a permission model. Review destructive
351 +/// paths anyway.
352 +Path protectDelete(Path p)
354 + p = p.toAbsolutePath().normalize();
355 + var home = Path.of(System.getProperty("user.home")).toAbsolutePath().normalize();
356 + if (p.getParent() == null || p.equals(home) || p.equals(CWD))
357 + throw new IllegalArgumentException("refuse to delete: " + p);
358 + return p;
361 +/// Delete a file or symlink if present.
362 +///
363 +/// Reason: `Files.deleteIfExists(...)` is verbose for one-off cleanup tasks.
364 +///
365 +/// Usage: `rm("target", "old.log");` or `rm("old.log");`.
366 +///
367 +/// Pitfall: refuses normal directories; use `rmdir(...)` for empty directories
368 +/// or `rmTree(...)` for recursive deletion.
369 +void rm(String first, String... more) throws Exception
371 + var p = protectDelete(path(first, more));
372 + if (Files.isDirectory(p, LinkOption.NOFOLLOW_LINKS) && !Files.isSymbolicLink(p))
373 + throw new IllegalArgumentException("is a directory; use rmdir or rmTree: " + p);
374 + Files.deleteIfExists(p);
377 +/// Delete an empty directory if present.
378 +///
379 +/// Reason: common cleanup wants `rmdir` semantics, not recursive deletion.
380 +///
381 +/// Usage: `rmdir("target", "empty");`.
382 +///
383 +/// Pitfall: fails when the directory is not empty. That is intentional; choose
384 +/// `rmTree(...)` explicitly for recursive deletion.
385 +void rmdir(String first, String... more) throws Exception
387 + Files.deleteIfExists(protectDelete(path(first, more)));
390 +/// Recursively delete a file tree.
391 +///
392 +/// Reason: some build/cache cleanup truly needs recursive deletion, but it
393 +/// should be explicit and guarded.
394 +///
395 +/// Usage: `rmTree("target");`.
396 +///
397 +/// Pitfall: deletes contents recursively. It refuses HOME, filesystem roots, and
398 +/// current `pwd()`, but callers still own choosing the right path.
399 +void rmTree(String first, String... more) throws Exception
401 + var p = protectDelete(path(first, more));
402 + if (!Files.exists(p, LinkOption.NOFOLLOW_LINKS))
403 + return;
404 + if (Files.isSymbolicLink(p) || !Files.isDirectory(p, LinkOption.NOFOLLOW_LINKS))
406 + Files.delete(p);
407 + return;
409 + try (var stream = Files.walk(p))
411 + for (var x : stream.sorted(Comparator.reverseOrder()).toList())
412 + Files.deleteIfExists(x);
416 +/// List direct children matching a glob in `pwd()`.
417 +///
418 +/// Reason: simple file selection should not need shell glob expansion.
419 +///
420 +/// Usage: `for (var file : glob("*.symlinks")) IO.println(file);`.
421 +///
422 +/// Pitfall: this is not recursive and uses Java `DirectoryStream` glob syntax,
423 +/// not Bash globstar rules.
424 +List<Path> glob(String pattern) throws Exception
426 + try (var stream = Files.newDirectoryStream(CWD, pattern))
428 + var paths = new ArrayList<Path>();
429 + stream.forEach(paths::add);
430 + paths.sort(Comparator.naturalOrder());
431 + return paths;
435 +/// Find an executable on `PATH`.
436 +///
437 +/// Reason: tasks sometimes need an explicit dependency probe without shelling out
438 +/// to `which`/`command -v`.
439 +///
440 +/// Usage: `if (which("podman") == null) throw new IllegalStateException("podman missing");`.
441 +///
442 +/// Pitfall: returns `null` when not found. On Windows it checks `PATHEXT`; on
443 +/// Unix it checks the exact name only.
444 +String which(String name)
446 + var path = ENV.getOrDefault("PATH", "");
447 + var extensions = System.getProperty("os.name").toLowerCase(Locale.ROOT).contains("win")
448 + ? ENV.getOrDefault("PATHEXT", ".EXE;.CMD;.BAT").split(Pattern.quote(File.pathSeparator))
449 + : new String[] { "" };
450 + for (var dir : path.split(Pattern.quote(File.pathSeparator)))
452 + for (var extension : extensions)
454 + var candidate = Path.of(dir, name + extension);
455 + if (Files.isExecutable(candidate))
456 + return candidate.toString();
459 + return null;
461 +""";