gitgrip 1.0.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
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
//! File operations
//!
//! Handles copyfile, linkfile, and composefile operations.

use crate::core::manifest::ComposeFileConfig;
use std::path::Path;

fn is_windows_absolute(path: &str) -> bool {
    let bytes = path.as_bytes();
    (bytes.len() >= 2 && bytes[0].is_ascii_alphabetic() && bytes[1] == b':')
        || path.starts_with("\\\\")
}

fn validate_relative_source_path(path: &str, field: &str) -> Result<(), String> {
    if path.is_empty() {
        return Err(format!("Invalid {}: empty path", field));
    }

    let normalized = path.replace('\\', "/");
    if normalized.starts_with('/') || normalized.starts_with("//") || is_windows_absolute(path) {
        return Err(format!("Invalid {}: absolute path '{}'", field, path));
    }

    if normalized.split('/').any(|segment| segment == "..") {
        return Err(format!("Invalid {}: path traversal '{}'", field, path));
    }

    Ok(())
}

fn validate_gripspace_name(name: &str) -> Result<(), String> {
    if name.is_empty() || name == "." {
        return Err(format!("Invalid gripspace name: '{}'", name));
    }

    // Allowlist: alphanumeric, hyphens, underscores, dots
    if !name
        .chars()
        .all(|c| c.is_ascii_alphanumeric() || c == '-' || c == '_' || c == '.')
    {
        return Err(format!("Invalid gripspace name: '{}'", name));
    }

    if name.contains("..") {
        return Err(format!("Invalid gripspace name: '{}'", name));
    }

    Ok(())
}

/// Process composefile entries, writing composed files to the workspace root.
///
/// Each composefile concatenates parts in order. Parts can come from:
/// - A gripspace: reads from `.gitgrip/spaces/<name>/<src>`
/// - The local manifest: reads from the manifest content directory
pub fn process_composefiles(
    workspace_root: &Path,
    manifests_dir: &Path,
    spaces_dir: &Path,
    composefiles: &[ComposeFileConfig],
) -> anyhow::Result<()> {
    for compose in composefiles {
        validate_relative_source_path(&compose.dest, "composefile dest")
            .map_err(anyhow::Error::msg)?;

        let separator = compose.separator.as_deref().unwrap_or("\n\n");
        let mut parts_content: Vec<String> = Vec::new();

        for part in &compose.parts {
            let source_path = if let Some(ref gs_name) = part.gripspace {
                if let Err(e) = validate_gripspace_name(gs_name) {
                    eprintln!(
                        "Warning: composefile '{}' has invalid gripspace name: {}",
                        compose.dest, e
                    );
                    continue;
                }
                if let Err(e) = validate_relative_source_path(&part.src, "composefile part src") {
                    eprintln!(
                        "Warning: composefile '{}' has invalid part src: {}",
                        compose.dest, e
                    );
                    continue;
                }
                // Source from gripspace
                spaces_dir.join(gs_name).join(&part.src)
            } else {
                if let Err(e) = validate_relative_source_path(&part.src, "composefile part src") {
                    eprintln!(
                        "Warning: composefile '{}' has invalid part src: {}",
                        compose.dest, e
                    );
                    continue;
                }
                // Source from local manifest repo
                manifests_dir.join(&part.src)
            };

            match std::fs::read_to_string(&source_path) {
                Ok(content) => {
                    parts_content.push(content);
                }
                Err(e) => {
                    let gs_label = part
                        .gripspace
                        .as_deref()
                        .map(|g| format!("gripspace:{}", g))
                        .unwrap_or_else(|| "manifest".to_string());
                    eprintln!(
                        "Warning: composefile '{}' part {}:{} not found: {}",
                        compose.dest, gs_label, part.src, e
                    );
                }
            }
        }

        if parts_content.is_empty() {
            continue;
        }

        let composed = parts_content.join(separator);
        let dest_path = workspace_root.join(&compose.dest);

        // Create parent directories if needed
        if let Some(parent) = dest_path.parent() {
            std::fs::create_dir_all(parent)?;
        }

        std::fs::write(&dest_path, composed)?;
    }

    Ok(())
}

/// Resolve a linkfile/copyfile source path that may reference a gripspace.
///
/// Gripspace-sourced files have src prefixed with `gripspace:<name>:<path>`.
/// This function resolves those to their actual filesystem path under `.gitgrip/spaces/`.
///
/// Returns `Err` if the gripspace name or path contains path traversal components.
pub fn resolve_file_source(
    src: &str,
    repo_path: &Path,
    spaces_dir: &Path,
) -> Result<std::path::PathBuf, String> {
    if let Some(rest) = src.strip_prefix("gripspace:") {
        // Format: gripspace:<name>:<path>
        if let Some(colon_pos) = rest.find(':') {
            let name = &rest[..colon_pos];
            let path = &rest[colon_pos + 1..];

            validate_gripspace_name(name)?;
            validate_relative_source_path(path, "gripspace path")?;

            return Ok(spaces_dir.join(name).join(path));
        }
        // Has "gripspace:" prefix but no second colon — malformed
        return Err(format!(
            "Malformed gripspace source '{}': expected format 'gripspace:<name>:<path>'",
            src
        ));
    }
    validate_relative_source_path(src, "manifest path")?;
    Ok(repo_path.join(src))
}

#[cfg(test)]
mod tests {
    use super::*;
    use crate::core::manifest::{ComposeFileConfig, ComposeFilePart};
    use tempfile::TempDir;

    #[test]
    fn test_process_composefiles_basic() {
        let temp = TempDir::new().unwrap();
        let workspace = temp.path();
        let manifests_dir = workspace.join(".gitgrip").join("manifests");
        let gripspaces_dir = workspace.join(".gitgrip").join("spaces");

        std::fs::create_dir_all(&manifests_dir).unwrap();
        std::fs::create_dir_all(gripspaces_dir.join("base-space")).unwrap();

        // Create source files
        std::fs::write(
            gripspaces_dir.join("base-space").join("BASE.md"),
            "# Base Content",
        )
        .unwrap();
        std::fs::write(manifests_dir.join("LOCAL.md"), "# Local Content").unwrap();

        let composefiles = vec![ComposeFileConfig {
            dest: "COMPOSED.md".to_string(),
            parts: vec![
                ComposeFilePart {
                    gripspace: Some("base-space".to_string()),
                    src: "BASE.md".to_string(),
                },
                ComposeFilePart {
                    gripspace: None,
                    src: "LOCAL.md".to_string(),
                },
            ],
            separator: None,
        }];

        let result =
            process_composefiles(workspace, &manifests_dir, &gripspaces_dir, &composefiles);
        assert!(result.is_ok());

        let content = std::fs::read_to_string(workspace.join("COMPOSED.md")).unwrap();
        assert_eq!(content, "# Base Content\n\n# Local Content");
    }

    #[test]
    fn test_process_composefiles_custom_separator() {
        let temp = TempDir::new().unwrap();
        let workspace = temp.path();
        let manifests_dir = workspace.join(".gitgrip").join("manifests");
        let gripspaces_dir = workspace.join(".gitgrip").join("spaces");

        std::fs::create_dir_all(&manifests_dir).unwrap();
        std::fs::create_dir_all(&gripspaces_dir).unwrap();

        std::fs::write(manifests_dir.join("PART1.md"), "Part 1").unwrap();
        std::fs::write(manifests_dir.join("PART2.md"), "Part 2").unwrap();

        let composefiles = vec![ComposeFileConfig {
            dest: "OUTPUT.md".to_string(),
            parts: vec![
                ComposeFilePart {
                    gripspace: None,
                    src: "PART1.md".to_string(),
                },
                ComposeFilePart {
                    gripspace: None,
                    src: "PART2.md".to_string(),
                },
            ],
            separator: Some("\n\n---\n\n".to_string()),
        }];

        let result =
            process_composefiles(workspace, &manifests_dir, &gripspaces_dir, &composefiles);
        assert!(result.is_ok());

        let content = std::fs::read_to_string(workspace.join("OUTPUT.md")).unwrap();
        assert_eq!(content, "Part 1\n\n---\n\nPart 2");
    }

    #[test]
    fn test_process_composefiles_missing_part() {
        let temp = TempDir::new().unwrap();
        let workspace = temp.path();
        let manifests_dir = workspace.join(".gitgrip").join("manifests");
        let gripspaces_dir = workspace.join(".gitgrip").join("spaces");

        std::fs::create_dir_all(&manifests_dir).unwrap();
        std::fs::create_dir_all(&gripspaces_dir).unwrap();

        std::fs::write(manifests_dir.join("EXISTS.md"), "I exist").unwrap();

        let composefiles = vec![ComposeFileConfig {
            dest: "OUTPUT.md".to_string(),
            parts: vec![
                ComposeFilePart {
                    gripspace: Some("nonexistent".to_string()),
                    src: "MISSING.md".to_string(),
                },
                ComposeFilePart {
                    gripspace: None,
                    src: "EXISTS.md".to_string(),
                },
            ],
            separator: None,
        }];

        let result =
            process_composefiles(workspace, &manifests_dir, &gripspaces_dir, &composefiles);
        assert!(result.is_ok());

        // Should still write the available part
        let content = std::fs::read_to_string(workspace.join("OUTPUT.md")).unwrap();
        assert_eq!(content, "I exist");
    }

    #[test]
    fn test_process_composefiles_creates_parent_dirs() {
        let temp = TempDir::new().unwrap();
        let workspace = temp.path();
        let manifests_dir = workspace.join(".gitgrip").join("manifests");
        let gripspaces_dir = workspace.join(".gitgrip").join("spaces");

        std::fs::create_dir_all(&manifests_dir).unwrap();
        std::fs::create_dir_all(&gripspaces_dir).unwrap();

        std::fs::write(manifests_dir.join("content.txt"), "hello").unwrap();

        let composefiles = vec![ComposeFileConfig {
            dest: "nested/dir/output.txt".to_string(),
            parts: vec![ComposeFilePart {
                gripspace: None,
                src: "content.txt".to_string(),
            }],
            separator: None,
        }];

        let result =
            process_composefiles(workspace, &manifests_dir, &gripspaces_dir, &composefiles);
        assert!(result.is_ok());
        assert!(workspace.join("nested/dir/output.txt").exists());
    }

    #[test]
    fn test_resolve_file_source_local() {
        let repo_path = Path::new("/workspace/repo");
        let gripspaces_dir = Path::new("/workspace/.gitgrip/spaces");
        let result = resolve_file_source("README.md", repo_path, gripspaces_dir).unwrap();
        assert_eq!(result, Path::new("/workspace/repo/README.md"));
    }

    #[test]
    fn test_resolve_file_source_gripspace() {
        let repo_path = Path::new("/workspace/.gitgrip/manifests");
        let gripspaces_dir = Path::new("/workspace/.gitgrip/spaces");
        let result =
            resolve_file_source("gripspace:base:CLAUDE.md", repo_path, gripspaces_dir).unwrap();
        assert_eq!(
            result,
            Path::new("/workspace/.gitgrip/spaces/base/CLAUDE.md")
        );
    }

    #[test]
    fn test_resolve_file_source_path_traversal_name() {
        let repo_path = Path::new("/workspace/repo");
        let gripspaces_dir = Path::new("/workspace/.gitgrip/spaces");
        let result =
            resolve_file_source("gripspace:../../../etc:passwd", repo_path, gripspaces_dir);
        assert!(result.is_err());
    }

    #[test]
    fn test_resolve_file_source_path_traversal_path() {
        let repo_path = Path::new("/workspace/repo");
        let gripspaces_dir = Path::new("/workspace/.gitgrip/spaces");
        let result = resolve_file_source(
            "gripspace:valid:../../etc/passwd",
            repo_path,
            gripspaces_dir,
        );
        assert!(result.is_err());
    }

    #[test]
    fn test_resolve_file_source_empty_name() {
        let repo_path = Path::new("/workspace/repo");
        let gripspaces_dir = Path::new("/workspace/.gitgrip/spaces");
        let result = resolve_file_source("gripspace::file.md", repo_path, gripspaces_dir);
        assert!(result.is_err());
    }

    #[test]
    fn test_resolve_file_source_local_path_traversal() {
        let repo_path = Path::new("/workspace/repo");
        let gripspaces_dir = Path::new("/workspace/.gitgrip/spaces");
        let result = resolve_file_source("../outside.txt", repo_path, gripspaces_dir);
        assert!(result.is_err());
    }

    #[test]
    fn test_resolve_file_source_local_windows_absolute_path() {
        let repo_path = Path::new("/workspace/repo");
        let gripspaces_dir = Path::new("/workspace/.gitgrip/spaces");
        let result = resolve_file_source("C:\\Windows\\System32\\etc", repo_path, gripspaces_dir);
        assert!(result.is_err());
    }

    #[test]
    fn test_process_composefiles_dest_path_traversal() {
        let temp = TempDir::new().unwrap();
        let workspace = temp.path();
        let manifests_dir = workspace.join(".gitgrip").join("manifests");
        let gripspaces_dir = workspace.join(".gitgrip").join("spaces");

        std::fs::create_dir_all(&manifests_dir).unwrap();
        std::fs::create_dir_all(&gripspaces_dir).unwrap();
        std::fs::write(manifests_dir.join("file.md"), "content").unwrap();

        let composefiles = vec![ComposeFileConfig {
            dest: "../escaped.md".to_string(),
            parts: vec![ComposeFilePart {
                gripspace: None,
                src: "file.md".to_string(),
            }],
            separator: None,
        }];

        let result =
            process_composefiles(workspace, &manifests_dir, &gripspaces_dir, &composefiles);
        assert!(result.is_err());
    }

    #[test]
    fn test_process_composefiles_dest_windows_absolute_path() {
        let temp = TempDir::new().unwrap();
        let workspace = temp.path();
        let manifests_dir = workspace.join(".gitgrip").join("manifests");
        let gripspaces_dir = workspace.join(".gitgrip").join("spaces");

        std::fs::create_dir_all(&manifests_dir).unwrap();
        std::fs::create_dir_all(&gripspaces_dir).unwrap();
        std::fs::write(manifests_dir.join("file.md"), "content").unwrap();

        let composefiles = vec![ComposeFileConfig {
            dest: "C:\\temp\\escaped.md".to_string(),
            parts: vec![ComposeFilePart {
                gripspace: None,
                src: "file.md".to_string(),
            }],
            separator: None,
        }];

        let result =
            process_composefiles(workspace, &manifests_dir, &gripspaces_dir, &composefiles);
        assert!(result.is_err());
    }

    #[test]
    fn test_process_composefiles_invalid_gripspace_name() {
        let temp = TempDir::new().unwrap();
        let workspace = temp.path();
        let manifests_dir = workspace.join(".gitgrip").join("manifests");
        let gripspaces_dir = workspace.join(".gitgrip").join("spaces");

        std::fs::create_dir_all(&manifests_dir).unwrap();
        std::fs::create_dir_all(&gripspaces_dir).unwrap();
        std::fs::write(manifests_dir.join("fallback.md"), "ok").unwrap();

        // A composefile part with invalid gripspace name should be skipped
        let composefiles = vec![ComposeFileConfig {
            dest: "output.md".to_string(),
            parts: vec![
                ComposeFilePart {
                    gripspace: Some("../evil".to_string()),
                    src: "file.md".to_string(),
                },
                ComposeFilePart {
                    gripspace: None,
                    src: "fallback.md".to_string(),
                },
            ],
            separator: None,
        }];

        let result =
            process_composefiles(workspace, &manifests_dir, &gripspaces_dir, &composefiles);
        assert!(result.is_ok());

        // Only the valid part should be written
        let content = std::fs::read_to_string(workspace.join("output.md")).unwrap();
        assert_eq!(content, "ok");
    }

    #[test]
    fn test_resolve_file_source_malformed_gripspace_no_second_colon() {
        let repo_path = Path::new("/workspace/repo");
        let gripspaces_dir = Path::new("/workspace/.gitgrip/spaces");
        let result = resolve_file_source("gripspace:only-name", repo_path, gripspaces_dir);
        assert!(result.is_err());
        assert!(result.unwrap_err().contains("Malformed gripspace source"));
    }

    #[test]
    fn test_resolve_file_source_backslash_path() {
        let repo_path = Path::new("/workspace/repo");
        let gripspaces_dir = Path::new("/workspace/.gitgrip/spaces");
        let result =
            resolve_file_source("gripspace:valid:\\etc\\passwd", repo_path, gripspaces_dir);
        assert!(result.is_err());
    }

    #[test]
    fn test_process_composefiles_dest_backslash_rejected() {
        let temp = TempDir::new().unwrap();
        let workspace = temp.path();
        let manifests_dir = workspace.join(".gitgrip").join("manifests");
        let gripspaces_dir = workspace.join(".gitgrip").join("spaces");

        std::fs::create_dir_all(&manifests_dir).unwrap();
        std::fs::create_dir_all(&gripspaces_dir).unwrap();
        std::fs::write(manifests_dir.join("file.md"), "content").unwrap();

        let composefiles = vec![ComposeFileConfig {
            dest: "\\escaped.md".to_string(),
            parts: vec![ComposeFilePart {
                gripspace: None,
                src: "file.md".to_string(),
            }],
            separator: None,
        }];

        let result =
            process_composefiles(workspace, &manifests_dir, &gripspaces_dir, &composefiles);
        assert!(result.is_err());
    }
}