ctb_cli/subprocess.rs
1// SPDX-License-Identifier: AGPL-3.0-or-later
2/*
3This file is part of Collective Toolbox, a database and document workspace and utilities.
4Copyright (C) 2026 Collective Toolbox Developers
5Contact: info@collectivetoolbox.com
6
7This program is free software: you can redistribute it and/or modify it under
8the terms of the GNU Affero General Public License as published by the Free
9Software Foundation, either version 3 of the License, or (at your option) any
10later version.
11
12This program is distributed in the hope that it will be useful, but WITHOUT ANY
13WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR
14A PARTICULAR PURPOSE. See the GNU Affero General Public License for more details.
15
16You should have received a copy of the GNU Affero General Public License along
17with this program. If not, see <https://www.gnu.org/licenses/>.
18*/
19
20//! Subprocess argument parsing and dispatch for workspace child processes.
21
22#[allow(
23 unused_imports,
24 clippy::wildcard_imports,
25 reason = "Standard workspace module prelude"
26)]
27use crate::utilities::*;
28
29use ipc::ChildKind;
30
31/// Parse workspace/subprocess CLI arguments for the IPC runner.
32///
33/// This helper recognizes the subprocess marker [`ctb_utilities::ipc::IPC_ARG`]
34/// and returns:
35/// - `Some(kind)` when invoked as a subprocess (e.g. `--runtime`)
36/// - `None` when invoked as the workspace (normal parent process)
37///
38/// It also returns the remaining non-IPC arguments:
39/// - for subprocesses: arguments after the POSIX `--` separator
40/// - for workspace: all arguments (excluding the program name)
41pub fn parse_subprocess_cli(
42 raw: Vec<String>,
43) -> Result<(Option<ChildKind>, Vec<String>)> {
44 use ctb_utilities::ipc::IPC_ARG;
45 use ipc::child_kind_from_string;
46
47 // Reason for fallback: raw contains command-line arguments starting with executable name at raw[0]. If raw is empty or contains only the executable name, raw.get(1..) returns None and defaulting to an empty slice correctly reflects zero remaining CLI arguments.
48 let args = raw.get(1..).unwrap_or(&[]);
49 let is_subprocess = args.first().is_some_and(|a| a == IPC_ARG);
50 if !is_subprocess {
51 return Ok((None, args.to_vec()));
52 }
53
54 let args = if is_subprocess {
55 // Reason for fallback: IPC_ARG "--ctoolbox-ipc" is at args[0]. Slicing at 1.. strips the IPC marker; if no further arguments follow, returning an empty slice correctly represents zero remaining subprocess arguments.
56 args.get(1..).unwrap_or(&[])
57 } else {
58 args
59 };
60
61 // Split at POSIX arg separator.
62 let (ipc_args, remaining) = match args.iter().position(|a| a == "--") {
63 Some(idx) => (
64 #[expect(
65 clippy::expect_used,
66 reason = "idx is index of -- element, so ..idx is in bounds"
67 )]
68 args.get(..idx)
69 .expect("idx <= args.len() guaranteed by position search"),
70 // Reason for fallback: idx + 1 may exceed args length if "--" is the last element, returning an empty slice for remaining arguments.
71 args.get(idx.saturating_add(1)..).unwrap_or(&[]).to_vec(),
72 ),
73 None => (args, Vec::new()),
74 };
75
76 if !is_subprocess {
77 return Ok((None, args.to_vec()));
78 }
79
80 // Determine which child we are.
81 let mut kind: Option<ChildKind> = None;
82 for arg in ipc_args {
83 let Some(flag) = arg.strip_prefix("--") else {
84 continue;
85 };
86 if flag == "socket" {
87 continue;
88 }
89 if let Ok(k) = child_kind_from_string(flag) {
90 kind = Some(k);
91 return Ok((kind, remaining));
92 }
93 }
94
95 Err(anyhow::anyhow!(
96 "subprocess mode requires a child kind flag"
97 ))
98}
99
100/// Extract `--socket <path>` from the IPC args.
101pub fn parse_subprocess_socket(raw: &[String]) -> Result<Option<String>> {
102 use ctb_utilities::ipc::IPC_ARG;
103
104 // Reason for fallback: raw contains argv where raw[0] is executable path. Default to empty slice if raw has <= 1 element.
105 let args = raw.get(1..).unwrap_or(&[]);
106 let is_subprocess = args.first().is_some_and(|a| a == IPC_ARG);
107 if !is_subprocess {
108 return Ok(None);
109 }
110 // Reason for fallback: strip IPC_ARG marker; if args has <= 1 element, default to empty slice for subprocess options.
111 let args = args.get(1..).unwrap_or(&[]);
112
113 // Only consider args before POSIX separator.
114 // Reason for fallback: when "--" separator is not present, position() returns None and ipc_args_end defaults to full args length so all arguments are checked for --socket.
115 let ipc_args_end =
116 args.iter().position(|a| a == "--").unwrap_or(args.len());
117 // Reason for fallback: ipc_args_end is guaranteed <= args.len().
118 let ipc_args = args.get(..ipc_args_end).unwrap_or(&[]);
119
120 let mut it = ipc_args.iter();
121 while let Some(a) = it.next() {
122 if a == "--socket" {
123 return Ok(it.next().cloned());
124 }
125 }
126
127 Ok(None)
128}
129
130/// Read a single-line IPC capability token from stdin.
131pub fn read_token_from_stdin() -> Result<String> {
132 use std::io::Read;
133
134 let mut buf = String::new();
135 std::io::stdin().read_to_string(&mut buf)?;
136 let token = buf
137 .lines()
138 .next()
139 .ok_or_else(|| anyhow::anyhow!("missing IPC token on stdin"))?
140 .trim()
141 .to_string();
142 anyhow::ensure!(!token.is_empty(), "missing IPC token on stdin");
143 Ok(token)
144}