Debian Codegraph @

cli/src/commands/fix.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 std::collections::HashMap;
16 use std::io::Write as _;
17 use std::path::Path;
18 use std::process::Stdio;
19
20 use clap_complete::ArgValueCompleter;
21 use futures::AsyncReadExt as _;
22 use futures::TryStreamExt as _;
23 use itertools::Itertools as _;
24 use jj_lib::backend::FileId;
25 use jj_lib::commit::Commit;
26 use jj_lib::fileset;
27 use jj_lib::fileset::FilesetDiagnostics;
28 use jj_lib::fileset::FilesetExpression;
29 use jj_lib::fileset::FilesetParseContext;
30 use jj_lib::fix::FileToFix;
31 use jj_lib::fix::FixError;
32 use jj_lib::fix::LineRange;
33 use jj_lib::fix::ParallelFileFixer;
34 use jj_lib::fix::RegionsToFormat;
35 use jj_lib::fix::compute_changed_ranges;
36 use jj_lib::fix::compute_file_line_count;
37 use jj_lib::fix::fix_files;
38 use jj_lib::matchers::Matcher;
39 use jj_lib::repo::Repo as _;
40 use jj_lib::revset::RevsetStreamExt as _;
41 use jj_lib::settings::UserSettings;
42 use jj_lib::store::Store;
43 use jj_lib::ui_path::RepoPathUiConverter;
44 use pollster::FutureExt as _;
45 use tracing::instrument;
46
47 use crate::cli_util::CommandHelper;
48 use crate::cli_util::RevisionArg;
49 use crate::cli_util::print_unmatched_explicit_paths;
50 use crate::command_error::CommandError;
51 use crate::command_error::config_error;
52 use crate::command_error::print_parse_diagnostics;
53 use crate::complete;
54 use crate::config::CommandNameAndArgs;
55 use crate::ui::Ui;
56
57 /// Update files with formatting fixes or other changes
58 ///
59 /// The primary use case for this command is to apply the results of automatic
60 /// code formatting tools to revisions that may not be properly formatted yet.
61 /// It can also be used to modify files with other tools like `sed` or `sort`.
62 ///
63 /// The modification made by `jj fix` can be reviewed by `jj op show -p`.
64 ///
65 /// ### How it works
66 ///
67 /// The changed files in the given revisions will be updated with any fixes
68 /// determined by passing their file content through any external tools the user
69 /// has configured for those files. Descendants will also be updated by passing
70 /// their versions of the same files through the same tools, which will ensure
71 /// that the fixes are not lost. This will never result in new conflicts. Files
72 /// with existing conflicts will be updated on all sides of the conflict, which
73 /// can potentially increase or decrease the number of conflict markers.
74 ///
75 /// ### Deduplication
76 ///
77 /// When fixing multiple commits, if the same file content appears at the same
78 /// path in different commits, the tool is run only once and the result is
79 /// reused. This means that tools used with `jj fix` must produce deterministic
80 /// output.
81 ///
82 /// ### Configuration
83 ///
84 /// See `jj help -k config` chapter `Code formatting and other file content
85 /// transformations` to understand how to configure your tools.
86 ///
87 /// ### Execution example
88 ///
89 /// Let's consider the following configuration. We have two code formatters
90 /// (`clang-format` and `black`), which apply to three different file extensions
91 /// (`.cc`, `.h`, and `.py`):
92 ///
93 /// ```toml
94 /// [fix.tools.clang-format]
95 /// command = ["/usr/bin/clang-format", "--assume-filename=$path"]
96 /// patterns = ["glob:'**/*.cc'",
97 /// "glob:'**/*.h'"]
98 ///
99 /// [fix.tools.black]
100 /// command = ["/usr/bin/black", "-", "--stdin-filename=$path"]
101 /// patterns = ["glob:'**/*.py'"]
102 /// ```
103 ///
104 /// Now, let's see what would happen to the following history, when executing
105 /// `jj fix`.
106 ///
107 /// ```text
108 /// C (mutable)
109 /// | Modifies file: foo.py
110 /// |
111 /// B @ (working copy - mutable)
112 /// | Modifies file: README.md
113 /// |
114 /// A (mutable)
115 /// | Modifies files: src/bar.cc and src/bar.h
116 /// |
117 /// X (immutable)
118 /// ```
119 ///
120 /// By default, `jj fix` will modify revisions that match the revset
121 /// `reachable(@, mutable())` (see `jj help -k revsets`), which corresponds to
122 /// the revisions `A`, `B` and `C` here.
123 ///
124 /// The following operations will then happen:
125 ///
126 /// - For revision `A`, the contents from this revision for files `src/bar.cc`
127 /// and `src/bar.h` will be provided to `clang-format`, and the resulting
128 /// output will be used to recreate revision `A`, which we will call `A'`. All
129 /// other files are untouched.
130 /// - For revision `B`, the same thing happens for files `src/bar.cc` and
131 /// `src/bar.h`. Their contents from revision `B` will go through
132 /// `clang-format`. The file `README.md`, same as all other files, is
133 /// untouched as no pattern matches it. We obtain revision `B'`.
134 /// - For revision `C`, the files `src/bar.cc` and `src/bar.h` go through
135 /// `clang-format` and the file `foo.py` is fixed using `black`. All other
136 /// files are untouched. We obtain revision `C'`.
137 ///
138 /// ```text
139 /// C (mutable) /-> C'
140 /// | src/bar.cc -> clang-format -| |
141 /// | src/bar.h --> clang-format -| |
142 /// | foo.py -----> black --------| |
143 /// | * --------------------------/ |
144 /// | |
145 /// B @ (working copy - mutable) /-> B' @
146 /// | src/bar.cc -> clang-format -| |
147 /// | src/bar.h --> clang-format -| |
148 /// | * --------------------------| |
149 /// | |
150 /// A (mutable) /-> A'
151 /// | src/bar.cc -> clang-format -| |
152 /// | src/bar.h --> clang-format -| |
153 /// | * --------------------------/ |
154 /// | |
155 /// X (immutable) X
156 /// ```
157 ///
158 /// The revisions are now all correctly formatted according to the
159 /// configuration.
160 #[derive(clap::Args, Clone, Debug)]
161 #[command(verbatim_doc_comment)]
162 pub(crate) struct FixArgs {
163 /// Fix files in the specified revision(s) and their descendants. If no
164 /// revisions are specified, this defaults to the `revsets.fix` setting, or
165 /// `reachable(@, mutable())` if it is not set.
166 #[arg(long, short, value_name = "REVSETS")]
167 #[arg(add = ArgValueCompleter::new(complete::revset_expression_mutable))]
168 source: Vec<RevisionArg>,
169
170 /// Fix only these paths
171 #[arg(value_name = "FILESETS", value_hint = clap::ValueHint::AnyPath)]
172 paths: Vec<String>,
173
174 /// Fix unchanged files in addition to changed ones. If no paths are
175 /// specified, all files in the repo will be fixed.
176 #[arg(long)]
177 include_unchanged_files: bool,
178
179 /// Format all lines instead of only modified lines.
180 ///
181 /// If the formatter doesn't support formatting only modified lines, then
182 /// this option has no effect since the formatter always formats all lines.
183 #[arg(long, short)]
184 all_lines: bool,
185 }
186
187 #[instrument(skip_all)]
188 pub(crate) async fn cmd_fix(
189 ui: &mut Ui,
190 command: &CommandHelper,
191 args: &FixArgs,
192 ) -> Result<(), CommandError> {
193 let mut workspace_command = command.workspace_helper(ui).await?;
194 let workspace_root = workspace_command.workspace_root().to_owned();
195 let path_converter = workspace_command.path_converter().to_owned();
196 let tools_config = get_tools_config(
197 ui,
198 workspace_command.settings(),
199 &workspace_command.env().fileset_parse_context_for_config(),
200 )?;
201 let target_expr = if args.source.is_empty() {
202 let revs = workspace_command.settings().get_string("revsets.fix")?;
203 workspace_command.parse_revset(ui, &RevisionArg::from(revs))?
204 } else {
205 workspace_command.parse_union_revsets(ui, &args.source)?
206 }
207 .resolve()?;
208 workspace_command
209 .check_rewritable_expr(&target_expr)
210 .await?;
211
212 let repo = workspace_command.repo();
213
214 let commits: Vec<Commit> = target_expr
215 .descendants()
216 .evaluate(repo.as_ref())?
217 .stream()
218 .commits(repo.store())
219 .try_collect()
220 .await?;
221
222 let commit_ids = commits
223 .iter()
224 .map(|commit| commit.id().clone())
225 .collect_vec();
226
227 let trees: Vec<_> = commits.iter().map(|commit| commit.tree()).collect();
228
229 let fileset_expression = workspace_command.parse_file_patterns(ui, &args.paths)?;
230 let matcher = fileset_expression.to_matcher();
231
232 let mut tx = workspace_command.start_transaction();
233 let mut parallel_fixer = ParallelFileFixer::new(|store, file_to_fix| {
234 fix_one_file(
235 ui,
236 &workspace_root,
237 &path_converter,
238 &tools_config,
239 store,
240 file_to_fix,
241 args.all_lines,
242 )
243 .block_on()
244 });
245
246 print_unmatched_explicit_paths(ui, tx.base_workspace_helper(), &fileset_expression, &trees)
247 .await?;
248
249 let summary = fix_files(
250 commit_ids,
251 &matcher,
252 args.include_unchanged_files,
253 tx.repo_mut(),
254 &mut parallel_fixer,
255 )
256 .await?;
257 writeln!(
258 ui.status(),
259 "Fixed {} commits of {} checked.",
260 summary.num_fixed_commits,
261 summary.num_checked_commits
262 )?;
263 tx.finish(ui, format!("fixed {} commits", summary.num_fixed_commits))
264 .await
265 }
266
267 /// Invokes all matching tools (if any) to file_to_fix. If the content is
268 /// successfully transformed the new content is written and the new FileId is
269 /// returned. Returns None if the content is unchanged.
270 ///
271 /// The matching tools are invoked in order, with the result of one tool feeding
272 /// into the next tool. Returns FixError if there is an error reading or writing
273 /// the file. However, if a tool invocation fails for whatever reason, the tool
274 /// is simply skipped and we proceed to invoke the next tool (this is
275 /// indistinguishable from succeeding with no changes).
276 ///
277 /// TODO: Better error handling so we can tell the user what went wrong with
278 /// each failed input.
279 async fn fix_one_file(
280 ui: &Ui,
281 workspace_root: &Path,
282 path_converter: &RepoPathUiConverter,
283 tools_config: &ToolsConfig,
284 store: &Store,
285 file_to_fix: &FileToFix,
286 all_lines_arg: bool,
287 ) -> Result<Option<FileId>, FixError> {
288 let mut matching_tools = tools_config
289 .tools
290 .iter()
291 .filter(|tool_config| tool_config.matcher.matches(&file_to_fix.repo_path))
292 .peekable();
293
294 if matching_tools.peek().is_none() {
295 return Ok(None);
296 }
297
298 // The first matching tool gets its input from the committed file, and any
299 // subsequent matching tool gets its input from the previous matching tool's
300 // output.
301
302 // TODO: Consider adding a check for some max file size config or some global
303 // limit for both `old_content` and `base_content`.
304 let mut old_content = vec![];
305 let mut read = store
306 .read_file(&file_to_fix.repo_path, &file_to_fix.file_id)
307 .await?;
308 read.read_to_end(&mut old_content).await?;
309
310 // Do not run any tools on empty files.
311 if old_content.is_empty() {
312 return Ok(None);
313 }
314
315 // Load the base content from the file_to_fix (if exists) iff any tool needs it.
316 let base_content = if all_lines_arg {
317 None
318 } else {
319 match &file_to_fix.base_file_id {
320 Some(base_file_id) if matching_tools.clone().any(|t| t.line_range_arg.is_some()) => {
321 let mut content = vec![];
322 let mut read = store
323 .read_file(&file_to_fix.repo_path, base_file_id)
324 .await?;
325 read.read_to_end(&mut content).await?;
326 Some(content)
327 }
328 _ => None,
329 }
330 };
331
332 let new_content = matching_tools.fold(old_content.clone(), |prev_content, tool_config| {
333 let mut extra_args = Vec::new();
334
335 if let Some(line_range_arg) = &tool_config.line_range_arg {
336 let RegionsToFormat::LineRanges(ranges) =
337 compute_regions_to_format(base_content.as_deref(), &prev_content);
338 if ranges.is_empty() && !tool_config.run_tool_if_zero_line_ranges {
339 // Don't run the tool if there are no line ranges to format and the tool is
340 // configured to not run in that case.
341 return prev_content;
342 }
343
344 for range in ranges {
345 extra_args.push(
346 line_range_arg
347 .replace("$first", &range.first.to_string())
348 .replace("$last", &range.last.to_string()),
349 );
350 }
351 }
352
353 match run_tool(
354 ui,
355 workspace_root,
356 path_converter,
357 &tool_config.command,
358 file_to_fix,
359 &prev_content,
360 &extra_args,
361 ) {
362 Ok(next_content) => next_content,
363 // TODO: Because the stderr is passed through, this isn't always failing
364 // silently, but it should do something better will the exit code, tool
365 // name, etc.
366 Err(()) => prev_content,
367 }
368 });
369
370 if new_content != old_content {
371 // TODO: send futures back over channel
372 let new_file_id = store
373 .write_file(&file_to_fix.repo_path, &mut new_content.as_slice())
374 .await?;
375 return Ok(Some(new_file_id));
376 }
377
378 Ok(None)
379 }
380
381 /// Computes the modified line ranges between the base and current file.
382 pub fn compute_regions_to_format(
383 base_content: Option<&[u8]>,
384 current_content: &[u8],
385 ) -> RegionsToFormat {
386 if current_content.is_empty() {
387 // If the current file content is empty, then there are no regions to format.
388 RegionsToFormat::LineRanges(vec![])
389 } else if let Some(base) = base_content {
390 // If the base file content is available, then compute the modified line ranges
391 // to format between the base and current file.
392 compute_changed_ranges(base, current_content)
393 } else {
394 // Otherwise, format the entire file.
395 let line_count = compute_file_line_count(current_content);
396 RegionsToFormat::LineRanges(vec![LineRange {
397 first: 1,
398 last: line_count,
399 }])
400 }
401 }
402
403 /// Runs the `tool_command` to fix the given file content.
404 ///
405 /// The `old_content` is assumed to be that of the `file_to_fix`'s `FileId`, but
406 /// this is not verified.
407 ///
408 /// Returns the new file content, whose value will be the same as `old_content`
409 /// unless the command introduced changes. Returns `None` if there were any
410 /// failures when starting, stopping, or communicating with the subprocess.
411 fn run_tool(
412 ui: &Ui,
413 workspace_root: &Path,
414 path_converter: &RepoPathUiConverter,
415 tool_command: &CommandNameAndArgs,
416 file_to_fix: &FileToFix,
417 old_content: &[u8],
418 extra_args: &[String],
419 ) -> Result<Vec<u8>, ()> {
420 let mut vars: HashMap<&str, &str> = HashMap::new();
421 vars.insert("path", file_to_fix.repo_path.as_internal_file_string());
422 // TODO: workspace_root.to_str() returns None if the workspace path is not
423 // UTF-8, but we ignore that failure so `jj fix` still runs in that
424 // situation. Maybe we should do something like substituting bytes instead
425 // of strings so we can handle any Path here.
426 if let Some(root) = workspace_root.to_str() {
427 vars.insert("root", root);
428 }
429 let mut command = tool_command.to_command_with_variables(&vars);
430 if !extra_args.is_empty() {
431 command.args(extra_args);
432 }
433
434 tracing::debug!(?command, ?file_to_fix.repo_path, "spawning fix tool");
435 let Ok(mut child) = command
436 .current_dir(workspace_root)
437 .stdin(Stdio::piped())
438 .stdout(Stdio::piped())
439 .stderr(Stdio::piped())
440 .spawn()
441 else {
442 writeln!(
443 ui.warning_default(),
444 "Failed to start `{}`.",
445 tool_command.split_name(),
446 )
447 .ok();
448 return Err(());
449 };
450 let mut stdin = child.stdin.take().expect(
451 "The child process is created with piped stdin, and it's our first access to stdin.",
452 );
453 let output = std::thread::scope(|s| {
454 s.spawn(move || {
455 stdin.write_all(old_content).ok();
456 });
457 child.wait_with_output().or(Err(()))
458 })?;
459 tracing::debug!(?command, ?output.status, "fix tool exited:");
460 if !output.stderr.is_empty() {
461 let mut stderr = ui.stderr();
462 writeln!(
463 stderr,
464 "{}:",
465 path_converter.format_file_path(&file_to_fix.repo_path)
466 )
467 .ok();
468 stderr.write_all(&output.stderr).ok();
469 writeln!(stderr).ok();
470 }
471 if output.status.success() {
472 Ok(output.stdout)
473 } else {
474 writeln!(
475 ui.warning_default(),
476 "Fix tool `{}` exited with non-zero exit code for `{}`",
477 tool_command.split_name(),
478 path_converter.format_file_path(&file_to_fix.repo_path)
479 )
480 .ok();
481 Err(())
482 }
483 }
484
485 /// Represents an entry in the `fix.tools` config table.
486 struct ToolConfig {
487 /// The command that will be run to fix a matching file.
488 command: CommandNameAndArgs,
489 /// The matcher that determines if this tool matches a file.
490 matcher: Box<dyn Matcher>,
491 /// Whether the tool is enabled
492 enabled: bool,
493 /// Arguments to pass changed line ranges to the tool.
494 /// The string is a template where `$first` and `$last` are replaced by the
495 /// 1-based first and last inclusive line numbers of the changed range.
496 /// For example, `"--lines=$first-$last"`.
497 line_range_arg: Option<String>,
498 /// Whether to run the tool invocation for this tool on files that had
499 /// zero line ranges to format in the revision being fixed.
500 ///
501 /// Defaults to `false`, meaning the tool is skipped for these files.
502 /// This default behavior serves two main purposes:
503 /// - Avoiding unnecessary executions of tools when no line ranges are
504 /// modified.
505 /// - Preventing tools configured with `line-range-arg` from making overly
506 /// broad changes (formatting the whole file) when no line ranges are
507 /// available.
508 ///
509 /// Setting this to `true` is useful if the tool should run regardless of
510 /// diffs (e.g., to sort imports, or run with
511 /// `--include-unchanged-files`).
512 run_tool_if_zero_line_ranges: bool,
513 // TODO: Store the `name` field here and print it with the command's stderr, to clearly
514 // associate any errors/warnings with the tool and its configuration entry.
515 }
516
517 /// Represents the `fix.tools` config table.
518 struct ToolsConfig {
519 /// Some tools, stored in the order they will be executed if more than one
520 /// of them matches the same file.
521 tools: Vec<ToolConfig>,
522 }
523
524 /// Simplifies deserialization of the config values while building a ToolConfig.
525 #[derive(Clone, Debug, Eq, PartialEq, serde::Deserialize)]
526 #[serde(rename_all = "kebab-case")]
527 struct RawToolConfig {
528 command: CommandNameAndArgs,
529 patterns: Vec<String>,
530 #[serde(default = "default_tool_enabled")]
531 enabled: bool,
532 #[serde(default)]
533 line_range_arg: Option<String>,
534 #[serde(default)]
535 run_tool_if_zero_line_ranges: bool,
536 }
537
538 fn default_tool_enabled() -> bool {
539 true
540 }
541
542 /// Parses the `fix.tools` config table.
543 ///
544 /// Fails if any of the commands or patterns are obviously unusable, but does
545 /// not check for issues that might still occur later like missing executables.
546 /// This is a place where we could fail earlier in some cases, though.
547 fn get_tools_config(
548 ui: &mut Ui,
549 settings: &UserSettings,
550 fileset_context: &FilesetParseContext,
551 ) -> Result<ToolsConfig, CommandError> {
552 let mut tools: Vec<ToolConfig> = settings
553 .table_keys("fix.tools")
554 // Sort keys early so errors are deterministic.
555 .sorted()
556 .map(|name| -> Result<ToolConfig, CommandError> {
557 let mut diagnostics = FilesetDiagnostics::new();
558 let tool: RawToolConfig = settings.get(["fix", "tools", name])?;
559 let expression = FilesetExpression::union_all(
560 tool.patterns
561 .iter()
562 .map(|arg| fileset::parse(&mut diagnostics, arg, fileset_context))
563 .try_collect()?,
564 );
565 if tool.line_range_arg.is_none() && tool.run_tool_if_zero_line_ranges {
566 return Err(config_error(
567 "run-tool-if-zero-line-ranges can only be set when line-range-arg is set",
568 ));
569 }
570 print_parse_diagnostics(ui, &format!("In `fix.tools.{name}`"), &diagnostics)?;
571 Ok(ToolConfig {
572 command: tool.command,
573 matcher: expression.to_matcher(),
574 enabled: tool.enabled,
575 line_range_arg: tool.line_range_arg,
576 run_tool_if_zero_line_ranges: tool.run_tool_if_zero_line_ranges,
577 })
578 })
579 .try_collect()?;
580 if tools.is_empty() {
581 return Err(config_error("No `fix.tools` are configured"));
582 }
583 tools.retain(|t| t.enabled);
584 if tools.is_empty() {
585 Err(config_error(
586 "At least one entry of `fix.tools` must be enabled.".to_string(),
587 ))
588 } else {
589 Ok(ToolsConfig { tools })
590 }
591 }
592
593 #[cfg(test)]
594 mod tests {
595 use super::*;
596
597 fn line_range(first: usize, last: usize) -> LineRange {
598 LineRange::new(first, last)
599 }
600
601 #[test]
602 fn test_compute_regions_to_format_default() {
603 // Base content None.
604 assert_eq!(
605 compute_regions_to_format(None, b"a\nb\nc\n"),
606 RegionsToFormat::LineRanges(vec![line_range(1, 3)])
607 );
608
609 // Empty base content.
610 assert_eq!(
611 compute_regions_to_format(Some(b""), b"a\nb\nc\n"),
612 RegionsToFormat::LineRanges(vec![line_range(1, 3)])
613 );
614
615 // Modified base content.
616 assert_eq!(
617 compute_regions_to_format(Some(b"a\nB\nc\n"), b"a\nb\nc\n"),
618 RegionsToFormat::LineRanges(vec![line_range(2, 2)])
619 );
620
621 // Deleted base content.
622 assert_eq!(
623 compute_regions_to_format(Some(b"a\nb\nc\nd\n"), b"a\nb\nc\n"),
624 RegionsToFormat::LineRanges(vec![])
625 );
626
627 // Multiple line ranges.
628 assert_eq!(
629 compute_regions_to_format(Some(b"A\nb\nC\n"), b"a\nb\nc\n"),
630 RegionsToFormat::LineRanges(vec![line_range(1, 1), line_range(3, 3)])
631 );
632
633 // Deleted current content.
634 assert_eq!(
635 compute_regions_to_format(Some(b"a\nb\nc\n"), b""),
636 RegionsToFormat::LineRanges(vec![])
637 );
638 }
639 }