stitch

Note taking for messy minimalists

git clone git://mccd.space/stitch

arbitrary_command.ml (1772B)

      1 module Grep = Grep
      2 
      3 let extract_env env =
      4   env
      5   |> Array.to_list
      6   |> List.map (fun env_var ->
      7     let result = Str.bounded_split (Str.regexp "=") env_var 2 in
      8     match result with
      9     | [ a; b ] -> a, b
     10     | [ a ] -> a, ""
     11     | _ -> failwith ("Could not split the environment variables: " ^ env_var))
     12 
     13 
     14 let run ~(on_return : string -> unit) t ~selected_file ~content ~command =
     15   (* Substitute after splitting to more easily deal with file names that have spaces *)
     16   let command =
     17     let s = Str.global_replace (Str.regexp "%(file)") selected_file command in
     18     Str.global_replace (Str.regexp "%(line)") content s
     19   in
     20   let shell = Sys.getenv "SHELL" in
     21   let command = List.concat [ [ shell; "-c"; command ] ] in
     22   Common.Term.cursor t (Some (0, 0));
     23   try
     24     let exit_code =
     25       let open Shexp_process in
     26       let context =
     27         Context.create
     28           ~stdin:Unix.stdin
     29           ~stdout:Unix.stdout
     30           ~stderr:Unix.stderr
     31           ~unix_env:(Unix.environment () |> extract_env)
     32           ()
     33       in
     34       let result =
     35         eval ~context (chdir Grep.execution_directory (call_exit_code command))
     36       in
     37       Context.dispose context;
     38       result
     39     in
     40     Common.Term.cursor t None;
     41     on_return ("Command exited with code " ^ Int.to_string exit_code)
     42   with
     43   | exn ->
     44     let oc = open_out "/tmp/stitch-error" in
     45     let environment = String.concat "," (Unix.environment () |> Array.to_list) in
     46     let commands_result = String.concat " " command in
     47     Printf.fprintf
     48       oc
     49       "%s\n%s\n%s\n%s\n%s\n"
     50       environment
     51       selected_file
     52       commands_result
     53       (Printexc.to_string exn)
     54       (Printexc.get_backtrace ());
     55     close_out oc;
     56     on_return "ERROR: Failed to run command. Error written to /tmp/stitch-error"