Skip to main content

nerdbank_gitversioning/
git_context.rs

1// Copyright (c) .NET Foundation and Contributors. All rights reserved.
2// Licensed under the MIT license. See LICENSE file in the project root for full license information.
3
4//! Repository discovery and the Git operations used by version calculation.
5//!
6//! This module deliberately does not read version files or walk history. It owns the
7//! selected commit and provides the small, testable repository surface those layers need.
8
9use std::env;
10use std::path::{Path, PathBuf};
11
12use chrono::{DateTime, FixedOffset, TimeZone};
13use git2::{BranchType, Commit, ErrorCode, Oid, Repository, Status};
14
15use crate::{Error, Result};
16
17const NO_REPOSITORY_MESSAGE: &str = "Not a git repo";
18const DISABLED_COMMIT_ID: &str = "nerdbankdisabled";
19
20/// Selects how repository operations are performed.
21#[derive(Clone, Copy, Debug, Default, Eq, PartialEq)]
22pub enum GitEngine {
23    /// Opens the repository but rejects mutations.
24    #[default]
25    ReadOnly,
26
27    /// Opens the repository and permits mutations.
28    ReadWrite,
29
30    /// Does not open the repository or calculate Git-derived values.
31    Disabled,
32}
33
34/// Describes what kind of context was created.
35#[derive(Clone, Copy, Debug, Eq, PartialEq)]
36pub enum GitContextKind {
37    /// A repository was found and opened.
38    Repository,
39
40    /// A repository was found, but Git was explicitly disabled.
41    Disabled,
42
43    /// No repository was found.
44    NoRepository,
45}
46
47/// The author and committer timestamps for a commit.
48#[derive(Clone, Copy, Debug, Eq, PartialEq)]
49pub struct CommitDates {
50    /// The time recorded for the commit's author.
51    pub author: DateTime<FixedOffset>,
52
53    /// The time recorded for the committer.
54    pub committer: DateTime<FixedOffset>,
55}
56
57/// Represents a directory and selected commit within a Git repository.
58pub struct GitContext {
59    repository: Option<Repository>,
60    kind: GitContextKind,
61    engine: GitEngine,
62    working_tree_path: PathBuf,
63    git_directory: Option<PathBuf>,
64    repo_relative_project_directory: PathBuf,
65    selected_commit: Option<Oid>,
66}
67
68impl GitContext {
69    /// Discovers a repository from `path` or one of its ancestors.
70    ///
71    /// Git's own discovery is used, so linked worktrees and textual `.git` files are
72    /// supported. A path outside a repository produces a usable [`GitContextKind::NoRepository`]
73    /// context. Bare repositories are rejected because version calculation requires a
74    /// working tree.
75    pub fn create(
76        path: impl AsRef<Path>,
77        committish: Option<&str>,
78        engine: GitEngine,
79    ) -> Result<Self> {
80        let requested_path = absolute_path(path.as_ref())?;
81        match Repository::discover(&requested_path) {
82            Ok(repository) => Self::from_repository(repository, requested_path, committish, engine),
83            Err(error) if error.code() == ErrorCode::NotFound => {
84                Ok(Self::without_repository(requested_path, engine))
85            }
86            Err(error) => Err(error.into()),
87        }
88    }
89
90    /// Creates a context using the effective engine selected by environment policy.
91    pub fn create_with_environment(
92        path: impl AsRef<Path>,
93        committish: Option<&str>,
94        default_engine: GitEngine,
95    ) -> Result<Self> {
96        Self::create(path, committish, effective_git_engine(default_engine))
97    }
98
99    /// Gets the kind of context that was created.
100    pub fn kind(&self) -> GitContextKind {
101        self.kind
102    }
103
104    /// Gets the requested Git engine.
105    pub fn engine(&self) -> GitEngine {
106        self.engine
107    }
108
109    /// Gets whether an actual repository backs this context.
110    pub fn is_repository(&self) -> bool {
111        self.git_directory.is_some()
112    }
113
114    /// Gets the absolute root of the working tree.
115    pub fn working_tree_path(&self) -> &Path {
116        &self.working_tree_path
117    }
118
119    /// Gets the repository metadata directory. In a linked worktree this is the
120    /// worktree-specific Git directory, not necessarily `<working tree>/.git`.
121    pub fn git_directory(&self) -> Option<&Path> {
122        self.git_directory.as_deref()
123    }
124
125    /// Gets the directory selected for version calculation, relative to the working tree.
126    pub fn repo_relative_project_directory(&self) -> &Path {
127        &self.repo_relative_project_directory
128    }
129
130    /// Selects the directory used by higher version-file layers.
131    pub fn set_repo_relative_project_directory(
132        &mut self,
133        directory: impl AsRef<Path>,
134    ) -> Result<()> {
135        let directory = directory.as_ref();
136        if directory.is_absolute() {
137            return Err(Error::InvalidFormat(format!(
138                "Path '{}' must be relative to the working tree.",
139                directory.display()
140            )));
141        }
142
143        self.repo_relative_project_directory = directory.to_path_buf();
144        Ok(())
145    }
146
147    /// Gets the absolute directory selected for version calculation.
148    pub fn absolute_project_directory(&self) -> PathBuf {
149        self.working_tree_path
150            .join(&self.repo_relative_project_directory)
151    }
152
153    /// Exposes the repository to the future version-file and history layers.
154    pub fn repository(&self) -> Option<&Repository> {
155        self.repository.as_ref()
156    }
157
158    /// Gets the selected commit ID.
159    pub fn git_commit_id(&self) -> Option<Oid> {
160        self.selected_commit
161    }
162
163    /// Gets whether the selected commit is the commit at `HEAD`.
164    pub fn is_head(&self) -> Result<bool> {
165        let Some(selected) = self.selected_commit else {
166            return Ok(false);
167        };
168        let Some(repository) = &self.repository else {
169            return Ok(false);
170        };
171
172        match repository.head().and_then(|head| head.peel_to_commit()) {
173            Ok(head) => Ok(head.id() == selected),
174            Err(error) if matches!(error.code(), ErrorCode::UnbornBranch | ErrorCode::NotFound) => {
175                Ok(false)
176            }
177            Err(error) => Err(error.into()),
178        }
179    }
180
181    /// Gets the selected commit's author and committer timestamps.
182    pub fn git_commit_dates(&self) -> Result<Option<CommitDates>> {
183        let Some(commit) = self.selected_commit()? else {
184            return Ok(None);
185        };
186
187        Ok(Some(CommitDates {
188            author: convert_time(commit.author().when())?,
189            committer: convert_time(commit.committer().when())?,
190        }))
191    }
192
193    /// Gets the canonical name of `HEAD`, such as `refs/heads/main`.
194    ///
195    /// A detached `HEAD` is reported as `HEAD`; an unborn repository has no name.
196    pub fn head_canonical_name(&self) -> Result<Option<String>> {
197        let Some(repository) = &self.repository else {
198            return Ok(None);
199        };
200
201        match repository.head() {
202            Ok(head) => Ok(Some(head.name()?.to_owned())),
203            Err(error) if matches!(error.code(), ErrorCode::UnbornBranch | ErrorCode::NotFound) => {
204                Ok(None)
205            }
206            Err(error) => Err(error.into()),
207        }
208    }
209
210    /// Gets canonical tag names that resolve to the selected commit.
211    ///
212    /// Annotated tags are peeled before comparison.
213    pub fn head_tags(&self) -> Result<Option<Vec<String>>> {
214        let Some(selected) = self.selected_commit else {
215            return Ok(None);
216        };
217        let Some(repository) = &self.repository else {
218            return Ok(None);
219        };
220        let mut tags = Vec::new();
221        for reference in repository.references_glob("refs/tags/*")? {
222            let reference = reference?;
223            if reference.peel_to_commit().map(|commit| commit.id()).ok() == Some(selected)
224                && let Ok(name) = reference.name()
225            {
226                tags.push(name.to_owned());
227            }
228        }
229        tags.sort();
230        Ok(Some(tags))
231    }
232
233    /// Gets whether the repository is shallow.
234    ///
235    /// libgit2 checks the common repository directory, which also handles linked
236    /// worktrees correctly.
237    pub fn is_shallow(&self) -> bool {
238        self.repository.as_ref().is_some_and(Repository::is_shallow)
239    }
240
241    /// Gets whether tracked, untracked, or staged working-tree changes exist.
242    pub fn is_working_tree_dirty(&self) -> Result<bool> {
243        let Some(repository) = &self.repository else {
244            return Ok(false);
245        };
246        Ok(repository.statuses(None)?.iter().any(|entry| {
247            let status = entry.status();
248            status != Status::CURRENT && !status.contains(Status::IGNORED)
249        }))
250    }
251
252    /// Determines whether Git would ignore `path`.
253    pub fn is_ignored(&self, path: impl AsRef<Path>) -> Result<bool> {
254        let Some(repository) = &self.repository else {
255            return Ok(false);
256        };
257        let relative = self.repo_relative_path(path.as_ref())?;
258        Ok(repository.status_should_ignore(&relative)?)
259    }
260
261    /// Attempts to select a commit using any revparse-compatible committish.
262    ///
263    /// Tags (including annotated tags), local and remote branches, abbreviated IDs,
264    /// and first-parent expressions such as `HEAD~2` are accepted.
265    pub fn try_select_commit(&mut self, committish: &str) -> Result<bool> {
266        match self.kind {
267            GitContextKind::Disabled => return Ok(true),
268            GitContextKind::NoRepository => return Err(no_repository_error()),
269            GitContextKind::Repository => {}
270        }
271
272        let repository = self.repository.as_ref().expect("repository context");
273        match resolve_commit(repository, committish) {
274            Ok(commit) => {
275                self.selected_commit = Some(commit);
276                Ok(true)
277            }
278            Err(error)
279                if matches!(
280                    error.code(),
281                    ErrorCode::NotFound
282                        | ErrorCode::Ambiguous
283                        | ErrorCode::InvalidSpec
284                        | ErrorCode::Peel
285                ) =>
286            {
287                Ok(false)
288            }
289            Err(error) => Err(error.into()),
290        }
291    }
292
293    /// Creates a lightweight tag at the selected commit.
294    pub fn apply_tag(&self, name: &str) -> Result<Oid> {
295        self.ensure_writable()?;
296        let repository = self.repository.as_ref().expect("repository context");
297        let commit = self
298            .selected_commit()?
299            .ok_or_else(|| Error::InvalidOperation("No commit is selected.".to_owned()))?;
300        Ok(repository.tag_lightweight(name, commit.as_object(), false)?)
301    }
302
303    /// Adds a path to the index and writes the updated index.
304    pub fn stage(&self, path: impl AsRef<Path>) -> Result<()> {
305        self.ensure_writable()?;
306        let repository = self.repository.as_ref().expect("repository context");
307        let relative = self.repo_relative_path(path.as_ref())?;
308        let mut index = repository.index()?;
309        index.add_path(&relative)?;
310        index.write()?;
311        Ok(())
312    }
313
314    /// Gets the shortest object ID of at least `min_length` characters that uniquely
315    /// identifies the selected commit in this object database.
316    pub fn short_unique_commit_id(&self, min_length: usize) -> Result<String> {
317        match self.kind {
318            GitContextKind::Disabled => return Ok(DISABLED_COMMIT_ID.to_owned()),
319            GitContextKind::NoRepository => return Err(no_repository_error()),
320            GitContextKind::Repository => {}
321        }
322        let selected = self
323            .selected_commit
324            .ok_or_else(|| Error::InvalidOperation("No commit is selected.".to_owned()))?;
325        self.short_unique_id(selected, min_length)
326    }
327
328    /// Gets a shortest unique ID for an arbitrary commit.
329    pub fn short_unique_id(&self, commit_id: Oid, min_length: usize) -> Result<String> {
330        match self.kind {
331            GitContextKind::Disabled => return Ok(DISABLED_COMMIT_ID.to_owned()),
332            GitContextKind::NoRepository => return Err(no_repository_error()),
333            GitContextKind::Repository => {}
334        }
335        if !(1..=40).contains(&min_length) {
336            return Err(Error::InvalidFormat(
337                "A short commit ID length must be between 1 and 40.".to_owned(),
338            ));
339        }
340
341        let repository = self.repository.as_ref().expect("repository context");
342        repository.find_commit(commit_id)?;
343        let full_id = commit_id.to_string();
344        let mut length = min_length;
345        let odb = repository.odb()?;
346        while length < full_id.len() {
347            let prefix = &full_id[..length];
348            let mut collision = false;
349            odb.foreach(|candidate| {
350                if *candidate != commit_id && candidate.to_string().starts_with(prefix) {
351                    collision = true;
352                }
353                true
354            })?;
355            if !collision {
356                break;
357            }
358            length += 1;
359        }
360        Ok(full_id[..length].to_owned())
361    }
362
363    /// Detects the repository's default branch using remote HEADs, local configuration,
364    /// and conventional names, in that order.
365    pub fn default_branch(&self) -> Result<String> {
366        let Some(repository) = &self.repository else {
367            return Ok("master".to_owned());
368        };
369
370        let remotes = repository.remotes()?;
371        let mut remote_names = Vec::new();
372        for remote in remotes.iter() {
373            if let Some(name) = remote? {
374                remote_names.push(name.to_owned());
375            }
376        }
377        for preferred in ["upstream", "origin"] {
378            if remote_names.iter().any(|name| name == preferred)
379                && let Some(branch) = remote_default_branch(repository, preferred)?
380            {
381                return Ok(branch);
382            }
383        }
384        for remote in &remote_names {
385            if remote != "upstream"
386                && remote != "origin"
387                && let Some(branch) = remote_default_branch(repository, remote)?
388            {
389                return Ok(branch);
390            }
391        }
392
393        let mut local_branches = Vec::new();
394        for branch in repository.branches(Some(BranchType::Local))? {
395            let (branch, _) = branch?;
396            if let Some(name) = branch.name()? {
397                local_branches.push(name.to_owned());
398            }
399        }
400        if local_branches.len() == 1 {
401            return Ok(local_branches.remove(0));
402        }
403        if let Ok(configured) = repository.config()?.get_string("init.defaultBranch")
404            && local_branches.iter().any(|branch| branch == &configured)
405        {
406            return Ok(configured);
407        }
408        for conventional in ["master", "main", "develop"] {
409            if local_branches.iter().any(|branch| branch == conventional) {
410                return Ok(conventional.to_owned());
411            }
412        }
413        Ok("master".to_owned())
414    }
415
416    fn from_repository(
417        repository: Repository,
418        requested_path: PathBuf,
419        committish: Option<&str>,
420        engine: GitEngine,
421    ) -> Result<Self> {
422        let working_tree_path = repository.workdir().ok_or_else(|| {
423            Error::InvalidOperation("Bare repositories are not supported.".to_owned())
424        })?;
425        let working_tree_path = trim_trailing_separator(&absolute_path(working_tree_path)?);
426        let git_directory = trim_trailing_separator(repository.path());
427        let relative = requested_path
428            .strip_prefix(&working_tree_path)
429            .unwrap_or(Path::new(""))
430            .to_path_buf();
431
432        if engine == GitEngine::Disabled {
433            return Ok(Self {
434                repository: None,
435                kind: GitContextKind::Disabled,
436                engine,
437                working_tree_path,
438                git_directory: Some(git_directory),
439                repo_relative_project_directory: relative,
440                selected_commit: None,
441            });
442        }
443
444        let selected_commit = match committish {
445            Some(spec) => Some(resolve_commit(&repository, spec).map_err(|_| {
446                Error::InvalidFormat(format!("No matching commit found for '{spec}'."))
447            })?),
448            None => match repository.head().and_then(|head| head.peel_to_commit()) {
449                Ok(commit) => Some(commit.id()),
450                Err(error)
451                    if matches!(error.code(), ErrorCode::UnbornBranch | ErrorCode::NotFound) =>
452                {
453                    None
454                }
455                Err(error) => return Err(error.into()),
456            },
457        };
458
459        Ok(Self {
460            repository: Some(repository),
461            kind: GitContextKind::Repository,
462            engine,
463            working_tree_path,
464            git_directory: Some(git_directory),
465            repo_relative_project_directory: relative,
466            selected_commit,
467        })
468    }
469
470    fn without_repository(path: PathBuf, engine: GitEngine) -> Self {
471        let root = path
472            .ancestors()
473            .last()
474            .map(Path::to_path_buf)
475            .unwrap_or_else(|| path.clone());
476        let relative = path
477            .strip_prefix(&root)
478            .unwrap_or(Path::new(""))
479            .to_path_buf();
480        Self {
481            repository: None,
482            kind: GitContextKind::NoRepository,
483            engine,
484            working_tree_path: root,
485            git_directory: None,
486            repo_relative_project_directory: relative,
487            selected_commit: None,
488        }
489    }
490
491    fn selected_commit(&self) -> Result<Option<Commit<'_>>> {
492        match (&self.repository, self.selected_commit) {
493            (Some(repository), Some(commit)) => Ok(Some(repository.find_commit(commit)?)),
494            _ => Ok(None),
495        }
496    }
497
498    fn repo_relative_path(&self, path: &Path) -> Result<PathBuf> {
499        if path.is_absolute() {
500            let path = absolute_path(path)?;
501            path.strip_prefix(&self.working_tree_path)
502                .map(Path::to_path_buf)
503                .map_err(|_| {
504                    Error::InvalidFormat(format!(
505                        "Path '{}' is not within repository '{}'.",
506                        path.display(),
507                        self.working_tree_path.display()
508                    ))
509                })
510        } else {
511            Ok(path.to_path_buf())
512        }
513    }
514
515    fn ensure_writable(&self) -> Result<()> {
516        match self.kind {
517            GitContextKind::Disabled => Err(Error::InvalidOperation(
518                "Git operations are disabled.".to_owned(),
519            )),
520            GitContextKind::NoRepository => Err(no_repository_error()),
521            GitContextKind::Repository if self.engine != GitEngine::ReadWrite => Err(
522                Error::InvalidOperation("The Git context is read-only.".to_owned()),
523            ),
524            GitContextKind::Repository => Ok(()),
525        }
526    }
527}
528
529/// Gets the effective Git engine after applying `NBGV_GitEngine`, Dependabot, and
530/// GitHub Copilot policy.
531///
532/// `NBGV_GitEngine` has precedence and accepts the case-sensitive compatibility
533/// values `LibGit2`, `Managed`, and `Disabled`. Unknown values are ignored.
534/// Otherwise `DEPENDABOT=true` (case-insensitive) or the exact GitHub actor
535/// `copilot-swe-agent[bot]` disables Git.
536pub fn effective_git_engine(default_engine: GitEngine) -> GitEngine {
537    effective_git_engine_from(
538        default_engine,
539        env::var("NBGV_GitEngine").ok().as_deref(),
540        env::var("DEPENDABOT").ok().as_deref(),
541        env::var("GITHUB_ACTOR").ok().as_deref(),
542    )
543}
544
545fn effective_git_engine_from(
546    default_engine: GitEngine,
547    configured: Option<&str>,
548    dependabot: Option<&str>,
549    github_actor: Option<&str>,
550) -> GitEngine {
551    match configured {
552        Some("LibGit2") => return GitEngine::ReadWrite,
553        Some("Managed") => return GitEngine::ReadOnly,
554        Some("Disabled") => return GitEngine::Disabled,
555        _ => {}
556    }
557    if dependabot.is_some_and(|value| value.eq_ignore_ascii_case("true"))
558        || github_actor == Some("copilot-swe-agent[bot]")
559    {
560        GitEngine::Disabled
561    } else {
562        default_engine
563    }
564}
565
566fn resolve_commit(
567    repository: &Repository,
568    committish: &str,
569) -> std::result::Result<Oid, git2::Error> {
570    if let Ok(oid) = Oid::from_str(committish)
571        && let Ok(commit) = repository.find_commit(oid)
572    {
573        return Ok(commit.id());
574    }
575    repository
576        .revparse_single(committish)?
577        .peel_to_commit()
578        .map(|commit| commit.id())
579}
580
581fn remote_default_branch(repository: &Repository, remote: &str) -> Result<Option<String>> {
582    let reference_name = format!("refs/remotes/{remote}/HEAD");
583    let prefix = format!("refs/remotes/{remote}/");
584    match repository.find_reference(&reference_name) {
585        Ok(reference) => Ok(reference
586            .symbolic_target()?
587            .and_then(|target| target.strip_prefix(&prefix))
588            .map(str::to_owned)),
589        Err(error) if error.code() == ErrorCode::NotFound => Ok(None),
590        Err(error) => Err(error.into()),
591    }
592}
593
594fn convert_time(time: git2::Time) -> Result<DateTime<FixedOffset>> {
595    let offset = FixedOffset::east_opt(time.offset_minutes() * 60).ok_or_else(|| {
596        Error::InvalidFormat(format!(
597            "Commit has an invalid timezone offset: {} minutes.",
598            time.offset_minutes()
599        ))
600    })?;
601    offset
602        .timestamp_opt(time.seconds(), 0)
603        .single()
604        .ok_or_else(|| Error::InvalidFormat("Commit has an invalid timestamp.".to_owned()))
605}
606
607fn absolute_path(path: &Path) -> std::io::Result<PathBuf> {
608    let absolute = if path.is_absolute() {
609        path.to_path_buf()
610    } else {
611        env::current_dir()?.join(path)
612    };
613    match dunce::canonicalize(&absolute) {
614        Ok(canonical) => Ok(canonical),
615        Err(error) if error.kind() == std::io::ErrorKind::NotFound => {
616            for ancestor in absolute.ancestors().skip(1) {
617                if let Ok(canonical_ancestor) = dunce::canonicalize(ancestor) {
618                    return Ok(canonical_ancestor.join(absolute.strip_prefix(ancestor).unwrap()));
619                }
620            }
621            Ok(absolute)
622        }
623        Err(error) => Err(error),
624    }
625}
626
627fn trim_trailing_separator(path: &Path) -> PathBuf {
628    path.components().collect()
629}
630
631fn no_repository_error() -> Error {
632    Error::InvalidOperation(NO_REPOSITORY_MESSAGE.to_owned())
633}
634
635#[cfg(test)]
636mod tests {
637    use std::fs;
638    use std::sync::atomic::{AtomicU64, Ordering};
639
640    use git2::{ObjectType, Signature};
641
642    use super::*;
643
644    static NEXT_DIRECTORY: AtomicU64 = AtomicU64::new(0);
645
646    struct TestRepository {
647        path: PathBuf,
648        head: Oid,
649    }
650
651    impl TestRepository {
652        fn create() -> Self {
653            let path = env::temp_dir().join(format!(
654                "nbgv-rust-git-context-{}-{}",
655                std::process::id(),
656                NEXT_DIRECTORY.fetch_add(1, Ordering::Relaxed)
657            ));
658            let repository = Repository::init(&path).unwrap();
659            let signature =
660                Signature::new("Test", "test@example.com", &git2::Time::new(10, 60)).unwrap();
661            fs::write(path.join("tracked.txt"), "one").unwrap();
662            let mut index = repository.index().unwrap();
663            index.add_path(Path::new("tracked.txt")).unwrap();
664            index.write().unwrap();
665            let tree_id = index.write_tree().unwrap();
666            let tree = repository.find_tree(tree_id).unwrap();
667            let head = repository
668                .commit(Some("HEAD"), &signature, &signature, "initial", &tree, &[])
669                .unwrap();
670            drop(tree);
671            drop(index);
672            drop(repository);
673            Self { path, head }
674        }
675    }
676
677    impl Drop for TestRepository {
678        fn drop(&mut self) {
679            let _ = fs::remove_dir_all(&self.path);
680        }
681    }
682
683    #[test]
684    fn discovers_from_subdirectory_and_reads_metadata() {
685        let test = TestRepository::create();
686        let subdirectory = test.path.join("a").join("b");
687        fs::create_dir_all(&subdirectory).unwrap();
688
689        let context = GitContext::create(&subdirectory, None, GitEngine::ReadOnly).unwrap();
690
691        assert_eq!(context.kind(), GitContextKind::Repository);
692        assert_eq!(
693            context.working_tree_path(),
694            absolute_path(&test.path).unwrap()
695        );
696        assert_eq!(context.repo_relative_project_directory(), Path::new("a/b"));
697        assert_eq!(context.git_commit_id(), Some(test.head));
698        assert!(context.is_head().unwrap());
699        assert_eq!(
700            context.git_commit_dates().unwrap().unwrap().author.offset(),
701            &FixedOffset::east_opt(3600).unwrap()
702        );
703        assert!(!context.is_shallow());
704    }
705
706    #[test]
707    fn discovers_linked_worktree_git_file() {
708        let test = TestRepository::create();
709        let linked_path = test.path.with_extension("linked");
710        let repository = Repository::open(&test.path).unwrap();
711        let worktree = repository.worktree("linked", &linked_path, None).unwrap();
712        drop(worktree);
713        drop(repository);
714
715        let context = GitContext::create(&linked_path, None, GitEngine::ReadOnly).unwrap();
716
717        assert_eq!(
718            context.working_tree_path(),
719            absolute_path(&linked_path).unwrap()
720        );
721        assert!(linked_path.join(".git").is_file());
722        assert!(context.git_directory().unwrap().is_dir());
723        assert_eq!(context.git_commit_id(), Some(test.head));
724        fs::remove_dir_all(linked_path).unwrap();
725    }
726
727    #[test]
728    fn detects_shallow_repository() {
729        let test = TestRepository::create();
730        fs::write(
731            test.path.join(".git").join("shallow"),
732            format!("{}\n", test.head),
733        )
734        .unwrap();
735
736        let context = GitContext::create(&test.path, None, GitEngine::ReadOnly).unwrap();
737
738        assert!(context.is_shallow());
739    }
740
741    #[test]
742    fn selects_committishes_and_reports_tags() {
743        let test = TestRepository::create();
744        let repository = Repository::open(&test.path).unwrap();
745        let head = repository.find_commit(test.head).unwrap();
746        repository
747            .tag_lightweight("v1", head.as_object(), false)
748            .unwrap();
749        drop(head);
750        drop(repository);
751        let mut context = GitContext::create(&test.path, None, GitEngine::ReadOnly).unwrap();
752
753        assert!(context.try_select_commit("v1").unwrap());
754        assert!(
755            context
756                .try_select_commit(&test.head.to_string()[..12])
757                .unwrap()
758        );
759        assert!(!context.try_select_commit("HEAD~999").unwrap());
760        assert_eq!(context.head_tags().unwrap().unwrap(), vec!["refs/tags/v1"]);
761        assert_eq!(
762            context.short_unique_commit_id(8).unwrap(),
763            test.head.to_string()[..8]
764        );
765    }
766
767    #[test]
768    fn selects_local_remote_and_annotated_tag_refs() {
769        let test = TestRepository::create();
770        let repository = Repository::open(&test.path).unwrap();
771        let head = repository.find_commit(test.head).unwrap();
772        repository.branch("feature", &head, false).unwrap();
773        repository
774            .reference(
775                "refs/remotes/origin/feature",
776                test.head,
777                true,
778                "compatibility fixture",
779            )
780            .unwrap();
781        let signature =
782            Signature::new("Test", "test@example.com", &git2::Time::new(20, -60)).unwrap();
783        repository
784            .tag("annotated", head.as_object(), &signature, "release", false)
785            .unwrap();
786        drop(head);
787        drop(repository);
788
789        let mut context = GitContext::create(&test.path, None, GitEngine::ReadOnly).unwrap();
790        for committish in ["feature", "origin/feature", "annotated"] {
791            assert!(
792                context.try_select_commit(committish).unwrap(),
793                "{committish}"
794            );
795            assert_eq!(Some(test.head), context.git_commit_id());
796        }
797        assert_eq!(
798            context.head_tags().unwrap().unwrap(),
799            vec!["refs/tags/annotated"]
800        );
801    }
802
803    #[test]
804    fn lengthens_an_ambiguous_short_id() {
805        let test = TestRepository::create();
806        let repository = Repository::open(&test.path).unwrap();
807        let odb = repository.odb().unwrap();
808        let prefix = &test.head.to_string()[..1];
809        for value in 0..1000 {
810            let candidate = odb
811                .write(ObjectType::Blob, format!("collision-{value}").as_bytes())
812                .unwrap();
813            if candidate != test.head && candidate.to_string().starts_with(prefix) {
814                break;
815            }
816        }
817        drop(odb);
818        drop(repository);
819        let context = GitContext::create(&test.path, None, GitEngine::ReadOnly).unwrap();
820
821        assert!(context.short_unique_commit_id(1).unwrap().len() > 1);
822    }
823
824    #[test]
825    fn supports_ignore_status_stage_and_tag_mutations() {
826        let test = TestRepository::create();
827        fs::write(test.path.join(".gitignore"), "*.tmp\n").unwrap();
828        fs::write(test.path.join("ignored.tmp"), "ignored").unwrap();
829        fs::write(test.path.join("new.txt"), "new").unwrap();
830        let context = GitContext::create(&test.path, None, GitEngine::ReadWrite).unwrap();
831
832        assert!(context.is_ignored(test.path.join("ignored.tmp")).unwrap());
833        assert!(context.is_working_tree_dirty().unwrap());
834        context.stage("new.txt").unwrap();
835        assert!(
836            context
837                .repository()
838                .unwrap()
839                .index()
840                .unwrap()
841                .get_path(Path::new("new.txt"), 0)
842                .is_some()
843        );
844        context.apply_tag("created").unwrap();
845        assert!(
846            context
847                .repository()
848                .unwrap()
849                .find_reference("refs/tags/created")
850                .is_ok()
851        );
852    }
853
854    #[test]
855    fn detects_default_branch_in_compatibility_order() {
856        let test = TestRepository::create();
857        let repository = Repository::open(&test.path).unwrap();
858        repository
859            .remote("origin", "https://example.com/repo")
860            .unwrap();
861        repository
862            .reference("refs/remotes/origin/main", test.head, true, "test")
863            .unwrap();
864        repository
865            .reference_symbolic(
866                "refs/remotes/origin/HEAD",
867                "refs/remotes/origin/main",
868                true,
869                "test",
870            )
871            .unwrap();
872        drop(repository);
873
874        let context = GitContext::create(&test.path, None, GitEngine::ReadOnly).unwrap();
875        assert_eq!(context.default_branch().unwrap(), "main");
876    }
877
878    #[test]
879    fn models_disabled_and_no_repository_contexts() {
880        let test = TestRepository::create();
881        let mut disabled =
882            GitContext::create(&test.path, Some("does-not-matter"), GitEngine::Disabled).unwrap();
883        assert_eq!(disabled.kind(), GitContextKind::Disabled);
884        assert!(disabled.is_repository());
885        assert!(disabled.try_select_commit("anything").unwrap());
886        assert_eq!(
887            disabled.short_unique_commit_id(7).unwrap(),
888            DISABLED_COMMIT_ID
889        );
890
891        let outside = test.path.parent().unwrap().join(format!(
892            "nbgv-no-repo-{}",
893            NEXT_DIRECTORY.fetch_add(1, Ordering::Relaxed)
894        ));
895        fs::create_dir_all(&outside).unwrap();
896        let no_repository = GitContext::create(&outside, None, GitEngine::ReadOnly).unwrap();
897        assert_eq!(no_repository.kind(), GitContextKind::NoRepository);
898        assert!(!no_repository.is_repository());
899        fs::remove_dir_all(outside).unwrap();
900    }
901
902    #[test]
903    fn applies_effective_engine_policy() {
904        assert_eq!(
905            effective_git_engine_from(GitEngine::ReadOnly, None, Some("TRUE"), None),
906            GitEngine::Disabled
907        );
908        assert_eq!(
909            effective_git_engine_from(
910                GitEngine::ReadWrite,
911                None,
912                None,
913                Some("copilot-swe-agent[bot]")
914            ),
915            GitEngine::Disabled
916        );
917        assert_eq!(
918            effective_git_engine_from(
919                GitEngine::ReadOnly,
920                Some("LibGit2"),
921                Some("true"),
922                Some("copilot-swe-agent[bot]")
923            ),
924            GitEngine::ReadWrite
925        );
926        assert_eq!(
927            effective_git_engine_from(
928                GitEngine::ReadWrite,
929                Some("invalid"),
930                Some("false"),
931                Some("COPILOT-SWE-AGENT[BOT]")
932            ),
933            GitEngine::ReadWrite
934        );
935    }
936}