twig-tmux 0.1.3

Tmux session manager with git worktree support
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
use std::path::PathBuf;
use std::process::Command;
use std::thread::sleep;
use std::time::{Duration, Instant, SystemTime, UNIX_EPOCH};

use anyhow::{Context, Result};

use crate::config::{Project, Window};
use crate::tmux_control::ControlClient;

const SETUP_WINDOW_NAME: &str = "setup-twig";

/// Check if a tmux session exists
pub fn session_exists(name: &str) -> Result<bool> {
    let output = Command::new("tmux")
        .args(["has-session", "-t", name])
        .output()
        .context("Failed to check tmux session")?;

    Ok(output.status.success())
}

/// Check if a tmux session exists on a specific socket
pub fn session_exists_with_socket(name: &str, socket_path: &str) -> Result<bool> {
    let output = Command::new("tmux")
        .args(["-S", socket_path, "has-session", "-t", name])
        .output()
        .context("Failed to check tmux session")?;

    Ok(output.status.success())
}

/// Attach to an existing tmux session
pub fn attach_session(name: &str) -> Result<()> {
    let status = Command::new("tmux")
        .args(["attach-session", "-t", name])
        .status()
        .context("Failed to attach to tmux session")?;

    if !status.success() {
        anyhow::bail!("Failed to attach to session: {}", name);
    }

    Ok(())
}

/// Switch to a tmux session (when already inside tmux)
pub fn switch_client(name: &str) -> Result<()> {
    let status = Command::new("tmux")
        .args(["switch-client", "-t", name])
        .status()
        .context("Failed to switch tmux client")?;

    if !status.success() {
        anyhow::bail!("Failed to switch to session: {}", name);
    }

    Ok(())
}

/// Check if we're inside a tmux session
pub fn inside_tmux() -> bool {
    std::env::var("TMUX").is_ok()
}

/// Get the current tmux session name (if inside tmux)
pub fn current_session_name() -> Option<String> {
    if !inside_tmux() {
        return None;
    }

    let output = Command::new("tmux")
        .args(["display-message", "-p", "#{session_name}"])
        .output()
        .ok()?;

    if output.status.success() {
        Some(String::from_utf8_lossy(&output.stdout).trim().to_string())
    } else {
        None
    }
}

/// Get the current tmux window name (if inside tmux)
pub fn current_window_name() -> Option<String> {
    if !inside_tmux() {
        return None;
    }

    let output = Command::new("tmux")
        .args(["display-message", "-p", "#{window_name}"])
        .output()
        .ok()?;

    if output.status.success() {
        Some(String::from_utf8_lossy(&output.stdout).trim().to_string())
    } else {
        None
    }
}

/// Get the current tmux session name for a specific socket
pub fn current_session_name_with_socket(socket_path: &str) -> Option<String> {
    let output = Command::new("tmux")
        .args([
            "-S",
            socket_path,
            "display-message",
            "-p",
            "#{session_name}",
        ])
        .output()
        .ok()?;

    if output.status.success() {
        Some(String::from_utf8_lossy(&output.stdout).trim().to_string())
    } else {
        None
    }
}

/// Get the current tmux window name for a specific socket
pub fn current_window_name_with_socket(socket_path: &str) -> Option<String> {
    let output = Command::new("tmux")
        .args(["-S", socket_path, "display-message", "-p", "#{window_name}"])
        .output()
        .ok()?;

    if output.status.success() {
        Some(String::from_utf8_lossy(&output.stdout).trim().to_string())
    } else {
        None
    }
}

/// Detach from current tmux session
pub fn detach() -> Result<()> {
    Command::new("tmux")
        .arg("detach-client")
        .status()
        .context("Failed to detach from tmux")?;
    Ok(())
}

/// Kill a tmux session
pub fn kill_session(name: &str) -> Result<()> {
    kill_session_with_timeout(name, Duration::from_secs(30))
}

/// Safely kill a session, switching away first if we're inside it
pub fn safe_kill_session(name: &str) -> Result<()> {
    if let Some(current) = current_session_name() {
        if current == name {
            // We're inside the session we want to kill
            // Try to switch to another session first
            let sessions = list_sessions()?;
            let other_session = sessions.iter().find(|s| *s != name);

            if let Some(other) = other_session {
                switch_client(other)?;
            } else {
                // No other session, detach first
                detach()?;
            }
        }
    }

    kill_session(name)
}

/// List all tmux sessions
pub fn list_sessions() -> Result<Vec<String>> {
    let output = Command::new("tmux")
        .args(["list-sessions", "-F", "#{session_name}"])
        .output()
        .context("Failed to list tmux sessions")?;

    if output.status.success() {
        let sessions = String::from_utf8(output.stdout)?
            .lines()
            .map(|s| s.to_string())
            .collect();
        Ok(sessions)
    } else {
        // No sessions exist
        Ok(vec![])
    }
}

/// Builder for creating tmux sessions
pub struct SessionBuilder {
    session_name: String,
    root: String,
    windows: Vec<Window>,
    project_name: String,
    worktree_branch: Option<String>,
    post_create_commands: Vec<String>,
}

impl SessionBuilder {
    pub fn new(project: &Project) -> Self {
        let post_create_commands = project
            .worktree
            .as_ref()
            .map(|w| w.post_create.clone())
            .unwrap_or_default();

        Self {
            session_name: project.name.clone(),
            root: project.root.clone(),
            windows: project.windows.clone(),
            project_name: project.name.clone(),
            worktree_branch: None,
            post_create_commands,
        }
    }

    pub fn with_session_name(mut self, name: String) -> Self {
        self.session_name = name;
        self
    }

    pub fn with_root(mut self, root: String) -> Self {
        self.root = root;
        self
    }

    pub fn with_worktree(mut self, branch: String) -> Self {
        self.worktree_branch = Some(branch);
        self
    }

    /// Start the tmux session using tmux control mode.
    /// Creates session, runs post-create commands sequentially, then sets up windows.
    pub fn start_with_control(&self) -> Result<()> {
        let mut client = ControlClient::connect(None)?;
        self.create_session_with_control(&mut client)?;
        self.run_post_create_with_control(&mut client)?;
        self.setup_windows_with_control(&mut client)?;
        Ok(())
    }

    pub fn create_session_with_control(&self, client: &mut ControlClient) -> Result<()> {
        let root_expanded = PathBuf::from(shellexpand::tilde(&self.root).to_string());
        let mut env = vec![("TWIG_PROJECT", self.project_name.as_str())];
        if let Some(branch) = self.worktree_branch.as_deref() {
            env.push(("TWIG_WORKTREE", branch));
        }

        client.new_session(&self.session_name, SETUP_WINDOW_NAME, &root_expanded, &env)?;

        client.set_environment(&self.session_name, "TWIG_PROJECT", &self.project_name)?;
        if let Some(branch) = &self.worktree_branch {
            client.set_environment(&self.session_name, "TWIG_WORKTREE", branch)?;
        }

        Ok(())
    }

    pub fn run_post_create_with_control(&self, client: &mut ControlClient) -> Result<()> {
        if self.post_create_commands.is_empty() {
            return Ok(());
        }

        let target = format!("{}:{}", self.session_name, SETUP_WINDOW_NAME);

        for (index, command) in self.post_create_commands.iter().enumerate() {
            let trimmed = command.trim();
            if trimmed.is_empty() {
                continue;
            }

            let token = unique_wait_token(&self.session_name, index);
            let signal = format!("{}; tmux wait-for -S {}", trimmed, token);
            client.send_keys(&target, &signal, true)?;
            client.wait_for(&token)?;
        }

        Ok(())
    }

    pub fn setup_windows_with_control(&self, client: &mut ControlClient) -> Result<()> {
        let root_expanded = PathBuf::from(shellexpand::tilde(&self.root).to_string());

        let first_window = self.windows.first();
        let first_window_name = first_window
            .map(|w| w.name())
            .unwrap_or_else(|| "shell".to_string());

        client.rename_window(
            &format!("{}:{}", self.session_name, SETUP_WINDOW_NAME),
            &first_window_name,
        )?;

        if let Some(window) = first_window {
            self.setup_window_with_control(
                client,
                &self.session_name,
                &first_window_name,
                window,
                &root_expanded,
            )?;
        }

        for window in self.windows.iter().skip(1) {
            let window_name = window.name();
            client.new_window(&self.session_name, &window_name, &root_expanded)?;
            self.setup_window_with_control(
                client,
                &self.session_name,
                &window_name,
                window,
                &root_expanded,
            )?;
        }

        client.select_window(&format!("{}:{}", self.session_name, first_window_name))?;

        Ok(())
    }

    fn setup_window_with_control(
        &self,
        client: &mut ControlClient,
        session: &str,
        window_name: &str,
        window: &Window,
        root: &std::path::Path,
    ) -> Result<()> {
        let target = format!("{}:{}", session, window_name);

        if window.has_panes() {
            let panes = window.panes();
            let layout = window.layout();

            if let Some(first_pane) = panes.first() {
                if let Some(cmd) = first_pane.command() {
                    client.send_keys(&target, cmd, true)?;
                }
            }

            for pane in panes.iter().skip(1) {
                let split_arg = if layout.as_deref() == Some("main-horizontal") {
                    Some("-v")
                } else {
                    Some("-h")
                };

                client.split_window_with_direction(&target, root, split_arg)?;

                if let Some(cmd) = pane.command() {
                    client.send_keys(&target, cmd, true)?;
                }
            }

            if let Some(layout_name) = layout {
                client.select_layout(&target, &layout_name)?;
            }

            let base_index = get_base_index();
            client.select_pane(&format!("{}.{}", target, base_index))?;
        } else if let Some(cmd) = window.simple_command() {
            client.send_keys(&target, &cmd, true)?;
        }

        Ok(())
    }
}

/// Get tmux base-index setting (default is 0, but users often set to 1)
fn get_base_index() -> u32 {
    let output = Command::new("tmux")
        .args(["show-option", "-gv", "base-index"])
        .output()
        .ok();

    output
        .and_then(|o| String::from_utf8(o.stdout).ok())
        .and_then(|s| s.trim().parse().ok())
        .unwrap_or(0)
}

fn unique_wait_token(session: &str, index: usize) -> String {
    let now = SystemTime::now()
        .duration_since(UNIX_EPOCH)
        .unwrap_or_default()
        .as_nanos();
    format!("twig-post-create-{}-{}-{}", session, index, now)
}

fn kill_session_with_timeout(name: &str, timeout: Duration) -> Result<()> {
    let mut client = ControlClient::connect(None)?;
    client.kill_session(name)?;

    let start = Instant::now();
    loop {
        if !session_exists(name)? {
            return Ok(());
        }

        if start.elapsed() >= timeout {
            anyhow::bail!("Timed out waiting for session '{}' to stop", name);
        }

        sleep(Duration::from_millis(200));
    }
}

/// Connect to a session (attach or switch depending on context)
pub fn connect_to_session(name: &str) -> Result<()> {
    if inside_tmux() {
        switch_client(name)
    } else {
        attach_session(name)
    }
}