Debian Codegraph @

cli/src/commands/util/exec.rs

raw
1 // Copyright 2024 The Jujutsu Authors
2 //
3 // Licensed under the Apache License, Version 2.0 (the "License");
4 // you may not use this file except in compliance with the License.
5 // You may obtain a copy of the License at
6 //
7 // https://www.apache.org/licenses/LICENSE-2.0
8 //
9 // Unless required by applicable law or agreed to in writing, software
10 // distributed under the License is distributed on an "AS IS" BASIS,
11 // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
12 // See the License for the specific language governing permissions and
13 // limitations under the License.
14
15 use crate::cli_util::CommandHelper;
16 use crate::command_error::CommandError;
17 use crate::command_error::user_error;
18 use crate::command_error::user_error_with_message;
19 use crate::ui::Ui;
20
21 /// Execute an external command via jj
22 ///
23 /// This command will have access to the environment variable JJ_WORKSPACE_ROOT.
24 ///
25 /// This is useful for arbitrary aliases.
26 ///
27 /// !! WARNING !!
28 ///
29 /// The following technique just provides a convenient syntax for running
30 /// arbitrary code on your system. Using it irresponsibly may cause damage
31 /// ranging from breaking the behavior of `jj undo` to wiping your file system.
32 /// Exercise the same amount of caution while writing these aliases as you would
33 /// when typing commands into the terminal!
34 ///
35 /// This feature may be removed or replaced by an embedded scripting language in
36 /// the future.
37 ///
38 /// Let's assume you have a script called "my-jj-script" in your $PATH and you
39 /// would like to execute it as "jj my-script". You would add the following line
40 /// to your configuration file to achieve that:
41 ///
42 /// ```toml
43 /// [aliases]
44 /// my-script = ["util", "exec", "--", "my-jj-script"]
45 /// # ^^^^
46 /// # This makes sure that flags are passed to your script instead of parsed by jj.
47 /// ```
48 ///
49 /// If you don't want to manage your script as a separate file, you can even
50 /// inline it into your config file:
51 ///
52 /// ```toml
53 /// [aliases]
54 /// my-inline-script = ["util", "exec", "--", "bash", "-c", """
55 /// set -euo pipefail
56 /// echo "Look Ma, everything in one file!"
57 /// echo "args: $@"
58 /// """, ""]
59 /// # ^^
60 /// # This last empty string will become "$0" in bash, so your actual arguments
61 /// # are all included in "$@" and start at "$1" as expected.
62 /// ```
63 ///
64 /// > Note: Shebangs (e.g. `#!/usr/bin/env`) aren't necessary since you're
65 /// > already explicitly passing your script into the right shell.
66 #[derive(clap::Args, Clone, Debug)]
67 #[command(verbatim_doc_comment)]
68 pub(crate) struct UtilExecArgs {
69 /// External command to execute
70 command: String,
71
72 /// Arguments to pass to the external command
73 #[arg(value_hint = clap::ValueHint::FilePath)]
74 args: Vec<String>,
75 }
76
77 pub async fn cmd_util_exec(
78 _: &mut Ui,
79 command: &CommandHelper,
80 args: &UtilExecArgs,
81 ) -> Result<(), CommandError> {
82 let workspace_root = command
83 .workspace_loader()
84 .ok()
85 .map(|loader| loader.workspace_root());
86 let mut cmd = std::process::Command::new(&args.command);
87 cmd.args(&args.args);
88
89 if let Some(workspace_root) = workspace_root {
90 cmd.env("JJ_WORKSPACE_ROOT", workspace_root);
91 }
92
93 let status = cmd.status().map_err(|err| {
94 user_error_with_message(
95 format!("Failed to execute external command '{}'", args.command),
96 err,
97 )
98 })?;
99
100 // Try to match the exit status of the executed process.
101 if let Some(exit_code) = status.code() {
102 std::process::exit(exit_code);
103 }
104 if !status.success() {
105 // signal
106 return Err(user_error(format!(
107 "External command was terminated by {status}"
108 )));
109 }
110 Ok(())
111 }