gitgrip 0.13.0

Multi-repo workflow tool - manage multiple git repositories as one
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
//! Repository information and operations

use std::path::{Path, PathBuf};

use crate::core::manifest::{
    Manifest, ManifestRepoConfig, PlatformType, RepoAgentConfig, RepoConfig,
};
use crate::core::manifest_paths;

/// Extended repository information with computed fields
#[derive(Debug, Clone)]
pub struct RepoInfo {
    /// Repository name (from manifest key)
    pub name: String,
    /// Git URL (SSH or HTTPS)
    pub url: String,
    /// Local path relative to manifest root
    pub path: String,
    /// Absolute path on disk
    pub absolute_path: PathBuf,
    /// Default branch (e.g., "main", "master")
    pub default_branch: String,
    /// Owner/namespace from git URL
    pub owner: String,
    /// Repo name from git URL
    pub repo: String,
    /// Detected or configured platform type
    pub platform_type: PlatformType,
    /// Optional base URL for self-hosted platform instances
    pub platform_base_url: Option<String>,
    /// Project name (Azure DevOps only)
    pub project: Option<String>,
    /// Reference repo (read-only, excluded from branch/PR operations)
    pub reference: bool,
    /// Groups this repo belongs to (for selective operations)
    pub groups: Vec<String>,
    /// Agent context metadata (build/test/lint commands for AI agents)
    pub agent: Option<RepoAgentConfig>,
}

impl RepoInfo {
    /// Create RepoInfo from a manifest RepoConfig
    pub fn from_config(name: &str, config: &RepoConfig, workspace_root: &PathBuf) -> Option<Self> {
        let parsed = parse_git_url(&config.url)?;

        let absolute_path = workspace_root.join(&config.path);

        let platform_type = config
            .platform
            .as_ref()
            .map(|p| p.platform_type)
            .unwrap_or_else(|| detect_platform(&config.url));
        let platform_base_url = config.platform.as_ref().and_then(|p| p.base_url.clone());

        Some(Self {
            name: name.to_string(),
            url: config.url.clone(),
            path: config.path.clone(),
            absolute_path,
            default_branch: config.default_branch.clone(),
            owner: parsed.owner,
            repo: parsed.repo,
            platform_type,
            platform_base_url,
            project: parsed.project,
            reference: config.reference,
            groups: config.groups.clone(),
            agent: config.agent.clone(),
        })
    }

    /// Check if the repository exists on disk
    pub fn exists(&self) -> bool {
        self.absolute_path.join(".git").exists()
    }
}

/// Parsed git URL components
struct ParsedUrl {
    owner: String,
    repo: String,
    project: Option<String>,
}

/// Parse a git URL to extract owner and repo
fn parse_git_url(url: &str) -> Option<ParsedUrl> {
    // Handle SSH URLs: git@github.com:owner/repo.git
    if url.starts_with("git@") {
        let parts: Vec<&str> = url.splitn(2, ':').collect();
        if parts.len() != 2 {
            return None;
        }
        let path = parts[1].trim_end_matches(".git");

        // Handle Azure DevOps SSH: git@ssh.dev.azure.com:v3/org/project/repo
        if url.contains("dev.azure.com") || url.contains("visualstudio.com") {
            let segments: Vec<&str> = path.split('/').collect();
            if segments.len() >= 4 && segments[0] == "v3" {
                return Some(ParsedUrl {
                    owner: segments[1].to_string(),
                    repo: segments[3].to_string(),
                    project: Some(segments[2].to_string()),
                });
            }
        }

        // Standard format: owner/repo
        let segments: Vec<&str> = path.split('/').collect();
        if segments.len() >= 2 {
            return Some(ParsedUrl {
                owner: segments[0].to_string(),
                repo: segments[segments.len() - 1].to_string(),
                project: None,
            });
        }
    }

    // Handle HTTPS URLs: https://github.com/owner/repo.git
    if url.starts_with("https://") || url.starts_with("http://") {
        let url_without_proto = url
            .trim_start_matches("https://")
            .trim_start_matches("http://");
        let path = url_without_proto
            .split_once('/')?
            .1
            .trim_end_matches(".git");

        // Handle Azure DevOps HTTPS: https://dev.azure.com/org/project/_git/repo
        if url.contains("dev.azure.com") {
            let segments: Vec<&str> = path.split('/').collect();
            if segments.len() >= 4 && segments[2] == "_git" {
                return Some(ParsedUrl {
                    owner: segments[0].to_string(),
                    repo: segments[3].to_string(),
                    project: Some(segments[1].to_string()),
                });
            }
        }

        // Handle visualstudio.com: https://org.visualstudio.com/project/_git/repo
        if url.contains("visualstudio.com") {
            // Extract org from subdomain
            let host_and_path: Vec<&str> = url_without_proto.splitn(2, '/').collect();
            if host_and_path.len() < 2 {
                return None;
            }
            let host = host_and_path[0];
            let org = host.split('.').next()?;
            let segments: Vec<&str> = path.split('/').collect();
            if segments.len() >= 3 && segments[1] == "_git" {
                return Some(ParsedUrl {
                    owner: org.to_string(),
                    repo: segments[2].to_string(),
                    project: Some(segments[0].to_string()),
                });
            }
        }

        // Standard format: owner/repo
        let segments: Vec<&str> = path.split('/').collect();
        if segments.len() >= 2 {
            return Some(ParsedUrl {
                owner: segments[0].to_string(),
                repo: segments[segments.len() - 1].to_string(),
                project: None,
            });
        }
    }

    // Handle file:// URLs (used in testing with local bare repos)
    if url.starts_with("file://") {
        let path = url.trim_start_matches("file://").trim_end_matches(".git");
        // Extract the last path component as repo name
        if let Some(name) = path.rsplit('/').next() {
            return Some(ParsedUrl {
                owner: "local".to_string(),
                repo: name.to_string(),
                project: None,
            });
        }
    }

    None
}

/// Filter repos from a manifest by name, group, and reference status.
///
/// Replaces the repeated `.iter().filter_map().filter().filter().collect()` pattern
/// found across commands.
pub fn filter_repos(
    manifest: &Manifest,
    workspace_root: &PathBuf,
    repos_filter: Option<&[String]>,
    group_filter: Option<&[String]>,
    include_reference: bool,
) -> Vec<RepoInfo> {
    manifest
        .repos
        .iter()
        .filter_map(|(name, config)| RepoInfo::from_config(name, config, workspace_root))
        .filter(|r| include_reference || !r.reference)
        .filter(|r| {
            repos_filter
                .map(|filter| filter.iter().any(|f| f == &r.name))
                .unwrap_or(true)
        })
        .filter(|r| {
            group_filter
                .map(|groups| r.groups.iter().any(|g| groups.contains(g)))
                .unwrap_or(true)
        })
        .collect()
}

/// Get RepoInfo for the manifest repo if it exists.
///
/// This provides a standardized way to include the manifest repository
/// in operations like sync, branch, checkout, push, and diff.
pub fn get_manifest_repo_info(manifest: &Manifest, workspace_root: &Path) -> Option<RepoInfo> {
    let manifest_config = manifest.manifest.as_ref()?;
    let manifests_dir = manifest_paths::resolve_manifest_repo_dir(workspace_root)?;

    // Only return if the manifest repo actually exists as a git repo
    if !manifests_dir.join(".git").exists() {
        return None;
    }

    create_manifest_repo_info(manifest_config, workspace_root)
}

/// Create RepoInfo from ManifestRepoConfig
fn create_manifest_repo_info(
    config: &ManifestRepoConfig,
    workspace_root: &Path,
) -> Option<RepoInfo> {
    let repo_dir = manifest_paths::resolve_manifest_repo_dir(workspace_root)
        .unwrap_or_else(|| manifest_paths::main_space_dir(workspace_root));
    let path = repo_dir
        .strip_prefix(workspace_root)
        .ok()
        .map(|p| p.to_string_lossy().to_string())
        .unwrap_or_else(|| manifest_paths::MAIN_SPACE_DIR.to_string());

    RepoInfo::from_config(
        "manifest",
        &RepoConfig {
            url: config.url.clone(),
            path,
            default_branch: config.default_branch.clone(),
            copyfile: config.copyfile.clone(),
            linkfile: config.linkfile.clone(),
            platform: config.platform.clone(),
            reference: false,
            groups: Vec::new(),
            agent: None,
        },
        &workspace_root.to_path_buf(),
    )
}

/// Detect platform type from URL
fn detect_platform(url: &str) -> PlatformType {
    // Check GitHub first (most common)
    if url.contains("github.com") {
        return PlatformType::GitHub;
    }

    // Check Azure DevOps before GitLab (avoid false positives)
    if url.contains("dev.azure.com") || url.contains("visualstudio.com") {
        return PlatformType::AzureDevOps;
    }

    // Check Bitbucket before GitLab
    if url.contains("bitbucket.org") || url.contains("bitbucket.") {
        return PlatformType::Bitbucket;
    }

    // Check GitLab - ensure it's in hostname, not just path
    if url.contains("gitlab.com") || url.contains("gitlab.") {
        return PlatformType::GitLab;
    }

    // Default to GitHub for backward compatibility
    PlatformType::GitHub
}

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

    #[test]
    fn test_parse_github_ssh() {
        let parsed = parse_git_url("git@github.com:user/repo.git").unwrap();
        assert_eq!(parsed.owner, "user");
        assert_eq!(parsed.repo, "repo");
        assert!(parsed.project.is_none());
    }

    #[test]
    fn test_parse_github_https() {
        let parsed = parse_git_url("https://github.com/user/repo.git").unwrap();
        assert_eq!(parsed.owner, "user");
        assert_eq!(parsed.repo, "repo");
    }

    #[test]
    fn test_parse_azure_https() {
        let parsed = parse_git_url("https://dev.azure.com/org/project/_git/repo").unwrap();
        assert_eq!(parsed.owner, "org");
        assert_eq!(parsed.repo, "repo");
        assert_eq!(parsed.project, Some("project".to_string()));
    }

    #[test]
    fn test_parse_azure_ssh() {
        let parsed = parse_git_url("git@ssh.dev.azure.com:v3/org/project/repo").unwrap();
        assert_eq!(parsed.owner, "org");
        assert_eq!(parsed.repo, "repo");
        assert_eq!(parsed.project, Some("project".to_string()));
    }

    #[test]
    fn test_parse_file_url() {
        let parsed = parse_git_url("file:///tmp/remotes/myrepo.git").unwrap();
        assert_eq!(parsed.owner, "local");
        assert_eq!(parsed.repo, "myrepo");
        assert!(parsed.project.is_none());
    }

    #[test]
    fn test_parse_file_url_no_extension() {
        let parsed = parse_git_url("file:///tmp/repos/test-repo").unwrap();
        assert_eq!(parsed.owner, "local");
        assert_eq!(parsed.repo, "test-repo");
    }

    #[test]
    fn test_detect_github() {
        assert_eq!(
            detect_platform("git@github.com:user/repo.git"),
            PlatformType::GitHub
        );
    }

    #[test]
    fn test_detect_gitlab() {
        assert_eq!(
            detect_platform("git@gitlab.com:user/repo.git"),
            PlatformType::GitLab
        );
    }

    #[test]
    fn test_detect_azure() {
        assert_eq!(
            detect_platform("https://dev.azure.com/org/project/_git/repo"),
            PlatformType::AzureDevOps
        );
    }

    #[test]
    fn test_get_manifest_repo_info_no_manifest() {
        use crate::core::manifest::Manifest;
        use std::collections::HashMap;
        use tempfile::TempDir;

        let temp = TempDir::new().unwrap();
        let manifest = Manifest {
            version: 1,
            gripspaces: None,
            manifest: None,
            repos: HashMap::new(),
            settings: Default::default(),
            workspace: None,
        };

        let result = get_manifest_repo_info(&manifest, temp.path());
        assert!(result.is_none());
    }

    #[test]
    fn test_get_manifest_repo_info_no_git_dir() {
        use crate::core::manifest::{Manifest, ManifestRepoConfig};
        use std::collections::HashMap;
        use tempfile::TempDir;

        let temp = TempDir::new().unwrap();
        let manifest = Manifest {
            version: 1,
            gripspaces: None,
            manifest: Some(ManifestRepoConfig {
                url: "git@github.com:user/manifest.git".to_string(),
                default_branch: "main".to_string(),
                copyfile: None,
                linkfile: None,
                composefile: None,
                platform: None,
            }),
            repos: HashMap::new(),
            settings: Default::default(),
            workspace: None,
        };

        // No manifest repo git directory exists
        let result = get_manifest_repo_info(&manifest, temp.path());
        assert!(result.is_none());
    }

    #[test]
    fn test_get_manifest_repo_info_with_git_dir() {
        use crate::core::manifest::{Manifest, ManifestRepoConfig};
        use std::collections::HashMap;
        use std::fs;
        use tempfile::TempDir;

        let temp = TempDir::new().unwrap();

        // Create .gitgrip/spaces/main/.git directory
        let manifests_dir = temp.path().join(".gitgrip").join("spaces").join("main");
        fs::create_dir_all(manifests_dir.join(".git")).unwrap();

        let manifest = Manifest {
            version: 1,
            gripspaces: None,
            manifest: Some(ManifestRepoConfig {
                url: "git@github.com:user/manifest.git".to_string(),
                default_branch: "main".to_string(),
                copyfile: None,
                linkfile: None,
                composefile: None,
                platform: None,
            }),
            repos: HashMap::new(),
            settings: Default::default(),
            workspace: None,
        };

        let result = get_manifest_repo_info(&manifest, temp.path());
        assert!(result.is_some());

        let info = result.unwrap();
        assert_eq!(info.name, "manifest");
        assert_eq!(info.path, ".gitgrip/spaces/main");
        assert_eq!(info.default_branch, "main");
        assert!(!info.reference);
    }
}