aboutsummaryrefslogtreecommitdiff
path: root/lib/arbitrary_command.ml
blob: 920a82f3f0fce44ffa0b1b9ecd5bc6c3d6ffcbcf (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
module Grep = Grep

let run ~(on_return : string -> unit) t ~selected_file ~content ~command =
  let command = String.split_on_char ' ' command in
  (* Substitute after splitting to more easily deal with file names that have spaces *)
  let command =
    command
    |> List.map (fun s ->
      let s = Str.global_replace (Str.regexp "%(file)") selected_file s in
      Str.global_replace (Str.regexp "%(content)") content s)
  in
  Common.Term.cursor t (Some (0, 0));
  try
    let result =
      let open Shexp_process in
      let open Shexp_process.Infix in
      eval (chdir Grep.execution_directory (call command |- read_all))
    in
    Common.Term.cursor t None;
    on_return result
  with
  | exn ->
    let oc = open_out "/tmp/stitch-error" in
    let commands_result = String.concat " " command in
    Printf.fprintf
      oc
      "%s\n%s\n%s\n%s\n"
      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"