radicle: Improve cwd to search parents

If a `rad` command that requires an RID is executed within a
subdirectory of a Radicle project, then it will fail saying:

    ✗ Error: Current directory is not a radicle project

Improve this flow by searching parent directories and/or using the
GIT_DIR environment variable.

This is safe as long as the operations are read-only when calling
`cwd`. Currently they are:
- `Repository::open_ext` -- will not create a repository, only open
  one.
- `Repository::find_remote` -- this will only read the remote from the
  config and get the URL to parse the RID.

Signed-off-by: Fintan Halpenny <fintan.halpenny@gmail.com>
X-Clacks-Overhead: GNU Terry Pratchett
This commit is contained in:
Fintan Halpenny 2023-10-23 14:23:53 +01:00 committed by cloudhead
parent 7e3c7a7ae0
commit c82344496b
No known key found for this signature in database
1 changed files with 16 additions and 1 deletions

View File

@ -269,8 +269,23 @@ pub fn remove_remote(repo: &git2::Repository) -> Result<(), RemoteError> {
}
/// Get the Id of project in current working directory
///
/// It will atempt to search parent directories if `path` did not find
/// a git repository.
///
/// # Safety
///
/// This function should only perform read operations since we do not
/// want to modify the wrong repository in the case that it found a
/// Git repository that is not a Radicle repository.
pub fn cwd() -> Result<(git2::Repository, Id), RemoteError> {
let repo = git2::Repository::open(Path::new("."))?;
let mut flags = git2::RepositoryOpenFlags::empty();
// Allow to search upwards.
flags.set(git2::RepositoryOpenFlags::NO_SEARCH, false);
// Allow to use `GIT_DIR` env.
flags.set(git2::RepositoryOpenFlags::FROM_ENV, true);
let ceilings: &[&str] = &[];
let repo = git2::Repository::open_ext(Path::new("."), flags, ceilings)?;
let (_, id) = remote(&repo)?;
Ok((repo, id))