1use core::str::FromStr;
7
8use rootcause::prelude::ResultExt;
9use rootcause::report;
10use ytil_editor::Editor;
11use ytil_editor::FileToOpen;
12use ytil_sys::cli::Args;
13
14#[ytil_sys::main]
16fn main() -> rootcause::Result<()> {
17 let enriched_path_env = get_enriched_path_env()?;
18 let args = ytil_sys::cli::get();
19
20 if args.has_help() {
21 println!("{}", include_str!("../help.txt"));
22 return Ok(());
23 }
24
25 let Some(editor) = args.first().map(|x| Editor::from_str(x)).transpose()? else {
26 return Err(report!("missing editor arg")).attach_with(|| format!("args={args:#?}"));
27 };
28
29 let Some(file_to_open) = args.get(1) else {
30 return Err(report!("missing file arg")).attach_with(|| format!("args={args:#?}"));
31 };
32
33 let pane_id = match args.get(2) {
34 Some(x) => x.parse()?,
35 None => ytil_wezterm::get_current_pane_id()?,
36 };
37
38 let panes = ytil_wezterm::get_all_panes(&[enriched_path_env.by_ref()])?;
39
40 let file_to_open = FileToOpen::try_from((file_to_open.as_str(), pane_id, panes.as_slice()))?;
41
42 let editor_pane_id =
43 ytil_wezterm::get_sibling_pane_with_titles(&panes, pane_id, editor.pane_titles()).map(|x| x.pane_id)?;
44
45 let open_file_cmd = editor.open_file_cmd(&file_to_open);
46 let escaped_open_file_cmd = escape_single_quotes(&open_file_cmd);
47
48 ytil_cmd::silent_cmd("sh")
49 .args([
50 "-c",
51 &format!(
52 "{} && {} && {} && {}",
53 ytil_wezterm::send_text_to_pane_cmd(r"$'\e'", editor_pane_id),
56 ytil_wezterm::send_text_to_pane_cmd(&format!("'{escaped_open_file_cmd}'"), editor_pane_id),
57 ytil_wezterm::submit_pane_cmd(editor_pane_id),
58 ytil_wezterm::activate_pane_cmd(editor_pane_id),
59 ),
60 ])
61 .envs(std::iter::once(enriched_path_env.by_ref()))
62 .spawn()?;
63
64 Ok(())
65}
66
67struct Env {
69 name: &'static str,
71 value: String,
73}
74
75impl Env {
76 pub fn by_ref(&self) -> (&'static str, &str) {
78 (self.name, &self.value)
79 }
80}
81
82fn get_enriched_path_env() -> rootcause::Result<Env> {
87 let enriched_path = [
88 &std::env::var("PATH").unwrap_or_else(|_| String::new()),
89 "/opt/homebrew/bin",
90 &ytil_sys::dir::build_home_path(&[".local", "bin"])?.to_string_lossy(),
91 ]
92 .join(":");
93
94 Ok(Env {
95 name: "PATH",
96 value: enriched_path,
97 })
98}
99
100fn escape_single_quotes(s: &str) -> String {
104 s.replace('\'', "'\\''")
105}
106
107#[cfg(test)]
108mod tests {
109 use rstest::rstest;
110
111 use super::*;
112
113 #[rstest]
114 #[case::no_quotes("hello world", "hello world")]
115 #[case::single_quote("it's here", "it'\\''s here")]
116 #[case::multiple_quotes("a'b'c", "a'\\''b'\\''c")]
117 #[case::only_quote("'", "'\\''")]
118 #[case::empty("", "")]
119 fn test_escape_single_quotes_produces_expected_output(#[case] input: &str, #[case] expected: &str) {
120 pretty_assertions::assert_eq!(escape_single_quotes(input), expected);
121 }
122}