kiosk-core 0.1.0

Core library for kiosk — tmux session manager with worktree support
Documentation
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
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
use super::{
    parse_worktree_porcelain,
    provider::GitProvider,
    repo::{Repo, Worktree},
};
use anyhow::Result;
use std::{
    path::{Path, PathBuf},
    process::Command,
};

pub struct CliGitProvider;

impl GitProvider for CliGitProvider {
    fn discover_repos(&self, dirs: &[(PathBuf, u16)]) -> Vec<Repo> {
        let mut repos_with_dirs = Vec::new();

        for (dir, depth) in dirs {
            self.scan_dir_recursive(dir, dir, *depth, &mut repos_with_dirs);
        }

        repos_with_dirs.sort_by(|a, b| a.0.name.to_lowercase().cmp(&b.0.name.to_lowercase()));

        // Count occurrences of each repo name
        let mut name_counts = std::collections::HashMap::<String, usize>::new();
        for (repo, _) in &repos_with_dirs {
            *name_counts.entry(repo.name.clone()).or_insert(0) += 1;
        }

        // Apply collision resolution
        let mut repos = Vec::new();
        for (mut repo, search_dir) in repos_with_dirs {
            if name_counts[&repo.name] > 1 {
                // Multiple repos with same name - disambiguate with parent dir
                let parent_dir_name = search_dir.file_name().unwrap_or_default().to_string_lossy();
                repo.session_name = format!("{}--({parent_dir_name})", repo.name);
            } else {
                // Unique name - use as is
                repo.session_name.clone_from(&repo.name);
            }
            repos.push(repo);
        }

        repos
    }

    fn list_branches(&self, repo_path: &Path) -> Vec<String> {
        let output = Command::new("git")
            .args(["branch", "--format=%(refname:short)"])
            .current_dir(repo_path)
            .output();

        let Ok(output) = output else {
            return Vec::new();
        };

        String::from_utf8_lossy(&output.stdout)
            .lines()
            .map(String::from)
            .collect()
    }

    fn list_worktrees(&self, repo_path: &Path) -> Vec<Worktree> {
        let output = Command::new("git")
            .args(["worktree", "list", "--porcelain"])
            .current_dir(repo_path)
            .output();

        let Ok(output) = output else {
            return vec![Self::main_worktree(repo_path)];
        };

        let stdout = String::from_utf8_lossy(&output.stdout);
        let worktrees = parse_worktree_porcelain(&stdout);

        if worktrees.is_empty() {
            vec![Self::main_worktree(repo_path)]
        } else {
            worktrees
        }
    }

    fn add_worktree(&self, repo_path: &Path, branch: &str, worktree_path: &Path) -> Result<()> {
        let output = Command::new("git")
            .args(["worktree", "add", &worktree_path.to_string_lossy(), branch])
            .current_dir(repo_path)
            .output()?;

        if !output.status.success() {
            let stderr = String::from_utf8_lossy(&output.stderr);
            anyhow::bail!("git worktree add failed: {stderr}");
        }

        Ok(())
    }

    fn create_branch_and_worktree(
        &self,
        repo_path: &Path,
        new_branch: &str,
        base: &str,
        worktree_path: &Path,
    ) -> Result<()> {
        let output = Command::new("git")
            .args([
                "worktree",
                "add",
                "-b",
                new_branch,
                &worktree_path.to_string_lossy(),
                base,
            ])
            .current_dir(repo_path)
            .output()?;

        if !output.status.success() {
            let stderr = String::from_utf8_lossy(&output.stderr);
            anyhow::bail!("git worktree add -b failed: {stderr}");
        }

        Ok(())
    }
}

#[cfg(test)]
mod tests {
    use super::*;
    use std::collections::HashMap;
    use std::fs;

    fn init_test_repo(dir: &Path) {
        Command::new("git")
            .args(["init"])
            .current_dir(dir)
            .output()
            .unwrap();
        Command::new("git")
            .args(["config", "user.email", "test@test.com"])
            .current_dir(dir)
            .output()
            .unwrap();
        Command::new("git")
            .args(["config", "user.name", "Test"])
            .current_dir(dir)
            .output()
            .unwrap();
        let dummy = dir.join("README.md");
        fs::write(&dummy, "# test").unwrap();
        Command::new("git")
            .args(["add", "."])
            .current_dir(dir)
            .output()
            .unwrap();
        Command::new("git")
            .args(["commit", "-m", "init"])
            .current_dir(dir)
            .output()
            .unwrap();
    }

    #[test]
    fn test_discover_repos() {
        let tmp = tempfile::tempdir().unwrap();
        let repo_dir = tmp.path().join("my-repo");
        fs::create_dir_all(&repo_dir).unwrap();
        init_test_repo(&repo_dir);

        fs::create_dir_all(tmp.path().join("not-a-repo")).unwrap();

        let provider = CliGitProvider;
        let repos = provider.discover_repos(&[(tmp.path().to_path_buf(), 1)]);
        assert_eq!(repos.len(), 1);
        assert_eq!(repos[0].name, "my-repo");
        assert_eq!(repos[0].session_name, "my-repo");
        assert_eq!(repos[0].worktrees.len(), 1);
        assert_eq!(repos[0].worktrees[0].branch.as_deref(), Some("master"));
    }

    #[test]
    fn test_discover_repos_sorted() {
        let tmp = tempfile::tempdir().unwrap();
        for name in ["zebra", "alpha", "Middle"] {
            let d = tmp.path().join(name);
            fs::create_dir_all(&d).unwrap();
            init_test_repo(&d);
        }

        let provider = CliGitProvider;
        let repos = provider.discover_repos(&[(tmp.path().to_path_buf(), 1)]);
        let names: Vec<&str> = repos.iter().map(|r| r.name.as_str()).collect();
        assert_eq!(names, vec!["alpha", "Middle", "zebra"]);
        // All should have unique names, so session_names should match names
        for repo in &repos {
            assert_eq!(repo.session_name, repo.name);
        }
    }

    #[test]
    fn test_discover_repos_collision_detection() {
        let tmp1 = tempfile::tempdir().unwrap();
        let tmp2 = tempfile::tempdir().unwrap();

        // Create repos with same name in different directories
        let repo1 = tmp1.path().join("myrepo");
        let repo2 = tmp2.path().join("myrepo");
        fs::create_dir_all(&repo1).unwrap();
        fs::create_dir_all(&repo2).unwrap();
        init_test_repo(&repo1);
        init_test_repo(&repo2);

        let provider = CliGitProvider;
        let repos = provider.discover_repos(&[
            (tmp1.path().to_path_buf(), 1),
            (tmp2.path().to_path_buf(), 1),
        ]);
        assert_eq!(repos.len(), 2);

        // Both should have same name but different session names
        assert_eq!(repos[0].name, "myrepo");
        assert_eq!(repos[1].name, "myrepo");

        // Session names should be disambiguated with parent dir names
        let session_names: std::collections::HashSet<String> =
            repos.iter().map(|r| r.session_name.clone()).collect();
        assert_eq!(session_names.len(), 2); // Both should be unique

        // Both should contain the repo name and parent dir somehow
        for repo in &repos {
            assert!(repo.session_name.contains("myrepo"));
            assert!(repo.session_name.contains("--"));
        }
    }

    #[test]
    fn test_list_branches() {
        let tmp = tempfile::tempdir().unwrap();
        init_test_repo(tmp.path());

        Command::new("git")
            .args(["branch", "feat/test"])
            .current_dir(tmp.path())
            .output()
            .unwrap();

        let provider = CliGitProvider;
        let branches = provider.list_branches(tmp.path());
        assert!(branches.contains(&"master".to_string()));
        assert!(branches.contains(&"feat/test".to_string()));
    }

    #[test]
    fn test_add_worktree() {
        let tmp = tempfile::tempdir().unwrap();
        let repo = tmp.path().join("repo");
        fs::create_dir_all(&repo).unwrap();
        init_test_repo(&repo);

        Command::new("git")
            .args(["branch", "feat/wt-test"])
            .current_dir(&repo)
            .output()
            .unwrap();

        let provider = CliGitProvider;
        let wt_path = tmp.path().join("repo-feat-wt-test");
        provider
            .add_worktree(&repo, "feat/wt-test", &wt_path)
            .unwrap();

        assert!(wt_path.exists());
        assert!(wt_path.join("README.md").exists());

        let worktrees = provider.list_worktrees(&repo);
        assert_eq!(worktrees.len(), 2);
    }

    #[test]
    fn test_create_branch_and_worktree() {
        let tmp = tempfile::tempdir().unwrap();
        let repo = tmp.path().join("repo");
        fs::create_dir_all(&repo).unwrap();
        init_test_repo(&repo);

        let provider = CliGitProvider;
        let wt_path = tmp.path().join("repo-new-branch");
        provider
            .create_branch_and_worktree(&repo, "new-branch", "master", &wt_path)
            .unwrap();

        assert!(wt_path.exists());
        let branches = provider.list_branches(&repo);
        assert!(branches.contains(&"new-branch".to_string()));
    }

    #[test]
    fn test_add_worktree_fails_for_nonexistent_branch() {
        let tmp = tempfile::tempdir().unwrap();
        init_test_repo(tmp.path());

        let provider = CliGitProvider;
        let wt_path = tmp.path().join("wt-nope");
        let result = provider.add_worktree(tmp.path(), "nonexistent-branch", &wt_path);
        assert!(result.is_err());
    }
}

impl CliGitProvider {
    fn scan_dir_recursive<'a>(
        &self,
        dir: &Path,
        search_root: &'a Path,
        depth: u16,
        repos: &mut Vec<(Repo, &'a Path)>,
    ) {
        let Ok(entries) = std::fs::read_dir(dir) else {
            return;
        };

        for entry in entries.flatten() {
            let path = entry.path();
            if !path.is_dir() {
                continue;
            }

            // If this directory is a git repo, add it
            if path.join(".git").exists() {
                if let Some(repo) = self.build_repo(&path) {
                    repos.push((repo, search_root));
                }
            } else if depth > 1 {
                // Recurse into subdirectories if we have remaining depth
                self.scan_dir_recursive(&path, search_root, depth - 1, repos);
            }
        }
    }

    fn build_repo(&self, path: &Path) -> Option<Repo> {
        let name = path.file_name()?.to_string_lossy().to_string();
        let worktrees = self.list_worktrees(path);
        Some(Repo {
            session_name: name.clone(),
            name,
            path: path.to_path_buf(),
            worktrees,
        })
    }

    fn main_worktree(repo_path: &Path) -> Worktree {
        let branch = Command::new("git")
            .args(["rev-parse", "--abbrev-ref", "HEAD"])
            .current_dir(repo_path)
            .output()
            .ok()
            .and_then(|o| {
                let s = String::from_utf8_lossy(&o.stdout).trim().to_string();
                if s.is_empty() { None } else { Some(s) }
            });

        Worktree {
            path: repo_path.to_path_buf(),
            branch,
            is_main: true,
        }
    }
}

#[cfg(test)]
mod tests {
    use super::*;
    use std::fs;

    fn init_test_repo(dir: &Path) {
        Command::new("git")
            .args(["init"])
            .current_dir(dir)
            .output()
            .unwrap();
        Command::new("git")
            .args(["config", "user.email", "test@test.com"])
            .current_dir(dir)
            .output()
            .unwrap();
        Command::new("git")
            .args(["config", "user.name", "Test"])
            .current_dir(dir)
            .output()
            .unwrap();
        let dummy = dir.join("README.md");
        fs::write(&dummy, "# test").unwrap();
        Command::new("git")
            .args(["add", "."])
            .current_dir(dir)
            .output()
            .unwrap();
        Command::new("git")
            .args(["commit", "-m", "init"])
            .current_dir(dir)
            .output()
            .unwrap();
    }

    #[test]
    fn test_discover_repos() {
        let tmp = tempfile::tempdir().unwrap();
        let repo_dir = tmp.path().join("my-repo");
        fs::create_dir_all(&repo_dir).unwrap();
        init_test_repo(&repo_dir);

        fs::create_dir_all(tmp.path().join("not-a-repo")).unwrap();

        let provider = CliGitProvider;
        let repos = provider.discover_repos(&[tmp.path().to_path_buf()]);
        assert_eq!(repos.len(), 1);
        assert_eq!(repos[0].name, "my-repo");
        assert_eq!(repos[0].worktrees.len(), 1);
        assert_eq!(repos[0].worktrees[0].branch.as_deref(), Some("master"));
    }

    #[test]
    fn test_discover_repos_sorted() {
        let tmp = tempfile::tempdir().unwrap();
        for name in ["zebra", "alpha", "Middle"] {
            let d = tmp.path().join(name);
            fs::create_dir_all(&d).unwrap();
            init_test_repo(&d);
        }

        let provider = CliGitProvider;
        let repos = provider.discover_repos(&[tmp.path().to_path_buf()]);
        let names: Vec<&str> = repos.iter().map(|r| r.name.as_str()).collect();
        assert_eq!(names, vec!["alpha", "Middle", "zebra"]);
    }

    #[test]
    fn test_list_branches() {
        let tmp = tempfile::tempdir().unwrap();
        init_test_repo(tmp.path());

        Command::new("git")
            .args(["branch", "feat/test"])
            .current_dir(tmp.path())
            .output()
            .unwrap();

        let provider = CliGitProvider;
        let branches = provider.list_branches(tmp.path());
        assert!(branches.contains(&"master".to_string()));
        assert!(branches.contains(&"feat/test".to_string()));
    }

    #[test]
    fn test_add_worktree() {
        let tmp = tempfile::tempdir().unwrap();
        let repo = tmp.path().join("repo");
        fs::create_dir_all(&repo).unwrap();
        init_test_repo(&repo);

        Command::new("git")
            .args(["branch", "feat/wt-test"])
            .current_dir(&repo)
            .output()
            .unwrap();

        let provider = CliGitProvider;
        let wt_path = tmp.path().join("repo-feat-wt-test");
        provider
            .add_worktree(&repo, "feat/wt-test", &wt_path)
            .unwrap();

        assert!(wt_path.exists());
        assert!(wt_path.join("README.md").exists());

        let worktrees = provider.list_worktrees(&repo);
        assert_eq!(worktrees.len(), 2);
    }

    #[test]
    fn test_create_branch_and_worktree() {
        let tmp = tempfile::tempdir().unwrap();
        let repo = tmp.path().join("repo");
        fs::create_dir_all(&repo).unwrap();
        init_test_repo(&repo);

        let provider = CliGitProvider;
        let wt_path = tmp.path().join("repo-new-branch");
        provider
            .create_branch_and_worktree(&repo, "new-branch", "master", &wt_path)
            .unwrap();

        assert!(wt_path.exists());
        let branches = provider.list_branches(&repo);
        assert!(branches.contains(&"new-branch".to_string()));
    }

    #[test]
    fn test_add_worktree_fails_for_nonexistent_branch() {
        let tmp = tempfile::tempdir().unwrap();
        init_test_repo(tmp.path());

        let provider = CliGitProvider;
        let wt_path = tmp.path().join("wt-nope");
        let result = provider.add_worktree(tmp.path(), "nonexistent-branch", &wt_path);
        assert!(result.is_err());
    }
}