stax 0.50.2

Fast stacked Git branches and PRs
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
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
use anyhow::{Context, Result};
use serde::{Deserialize, Serialize};
use std::fs;
use std::path::PathBuf;
use std::process::Command;

use crate::remote::ForgeType;

/// Main config (safe to commit to dotfiles)
#[derive(Debug, Serialize, Deserialize, Default)]
pub struct Config {
    #[serde(default)]
    pub branch: BranchConfig,
    #[serde(default)]
    pub remote: RemoteConfig,
    #[serde(default)]
    pub submit: SubmitConfig,
    #[serde(default)]
    pub ui: UiConfig,
    #[serde(default)]
    pub ai: AiConfig,
    #[serde(default)]
    pub auth: AuthConfig,
    #[serde(default)]
    pub worktree: WorktreeConfig,
}

#[derive(Debug, Serialize, Deserialize)]
pub struct BranchConfig {
    /// Prefix for new branches (e.g., "cesar/")
    /// DEPRECATED: Use `format` instead. Kept for backward compatibility.
    #[serde(default)]
    pub prefix: Option<String>,
    /// Whether to add date to branch names
    /// DEPRECATED: Use `format` instead. Kept for backward compatibility.
    #[serde(default)]
    pub date: bool,
    /// Date format string (default: "%m-%d", e.g., "01-19")
    /// Use chrono strftime format: %Y=year, %m=month, %d=day
    #[serde(default = "default_date_format")]
    pub date_format: String,
    /// Character to replace spaces and special chars (default: "-")
    #[serde(default = "default_replacement")]
    pub replacement: String,
    /// Branch name format template. Placeholders:
    /// - {user}: Git username (from config.branch.user or git user.name)
    /// - {date}: Current date (formatted by date_format)
    /// - {message}: The branch name/message input
    ///
    /// Examples: "{message}", "{user}/{message}", "{user}/{date}/{message}"
    #[serde(default)]
    pub format: Option<String>,
    /// Username for branch naming. If not set, uses git config user.name
    #[serde(default)]
    pub user: Option<String>,
}

#[derive(Debug, Serialize, Deserialize)]
pub struct RemoteConfig {
    /// Git remote name (default: "origin")
    #[serde(default = "default_remote_name")]
    pub name: String,
    /// Base web URL for GitHub (e.g., https://github.com or GitHub Enterprise URL)
    #[serde(default = "default_remote_base_url")]
    pub base_url: String,
    /// API base URL (GitHub Enterprise), e.g., https://github.company.com/api/v3
    #[serde(default)]
    pub api_base_url: Option<String>,
    /// Explicit forge type override: "github", "gitlab", or "gitea" / "forgejo".
    /// When set, skips auto-detection from the remote hostname.
    #[serde(default)]
    pub forge: Option<ForgeType>,
}

#[derive(Debug, Serialize, Deserialize, Default)]
pub struct SubmitConfig {
    /// Where stax-managed stack links should be synced on submit.
    #[serde(default)]
    pub stack_links: StackLinksMode,
}

#[derive(Debug, Clone, Copy, Serialize, Deserialize, PartialEq, Eq, Default)]
#[serde(rename_all = "lowercase")]
pub enum StackLinksMode {
    #[default]
    Comment,
    Body,
    Both,
    Off,
}

#[derive(Debug, Serialize, Deserialize)]
pub struct UiConfig {
    /// Whether to show contextual tips/suggestions (default: true)
    #[serde(default = "default_tips")]
    pub tips: bool,
}

#[derive(Debug, Serialize, Deserialize, Default, Clone)]
pub struct AiFeatureConfig {
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub agent: Option<String>,
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub model: Option<String>,
}

#[derive(Debug, Serialize, Deserialize, Default)]
pub struct AiConfig {
    /// AI agent to use: "claude", "codex", "gemini", or "opencode" (default: auto-detect)
    #[serde(default)]
    pub agent: Option<String>,
    /// Model to use with the AI agent (default: agent's own default)
    #[serde(default)]
    pub model: Option<String>,
    /// Per-feature overrides for PR body generation (`stax generate`, `stax submit --ai-body`)
    #[serde(default, skip_serializing_if = "AiFeatureConfig::is_empty")]
    pub generate: AiFeatureConfig,
    /// Per-feature overrides for standup summaries (`stax standup --summary`)
    #[serde(default, skip_serializing_if = "AiFeatureConfig::is_empty")]
    pub standup: AiFeatureConfig,
    /// Per-feature overrides for conflict resolution (`stax resolve`)
    #[serde(default, skip_serializing_if = "AiFeatureConfig::is_empty")]
    pub resolve: AiFeatureConfig,
    /// Per-feature overrides for interactive AI lanes (`stax lane`)
    #[serde(default, skip_serializing_if = "AiFeatureConfig::is_empty")]
    pub lane: AiFeatureConfig,
}

impl AiFeatureConfig {
    pub fn is_empty(&self) -> bool {
        self.agent.is_none() && self.model.is_none()
    }
}

impl AiConfig {
    /// Return a mutable reference to the per-feature config for `feature`.
    /// Returns `None` for unknown feature keys.
    pub fn feature_config_mut(&mut self, feature: &str) -> Option<&mut AiFeatureConfig> {
        match feature {
            "generate" => Some(&mut self.generate),
            "standup" => Some(&mut self.standup),
            "resolve" => Some(&mut self.resolve),
            "lane" => Some(&mut self.lane),
            _ => None,
        }
    }

    /// Resolve the agent for a given feature, falling back to the global default.
    pub fn agent_for(&self, feature: &str) -> Option<&str> {
        let feature_cfg = match feature {
            "generate" => &self.generate,
            "standup" => &self.standup,
            "resolve" => &self.resolve,
            "lane" => &self.lane,
            _ => return self.agent.as_deref(),
        };
        feature_cfg
            .agent
            .as_deref()
            .filter(|a| !a.is_empty())
            .or(self.agent.as_deref())
    }

    /// Resolve the model for a given feature, falling back to the global default.
    pub fn model_for(&self, feature: &str) -> Option<&str> {
        let feature_cfg = match feature {
            "generate" => &self.generate,
            "standup" => &self.standup,
            "resolve" => &self.resolve,
            "lane" => &self.lane,
            _ => return self.model.as_deref(),
        };
        feature_cfg
            .model
            .as_deref()
            .filter(|m| !m.is_empty())
            .or(self.model.as_deref())
    }
}

#[derive(Debug, Serialize, Deserialize)]
pub struct AuthConfig {
    /// Whether to use `gh auth token` as a fallback auth source (default: true)
    #[serde(default = "default_use_gh_cli")]
    pub use_gh_cli: bool,
    /// Whether to allow ambient GITHUB_TOKEN env var (default: false)
    #[serde(default = "default_allow_github_token_env")]
    pub allow_github_token_env: bool,
    /// Optional GitHub hostname for `gh auth token --hostname` (enterprise)
    #[serde(default)]
    pub gh_hostname: Option<String>,
}

#[derive(Debug, Serialize, Deserialize)]
pub struct WorktreeConfig {
    /// Directory for stax-managed worktrees. Empty means the default external root:
    /// ~/.stax/worktrees/<repo>.
    #[serde(default = "default_worktree_root_dir")]
    pub root_dir: String,
    #[serde(default)]
    pub hooks: WorktreeHooksConfig,
}

#[derive(Debug, Serialize, Deserialize, Default)]
pub struct WorktreeHooksConfig {
    /// Blocking hook run after creating a worktree and before launch
    #[serde(default)]
    pub post_create: Option<String>,
    /// Background hook run after a new worktree is ready
    #[serde(default)]
    pub post_start: Option<String>,
    /// Background hook run after jumping to an existing worktree
    #[serde(default)]
    pub post_go: Option<String>,
    /// Blocking hook run before removing a worktree
    #[serde(default)]
    pub pre_remove: Option<String>,
    /// Background hook run after removing a worktree
    #[serde(default)]
    pub post_remove: Option<String>,
}

impl Default for WorktreeConfig {
    fn default() -> Self {
        Self {
            root_dir: default_worktree_root_dir(),
            hooks: WorktreeHooksConfig::default(),
        }
    }
}

#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub enum GitHubAuthSource {
    StaxGithubTokenEnv,
    CredentialsFile,
    GhCli,
    GithubTokenEnv,
}

impl GitHubAuthSource {
    pub fn display_name(self) -> &'static str {
        match self {
            Self::StaxGithubTokenEnv => "STAX_GITHUB_TOKEN",
            Self::CredentialsFile => "credentials file (~/.config/stax/.credentials)",
            Self::GhCli => "gh auth token",
            Self::GithubTokenEnv => "GITHUB_TOKEN",
        }
    }
}

#[derive(Debug, Clone)]
pub struct GitHubAuthStatus {
    pub active_source: Option<GitHubAuthSource>,
    pub stax_env_available: bool,
    pub credentials_file_available: bool,
    pub gh_cli_available: bool,
    pub github_env_available: bool,
    pub use_gh_cli: bool,
    pub allow_github_token_env: bool,
    pub gh_hostname: Option<String>,
}

impl Default for BranchConfig {
    fn default() -> Self {
        Self {
            prefix: None,
            date: false,
            date_format: default_date_format(),
            replacement: default_replacement(),
            format: None,
            user: None,
        }
    }
}

fn default_date_format() -> String {
    "%m-%d".to_string()
}

impl Default for RemoteConfig {
    fn default() -> Self {
        Self {
            name: default_remote_name(),
            base_url: default_remote_base_url(),
            api_base_url: None,
            forge: None,
        }
    }
}

impl Default for UiConfig {
    fn default() -> Self {
        Self {
            tips: default_tips(),
        }
    }
}

impl Default for AuthConfig {
    fn default() -> Self {
        Self {
            use_gh_cli: default_use_gh_cli(),
            allow_github_token_env: default_allow_github_token_env(),
            gh_hostname: None,
        }
    }
}

fn default_replacement() -> String {
    "-".to_string()
}

fn default_worktree_root_dir() -> String {
    String::new()
}

fn default_remote_name() -> String {
    "origin".to_string()
}

fn default_remote_base_url() -> String {
    "https://github.com".to_string()
}

fn default_tips() -> bool {
    true
}

fn default_use_gh_cli() -> bool {
    true
}

fn default_allow_github_token_env() -> bool {
    false
}

impl Config {
    /// Get the config directory.
    /// Default: `~/.config/stax` (Unix) or `C:\Users\<you>\.config\stax` (Windows).
    /// Override with `STAX_CONFIG_DIR` env var for testing or custom locations.
    pub fn dir() -> Result<PathBuf> {
        if let Ok(dir) = std::env::var("STAX_CONFIG_DIR") {
            return Ok(PathBuf::from(dir));
        }
        let home = dirs::home_dir().context("Could not find home directory")?;
        Ok(home.join(".config").join("stax"))
    }

    /// Get the config file path
    pub fn path() -> Result<PathBuf> {
        Ok(Self::dir()?.join("config.toml"))
    }

    /// Get the credentials file path (separate from config, not for dotfiles)
    fn credentials_path() -> Result<PathBuf> {
        Ok(Self::dir()?.join(".credentials"))
    }

    /// Ensure config exists, creating default if needed
    /// Call this once at startup
    pub fn ensure_exists() -> Result<()> {
        let path = Self::path()?;
        if !path.exists() {
            let config = Config::default();
            config.save()?;
        }
        Ok(())
    }

    /// Load config from file
    pub fn load() -> Result<Self> {
        let path = Self::path()?;
        if path.exists() {
            let content = fs::read_to_string(&path)?;
            let config: Config = toml::from_str(&content)?;
            Ok(config)
        } else {
            Ok(Config::default())
        }
    }

    /// Save config to file
    pub fn save(&self) -> Result<()> {
        let path = Self::path()?;
        if let Some(parent) = path.parent() {
            fs::create_dir_all(parent)?;
        }
        let content = toml::to_string_pretty(self)?;
        fs::write(&path, content)?;
        Ok(())
    }

    /// Clear any saved AI agent/model defaults so interactive commands can re-prompt.
    pub fn clear_ai_defaults(&mut self) -> bool {
        let had_saved_defaults = self.ai.agent.is_some()
            || self.ai.model.is_some()
            || !self.ai.generate.is_empty()
            || !self.ai.standup.is_empty()
            || !self.ai.resolve.is_empty()
            || !self.ai.lane.is_empty();
        self.ai.agent = None;
        self.ai.model = None;
        self.ai.generate = AiFeatureConfig::default();
        self.ai.standup = AiFeatureConfig::default();
        self.ai.resolve = AiFeatureConfig::default();
        self.ai.lane = AiFeatureConfig::default();
        had_saved_defaults
    }

    /// Get GitHub token (from env var, credentials file, or gh cli)
    /// Priority:
    /// 1. STAX_GITHUB_TOKEN
    /// 2. credentials file (~/.config/stax/.credentials)
    /// 3. gh auth token (if auth.use_gh_cli = true)
    /// 4. GITHUB_TOKEN (if auth.allow_github_token_env = true)
    pub fn github_token() -> Option<String> {
        let auth_config = Self::load().map(|c| c.auth).unwrap_or_default();
        Self::resolve_github_auth_with_config(&auth_config).map(|(_, token)| token)
    }

    /// Like `github_token` but also returns the source for error messages.
    pub fn github_token_with_source() -> Option<(GitHubAuthSource, String)> {
        let auth_config = Self::load().map(|c| c.auth).unwrap_or_default();
        Self::resolve_github_auth_with_config(&auth_config)
    }

    /// Get the saved credentials-file token written by `stax auth`.
    ///
    /// This stored token is forge-agnostic and can be reused across GitHub,
    /// GitLab, and Gitea when forge-specific env vars are not set.
    pub fn saved_forge_token() -> Option<String> {
        Self::token_from_credentials_file()
    }

    pub fn github_auth_status() -> GitHubAuthStatus {
        let auth_config = Self::load().map(|c| c.auth).unwrap_or_default();

        let stax_env_available = Self::read_env_token("STAX_GITHUB_TOKEN").is_some();
        let credentials_file_available = Self::token_from_credentials_file().is_some();
        let gh_cli_available = if auth_config.use_gh_cli {
            Self::token_from_gh_cli(auth_config.gh_hostname.as_deref())
                .ok()
                .flatten()
                .is_some()
        } else {
            false
        };
        let github_env_available = Self::read_env_token("GITHUB_TOKEN").is_some();

        let active_source = if stax_env_available {
            Some(GitHubAuthSource::StaxGithubTokenEnv)
        } else if credentials_file_available {
            Some(GitHubAuthSource::CredentialsFile)
        } else if auth_config.use_gh_cli && gh_cli_available {
            Some(GitHubAuthSource::GhCli)
        } else if auth_config.allow_github_token_env && github_env_available {
            Some(GitHubAuthSource::GithubTokenEnv)
        } else {
            None
        };

        GitHubAuthStatus {
            active_source,
            stax_env_available,
            credentials_file_available,
            gh_cli_available,
            github_env_available,
            use_gh_cli: auth_config.use_gh_cli,
            allow_github_token_env: auth_config.allow_github_token_env,
            gh_hostname: auth_config.gh_hostname,
        }
    }

    /// Set the saved API token (to credentials file)
    pub fn set_github_token(token: &str) -> Result<()> {
        let path = Self::credentials_path()?;
        if let Some(parent) = path.parent() {
            fs::create_dir_all(parent)?;
        }
        fs::write(&path, token)?;

        // Set restrictive permissions on Unix
        #[cfg(unix)]
        {
            use std::os::unix::fs::PermissionsExt;
            let perms = std::fs::Permissions::from_mode(0o600);
            fs::set_permissions(&path, perms)?;
        }

        Ok(())
    }

    /// Read token from gh CLI for explicit import (`stax auth --from-gh`).
    pub fn gh_cli_token_for_import() -> Result<String> {
        let auth_config = Self::load().map(|c| c.auth).unwrap_or_default();

        Self::token_from_gh_cli(auth_config.gh_hostname.as_deref())?.context(
            "Could not read token from `gh auth token`.\n\
             Ensure GitHub CLI is installed and authenticated (`gh auth login`).",
        )
    }

    fn read_env_token(var_name: &str) -> Option<String> {
        std::env::var(var_name)
            .ok()
            .and_then(|value| Self::normalize_token(value.as_str()))
    }

    fn token_from_credentials_file() -> Option<String> {
        let path = Self::credentials_path().ok()?;
        let token = fs::read_to_string(path).ok()?;
        Self::normalize_token(token.as_str())
    }

    fn token_from_gh_cli(hostname: Option<&str>) -> Result<Option<String>> {
        let mut command = Command::new("gh");
        command.args(["auth", "token"]);
        if let Some(host) = hostname.and_then(Self::normalize_token) {
            command.args(["--hostname", host.as_str()]);
        }

        let output = match command.output() {
            Ok(output) => output,
            Err(err) if err.kind() == std::io::ErrorKind::NotFound => return Ok(None),
            Err(err) => return Err(err).context("Failed to execute `gh auth token`"),
        };

        if !output.status.success() {
            return Ok(None);
        }

        let token = String::from_utf8_lossy(&output.stdout);
        Ok(Self::normalize_token(token.as_ref()))
    }

    fn normalize_token(token: &str) -> Option<String> {
        let trimmed = token.trim();
        if trimmed.is_empty() {
            None
        } else {
            Some(trimmed.to_string())
        }
    }

    fn resolve_github_auth_with_config(
        auth_config: &AuthConfig,
    ) -> Option<(GitHubAuthSource, String)> {
        if let Some(token) = Self::read_env_token("STAX_GITHUB_TOKEN") {
            return Some((GitHubAuthSource::StaxGithubTokenEnv, token));
        }

        if let Some(token) = Self::token_from_credentials_file() {
            return Some((GitHubAuthSource::CredentialsFile, token));
        }

        if auth_config.use_gh_cli {
            if let Ok(Some(token)) = Self::token_from_gh_cli(auth_config.gh_hostname.as_deref()) {
                return Some((GitHubAuthSource::GhCli, token));
            }
        }

        if auth_config.allow_github_token_env {
            if let Some(token) = Self::read_env_token("GITHUB_TOKEN") {
                return Some((GitHubAuthSource::GithubTokenEnv, token));
            }
        }

        None
    }

    /// Format a branch name according to config settings
    pub fn format_branch_name(&self, name: &str) -> String {
        self.format_branch_name_with_prefix_override(name, None)
    }

    /// Format a branch name, optionally overriding the configured prefix
    pub fn format_branch_name_with_prefix_override(
        &self,
        name: &str,
        prefix_override: Option<&str>,
    ) -> String {
        // Sanitize the message/name first
        let sanitized_name = self.sanitize_branch_segment(name);

        // If format template is set, use it (new behavior)
        if let Some(ref format_template) = self.branch.format {
            if !format_template.contains("{message}") {
                eprintln!(
                    "Warning: branch.format template is missing {{message}} placeholder. \
                     The branch name input will not appear in the generated name."
                );
            }
            return self.apply_format_template(format_template, &sanitized_name, prefix_override);
        }

        // Legacy behavior: use prefix/date fields for backward compatibility
        let replacement = &self.branch.replacement;
        let mut result = sanitized_name;

        // Add date if enabled (legacy, preserves original %Y-%m-%d format)
        if self.branch.date {
            let date = chrono::Local::now().format("%Y-%m-%d").to_string();
            result = format!("{}{}{}", date, replacement, result);
        }

        let prefix = if let Some(override_prefix) = prefix_override {
            let trimmed = override_prefix.trim();
            if trimmed.is_empty() {
                None
            } else {
                Some(Self::normalize_prefix_override(trimmed))
            }
        } else {
            self.branch.prefix.clone()
        };

        if let Some(prefix) = prefix {
            if !result.starts_with(&prefix) {
                result = format!("{}{}", prefix, result);
            }
        }

        result
    }

    /// Apply the format template to create a branch name
    fn apply_format_template(
        &self,
        template: &str,
        message: &str,
        prefix_override: Option<&str>,
    ) -> String {
        let mut result = template.to_string();

        // Replace {message} placeholder
        result = result.replace("{message}", message);

        // Replace {date} placeholder if present
        if result.contains("{date}") {
            let date = chrono::Local::now()
                .format(&self.branch.date_format)
                .to_string();
            result = result.replace("{date}", &date);
        }

        // Replace {user} placeholder if present
        if result.contains("{user}") {
            let user = self.get_user_for_branch();
            result = result.replace("{user}", &user);
        }

        // Clean up empty segments: collapse repeated separators and trim leading/trailing ones
        // This handles cases where {user} resolves to "" (e.g., "/02-11/msg" -> "02-11/msg")
        while result.contains("//") {
            result = result.replace("//", "/");
        }
        result = result.trim_matches('/').to_string();

        // Handle prefix override (for -p flag compatibility)
        if let Some(override_prefix) = prefix_override {
            let trimmed = override_prefix.trim();
            if !trimmed.is_empty() {
                let normalized = Self::normalize_prefix_override(trimmed);
                if !result.starts_with(&normalized) {
                    result = format!("{}{}", normalized, result);
                }
            }
        }

        result
    }

    /// Sanitize a segment of the branch name (replace special chars, collapse duplicates)
    fn sanitize_branch_segment(&self, segment: &str) -> String {
        let replacement = &self.branch.replacement;

        let mut result: String = segment
            .chars()
            .map(|c| {
                if c.is_alphanumeric() || c == '-' || c == '_' || c == '/' {
                    c
                } else {
                    replacement.chars().next().unwrap_or('-')
                }
            })
            .collect();

        // Replace multiple consecutive replacements with single one
        while result.contains(&format!("{}{}", replacement, replacement)) {
            result = result.replace(&format!("{}{}", replacement, replacement), replacement);
        }

        // Trim leading/trailing replacement chars
        let replacement_char = replacement.chars().next().unwrap_or('-');
        result = result
            .trim_start_matches(replacement_char)
            .trim_end_matches(replacement_char)
            .to_string();

        result
    }

    /// Get the username for branch naming
    /// Priority: 1. config.branch.user (explicit empty disables fallback),
    /// 2. git config user.name, 3. empty string
    fn get_user_for_branch(&self) -> String {
        // First check config
        if let Some(ref user) = self.branch.user {
            if user.is_empty() {
                return String::new();
            }
            return self.sanitize_branch_segment(user);
        }

        // Then try git config user.name
        if let Ok(output) = std::process::Command::new("git")
            .args(["config", "user.name"])
            .output()
        {
            if output.status.success() {
                let name = String::from_utf8_lossy(&output.stdout).trim().to_string();
                if !name.is_empty() {
                    return self.sanitize_branch_segment(&name);
                }
            }
        }

        // Fallback to empty
        String::new()
    }

    fn normalize_prefix_override(prefix: &str) -> String {
        if prefix.ends_with('/') || prefix.ends_with('-') || prefix.ends_with('_') {
            prefix.to_string()
        } else {
            format!("{}/", prefix)
        }
    }

    pub fn remote_name(&self) -> &str {
        self.remote.name.as_str()
    }

    pub fn remote_base_url(&self) -> &str {
        self.remote.base_url.as_str()
    }

    pub fn remote_forge_override(&self) -> Option<ForgeType> {
        self.remote.forge
    }
}

#[cfg(test)]
mod tests;