Debian Codegraph @

rust/rhg/src/commands/annotate.rs

raw
1 use core::str;
2 use std::cell::Ref;
3 use std::collections::hash_map::Entry;
4 use std::ffi::OsString;
5
6 use chrono::DateTime;
7 use chrono::FixedOffset;
8 use chrono::Local;
9 use format_bytes::format_bytes;
10 use hg::encoding::Encoder;
11 use hg::errors::HgError;
12 use hg::errors::IoResultExt as _;
13 use hg::operations::annotate;
14 use hg::operations::AnnotateOptions;
15 use hg::operations::AnnotateOutput;
16 use hg::operations::ChangesetAnnotatedFile;
17 use hg::repo::Repo;
18 use hg::revlog::changelog::Changelog;
19 use hg::revlog::RevisionOrWdir;
20 use hg::utils::hg_path::HgPath;
21 use hg::utils::strings::CleanWhitespace;
22 use hg::FastHashMap;
23 use hg::Node;
24 use hg::Revision;
25 use hg::WORKING_DIRECTORY_HEX;
26 use hg::WORKING_DIRECTORY_REVISION;
27
28 use crate::error::CommandError;
29 use crate::ui::StdoutBuffer;
30 use crate::utils::path_utils::resolve_file_args;
31
32 pub const HELP_TEXT: &str = "
33 show changeset information by line for each file
34 ";
35
36 pub fn args() -> clap::Command {
37 clap::command!("annotate")
38 .alias("blame")
39 .args_override_self(true)
40 .arg(
41 clap::Arg::new("files")
42 .help("files to annotate")
43 .required(true)
44 .num_args(1..)
45 .value_name("FILE")
46 .value_parser(clap::value_parser!(OsString)),
47 )
48 .arg(
49 clap::Arg::new("rev")
50 .help("annotate the specified revision")
51 .short('r')
52 .long("rev")
53 .value_name("REV")
54 .default_value("."),
55 )
56 .arg(
57 clap::Arg::new("follow")
58 .help(
59 "follow copies/renames and list the filename (DEPRECATED)",
60 )
61 .long("follow")
62 .action(clap::ArgAction::SetTrue),
63 )
64 .arg(
65 clap::Arg::new("no-follow")
66 .help("don't follow copies and renames")
67 .long("no-follow")
68 .action(clap::ArgAction::SetTrue)
69 .conflicts_with("follow"),
70 )
71 .arg(
72 clap::Arg::new("text")
73 .help("treat all files as text")
74 .short('a')
75 .long("text")
76 .action(clap::ArgAction::SetTrue),
77 )
78 .arg(
79 clap::Arg::new("user")
80 .help("list the author (long with -v)")
81 .short('u')
82 .long("user")
83 .action(clap::ArgAction::SetTrue),
84 )
85 .arg(
86 clap::Arg::new("number")
87 .help("list the revision number (default)")
88 .short('n')
89 .long("number")
90 .action(clap::ArgAction::SetTrue),
91 )
92 .arg(
93 clap::Arg::new("changeset")
94 .help("list the changeset")
95 .short('c')
96 .long("changeset")
97 .action(clap::ArgAction::SetTrue),
98 )
99 .arg(
100 clap::Arg::new("date")
101 .help("list the date (short with -q)")
102 .short('d')
103 .long("date")
104 .action(clap::ArgAction::SetTrue),
105 )
106 .arg(
107 clap::Arg::new("file")
108 .help("list the filename")
109 .short('f')
110 .long("file")
111 .action(clap::ArgAction::SetTrue),
112 )
113 .arg(
114 clap::Arg::new("line-number")
115 .help("show the line number at the first appearance")
116 .short('l')
117 .long("line-number")
118 .action(clap::ArgAction::SetTrue),
119 )
120 .arg(
121 clap::Arg::new("quiet")
122 .help("show short date for -d")
123 .short('q')
124 .long("quiet")
125 .action(clap::ArgAction::SetTrue),
126 )
127 .arg(
128 clap::Arg::new("verbose")
129 .help("show full username for -u")
130 .short('v')
131 .long("verbose")
132 .action(clap::ArgAction::SetTrue)
133 .conflicts_with("quiet"),
134 )
135 .arg(
136 clap::Arg::new("ignore-all-space")
137 .help("ignore white space when comparing lines")
138 .short('w')
139 .long("ignore-all-space")
140 .action(clap::ArgAction::SetTrue),
141 )
142 .arg(
143 clap::Arg::new("ignore-space-change")
144 .help("ignore changes in the amount of white space")
145 .short('b')
146 .long("ignore-space-change")
147 .action(clap::ArgAction::SetTrue),
148 )
149 .arg(
150 clap::Arg::new("ignore-blank-lines")
151 .help("ignore changes whose lines are all blank")
152 .short('B')
153 .long("ignore-blank-lines")
154 .action(clap::ArgAction::SetTrue),
155 )
156 .arg(
157 clap::Arg::new("ignore-space-at-eol")
158 .help("ignore changes in whitespace at EOL")
159 .short('Z')
160 .long("ignore-space-at-eol")
161 .action(clap::ArgAction::SetTrue),
162 )
163 .arg(
164 clap::Arg::new("template")
165 .help("display with template")
166 .short('T')
167 .long("template"),
168 )
169 .about(HELP_TEXT)
170 }
171
172 #[tracing::instrument(level = "debug", skip_all, name = "rhg annotate")]
173 pub fn run(invocation: &crate::CliInvocation) -> Result<(), CommandError> {
174 let config = invocation.config;
175 if config.has_non_empty_section(b"annotate") {
176 return Err(CommandError::unsupported(
177 "rhg annotate does not support any [annotate] configs",
178 ));
179 }
180
181 let repo = invocation.repo?;
182 let args = invocation.subcommand_args;
183
184 let rev = args.get_one::<String>("rev").expect("rev has a default");
185 let rev = hg::revset::resolve_single(rev, repo)?;
186
187 let files = match args.get_many::<OsString>("files") {
188 None => vec![],
189 Some(files) => resolve_file_args(repo, files)?,
190 };
191
192 let options = AnnotateOptions {
193 treat_binary_as_text: args.get_flag("text"),
194 follow_copies: !args.get_flag("no-follow"),
195 whitespace: if args.get_flag("ignore-all-space") {
196 Some(CleanWhitespace::All)
197 } else if args.get_flag("ignore-space-change") {
198 Some(CleanWhitespace::Collapse)
199 } else if args.get_flag("ignore-space-at-eol") {
200 Some(CleanWhitespace::AtEol)
201 } else {
202 // We ignore the --ignore-blank-lines flag (present for consistency
203 // with other commands) since it has no effect on annotate.
204 None
205 },
206 };
207
208 let mut include = Include {
209 user: args.get_flag("user"),
210 number: args.get_flag("number"),
211 changeset: args.get_flag("changeset"),
212 date: args.get_flag("date"),
213 file: args.get_flag("file") || args.get_flag("follow"),
214 line_number: args.get_flag("line-number"),
215 };
216 if !(include.user || include.file || include.date || include.changeset) {
217 include.number = true;
218 }
219 if include.line_number && !(include.number || include.changeset) {
220 return Err(CommandError::abort(
221 "abort: at least one of -n/-c is required for -l",
222 ));
223 }
224
225 let verbosity = match (args.get_flag("quiet"), args.get_flag("verbose")) {
226 (false, false) => Verbosity::Default,
227 (true, false) => Verbosity::Quiet,
228 (false, true) => Verbosity::Verbose,
229 (true, true) => unreachable!(),
230 };
231
232 let template = match args.get_one::<String>("template") {
233 None => Template::Default,
234 Some(name) if name == "json" => Template::Json,
235 _ => {
236 return Err(CommandError::unsupported("only -Tjson is suppported"))
237 }
238 };
239
240 let wdir_config = if rev.is_wdir() {
241 let user = config.username()?;
242 Some(WdirConfig { user })
243 } else {
244 None
245 };
246
247 let format_config =
248 FormatConfig { template, include, verbosity, wdir_config };
249
250 let file_results = files.iter().map(|path| -> FileResult {
251 (path.as_ref(), annotate(repo, path, rev, options))
252 });
253
254 print_output(repo, invocation.ui, &format_config, rev, file_results)
255 }
256
257 struct FormatConfig {
258 template: Template,
259 include: Include,
260 verbosity: Verbosity,
261 wdir_config: Option<WdirConfig>,
262 }
263
264 enum Template {
265 Default,
266 Json,
267 }
268
269 struct Include {
270 user: bool,
271 number: bool,
272 changeset: bool,
273 date: bool,
274 file: bool,
275 line_number: bool,
276 }
277
278 impl Include {
279 fn count(&self) -> usize {
280 // Rust guarantees false is 0 and true is 1.
281 self.user as usize
282 + self.number as usize
283 + self.changeset as usize
284 + self.date as usize
285 + self.file as usize
286 + self.line_number as usize
287 }
288 }
289
290 enum Verbosity {
291 Quiet,
292 Default,
293 Verbose,
294 }
295
296 /// Information to use for lines that changed in the working directory.
297 struct WdirConfig {
298 user: Vec<u8>,
299 }
300
301 /// Information that we can cache per changeset.
302 /// For [`Template::Json`], the values are JSON encoded.
303 #[derive(Default)]
304 struct ChangesetData {
305 user: Option<Vec<u8>>,
306 changeset: Option<Vec<u8>>,
307 date: Option<Vec<u8>>,
308 }
309
310 /// Whether the "+" sigil calculation is for --number or --changeset.
311 #[derive(PartialEq, Eq)]
312 enum SigilFor {
313 Number,
314 Changeset,
315 }
316
317 type FileResult<'a> = (&'a HgPath, Result<AnnotateOutput, HgError>);
318
319 fn print_output<'a>(
320 repo: &Repo,
321 ui: &crate::Ui,
322 config: &FormatConfig,
323 rev: RevisionOrWdir,
324 file_results: impl Iterator<Item = FileResult<'a>>,
325 ) -> Result<(), CommandError> {
326 let encoder = ui.encoder();
327 let stdout = &mut ui.stdout_buffer();
328 let dirstate_p1 =
329 repo.changelog()?.rev_from_node(repo.dirstate_parents()?.p1.into())?;
330 let mut cache = Cache::new(repo)?;
331 match config.template {
332 Template::Default => {
333 for (path, output) in file_results {
334 match output? {
335 AnnotateOutput::Text(file) => {
336 print_lines_default(
337 file,
338 config,
339 stdout,
340 encoder,
341 cache.for_path(path),
342 dirstate_p1,
343 )?;
344 }
345 AnnotateOutput::Binary => {
346 stdout.write_all(&format_bytes!(
347 b"{}: binary file\n",
348 path.as_bytes()
349 ))?;
350 }
351 AnnotateOutput::NotFound => {
352 return handle_not_found(repo, rev, path)
353 }
354 }
355 }
356 }
357 Template::Json => {
358 stdout.write_all(b"[")?;
359 let mut file_sep: &[u8] = b"\n";
360 for (path, output) in file_results {
361 stdout.write_all(file_sep)?;
362 file_sep = b",\n";
363 stdout.write_all(b" {\n")?;
364 match output? {
365 AnnotateOutput::Text(file) => {
366 print_lines_json(
367 file,
368 config,
369 stdout,
370 cache.for_path(path),
371 )?;
372 }
373 AnnotateOutput::Binary => {}
374 AnnotateOutput::NotFound => {
375 return handle_not_found(repo, rev, path)
376 }
377 }
378 let path = json_string(path.as_bytes())?;
379 stdout
380 .write_all(&format_bytes!(b" \"path\": {}\n }", path))?;
381 }
382 stdout.write_all(b"\n]\n")?;
383 }
384 }
385 stdout.flush()?;
386 Ok(())
387 }
388
389 type Stdout<'a> = StdoutBuffer<'a, std::io::BufWriter<std::io::StdoutLock<'a>>>;
390
391 fn print_lines_default(
392 file: ChangesetAnnotatedFile,
393 config: &FormatConfig,
394 stdout: &mut Stdout,
395 encoder: &Encoder,
396 mut cache: CacheForPath,
397 dirstate_p1: Revision,
398 ) -> Result<(), CommandError> {
399 // Serialize the annotation fields (revision, user, etc.) for each line
400 // and keep track of their maximum lengths so that we can align them.
401 let mut field_lists: Vec<Vec<Vec<u8>>> =
402 Vec::with_capacity(file.annotations.len());
403 let num_fields = config.include.count();
404 let mut widths = vec![0usize; num_fields];
405 for annotation in file.annotations {
406 let rev = annotation.revision;
407 let data = cache.get_data(rev, config)?;
408 let mut fields = Vec::with_capacity(num_fields);
409 if let Some(user) = &data.user {
410 fields.push(user.clone());
411 }
412 if config.include.number {
413 let number = rev.exclude_wdir().unwrap_or(dirstate_p1);
414 let sigil = fmt_sigil(config, rev, SigilFor::Number);
415 fields.push(format_bytes!(b"{}{}", number, sigil));
416 }
417 if let Some(changeset) = &data.changeset {
418 let sigil = fmt_sigil(config, rev, SigilFor::Changeset);
419 fields.push(format_bytes!(b"{}{}", changeset, sigil));
420 }
421 if let Some(date) = &data.date {
422 fields.push(date.clone());
423 }
424 if config.include.file {
425 fields.push(annotation.path.into_vec());
426 }
427 if config.include.line_number {
428 fields.push(format_bytes!(b"{}", annotation.line_number));
429 }
430 for (field, width) in fields.iter().zip(widths.iter_mut()) {
431 *width = std::cmp::max(*width, encoder.column_width_bytes(field));
432 }
433 field_lists.push(fields);
434 }
435 // Print each line of the file prefixed by aligned annotations.
436 let total_width = widths.iter().sum::<usize>() + num_fields - 1;
437 for (fields, line) in field_lists.iter().zip(file.lines.iter()) {
438 let mut annotation = Vec::with_capacity(total_width);
439 for (i, (field, width)) in fields.iter().zip(widths.iter()).enumerate()
440 {
441 if i > 0 {
442 let colon = config.include.line_number && i == num_fields - 1;
443 annotation.push(if colon { b':' } else { b' ' });
444 }
445 let padding = width - encoder.column_width_bytes(field);
446 annotation.resize(annotation.len() + padding, b' ');
447 annotation.extend_from_slice(field);
448 }
449 stdout.write_all(&format_bytes!(b"{}: {}", annotation, line))?;
450 }
451 if let Some(line) = file.lines.last() {
452 if !line.ends_with(b"\n") {
453 stdout.write_all(b"\n")?;
454 }
455 }
456 Ok(())
457 }
458
459 fn print_lines_json(
460 file: ChangesetAnnotatedFile,
461 config: &FormatConfig,
462 stdout: &mut Stdout,
463 mut cache: CacheForPath,
464 ) -> Result<(), CommandError> {
465 stdout.write_all(br#" "lines": ["#)?;
466 let mut line_sep: &[u8] = b"";
467 for (annotation, line) in file.annotations.iter().zip(file.lines.iter()) {
468 stdout.write_all(line_sep)?;
469 line_sep = b", ";
470
471 let mut property_sep: &[u8] = b"";
472 let mut property = |key: &[u8], value: &[u8]| {
473 let res = format_bytes!(br#"{}"{}": {}"#, property_sep, key, value);
474 property_sep = b", ";
475 res
476 };
477
478 stdout.write_all(b"{")?;
479 let rev = annotation.revision;
480 let data = cache.get_data(rev, config)?;
481 if let Some(date_json) = &data.date {
482 stdout.write_all(&property(b"date", date_json))?;
483 }
484 stdout.write_all(&property(b"line", &json_string(line)?))?;
485 if config.include.line_number {
486 let lineno = annotation.line_number.to_string();
487 stdout.write_all(&property(b"lineno", lineno.as_bytes()))?;
488 }
489 if let Some(changeset_json) = &data.changeset {
490 stdout.write_all(&property(b"node", changeset_json))?;
491 }
492 if config.include.file {
493 let path = json_string(annotation.path.as_bytes())?;
494 stdout.write_all(&property(b"path", &path))?;
495 }
496 if config.include.number {
497 let number = match rev.exclude_wdir() {
498 Some(rev) => rev.0,
499 None => WORKING_DIRECTORY_REVISION.0,
500 };
501 stdout
502 .write_all(&property(b"rev", number.to_string().as_bytes()))?;
503 }
504 if let Some(user_json) = &data.user {
505 stdout.write_all(&property(b"user", user_json))?;
506 }
507 stdout.write_all(b"}")?;
508 }
509 stdout.write_all(b"],\n")?;
510 Ok(())
511 }
512
513 fn handle_not_found(
514 repo: &Repo,
515 rev: RevisionOrWdir,
516 path: &HgPath,
517 ) -> Result<(), CommandError> {
518 Err(CommandError::abort(match rev.exclude_wdir() {
519 Some(rev) => {
520 let short = repo.changelog()?.node_from_rev(rev).short();
521 format!("abort: {path}: no such file in rev {short:x}",)
522 }
523 None => {
524 format!("abort: {path}: No such file or directory")
525 }
526 }))
527 }
528
529 /// Returns the sigil to put after the revision number or changeset.
530 fn fmt_sigil(
531 config: &FormatConfig,
532 rev: RevisionOrWdir,
533 which: SigilFor,
534 ) -> &'static [u8] {
535 // The "+" sigil is only used for '--rev wdir()'.
536 if config.wdir_config.is_none() {
537 return b"";
538 };
539 // With --number --changeset, put it after the changeset.
540 if which == SigilFor::Number && config.include.changeset {
541 return b"";
542 }
543 if rev.is_wdir() {
544 b"+"
545 } else {
546 b" "
547 }
548 }
549
550 /// A cache of [`ChangesetData`] for each changeset we've seen.
551 struct Cache<'a> {
552 repo: &'a Repo,
553 changelog: Ref<'a, Changelog>,
554 map: FastHashMap<RevisionOrWdir, ChangesetData>,
555 }
556
557 impl<'a> Cache<'a> {
558 fn new(repo: &'a Repo) -> Result<Self, CommandError> {
559 Ok(Self { repo, changelog: repo.changelog()?, map: Default::default() })
560 }
561
562 fn for_path(&mut self, path: &'a HgPath) -> CacheForPath<'_, 'a> {
563 CacheForPath { cache: self, path }
564 }
565 }
566
567 /// [`Cache`] scoped to annotating a particular file.
568 struct CacheForPath<'a, 'b> {
569 cache: &'a mut Cache<'b>,
570 path: &'a HgPath,
571 }
572
573 impl CacheForPath<'_, '_> {
574 fn get_data(
575 &mut self,
576 rev: RevisionOrWdir,
577 config: &FormatConfig,
578 ) -> Result<&ChangesetData, CommandError> {
579 Ok(match self.cache.map.entry(rev) {
580 Entry::Occupied(occupied) => occupied.into_mut(),
581 Entry::Vacant(vacant) => vacant.insert(ChangesetData::create(
582 rev,
583 self.path,
584 self.cache.repo,
585 &self.cache.changelog,
586 config,
587 )?),
588 })
589 }
590 }
591
592 impl Drop for CacheForPath<'_, '_> {
593 fn drop(&mut self) {
594 // Clear the wdir cache entry, otherwise `rhg annotate --date f1 f2`
595 // would use f1's mtime for lines in f2 attributed to wdir.
596 self.cache.map.remove(&RevisionOrWdir::wdir());
597 }
598 }
599
600 impl ChangesetData {
601 fn create(
602 revision: RevisionOrWdir,
603 path: &HgPath,
604 repo: &Repo,
605 changelog: &Changelog,
606 config: &FormatConfig,
607 ) -> Result<Self, CommandError> {
608 let include = &config.include;
609 if !(include.user || include.changeset || include.date) {
610 return Ok(Self::default());
611 }
612 match revision.exclude_wdir() {
613 Some(revision) => {
614 let entry = changelog.entry(revision)?;
615 let data = entry.data()?;
616 let node = *entry.as_revlog_entry().node();
617 Self::new(data.user(), node, data.timestamp()?, config)
618 }
619 None => {
620 let node = match config.template {
621 Template::Default => repo.dirstate_parents()?.p1,
622 Template::Json => Node::from_hex(WORKING_DIRECTORY_HEX)
623 .expect("wdir hex should parse"),
624 };
625 let fs_path = hg::utils::hg_path::hg_path_to_path_buf(path)?;
626 let meta =
627 repo.working_directory_vfs().symlink_metadata(&fs_path)?;
628 let mtime = meta.modified().when_reading_file(&fs_path)?;
629 let mtime = DateTime::<Local>::from(mtime).fixed_offset();
630 let user =
631 &config.wdir_config.as_ref().expect("should be set").user;
632 Self::new(user, node, mtime, config)
633 }
634 }
635 }
636
637 fn new(
638 user: &[u8],
639 changeset: Node,
640 date: DateTime<FixedOffset>,
641 config: &FormatConfig,
642 ) -> Result<Self, CommandError> {
643 let mut result = ChangesetData::default();
644 if config.include.user {
645 let user = match config.template {
646 Template::Default => match config.verbosity {
647 Verbosity::Verbose => user.to_vec(),
648 _ => hg::utils::strings::short_user(user).to_vec(),
649 },
650 Template::Json => json_string(user)?,
651 };
652 result.user = Some(user.to_vec());
653 }
654 if config.include.changeset {
655 let hex = match config.template {
656 Template::Default => format!("{:x}", changeset.short()),
657 Template::Json => format!("\"{:x}\"", changeset),
658 };
659 result.changeset = Some(hex.into_bytes());
660 }
661 if config.include.date {
662 let date = match config.template {
663 Template::Default => {
664 format!(
665 "{}",
666 date.format(match config.verbosity {
667 Verbosity::Quiet => "%Y-%m-%d",
668 _ => "%a %b %d %H:%M:%S %Y %z",
669 })
670 )
671 }
672 Template::Json => format!(
673 "[{}.0, {}]",
674 date.timestamp(),
675 date.offset().utc_minus_local(),
676 ),
677 };
678 result.date = Some(date.into_bytes());
679 }
680 Ok(result)
681 }
682 }
683
684 fn json_string(text: &[u8]) -> Result<Vec<u8>, CommandError> {
685 serde_json::to_vec(&String::from_utf8_lossy(text)).map_err(|err| {
686 CommandError::abort(format!(
687 "failed to serialize string to JSON: {err}"
688 ))
689 })
690 }