git-parsec 0.3.0

Git worktree lifecycle manager — ticket to PR in one command. Parallel AI agent workflows with Jira & GitHub Issues integration.
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
use anyhow::{Context, Result};
use dialoguer::{Confirm, Input, Select};
use serde::{Deserialize, Serialize};
use std::collections::HashMap;
use std::path::{Path, PathBuf};

// ---------------------------------------------------------------------------
// Default value helpers required by serde
// ---------------------------------------------------------------------------

fn default_base_dir() -> String {
    ".parsec/workspaces".to_string()
}

fn default_branch_prefix() -> String {
    "feature/".to_string()
}

fn default_provider() -> TrackerProvider {
    TrackerProvider::None
}

fn default_true() -> bool {
    true
}

// ---------------------------------------------------------------------------
// TrackerProvider
// ---------------------------------------------------------------------------

#[derive(Debug, Clone, Serialize, Deserialize, PartialEq)]
#[serde(rename_all = "lowercase")]
#[derive(Default)]
pub enum TrackerProvider {
    Jira,
    Github,
    Gitlab,
    #[default]
    None,
}

impl std::fmt::Display for TrackerProvider {
    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
        match self {
            TrackerProvider::Jira => write!(f, "jira"),
            TrackerProvider::Github => write!(f, "github"),
            TrackerProvider::Gitlab => write!(f, "gitlab"),
            TrackerProvider::None => write!(f, "none"),
        }
    }
}

// ---------------------------------------------------------------------------
// WorktreeLayout
// ---------------------------------------------------------------------------

#[derive(Debug, Clone, Serialize, Deserialize, PartialEq)]
#[serde(rename_all = "lowercase")]
#[derive(Default)]
pub enum WorktreeLayout {
    #[default]
    Sibling, // ../repo.ticket/ (worktrunk-style, default)
    Internal, // .parsec/workspaces/ticket/ (inside repo)
}

fn default_layout() -> WorktreeLayout {
    WorktreeLayout::Sibling
}

impl std::fmt::Display for WorktreeLayout {
    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
        match self {
            WorktreeLayout::Sibling => write!(f, "sibling"),
            WorktreeLayout::Internal => write!(f, "internal"),
        }
    }
}

// ---------------------------------------------------------------------------
// WorkspaceConfig
// ---------------------------------------------------------------------------

#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct WorkspaceConfig {
    #[serde(default = "default_layout")]
    pub layout: WorktreeLayout,
    #[serde(default = "default_base_dir")]
    pub base_dir: String, // only used for Internal layout
    #[serde(default = "default_branch_prefix")]
    pub branch_prefix: String,
    /// Default base branch for worktree creation (e.g. "develop")
    #[serde(default)]
    pub default_base: Option<String>,
}

impl Default for WorkspaceConfig {
    fn default() -> Self {
        Self {
            layout: default_layout(),
            base_dir: default_base_dir(),
            branch_prefix: default_branch_prefix(),
            default_base: None,
        }
    }
}

// ---------------------------------------------------------------------------
// JiraConfig
// ---------------------------------------------------------------------------

#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct JiraConfig {
    pub base_url: String,
    pub email: Option<String>,
    pub project: Option<String>,
    pub board_id: Option<u64>,
    pub assignee: Option<String>,
}

// ---------------------------------------------------------------------------
// GitlabConfig
// ---------------------------------------------------------------------------

#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct GitlabConfig {
    pub base_url: String,
}

// ---------------------------------------------------------------------------
// TrackerConfig
// ---------------------------------------------------------------------------

#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct TrackerConfig {
    #[serde(default = "default_provider")]
    pub provider: TrackerProvider,
    #[serde(default)]
    pub jira: Option<JiraConfig>,
    #[serde(default)]
    pub gitlab: Option<GitlabConfig>,
    #[serde(default)]
    pub auto_transition: Option<AutoTransitionConfig>,
    /// When true, auto-post PR link as comment on the ticket during `parsec ship`
    #[serde(default)]
    pub comment_on_ship: bool,
}

impl Default for TrackerConfig {
    fn default() -> Self {
        Self {
            provider: default_provider(),
            jira: None,
            gitlab: None,
            auto_transition: None,
            comment_on_ship: false,
        }
    }
}

// ---------------------------------------------------------------------------
// ShipConfig
// ---------------------------------------------------------------------------

#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct ShipConfig {
    #[serde(default = "default_true")]
    pub auto_pr: bool,
    #[serde(default = "default_true")]
    pub auto_cleanup: bool,
    #[serde(default)]
    pub draft: bool,
    #[serde(default)]
    pub default_base: Option<String>,
}

impl Default for ShipConfig {
    fn default() -> Self {
        Self {
            auto_pr: true,
            auto_cleanup: true,
            draft: false,
            default_base: None,
        }
    }
}

// ---------------------------------------------------------------------------
// HooksConfig
// ---------------------------------------------------------------------------

#[derive(Debug, Clone, Serialize, Deserialize, Default)]
pub struct HooksConfig {
    /// Commands to run after creating a worktree (in the worktree directory)
    #[serde(default)]
    pub post_create: Vec<String>,
}

// ---------------------------------------------------------------------------
// AutoTransitionConfig
// ---------------------------------------------------------------------------

#[derive(Debug, Clone, Serialize, Deserialize, Default)]
pub struct AutoTransitionConfig {
    /// Target status name when `parsec start` is run (e.g. "In Progress")
    #[serde(default)]
    pub on_start: Option<String>,
    /// Target status name when `parsec ship` is run (e.g. "In Review")
    #[serde(default)]
    pub on_ship: Option<String>,
    /// Target status name when `parsec merge` is run (e.g. "Done")
    #[serde(default)]
    pub on_merge: Option<String>,
}

// ---------------------------------------------------------------------------
// GithubHostConfig
// ---------------------------------------------------------------------------

/// Per-host GitHub configuration (e.g. token for github.com or a GHE instance).
#[derive(Debug, Clone, Serialize, Deserialize, Default)]
pub struct GithubHostConfig {
    /// Personal access token for this host.
    pub token: Option<String>,
}

// ---------------------------------------------------------------------------
// RepoTrackerOverride / RepoOverrideConfig
// ---------------------------------------------------------------------------

/// Tracker overrides that can be set per-repo.
#[derive(Debug, Clone, Serialize, Deserialize, Default)]
pub struct RepoTrackerOverride {
    pub provider: Option<TrackerProvider>,
    #[serde(default)]
    pub jira: Option<JiraConfig>,
    #[serde(default)]
    pub gitlab: Option<GitlabConfig>,
}

/// Per-repo configuration overrides.
#[derive(Debug, Clone, Serialize, Deserialize, Default)]
pub struct RepoOverrideConfig {
    #[serde(default)]
    pub tracker: Option<RepoTrackerOverride>,
}

// ---------------------------------------------------------------------------
// ParsecConfig
// ---------------------------------------------------------------------------

#[derive(Debug, Clone, Serialize, Deserialize, Default)]
pub struct ParsecConfig {
    #[serde(default)]
    pub workspace: WorkspaceConfig,
    #[serde(default)]
    pub tracker: TrackerConfig,
    #[serde(default)]
    pub ship: ShipConfig,
    #[serde(default)]
    pub hooks: HooksConfig,
    /// Per-host GitHub tokens. Keys are hostnames like "github.com" or
    /// "github.example.com". Serializes as `[github."hostname"]` in TOML.
    #[serde(default)]
    pub github: HashMap<String, GithubHostConfig>,
    /// Per-repo configuration overrides. Keys are "owner/repo" strings.
    /// Serializes as `[repos."owner/repo"]` in TOML.
    #[serde(default)]
    pub repos: HashMap<String, RepoOverrideConfig>,
}

impl ParsecConfig {
    /// Return the canonical path to the config file.
    pub fn config_path() -> PathBuf {
        dirs::config_dir()
            .unwrap_or_else(|| {
                dirs::home_dir()
                    .unwrap_or_else(|| PathBuf::from("."))
                    .join(".config")
            })
            .join("parsec")
            .join("config.toml")
    }

    /// Load the config from disk. Returns `Default` if the file does not exist.
    pub fn load() -> Result<Self> {
        let path = Self::config_path();

        if !path.exists() {
            return Ok(Self::default());
        }

        let contents = std::fs::read_to_string(&path)
            .with_context(|| format!("Failed to read config file: {}", path.display()))?;

        let config: Self = toml::from_str(&contents)
            .with_context(|| format!("Failed to parse config file: {}", path.display()))?;

        Ok(config)
    }

    /// Persist the config to disk, creating parent directories as needed.
    pub fn save(&self) -> Result<()> {
        let path = Self::config_path();

        if let Some(parent) = path.parent() {
            std::fs::create_dir_all(parent).with_context(|| {
                format!("Failed to create config directory: {}", parent.display())
            })?;
        }

        let contents =
            toml::to_string_pretty(self).context("Failed to serialize config to TOML")?;

        std::fs::write(&path, contents)
            .with_context(|| format!("Failed to write config file: {}", path.display()))?;

        Ok(())
    }

    /// Apply per-repo tracker overrides for the repository at `repo_root`.
    ///
    /// Runs `git remote get-url origin`, parses `owner/repo` from the URL,
    /// and merges any matching `[repos."owner/repo".tracker]` settings into
    /// `self.tracker`. Silently ignores errors (no remote, no match, etc.).
    pub fn resolve_for_repo(&mut self, repo_root: &Path) {
        // Get the origin remote URL; silently skip if unavailable.
        let remote_url = match std::process::Command::new("git")
            .args(["remote", "get-url", "origin"])
            .current_dir(repo_root)
            .output()
        {
            Ok(out) if out.status.success() => String::from_utf8(out.stdout).unwrap_or_default(),
            _ => return,
        };
        let remote_url = remote_url.trim();

        // Parse owner/repo from the URL.
        let parsed = crate::github::parse_github_remote(remote_url);
        let remote = match parsed {
            Some(r) => r,
            None => return,
        };
        let key = format!("{}/{}", remote.owner, remote.repo);

        // Look up the per-repo override.
        let repo_cfg = match self.repos.get(&key) {
            Some(r) => r.clone(),
            None => return,
        };

        let tracker_override = match repo_cfg.tracker {
            Some(t) => t,
            None => return,
        };

        // Apply overrides.
        if let Some(provider) = tracker_override.provider {
            self.tracker.provider = provider;
        }
        if let Some(jira) = tracker_override.jira {
            self.tracker.jira = Some(jira);
        }
        if let Some(gitlab) = tracker_override.gitlab {
            self.tracker.gitlab = Some(gitlab);
        }
    }

    /// Interactively prompt the user to configure parsec and return the resulting config.
    pub fn init_interactive() -> Result<Self> {
        let mut config = Self::default();

        // ---- Tracker provider ------------------------------------------------
        let provider_options = &["None", "Jira", "GitHub", "GitLab"];
        let provider_idx = Select::new()
            .with_prompt("Issue tracker provider")
            .items(provider_options)
            .default(0)
            .interact()
            .context("Failed to read tracker provider selection")?;

        config.tracker.provider = match provider_idx {
            1 => TrackerProvider::Jira,
            2 => TrackerProvider::Github,
            3 => TrackerProvider::Gitlab,
            _ => TrackerProvider::None,
        };

        // ---- Jira-specific options -------------------------------------------
        if config.tracker.provider == TrackerProvider::Jira {
            let base_url: String = Input::new()
                .with_prompt("Jira base URL (e.g. https://yourorg.atlassian.net)")
                .interact_text()
                .context("Failed to read Jira base URL")?;

            let email_input: String = Input::new()
                .with_prompt("Jira email (leave blank to skip)")
                .allow_empty(true)
                .interact_text()
                .context("Failed to read Jira email")?;

            config.tracker.jira = Some(JiraConfig {
                base_url,
                email: if email_input.is_empty() {
                    None
                } else {
                    Some(email_input)
                },
                project: None,
                board_id: None,
                assignee: None,
            });
        }

        // ---- GitLab-specific options -----------------------------------------
        if config.tracker.provider == TrackerProvider::Gitlab {
            let base_url: String = Input::new()
                .with_prompt("GitLab base URL (e.g. https://gitlab.com)")
                .default("https://gitlab.com".to_string())
                .interact_text()
                .context("Failed to read GitLab base URL")?;

            config.tracker.gitlab = Some(GitlabConfig { base_url });
        }

        // ---- Worktree layout -------------------------------------------------
        let layout_options = &[
            "Sibling (recommended - worktrees next to repo)",
            "Internal (worktrees inside .parsec/)",
        ];
        let layout_idx = Select::new()
            .with_prompt("Worktree layout")
            .items(layout_options)
            .default(0)
            .interact()
            .context("Failed to read layout selection")?;
        config.workspace.layout = match layout_idx {
            1 => WorktreeLayout::Internal,
            _ => WorktreeLayout::Sibling,
        };

        // ---- Branch prefix ---------------------------------------------------
        let branch_prefix: String = Input::new()
            .with_prompt("Branch prefix for new worktrees")
            .default("feature/".to_string())
            .interact_text()
            .context("Failed to read branch prefix")?;

        config.workspace.branch_prefix = branch_prefix;

        // ---- Ship options ----------------------------------------------------
        config.ship.auto_pr = Confirm::new()
            .with_prompt("Automatically open a PR when shipping?")
            .default(true)
            .interact()
            .context("Failed to read auto PR preference")?;

        config.ship.draft = Confirm::new()
            .with_prompt("Create PRs as drafts by default?")
            .default(false)
            .interact()
            .context("Failed to read draft PR preference")?;

        Ok(config)
    }
}