Skip to main content

graphforge_cli/
process.rs

1//! Console execution with inherited OS streams and invocation-scoped state.
2use crate::{
3    Diagnostics, argument_error_execution, error_exit_code, parse_cli, requests_json, run,
4    write_runtime_error,
5};
6use std::io::{self, Write};
7
8thread_local! {
9    // Invocation-local: a streaming call must not enable vault access, browser
10    // prompts or clone progress for later captured calls in the host.
11    static PROCESS_ATTACHED: std::cell::Cell<bool> = const { std::cell::Cell::new(false) };
12}
13
14pub(crate) fn process_attached() -> bool {
15    PROCESS_ATTACHED.get()
16}
17
18/// Prompts require an attached console with both input and diagnostics on terminals.
19pub(crate) fn interactive_process() -> bool {
20    use std::io::IsTerminal as _;
21    process_attached() && io::stdin().is_terminal() && io::stderr().is_terminal()
22}
23
24struct ProcessAttachment(bool);
25
26impl Drop for ProcessAttachment {
27    fn drop(&mut self) {
28        PROCESS_ATTACHED.set(self.0);
29    }
30}
31
32/// Execute with the actual process stdin, stdout and stderr, returning its status.
33///
34/// Intended for console launchers: notices stream immediately and terminal
35/// detection uses the OS descriptors. This never exits the embedding host or
36/// installs signal handlers; the host retains signal ownership.
37/// Captured callers should continue to use [`crate::execute`].
38pub fn execute_process<I, T>(args: I) -> i32
39where
40    I: IntoIterator<Item = T>,
41    T: Into<std::ffi::OsString> + Clone,
42{
43    let args: Vec<std::ffi::OsString> = args.into_iter().map(Into::into).collect();
44    let cli = match parse_cli(&args) {
45        Ok(cli) => cli,
46        Err(error) if !requests_json(&args) || !error.use_stderr() => {
47            let _ = error.print();
48            return error.exit_code();
49        }
50        Err(error) => {
51            let refused = argument_error_execution(&error, true);
52            let _ = io::stderr().write_all(&refused.stderr);
53            return refused.exit_code;
54        }
55    };
56    let _attachment = ProcessAttachment(PROCESS_ATTACHED.replace(true));
57    let json = cli.json;
58    let mut output = io::stdout().lock();
59    let mut stderr = io::stderr();
60    let mut diagnostics = Diagnostics::new(json, &mut stderr);
61    let result = run(cli, &mut output, &mut diagnostics);
62    let warnings = diagnostics.collected();
63    drop(diagnostics);
64    let _ = output.flush();
65    match result {
66        Ok(exit_code) => exit_code,
67        Err(error) => {
68            let _ = write_runtime_error(&error, json, &mut stderr.lock(), &warnings);
69            error_exit_code(&error)
70        }
71    }
72}
73
74/// Stream process output directly and terminate with the native CLI exit status.
75pub fn run_process() {
76    crate::hub_clone::own_process_signals();
77    std::process::exit(execute_process(std::env::args_os()));
78}
79
80#[cfg(test)]
81mod tests {
82    use super::*;
83    use crate::execute;
84
85    #[test]
86    fn process_attachment_is_thread_local_and_restored_after_failure() {
87        assert!(!process_attached());
88        {
89            let _attachment = ProcessAttachment(PROCESS_ATTACHED.replace(true));
90            assert!(process_attached());
91            std::thread::spawn(|| assert!(!process_attached()))
92                .join()
93                .unwrap();
94        }
95        assert!(!process_attached());
96        let root = tempfile::tempdir().unwrap();
97        let status = execute_process([
98            "gf",
99            "--project-dir",
100            root.path().join("missing").to_str().unwrap(),
101            "config",
102            "validate",
103        ]);
104        assert_eq!(status, 3);
105        assert!(!process_attached());
106        assert_eq!(execute(["gf", "--version"]).exit_code, 0);
107    }
108}