Phase 2, first part: values and value commands

- Values are Json of (text json); a record is JsonFields.
- Value commands: files, procs, open, where, select, get, sort-by,
  first, last, count, reverse, uniq, lines, from-json, to-json,
  from-csv, to-csv, each with a short name.
- Value commands next to each other run as one unit: a (std run)
  filter in a job, or in the shell when a line has no program.
- Records are shown as a table; values go to programs as lines.
- A name is a shell command, a short name, a program on PATH, then a
  long name.
- 2>&1, with >FILE 2>&1.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
This commit is contained in:
Linus Björnstam 2026-12-01 07:05:09 +01:00
parent 3518b7711d
commit 027acc84e6
12 changed files with 1142 additions and 37 deletions

View file

@ -22,8 +22,12 @@ non-trivial functions. No essays.
- `(bjosh shell)`: the state, variables and the job table.
- `(bjosh builtins)`: the shell commands.
- `(bjosh exec)`: lines to `(std run)` forms and jobs.
- `(bjosh values)`: values (`Json`), streams of them, text and tables.
- `(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.
- 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 and the prompt under `script`.

View file

@ -250,11 +250,47 @@ JSON is the format at the edge, not between built-ins.
- Tests: each command with ~-c~, and mixed pipes such as
~files | where size > 1000 | to-json | jq .name~.
*Implemented, the first part (2026-12-01). Where the code differs from
the text above:*
- ~(std run)~ (Bjolang b8c92ff, d808624): a filter can be the first or
last stage of a job. The first reads an empty input; the last writes
~current-output-port~. ~job-control~ now ignores SIGTTOU, so the
write works with ~tostop~ set. ~errors-to-output~ is 2>&1.
- ~Value~ is ~Json~ of ~(text json)~, and a record is a ~JsonFields~, which
keeps the order of its fields. JSON is read with ~#:objects 'fields~.
- Modules: ~values~ (streams, text, tables), ~commands~ (the value
commands and their table), ~pipeline~ (value commands next to each
other, as one unit).
- A stream between value commands is a channel of ~(Option Json)~:
~None~ ends it. A unit of value commands runs in one ~with-cancel~
scope. A command that raises cancels the others.
- Names (decision 4): a shell command, then a short name, then a program
on ~PATH~, then a long name. So ~uniq~ and ~last~ are the programs on a
machine that has them, and ~u~ and ~tl~ the value commands. The test of
decision 4 is in ~tests/values.bjo~.
- ~where~ also takes ~eq ne lt le gt ge~: ~<~ and ~>~ are redirections
unless quoted. A string that reads as a number is a number against a
number.
- ~first~ and ~last~ take 10 values unless given a count. ~first~ reads
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.
- ~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).
** Phase 3: more POSIX, and the rest of the edges
- ~$(...)~: the output of a line as a word. Its text, with the last line
break taken away, as in POSIX.
- ~2>&1~ (the ~(std run)~ change of decision 10).
- ~2>&1~ (the ~(std run)~ change of decision 10). Done in phase 2.
- ~NAME=value command~: the variable for that command only.
- Aliases, and a start-up file (~~/.config/bjosh/rc~) of shell lines.
- Lines above the input with bjoterm (decision 11), for "Done" lines at
@ -276,9 +312,8 @@ JSON is the format at the edge, not between built-ins.
short name. The built-in still wins, and ~command NAME~ runs the
program. The test of decision 4 shows a new collision.
- *A built-in at the end of a job writes the terminal from the
background.* With ~tostop~ set, the shell gets SIGTTOU. ~job-control~
catches SIGTTOU (it does not ignore it), so the write could fail or
repeat. Find out in the ~(std run)~ change.
background.* Solved: ~job-control~ ignores SIGTTOU, so the write goes
through with ~tostop~ set. Tested under ~script~.
- *Start-up time.* A .NET program starts in about 100 ms. AOT should fix
it, if bjoterm's glue and ~(std run)~ work under AOT.
- *Ctrl-C during a built-in that blocks.* Cancelling works only at a

View file

@ -14,6 +14,7 @@
(import (std run))
(import (bjoterm line))
(import (bjosh shell))
(import (bjosh commands))
(export builtin? run-builtin builtin-names find-program)
@ -204,15 +205,31 @@
(cond
((builtin? name) (println (str name " is a shell command")) 0)
(else
(match (value-command name (fun (n) (some? (find-program n))))
((Some c)
(println (str name " is a value command: "
(record-ref c long) ", " (record-ref c short)))
0)
(None
(match (find-program name)
((Some path) (println (str name " is " path)) 0)
(None (shell-error (str "type: " name ": not found")) 1)))))))
(None (shell-error (str "type: " name ": not found")) 1)))))))))
(: (-> Builtin string))
(defun (builtin-help-line b)
(str " " (string-pad-right (record-ref b usage) 28) (record-ref b help)))
(: (-> ValueCommand string))
(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)))
(: (-> Shell (Vec string) int))
(defun (help sh args)
(for-each (fun (b)
(println (str (string-pad-right (record-ref b usage) 28) (record-ref b help))))
(builtins))
(println "Shell commands:")
(for-each (fun (b) (println (builtin-help-line b))) (builtins))
(println "")
(println "Value commands, by long and short name. A long name that is a program runs the program.")
(for-each (fun (c) (println (value-help-line c))) (value-commands))
0)
(: (-> Shell (Vec string) int))

479
src/commands.bjo Normal file
View file

@ -0,0 +1,479 @@
;; 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 commands): the value commands. See decision 4 of plan.org.
;;
;; - Each command has a long name and a short one. The short name always
;; runs the command. The long name runs it only when no program of that
;; name is on PATH: `uniq` is the program, `u` the command.
;; - A command reads bytes (`OnBytes`), values (`OnValues`), or nothing
;; (`OnNothing`), and writes values. The caller connects them: see
;; (bjosh exec).
;; - A command raises with `command-error` when its arguments or its input
;; are wrong. The message starts with its long name.
(import (std prelude))
(import (std datetime))
(import (text json))
(import (text csv))
(import (bjosh values))
(export ValueCommand Body value-command value-commands value-names lines-body)
(import/extern
(regex-match? (: System.Text.RegularExpressions.Regex.IsMatch (-> string string bool)
#:raises (System.ArgumentException))))
;; How a command reads.
(type (: Body (Union (: OnBytes (-bjo-> (Vec string) InputPort Values Unit))
(: OnValues (-bjo-> (Vec string) Values Values Unit))
(: OnNothing (-bjo-> (Vec string) Values Unit)))))
(type (: ValueCommand (Record (: long string)
(: short string)
(: usage string)
(: help string)
(: body Body))))
;; ===========================================================================
;; Arguments
;; ===========================================================================
;; The one count argument, or `default` without one.
(: (-> string (Vec string) int int))
(defun (count-arg name args default)
(cond
((vec-empty? args) default)
((> (vec-length args) 1) (command-error (str name ": one count at most")))
(else
(match (string->int (vec-ref args 0))
((Some n) #:when (>= n 0) n)
(_ (command-error (str name ": not a count: " (vec-ref args 0))))))))
(: (-> string (Vec string) void))
(defun (no-args name args)
(unless (vec-empty? args)
(command-error (str name ": takes no arguments"))))
;; Reads to the end of `in` and throws the values away, so that the stage
;; before it can end.
(: (-> Values Unit))
(defbjo (drain! in)
(let go ()
(match (next! in)
(None unit)
((Some _) (go)))))
;; All the values of `in`.
(: (-> Values (Vec Json)))
(defbjo (collect! in)
(let go ((acc []))
(match (next! in)
(None acc)
((Some v) (go (vec-add acc v))))))
(: (-> (Vec Json) Values Unit))
(defbjo (emit-all! vs out)
(let go ((i 0))
(when (< i (vec-length vs))
(emit! out (vec-ref vs i))
(go (+ i 1))))
unit)
;; ===========================================================================
;; Text and formats
;; ===========================================================================
(: (-> (Vec string) InputPort Values Unit))
(defbjo (lines-body args in out)
(no-args "lines" args)
(let go ()
(match (read-line/opt in)
(None unit)
((Some line) (emit! out (JsonStr line)) (go)))))
;; One document, or one per line. An array is its values.
(: (-> string string Values Unit))
(defbjo (emit-json name text out)
(match (parse-json text #:objects 'fields)
((Ok (JsonArr items)) (emit-all! (iarray->vec items) out))
((Ok v) (emit! out v))
((Err whole)
(def lines (vec-filter (fun (l) (not (string-empty? (string-trim l)))) (string-split text "\n")))
(if (< (vec-length lines) 2)
(command-error (str name ": " whole))
(let go ((i 0))
(when (< i (vec-length lines))
(match (parse-json (vec-ref lines i) #:objects 'fields)
((Ok v) (emit! out v) (go (+ i 1)))
((Err why) (command-error (str name ": line " (int->string (+ i 1)) ": " why)))))))))
unit)
(: (-> (Vec string) InputPort Values Unit))
(defbjo (from-json-body args in out)
(no-args "from-json" args)
(emit-json "from-json" (read-all in) out))
;; Records from CSV: the first row names the fields. A field that reads as
;; a number is a number.
(: (-> string string Values Unit))
(defbjo (emit-csv name text out)
(match (parse-csv text)
((Err e) (command-error (str name ": " (written e))))
((Ok rows)
(unless (vec-empty? rows)
(def names (iarray->vec (vec-ref rows 0)))
(let go ((i 1))
(when (< i (vec-length rows))
(def row (iarray->vec (vec-ref rows i)))
(emit! out (record-of
(vec-map (fun (j)
(Tuple (vec-ref names j)
(if (< j (vec-length row)) (word->value (vec-ref row j)) JsonNull)))
(->vec (range 0 (vec-length names))))))
(go (+ i 1)))))))
unit)
(: (-> (Vec string) InputPort Values Unit))
(defbjo (from-csv-body args in out)
(no-args "from-csv" args)
(emit-csv "from-csv" (read-all in) out))
(: (-> (Vec string) Values Values Unit))
(defbjo (to-json-body args in out)
(no-args "to-json" args)
(let go ()
(match (next! in)
(None unit)
((Some v) (emit! out (JsonStr (json->string v))) (go)))))
(: (-> (Vec string) Values Values Unit))
(defbjo (to-csv-body args in out)
(no-args "to-csv" args)
(def rows (vec-map (fun (v)
(match (record-fields v)
((Some fs) fs)
(None (command-error "to-csv: a value that is not a record"))))
(collect! in)))
(unless (vec-empty? rows)
(def names (columns-of rows))
(emit! out (JsonStr (csv-row->string names)))
(let go ((i 0))
(when (< i (vec-length rows))
(def row (vec-ref rows i))
(emit! out (JsonStr (csv-row->string
(vec-map (fun (name)
(match (find (fun (f) (= (fst f) name)) row)
((Some f) (value-line (snd f)))
(None "")))
names))))
(go (+ i 1)))))
unit)
;; A file by its extension: .json as from-json, .csv as from-csv, else lines.
(: (-> (Vec string) Values Unit))
(defbjo (open-body args out)
(unless (= (vec-length args) 1)
(command-error "open: one file"))
(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))))))
(cond
((string-ends-with? path ".json") (emit-json "open" text out))
((string-ends-with? path ".csv") (emit-csv "open" text out))
(else
(def body (if (string-ends-with? text "\n") (string-take text (- (string-length text) 1)) text))
(def lines (string-split body "\n"))
(unless (string-empty? text)
(emit-all! (vec-map (fun (l) (JsonStr l)) lines) out))))
unit)
;; ===========================================================================
;; Filters
;; ===========================================================================
;; Whether `v` OP `want` holds.
;; - Words for the operators too, since < and > are redirections unless
;; quoted.
;; - =~ and contains compare the text of the values.
(: (-> string Json string Json bool))
(defun (holds? name v op want)
;; A string that reads as a number is a number against a number.
(def x (match (Tuple v want)
((Tuple (JsonStr s) (JsonInt _)) (word->value s))
((Tuple (JsonStr s) (JsonFloat _)) (word->value s))
(_ v)))
(def c (value-compare x want))
(cond
((or (= op "==") (= op "eq")) (= c 0))
((or (= op "!=") (= op "ne")) (not (= c 0)))
((or (= op "<") (= op "lt")) (< c 0))
((or (= op "<=") (= op "le")) (<= c 0))
((or (= op ">") (= op "gt")) (> c 0))
((or (= op ">=") (= op "ge")) (>= c 0))
((= op "=~")
(match (try (regex-match? (value-line v) (value-line want)) #:catch (System.ArgumentException))
((Ok b) b)
((Err e) (command-error (str name ": not a regular expression: " (value-line want))))))
((= op "contains") (string-contains? (value-line v) (value-line want)))
(else (command-error (str name ": no operator " op)))))
(: (-> (Vec string) Values Values Unit))
(defbjo (where-body args in out)
(unless (= (vec-length args) 3)
(command-error "where: FIELD OP VALUE, such as: where size gt 1000"))
(def field (vec-ref args 0))
(def op (vec-ref args 1))
(def want (word->value (vec-ref args 2)))
;; An operator that is wrong is an error before the first value.
(ignore (holds? "where" JsonNull op want))
(let go ()
(match (next! in)
(None unit)
((Some v)
(match (value-field v field)
((Some x) #:when (holds? "where" x op want) (emit! out v))
(_ unit))
(go)))))
(: (-> (Vec string) Values Values Unit))
(defbjo (select-body args in out)
(when (vec-empty? args)
(command-error "select: the fields to keep"))
(let go ()
(match (next! in)
(None unit)
((Some v)
(emit! out (record-of (vec-map (fun (name)
(Tuple name (match (value-field v name) ((Some x) x) (None JsonNull))))
args)))
(go)))))
(: (-> (Vec string) Values Values Unit))
(defbjo (get-body args in out)
(unless (= (vec-length args) 1)
(command-error "get: one field"))
(def name (vec-ref args 0))
(let go ()
(match (next! in)
(None unit)
((Some v)
(match (value-field v name)
((Some x) (emit! out x))
(None unit))
(go)))))
;; sort-by [-r] [FIELD]: by the value itself without a field.
(: (-> (Vec string) Values Values Unit))
(defbjo (sort-by-body args in out)
(def reverse? (vec-contains? args "-r"))
(def names (vec-filter (fun (a) (not (= a "-r"))) args))
(when (> (vec-length names) 1)
(command-error "sort-by: one field at most"))
(def key (fun (v)
(if (vec-empty? names)
v
(match (value-field v (vec-ref names 0)) ((Some x) x) (None JsonNull)))))
(def sorted (vec-sort-by (fun (a b) (value-compare (key a) (key b))) (collect! in)))
(emit-all! (if reverse? (vec-reverse sorted) sorted) out))
(: (-> (Vec string) Values Values Unit))
(defbjo (first-body args in out)
(def n (count-arg "first" args 10))
(let go ((i 0))
(if (< i n)
(match (next! in)
(None unit)
((Some v) (emit! out v) (go (+ i 1))))
(drain! in))))
(: (-> (Vec string) Values Values Unit))
(defbjo (last-body args in out)
(def n (count-arg "last" args 10))
(def all (collect! in))
(emit-all! (vec-drop all (max 0 (- (vec-length all) n))) out))
(: (-> (Vec string) Values Values Unit))
(defbjo (count-body args in out)
(no-args "count" args)
(emit! out (JsonInt (cast long (vec-length (collect! in))))))
(: (-> (Vec string) Values Values Unit))
(defbjo (reverse-body args in out)
(no-args "reverse" args)
(emit-all! (vec-reverse (collect! in)) out))
;; Each value once, where it first comes.
(: (-> (Vec string) Values Values Unit))
(defbjo (uniq-body args in out)
(no-args "uniq" args)
(let go ((seen (map-empty)))
(match (next! in)
(None unit)
((Some v)
(def key (json->string v))
(match (map-try-ref seen key)
((Some _) (go seen))
(None
(emit! out v)
(go (map-set seen key #t))))))))
;; ===========================================================================
;; Sources
;; ===========================================================================
;; The last part of a path.
(: (-> Path string))
(defun (file-name p)
(match (path-filename (path->string/lossy p))
((Some n) n)
(None "")))
;; A time as local "YYYY-MM-DD HH:MM", which sorts as text.
(: (-> long string))
(defun (local-time ms)
(match (unix-milliseconds->instant ms)
(None "")
((Some i)
(def offset (duration->milliseconds (timezone-offset-at (clock-timezone) i)))
(match (unix-milliseconds->instant (+ ms offset))
(None "")
((Some local)
(instant->text local '((year 4) "-" (month 2) "-" (day 2) " " (hours 2) ":" (minutes 2))))))))
(: (-> FsInfo string))
(defun (kind-name info)
(if (record-ref info link?)
"link"
(match (record-ref info kind)
(FsFile "file")
(FsDirectory "dir")
(FsLink "link")
(FsOther "other"))))
;; files [DIR...]: name, type, size, modified, sorted by name.
(: (-> (Vec string) Values Unit))
(defbjo (files-body args out)
(def dirs (if (vec-empty? args) ["."] args))
(let go ((d 0))
(when (< d (vec-length dirs))
(def dir (vec-ref dirs d))
(def names
(match (try (->vec (vec-map (fun (p) (file-name p))
(vec-append (match (directory-files dir) ((Ok v) v) ((Err e) (raise-err (Err e))))
(match (directory-subdirectories dir) ((Ok v) v) ((Err e) (raise-err (Err e)))))))
#:catch (System.Exception))
((Ok v) (vec-sort v))
((Err e) (command-error (str "files: " dir ": " (.-Message e))))))
(let each ((i 0))
(when (< i (vec-length names))
(def name (vec-ref names i))
(match (file-info (path-combine dir name))
((Some info)
(emit! out (record-of [(Tuple "name" (JsonStr name))
(Tuple "type" (JsonStr (kind-name info)))
(Tuple "size" (JsonInt (record-ref info size)))
(Tuple "modified" (JsonStr (local-time (record-ref info modified-ms))))])))
(None unit))
(each (+ i 1))))
(go (+ d 1))))
unit)
;; The fields of /proc/PID/stat after the name, which is in parentheses and
;; can hold spaces and parentheses itself.
(: (-> string (Option (Tuple string (Vec string)))))
(defun (stat-fields text)
(match (string-split-once text " (")
(None None)
((Some (Tuple _ rest))
(def parts (string-split rest ")"))
(if (< (vec-length parts) 2)
None
(let ((name (string-join (vec-take parts (- (vec-length parts) 1)) ")"))
(after (vec-ref parts (- (vec-length parts) 1))))
(Some (Tuple name (vec-filter (fun (f) (not (string-empty? f))) (string-split after " ")))))))))
;; procs: pid, ppid, name, state, mem (resident bytes), command.
(: (-> (Vec string) Values Unit))
(defbjo (procs-body args out)
(no-args "procs" args)
(def pids (match (directory-subdirectories "/proc")
((Ok ds) (vec-sort (vec-fold (fun (p acc)
(match (string->long (file-name p))
((Some n) (vec-add acc n))
(None acc)))
[]
ds)))
((Err e) (command-error (str "procs: " (written e))))))
(let go ((i 0))
(when (< i (vec-length pids))
(def pid (vec-ref pids i))
(def dir (str "/proc/" (long->string pid)))
(match (file-read-text (str dir "/stat"))
((Ok text)
(match (stat-fields (string-trim-right text))
((Some (Tuple name fs)) #:when (>= (vec-length fs) 22)
(def command (match (file-read-text (str dir "/cmdline"))
((Ok c) (string-trim (string-replace c "\u{0}" " ")))
((Err _) "")))
(def pages (match (string->long (vec-ref fs 21)) ((Some n) n) (None 0L)))
(emit! out (record-of [(Tuple "pid" (JsonInt pid))
(Tuple "ppid" (word->value (vec-ref fs 1)))
(Tuple "name" (JsonStr name))
(Tuple "state" (JsonStr (vec-ref fs 0)))
(Tuple "mem" (JsonInt (* pages 4096L)))
(Tuple "command" (JsonStr command))])))
(_ unit)))
;; A process that ended since the list was read.
((Err _) unit))
(go (+ i 1))))
unit)
;; ===========================================================================
;; The table
;; ===========================================================================
(: (-> string string string string Body ValueCommand))
(defun (vc long short usage help body)
(ValueCommand (long long) (short short) (usage usage) (help help) (body body)))
(: (-> (Vec ValueCommand)))
(defun (value-commands)
[(vc "files" "l" "files [DIR...]" "the files of directories, as records: name, type, size, modified" (OnNothing files-body))
(vc "procs" "p" "procs" "the processes, from /proc: pid, ppid, name, state, mem, command" (OnNothing procs-body))
(vc "open" "o" "open FILE" "a file as values: .json as from-json, .csv as from-csv, else lines" (OnNothing open-body))
(vc "where" "wh" "where FIELD OP VALUE" "the values that match: OP is == != < <= > >= (or eq ne lt le gt ge), =~ or contains; FIELD it is the value itself" (OnValues where-body))
(vc "select" "se" "select FIELD..." "records with only the fields named" (OnValues select-body))
(vc "get" "g" "get FIELD" "one field of each record" (OnValues get-body))
(vc "sort-by" "so" "sort-by [-r] [FIELD]" "sorted by a field, or by the value; -r reverses" (OnValues sort-by-body))
(vc "first" "hd" "first [N]" "the first N values, 10 unless given" (OnValues first-body))
(vc "last" "tl" "last [N]" "the last N values, 10 unless given" (OnValues last-body))
(vc "count" "n" "count" "the number of values" (OnValues count-body))
(vc "reverse" "rv" "reverse" "the values in reverse order" (OnValues reverse-body))
(vc "uniq" "u" "uniq" "each value once, where it first comes" (OnValues uniq-body))
(vc "lines" "li" "lines" "text to one string per line" (OnBytes lines-body))
(vc "from-json" "fj" "from-json" "JSON text to values: one document, an array as its values, or one per line" (OnBytes from-json-body))
(vc "to-json" "tj" "to-json" "each value as a line of JSON" (OnValues to-json-body))
(vc "from-csv" "fcs" "from-csv" "CSV text to records; the first row names the fields" (OnBytes from-csv-body))
(vc "to-csv" "tcs" "to-csv" "records to CSV text, with a row of names first" (OnValues to-csv-body))])
;; The short and long names, for completion.
(: (-> (Vec string)))
(defun (value-names)
(vec-fold (fun (c acc) (vec-add (vec-add acc (record-ref c short)) (record-ref c long)))
[]
(value-commands)))
;; The command with this short name, or with this long name when
;; `program?` says no program has it.
(: (-> string (-> string bool) (Option ValueCommand)))
(defun (value-command name program?)
(def all (value-commands))
(match (find (fun (c) (= (record-ref c short) name)) all)
((Some c) (Some c))
(None
(match (find (fun (c) (= (record-ref c long) name)) all)
((Some c) #:when (not (program? name)) (Some c))
(_ None)))))

View file

@ -15,6 +15,7 @@
(import (bjoterm line))
(import (bjosh syntax))
(import (bjosh builtins))
(import (bjosh commands))
(export input-done? complete word-start command-position? quote-name file-candidates)
@ -93,7 +94,7 @@
(go (+ i 1) (vec-append all (path-names (vec-ref dirs i)))))))
(vec-map (fun (n) (str (quote-name n) " "))
(sorted-distinct (vec-filter (fun (n) (string-starts-with? n prefix))
(vec-append builtin-names programs)))))
(vec-append (vec-append builtin-names (value-names)) programs)))))
;; `names` sorted, each once.
(: (-> (Vec string) (Vec string)))

View file

@ -17,6 +17,11 @@
;; not supported. Without job control, the status of a pipe is that of
;; its last command.
;; - & runs one pipe in the background, and needs job control.
;; - Value commands next to each other in a pipe are one (std run) filter
;; (see (bjosh pipeline)). A pipe with programs is one form, as above. A
;; pipe of only value commands runs in the shell, and Ctrl-C stops it.
;; - A name is, in this order: a shell command, the short name of a value
;; command, a program on PATH, the long name of a value command.
(import (std prelude))
(import (std run))
@ -24,6 +29,9 @@
(import (bjosh expand))
(import (bjosh shell))
(import (bjosh builtins))
(import (bjosh commands))
(import (bjosh pipeline))
(import (std os))
(export run-text)
@ -88,7 +96,14 @@
(AppendFile (go (+ i 1) (FAppend path form)))
(ErrIntoFile (go (+ i 1) (FErrInto path form)))
(ErrAppendFile (go (+ i 1) (FErrAppend path form)))
(_ (Err "2>&1 and >&2 are not supported yet")))))))
;; Applies to what stdout is at this point. A later > or >> would
;; take stderr along, which POSIX does not.
(ErrToOut
(if (any? (fun (r) (match (fst r) ((or IntoFile AppendFile) #t) (_ #f)))
(vec-drop rs (+ i 1)))
(Err "2>&1 before > or >> is not supported yet: write >FILE 2>&1")
(go (+ i 1) (FErrToOut form))))
(OutToErr (Err ">&2 is not supported yet")))))))
;; The status for a form that did not start, after its message.
(: (-> RunError int))
@ -96,7 +111,7 @@
(match e
((NotFound name) (shell-error (str name ": command not found")) 127)
((CannotStart name _) (shell-error (run-error-message e)) 126)
(_ (shell-error (run-error-message e)) 1)))
(_ (shell-error (error-text e)) 1)))
;; A command of only assignments and redirections.
(: (-> Shell Expanded int))
@ -152,7 +167,84 @@
(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)
(None (run-form sh expanded text background?))))))
(None
(if (any? (fun (e) (some? (value-command-of (vec-ref (record-ref e argv) 0)))) expanded)
(run-mixed sh expanded text background?)
(run-form sh expanded text background?)))))))
(: (-> string (Option ValueCommand)))
(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)))))
(: (-> (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)))))
(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)
((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"))))
(None
(match (stage-form e)
((Ok f) (go (+ i 1) (vec-add (close parts) (PartProgram f)) []))
((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?))))))
(: (-> Shell (Vec Expanded) string bool int))
(defun (run-mixed sh expanded text background?)
(match (parts-of expanded)
((Err message) (shell-error message) 2)
((Ok parts)
(match parts
([(PartValues stages)] (run-values sh stages background?))
(_
(def n (vec-length parts))
(def forms (vec-map (fun (i) (part-form (vec-ref parts i) (= i (- n 1))))
(->vec (range 0 n))))
(start-form sh (FPipe (->list forms)) text background?))))))
;; The status of a pipe of value commands that raised: 130 when Ctrl-C
;; cancelled it, else 1 after the message.
(: (-> Exception int))
(defun (segment-failed e)
(match e
((: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?)
(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))))))
(: (-> Shell (Vec Expanded) string bool int))
(defun (run-form sh expanded text background?)
@ -161,7 +253,12 @@
(match (stage-form (vec-ref expanded i))
((Ok f) (go (+ i 1) (vec-add forms f)))
((Err message) (shell-error message) 2))
(let ((form (if (= (vec-length forms) 1) (vec-ref forms 0) (FPipe (->list forms)))))
(start-form sh (if (= (vec-length forms) 1) (vec-ref forms 0) (FPipe (->list forms)))
text background?))))
;; Starts `form` as a job, or with `run/interactive` without job control.
(: (-> Shell Form string bool int))
(defun (start-form sh form text background?)
;; The program writes to the same terminal or file.
(flush-port (parameter-ref current-output-port))
(match (record-ref sh jc)
@ -179,7 +276,7 @@
(begin (shell-error "& needs an interactive shell with job control") 2)
(match (run/interactive form)
((Ok code) code)
((Err e) (start-failed e))))))))))
((Err e) (start-failed e)))))))
(: (-> Shell AndOr bool int))
(defun (run-and-or sh a background?)

112
src/pipeline.bjo Normal file
View file

@ -0,0 +1,112 @@
;; 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 pipeline): runs value commands that are next to each other in a
;; pipe, as one unit. See decision 5 of plan.org.
;;
;; - Input: bytes on a port, from a program before them, or an empty port.
;; The first command reads the bytes when it reads bytes. A command that
;; reads values gets one string per line. One that reads nothing closes
;; the port.
;; - Between two commands: a channel of values. A command that reads bytes
;; after one that writes values gets their lines, all at once.
;; - Output: `show?` shows the values for a terminal (`show-values`), else
;; each is written as a line for a program (`write-values`).
;; - Each command runs in a fiber of one scope. When one raises, the scope
;; cancels the others and `run-segment` raises the failure.
(import (std prelude))
(import (bjosh values))
(import (bjosh commands))
(export ValueStage run-segment)
;; One value command and its arguments.
(type (: ValueStage (Record (: command ValueCommand)
(: args (Vec string)))))
;; Where a stage reads from.
(type (: Feed (Union (: FeedBytes InputPort)
(: FeedValues Values))))
(: (-> Values string))
(defbjo (values-text in)
(let go ((b (stringbuilder-empty)))
(match (next! in)
(None (stringbuilder->string b))
((Some v)
(stringbuilder-add-string! b (value-line v))
(stringbuilder-add-string! b "\n")
(go b)))))
;; Runs `f` and ends `out` after it.
(: (-> (-bjo-> (Vec string) Values Values Unit) (Vec string) Values Values Unit))
(defbjo (on-values f args in out)
(f args in out)
(end! out))
(: (-> (-bjo-> (Vec string) InputPort Values Unit) (Vec string) Feed Values Unit))
(defbjo (on-bytes f args feed out)
(def port (match feed
((FeedBytes p) p)
((FeedValues vs) (open-input-string (values-text vs)))))
(f args port out)
(end! out))
(: (-> (-bjo-> (Vec string) Values Unit) (Vec string) Values Unit))
(defbjo (on-nothing f args out)
(f args out)
(end! out))
(: (-> Values Unit))
(defbjo (discard in)
(let go ()
(match (next! in)
(None unit)
((Some _) (go)))))
;; Lines of bytes as strings, for a command that reads values first.
(: (-> InputPort Values Unit))
(defbjo (bytes->values port out)
(lines-body [] port out)
(end! out))
;; Starts `stage` in the current scope, reading `feed`. Returns its output.
(: (-> ValueStage Feed Values))
(defun (start-stage stage feed)
(def out (make-values))
(def args (record-ref stage args))
(match (record-ref (record-ref stage command) body)
((OnBytes f) (spawn (on-bytes f args feed out)))
((OnValues f)
(def in (match feed
((FeedValues vs) vs)
((FeedBytes p)
(def lines (make-values))
(spawn (bytes->values p lines))
lines)))
(spawn (on-values f args in out)))
((OnNothing f)
(match feed
((FeedBytes p) (close-input-port p))
((FeedValues vs) (spawn (discard vs))))
(spawn (on-nothing f args out))))
out)
;; Runs `stages` from `in` to `out`. Returns when all have ended, and raises
;; the first failure.
(: (-> (Vec ValueStage) InputPort OutputPort bool Unit))
(defbjo (run-segment stages in out show?)
(with-cancel (cancel)
(def last
(let go ((i 0) (feed (FeedBytes in)))
(def vs (start-stage (vec-ref stages i) feed))
(if (= (+ i 1) (vec-length stages))
vs
(go (+ i 1) (FeedValues vs)))))
(if show?
(spawn (show-values last out))
(spawn (write-values last out)))
unit)
unit)

View file

@ -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)
job-text-line foreground! report-jobs state->status error-text)
(type (: JobEntry (Record (: number int)
(: job Job)
@ -252,9 +252,17 @@
(when (= status 130) (println ""))
status)
((Err e)
(shell-error (run-error-message e))
(shell-error (error-text e))
1)))
;; The message of a run error. A filter's failure is a value command's, and
;; its message names the command.
(: (-> RunError string))
(defun (error-text e)
(match e
((FilterFailed x) (.-Message x))
(_ (run-error-message e))))
;; Writes a line for each job whose state changed since it was last seen,
;; and takes the jobs that are done out of the table.
(: (-> Shell void))

232
src/values.bjo Normal file
View file

@ -0,0 +1,232 @@
;; 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 values): the values that value commands pass, and how they become
;; text. See decisions 3 and 5 of plan.org.
;;
;; - A value is a `Json` of (text json). A record is a `JsonFields`: its
;; fields in order. JSON is read with `#:objects 'fields`, so a `JsonObj`
;; only comes from code that makes one.
;; - A stream of values is a channel of `(Option Json)`. `None` is its end:
;; a channel has no close.
(import (std prelude))
(import (std fmt))
(import (text json))
(export
Values make-values next! emit! end!
value-line value-cell word->value value-field value-compare
record-of record-fields record?
columns-of command-error write-values show-values)
(import/class
(InvalidOperationException (: System.InvalidOperationException (-> string InvalidOperationException) #:no-raise)))
(type (: Values (Chan (Option Json))))
(: (-> Values))
(defun (make-values) (make-chan))
;; The next value, or None at the end of the stream.
(: (-> Values (Option Json)))
(defbjo (next! in)
(chan-get in))
(: (-> Values Json Unit))
(defbjo (emit! out v)
(chan-put out (Some v))
unit)
;; Ends the stream.
(: (-> Values Unit))
(defbjo (end! out)
(chan-put out None)
unit)
;; Raises the error of a value command. The message starts with the
;; command's name.
(: (-> string %a))
(defun (command-error message)
(raise (cast Exception (InvalidOperationException. message))))
;; ===========================================================================
;; Records
;; ===========================================================================
(: (-> (Vec (Tuple string Json)) Json))
(defun (record-of fields)
(JsonFields (vec->iarray fields)))
;; The fields of a record, in order. None for a value that is not one.
(: (-> Json (Option (Vec (Tuple string Json)))))
(defun (record-fields v)
(match v
((JsonFields fs) (Some (iarray->vec fs)))
((JsonObj m) (Some (map->vec m)))
(_ None)))
(: (-> Json bool))
(defun (record? v)
(match (record-fields v)
((Some _) #t)
(None #f)))
;; The field `name` of a record. `it` is the value itself.
(: (-> Json string (Option Json)))
(defun (value-field v name)
(if (= name "it")
(Some v)
(json-object-ref v name)))
;; ===========================================================================
;; Text
;; ===========================================================================
;; A value as one line of text, for a program: a string as it is, null as
;; nothing, anything else as compact JSON.
(: (-> Json string))
(defun (value-line v)
(match v
((JsonStr s) s)
(JsonNull "")
(_ (json->string v))))
;; A value in a cell of a table: as `value-line`.
(: (-> Json string))
(defun (value-cell v)
(value-line v))
;; A word of a command as a value: a number when it reads as one, else a
;; string.
(: (-> string Json))
(defun (word->value s)
(match (parse-json s)
((Ok (JsonInt n)) (JsonInt n))
((Ok (JsonFloat x)) (JsonFloat x))
(_ (JsonStr s))))
;; The order of the kinds, for values of different kinds.
(: (-> Json int))
(defun (kind-rank v)
(match v
(JsonNull 0)
((JsonBool _) 1)
((JsonInt _) 2)
((JsonFloat _) 2)
((JsonStr _) 3)
((JsonArr _) 4)
(_ 5)))
(: (-> Json double))
(defun (number-of v)
(match v
((JsonInt n) (cast double n))
((JsonFloat x) x)
(_ 0.0)))
;; Negative, zero or positive, as for `vec-sort-by`.
;; - Numbers by value, an integer and a float too.
;; - Strings by their characters, bools false first.
;; - Values of different kinds by kind: null, bool, number, string, list,
;; record.
;; - Lists and records by their JSON text.
(: (-> Json Json int))
(defun (value-compare a b)
(def ra (kind-rank a))
(def rb (kind-rank b))
(cond
((not (= ra rb)) (compare ra rb))
(else
(match (Tuple a b)
((Tuple (JsonInt x) (JsonInt y)) (compare x y))
((Tuple (JsonStr x) (JsonStr y)) (compare x y))
((Tuple (JsonBool x) (JsonBool y)) (compare (if x 1 0) (if y 1 0)))
((Tuple JsonNull JsonNull) 0)
(_ (if (= ra 2)
(compare (number-of a) (number-of b))
(compare (json->string a) (json->string b))))))))
;; ===========================================================================
;; Writing and showing
;; ===========================================================================
;; Writes each value as a line, for a program: see `value-line`.
(: (-> Values OutputPort Unit))
(defbjo (write-values in out)
(let go ()
(match (next! in)
(None unit)
((Some v)
(write-string out (str (value-line v) "\n"))
(go)))))
;; The columns of some records: each name once, in the order they come.
(: (-> (Vec (Vec (Tuple string Json))) (Vec string)))
(defun (columns-of rows)
(vec-fold (fun (row names)
(vec-fold (fun (field acc)
(if (vec-contains? acc (fst field)) acc (vec-add acc (fst field))))
names
row))
[]
rows))
(: (-> Json bool))
(defun (number? v)
(match v ((JsonInt _) #t) ((JsonFloat _) #t) (_ #f)))
;; A table of records: a column for each name, right-aligned when every
;; value in it is a number.
(: (-> (Vec (Vec (Tuple string Json))) string))
(defun (table-text rows)
(def names (columns-of rows))
(def cell (fun (row name)
(match (find (fun (f) (= (fst f) name)) row)
((Some f) (snd f))
(None JsonNull))))
(def aligns
(vec-map (fun (name)
(if (all? (fun (row) (match (cell row name)
(JsonNull #t)
(v (number? v))))
rows)
AlignRight
AlignLeft))
names))
(def body (vec-map (fun (row) (vec-map (fun (name) (BStr (value-cell (cell row name)))) names)) rows))
(render->string (tabular/rows body
#:titles (vec-map (fun (name) (BStr name)) names)
#:align aligns
#:style StyleSimple)))
;; Writes the table of `rows`, or nothing when there are none.
(: (-> OutputPort (Vec (Vec (Tuple string Json))) void))
(defun (write-table out rows)
(unless (vec-empty? rows)
(def text (table-text rows))
(write-string out text)
(unless (string-ends-with? text "\n")
(write-string out "\n"))))
;; Shows values on a terminal.
;; - Records come as a table, once the last of them in a row has come: a
;; table needs all its rows for the widths.
;; - Every other value is a line, as `value-line` writes it, at once.
(: (-> Values OutputPort Unit))
(defbjo (show-values in out)
(let go ((rows []))
(match (next! in)
(None
(write-table out rows)
(flush-port out)
unit)
((Some v)
(match (record-fields v)
((Some fields) (go (vec-add rows fields)))
(None
(write-table out rows)
(write-string out (str (value-line v) "\n"))
(flush-port out)
(go [])))))))

View file

@ -48,6 +48,8 @@
"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 'printf x | u\\r'" "sleep 1"
"printf 'stty tostop; printf y | u; stty -tostop\\r'" "sleep 1"
"printf 'exit\\r'" "sleep 1"]
"; "))
(def command (str "(" keys ") | XDG_STATE_HOME=" state " script -qec 'dotnet src/main.exe' /dev/null"))
@ -61,6 +63,8 @@
(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 "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"
(match (file-read-text (path-combine state "bjosh/history"))
((Ok text) (string-contains? text "kill %1"))

View file

@ -66,8 +66,12 @@
(expect "> >> <" (c (str "echo x >" file "; echo y >>" file "; cat <" file)) "x\ny")
(expect "2>" (c (str "ls /no/such/dir 2>" file "; echo $?; grep -c . " file)) "2\n1")
(expect "> alone makes an empty file" (c (str ">" file "; wc -c <" file)) "0")
(expect "2>&1 is not supported yet" (c "ls 2>&1")
"err: bjosh: 2>&1 and >&2 are not supported yet\ncode: 2")
(expect "2>&1 into a pipe" (c "ls /no/such/dir 2>&1 | grep -c such") "1")
(expect ">FILE 2>&1" (c (str "ls /no/such/dir >" file " 2>&1; grep -c such " file)) "1")
(expect "2>&1 before >" (c (str "ls 2>&1 >" file))
"err: bjosh: 2>&1 before > or >> is not supported yet: write >FILE 2>&1\ncode: 2")
(expect ">&2 is not supported yet" (c "echo x >&2")
"err: bjosh: >&2 is not supported yet\ncode: 2")
;; Shell commands.
(expect "cd and pwd" (c "cd /tmp; pwd") "/tmp")

112
tests/values.bjo Normal file
View file

@ -0,0 +1,112 @@
;; 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/.
;; Value commands with bjosh -c: each command, mixed pipes, errors, and the
;; names of decision 4.
;;
;; bjo build && bjo test tests/values.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 scratch (path-combine (temp-dir) (str "bjosh-values-" (int->string process-id))))
;; Runs `line` in `scratch`. Returns "out", then "err: " and the error
;; text when there is one, then "code: n" when it is not 0.
(: (-> string string))
(defun (c line)
(def err-path (path-combine (temp-dir) (str "bjosh-values-err-" (int->string process-id))))
(def full (str "cd " scratch "; " line))
(match (run/output (FErrInto err-path (FArgv ["dotnet" (path-combine (current-directory) shell) "-c" full])))
((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)))))
(def fruit "printf 'banana\\napple\\nbanana\\ncherry\\n'")
(defun (main args)
(unless (file-exists? shell)
(println "FAILURE: src/main.exe is missing: run bjo build first"))
(ignore (directory-create scratch))
(ignore (directory-create (path-combine scratch "sub")))
(ignore (file-write-text (path-combine scratch "a.txt") "one\ntwo\n"))
(ignore (file-write-text (path-combine scratch "b.json") "[{\"n\": 1}, {\"n\": 2}]"))
(ignore (file-write-text (path-combine scratch "c.csv") "name,size\nx,1\ny,22\n"))
;; Lines from a program, and the filters.
(expect "sort-by" (c (str fruit " | so")) "apple\nbanana\nbanana\ncherry")
(expect "sort-by -r" (c (str fruit " | so -r | hd 1")) "cherry")
(expect "uniq" (c (str fruit " | u")) "banana\napple\ncherry")
(expect "count" (c (str fruit " | n")) "4")
(expect "reverse" (c (str fruit " | rv")) "cherry\nbanana\napple\nbanana")
(expect "first" (c (str fruit " | hd 2")) "banana\napple")
(expect "last" (c (str fruit " | tl 2")) "banana\ncherry")
(expect "lines, said" (c (str fruit " | li | n")) "4")
(expect "where it contains" (c (str fruit " | wh it contains err")) "cherry")
(expect "where it =~" (c (str fruit " | wh it =~ '^a'")) "apple")
(expect "where it ==" (c (str fruit " | wh it == apple")) "apple")
(expect "where with a quoted <" (c "printf '1\\n5\\n10\\n' | wh it '<' 6") "1\n5")
(expect "where gt on numbers" (c "printf '1\\n5\\n10\\n' | fj | wh it gt 2") "5\n10")
;; JSON and CSV.
(expect "from-json: a table, numbers to the right"
(c "echo '[{\"a\":1},{\"a\":30,\"b\":\"x\"}]' | fj")
" a b\n── ─\n 1\n30 x")
(expect "from-json: one value per line" (c "printf '{\"a\":1}\\n{\"a\":2}\\n' | fj | g a") "1\n2")
(expect "to-json keeps the order of fields" (c "echo '{\"b\":null,\"a\":1}' | fj | tj") "{\"b\":null,\"a\":1}")
(expect "select" (c "echo '{\"b\":2,\"a\":1,\"c\":3}' | fj | se c a | tj") "{\"c\":3,\"a\":1}")
(expect "get leaves out a record without the field" (c "echo '[{\"a\":1},{\"b\":2}]' | fj | g a") "1")
(expect "from-csv: numbers are numbers" (c "printf 'n,v\\nx,9\\ny,10\\n' | fcs | so v | g n") "x\ny")
(expect "to-csv" (c "printf 'n,v\\nx,1\\n' | fcs | tcs") "n,v\nx,1")
(expect "a bad document" (c "echo '{' | fj")
"err: bjosh: from-json: line 2, column 1: the document ended inside an object\ncode: 1")
;; Sources.
(expect "files" (c "l | g name") "a.txt\nb.json\nc.csv\nsub")
(expect "files: the type" (c "l | wh type == dir | g name") "sub")
(expect "files: the size" (c "l | wh name == a.txt | g size") "8")
(expect "files of a directory" (c "l sub | n") "0")
(expect "open .json" (c "o b.json | g n") "1\n2")
(expect "open .csv" (c "o c.csv | wh size gt 5 | g name") "y")
(expect "open, lines" (c "o a.txt") "one\ntwo")
(expect "procs" (c "p | wh pid == 1 | n") "1")
;; Values and programs in one pipe.
(expect "values into a program" (c "l | g name | grep json") "b.json")
(expect "a program, values, a program" (c (str fruit " | so | uniq -c | wc -l")) "3")
(expect "a value command between programs" (c (str fruit " | u | tr a-z A-Z")) "BANANA\nAPPLE\nCHERRY")
(expect "to-json into a program" (c "l | wh name == sub | tj | grep -c '\"type\":\"dir\"'") "1")
;; Errors.
(expect "where without its words" (c "l | wh name")
"err: bjosh: where: FIELD OP VALUE, such as: where size gt 1000\ncode: 1")
(expect "a bad count, in a pipe with programs" (c "printf 'a\\n' | hd x | cat")
"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")
;; Names (decision 4).
(expect "a long name that is a program runs the program" (c "printf 'a\\na\\n' | uniq -c") " 2 a")
(expect "a short name is always the value command" (c "type u") "u is a value command: uniq, u")
(expect "no short name is a program on this PATH"
(match (run/output '(sh "-c" "for n in l p o wh se g so hd tl n rv u li fj tj fcs tcs; do command -v $n; done; true"))
((Ok (Tuple _ out)) (string-trim-right out))
((Err e) (run-error-message e)))
"")
(ignore (directory-delete-tree scratch))
0)