;; 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 builtins): the shell commands. They change the shell, so they run ;; in its process and must be alone in a pipe. ;; ;; - Each takes the shell and its arguments, and returns an exit status. ;; - Each writes to the current output and error ports. ;; - `find-program` is the search of PATH that `type` and the completer ;; use. (import (std prelude)) (import (std run)) (import (bjoterm line)) (import (bjosh syntax)) (import (bjosh shell)) (import (bjosh commands)) (import (bjosh values)) (import (text json)) (export builtin? run-builtin builtin-names find-program shell-value-command) (type (: Builtin (Record (: name string) (: usage string) (: help string) (: run (-> Shell (Vec string) int))))) ;; =========================================================================== ;; The commands ;; =========================================================================== ;; Runs `f` on each item, and returns the largest status: 0 when all ;; succeed. (: (-> (Vec %a) (-> %a int) int)) (defun (each-status items f) (let go ((i 0) (status 0)) (if (= i (vec-length items)) status (go (+ i 1) (max status (f (vec-ref items i))))))) (: (-> Shell (Vec string) int)) (defun (cd sh args) (def old (current-directory)) (def target (cond ((vec-empty? args) (getenv "HOME")) ((= (vec-ref args 0) "-") (getenv "OLDPWD")) (else (Some (vec-ref args 0))))) (match target (None (shell-error "cd: no HOME or OLDPWD") 1) ((Some dir) (match (try (set-current-directory! dir) #:catch (System.Exception)) ((Ok _) (set-environment-variable! "OLDPWD" old) (set-environment-variable! "PWD" (current-directory)) (when (and (not (vec-empty? args)) (= (vec-ref args 0) "-")) (println (current-directory))) 0) ((Err e) (shell-error (str "cd: " dir ": " (.-Message e))) 1))))) (: (-> Shell (Vec string) int)) (defun (pwd sh args) (println (current-directory)) 0) (: (-> Shell (Vec string) int)) (defun (exit-shell sh args) (def code (if (vec-empty? args) (Some (record-ref sh status)) (string->int (vec-ref args 0)))) (match code (None (shell-error (str "exit: " (vec-ref args 0) ": not a number")) 2) ((Some code) (if (and (jobs-stopped? sh) (not (record-ref sh warned-stopped?))) (begin (warn-stopped! sh) (shell-error "there are stopped jobs; exit again to end them") 1) (begin (request-exit! sh code) code))))) ;; NAME=value sets and exports. NAME exports a shell variable. (: (-> Shell (Vec string) int)) (defun (export sh args) (if (vec-empty? args) (begin (shell-error "export: usage: export NAME[=value]...") 2) (each-status args (fun (arg) (match (string-split-once arg "=") ((Some (Tuple name value)) (var-export! sh name value) 0) (None (match (map-try-ref (record-ref sh vars) arg) ((Some value) (var-export! sh arg value) 0) (None (match (getenv arg) ((Some _) 0) (None (shell-error (str "export: " arg ": not set")) 1)))))))))) (: (-> Shell (Vec string) int)) (defun (unset sh args) (for-each (fun (name) (var-unset! sh name)) args) 0) (: (-> Shell (Vec string) int)) (defun (jobs sh args) (report-jobs sh) (for-each (fun (e) (println (job-text-line sh e))) (record-ref sh jobs)) 0) ;; The job of the first argument, or the current job. (: (-> Shell string (Vec string) (Result string JobEntry))) (defun (job-arg sh command args) (match (job-find sh (if (vec-empty? args) "%+" (vec-ref args 0))) ((Ok e) (Ok e)) ((Err message) (Err (if (vec-empty? args) (str command ": no current job") (str command ": " message)))))) (: (-> Shell (Vec string) int)) (defun (fg sh args) (match (job-arg sh "fg" args) ((Err message) (shell-error message) 1) ((Ok e) (println (record-ref e text)) (foreground! sh (record-ref e job) (record-ref e text))))) (: (-> Shell (Vec string) int)) (defun (bg sh args) (match (job-arg sh "bg" args) ((Err message) (shell-error message) 1) ((Ok e) (job-background (record-ref e job)) (job-set-state! e JobRunning) (job-mark-recent! sh (record-ref e number)) (println (str "[" (int->string (record-ref e number)) "]+ " (record-ref e text) " &")) 0))) (: (Vec (Tuple string int))) (def signal-names [(Tuple "HUP" 1) (Tuple "INT" 2) (Tuple "QUIT" 3) (Tuple "KILL" 9) (Tuple "USR1" 10) (Tuple "USR2" 12) (Tuple "TERM" 15) (Tuple "CONT" 18) (Tuple "STOP" 19) (Tuple "TSTP" 20)]) ;; A signal from -N, -NAME or -SIGNAME. (: (-> string (Option int))) (defun (signal-of text) (def body (string-drop text 1)) (def name (if (string-starts-with? body "SIG") (string-drop body 3) body)) (match (string->int body) ((Some n) (Some n)) (None (match (find (fun (p) (= (fst p) name)) signal-names) ((Some p) (Some (snd p))) (None None))))) ;; kill [-SIGNAL] %job|pid... Jobs get the signal here; pids go to the ;; kill program. (: (-> Shell (Vec string) int)) (defun (kill sh args) (def has-signal? (and (not (vec-empty? args)) (string-starts-with? (vec-ref args 0) "-"))) (def signal (if has-signal? (signal-of (vec-ref args 0)) (Some 15))) (def targets (if has-signal? (vec-slice args 1 (- (vec-length args) 1)) args)) (match signal (None (shell-error (str "kill: " (vec-ref args 0) ": no such signal")) 2) ((Some signal) (if (vec-empty? targets) (begin (shell-error "kill: usage: kill [-SIGNAL] %job|pid...") 2) (let ((pids (vec-filter (fun (t) (not (string-starts-with? t "%"))) targets))) (def job-status (each-status (vec-filter (fun (t) (string-starts-with? t "%")) targets) (fun (t) (match (job-find sh t) ((Ok e) (job-signal (record-ref e job) signal) ;; A stopped job gets the signal when it runs. (match (record-ref e state) ((JobStopped _) (unless (= signal 19) (job-signal (record-ref e job) 18))) (_ unit)) 0) ((Err message) (shell-error (str "kill: " message)) 1))))) (if (vec-empty? pids) job-status (match (run/interactive (FArgv (vec-append ["kill" (str "-" (int->string signal))] pids))) ((Ok code) (max code job-status)) ((Err e) (shell-error (run-error-message e)) 1)))))))) ;; The names of the aliases, sorted. (: (-> Shell (Vec string))) (defun (alias-names sh) (list->vec (list-sort (->list (map-keys (record-ref sh aliases)))))) ;; alias NAME='TEXT', as `alias` writes it, which the shell reads back. (: (-> string string string)) (defun (alias-line name text) (str "alias " name "='" (string-replace text "'" "'\\''") "'")) ;; alias: lists the aliases. alias NAME: shows one. alias NAME=TEXT: sets ;; one; TEXT must be one pipe. (: (-> Shell (Vec string) int)) (defun (alias sh args) (if (vec-empty? args) (begin (for-each (fun (name) (match (alias-ref sh name) ((Some text) (println (alias-line name text))) (None unit))) (alias-names sh)) 0) (each-status args (fun (arg) (match (string-split-once arg "=") ((Some (Tuple name text)) (match (parse-pipe text) ((Ok _) (alias-set! sh name text) 0) ((Err message) (shell-error (str "alias: " name ": " message)) 1))) (None (match (alias-ref sh arg) ((Some text) (println (alias-line arg text)) 0) (None (shell-error (str "alias: " arg ": not found")) 1)))))))) (: (-> Shell (Vec string) int)) (defun (unalias sh args) (each-status args (fun (name) (match (alias-ref sh name) ((Some _) (alias-remove! sh name) 0) (None (shell-error (str "unalias: " name ": not found")) 1))))) ;; The path of a program on PATH, or a name with a / that exists. (: (-> string (Option string))) (defun (find-program name) (if (string-contains? name "/") (if (file-exists? name) (Some name) None) (let ((dirs (match (getenv "PATH") ((Some p) (string-split p ":")) (None [])))) (let go ((i 0)) (if (= i (vec-length dirs)) None (let ((path (path-combine (vec-ref dirs i) name))) (if (and (not (string-empty? (vec-ref dirs i))) (file-exists? path)) (Some path) (go (+ i 1))))))))) (: (-> Shell (Vec string) int)) (defun (type-of sh args) (each-status args (fun (name) (cond ((some? (alias-ref sh name)) (println (str name " is an alias for " (match (alias-ref sh name) ((Some t) t) (None "")))) 0) ((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))))))))) (: (-> 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) (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")) (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)) (defun (history sh args) (match (record-ref sh editor) (None 0) ((Some ed) (def entries (line-history ed)) (loop (:for entry (in-vec entries)) (:for i (range 1 (+ 1 (vec-length entries)))) (:do (println (str (string-pad-left (int->string i) 5) " " entry)))) 0))) ;; =========================================================================== ;; The table ;; =========================================================================== (: (-> (Vec Builtin))) (defun (builtins) [(Builtin (name "cd") (usage "cd [DIR|-]") (help "change the directory; - is the one before") (run cd)) (Builtin (name "pwd") (usage "pwd") (help "write the current directory") (run pwd)) (Builtin (name "exit") (usage "exit [CODE]") (help "end the shell") (run exit-shell)) (Builtin (name "export") (usage "export NAME[=VALUE]...") (help "put variables in the environment") (run export)) (Builtin (name "unset") (usage "unset NAME...") (help "remove variables") (run unset)) (Builtin (name "jobs") (usage "jobs") (help "list the jobs") (run jobs)) (Builtin (name "fg") (usage "fg [%JOB]") (help "run a job in the foreground") (run fg)) (Builtin (name "bg") (usage "bg [%JOB]") (help "continue a stopped job in the background") (run bg)) (Builtin (name "kill") (usage "kill [-SIGNAL] %JOB|PID...") (help "send a signal; TERM by default") (run kill)) (Builtin (name "type") (usage "type NAME...") (help "what a name runs") (run type-of)) (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))]) ;; =========================================================================== ;; 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))) (: (Vec string)) (def builtin-names (vec-map (fun (b) (record-ref b 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)) ((Some b) (def status ((record-ref b run) sh args)) (flush-port (parameter-ref current-output-port)) status) (None (shell-error (str name ": no such shell command")) 127)))