Debian Codegraph @

cli/src/commands/file/annotate.rs

raw
1 // Copyright 2024 The Jujutsu Authors
2 //
3 // Licensed under the Apache License, Version 2.0 (the "License");
4 // you may not use this file except in compliance with the License.
5 // You may obtain a copy of the License at
6 //
7 // https://www.apache.org/licenses/LICENSE-2.0
8 //
9 // Unless required by applicable law or agreed to in writing, software
10 // distributed under the License is distributed on an "AS IS" BASIS,
11 // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
12 // See the License for the specific language governing permissions and
13 // limitations under the License.
14
15 use clap_complete::ArgValueCandidates;
16 use clap_complete::ArgValueCompleter;
17 use jj_lib::annotate::FileAnnotation;
18 use jj_lib::annotate::FileAnnotator;
19 use jj_lib::annotate::LineOrigin;
20 use jj_lib::backend::MergedTreeValueExt as _;
21 use jj_lib::repo::Repo;
22 use jj_lib::revset::RevsetExpression;
23 use tracing::instrument;
24
25 use crate::cli_util::CommandHelper;
26 use crate::cli_util::RevisionArg;
27 use crate::command_error::CommandError;
28 use crate::command_error::user_error;
29 use crate::commit_templater::AnnotationLine;
30 use crate::complete;
31 use crate::templater::TemplateRenderer;
32 use crate::ui::Ui;
33
34 /// Show the source change for each line of the target file.
35 ///
36 /// Annotates a revision line by line. Each line includes the source change that
37 /// introduced the associated line. A path to the desired file must be provided.
38 #[derive(clap::Args, Clone, Debug)]
39 pub(crate) struct FileAnnotateArgs {
40 /// the file to annotate
41 #[arg(value_hint = clap::ValueHint::AnyPath)]
42 #[arg(add = ArgValueCompleter::new(complete::all_revision_files))]
43 path: String,
44
45 /// an optional revision to start at
46 #[arg(long, short, value_name = "REVSET")]
47 #[arg(add = ArgValueCompleter::new(complete::revset_expression_all))]
48 revision: Option<RevisionArg>,
49
50 /// Render each line using the given template
51 ///
52 /// All 0-argument methods of the [`AnnotationLine` type] are available as
53 /// keywords in the template expression. See [`jj help -k templates`] for
54 /// more information.
55 ///
56 /// If not specified, this defaults to the `templates.file_annotate`
57 /// setting.
58 ///
59 /// [`AnnotationLine` type]:
60 /// https://docs.jj-vcs.dev/latest/templates/#annotationline-type
61 ///
62 /// [`jj help -k templates`]:
63 /// https://docs.jj-vcs.dev/latest/templates/
64 #[arg(long, short = 'T')]
65 #[arg(add = ArgValueCandidates::new(complete::template_aliases))]
66 template: Option<String>,
67 }
68
69 #[instrument(skip_all)]
70 pub(crate) async fn cmd_file_annotate(
71 ui: &mut Ui,
72 command: &CommandHelper,
73 args: &FileAnnotateArgs,
74 ) -> Result<(), CommandError> {
75 let workspace_command = command.workspace_helper(ui).await?;
76 let repo = workspace_command.repo();
77 let starting_commit = workspace_command
78 .resolve_single_rev(ui, args.revision.as_ref().unwrap_or(&RevisionArg::AT))
79 .await?;
80 let file_path = workspace_command.parse_file_path(&args.path)?;
81 let file_value = starting_commit.tree().path_value(&file_path).await?;
82 let ui_path = workspace_command.format_file_path(&file_path);
83
84 if file_value.is_absent() {
85 return Err(user_error(format!("No such path: {ui_path}")));
86 }
87 if file_value.to_file_merge().is_none() {
88 return Err(user_error(format!(
89 "Path exists but is not a regular file: {ui_path}"
90 )));
91 }
92
93 let template_text = match &args.template {
94 Some(value) => value.clone(),
95 None => workspace_command
96 .settings()
97 .get_string("templates.file_annotate")?,
98 };
99 let language = workspace_command.commit_template_language();
100 let template = workspace_command.parse_template(ui, &language, &template_text)?;
101
102 // TODO: Should we add an option to limit the domain to e.g. recent commits?
103 // Note that this is probably different from "--skip REVS", which won't
104 // exclude the revisions, but will ignore diffs in those revisions as if
105 // ancestor revisions had new content.
106 let mut annotator = FileAnnotator::from_commit(&starting_commit, &file_path).await?;
107 annotator
108 .compute(repo.as_ref(), &RevsetExpression::all())
109 .await?;
110 let annotation = annotator.to_annotation();
111
112 render_file_annotation(repo.as_ref(), ui, &template, &annotation).await?;
113 Ok(())
114 }
115
116 async fn render_file_annotation(
117 repo: &dyn Repo,
118 ui: &mut Ui,
119 template_render: &TemplateRenderer<'_, AnnotationLine>,
120 annotation: &FileAnnotation,
121 ) -> Result<(), CommandError> {
122 ui.request_pager();
123 let mut formatter = ui.stdout_formatter();
124 let mut last_id = None;
125 // At least in cases where the repository was jj-initialized shallowly,
126 // then unshallow'd with git, some changes will not have a commit id
127 // because jj does not import the unshallow'd commits. So we default
128 // to the root commit id for now.
129 let default_line_origin = LineOrigin {
130 commit_id: repo.store().root_commit_id().clone(),
131 line_number: 0,
132 };
133 for (line_number, (line_origin, content)) in annotation.line_origins().enumerate() {
134 let line_origin = line_origin.unwrap_or(&default_line_origin);
135 let commit = repo
136 .store()
137 .get_commit_async(&line_origin.commit_id)
138 .await?;
139 let first_line_in_hunk = last_id != Some(&line_origin.commit_id);
140 let annotation_line = AnnotationLine {
141 commit,
142 content: content.to_owned(),
143 line_number: line_number + 1,
144 original_line_number: line_origin.line_number + 1,
145 first_line_in_hunk,
146 };
147 template_render.format(&annotation_line, formatter.as_mut())?;
148 last_id = Some(&line_origin.commit_id);
149 }
150
151 Ok(())
152 }