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

backout: add --template option #3583

Closed
wants to merge 1 commit into from
Closed
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
27 changes: 27 additions & 0 deletions cli/src/commands/backout.rs
Original file line number Diff line number Diff line change
Expand Up @@ -18,6 +18,8 @@ use tracing::instrument;

use crate::cli_util::{CommandHelper, RevisionArg};
use crate::command_error::CommandError;
use crate::commit_templater::CommitTemplateLanguage;
use crate::formatter::PlainTextFormatter;
use crate::ui::Ui;

/// Apply the reverse of a revision on top of another revision
Expand All @@ -31,6 +33,11 @@ pub(crate) struct BackoutArgs {
// copy should be rebased on top?
#[arg(long, short, default_value = "@")]
destination: Vec<RevisionArg>,
/// Template used to generate the commit message
///
/// For the syntax, see https://github.com/martinvonz/jj/blob/main/docs/templates.md
#[arg(long, short = 'T')]
template: Option<String>,
}

#[instrument(skip_all)]
Expand All @@ -47,11 +54,31 @@ pub(crate) fn cmd_backout(
parents.push(destination);
}
let mut tx = workspace_command.start_transaction();
let commit_description = {
let language = tx.base_workspace_helper().commit_template_language()?;
let template_string = match &args.template {
Some(value) => value.to_string(),
None => command
.settings()
.config()
.get_string("templates.backout")?,
};
let template = tx.base_workspace_helper().parse_template(
&language,
&template_string,
CommitTemplateLanguage::wrap_commit,
)?;
let mut output = Vec::new();
let mut formatter = PlainTextFormatter::new(&mut output);
template.format(&commit_to_back_out, &mut formatter)?;
String::from_utf8(output).expect("template output should be utf-8 bytes")
};
back_out_commit(
command.settings(),
tx.mut_repo(),
&commit_to_back_out,
&parents,
Some(commit_description),
)?;
tx.finish(
ui,
Expand Down
2 changes: 2 additions & 0 deletions cli/src/config/templates.toml
Original file line number Diff line number Diff line change
@@ -1,4 +1,6 @@
[templates]
backout = '"backout of commit " ++ commit_id'

commit_summary = 'format_commit_summary_with_refs(self, branches)'
commit_summary_no_branches = 'format_commit_summary_with_refs(self, "")'

Expand Down
1 change: 1 addition & 0 deletions cli/tests/[email protected]
Original file line number Diff line number Diff line change
Expand Up @@ -217,6 +217,7 @@ Apply the reverse of a revision on top of another revision
* `-d`, `--destination <DESTINATION>` — The revision to apply the reverse changes on top of

Default value: `@`
* `-T`, `--template <TEMPLATE>` — Template used to generate the commit message



Expand Down
1 change: 1 addition & 0 deletions cli/tests/runner.rs
Original file line number Diff line number Diff line change
Expand Up @@ -11,6 +11,7 @@ fn test_no_forgotten_test_files() {
mod test_abandon_command;
mod test_advance_branches;
mod test_alias;
mod test_backout_command;
mod test_branch_command;
mod test_builtin_aliases;
mod test_cat_command;
Expand Down
102 changes: 102 additions & 0 deletions cli/tests/test_backout_command.rs
Original file line number Diff line number Diff line change
@@ -0,0 +1,102 @@
// Copyright 2024 The Jujutsu Authors
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// https://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.

use std::path::Path;

use crate::common::TestEnvironment;

fn create_commit(test_env: &TestEnvironment, repo_path: &Path, name: &str, parents: &[&str]) {
if parents.is_empty() {
test_env.jj_cmd_ok(repo_path, &["new", "root()", "-m", name]);
} else {
let mut args = vec!["new", "-m", name];
args.extend(parents);
test_env.jj_cmd_ok(repo_path, &args);
}
std::fs::write(repo_path.join(name), format!("{name}\n")).unwrap();
test_env.jj_cmd_ok(repo_path, &["branch", "create", name]);
}

#[test]
fn test_backout() {
let test_env = TestEnvironment::default();
test_env.jj_cmd_ok(test_env.env_root(), &["init", "repo", "--git"]);
let repo_path = test_env.env_root().join("repo");

create_commit(&test_env, &repo_path, "a", &[]);
// Test the setup
insta::assert_snapshot!(get_log_output(&test_env, &repo_path), @r###"
@ 2443ea76b0b1 a
◉ 000000000000
"###);
let stdout = test_env.jj_cmd_success(&repo_path, &["diff", "-s"]);
insta::assert_snapshot!(stdout, @r###"
A a
"###);

let (stdout, stderr) = test_env.jj_cmd_ok(&repo_path, &["backout", "-r", "a"]);
insta::assert_snapshot!(stdout, @"");
insta::assert_snapshot!(stderr, @"");
insta::assert_snapshot!(get_log_output(&test_env, &repo_path), @r###"
◉ 8fe4e9345020 backout of commit 2443ea76b0b1c531326908326aab7020abab8e6c
@ 2443ea76b0b1 a
◉ 000000000000
"###);
let stdout = test_env.jj_cmd_success(&repo_path, &["diff", "-s", "-r", "@+"]);
insta::assert_snapshot!(stdout, @r###"
D a
"###);
}

#[test]
fn test_backout_template() {
let test_env = TestEnvironment::default();
test_env.jj_cmd_ok(test_env.env_root(), &["init", "repo", "--git"]);
let repo_path = test_env.env_root().join("repo");

create_commit(&test_env, &repo_path, "a", &[]);
// Test the setup
insta::assert_snapshot!(get_log_output(&test_env, &repo_path), @r###"
@ 2443ea76b0b1 a
◉ 000000000000
"###);
let stdout = test_env.jj_cmd_success(&repo_path, &["diff", "-s"]);
insta::assert_snapshot!(stdout, @r###"
A a
"###);

// Verify that message of backed out commit follows the provided template
let (stdout, stderr) = test_env.jj_cmd_ok(
&repo_path,
&[
"backout",
"-r",
"a",
"-T",
r#""Revert commit " ++ commit_id.short() ++ " \"" ++ description.first_line() ++ "\"""#,
],
);
insta::assert_snapshot!(stdout, @"");
insta::assert_snapshot!(stderr, @"");
insta::assert_snapshot!(get_log_output(&test_env, &repo_path), @r###"
◉ 1db880a5204e Revert commit 2443ea76b0b1 "a"
@ 2443ea76b0b1 a
◉ 000000000000
"###);
}

fn get_log_output(test_env: &TestEnvironment, cwd: &Path) -> String {
let template = r#"commit_id.short() ++ " " ++ description"#;
test_env.jj_cmd_success(cwd, &["log", "-T", template])
}
6 changes: 5 additions & 1 deletion lib/src/rewrite.rs
Original file line number Diff line number Diff line change
Expand Up @@ -314,6 +314,7 @@ pub fn back_out_commit(
mut_repo: &mut MutableRepo,
old_commit: &Commit,
new_parents: &[Commit],
commit_description: Option<String>,
) -> BackendResult<Commit> {
let old_base_tree = merge_commit_trees(mut_repo, &old_commit.parents())?;
let new_base_tree = merge_commit_trees(mut_repo, new_parents)?;
Expand All @@ -326,7 +327,10 @@ pub fn back_out_commit(
// TODO: i18n the description based on repo language
mut_repo
.new_commit(settings, new_parent_ids, new_tree.id())
.set_description(format!("backout of commit {}", &old_commit.id().hex()))
.set_description(
commit_description
.unwrap_or_else(|| format!("backout of commit {}", &old_commit.id().hex())),
Copy link
Member Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

I'm wondering if the commit description should just be required?

Copy link
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

I was just about to say that :) Then you can remove the i18n comment too. (I'm kind of wondering if we even want this function or if we should just inline it in the CLI crate, but we can decide that later.)

Copy link
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

and -m/--message could support some form of templating if needed.
#3253

Copy link
Member Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Are you suggesting adding a --message option, and also using it as a template when --template is also passed, like what the last few comments suggest?

Copy link
Contributor

@yuja yuja May 4, 2024

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Are you suggesting adding a --message option,

Yes. It's similar to commit -m/describe -m.

also using it as a template when --template is also passed

I have no concrete idea how template expression will be enabled in --message (and other string arguments.)

If there's there isn't an immediate need for templated commit message, I would just add -m/--message.

Copy link
Member Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

The reason I started this PR was because I wanted automatically generated git revert-style commit messages, without having to manually type out the old commit's description + commit hash. Since #2669 had requests for different formats, I thought templating would be the preferred solution. Otherwise, if switching to git revert-style commit messages is acceptable, I can change this PR to do that.

I also wanted #3339 (multiple revisions for backout), which I think wouldn't work too well with --message.

Any thoughts? (/cc @thoughtpolice since you commented on #2669.)

Copy link
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

The reason I started this PR was because I wanted automatically generated git revert-style commit messages, without having to manually type out the old commit's description + commit hash. Since #2669 had requests for different formats, I thought templating would be the preferred solution.

Perhaps, it will be per-action (e.g. describe/squash/backout/..) description template? Mercurial has a similar feature.
#1354
https://repo.mercurial-scm.org/hg/help/config (search "committemplate")

One tricky part is what the self commit (= template context) should be. In order to generate a default commit description, we'll need the source commit. If we add multi-rev backout, it will be Vec<Commit>. OTOH, we might have to use the new "backout" commit to generate a editor message, which may contain a diff or diff summary. If jj backout is changed to open an editor by default, there might be separate templates for commit description and editor content.

Otherwise, if switching to git revert-style commit messages is acceptable,

I personally think it's acceptable.

)
.write()
}

Expand Down