Something went wrong. Try again.
Shells in OCaml
Something went wrong. Try again.
123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220module C = Merry.Eval.Make (Merry_posix.State) (Merry_posix.Fd) (Merry_posix.Exec)
module I = Merry.Interactive.Make (Merry_posix.State) (Merry_posix.Fd) (Merry_posix.Exec) (Merry.History.Prefix_search)
type shell = { dump : bool; command : bool; merge : bool; trace : bool; arguments : string list; after_dashes : string list; options : Merry.Options.t; verbose : int;}
let _pp_shell ppf = let open Merry.Import in Fmt.( braces @@ record [ Fmt.field "dump" (fun t -> t.dump) Fmt.bool; Fmt.field "trace" (fun t -> t.trace) Fmt.bool; Fmt.field "command" (fun t -> t.command) Fmt.bool; Fmt.field "merge" (fun t -> t.merge) Fmt.bool; Fmt.field "arguments" (fun t -> t.arguments) Fmt.(lst string); Fmt.field "after_dashes" (fun t -> t.after_dashes) Fmt.(lst string); ]) ppf
let default_shell = { dump = false; command = false; merge = false; trace = false; arguments = []; after_dashes = []; options = Merry.Options.default; verbose = 0; }
let subst_tilde ctx path = let open Merry in match State.lookup (C.state ctx) ~param:"HOME" with | None, _ -> path | Some home, _ -> ( let home = Ast.Fragment.join_list ~sep:"" home in match Fpath.rem_prefix (Fpath.v home) path with | Some rel -> Fpath.(v "~" // rel) | None -> path)
let merge_prompt (ctx : C.t Merry.Exit.t) = let open Merry in let head, sesh = C.current_session (Exit.value ctx) in let sesh = Option.value ~default:"main" sesh in let state = match ctx with | Exit.Zero ctx | Exit.Nonzero { value = ctx; _ } -> C.state ctx in let pp_status ppf = function | Exit.Zero _ -> () | Exit.Nonzero { exit_code; _ } -> Fmt.pf ppf "[%a] " (Logger.pp_colored `Red Fmt.int) exit_code in let pp_head fmt = function | None -> Fmt.nop fmt () | Some h -> Fmt.pf fmt "#%a" (Logger.pp_colored `Magenta Fmt.string) h in let pp_sesh fmt sesh = Fmt.pf fmt "[%a%a]" (Logger.pp_colored `Green Fmt.string) sesh pp_head head in let fs = Exit.value ctx |> C.env |> fun env -> env#fs in Fmt.pf Format.str_formatter "%a%a:%a:%s%s >\n%!" pp_status ctx Fmt.(Logger.pp_colored `Yellow string) (Eunix.get_user_and_host fs) pp_sesh sesh (if C.is_committing (Exit.value ctx) then "c:" else "") (Fpath.normalize @@ State.cwd state |> subst_tilde (Exit.value ctx) |> Fpath.to_string); Format.flush_str_formatter ()
let sh ~name:_ shell env = let executor = Merry_posix.Exec.{ mgr = env#process_mgr } in let interactive = shell.arguments = [] in let pos_zero = match shell.arguments with f :: _ -> f | [] -> "msh" in let path = match Sys.getenv_opt "PATH" with | Some v -> Option.some @@ String.split_on_char ':' v | None -> None in let home = match Sys.getenv_opt "HOME" with Some v -> v ^ "/" | None -> "/" in let xdg = Xdge.create Eio.Path.(env#fs / home) "merry" in let store_dir = Xdge.data_dir xdg in let fd_table = Merry.Fd_table.load Eio.Path.(env#fs / "/proc") in Eio.Switch.run ~name:"async" @@ fun async_switch -> let config = C.make_config ~merge:shell.merge ~tracing:shell.trace () in let ctx argv = C.make_ctx ~config ~interactive ~build:(Merry__.Zfs_store.Build.Image "alpine") (Merry_posix.State.make ~home path (Fpath.v (Merry.Eunix.cwd ()))) executor fd_table ~async_switch ~options:shell.options ~argv ~store_dir ~program:pos_zero env in let bruit_ctx ~hint = Bruit_unix.stdctx ~hint () in match (shell.arguments, shell.command) with | [], false -> let argv = Array.of_list (pos_zero :: shell.arguments) in let prompt = if shell.merge then Some merge_prompt else None in I.run ?prompt bruit_ctx (Merry.Exit.zero (ctx argv)) | _ -> let ast, rest = match (shell.command, shell.arguments @ shell.after_dashes) with | false, file :: rest -> Merry.Debug.Log.debug (fun f -> f "msh executing %s" file); (Merry.Ast.of_file Eio.Path.(env#fs / file), rest) | true, c :: rest -> (Merry.Ast.of_string c, rest) | b, cs -> Fmt.failwith "Bad usage: %b %a" b Fmt.(list string) cs in if shell.dump then Merry.Ast.Dump.pp Fmt.stdout ast else let args = if shell.command then Array.of_list rest else begin let rest = match shell.after_dashes with | [] -> shell.arguments | some -> shell.arguments @ ("--" :: some) in Array.of_list rest end in let ctx, _ast = C.run (Merry.Exit.zero (ctx args)) ast in if shell.trace then begin Eio.Path.( save ~create:(`Or_truncate 0o644) (env#cwd / "msh-trace.csv")) (Fmt.str "%a" Merry.Trace.pp (C.trace (Merry.Exit.value ctx))) end; C.exit_from_eval ctx
(* Command line parsing for a shell is really awkward for reasons that I do not understand. But, it means we have to do this by hand. *)
exception Unknown_flag of string
let parse_arguments argv = let rec loop acc = function | "--" :: rest -> { acc with after_dashes = rest } | "-c" :: rest -> loop { acc with command = true } rest | "-d" :: rest | "--dump" :: rest -> loop { acc with dump = true } rest | "-t" :: rest | "--trace" :: rest -> loop { acc with trace = true } rest | "-m" :: rest | "--merge" :: rest -> loop { acc with merge = true } rest | "-e" :: rest -> loop { acc with options = Merry.Options.update acc.options [ (`Errexit, true) ]; } rest | "-v" :: rest -> loop { acc with verbose = acc.verbose + 1 } rest | arg :: rest -> (* Arguments for a command or for a script to run *) if acc.command || match acc.arguments with _ :: _ -> true | _ -> false then begin loop { acc with arguments = arg :: acc.arguments } rest end else if String.starts_with ~prefix:"-" arg || String.starts_with ~prefix:"--" arg then raise (Unknown_flag arg) else loop { acc with arguments = arg :: acc.arguments } rest | [] -> acc in let t = loop default_shell argv in { t with arguments = List.rev t.arguments }
let setup_log style_renderer level = Fmt_tty.setup_std_outputs ?style_renderer (); Logs.set_level ~all:false level; let override = Sys.getenv_opt "MSH_DEBUG" in let level = match override with Some _ -> Some Logs.Debug | None -> level in Logs.Src.set_level Merry.Debug.src level; Logs.set_reporter (Logs_fmt.reporter ()); ()
let reserve_fds n = Merry.Debug.Log.debug (fun f -> f "Reserving %i file descriptors" n); let fds = List.init n (fun _ -> Unix.openfile "/dev/null" [] 0) in fun () -> Merry.Debug.Log.debug (fun f -> f "Closing %i reserved file descriptors" n); List.iter Unix.close fds
let main () = let close_fds = reserve_fds 10 in Eio_posix.run @@ fun env -> Lwt_eio.with_event_loop ~clock:env#clock @@ fun _token -> close_fds (); let name, args = match Array.to_list Sys.argv with | [ name ] -> (name, []) | name :: rest -> (name, rest) | [] -> Fmt.failwith "Not possible to have no name!" in let shell_options = parse_arguments args in if shell_options.verbose >= 2 || (Option.is_some @@ Sys.getenv_opt "MSH_DEBUG") then setup_log (Some `Ansi_tty) (Some Debug); sh ~name shell_options env
let () = Memtrace.trace_if_requested ~context:"msh.0.0.1" (); Fmt_tty.setup_std_outputs (); if !Sys.interactive then () else main ()