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

Implement jj sign and jj unsign commands #4747

Open
wants to merge 2 commits into
base: main
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
4 changes: 4 additions & 0 deletions CHANGELOG.md
Original file line number Diff line number Diff line change
Expand Up @@ -116,6 +116,10 @@ to [Semantic Versioning](https://semver.org/spec/v2.0.0.html).
* New `subject(pattern)` revset function that matches first line of commit
descriptions.

* The new `jj sign` command allows signing commits.

* The new `jj unsign` command allows unsigning commits.

Comment on lines +119 to +122
Copy link
Contributor Author

Choose a reason for hiding this comment

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

These do feel a bit scarce, but maybe that's ok? I am open to suggestions of things to add here.

### Fixed bugs

* Fixed diff selection by external tools with `jj split`/`commit -i FILESETS`.
Expand Down
6 changes: 6 additions & 0 deletions cli/src/commands/mod.rs
Original file line number Diff line number Diff line change
Expand Up @@ -46,12 +46,14 @@ mod restore;
mod root;
mod run;
mod show;
mod sign;
mod simplify_parents;
mod sparse;
mod split;
mod squash;
mod status;
mod tag;
mod unsign;
mod unsquash;
mod util;
mod version;
Expand Down Expand Up @@ -130,6 +132,7 @@ enum Command {
// TODO: Flesh out.
Run(run::RunArgs),
Show(show::ShowArgs),
Sign(sign::SignArgs),
SimplifyParents(simplify_parents::SimplifyParentsArgs),
#[command(subcommand)]
Sparse(sparse::SparseCommand),
Expand All @@ -142,6 +145,7 @@ enum Command {
Util(util::UtilCommand),
/// Undo an operation (shortcut for `jj op undo`)
Undo(operation::undo::OperationUndoArgs),
Unsign(unsign::UnsignArgs),
// TODO: Delete `unsquash` in jj 0.28+
#[command(hide = true)]
Unsquash(unsquash::UnsquashArgs),
Expand Down Expand Up @@ -210,12 +214,14 @@ pub fn run_command(ui: &mut Ui, command_helper: &CommandHelper) -> Result<(), Co
simplify_parents::cmd_simplify_parents(ui, command_helper, args)
}
Command::Show(args) => show::cmd_show(ui, command_helper, args),
Command::Sign(args) => sign::cmd_sign(ui, command_helper, args),
Command::Sparse(args) => sparse::cmd_sparse(ui, command_helper, args),
Command::Split(args) => split::cmd_split(ui, command_helper, args),
Command::Squash(args) => squash::cmd_squash(ui, command_helper, args),
Command::Status(args) => status::cmd_status(ui, command_helper, args),
Command::Tag(args) => tag::cmd_tag(ui, command_helper, args),
Command::Undo(args) => operation::undo::cmd_op_undo(ui, command_helper, args),
Command::Unsign(args) => unsign::cmd_unsign(ui, command_helper, args),
Command::Unsquash(args) => unsquash::cmd_unsquash(ui, command_helper, args),
Command::Untrack(args) => {
let cmd = renamed_cmd("untrack", "file untrack", file::untrack::cmd_file_untrack);
Expand Down
161 changes: 161 additions & 0 deletions cli/src/commands/sign.rs
Original file line number Diff line number Diff line change
@@ -0,0 +1,161 @@
// Copyright 2023 The Jujutsu Authors
pylbrecht marked this conversation as resolved.
Show resolved Hide resolved
//
// 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 clap_complete::ArgValueCandidates;
use indexmap::IndexSet;
use itertools::Itertools;
use jj_lib::commit::Commit;
use jj_lib::commit::CommitIteratorExt;
use jj_lib::signing::SignBehavior;

use crate::cli_util::short_commit_hash;
use crate::cli_util::CommandHelper;
use crate::cli_util::RevisionArg;
use crate::command_error::user_error_with_hint;
use crate::command_error::CommandError;
use crate::complete;
use crate::ui::Ui;

/// Cryptographically sign a revision
#[derive(clap::Args, Clone, Debug)]
pub struct SignArgs {
/// What key to use, depends on the configured signing backend.
#[arg()]
key: Option<String>,
/// What revision(s) to sign
#[arg(
long, short,
default_value = "@",
pylbrecht marked this conversation as resolved.
Show resolved Hide resolved
Copy link
Contributor

Choose a reason for hiding this comment

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

nit: omit the default value for now? I don't think the current default is useful. (the same for unsign)

value_name = "REVSETS",
add = ArgValueCandidates::new(complete::mutable_revisions),
)]
revisions: Vec<RevisionArg>,
/// Sign a commit that is not authored by you.
Copy link
Contributor

Choose a reason for hiding this comment

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

nit: "Sign revisions that are .."?

#[arg(long)]
allow_not_mine: bool,
}

pub fn check_commits_authored_by<'a>(
commits: impl IntoIterator<Item = &'a Commit>,
user_email: &str,
hint: &str,
) -> Result<(), CommandError> {
let bad_commits = commits
.into_iter()
.filter(|commit| commit.author().email != user_email)
Comment on lines +54 to +56
Copy link
Contributor

Choose a reason for hiding this comment

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

nit: Can't we use SignSettings::should_sign()?

BTW, I'm not sure if this should be an error. If a warning is good enough, warnings can be emitted within/after transform_descendants().

@necauqua any thoughts?

Copy link
Contributor

Choose a reason for hiding this comment

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

My thoughts about jj philosophy are that you can always jj undo any rewrite - at least if jj gabe you a warning/notice that something unusual has happened.

So, in that case, error => warning is good imo

//offtop
I guess the same applies to removing all: btw, even though I like it and didn't like the idea of getting rid of it - if jj brings your attention to the fact that rebase happened to affect multiple revs so that you can undo it if it was not what you expected - the all: stumble it not needed

Copy link
Contributor Author

Choose a reason for hiding this comment

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

I really like the idea of embracing jj undo. Warnings it is then!

.collect_vec();

match bad_commits.len() {
0 => Ok(()),
1 => Err(user_error_with_hint(
format!(
"Commit {} is not authored by you.",
short_commit_hash(bad_commits[0].id()),
),
hint,
)),
2.. => Err(user_error_with_hint(
format!(
"The following commits are not authored by you:\n {}",
bad_commits
.into_iter()
.ids()
.map(short_commit_hash)
.join("\n ")
),
hint,
)),
}
}

pub fn cmd_sign(ui: &mut Ui, command: &CommandHelper, args: &SignArgs) -> Result<(), CommandError> {
let mut workspace_command = command.workspace_helper(ui)?;

let commits: IndexSet<Commit> = workspace_command
.parse_union_revsets(ui, &args.revisions)?
.evaluate_to_commits()?
.try_collect()?;

workspace_command.check_rewritable(commits.iter().ids())?;

if !args.allow_not_mine {
check_commits_authored_by(
&commits,
command.settings().user_email(),
"Use --allow-not-mine to sign anyway.",
)?;
}

let mut tx = workspace_command.start_transaction();

let behavior = if args.allow_not_mine {
SignBehavior::Force
} else {
SignBehavior::Own
};
let mut signed_commits = vec![];
tx.repo_mut().transform_descendants(
commits.iter().ids().cloned().collect_vec(),
pylbrecht marked this conversation as resolved.
Show resolved Hide resolved
|rewriter| {
if rewriter.old_commit().is_signed() {
// Don't resign commits, which are already signed by me. For people using
// hardware devices for signatures, resigning commits is
// cumbersome.
return Ok(());
}

if commits.contains(rewriter.old_commit()) {
necauqua marked this conversation as resolved.
Show resolved Hide resolved
let commit_builder = rewriter.reparent();
Copy link
Contributor

@yuja yuja Jan 22, 2025

Choose a reason for hiding this comment

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

We'll probably need to do always .reparent(). See cmd_describe() for example.

.reparent() can be skipped when !rewriter.parents_changed() && no_need_to_sign_the_current_commit. cmd_describe() excludes uninteresting commits prior to transform_descendants(). I'm not sure which is better here, but prefiltering might simplify the condition to do .reparent().

let new_commit = commit_builder
.set_sign_key(args.key.clone())
.set_sign_behavior(behavior)
.write()?;
signed_commits.push(new_commit);
}
Ok(())
pylbrecht marked this conversation as resolved.
Show resolved Hide resolved
},
)?;

if let Some(mut formatter) = ui.status_formatter() {
match &*signed_commits {
[] => {}
[commit] => {
write!(formatter, "Signed commit ")?;
tx.base_workspace_helper()
.write_commit_summary(formatter.as_mut(), commit)?;
writeln!(ui.status())?;
}
commits => {
let template = tx.base_workspace_helper().commit_summary_template();
writeln!(formatter, "Signed the following commits:")?;
for commit in commits {
write!(formatter, " ")?;
template.format(commit, formatter.as_mut())?;
writeln!(formatter)?;
}
}
};
}
let transaction_description = match &*signed_commits {
[] => "".to_string(),
[commit] => format!("sign commit {}", commit.id()),
commits => format!(
"sign commit {} and {} more",
commits[0].id(),
commits.len() - 1
),
};
tx.finish(ui, transaction_description)?;
Ok(())
}
116 changes: 116 additions & 0 deletions cli/src/commands/unsign.rs
Original file line number Diff line number Diff line change
@@ -0,0 +1,116 @@
// Copyright 2023 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 clap_complete::ArgValueCandidates;
use indexmap::IndexSet;
use itertools::Itertools;
use jj_lib::commit::Commit;
use jj_lib::commit::CommitIteratorExt;
use jj_lib::signing::SignBehavior;

use super::sign::check_commits_authored_by;
use crate::cli_util::CommandHelper;
use crate::cli_util::RevisionArg;
use crate::command_error::CommandError;
use crate::complete;
use crate::ui::Ui;

/// Drop a cryptographic signature
#[derive(clap::Args, Clone, Debug)]
pub struct UnsignArgs {
/// What revision(s) to unsign
#[arg(
long, short,
default_value = "@",
value_name = "REVSETS",
add = ArgValueCandidates::new(complete::mutable_revisions),
)]
revisions: Vec<RevisionArg>,
/// Unsign a commit that is not authored by you.
#[arg(long, short)]
allow_not_mine: bool,
Comment on lines +40 to +42
Copy link
Contributor

Choose a reason for hiding this comment

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

@necauqua Do we need --allow-not-mine for unsign?

Copy link
Contributor

Choose a reason for hiding this comment

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

Actually, it's the same thing with jj undo - I now think that we don't need this flag at all in both subcommands.

If jj prints a warning that you messed with someone's signature, you can just undo that.

Or, if we keep it, it's better to have it in both ones for consistency

Copy link
Contributor Author

Choose a reason for hiding this comment

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

Actually, it's the same thing with jj undo - I now think that we don't need this flag at all in both subcommands.

If jj prints a warning that you messed with someone's signature, you can just undo that.

Couldn't agree more on removing the flag entirely. That also leaves us with a simpler interface.

}

pub fn cmd_unsign(
ui: &mut Ui,
command: &CommandHelper,
args: &UnsignArgs,
) -> Result<(), CommandError> {
let mut workspace_command = command.workspace_helper(ui)?;

let commits: IndexSet<Commit> = workspace_command
.parse_union_revsets(ui, &args.revisions)?
.evaluate_to_commits()?
.try_collect()?;

if !args.allow_not_mine {
check_commits_authored_by(
&commits,
workspace_command.settings().user_email(),
"Use --allow-not-mine to unsign anyway.",
)?;
}

workspace_command.check_rewritable(commits.iter().ids())?;

let mut tx = workspace_command.start_transaction();

let mut unsigned_commits = vec![];
tx.repo_mut().transform_descendants(
commits.iter().ids().cloned().collect_vec(),
|rewriter| {
if commits.contains(rewriter.old_commit()) {
let commit_builder = rewriter.reparent();
let new_commit = commit_builder
.set_sign_behavior(SignBehavior::Drop)
.write()?;
unsigned_commits.push(new_commit);
}
Ok(())
},
)?;

if let Some(mut formatter) = ui.status_formatter() {
match &*unsigned_commits {
[] => {}
[commit] => {
write!(formatter, "Unsigned commit ")?;
tx.base_workspace_helper()
.write_commit_summary(formatter.as_mut(), commit)?;
writeln!(ui.status())?;
}
commits => {
let template = tx.base_workspace_helper().commit_summary_template();
writeln!(formatter, "Unsigned the following commits:")?;
for commit in commits {
write!(formatter, " ")?;
template.format(commit, formatter.as_mut())?;
writeln!(formatter)?;
}
}
};
}
let transaction_description = match &*unsigned_commits {
[] => "".to_string(),
[commit] => format!("unsign commit {}", commit.id()),
commits => format!(
"unsign commit {} and {} more",
commits[0].id(),
commits.len() - 1
),
};
tx.finish(ui, transaction_description)?;

Ok(())
}
Loading