worktrunk 0.36.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
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
//! Project-level configuration
//!
//! Configuration that is checked into the repository and shared across all developers.

use std::collections::BTreeMap;

use config::ConfigError;
use schemars::JsonSchema;
use serde::{Deserialize, Serialize};

use super::commands::CommandConfig;
use super::{CopyIgnoredConfig, HooksConfig, StepConfig};

/// Project-level configuration for `wt list` output.
///
/// This is distinct from user-level `ListConfig` which controls CLI defaults.
/// Project-level config is for project-specific features like dev server URLs.
///
/// # Example
///
/// ```toml
/// [list]
/// url = "http://localhost:{{ branch | hash_port }}"
/// ```
#[derive(Debug, Serialize, Deserialize, Clone, Default, PartialEq, JsonSchema)]
pub struct ProjectListConfig {
    /// URL template for dev server links shown in `wt list`.
    ///
    /// Available variable: `{{ branch }}` (the branch name).
    /// Available filters: `{{ branch | hash_port }}` (deterministic port 10000-19999),
    /// `{{ branch | sanitize }}` (filesystem-safe name).
    ///
    /// The URL is displayed with health-check styling: dim if the port is not
    /// listening, normal if it is.
    #[serde(default)]
    pub url: Option<String>,
}

/// Project-level CI configuration.
///
/// Override CI platform detection when URL-based detection fails (e.g., GitHub
/// Enterprise or self-hosted GitLab with custom domains).
///
/// # Example
///
/// ```toml
/// [ci]
/// platform = "github"  # or "gitlab"
/// ```
#[derive(Debug, Serialize, Deserialize, Clone, Default, PartialEq, JsonSchema)]
pub struct ProjectCiConfig {
    /// CI platform override. When set, skips URL-based platform detection.
    ///
    /// Values: "github" or "gitlab"
    #[serde(default)]
    pub platform: Option<String>,
}

/// Project-level forge configuration.
///
/// Override forge detection when URL-based detection fails (e.g., SSH host
/// aliases, GitHub Enterprise, or self-hosted GitLab with custom domains).
///
/// # Example
///
/// ```toml
/// [forge]
/// platform = "github"              # or "gitlab"
/// hostname = "github.example.com"  # API hostname for GHE / self-hosted GitLab
/// ```
#[derive(Debug, Serialize, Deserialize, Clone, Default, PartialEq, JsonSchema)]
pub struct ProjectForgeConfig {
    /// Forge platform override. When set, skips URL-based platform detection.
    ///
    /// Values: "github" or "gitlab"
    #[serde(default)]
    pub platform: Option<String>,

    /// API hostname for GitHub Enterprise or self-hosted GitLab.
    ///
    /// Only needed when the remote URL uses an SSH host alias that doesn't
    /// resolve to the real API hostname. For standard github.com/gitlab.com
    /// setups, this is not needed.
    #[serde(default)]
    pub hostname: Option<String>,
}

impl ProjectListConfig {
    /// Returns true if any list configuration is set.
    pub fn is_configured(&self) -> bool {
        self.url.is_some()
    }
}

impl ProjectConfig {
    /// Get the CI platform override if configured.
    ///
    /// Deprecated: use [`forge_platform()`](Self::forge_platform) instead.
    pub fn ci_platform(&self) -> Option<&str> {
        self.ci.as_ref().and_then(|ci| ci.platform.as_deref())
    }

    /// Get the forge platform override, checking `[forge]` first then `[ci]`.
    pub fn forge_platform(&self) -> Option<&str> {
        self.forge
            .as_ref()
            .and_then(|f| f.platform.as_deref())
            .or_else(|| self.ci_platform())
    }

    /// Get the forge API hostname if configured.
    pub fn forge_hostname(&self) -> Option<&str> {
        self.forge.as_ref().and_then(|f| f.hostname.as_deref())
    }

    /// Get `wt step copy-ignored` configuration if configured.
    pub fn copy_ignored(&self) -> Option<&CopyIgnoredConfig> {
        self.step
            .as_ref()
            .and_then(|step| step.copy_ignored.as_ref())
    }
}

/// Project-specific configuration with hooks.
///
/// This config is stored at `<repo>/.config/wt.toml` within the repository and
/// IS checked into git. It defines project-specific hooks that run automatically
/// during worktree operations. All developers working on the project share this config.
///
/// # Template Variables
///
/// All hooks support these template variables:
/// - `{{ repo }}` - Repository directory name (e.g., "myproject")
/// - `{{ repo_path }}` - Absolute path to repository root (e.g., "/path/to/myproject")
/// - `{{ branch }}` - Branch name (e.g., "feature/auth")
/// - `{{ worktree_name }}` - Worktree directory name (e.g., "myproject.feature-auth")
/// - `{{ worktree_path }}` - Absolute path to the worktree (e.g., "/path/to/myproject.feature-auth")
/// - `{{ primary_worktree_path }}` - Primary worktree path (main worktree for normal repos; default branch worktree for bare repos)
/// - `{{ default_branch }}` - Default branch name (e.g., "main")
/// - `{{ commit }}` - Current HEAD commit SHA (full 40-character hash)
/// - `{{ short_commit }}` - Current HEAD commit SHA (short 7-character hash)
/// - `{{ remote }}` - Primary remote name (e.g., "origin")
/// - `{{ upstream }}` - Upstream tracking branch (e.g., "origin/feature"), if configured
///
/// Merge-related hooks (`pre-commit`, `pre-merge`, `post-merge`) also support:
/// - `{{ target }}` - Target branch for the merge (e.g., "main")
///
/// # Filters
///
/// - `{{ branch | sanitize }}` - Replace `/` and `\` with `-` (e.g., "feature-auth")
/// - `{{ branch | hash_port }}` - Hash string to deterministic port (10000-19999)
#[derive(Debug, Serialize, Deserialize, Clone, Default, PartialEq, JsonSchema)]
pub struct ProjectConfig {
    /// Project hooks (same keys as user hooks, flattened at top level)
    #[serde(flatten, default)]
    pub hooks: HooksConfig,

    /// Configuration for `wt list` output
    #[serde(default)]
    pub list: Option<ProjectListConfig>,

    /// CI configuration (platform override). Deprecated: use `[forge]` instead.
    #[serde(default)]
    pub ci: Option<ProjectCiConfig>,

    /// Forge configuration (platform detection override, API hostname)
    #[serde(default)]
    pub forge: Option<ProjectForgeConfig>,

    /// Configuration for `wt step` subcommands.
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub step: Option<StepConfig>,

    /// \[experimental\] Command aliases for `wt step <name>`.
    ///
    /// Each alias maps a name to one or more command templates. All hook
    /// template variables are available (e.g., `{{ branch }}`, `{{ worktree_path }}`).
    ///
    /// Uses `CommandConfig` for consistency with hooks. This means the
    /// named-table format (`[aliases.deploy] build = "..." run = "..."`)
    /// technically works, but the single-string format is the expected usage.
    ///
    /// ```toml
    /// [aliases]
    /// deploy = "cd {{ worktree_path }} && make deploy"
    /// lint = "npm run lint"
    /// ```
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub aliases: Option<BTreeMap<String, CommandConfig>>,
}

impl ProjectConfig {
    /// Load project configuration from .config/wt.toml in the repository root
    ///
    /// Set `write_hints` to true for normal usage. Set to false during completion
    /// to avoid side effects (writing git config hints).
    pub fn load(
        repo: &crate::git::Repository,
        write_hints: bool,
    ) -> Result<Option<Self>, ConfigError> {
        let config_path = match repo
            .project_config_path()
            .map_err(|e| ConfigError::Message(format!("Failed to get config path: {}", e)))?
        {
            Some(path) if path.exists() => path,
            _ => return Ok(None),
        };

        // Load directly with toml crate to preserve insertion order (with preserve_order feature)
        let contents = std::fs::read_to_string(&config_path)
            .map_err(|e| ConfigError::Message(format!("Failed to read config file: {}", e)))?;

        // Check for deprecated template variables and create migration file if needed
        // Only write migration file in main worktree, not linked worktrees
        // Use show_brief_warning=true to emit a brief pointer to `wt config show`
        let is_main_worktree = !repo.current_worktree().is_linked().unwrap_or(true);
        let repo_for_hints = if write_hints { Some(repo) } else { None };
        let _ = super::deprecation::check_and_migrate(
            &config_path,
            &contents,
            is_main_worktree,
            "Project config",
            repo_for_hints,
            true, // show_brief_warning
        );

        // Warn about unknown fields (only in main worktree where it's actionable)
        if is_main_worktree {
            super::deprecation::warn_unknown_fields::<ProjectConfig>(
                &config_path,
                &find_unknown_keys(&contents),
                "Project config",
            );
        }

        let config: ProjectConfig = toml::from_str(&contents).map_err(|e| {
            ConfigError::Message(format!(
                "Project config at {} failed to parse:\n{e}",
                crate::path::format_path_for_display(&config_path),
            ))
        })?;

        Ok(Some(config))
    }
}

/// Returns all valid top-level keys in project config, derived from the JsonSchema.
///
/// This includes keys from ProjectConfig and HooksConfig (flattened).
/// Public for use by the `WorktrunkConfig` trait implementation.
pub fn valid_project_config_keys() -> Vec<String> {
    use schemars::SchemaGenerator;

    let schema = SchemaGenerator::default().into_root_schema_for::<ProjectConfig>();

    schema
        .as_object()
        .and_then(|obj| obj.get("properties"))
        .and_then(|p| p.as_object())
        .map(|props| props.keys().cloned().collect())
        .unwrap_or_default()
}

/// Find unknown keys in project config TOML content
///
/// Returns a map of unrecognized top-level keys (with their values) that will be ignored.
/// Compares against the known valid keys derived from the JsonSchema.
/// The values are included to allow checking if keys belong in the other config type.
pub fn find_unknown_keys(contents: &str) -> std::collections::HashMap<String, toml::Value> {
    let Ok(table) = contents.parse::<toml::Table>() else {
        return std::collections::HashMap::new();
    };

    let valid_keys = valid_project_config_keys();

    table
        .into_iter()
        .filter(|(key, _)| !valid_keys.contains(key))
        .collect()
}

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

    #[test]
    fn test_deserialize_all_hooks() {
        let contents = r#"
post-create = "npm install"
post-start = "npm run watch"
post-switch = "rename-tab"
pre-commit = "cargo fmt --check"
pre-merge = "cargo test"
post-merge = "git push"
pre-remove = "echo bye"
"#;
        let config: ProjectConfig = toml::from_str(contents).unwrap();
        assert!(config.hooks.post_create.is_some());
        assert!(config.hooks.post_start.is_some());
        assert!(config.hooks.post_switch.is_some());
        assert!(config.hooks.pre_commit.is_some());
        assert!(config.hooks.pre_merge.is_some());
        assert!(config.hooks.post_merge.is_some());
        assert!(config.hooks.pre_remove.is_some());
    }

    // ============================================================================
    // ListConfig Tests
    // ============================================================================

    #[test]
    fn test_deserialize_list_url() {
        let contents = r#"
[list]
url = "http://localhost:{{ branch | hash_port }}"
"#;
        let config: ProjectConfig = toml::from_str(contents).unwrap();
        assert!(config.list.is_some());
        let list = config.list.unwrap();
        assert_eq!(
            list.url.as_deref(),
            Some("http://localhost:{{ branch | hash_port }}")
        );
        assert!(list.is_configured());
    }

    #[test]
    fn test_deserialize_list_empty() {
        let contents = r#"
[list]
"#;
        let config: ProjectConfig = toml::from_str(contents).unwrap();
        assert!(config.list.is_some());
        let list = config.list.unwrap();
        assert!(list.url.is_none());
        assert!(!list.is_configured());
    }

    #[test]
    fn test_deserialize_step_copy_ignored() {
        let contents = r#"
[step.copy-ignored]
exclude = [".conductor/", ".entire/"]
"#;
        let config: ProjectConfig = toml::from_str(contents).unwrap();
        assert_eq!(
            config.copy_ignored().unwrap().exclude,
            vec![".conductor/".to_string(), ".entire/".to_string()]
        );
    }

    // ============================================================================
    // CiConfig Tests
    // ============================================================================

    #[test]
    fn test_deserialize_ci_platform_github() {
        let contents = r#"
[ci]
platform = "github"
"#;
        let config: ProjectConfig = toml::from_str(contents).unwrap();
        assert!(config.ci.is_some());
        let ci = config.ci.unwrap();
        assert_eq!(ci.platform.as_deref(), Some("github"));
    }

    #[test]
    fn test_deserialize_ci_platform_gitlab() {
        let contents = r#"
[ci]
platform = "gitlab"
"#;
        let config: ProjectConfig = toml::from_str(contents).unwrap();
        assert!(config.ci.is_some());
        let ci = config.ci.unwrap();
        assert_eq!(ci.platform.as_deref(), Some("gitlab"));
    }

    #[test]
    fn test_deserialize_ci_empty() {
        let contents = r#"
[ci]
"#;
        let config: ProjectConfig = toml::from_str(contents).unwrap();
        assert!(config.ci.is_some());
        let ci = config.ci.unwrap();
        assert!(ci.platform.is_none());
    }

    #[test]
    fn test_ci_config_default() {
        let config = ProjectCiConfig::default();
        assert!(config.platform.is_none());
    }

    // ============================================================================
    // ForgeConfig Tests
    // ============================================================================

    #[test]
    fn test_deserialize_forge_platform() {
        let contents = r#"
[forge]
platform = "github"
"#;
        let config: ProjectConfig = toml::from_str(contents).unwrap();
        assert_eq!(config.forge_platform(), Some("github"));
        assert!(config.forge_hostname().is_none());
    }

    #[test]
    fn test_deserialize_forge_hostname() {
        let contents = r#"
[forge]
platform = "github"
hostname = "github.example.com"
"#;
        let config: ProjectConfig = toml::from_str(contents).unwrap();
        assert_eq!(config.forge_platform(), Some("github"));
        assert_eq!(config.forge_hostname(), Some("github.example.com"));
    }

    #[test]
    fn test_forge_platform_falls_back_to_ci() {
        let contents = r#"
[ci]
platform = "gitlab"
"#;
        let config: ProjectConfig = toml::from_str(contents).unwrap();
        // forge.platform not set, falls back to ci.platform
        assert_eq!(config.forge_platform(), Some("gitlab"));
    }

    #[test]
    fn test_forge_platform_takes_precedence_over_ci() {
        let contents = r#"
[ci]
platform = "gitlab"

[forge]
platform = "github"
"#;
        let config: ProjectConfig = toml::from_str(contents).unwrap();
        // forge.platform takes precedence
        assert_eq!(config.forge_platform(), Some("github"));
        // ci.platform still accessible directly
        assert_eq!(config.ci_platform(), Some("gitlab"));
    }

    #[test]
    fn test_forge_config_default() {
        let config = ProjectForgeConfig::default();
        assert!(config.platform.is_none());
        assert!(config.hostname.is_none());
    }

    // ============================================================================
    // find_unknown_keys Tests
    // ============================================================================

    #[test]
    fn test_find_unknown_keys_empty() {
        let contents = "";
        let keys = find_unknown_keys(contents);
        assert!(keys.is_empty());
    }

    #[test]
    fn test_find_unknown_keys_all_known() {
        let contents = r#"
post-create = "npm install"
pre-merge = "cargo test"

[step.copy-ignored]
exclude = [".conductor/"]
"#;
        let keys = find_unknown_keys(contents);
        assert!(keys.is_empty());
    }

    #[test]
    fn test_find_unknown_keys_unknown_key() {
        let contents = r#"
post-create = "npm install"
unknown-key = "value"
"#;
        let keys = find_unknown_keys(contents);
        assert_eq!(keys.len(), 1);
        assert!(keys.contains_key("unknown-key"));
    }

    #[test]
    fn test_find_unknown_keys_multiple_unknown() {
        let contents = r#"
foo = "bar"
baz = "qux"
post-create = "npm install"
"#;
        let keys = find_unknown_keys(contents);
        assert_eq!(keys.len(), 2);
        assert!(keys.contains_key("foo"));
        assert!(keys.contains_key("baz"));
    }

    // ============================================================================
    // Serialization Tests
    // ============================================================================

    #[test]
    fn test_serialize_empty_config() {
        let config = ProjectConfig::default();
        let serialized = toml::to_string(&config).unwrap();
        // Default config should serialize to empty or minimal string
        assert!(serialized.is_empty() || serialized.trim().is_empty());
    }

    #[test]
    fn test_config_equality() {
        let config1 = ProjectConfig::default();
        let config2 = ProjectConfig::default();
        assert_eq!(config1, config2);
    }

    #[test]
    fn test_config_clone() {
        let contents = r#"pre-merge = "cargo test""#;
        let config: ProjectConfig = toml::from_str(contents).unwrap();
        let cloned = config.clone();
        assert_eq!(config, cloned);
    }
}