diff --git a/plan.org b/plan.org index f686fb6..d993896 100644 --- a/plan.org +++ b/plan.org @@ -275,16 +275,23 @@ the text above:* its input to the end after the count, so the stage before it can end. - ~from-json~ reads one document, and gives an array as its values; else one document per line. ~open~ goes by the extension. -- Value commands with ~&~, with redirections, or with assignments are an - error. A pipe of only value commands runs in the shell, with an empty - input; Ctrl-C stops it with status 130. +- Redirections of value commands: ~<~ on the first of a group, ~>~ and + ~>>~ on the last, which then writes lines, not a table. A value command + after one with ~>~ is an error. ~2>~, ~2>&1~, assignments and ~&~ of + value commands are errors. +- A pipe of only value commands runs in the shell, with an empty input + or the file of ~<~. Ctrl-C cancels it with status 130, but only at a + point where a command waits for a value: a read of a terminal or a FIFO + (~li < /dev/tty~) is not cancelled, and goes on until it has a line. + There is no test of Ctrl-C: no value command waits long otherwise. +- ~jobs~ and ~history~ are values in a pipe: records of number, current, + state, command and id; and of number and line. Alone they write text. - ~2>&1~ is done (phase 3): ~>FILE 2>&1~ works, ~2>&1 >FILE~ is an error. ~>&2~ has no form in ~(std run)~ yet. -- Not done: ~jobs~ and ~history~ as values, and ~echo~. A value ~echo~ - would take the name from ~/bin/echo~, which decision 4 does not allow; - to decide. -- Tests: ~tests/values.bjo~ (40); ~tests/run.bjo~ (34); - ~tests/interactive.bjo~ (10). +- Not done: ~echo~. A value ~echo~ would take the name from ~/bin/echo~, + which decision 4 does not allow; to decide. +- Tests: ~tests/values.bjo~ (51); ~tests/run.bjo~ (34); + ~tests/interactive.bjo~ (12). ** Phase 3: more POSIX, and the rest of the edges diff --git a/src/builtins.bjo b/src/builtins.bjo index 05c4a49..4a2bdc4 100644 --- a/src/builtins.bjo +++ b/src/builtins.bjo @@ -15,8 +15,10 @@ (import (bjoterm line)) (import (bjosh shell)) (import (bjosh commands)) +(import (bjosh values)) +(import (text json)) -(export builtin? run-builtin builtin-names find-program) +(export builtin? run-builtin builtin-names find-program shell-value-command) (type (: Builtin (Record (: name string) (: usage string) @@ -262,6 +264,52 @@ (Builtin (name "help") (usage "help") (help "this list") (run help)) (Builtin (name "history") (usage "history") (help "the lines written before") (run history))]) +;; =========================================================================== +;; Shell commands as values, in a pipe +;; =========================================================================== + +;; jobs in a pipe: number, current (+, - or nothing), state, command, id. +(: (-> Shell (Vec string) Values Unit)) +(defbjo (jobs-values sh args out) + (unless (vec-empty? args) + (command-error "jobs: takes no arguments in a pipe")) + (def entries (record-ref sh jobs)) + (let go ((i 0)) + (when (< i (vec-length entries)) + (def e (vec-ref entries i)) + (emit! out (record-of [(Tuple "number" (JsonInt (cast long (record-ref e number)))) + (Tuple "current" (JsonStr (string-trim (job-mark sh e)))) + (Tuple "state" (JsonStr (job-state-text e))) + (Tuple "command" (JsonStr (record-ref e text))) + (Tuple "id" (JsonInt (cast long (job-id (record-ref e job)))))])) + (go (+ i 1)))) + unit) + +;; history in a pipe: number and line, oldest first. +(: (-> Shell (Vec string) Values Unit)) +(defbjo (history-values sh args out) + (unless (vec-empty? args) + (command-error "history: takes no arguments in a pipe")) + (def entries (match (record-ref sh editor) ((Some ed) (line-history ed)) (None []))) + (let go ((i 0)) + (when (< i (vec-length entries)) + (emit! out (record-of [(Tuple "number" (JsonInt (cast long (+ i 1)))) + (Tuple "line" (JsonStr (vec-ref entries i)))])) + (go (+ i 1)))) + unit) + +;; The shell commands that are value sources in a pipe: jobs and history. +(: (-> Shell string (Option ValueCommand))) +(defun (shell-value-command sh name) + (cond + ((= name "jobs") + (Some (ValueCommand (long "jobs") (short "jobs") (usage "jobs") (help "the jobs, as records") + (body (OnNothing (bjoroutine (args out) (jobs-values sh args out))))))) + ((= name "history") + (Some (ValueCommand (long "history") (short "history") (usage "history") (help "the lines written before, as records") + (body (OnNothing (bjoroutine (args out) (history-values sh args out))))))) + (else None))) + (: (-> string bool)) (defun (builtin? name) (any? (fun (b) (= (record-ref b name) name)) (builtins))) diff --git a/src/commands.bjo b/src/commands.bjo index 6767df4..b048eee 100644 --- a/src/commands.bjo +++ b/src/commands.bjo @@ -179,7 +179,7 @@ (def path (vec-ref args 0)) (def text (match (file-read-text path) ((Ok t) t) - ((Err e) (command-error (str "open: " path ": " (written e)))))) + ((Err e) (command-error (str "open: " (fs-error-message e)))))) (cond ((string-ends-with? path ".json") (emit-json "open" text out)) ((string-ends-with? path ".csv") (emit-csv "open" text out)) @@ -406,7 +406,7 @@ (None acc))) [] ds))) - ((Err e) (command-error (str "procs: " (written e)))))) + ((Err e) (command-error (str "procs: " (fs-error-message e)))))) (let go ((i 0)) (when (< i (vec-length pids)) (def pid (vec-ref pids i)) diff --git a/src/exec.bjo b/src/exec.bjo index 25f4218..6b999f5 100644 --- a/src/exec.bjo +++ b/src/exec.bjo @@ -124,14 +124,14 @@ (let* ((path (snd (vec-ref rs i))) (problem (match (fst (vec-ref rs i)) ((or IntoFile ErrIntoFile) - (match (file-write-text path "") ((Ok _) None) ((Err e) (Some (written e))))) + (match (file-write-text path "") ((Ok _) None) ((Err e) (Some (fs-error-message e))))) ((or AppendFile ErrAppendFile) - (match (file-append-text path "") ((Ok _) None) ((Err e) (Some (written e))))) - (FromFile (if (file-exists? path) None (Some "no such file"))) + (match (file-append-text path "") ((Ok _) None) ((Err e) (Some (fs-error-message e))))) + (FromFile (if (file-exists? path) None (Some (str "not found: " path)))) (_ None)))) (match problem (None (go (+ i 1))) - ((Some message) (shell-error (str path ": " message)) 1)))))) + ((Some message) (shell-error message) 1)))))) (: (-> Shell (Vec Command) bool int)) (defun (run-pipeline sh pipe background?) @@ -147,10 +147,12 @@ (def text (string-join (vec-map expanded->string expanded) " | ")) (def first (vec-ref expanded 0)) (def name (if (vec-empty? (record-ref first argv)) "" (vec-ref (record-ref first argv) 0))) + ;; jobs and history are values in a pipe. (def builtin-in-pipe (find (fun (e) (and (not (vec-empty? (record-ref e argv))) - (builtin? (vec-ref (record-ref e argv) 0)))) - expanded)) + (builtin? (vec-ref (record-ref e argv) 0)) + (not (some? (shell-value-command sh (vec-ref (record-ref e argv) 0)))))) + expanded)) (cond ((and (= (vec-length expanded) 1) (vec-empty? (record-ref first argv))) (run-bare sh first)) @@ -168,7 +170,7 @@ (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) (None - (if (any? (fun (e) (some? (value-command-of (vec-ref (record-ref e argv) 0)))) expanded) + (if (any? (fun (e) (some? (stage-command sh (vec-ref (record-ref e argv) 0)))) expanded) (run-mixed sh expanded text background?) (run-form sh expanded text background?))))))) @@ -176,43 +178,108 @@ (defun (value-command-of name) (value-command name (fun (n) (some? (find-program n))))) -;; A part of a pipe: a program, or value commands next to each other. -(type (: Part (Union (: PartProgram Form) - (: PartValues (Vec ValueStage))))) +;; The value command a stage of a pipe runs, if any. +(: (-> Shell string (Option ValueCommand))) +(defun (stage-command sh name) + (match (shell-value-command sh name) + ((Some c) (Some c)) + (None (value-command-of name)))) -(: (-> (Vec Expanded) (Result string (Vec Part)))) -(defun (parts-of expanded) - (let go ((i 0) (parts []) (stages [])) - (def close (fun (ps) (if (vec-empty? stages) ps (vec-add ps (PartValues stages))))) +;; Value commands next to each other, with the file the first reads (<) +;; and the file the last writes (> or >>, with append?). +(type (: Segment (Record (: stages (Vec ValueStage)) + (: from (Option string)) + (: into (Option (Tuple string bool)))))) + +;; A part of a pipe: a program, or a segment. +(type (: Part (Union (: PartProgram Form) + (: PartValues Segment)))) + +;; The redirections of a value command, added to `seg`. +;; - < only on the first command of a segment. +;; - > and >> only on the last command of a pipe, or before a program: +;; a value command after one is an error. +(: (-> string Expanded Segment (Result string Segment))) +(defun (with-redirects name e seg) + (let go ((i 0) (seg seg)) + (def rs (record-ref e redirects)) + (if (= i (vec-length rs)) + (Ok seg) + (let ((path (snd (vec-ref rs i)))) + (match (fst (vec-ref rs i)) + (FromFile + (if (= (vec-length (record-ref seg stages)) 1) + (go (+ i 1) (record-set seg (from (Some path)))) + (Err (str name ": < on a value command after another one")))) + (IntoFile (go (+ i 1) (record-set seg (into (Some (Tuple path #f)))))) + (AppendFile (go (+ i 1) (record-set seg (into (Some (Tuple path #t)))))) + (_ (Err (str name ": 2>, 2>&1 and >&2 of value commands are not supported yet")))))))) + +;; Whether the segment's output goes to a file: nothing can follow it. +(: (-> Segment bool)) +(defun (closed? seg) + (match (record-ref seg into) + ((Some _) #t) + (None #f))) + +(: (-> (Vec ValueStage) Segment)) +(defun (segment-of stages) + (Segment (stages stages) (from None) (into None))) + +(: (-> Shell (Vec Expanded) (Result string (Vec Part)))) +(defun (parts-of sh expanded) + (parts-from sh expanded 0 [] None)) + +(: (-> Shell (Vec Expanded) int (Vec Part) (Option Segment) (Result string (Vec Part)))) +(defun (parts-from sh expanded i parts current) + (def close (fun (ps) (match current ((Some seg) (vec-add ps (PartValues seg))) (None ps)))) (if (= i (vec-length expanded)) (Ok (close parts)) (let* ((e (vec-ref expanded i)) (argv (record-ref e argv)) (name (vec-ref argv 0))) - (match (value-command-of name) + (match (stage-command sh name) ((Some c) - (if (and (vec-empty? (record-ref e assigns)) (vec-empty? (record-ref e redirects))) - (go (+ i 1) parts (vec-add stages (ValueStage (command c) (args (vec-drop argv 1))))) - (Err (str name ": assignments and redirections of value commands are not supported yet")))) + (def stage (ValueStage (command c) (args (vec-drop argv 1)))) + (def seg (match current + ((Some seg) #:when (not (closed? seg)) + (record-set seg (stages (vec-add (record-ref seg stages) stage)))) + (_ (segment-of [stage])))) + (cond + ((match current ((Some old) (closed? old)) (None #f)) + (Err (str name ": the value command before it writes to a file, so nothing can be piped into it"))) + ((not (vec-empty? (record-ref e assigns))) + (Err (str name ": assignments of value commands are not supported"))) + (else + (match (with-redirects name e seg) + ((Ok seg) (parts-from sh expanded (+ i 1) parts (Some seg))) + ((Err message) (Err message)))))) (None (match (stage-form e) - ((Ok f) (go (+ i 1) (vec-add (close parts) (PartProgram f)) [])) - ((Err message) (Err message))))))))) + ((Ok f) (parts-from sh expanded (+ i 1) (vec-add (close parts) (PartProgram f)) None)) + ((Err message) (Err message)))))))) (: (-> Part bool Form)) (defun (part-form part last?) (match part ((PartProgram f) f) - ((PartValues stages) - (FFilter (bjoroutine (in out) (run-segment stages in out last?)))))) + ((PartValues seg) + (def stages (record-ref seg stages)) + (def show? (and last? (not (closed? seg)))) + (def base (FFilter (bjoroutine (in out) (run-segment stages in out show?)))) + (def read (match (record-ref seg from) ((Some path) (FFrom path base)) (None base))) + (match (record-ref seg into) + ((Some (Tuple path #t)) (FAppend path read)) + ((Some (Tuple path #f)) (FInto path read)) + (None read))))) (: (-> Shell (Vec Expanded) string bool int)) (defun (run-mixed sh expanded text background?) - (match (parts-of expanded) + (match (parts-of sh expanded) ((Err message) (shell-error message) 2) ((Ok parts) (match parts - ([(PartValues stages)] (run-values sh stages background?)) + ([(PartValues seg)] (run-values sh seg background?)) (_ (def n (vec-length parts)) (def forms (vec-map (fun (i) (part-form (vec-ref parts i) (= i (- n 1)))) @@ -227,24 +294,50 @@ ((:is Bjolang.Runtime.Cancelled) (println "") 130) (_ (shell-error (.-Message e)) 1))) -;; Value commands only: in the shell, with no input, shown on stdout. -;; Status 130 after Ctrl-C, 1 when a command raises. -(: (-> Shell (Vec ValueStage) bool int)) -(defun (run-values sh stages background?) +;; Value commands only, in the shell. +;; - Input: the file of <, else nothing. +;; - Output: the file of > or >>, as lines, else shown on stdout. +;; - Status 130 after Ctrl-C, 1 when a command raises or a file does not +;; open. +(: (-> Shell Segment bool int)) +(defun (run-values sh seg background?) (cond (background? (shell-error "& is not supported for a pipe of only value commands") 2) (else - (def out (parameter-ref current-output-port)) - (flush-port out) - (match (try (with-signal-cancel [Interrupt] - (sync/blocking (promise-join (bjo (run-segment stages (open-input-string "") out #t))))) - #:catch (System.Exception)) - ((Ok (Ok (Ok _))) 0) - ((Ok (Ok (Err e))) (segment-failed e)) - ((Ok (Err _)) (println "") 130) - ((Err e) (segment-failed e)))))) + (match (record-ref seg from) + ((Some path) + (match (open-input-file path) + ((Ok in) (run-values-from sh seg in)) + ((Err e) (shell-error (fs-error-message e)) 1))) + (None (run-values-from sh seg (open-input-string ""))))))) + +(: (-> Shell Segment InputPort int)) +(defun (run-values-from sh seg in) + (def status + (match (record-ref seg into) + ((Some (Tuple path append?)) + (match (open-output-file path #:mode (if append? Append Truncate)) + ((Ok out) + (def status (run-values-into seg in out #f)) + (close-output-port out) + status) + ((Err e) (shell-error (fs-error-message e)) 1))) + (None (run-values-into seg in (parameter-ref current-output-port) #t)))) + (close-input-port in) + status) + +(: (-> Segment InputPort OutputPort bool int)) +(defun (run-values-into seg in out show?) + (flush-port (parameter-ref current-output-port)) + (match (try (with-signal-cancel [Interrupt] + (sync/blocking (promise-join (bjo (run-segment (record-ref seg stages) in out show?))))) + #:catch (System.Exception)) + ((Ok (Ok (Ok _))) 0) + ((Ok (Ok (Err e))) (segment-failed e)) + ((Ok (Err _)) (println "") 130) + ((Err e) (segment-failed e)))) (: (-> Shell (Vec Expanded) string bool int)) (defun (run-form sh expanded text background?) diff --git a/src/main.bjo b/src/main.bjo index 01f5a85..7982817 100644 --- a/src/main.bjo +++ b/src/main.bjo @@ -77,7 +77,7 @@ (defun (run-file args) (match (file-read-text (vec-ref args 0)) ((Ok text) (run-script (make-shell None None args) text)) - ((Err e) (shell-error (str (vec-ref args 0) ": " (written e))) 127))) + ((Err e) (shell-error (fs-error-message e)) 127))) (defun (main args) (cond diff --git a/src/shell.bjo b/src/shell.bjo index 0d5472f..02b108e 100644 --- a/src/shell.bjo +++ b/src/shell.bjo @@ -24,7 +24,7 @@ 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? - job-text-line foreground! report-jobs state->status error-text) + job-text-line job-mark job-state-text foreground! report-jobs state->status error-text) (type (: JobEntry (Record (: number int) (: job Job) @@ -207,28 +207,36 @@ ((= code 143) "Terminated") (else (str "Exit " (int->string code))))) +;; "+" for the current job, "-" for the previous one, else " ". +(: (-> Shell JobEntry string)) +(defun (job-mark sh e) + (def number (record-ref e number)) + (match (job-current sh 0) + ((Some c) (if (= (record-ref c number) number) "+" + (match (job-current sh 1) + ((Some p) (if (= (record-ref p number) number) "-" " ")) + (None " ")))) + (None " "))) + +;; The state of a job as `jobs` writes it: Running, Stopped, Done, ... +(: (-> JobEntry string)) +(defun (job-state-text e) + (match (record-ref e state) + (JobRunning "Running") + ((JobStopped 21) "Stopped (tty input)") + ((JobStopped 22) "Stopped (tty output)") + ((JobStopped _) "Stopped") + ((JobDone _) + (match (job-result (record-ref e job)) + ((Ok _) "Done") + ((Err (Exited _ code _)) (exit-text code)) + ((Err _) "Failed"))))) + ;; A line of `jobs`: [n]+ State text. (: (-> Shell JobEntry string)) (defun (job-text-line sh e) - (def number (record-ref e number)) - (def mark (match (job-current sh 0) - ((Some c) (if (= (record-ref c number) number) "+" - (match (job-current sh 1) - ((Some p) (if (= (record-ref p number) number) "-" " ")) - (None " ")))) - (None " "))) - (def state-text - (match (record-ref e state) - (JobRunning "Running") - ((JobStopped 21) "Stopped (tty input)") - ((JobStopped 22) "Stopped (tty output)") - ((JobStopped _) "Stopped") - ((JobDone _) - (match (job-result (record-ref e job)) - ((Ok _) "Done") - ((Err (Exited _ code _)) (exit-text code)) - ((Err _) "Failed"))))) - (str "[" (int->string number) "]" mark " " (string-pad-right state-text 22) (record-ref e text))) + (str "[" (int->string (record-ref e number)) "]" (job-mark sh e) " " + (string-pad-right (job-state-text e) 22) (record-ref e text))) ;; Waits for a job in the foreground. A job that stops goes in the table ;; and gets a line; a job that ends leaves it. Returns its status. diff --git a/tests/interactive.bjo b/tests/interactive.bjo index aa7b517..028b2f9 100644 --- a/tests/interactive.bjo +++ b/tests/interactive.bjo @@ -48,6 +48,10 @@ "printf 'echo status $?\\r'" "sleep 0.5" "printf 'ech'" "sleep 0.3" "printf '\\032'" "sleep 0.5" "printf 'o alive\\r'" "sleep 0.5" + "printf 'sleep 30 &\\r'" "sleep 1" + "printf 'jobs | g command\\r'" "sleep 1" + "printf 'history | tl 1 | g line\\r'" "sleep 1" + "printf 'kill %%1\\r'" "sleep 0.5" "printf 'printf x | u\\r'" "sleep 1" "printf 'stty tostop; printf y | u; stty -tostop\\r'" "sleep 1" "printf 'exit\\r'" "sleep 1"] @@ -63,6 +67,9 @@ (expect-true "Ctrl-C ends a job, and the prompt starts a new line" (string-contains? out "^C\n")) (expect-true "with status 130" (string-contains? out "status 130")) (expect-true "Ctrl-Z at the prompt does not stop the shell" (string-contains? out "\nalive\n")) + (expect-true "jobs in a pipe" (string-contains? out "jobs | g command\nsleep 30\n")) + (expect-true "history in a pipe, with this line last" + (string-contains? out "history | tl 1 | g line\nhistory | tl 1 | g line\n")) (expect-true "a value command at the end of a job" (string-contains? out "printf x | u\nx\n")) (expect-true "and with tostop set" (string-contains? out "stty -tostop\ny\n")) (expect-true "the history is saved" diff --git a/tests/values.bjo b/tests/values.bjo index 9f44af5..bd16b1c 100644 --- a/tests/values.bjo +++ b/tests/values.bjo @@ -96,8 +96,26 @@ "err: bjosh: first: not a count: x\ncode: 1") (expect "a bad regular expression" (c "l | wh name =~ '('") "err: bjosh: where: not a regular expression: (\ncode: 1") - (expect "a redirection of a value command" (c "l > f") - "err: bjosh: l: assignments and redirections of value commands are not supported yet\ncode: 2") + + ;; Redirections. + (expect "> writes lines" (c "l > out.txt; wc -l < out.txt") "5") + (expect ">> appends" (c "l | g name > out.txt; l | g name >> out.txt; wc -l < out.txt") "10") + (expect "< reads a file" (c "o a.txt | rv > r.txt; so < r.txt") "one\ntwo") + (expect "< into a pipe with a program" (c "so < a.txt | tr a-z A-Z") "ONE\nTWO") + (expect "> after a program" (c "cat a.txt | rv > r.txt; cat r.txt") "two\none") + (expect "< on a file that is not there" (string-starts-with? (c "so < nosuch") "err: bjosh: not found: nosuch: ") #t) + (expect "< after another value command" (c "n | so < a.txt") + "err: bjosh: so: < on a value command after another one\ncode: 2") + (expect "a value command after >" (c "l > f | n") + "err: bjosh: n: the value command before it writes to a file, so nothing can be piped into it\ncode: 2") + (expect "2> of a value command" (c "l 2> e") + "err: bjosh: l: 2>, 2>&1 and >&2 of value commands are not supported yet\ncode: 2") + (expect "an assignment of a value command" (c "X=1 l") + "err: bjosh: l: assignments of value commands are not supported\ncode: 2") + + ;; Shell commands as values, in a pipe. + (expect "jobs in a pipe, without jobs" (c "jobs | n") "0") + (expect "history in a pipe, without an editor" (c "history | n") "0") ;; Names (decision 4). (expect "a long name that is a program runs the program" (c "printf 'a\\na\\n' | uniq -c") " 2 a")