worktrunk 0.40.0

A CLI for Git worktree management, designed for parallel AI agent workflows
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
506
507
508
509
510
511
512
513
514
515
516
//! Tests for template expansion with special characters and edge cases
//!
//! These tests target potential shell injection vulnerabilities and
//! edge cases in template variable substitution.

use super::expand_template;
use crate::testing::TestRepo;
use std::collections::HashMap;

fn test_repo() -> TestRepo {
    TestRepo::new()
}

/// Helper to build vars with common fields
fn vars_with_branch(branch: &str) -> HashMap<&str, &str> {
    let mut vars = HashMap::new();
    vars.insert("branch", branch);
    vars.insert("main_worktree", "myrepo");
    vars.insert("repo", "myrepo");
    vars
}

#[test]
fn test_expand_template_normal() {
    let test = test_repo();
    let vars = vars_with_branch("feature");
    let result = expand_template(
        "echo {{ branch }} {{ main_worktree }}",
        &vars,
        true,
        &test.repo,
        "test",
    )
    .unwrap();
    assert_eq!(result, "echo feature myrepo");
}

#[test]
fn test_expand_template_branch_with_slashes() {
    let test = test_repo();
    // Use {{ branch | sanitize }} to replace slashes with dashes
    let vars = vars_with_branch("feature/nested/branch");
    let result = expand_template(
        "echo {{ branch | sanitize }}",
        &vars,
        true,
        &test.repo,
        "test",
    )
    .unwrap();
    assert_eq!(result, "echo feature-nested-branch");
}

#[test]
fn test_expand_template_sanitize_hash_filter() {
    let test = test_repo();

    // Already-safe names pass through unchanged (no hash suffix)
    let vars = vars_with_branch("server");
    let result = expand_template(
        "{{ branch | sanitize_hash }}",
        &vars,
        false,
        &test.repo,
        "test",
    )
    .unwrap();
    assert_eq!(result, "server");

    // Unsafe characters are replaced and a 3-char hash suffix is appended
    let vars = vars_with_branch("feature/auth");
    let result = expand_template(
        "{{ branch | sanitize_hash }}",
        &vars,
        false,
        &test.repo,
        "test",
    )
    .unwrap();
    assert!(result.starts_with("feature-auth-"), "got: {result}");
    assert_eq!(result.len(), "feature-auth-".len() + 3, "got: {result}");

    // Empty input becomes "_empty-<hash>"
    let mut vars = HashMap::new();
    vars.insert("name", "");
    let result = expand_template(
        "{{ name | sanitize_hash }}",
        &vars,
        false,
        &test.repo,
        "test",
    )
    .unwrap();
    assert!(result.starts_with("_empty-"), "got: {result}");
    assert_eq!(result.len(), "_empty-".len() + 3, "got: {result}");
}

#[test]
fn test_expand_template_branch_raw_with_slashes() {
    let test = test_repo();
    // Raw branch preserves slashes
    let vars = vars_with_branch("feature/nested/branch");
    let result = expand_template("echo {{ branch }}", &vars, true, &test.repo, "test").unwrap();
    assert_eq!(result, "echo feature/nested/branch");
}

// Tests with platform-specific shell escaping (Unix uses single quotes, Windows uses double quotes)
#[test]
#[cfg(unix)]
fn test_expand_template_branch_escaping() {
    let test = test_repo();
    let expand = |input| {
        expand_template(
            "echo {{ branch }}",
            &vars_with_branch(input),
            true,
            &test.repo,
            "test",
        )
        .unwrap()
    };

    assert_eq!(expand("feature name"), "echo 'feature name'"); // spaces
    assert_eq!(expand("feature$(whoami)"), "echo 'feature$(whoami)'"); // command sub
    assert_eq!(expand("feature`id`"), "echo 'feature`id`'"); // backticks
}

#[test]
#[cfg(unix)]
fn snapshot_expand_template_branch_with_quotes() {
    let test = test_repo();
    let vars = vars_with_branch("feature'test");
    let result = expand_template("echo '{{ branch }}'", &vars, true, &test.repo, "test").unwrap();
    insta::assert_snapshot!(result, @r"echo ''feature'\''test''");
}

#[test]
#[cfg(unix)]
fn test_expand_template_extra_vars_path_escaping() {
    let test = test_repo();
    let expand = |path| {
        expand_template(
            "cd {{ worktree }}",
            &HashMap::from([("worktree", path)]),
            true,
            &test.repo,
            "test",
        )
        .unwrap()
    };

    assert_eq!(
        expand("/path with spaces/to/wt"),
        "cd '/path with spaces/to/wt'"
    ); // spaces
    assert_eq!(expand("/path/$USER/worktree"), "cd '/path/$USER/worktree'"); // dollar sign
}

#[test]
#[cfg(unix)]
fn snapshot_expand_template_extra_vars_with_command_substitution() {
    let test = test_repo();
    let mut extras = HashMap::new();
    extras.insert("target", "main; rm -rf /");
    let result =
        expand_template("git merge {{ target }}", &extras, true, &test.repo, "test").unwrap();

    insta::assert_snapshot!(result, @"git merge 'main; rm -rf /'");
}

#[test]
fn test_expand_template_variable_override() {
    let test = test_repo();
    // Variables in the hashmap take precedence
    let mut vars = HashMap::new();
    vars.insert("branch", "overridden");
    let result = expand_template("echo {{ branch }}", &vars, true, &test.repo, "test").unwrap();

    assert_eq!(result, "echo overridden");
}

#[test]
fn test_expand_template_missing_variable() {
    let test = test_repo();
    // Undefined variables error in SemiStrict mode (catches typos)
    let vars: HashMap<&str, &str> = HashMap::new();
    let result = expand_template("echo {{ undefined }}", &vars, true, &test.repo, "test");

    assert!(result.is_err());
    let err = result.unwrap_err();
    assert!(
        err.message.contains("undefined value"),
        "got: {}",
        err.message
    );
}

#[test]
#[cfg(unix)]
fn test_expand_template_empty_branch() {
    let test = test_repo();
    let mut vars = HashMap::new();
    vars.insert("branch", "");
    let result = expand_template("echo {{ branch }}", &vars, true, &test.repo, "test").unwrap();

    // Empty string is shell-escaped to ''
    assert_eq!(result, "echo ''");
}

#[test]
#[cfg(unix)]
fn test_expand_template_unicode_in_branch() {
    let test = test_repo();
    // Unicode characters in branch name are shell-escaped
    let vars = vars_with_branch("feature-\u{1F680}");
    let result = expand_template("echo {{ branch }}", &vars, true, &test.repo, "test").unwrap();

    // Unicode is preserved but quoted for shell safety
    assert_eq!(result, "echo 'feature-\u{1F680}'");
}

#[test]
fn test_expand_template_backslash_in_branch() {
    let test = test_repo();
    // Use {{ branch | sanitize }} to replace backslashes with dashes
    // Note: shell_escape=false to test sanitize filter in isolation
    let vars = vars_with_branch(r"feature\branch");
    let result = expand_template(
        "path/{{ branch | sanitize }}",
        &vars,
        false,
        &test.repo,
        "test",
    )
    .unwrap();

    // Backslashes are replaced with dashes by sanitize filter
    assert_eq!(result, "path/feature-branch");
}

#[test]
fn test_expand_template_multiple_replacements() {
    let test = test_repo();
    let mut vars = vars_with_branch("feature");
    vars.insert("worktree", "/path/to/wt");
    vars.insert("target", "develop");

    let result = expand_template(
        "cd {{ worktree }} && git merge {{ target }} from {{ branch }}",
        &vars,
        true,
        &test.repo,
        "test",
    )
    .unwrap();

    assert_eq!(result, "cd /path/to/wt && git merge develop from feature");
}

#[test]
fn test_expand_template_curly_braces_without_variables() {
    let test = test_repo();
    // Just curly braces, not variables
    let vars: HashMap<&str, &str> = HashMap::new();
    let result = expand_template("echo {}", &vars, true, &test.repo, "test").unwrap();

    assert_eq!(result, "echo {}");
}

#[test]
fn test_expand_template_nested_curly_braces() {
    let test = test_repo();
    // Nested braces - minijinja doesn't support {{{ syntax, use literal curly braces instead
    let vars = vars_with_branch("main");
    let result = expand_template(
        "echo {{ '{' ~ branch ~ '}' }}",
        &vars,
        true,
        &test.repo,
        "test",
    )
    .unwrap();

    // Renders as '{main}' — curly braces are shell metacharacters (brace expansion)
    // so the formatter correctly escapes the concatenated result
    assert_eq!(result, "echo '{main}'");
}

// Snapshot tests for shell escaping behavior
// These verify the exact shell-escaped output for security-critical cases
//
// Unix-only: Shell escaping is platform-dependent (Unix uses single quotes,
// Windows uses double quotes). These snapshots verify Unix shell behavior.

#[test]
#[cfg(unix)]
fn snapshot_shell_escaping_special_chars() {
    // Test various shell special characters
    let test_cases = vec![
        ("spaces", "feature name"),
        ("dollar", "feature$USER"),
        ("command_sub", "feature$(whoami)"),
        ("backticks", "feature`id`"),
        ("semicolon", "feature;rm -rf /"),
        ("pipe", "feature|grep foo"),
        ("ampersand", "feature&background"),
        ("redirect", "feature>output.txt"),
        ("wildcard", "feature*glob"),
        ("question", "feature?char"),
        ("brackets", "feature[0-9]"),
    ];

    let test = test_repo();
    let mut results = Vec::new();
    for (name, branch) in test_cases {
        let vars = vars_with_branch(branch);
        let result = expand_template("echo {{ branch }}", &vars, true, &test.repo, "test").unwrap();
        results.push((name, branch, result));
    }

    insta::assert_yaml_snapshot!(results);
}

#[test]
#[cfg(unix)]
fn snapshot_shell_escaping_quotes() {
    // Test quote handling
    let test_cases = vec![
        ("single_quote", "feature'test"),
        ("double_quote", "feature\"test"),
        ("mixed_quotes", "feature'test\"mixed"),
        ("multiple_single", "don't'panic"),
    ];

    let test = test_repo();
    let mut results = Vec::new();
    for (name, branch) in test_cases {
        let vars = vars_with_branch(branch);
        let result = expand_template("echo {{ branch }}", &vars, true, &test.repo, "test").unwrap();
        results.push((name, branch, result));
    }

    insta::assert_yaml_snapshot!(results);
}

#[test]
#[cfg(unix)]
fn snapshot_shell_escaping_paths() {
    // Test path escaping with various special characters
    let test_cases = vec![
        ("spaces", "/path with spaces/to/worktree"),
        ("dollar", "/path/$USER/worktree"),
        ("tilde", "~/worktree"),
        ("special_chars", "/path/to/worktree (new)"),
        ("unicode", "/path/to/\u{1F680}/worktree"),
    ];

    let test = test_repo();
    let mut results = Vec::new();
    for (name, path) in test_cases {
        let mut vars = vars_with_branch("main");
        vars.insert("worktree", path);
        let result = expand_template(
            "cd {{ worktree }} && echo {{ branch }}",
            &vars,
            true,
            &test.repo,
            "test",
        )
        .unwrap();
        results.push((name, path, result));
    }

    insta::assert_yaml_snapshot!(results);
}

#[test]
#[cfg(unix)]
fn snapshot_complex_templates() {
    // Test realistic complex template commands
    // Note: {{ branch | sanitize }} is used when branch sanitization is needed
    let test_cases = vec![
        (
            "cd_and_merge",
            "cd {{ worktree }} && git merge {{ target }}",
            "feature branch",
        ),
        (
            "npm_install",
            "cd {{ main_worktree }}/{{ branch | sanitize }} && npm install",
            "feature/new-ui",
        ),
        (
            "echo_vars",
            "echo 'Branch: {{ branch }}' 'Worktree: {{ worktree }}'",
            "test$injection",
        ),
    ];

    let test = test_repo();
    let mut results = Vec::new();
    for (name, template, branch) in test_cases {
        let mut vars = HashMap::new();
        vars.insert("branch", branch);
        vars.insert("main_worktree", "/repo/path");
        vars.insert("worktree", "/path with spaces/wt");
        vars.insert("target", "main; rm -rf /");
        let result = expand_template(template, &vars, true, &test.repo, "test").unwrap();
        results.push((name, template, branch, result));
    }

    insta::assert_yaml_snapshot!(results);
}

// Tests for literal expansion (shell_escape=false)

#[test]
fn test_expand_template_literal_normal() {
    let test = test_repo();
    let mut vars = HashMap::new();
    vars.insert("main_worktree", "myrepo");
    vars.insert("branch", "feature");
    let result = expand_template(
        "{{ main_worktree }}.{{ branch }}",
        &vars,
        false,
        &test.repo,
        "test",
    )
    .unwrap();
    assert_eq!(result, "myrepo.feature");
}

#[test]
fn test_expand_template_literal_unicode_no_escaping() {
    let test = test_repo();
    // Unicode should NOT be shell-escaped in filesystem paths
    let mut vars = HashMap::new();
    vars.insert("main_worktree", "myrepo");
    vars.insert("branch", "test-\u{2282}");
    let result = expand_template(
        "{{ main_worktree }}.{{ branch }}",
        &vars,
        false,
        &test.repo,
        "test",
    )
    .unwrap();
    // Path should contain literal unicode, NO quotes
    assert_eq!(result, "myrepo.test-\u{2282}");
    assert!(
        !result.contains('\''),
        "Path should not contain shell quotes"
    );
}

#[test]
fn test_expand_template_literal_spaces_no_escaping() {
    let test = test_repo();
    // Spaces should NOT be shell-escaped (filesystem paths can have spaces)
    let mut vars = HashMap::new();
    vars.insert("main_worktree", "my repo");
    vars.insert("branch", "feature name");
    let result = expand_template(
        "{{ main_worktree }}.{{ branch }}",
        &vars,
        false,
        &test.repo,
        "test",
    )
    .unwrap();
    // No shell quotes around spaces
    assert_eq!(result, "my repo.feature name");
    assert!(
        !result.contains('\''),
        "Path should not contain shell quotes"
    );
}

#[test]
fn test_expand_template_literal_sanitizes_slashes() {
    let test = test_repo();
    // Use {{ branch | sanitize }} to replace slashes with dashes
    let mut vars = HashMap::new();
    vars.insert("main_worktree", "myrepo");
    vars.insert("branch", "feature/nested/branch");
    let result = expand_template(
        "{{ main_worktree }}.{{ branch | sanitize }}",
        &vars,
        false,
        &test.repo,
        "test",
    )
    .unwrap();
    assert_eq!(result, "myrepo.feature-nested-branch");
}

#[test]
#[cfg(unix)]
fn test_expand_template_literal_vs_escaped_unicode() {
    let test = test_repo();
    // Demonstrate the difference between literal and escaped expansion
    let mut vars = HashMap::new();
    vars.insert("main_worktree", "myrepo");
    vars.insert("branch", "test-\u{2282}");
    let template = "{{ main_worktree }}.{{ branch }}";

    let literal_result = expand_template(template, &vars, false, &test.repo, "test").unwrap();
    let escaped_result = expand_template(template, &vars, true, &test.repo, "test").unwrap();

    // Literal has no quotes
    assert_eq!(literal_result, "myrepo.test-\u{2282}");
    // Escaped has shell quotes around the unicode part
    // (shell_escape only quotes strings containing special chars)
    assert_eq!(escaped_result, "myrepo.'test-\u{2282}'");
}