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"