aboutsummaryrefslogtreecommitdiff
path: root/lib/arbitrary_command.ml
blob: c39c32ee6835e493891c27d244bcb9f199464345 (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
module Grep = Grep

let extract_env env =
  env
  |> Array.to_list
  |> List.map (fun env_var ->
    let result = Str.bounded_split (Str.regexp "=") env_var 2 in
    match result with
    | [ a; b ] -> a, b
    | [ a ] -> a, ""
    | _ -> failwith ("Could not split the environment variables: " ^ env_var))


let run ~(on_return : string -> unit) t ~selected_file ~content ~command =
  (* Substitute after splitting to more easily deal with file names that have spaces *)
  let command =
    let s = Str.global_replace (Str.regexp "%(file)") selected_file command in
    Str.global_replace (Str.regexp "%(line)") content s
  in
  let shell = Sys.getenv "SHELL" in
  let command = List.concat [ [ shell; "-c"; command ] ] in
  Common.Term.cursor t (Some (0, 0));
  try
    let exit_code =
      let open Shexp_process in
      let context =
        Context.create
          ~stdin:Unix.stdin
          ~stdout:Unix.stdout
          ~stderr:Unix.stderr
          ~unix_env:(Unix.environment () |> extract_env)
          ()
      in
      let result =
        eval ~context (chdir Grep.execution_directory (call_exit_code command))
      in
      Context.dispose context;
      result
    in
    Common.Term.cursor t None;
    on_return ("Command exited with code " ^ Int.to_string exit_code)
  with
  | exn ->
    let oc = open_out "/tmp/stitch-error" in
    let environment = String.concat "," (Unix.environment () |> Array.to_list) in
    let commands_result = String.concat " " command in
    Printf.fprintf
      oc
      "%s\n%s\n%s\n%s\n%s\n"
      environment
      selected_file
      commands_result
      (Printexc.to_string exn)
      (Printexc.get_backtrace ());
    close_out oc;
    on_return "ERROR: Failed to run command. Error written to /tmp/stitch-error"