diff --git a/atomic-cli/src/commands/clone/command.rs b/atomic-cli/src/commands/clone/command.rs index cfd5b627..766e2e3e 100644 --- a/atomic-cli/src/commands/clone/command.rs +++ b/atomic-cli/src/commands/clone/command.rs @@ -26,9 +26,11 @@ //! resolution. If the clone fails partway through, the `CleanupGuard` //! ensures the partially created directory is removed. +use std::path::Path; use std::time::Duration; use clap::Parser; +use git2::Repository as GitRepository; use atomic_core::types::Base32; use atomic_remote::{HttpRemote, HttpRemoteConfig}; @@ -38,7 +40,8 @@ use crate::commands::Command; use crate::error::{CliError, CliResult}; use crate::output::{ create_progress_bar, create_spinner, error, finish_error, finish_success, hash as style_hash, - hint, print_blank, print_hint, print_success, print_warning, success, view as style_view, + hint, print_blank, print_hint, print_info, print_success, print_warning, success, + view as style_view, }; use super::helpers::{ @@ -135,6 +138,61 @@ pub struct Clone { /// Useful for examining changes before applying. #[arg(long)] pub download_only: bool, + + /// Bootstrap Atomic in an existing Git checkout without materializing + /// Atomic content over Git's working tree. + #[arg(long, requires = "path", conflicts_with = "download_only")] + pub into_existing: bool, +} + +fn validate_existing_git_checkout(path: &Path) -> CliResult<()> { + if !path.is_dir() { + return Err(CliError::InvalidPath { + path: path.to_path_buf(), + source: None, + }); + } + + let git_repo = GitRepository::discover(path).map_err(|_| CliError::InvalidArgument { + message: format!( + "--into-existing requires an existing Git checkout: {}", + path.display() + ), + })?; + + let workdir = git_repo + .workdir() + .ok_or_else(|| CliError::InvalidArgument { + message: format!( + "--into-existing requires a non-bare Git checkout: {}", + path.display() + ), + })?; + + let target = std::fs::canonicalize(path).map_err(|e| CliError::InvalidPath { + path: path.to_path_buf(), + source: Some(e), + })?; + let workdir = std::fs::canonicalize(workdir).map_err(|e| CliError::InvalidPath { + path: workdir.to_path_buf(), + source: Some(e), + })?; + if target != workdir { + return Err(CliError::InvalidArgument { + message: format!( + "--into-existing must target the Git worktree root: {}", + path.display() + ), + }); + } + + if path.join(".atomic").exists() { + return Err(CliError::RepositoryExists { + path: path.join(".atomic"), + }); + } + + Ok(()) } impl Clone { @@ -161,6 +219,7 @@ impl Clone { insecure: false, timeout: DEFAULT_TIMEOUT_SECS, download_only: false, + into_existing: false, } } @@ -194,6 +253,12 @@ impl Clone { self } + /// Builder: bootstrap an existing Git checkout. + pub fn with_into_existing(mut self, into_existing: bool) -> Self { + self.into_existing = into_existing; + self + } + // Internal Helper Methods /// Build the HTTP remote configuration. @@ -236,26 +301,35 @@ impl Clone { ); print_blank(); - // Validate target doesn't exist - validate_target_path(&target_path)?; - - // Create cleanup guard - will remove directory if we fail - let guard = CleanupGuard::new(target_path.clone()); - - // Create target directory - std::fs::create_dir_all(&target_path).map_err(|e| CliError::InvalidPath { - path: target_path.clone(), - source: Some(e), - })?; + let guard = if self.into_existing { + validate_existing_git_checkout(&target_path)?; + None + } else { + validate_target_path(&target_path)?; + std::fs::create_dir_all(&target_path).map_err(|e| CliError::InvalidPath { + path: target_path.clone(), + source: Some(e), + })?; + Some(CleanupGuard::new(target_path.clone())) + }; // Initialize repository let spinner = create_spinner("Initializing repository..."); - let repo = Repository::init(&target_path).map_err(|e| { + let mut repo = Repository::init(&target_path).map_err(|e| { finish_error(&spinner, "Failed to initialize"); CliError::Repository(e) })?; finish_success(&spinner, "Repository initialized"); + // Clone must insert remote changes into the requested local view, + // rather than whichever default view repository initialization chose. + if !repo.view_exists(&self.view).map_err(CliError::Repository)? { + repo.create_shared_view(&self.view) + .map_err(CliError::Repository)?; + } + repo.align_to_view(&self.view) + .map_err(CliError::Repository)?; + // Connect to remote let spinner = create_spinner("Connecting to remote..."); let config = self.build_remote_config().await; @@ -294,7 +368,9 @@ impl Clone { )); // Disable cleanup guard - clone succeeded - guard.disable(); + if let Some(guard) = guard { + guard.disable(); + } return Ok(()); } @@ -446,7 +522,9 @@ impl Clone { print_hint("Use 'atomic insert' to insert the downloaded changes"); // Disable cleanup guard - clone succeeded - guard.disable(); + if let Some(guard) = guard { + guard.disable(); + } return Ok(()); } @@ -488,17 +566,21 @@ impl Clone { } } - // Output the working copy — reconstruct files from the graph - match repo.materialize() { - Ok(output) => { - log::info!( - "Output working copy: {} files, {} dirs", - output.files_written, - output.directories_created - ); - } - Err(e) => { - apply_errors.push(format!("output working copy: {}", e)); + if self.into_existing { + print_info("Preserving the existing Git working copy."); + } else { + // Output the working copy — reconstruct files from the graph + match repo.materialize() { + Ok(output) => { + log::info!( + "Output working copy: {} files, {} dirs", + output.files_written, + output.directories_created + ); + } + Err(e) => { + apply_errors.push(format!("output working copy: {}", e)); + } } } @@ -590,8 +672,14 @@ impl Clone { )); } + if self.into_existing { + print_hint("Next: run 'atomic git import --incremental' to import the Git checkout."); + } + // Disable cleanup guard - clone succeeded - guard.disable(); + if let Some(guard) = guard { + guard.disable(); + } Ok(()) } @@ -653,6 +741,7 @@ mod tests { assert!(!clone.insecure); assert_eq!(clone.timeout, DEFAULT_TIMEOUT_SECS); assert!(!clone.download_only); + assert!(!clone.into_existing); } /// Test Default trait implementation. @@ -698,6 +787,12 @@ mod tests { assert!(clone.download_only); } + #[test] + fn test_clone_with_into_existing() { + let clone = Clone::new("https://example.com/repo".to_string()).with_into_existing(true); + assert!(clone.into_existing); + } + /// Test chaining multiple builder methods. #[test] fn test_clone_builder_chain() { @@ -706,7 +801,8 @@ mod tests { .with_view("dev") .with_insecure(true) .with_timeout(120) - .with_download_only(true); + .with_download_only(true) + .with_into_existing(true); assert_eq!(clone.url, "https://example.com/repo"); assert_eq!(clone.path, Some("my-project".to_string())); @@ -714,6 +810,7 @@ mod tests { assert!(clone.insecure); assert_eq!(clone.timeout, 120); assert!(clone.download_only); + assert!(clone.into_existing); } /// Test Clone can be cloned (the trait, not the command). @@ -790,6 +887,43 @@ mod tests { assert_eq!(clone.get_display_name(), "repo"); } + #[test] + fn test_validate_existing_git_checkout_accepts_git_worktree() { + let dir = tempfile::tempdir().unwrap(); + GitRepository::init(dir.path()).unwrap(); + + assert!(validate_existing_git_checkout(dir.path()).is_ok()); + } + + #[test] + fn test_validate_existing_git_checkout_rejects_non_git_directory() { + let dir = tempfile::tempdir().unwrap(); + + assert!(validate_existing_git_checkout(dir.path()).is_err()); + } + + #[test] + fn test_validate_existing_git_checkout_rejects_git_subdirectory() { + let dir = tempfile::tempdir().unwrap(); + GitRepository::init(dir.path()).unwrap(); + let child = dir.path().join("child"); + std::fs::create_dir(&child).unwrap(); + + assert!(validate_existing_git_checkout(&child).is_err()); + } + + #[test] + fn test_validate_existing_git_checkout_rejects_atomic_repository() { + let dir = tempfile::tempdir().unwrap(); + GitRepository::init(dir.path()).unwrap(); + std::fs::create_dir(dir.path().join(".atomic")).unwrap(); + + assert!(matches!( + validate_existing_git_checkout(dir.path()), + Err(CliError::RepositoryExists { .. }) + )); + } + // Constant Tests /// Test that DEFAULT_VIEW is "dev" (atomic-api convention). diff --git a/atomic-repository/src/repository/switch.rs b/atomic-repository/src/repository/switch.rs index ac52b60b..04413621 100644 --- a/atomic-repository/src/repository/switch.rs +++ b/atomic-repository/src/repository/switch.rs @@ -310,8 +310,9 @@ impl Repository { let name = entry.file_name(); let name_str = name.to_string_lossy(); - // Never move .atomic into the working copy - if name_str == DOT_DIR { + // Never move VCS administrative directories into the working copy. + // `.git` belongs to Git's checkout and must not be view-scoped. + if name_str == DOT_DIR || name_str == ".git" { continue; } @@ -393,8 +394,10 @@ impl Repository { Err(_) => continue, }; - // Never touch the .atomic directory itself. - if rel.starts_with(DOT_DIR) { + // Never touch VCS administrative directories. `.git` can be + // ignored by `.atomicignore` after `atomic git import`, but + // it remains owned by Git rather than a view workspace. + if rel.starts_with(DOT_DIR) || rel.starts_with(".git") { continue; } diff --git a/tests/harness/19_git_shadow.sh b/tests/harness/19_git_shadow.sh index 21fcebea..53ec3fe6 100755 --- a/tests/harness/19_git_shadow.sh +++ b/tests/harness/19_git_shadow.sh @@ -307,7 +307,88 @@ else fi # ════════════════════════════════════════════════════════════════════════ -# Section 9: GitLab MR format detection +# Section 9: Git-owned materialization after importing all local branches +# ════════════════════════════════════════════════════════════════════════ + +begin_section "Git shadow: Git owns the checked-out branch" + +make_temp_repo "git-owned-materialization" +init_git_repo + +git_commit "Main baseline" "shared.txt" "main baseline" +PRIMARY_BRANCH=$(git_default_branch) +git checkout -b zz-materialization 2>/dev/null +git_commit "Feature content" "feature-only.txt" "feature content" +printf '#!/bin/sh\necho feature\n' > feature-tool.sh +chmod +x feature-tool.sh +ln -s shared.txt feature-link +git add feature-tool.sh feature-link +git commit --quiet -m "Add executable and symlink" +git checkout "$PRIMARY_BRANCH" 2>/dev/null + +# `--all` imports every local Git branch. Git remains checked out on the +# primary branch, so Atomic must not leave the worktree materialized as the +# final non-HEAD Atomic view. +assert_success "import all local branches" atomic git import --all --no-vault + +assert_file_not_exists "feature file is absent from Git's checked-out branch" "feature-only.txt" +assert_file_not_exists "feature executable is absent from Git's checked-out branch" "feature-tool.sh" +assert_file_not_exists "feature symlink is absent from Git's checked-out branch" "feature-link" +assert_file_content "primary branch content survives import" "shared.txt" "main baseline" + +GIT_STATUS_AFTER_ALL=$(git status --short) +if [[ -z "$GIT_STATUS_AFTER_ALL" ]]; then + _pass "git status stays clean after all-branch import" +else + _fail "git status stays clean after all-branch import" "$GIT_STATUS_AFTER_ALL" +fi + +# Switching branches remains a Git-owned materialization. Incremental import +# must index this checkout rather than writing Atomic's version over it. +git checkout zz-materialization 2>/dev/null +assert_success "incremental import of checked-out feature" atomic git import --incremental --branch zz-materialization --no-vault +assert_file_content "feature checkout remains intact" "feature-only.txt" "feature content" +if [[ -x feature-tool.sh ]]; then + _pass "Git executable bit remains intact" +else + _fail "Git executable bit remains intact" "feature-tool.sh is not executable" +fi +if [[ -L feature-link ]]; then + _pass "Git symlink type remains intact" +else + _fail "Git symlink type remains intact" "feature-link is not a symlink" +fi + +GIT_STATUS_AFTER_FEATURE=$(git status --short) +if [[ -z "$GIT_STATUS_AFTER_FEATURE" ]]; then + _pass "git status stays clean after checked-out feature import" +else + _fail "git status stays clean after checked-out feature import" "$GIT_STATUS_AFTER_FEATURE" +fi + +# Switching views must not move Git's administrative state even though `.git` +# is ignored by the Atomic repository after Git import. Git remains able to +# own and restore its checked-out worktree after the switch. +assert_success "Atomic view switch materializes primary view" atomic view switch "$PRIMARY_BRANCH" +assert_dir_exists "Atomic view switch preserves Git metadata" ".git" +GIT_STATUS_AFTER_ATOMIC_SWITCH=$(git status --short) +if [[ -z "$GIT_STATUS_AFTER_ATOMIC_SWITCH" ]]; then + _pass "Atomic view switch preserves a clean Git checkout" +else + _fail "Atomic view switch preserves a clean Git checkout" "$GIT_STATUS_AFTER_ATOMIC_SWITCH" +fi +git checkout "$PRIMARY_BRANCH" 2>/dev/null +assert_success "incremental import restores Git-owned primary checkout" atomic git import --incremental --branch "$PRIMARY_BRANCH" --no-vault + +GIT_STATUS_AFTER_RESTORE=$(git status --short) +if [[ -z "$GIT_STATUS_AFTER_RESTORE" ]]; then + _pass "Git checkout restores a clean shared worktree" +else + _fail "Git checkout restores a clean shared worktree" "$GIT_STATUS_AFTER_RESTORE" +fi + +# ════════════════════════════════════════════════════════════════════════ +# Section 10: GitLab MR format detection # ════════════════════════════════════════════════════════════════════════ begin_section "Multi-forge: GitLab MR format"