diff --git a/AGENTS.md b/AGENTS.md index eb8d179..1f28e5e 100644 --- a/AGENTS.md +++ b/AGENTS.md @@ -10,8 +10,8 @@ non-trivial functions. No essays. ## This package -- `bjo build` builds the shell: `src/main.exe`, and the native - `src/main` (`(aot #t)`). +- `bjo build` builds the shell: `src/main.exe`. `bin/bjosh` starts it with + dotnet. No Native AOT: it cannot load the user's commands. - `bjo test` runs the tests. `tests/run.bjo` and `tests/interactive.bjo` run `src/main.exe`, so run `bjo build` first. - It depends on bjoterm at `../bjoterm`. A change there needs `bjo build` @@ -27,9 +27,18 @@ non-trivial functions. No essays. - `(bjosh commands)`: the value commands, and their table. - `(bjosh pipeline)`: value commands next to each other, as one unit. - `(bjosh editor)`: when Enter runs a line, and the completer. + - `(bjosh api)`: what a package of user commands imports: `Extension`, + `ShellCommand`, `ShellView`. + - `(bjosh user)`: builds and loads the package of user commands, in + `$XDG_CONFIG_HOME/bjosh/commands`, with `(std plugin)`. - Tests: - `tests/syntax.bjo`, `tests/expand.bjo`, `tests/editor.bjo`: unit tests. - `tests/run.bjo`: lines through `bjosh -c`, a file, and stdin. - `tests/values.bjo`: the value commands through `bjosh -c`. - `tests/interactive.bjo`: job control, the prompt and the start-up file under `script`. + - `tests/extension.bjo`: user commands and their prompt, in a package + that the test writes. +- The tests that run bjosh with `-c` load the user commands of your own + `XDG_CONFIG_HOME`, when there are any. `tests/extension.bjo` and + `tests/interactive.bjo` set it to a directory of their own. diff --git a/bin/bjosh b/bin/bjosh new file mode 100755 index 0000000..9582a1e --- /dev/null +++ b/bin/bjosh @@ -0,0 +1,4 @@ +#!/bin/sh +# Starts bjosh: src/main.exe beside this directory, with dotnet. +here=$(dirname "$(readlink -f "$0")") +exec dotnet "$here/../src/main.exe" "$@" diff --git a/manifest.bjodat b/manifest.bjodat index e8986a4..fe64fe8 100644 --- a/manifest.bjodat +++ b/manifest.bjodat @@ -3,8 +3,8 @@ (version "0.1.0") (description "A shell: POSIX command lines, job control, and built-in commands in Bjolang that pass values. Linux.") (license "MPL-2.0") - ;; A native executable too, src/main: a shell must start fast. - (aot #t) + ;; No Native AOT: it cannot load the user's commands (plan.org, phase 4). + ;; bin/bjosh starts src/main.exe. (depends ;; The line editor and the terminal. On disk until it has a remote. diff --git a/plan.org b/plan.org index d4a31c3..ec90257 100644 --- a/plan.org +++ b/plan.org @@ -364,10 +364,80 @@ the text above:* ~tests/line-terminal.bjo~ tests ~#:notices~; Bjolang's test 622 tests ~output-to-errors~. -** Phase 4: later +** Phase 4: commands in Bjolang -- Commands that users write in Bjolang, compiled, and loaded at start-up - from ~~/.config/bjosh/commands/~. +User commands, compiled, loaded into the shell at start-up. Needs +~(std plugin)~ in Bjolang (see plugin-plan.org there). + +1. *No Native AOT.* A Native AOT program cannot load assemblies. bjosh + runs as ~dotnet src/main.exe~, started by a script ~bin/bjosh~. Measured + (2026-12-01): 115 ms to the first prompt, against 9 ms with AOT. If that + is too slow: ReadyToRun for the modules, a change in Bjolang. + +2. *The package.* ~$XDG_CONFIG_HOME/bjosh/commands/~, or + ~~/.config/bjosh/commands/~: a Bjolang package that depends on bjosh. + Its module ~commands.bjo~ exports ~bjosh-extension~, an ~Extension~. + ~bjosh --new-commands~ writes the manifest, with the path of this + bjosh, and an example ~commands.bjo~. + +3. *~(bjosh api)~*, the module a package imports. It has the types and the + functions a command needs: + - ~Extension~: a record of ~commands~ (value commands), ~shell-commands~ + and ~prompt~ (~(Option (-> ShellView string))~). + - Value commands: ~ValueCommand~ as the built-in ones have, with their + long and short names, and the three kinds of body (bytes, values, + nothing). With ~emit!~, ~next!~, ~command-error~, ~record-of~ and the + ~Json~ type. + - Shell commands: ~(-> ShellView (Vec string) int)~. They run in the + shell, alone on a line, as ~cd~ does. + - ~ShellView~: what a shell command and the prompt can see and do: the + status ~$?~, a variable, setting a variable, the jobs (number and + state), and running a line (~shell-run~, which returns its status). So + a shell command can do what a shell function does: ~(shell-run sh + (str "cd " dir))~. + +4. *Loading.* + - At start-up of every bjosh (interactive, ~-c~ and a file), when the + directory is there. + - It is built with ~bjo build~ when a ~.bjo~ file or the manifest is + newer than ~commands.dll~: a build that does nothing takes 0.4 s, so + it is not run each time. The output of a build that fails is shown, + and the shell starts without the commands. + - ~reload~ builds and loads it again, into the same shell. + - An error of loading is one message; the shell goes on without the + commands. + +5. *Names.* A user's value command takes the place of a built-in one with + the same name, and follows the rule of decision 4 against PATH. A + user's shell command takes the place of a built-in one, except ~exit~, + ~reload~ and ~command~. ~type~ and ~help~ show them, marked as the + user's. + +6. *The prompt.* The order: ~PROMPT~ when it is set, else the extension's + ~prompt~, else the prompt of now. A prompt function that raises is + shown once, and the prompt of now is used until ~reload~. + +7. *Errors.* A command that raises is as a built-in one that raises: its + message, and status 1. + +8. *Tests.* ~tests/extension.bjo~ writes a package in a temporary + directory, with a value command, a shell command and a prompt, and runs + bjosh with ~XDG_CONFIG_HOME~ there: ~-c~ for the commands, ~script~ for + the prompt. Also: a package that does not compile, a rebuild after a + change, and ~reload~. + +*Implemented (2026-12-01). Where the code differs from the text above:* +- ~JobInfo~ has the fields ~job-number~, ~job-state~ and ~job-command~, and + the fields of ~ShellView~ are ~get-status~, ~get-var~, ~set-var~, + ~run-line~ and ~list-jobs~. With the names of ~JobEntry~ and ~Shell~, the + type checker could not tell the records apart in a lambda. +- A package that does not build is stale at each start, so each start + builds it again and shows the error, until it is fixed. +- Measured: 132 ms for ~bjosh -c true~ with the example package loaded. +- Tests: ~tests/extension.bjo~, 23 checks. The other tests: syntax 72, + expand 26, values 59, editor 24, run 60, interactive 16. + +** Phase 5: later - Control flow (~if~, ~for~). POSIX form, or a form of our own; to decide then. - Values in variables. diff --git a/src/api.bjo b/src/api.bjo new file mode 100644 index 0000000..6666171 --- /dev/null +++ b/src/api.bjo @@ -0,0 +1,91 @@ +;; This Source Code Form is subject to the terms of the Mozilla Public +;; License, v. 2.0. If a copy of the MPL was not distributed with this +;; file, You can obtain one at http://mozilla.org/MPL/2.0/. + +;; (bjosh api): what a package of user commands imports. See plan.org, +;; phase 4. +;; +;; - The package's module commands.bjo exports `bjosh-extension`, an +;; `Extension`: value commands, shell commands and a prompt. +;; - Value commands are as the built-in ones: a `ValueCommand` with a long +;; and a short name, and a `Body` that reads bytes, values or nothing. +;; They read with `next!`, write with `emit!`, and raise with +;; `command-error`. +;; - A shell command runs in the shell, alone on a line, as cd does. It gets +;; a `ShellView` and its arguments, and returns a status. +;; - The prompt function gets a `ShellView`, and returns the prompt. Escape +;; sequences in it take no columns. + +(import (std prelude)) +(import (text json)) +(import (bjosh values)) +(import (bjosh commands)) + +(export + Extension ShellCommand ShellView JobInfo + extension no-extension + shell-status shell-var shell-set-var! shell-run shell-jobs) + +(re-export + ValueCommand Body Values next! emit! command-error + record-of record-fields record? value-field value-line word->value) + +;; A job of the shell: its number, its state as `jobs` writes it (Running, +;; Stopped, Done, ...), and its command. +(type (: JobInfo (Record (: job-number int) (: job-state string) (: job-command string)))) + +;; What a shell command and the prompt can see of the shell, and do in it. +;; Read it with the functions below, not the fields. +(type (: ShellView (Record (: get-status (-> int)) + (: get-var (-> string (Option string))) + (: set-var (-> string string Unit)) + (: run-line (-> string int)) + (: list-jobs (-> (Vec JobInfo)))))) + +;; A shell command. +;; - `name`: what the user writes. +;; - `usage` and `help`: for `help`. +;; - `run`: takes the shell and the arguments, and returns the status. +(type (: ShellCommand (Record (: name string) + (: usage string) + (: help string) + (: run (-> ShellView (Vec string) int))))) + +;; What a package of user commands exports as `bjosh-extension`. +(type (: Extension (Record (: commands (Vec ValueCommand)) + (: shell-commands (Vec ShellCommand)) + (: prompt (Option (-> ShellView string)))))) + +;; An `Extension`. Each part is empty unless given. +(: (-> (#:commands (Vec ValueCommand)) (#:shell-commands (Vec ShellCommand)) + (#:prompt (Option (-> ShellView string))) + Extension)) +(defun (extension #:commands [] #:shell-commands [] #:prompt None) + (Extension (commands commands) (shell-commands shell-commands) (prompt prompt))) + +;; The extension of a shell with no package of user commands. +(: no-extension Extension) +(def no-extension (extension)) + +;; The status of the last line, $?. +(: (-> ShellView int)) +(defun (shell-status sh) ((record-ref sh get-status))) + +;; The value of a variable: a shell variable, the environment, or one of +;; ? $ and 0 to 9. +(: (-> ShellView string (Option string))) +(defun (shell-var sh name) ((record-ref sh get-var) name)) + +;; Sets a variable: in the environment when it is there, else as a shell +;; variable, as NAME=value does. +(: (-> ShellView string string Unit)) +(defun (shell-set-var! sh name value) ((record-ref sh set-var) name value)) + +;; Runs `line` as if it was typed, and returns its status. It writes to +;; stdout and stderr as the line would. +(: (-> ShellView string int)) +(defun (shell-run sh line) ((record-ref sh run-line) line)) + +;; The jobs, by number. +(: (-> ShellView (Vec JobInfo))) +(defun (shell-jobs sh) ((record-ref sh list-jobs))) diff --git a/src/builtins.bjo b/src/builtins.bjo index 52ebb03..7d548c2 100644 --- a/src/builtins.bjo +++ b/src/builtins.bjo @@ -15,6 +15,8 @@ (import (bjoterm line)) (import (bjosh syntax)) (import (bjosh shell)) +(import (bjosh api)) +(import (bjosh user)) (import (bjosh commands)) (import (bjosh values)) (import (text json)) @@ -221,6 +223,14 @@ ((Some text) (println (alias-line arg text)) 0) (None (shell-error (str "alias: " arg ": not found")) 1)))))))) +;; Builds the user's commands, and loads them again. +(: (-> Shell (Vec string) int)) +(defun (reload sh args) + (match (load-extension #t) + (None (shell-error (str "reload: there are no user commands in " (commands-dir))) 1) + ((Some (Ok ext)) (set-extension! sh ext) 0) + ((Some (Err message)) (shell-error message) 1))) + (: (-> Shell (Vec string) int)) (defun (unalias sh args) (each-status args @@ -252,7 +262,15 @@ (println (str name " is an alias for " (match (alias-ref sh name) ((Some t) t) (None "")))) 0) + ((some? (user-shell-command sh name)) (println (str name " is a shell command of yours")) 0) ((builtin? name) (println (str name " is a shell command")) 0) + ((some? (user-value-command sh name (fun (n) (some? (find-program n))))) + (match (user-value-command sh name (fun (n) (some? (find-program n)))) + ((Some c) + (println (str name " is a value command of yours: " + (record-ref c long) ", " (record-ref c short)))) + (None unit)) + 0) (else (match (value-command name (fun (n) (some? (find-program n)))) ((Some c) @@ -272,8 +290,21 @@ (defun (value-help-line c) (str " " (string-pad-right (record-ref c usage) 26) (string-pad-right (record-ref c short) 5) (record-ref c help))) +(: (-> ShellCommand string)) +(defun (user-help-line c) + (str " " (string-pad-right (record-ref c usage) 28) (record-ref c help))) + (: (-> Shell (Vec string) int)) (defun (help sh args) + (def ext (record-ref sh extension)) + (unless (vec-empty? (record-ref ext shell-commands)) + (println "Your shell commands:") + (for-each (fun (c) (println (user-help-line c))) (record-ref ext shell-commands)) + (println "")) + (unless (vec-empty? (record-ref ext commands)) + (println "Your value commands:") + (for-each (fun (c) (println (value-help-line c))) (record-ref ext commands)) + (println "")) (println "Shell commands:") (for-each (fun (b) (println (builtin-help-line b))) (builtins)) (println (str " " (string-pad-right "command NAME [ARG]..." 28) "run the program NAME, not an alias or a value command")) @@ -312,7 +343,8 @@ (Builtin (name "help") (usage "help") (help "this list") (run help)) (Builtin (name "history") (usage "history") (help "the lines written before") (run history)) (Builtin (name "alias") (usage "alias [NAME[=TEXT]]...") (help "list, show or set aliases; TEXT is one pipe") (run alias)) - (Builtin (name "unalias") (usage "unalias NAME...") (help "remove aliases") (run unalias))]) + (Builtin (name "unalias") (usage "unalias NAME...") (help "remove aliases") (run unalias)) + (Builtin (name "reload") (usage "reload") (help "build and load your commands again") (run reload))]) ;; =========================================================================== ;; Shell commands as values, in a pipe @@ -360,18 +392,21 @@ (body (OnNothing (bjoroutine (args out) (history-values sh args out))))))) (else None))) +(: (-> Builtin string)) +(defun (builtin-name b) (record-ref b name)) + (: (-> string bool)) (defun (builtin? name) - (any? (fun (b) (= (record-ref b name) name)) (builtins))) + (any? (fun (b) (= (builtin-name b) name)) (builtins))) (: (Vec string)) -(def builtin-names (vec-map (fun (b) (record-ref b name)) (builtins))) +(def builtin-names (vec-map builtin-name (builtins))) ;; Runs the shell command `name`. Returns its status; 127 when there is no ;; such command. (: (-> Shell string (Vec string) int)) (defun (run-builtin sh name args) - (match (find (fun (b) (= (record-ref b name) name)) (builtins)) + (match (find (fun (b) (= (builtin-name b) name)) (builtins)) ((Some b) (def status ((record-ref b run) sh args)) (flush-port (parameter-ref current-output-port)) diff --git a/src/exec.bjo b/src/exec.bjo index 8c32ca0..ab1898e 100644 --- a/src/exec.bjo +++ b/src/exec.bjo @@ -26,6 +26,9 @@ ;; - $(...) runs in a subshell (see `capture`). Its output is captured: ;; programs write through a filter at the end of their form, and value ;; commands write lines. +;; - The user's commands (see (bjosh user)): a shell command of theirs runs +;; as a shell command, before the shell's own. A value command of theirs +;; comes before a built-in one of the same name. ;; - >&2 copies stdout to stderr. It cannot be combined with another ;; redirection of stdout or stderr. @@ -37,9 +40,10 @@ (import (bjosh builtins)) (import (bjosh commands)) (import (bjosh pipeline)) +(import (bjosh api)) (import (std os)) -(export run-text expand-quoted) +(export run-text expand-quoted shell-view) ;; A command after expansion. `program?`: it was `command NAME`, so NAME is ;; a program, and `command` is not in `argv`. @@ -228,7 +232,7 @@ (def builtin-in-pipe (find (fun (e) (and (not (vec-empty? (record-ref e argv))) (not (record-ref e program?)) - (builtin? (vec-ref (record-ref e argv) 0)) + (shell-command? sh (vec-ref (record-ref e argv) 0)) (not (some? (shell-value-command sh (vec-ref (record-ref e argv) 0)))))) expanded)) (cond @@ -237,13 +241,17 @@ ((any? (fun (e) (vec-empty? (record-ref e argv))) expanded) (shell-error "a command in a pipe has no words") 2) - ((and (= (vec-length expanded) 1) (not (record-ref first program?)) (builtin? name)) + ((and (= (vec-length expanded) 1) (not (record-ref first program?)) (shell-command? sh name)) + (def args (vec-drop (record-ref first argv) 1)) (cond (background? (shell-error (str name ": a shell command cannot run in the background")) 2) ((not (and (vec-empty? (record-ref first assigns)) (vec-empty? (record-ref first redirects)))) (shell-error (str name ": assignments and redirections of shell commands are not supported yet")) 2) - (else (run-builtin sh name (vec-slice (record-ref first argv) 1 (- (vec-length (record-ref first argv)) 1)))))) + (else + (match (user-shell-command sh name) + ((Some c) (run-user-shell-command sh c args)) + (None (run-builtin sh name args)))))) (else (match builtin-in-pipe ((Some e) (shell-error (str (vec-ref (record-ref e argv) 0) ": a shell command cannot be in a pipe")) 2) @@ -261,7 +269,39 @@ (defun (stage-command sh name) (match (shell-value-command sh name) ((Some c) (Some c)) - (None (value-command-of name)))) + (None + (match (user-value-command sh name (fun (n) (some? (find-program n)))) + ((Some c) (Some c)) + (None (value-command-of name)))))) + +;; What a user's shell command and prompt see of `sh`. +(: (-> Shell ShellView)) +(defun (shell-view sh) + (ShellView (get-status (fun () (record-ref sh status))) + (get-var (fun (name) (var-ref sh name))) + (set-var (fun (name value) (var-set! sh name value) unit)) + (run-line (fun (line) (run-text sh line))) + (list-jobs (fun () + (vec-map (fun (e) (JobInfo (job-number (record-ref e number)) + (job-state (job-state-text e)) + (job-command (record-ref e text)))) + (record-ref sh jobs)))))) + +;; Runs the user's shell command `c`. A command that raises writes its +;; message, and returns 1. +(: (-> Shell ShellCommand (Vec string) int)) +(defun (run-user-shell-command sh c args) + (def status + (match (try ((record-ref c run) (shell-view sh) args) #:catch (System.Exception)) + ((Ok status) status) + ((Err e) (shell-error (str (record-ref c name) ": " (.-Message e))) 1))) + (flush-port (parameter-ref current-output-port)) + status) + +;; Whether `name` is a shell command: the user's or the shell's own. +(: (-> Shell string bool)) +(defun (shell-command? sh name) + (or (some? (user-shell-command sh name)) (builtin? name))) ;; The value command of a stage: none for `command NAME`, and for echo ;; with flags. diff --git a/src/main.bjo b/src/main.bjo index 0594634..5d65fa5 100644 --- a/src/main.bjo +++ b/src/main.bjo @@ -8,12 +8,17 @@ ;; terminal; else runs the lines of stdin ;; bjosh -c LINE runs LINE ;; bjosh FILE ARG... runs the lines of FILE, with $0 FILE, $1 ARG... +;; bjosh --new-commands +;; writes a package of user commands, with an +;; example; see (bjosh user) ;; ;; The exit code is the status of the last line, or the code of `exit`. ;; ;; - An interactive shell first runs the lines of the start-up file, ;; $XDG_CONFIG_HOME/bjosh/rc or ~/.config/bjosh/rc. -;; - The prompt is $PROMPT when it is set; see `custom-prompt`. +;; - Each bjosh loads the user's commands first, when there are any. +;; - The prompt is $PROMPT when it is set (see `custom-prompt`), else the +;; user's prompt function, else the directory and $. (import (std prelude)) (import (std run)) @@ -24,6 +29,8 @@ (import (bjosh builtins)) (import (bjosh exec)) (import (bjosh editor)) +(import (bjosh api)) +(import (bjosh user)) ;; =========================================================================== ;; The loop @@ -53,15 +60,39 @@ (str "~" (string-drop dir (string-length home))) dir)) -;; The prompt: `custom-prompt` of $PROMPT, else the directory, and $ green -;; after status 0, else red. +;; The prompt: `custom-prompt` of $PROMPT, else the user's prompt function, +;; else the directory, and $ green after status 0, else red. A prompt +;; function that raises writes its message once, and is not used again +;; until `reload`. (: (-> Shell string)) (defun (prompt sh) + (def user (record-ref (record-ref sh extension) prompt)) (match (var-ref sh "PROMPT") ((Some template) (custom-prompt sh template)) (None - (def color (if (= (record-ref sh status) 0) "32" "31")) - (str "\u{1B}[1;34m" (shown-directory) "\u{1B}[0m \u{1B}[" color "m$\u{1B}[0m ")))) + (match (if (record-ref sh prompt-failed?) None user) + ((Some f) + (match (try (f (shell-view sh)) #:catch (System.Exception)) + ((Ok text) text) + ((Err e) + (shell-error (str "the prompt of your commands raised: " (.-Message e))) + (prompt-failed! sh) + (default-prompt sh)))) + (None (default-prompt sh)))))) + +(: (-> Shell string)) +(defun (default-prompt sh) + (def color (if (= (record-ref sh status) 0) "32" "31")) + (str "\u{1B}[1;34m" (shown-directory) "\u{1B}[0m \u{1B}[" color "m$\u{1B}[0m ")) + +;; Loads the user's commands into `sh`. A failure writes its message. +(: (-> Shell Shell)) +(defun (with-extension sh) + (match (load-extension #f) + (None unit) + ((Some (Ok ext)) (set-extension! sh ext)) + ((Some (Err message)) (shell-error message))) + sh) (import/extern (user-name (: System.Environment.UserName string #:get #:no-raise)) @@ -125,7 +156,7 @@ (def path (history-path)) (ignore (line-history-load! ed path)) (ignore (try (directory-create (path-combine path "..")) #:catch (System.Exception))) - (def sh (make-shell jc (Some ed) ["bjosh"])) + (def sh (with-extension (make-shell jc (Some ed) ["bjosh"]))) (def rc (rc-path)) (when (file-exists? rc) (match (file-read-text rc) @@ -153,17 +184,23 @@ (: (-> (Vec string) int)) (defun (run-file args) (match (file-read-text (vec-ref args 0)) - ((Ok text) (run-script (make-shell None None args) text)) + ((Ok text) (run-script (with-extension (make-shell None None args)) text)) ((Err e) (shell-error (fs-error-message e)) 127))) (defun (main args) (cond + ((= args ["--new-commands"]) + (match (write-example) + (None + (println (str "Wrote " (commands-dir) ". Edit src/commands.bjo there, and run reload in bjosh.")) + 0) + ((Some message) (shell-error message) 1))) ((and (>= (vec-length args) 2) (= (vec-ref args 0) "-c")) - (run-script (make-shell None None (vec-add-first (vec-slice args 2 (- (vec-length args) 2)) "bjosh")) + (run-script (with-extension (make-shell None None (vec-add-first (vec-slice args 2 (- (vec-length args) 2)) "bjosh"))) (vec-ref args 1))) ((vec-empty? args) (match (terminal-open) ((Ok term) (interactive term)) ((Err _) - (run-script (make-shell None None ["bjosh"]) (read-all (parameter-ref current-input-port)))))) + (run-script (with-extension (make-shell None None ["bjosh"])) (read-all (parameter-ref current-input-port)))))) (else (run-file args)))) diff --git a/src/shell.bjo b/src/shell.bjo index bc1fd36..de3ba7f 100644 --- a/src/shell.bjo +++ b/src/shell.bjo @@ -21,10 +21,12 @@ (import (bjoterm line)) (import (bjosh syntax)) (import (bjosh expand)) +(import (bjosh api)) (export Shell JobEntry make-shell subshell shell-error - alias-ref alias-set! alias-remove! set-subst-status! + alias-ref alias-set! alias-remove! set-subst-status! set-extension! prompt-failed! + user-value-command user-shell-command set-status! request-exit! warn-stopped! var-export! var-ref var-set! var-unset! shell-expander job-set-state! job-add! job-remove! job-find job-current job-mark-recent! jobs-stopped? @@ -47,6 +49,9 @@ ;; commands write lines, not tables. ;; - `subst-status`: the status of the last $(...) of the command being ;; expanded. A command of only assignments returns it, as in POSIX. +;; - `extension`: the user's commands and prompt (see (bjosh user)). +;; - `prompt-failed?`: the user's prompt raised; it is not used until +;; `reload`. (type (: Shell (Record (: vars (Map string string) #:mutable) (: status int #:mutable) (: jc (Option JobControl)) @@ -58,7 +63,9 @@ (: warned-stopped? bool #:mutable) (: aliases (Map string string) #:mutable) (: capture? bool) - (: subst-status (Option int) #:mutable)))) + (: subst-status (Option int) #:mutable) + (: extension Extension #:mutable) + (: prompt-failed? bool #:mutable)))) (import/extern (pid (: System.Environment.ProcessId int #:get #:no-raise))) @@ -67,7 +74,8 @@ (defun (make-shell jc editor args) (Shell (vars (map-empty)) (status 0) (jc jc) (editor editor) (args args) (jobs []) (recent []) (exit-code None) (warned-stopped? #f) - (aliases (map-empty)) (capture? #f) (subst-status None))) + (aliases (map-empty)) (capture? #f) (subst-status None) + (extension no-extension) (prompt-failed? #f))) ;; A copy of `sh` for $(...): the same variables, aliases and status, which ;; it can change for itself, and no jobs or job control. @@ -76,11 +84,38 @@ (Shell (vars (record-ref sh vars)) (status (record-ref sh status)) (jc None) (editor (record-ref sh editor)) (args (record-ref sh args)) (jobs []) (recent []) (exit-code None) (warned-stopped? #f) - (aliases (record-ref sh aliases)) (capture? #t) (subst-status None))) + (aliases (record-ref sh aliases)) (capture? #t) (subst-status None) + (extension (record-ref sh extension)) (prompt-failed? (record-ref sh prompt-failed?)))) (: (-> Shell (Option int) void)) (defun (set-subst-status! sh status) (record-set! sh (subst-status status))) +(: (-> Shell Extension void)) +(defun (set-extension! sh ext) + (record-set! sh (extension ext) (prompt-failed? #f))) + +(: (-> Shell void)) +(defun (prompt-failed! sh) (record-set! sh (prompt-failed? #t))) + +;; The user's value command of `name`: by its short name, or by its long +;; name when `program?` says no program has that name (decision 4). +(: (-> Shell string (-> string bool) (Option ValueCommand))) +(defun (user-value-command sh name program?) + (def commands (record-ref (record-ref sh extension) commands)) + (match (find (fun (c) (= (record-ref c short) name)) commands) + ((Some c) (Some c)) + (None (if (program? name) + None + (find (fun (c) (= (record-ref c long) name)) commands))))) + +;; The user's shell command of `name`. exit, reload and command are always +;; the shell's own. +(: (-> Shell string (Option ShellCommand))) +(defun (user-shell-command sh name) + (if (vec-contains? ["exit" "reload" "command"] name) + None + (find (fun (c) (= (record-ref c name) name)) (record-ref (record-ref sh extension) shell-commands)))) + (: (-> Shell string (Option string))) (defun (alias-ref sh name) (map-try-ref (record-ref sh aliases) name)) diff --git a/src/user.bjo b/src/user.bjo new file mode 100644 index 0000000..f776c15 --- /dev/null +++ b/src/user.bjo @@ -0,0 +1,149 @@ +;; This Source Code Form is subject to the terms of the Mozilla Public +;; License, v. 2.0. If a copy of the MPL was not distributed with this +;; file, You can obtain one at http://mozilla.org/MPL/2.0/. + +;; (bjosh user): the package of user commands. See plan.org, phase 4. +;; +;; - Where: $XDG_CONFIG_HOME/bjosh/commands, or ~/.config/bjosh/commands. A +;; Bjolang package whose module src/commands.bjo exports +;; `bjosh-extension`, an `Extension` of (bjosh api). +;; - Building: `bjo build` in the package, when a file of it is newer than +;; src/commands.dll, or when asked (`reload`). A build that does nothing +;; takes 0.4 s, so it is not run at each start. +;; - Loading: with (std plugin). The package shares bjosh's modules, so its +;; commands are of bjosh's own types. +;; - Errors: a build that fails, or a load that fails, writes its message, +;; and the extension stays as it was. + +(import (std prelude)) +(import (std run)) +(import (std plugin)) +(import (bjosh api)) + +(export commands-dir load-extension write-example) + +(import/extern + (base-directory (: System.AppContext.BaseDirectory string #:get #:no-raise))) + +;; The directory of the package of user commands. +(: (-> string)) +(defun (commands-dir) + (def config (match (getenv "XDG_CONFIG_HOME") + ((Some c) c) + (None (path-combine (match (getenv "HOME") ((Some h) h) (None ".")) ".config")))) + (path-combine config "bjosh/commands")) + +(: (-> string long)) +(defun (modified-ms path) + (match (file-info path) + ((Some info) (record-ref info modified-ms)) + (None 0L))) + +;; Whether `dll` is older than the manifest or a .bjo file of `dir`. +(: (-> string string bool)) +(defun (stale? dir dll) + (def built (modified-ms dll)) + (or (= built 0L) + (> (modified-ms (path-combine dir "manifest.bjodat")) built) + (any? (fun (p) (and (string-ends-with? p ".bjo") (> (modified-ms p) built))) + (->vec (map path->string/lossy (directory-walk (path-combine dir "src"))))))) + +;; Runs `bjo build` in `dir`. Returns the message of a failure. +(: (-> string (Option string))) +(defun (build dir) + (match (run/output '(sh "-c" "cd \"$0\" && bjo build 2>&1" ,dir)) + ((Ok (Tuple 0 _)) None) + ((Ok (Tuple _ out)) (Some (str "the user commands did not build:\n" (string-trim-right out)))) + ((Err e) (Some (str "the user commands did not build: " (run-error-message e)))))) + +;; The extension of the package of user commands. +;; - None when there is no package. +;; - Builds it first when it is stale, or when `rebuild?`. +;; - Returns the message of a build or a load that fails. +(: (-> bool (Option (Result string Extension)))) +(defun (load-extension rebuild?) + (def dir (commands-dir)) + (def dll (path-combine dir "src/commands.dll")) + (if (not (file-exists? (path-combine dir "manifest.bjodat"))) + None + (Some + (match (if (or rebuild? (stale? dir dll)) (build dir) None) + ((Some message) (Err message)) + (None + (: (Result PluginError Extension)) + (def loaded (plugin-load dll "bjosh-extension")) + (match loaded + ((Ok ext) (Ok ext)) + ((Err e) (Err (str "the user commands did not load: " (plugin-error-message e)))))))))) + +;; The directory of this bjosh's package: the parent of src, where main.exe +;; is. +(: (-> string)) +(defun (bjosh-dir) + (path-absolute (path-combine base-directory ".."))) + +(: string) +(def example-commands + ";; Your commands for bjosh. `reload` in bjosh builds and loads them. +;; The types and functions are in (bjosh api): see its source. + +(import (std prelude)) +(import (text json)) +(import (bjosh api)) + +(export bjosh-extension) + +;; A value command: the values of its input, each twice. +(: (-> (Vec string) Values Values Unit)) +(defbjo (twice args in out) + (let go () + (match (next! in) + (None unit) + ((Some v) (emit! out v) (emit! out v) (go))))) + +;; A shell command, as a shell function would be: cd to a directory under +;; ~/src. +(: (-> ShellView (Vec string) int)) +(defun (src sh args) + (shell-run sh (str \"cd ~/src/\" (if (vec-empty? args) \"\" (vec-ref args 0))))) + +;; The prompt: the directory, and $ in red after a failure. +(: (-> ShellView string)) +(defun (prompt sh) + (def mark (if (= (shell-status sh) 0) \"$\" \"\\u{1B}[31m$\\u{1B}[0m\")) + (str (current-directory) \" \" mark \" \")) + +(: bjosh-extension Extension) +(def bjosh-extension + (extension + #:commands [(ValueCommand (long \"twice\") (short \"tw\") (usage \"twice\") + (help \"each value twice\") + (body (OnValues (bjoroutine (args in out) (twice args in out)))))] + #:shell-commands [(ShellCommand (name \"src\") (usage \"src [DIR]\") + (help \"cd to ~/src/DIR\") (run src))] + #:prompt (Some prompt))) +") + +;; Writes a package of user commands, with an example, to `commands-dir`. +;; Returns the message of a failure: the directory is there already, or a +;; file does not write. +(: (-> (Option string))) +(defun (write-example) + (def dir (commands-dir)) + (def manifest + (str "(package\n" + " (name (bjosh-commands))\n" + " (version \"0.1.0\")\n" + " (description \"My commands for bjosh.\")\n" + " (depends\n" + " (package (name (bjosh)) (source (path (dir " (written (bjosh-dir)) "))))))\n")) + (cond + ((directory-exists? dir) (Some (str dir ": there already"))) + (else + (ignore (directory-create (path-combine dir "src"))) + (match (file-write-text (path-combine dir "manifest.bjodat") manifest) + ((Err e) (Some (fs-error-message e))) + ((Ok _) + (match (file-write-text (path-combine dir "src/commands.bjo") example-commands) + ((Err e) (Some (fs-error-message e))) + ((Ok _) None))))))) diff --git a/tests/extension.bjo b/tests/extension.bjo new file mode 100644 index 0000000..2adc77c --- /dev/null +++ b/tests/extension.bjo @@ -0,0 +1,187 @@ +;; This Source Code Form is subject to the terms of the Mozilla Public +;; License, v. 2.0. If a copy of the MPL was not distributed with this +;; file, You can obtain one at http://mozilla.org/MPL/2.0/. + +;; User commands: a package in $XDG_CONFIG_HOME/bjosh/commands, built and +;; loaded by bjosh. See plan.org, phase 4. +;; +;; - `bjosh --new-commands` writes the package; the test then replaces its +;; src/commands.bjo. +;; - Value commands, shell commands, names that are protected, errors, a +;; rebuild after a change, and `reload`. +;; - The prompt, under `script`, when /usr/bin/script is there. +;; +;; bjo build && bjo test tests/extension.bjo + +(import (std prelude)) +(import (std simpletest)) +(import (std run)) + +(import/extern + (temp-dir (: System.IO.Path.GetTempPath (-> string))) + (process-id (: System.Environment.ProcessId int #:get #:no-raise))) + +(def shell "src/main.exe") + +(def config (path-combine (temp-dir) (str "bjosh-extension-" (int->string process-id)))) + +(def source (path-combine config "bjosh/commands/src/commands.bjo")) + +;; Runs bjosh with `args`, and this test's config directory. Returns "out", +;; then "err: " and the error text when there is one, then "code: n" when it +;; is not 0. +(: (-> (Vec string) string)) +(defun (bjosh args) + (def err-path (path-combine config "stderr")) + (match (run/output (FErrInto err-path (FArgv (vec-append ["env" (str "XDG_CONFIG_HOME=" config) "dotnet" shell] args)))) + ((Ok (Tuple code out)) + (def err (match (file-read-text err-path) ((Ok t) t) ((Err _) ""))) + (string-trim-right + (str out + (if (string-empty? err) "" (str "err: " err)) + (if (= code 0) "" (str "code: " (int->string code)))))) + ((Err e) (str "did not run: " (run-error-message e))))) + +(: (-> string string)) +(defun (c line) (bjosh ["-c" line])) + +;; The test's commands. `help-text` is the help of `twice`, to see a +;; rebuild. +(: (-> string string)) +(defun (commands help-text) + (str "(import (std prelude)) +(import (text json)) +(import (bjosh api)) + +(export bjosh-extension) + +(: (-> (Vec string) Values Values Unit)) +(defbjo (twice args in out) + (let go () + (match (next! in) + (None unit) + ((Some v) (emit! out v) (emit! out v) (go))))) + +(: (-> ShellView (Vec string) int)) +(defun (setx sh args) + (shell-set-var! sh \"X\" (string-join args \"-\")) + 0) + +(: (-> ShellView (Vec string) int)) +(defun (both sh args) + (def a (shell-run sh \"echo one\")) + (def b (shell-run sh \"false\")) + (println (str \"statuses \" (int->string a) \" \" (int->string b) \" X=\" + (match (shell-var sh \"X\") ((Some x) x) (None \"none\")))) + 7) + +(: (-> ShellView (Vec string) int)) +(defun (boom sh args) (command-error \"boom: it failed\")) + +(: (-> ShellView (Vec string) int)) +(defun (my-exit sh args) (println \"not this exit\") 0) + +(: (-> ShellView string)) +(defun (prompt sh) + (if (= (shell-status sh) 0) + (str \"[ext \" (int->string (vec-length (shell-jobs sh))) \"]> \") + (command-error \"the prompt failed\"))) + +(: bjosh-extension Extension) +(def bjosh-extension + (extension + #:commands [(ValueCommand (long \"twice\") (short \"tw\") (usage \"twice\") + (help \"" help-text "\") + (body (OnValues (bjoroutine (args in out) (twice args in out)))))] + #:shell-commands [(ShellCommand (name \"setx\") (usage \"setx WORD...\") (help \"set X\") (run setx)) + (ShellCommand (name \"both\") (usage \"both\") (help \"run two lines\") (run both)) + (ShellCommand (name \"boom\") (usage \"boom\") (help \"raise\") (run boom)) + (ShellCommand (name \"exit\") (usage \"exit\") (help \"not used\") (run my-exit))] + #:prompt (Some prompt))) +")) + +(: (-> string void)) +(defun (write-source text) + (match (file-write-text source text) + ((Ok _) unit) + ((Err e) (println (str "FAILURE: " (fs-error-message e)))))) + +;; The output without escape sequences and carriage returns. +(: (-> string string)) +(defun (plain text) + (def chars (string->vec (string-replace text "\r" ""))) + (let go ((i 0) (out (stringbuilder-empty))) + (cond + ((= i (vec-length chars)) (stringbuilder->string out)) + ((and (= (char->int (vec-ref chars i)) 27) (< (+ i 1) (vec-length chars)) (= (vec-ref chars (+ i 1)) #\[)) + (let skip ((j (+ i 2))) + (if (and (< j (vec-length chars)) + (let ((code (char->int (vec-ref chars j)))) (and (>= code 0x20) (<= code 0x3f)))) + (skip (+ j 1)) + (go (+ j 1) out)))) + (else (stringbuilder-add! out (vec-ref chars i)) (go (+ i 1) out))))) + +;; Types lines into an interactive bjosh under `script`. Returns what it +;; writes, without escape sequences. +(: (-> (Vec string) string)) +(defun (interactive lines) + (def keys (str "sleep 2.5; " + (string-join (vec-map (fun (l) (str "printf '" l "\\r'; sleep 0.7")) lines) "; "))) + (def command (str "(" keys ") | XDG_STATE_HOME=" config " XDG_CONFIG_HOME=" config + " script -qec 'dotnet src/main.exe' /dev/null")) + (match (run/output '(sh "-c" ,command)) + ((Ok (Tuple _ text)) (plain text)) + ((Err e) (run-error-message e)))) + +(defun (main args) + (unless (file-exists? shell) + (println "FAILURE: src/main.exe is missing: run bjo build first")) + (ignore (directory-create config)) + + (expect "no package: the shell runs as before" (c "echo hi") "hi") + (expect-true "--new-commands writes the package" + (string-starts-with? (bjosh ["--new-commands"]) "Wrote ")) + (expect-true "and not over one that is there" + (string-ends-with? (bjosh ["--new-commands"]) "there already\ncode: 1")) + (expect "the example builds and runs" (c "echo a | twice") "a\na") + + (write-source (commands "each value twice")) + (expect "a value command, by its long name" (c "echo a | twice | count") "2") + (expect "and by its short name" (c "echo a | tw | tw | count") "4") + (expect "type of a value command" (c "type twice") "twice is a value command of yours: twice, tw") + (expect "type of a shell command" (c "type setx") "setx is a shell command of yours") + (expect-true "help lists them" + (string-contains? (c "help") "Your shell commands:\n setx WORD... set X\n")) + (expect "a shell command sets a variable" (c "setx a b; echo $X") "a-b") + (expect "it runs lines, and returns a status" (c "X=v; both; echo $?") "one\nstatuses 0 1 X=v\n7") + (expect "a shell command that raises" (c "boom; echo $?") "1\nerr: bjosh: boom: boom: it failed") + (expect "exit is not replaced" (c "exit 4") "code: 4") + (expect "a shell command is not in a pipe" (c "setx a | cat") + "err: bjosh: setx: a shell command cannot be in a pipe\ncode: 2") + + (write-source (commands "each value two times")) + (expect-true "a change is built at the next start" + (string-contains? (c "help") "each value two times")) + + (write-source "(oops") + (def broken (c "echo still runs")) + (expect-true "a package that does not build: the shell runs" + (string-starts-with? broken "still runs\nerr: bjosh: the user commands did not build:")) + (expect-true "with the compiler's message" (string-contains? broken "never closed")) + (expect-true "and no user commands" (string-contains? (c "type twice") "not found")) + + (write-source (commands "after reload")) + (expect-true "reload builds and loads" (string-contains? (c "reload; help") "after reload")) + + (if (not (file-exists? "/usr/bin/script")) + (println "skipped: the prompt (no script command)") + (let ((out (interactive ["true" "false" "true" "exit"]))) + (expect-true "the prompt of the commands" (string-contains? out "[ext 0]> true")) + (expect-true "a prompt that raises writes its message" + (string-contains? out "bjosh: the prompt of your commands raised: the prompt failed")) + (expect "once" (vec-length (string-split out "the prompt failed")) 2) + (expect-true "and the default prompt is used after it" (not (string-contains? out "[ext 0]> exit"))))) + + (ignore (directory-delete-tree config)) + (println "extension ok") + 0)