Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

feat(switch): accept revset arguments, and explicitly support - shorthand #1463

Open
wants to merge 4 commits into
base: master
Choose a base branch
from
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
1 change: 1 addition & 0 deletions CHANGELOG.md
Original file line number Diff line number Diff line change
Expand Up @@ -12,6 +12,7 @@ and this project adheres to [Semantic Versioning](https://semver.org/spec/v2.0.0
### Changed

- `scm-record` upgraded to [v0.5.0](https://github.com/arxanas/scm-record/releases/tag/v0.5.0).
- (#1463): `git switch` now accepts a revset whose sole head will be checked out

## [v0.10.0] - 2024-10-10

Expand Down
3 changes: 3 additions & 0 deletions git-branchless-lib/src/git/repo.rs
Original file line number Diff line number Diff line change
Expand Up @@ -938,6 +938,9 @@ impl Repo {
return Err(Error::UnsupportedRevParseSpec(spec.to_owned()));
}

// `libgit2` doesn't understand that `-` is short for `@{-1}`
let spec = if spec == "-" { "@{-1}" } else { spec };

match self.inner.revparse_single(spec) {
Ok(object) => match object.into_commit() {
Ok(commit) => Ok(Some(Commit { inner: commit })),
Expand Down
82 changes: 59 additions & 23 deletions git-branchless-navigation/src/lib.rs
Original file line number Diff line number Diff line change
Expand Up @@ -25,11 +25,11 @@ use lib::core::repo_ext::RepoExt;
use lib::util::{ExitCode, EyreExitOr};
use tracing::{instrument, warn};

use git_branchless_opts::{SwitchOptions, TraverseCommitsOptions};
use git_branchless_revset::resolve_default_smartlog_commits;
use git_branchless_opts::{ResolveRevsetOptions, Revset, SwitchOptions, TraverseCommitsOptions};
use git_branchless_revset::{resolve_commits, resolve_default_smartlog_commits};
use git_branchless_smartlog::make_smartlog_graph;
use lib::core::config::get_next_interactive;
use lib::core::dag::{sorted_commit_set, CommitSet, Dag};
use lib::core::dag::{sorted_commit_set, union_all, CommitSet, Dag};
use lib::core::effects::Effects;
use lib::core::eventlog::{EventLogDb, EventReplayer};
use lib::core::formatting::Pluralize;
Expand Down Expand Up @@ -474,7 +474,7 @@ pub fn switch(
switch_options: &SwitchOptions,
) -> EyreExitOr<()> {
let SwitchOptions {
interactive: _,
interactive,
branch_name,
force,
merge,
Expand Down Expand Up @@ -510,27 +510,34 @@ pub fn switch(
false,
)?;

let initial_query = match switch_options {
SwitchOptions {
interactive: true,
branch_name: _,
force: _,
merge: _,
detach: _,
target,
} => Some(target.clone().unwrap_or_default()),
SwitchOptions {
interactive: false,
branch_name: _,
force: _,
merge: _,
detach: _,
target: _,
} => None,
enum Target {
/// The (possibly empty) target expression should be used as the initial
/// query in the commit selector.
Interactive(String),

/// The target expression is probably a git revision or reference and
/// should be passed directly to git for resolution.
Passthrough(String),

/// The target expression should be interpreted as a revset.
Revset(Revset),

/// No target expression was specified.
None,
}
let initial_query = match (interactive, target) {
(true, Some(target)) => Target::Interactive(target.to_string()),
(true, None) => Target::Interactive(String::new()),
(false, Some(target)) => match repo.revparse_single_commit(target.to_string().as_ref()) {
Ok(Some(_)) => Target::Passthrough(target.to_string()),
Ok(None) | Err(_) => Target::Revset(target.clone()),
},
(false, None) => Target::None,
};
let target: Option<CheckoutTarget> = match initial_query {
None => target.clone().map(CheckoutTarget::Unknown),
Some(initial_query) => {
Target::None => None,
Target::Passthrough(target) => Some(CheckoutTarget::Unknown(target)),
Target::Interactive(initial_query) => {
match prompt_select_commit(
None,
&initial_query,
Expand All @@ -552,6 +559,35 @@ pub fn switch(
None => return Ok(Err(ExitCode(1))),
}
}
Target::Revset(target) => {
let commit_sets = resolve_commits(
effects,
&repo,
&mut dag,
&[target.clone()],
&ResolveRevsetOptions::default(),
)?;

let commit_set = union_all(&commit_sets);
let commit_set = dag.query_heads(commit_set)?;
let commits = sorted_commit_set(&repo, &dag, &commit_set)?;

match commits.as_slice() {
[commit] => Some(CheckoutTarget::Unknown(commit.get_oid().to_string())),
[] | [..] => {
writeln!(
effects.get_error_stream(),
"Cannot switch to target: expected '{target}' to contain 1 head, but found {}.",
claytonrcarter marked this conversation as resolved.
Show resolved Hide resolved
commits.len()
)?;
writeln!(
effects.get_error_stream(),
"Target should be a commit or a set of commits with exactly 1 head. Aborting."
)?;
return Ok(Err(ExitCode(1)));
}
}
}
};

let additional_args = {
Expand Down
4 changes: 3 additions & 1 deletion git-branchless-opts/src/lib.rs
Original file line number Diff line number Diff line change
Expand Up @@ -172,13 +172,15 @@ pub struct SwitchOptions {

/// The commit or branch to check out.
///
/// If a revset is provided, it must evaluate to set with exactly 1 head.
///
/// If this is not provided, then interactive commit selection starts as
/// if `--interactive` were passed.
///
/// If this is provided and the `--interactive` flag is passed, this
/// text is used to pre-fill the interactive commit selector.
#[clap(value_parser)]
pub target: Option<String>,
pub target: Option<Revset>,
}

/// Internal use.
Expand Down
122 changes: 122 additions & 0 deletions git-branchless/tests/test_navigation.rs
Original file line number Diff line number Diff line change
Expand Up @@ -851,6 +851,128 @@ fn test_navigation_switch_target_only() -> eyre::Result<()> {
Ok(())
}

#[test]
fn test_navigation_switch_revset() -> eyre::Result<()> {
let git = make_git()?;
git.init_repo()?;

git.detach_head()?;
git.commit_file("test1", 1)?;
git.run(&["checkout", "HEAD~"])?;

{
{
let (stdout, _stderr) = git.branchless("smartlog", &[])?;
insta::assert_snapshot!(stdout, @r###"
@ f777ecc (master) create initial.txt
|
o 62fc20d create test1.txt
"###);
}

let (stdout, _stderr) = git.branchless("switch", &["descendants(master)"])?;
insta::assert_snapshot!(stdout, @r###"
branchless: running command: <git-executable> checkout 62fc20d2a290daea0d52bdc2ed2ad4be6491010e
O f777ecc (master) create initial.txt
|
@ 62fc20d create test1.txt
"###);
}

git.run(&["checkout", "HEAD~"])?;
git.commit_file("test2", 2)?;
git.run(&["checkout", "HEAD~"])?;

{
{
let (stdout, _stderr) = git.branchless("smartlog", &[])?;
insta::assert_snapshot!(stdout, @r###"
@ f777ecc (master) create initial.txt
|\
| o 62fc20d create test1.txt
|
o fe65c1f create test2.txt
"###);
}

let (_stdout, stderr) = git.branchless_with_options(
"switch",
&["descendants(master)"],
&GitRunOptions {
expected_exit_code: 1,
..Default::default()
},
)?;
insta::assert_snapshot!(stderr, @r###"
Cannot switch to target: expected 'descendants(master)' to contain 1 head, but found 2.
Target should be a commit or a set of commits with exactly 1 head. Aborting.
"###);
}

{
// switching back to "last checkout"
let (stdout, _stderr) = git.branchless("switch", &["@{-1}"])?;
insta::assert_snapshot!(stdout, @r###"
branchless: running command: <git-executable> checkout @{-1}
O f777ecc (master) create initial.txt
|\
| o 62fc20d create test1.txt
|
@ fe65c1f create test2.txt
"###);
}

{
// switching back to "last checkout"
let (stdout, _stderr) = git.branchless("switch", &["-"])?;
claytonrcarter marked this conversation as resolved.
Show resolved Hide resolved
insta::assert_snapshot!(stdout, @r###"
branchless: running command: <git-executable> checkout -
@ f777ecc (master) create initial.txt
|\
| o 62fc20d create test1.txt
|
o fe65c1f create test2.txt
"###);
}

{
// switching back to "last checkout" will also checkout last checked out
// branch, if any

let (stdout, _stderr) = git.branchless("switch", &["master"])?;
insta::assert_snapshot!(stdout, @r###"
branchless: running command: <git-executable> checkout master
@ f777ecc (> master) create initial.txt
|\
| o 62fc20d create test1.txt
|
o fe65c1f create test2.txt
"###);

let (stdout, _stderr) = git.branchless("switch", &["@{-2}"])?;
insta::assert_snapshot!(stdout, @r###"
branchless: running command: <git-executable> checkout @{-2}
O f777ecc (master) create initial.txt
|\
| o 62fc20d create test1.txt
|
@ fe65c1f create test2.txt
"###);

let (stdout, _stderr) = git.branchless("switch", &["-"])?;
insta::assert_snapshot!(stdout, @r###"
branchless: running command: <git-executable> checkout -
@ f777ecc (> master) create initial.txt
|\
| o 62fc20d create test1.txt
|
o fe65c1f create test2.txt
"###);
}

Ok(())
}

#[test]
#[cfg(unix)]
fn test_switch_auto_switch_interactive() -> eyre::Result<()> {
Expand Down
Loading