jj_lib/fix.rs
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//! API for transforming file content, for example to apply formatting, and
16//! propagate those changes across revisions.
17
18use std::collections::HashMap;
19use std::collections::HashSet;
20use std::sync::mpsc::channel;
21
22use futures::StreamExt as _;
23use futures::TryStreamExt as _;
24use jj_lib::backend::BackendError;
25use jj_lib::backend::CommitId;
26use jj_lib::backend::FileId;
27use jj_lib::backend::TreeValue;
28use jj_lib::matchers::Matcher;
29use jj_lib::merged_tree::TreeDiffEntry;
30use jj_lib::merged_tree_builder::MergedTreeBuilder;
31use jj_lib::repo::MutableRepo;
32use jj_lib::repo::Repo as _;
33use jj_lib::repo_path::RepoPathBuf;
34use jj_lib::revset::RevsetExpression;
35use jj_lib::store::Store;
36use rayon::iter::IntoParallelIterator as _;
37use rayon::prelude::ParallelIterator as _;
38
39use crate::revset::RevsetEvaluationError;
40use crate::revset::RevsetStreamExt as _;
41
42/// Represents a file whose content may be transformed by a FileFixer.
43// TODO: Add the set of changed line/byte ranges, so those can be passed into code formatters via
44// flags. This will help avoid introducing unrelated changes when working on code with out of date
45// formatting.
46#[derive(Debug, PartialEq, Eq, Hash, Clone)]
47pub struct FileToFix {
48 /// Unique identifier for the file content.
49 pub file_id: FileId,
50
51 /// The path is provided to allow the FileFixer to potentially:
52 /// - Choose different behaviors for different file names, extensions, etc.
53 /// - Update parts of the file's content that should be derived from the
54 /// file's path.
55 pub repo_path: RepoPathBuf,
56}
57
58/// Error fixing files.
59#[derive(Debug, thiserror::Error)]
60pub enum FixError {
61 /// Error while contacting the Backend.
62 #[error(transparent)]
63 Backend(#[from] BackendError),
64 /// Error resolving commit ancestry.
65 #[error(transparent)]
66 RevsetEvaluation(#[from] RevsetEvaluationError),
67 /// Error occurred while reading/writing file content.
68 #[error(transparent)]
69 Io(#[from] std::io::Error),
70 /// Error occurred while processing the file content.
71 #[error(transparent)]
72 FixContent(Box<dyn std::error::Error + Send + Sync>),
73}
74
75/// Fixes a set of files.
76///
77/// Fixing a file is implementation dependent. For example it may format source
78/// code using a code formatter.
79pub trait FileFixer {
80 /// Fixes a set of files. Stores the resulting file content (for modified
81 /// files).
82 ///
83 /// Returns a map describing the subset of `files_to_fix` that resulted in
84 /// changed file content (unchanged files should not be present in the map),
85 /// pointing to the new FileId for the file.
86 ///
87 /// TODO: Better error handling so we can tell the user what went wrong with
88 /// each failed input.
89 fn fix_files<'a>(
90 &mut self,
91 store: &Store,
92 files_to_fix: &'a HashSet<FileToFix>,
93 ) -> Result<HashMap<&'a FileToFix, FileId>, FixError>;
94}
95
96/// Aggregate information about the outcome of the file fixer.
97#[derive(Debug, Default)]
98pub struct FixSummary {
99 /// The commits that were rewritten. Maps old commit id to new commit id.
100 pub rewrites: HashMap<CommitId, CommitId>,
101
102 /// The number of commits that had files that were passed to the file fixer.
103 pub num_checked_commits: i32,
104 /// The number of new commits created due to file content changed by the
105 /// fixer.
106 pub num_fixed_commits: i32,
107}
108
109/// A [FileFixer] that applies fix_fn to each file, in parallel.
110///
111/// The implementation is currently based on [rayon].
112// TODO: Consider switching to futures, or document the decision not to. We
113// don't need threads unless the threads will be doing more than waiting for
114// pipes.
115pub struct ParallelFileFixer<T> {
116 fix_fn: T,
117}
118
119impl<T> ParallelFileFixer<T>
120where
121 T: Fn(&Store, &FileToFix) -> Result<Option<FileId>, FixError> + Sync + Send,
122{
123 /// Creates a ParallelFileFixer.
124 pub fn new(fix_fn: T) -> Self {
125 Self { fix_fn }
126 }
127}
128
129impl<T> FileFixer for ParallelFileFixer<T>
130where
131 T: Fn(&Store, &FileToFix) -> Result<Option<FileId>, FixError> + Sync + Send,
132{
133 /// Applies `fix_fn()` to the inputs and stores the resulting file content.
134 fn fix_files<'a>(
135 &mut self,
136 store: &Store,
137 files_to_fix: &'a HashSet<FileToFix>,
138 ) -> Result<HashMap<&'a FileToFix, FileId>, FixError> {
139 let (updates_tx, updates_rx) = channel();
140 files_to_fix.into_par_iter().try_for_each_init(
141 || updates_tx.clone(),
142 |updates_tx, file_to_fix| -> Result<(), FixError> {
143 let result = (self.fix_fn)(store, file_to_fix)?;
144 match result {
145 Some(new_file_id) => {
146 updates_tx.send((file_to_fix, new_file_id)).unwrap();
147 Ok(())
148 }
149 None => Ok(()),
150 }
151 },
152 )?;
153 drop(updates_tx);
154 let mut result = HashMap::new();
155 while let Ok((file_to_fix, new_file_id)) = updates_rx.recv() {
156 result.insert(file_to_fix, new_file_id);
157 }
158 Ok(result)
159 }
160}
161
162/// Updates files with formatting fixes or other changes, using the given
163/// FileFixer.
164///
165/// The primary use case is to apply the results of automatic code formatting
166/// tools to revisions that may not be properly formatted yet. It can also be
167/// used to modify files with other tools like `sed` or `sort`.
168///
169/// After the FileFixer is done, descendants are also updated, which ensures
170/// that the fixes are not lost. This will never result in new conflicts. Files
171/// with existing conflicts are updated on all sides of the conflict, which
172/// can potentially increase or decrease the number of conflict markers.
173pub async fn fix_files(
174 root_commits: Vec<CommitId>,
175 matcher: &dyn Matcher,
176 include_unchanged_files: bool,
177 repo_mut: &mut MutableRepo,
178 file_fixer: &mut impl FileFixer,
179) -> Result<FixSummary, FixError> {
180 let mut summary = FixSummary::default();
181
182 // Collect all of the unique `FileToFix`s we're going to use. file_fixer should
183 // be deterministic, and should not consider outside information, so it is
184 // safe to deduplicate inputs that correspond to multiple files or commits.
185 // This is typically more efficient, but it does prevent certain use cases
186 // like providing commit IDs as inputs to be inserted into files. We also
187 // need to record the mapping between files-to-fix and paths/commits, to
188 // efficiently rewrite the commits later.
189 //
190 // If a path is being fixed in a particular commit, it must also be fixed in all
191 // that commit's descendants. We do this as a way of propagating changes,
192 // under the assumption that it is more useful than performing a rebase and
193 // risking merge conflicts. In the case of code formatters, rebasing wouldn't
194 // reliably produce well formatted code anyway. Deduplicating inputs helps
195 // to prevent quadratic growth in the number of tool executions required for
196 // doing this in long chains of commits with disjoint sets of modified files.
197 let commits: Vec<_> = RevsetExpression::commits(root_commits.clone())
198 .descendants()
199 .evaluate(repo_mut)?
200 .stream()
201 .commits(repo_mut.store())
202 .try_collect()
203 .await?;
204 tracing::debug!(
205 ?root_commits,
206 ?commits,
207 "looking for files to fix in commits:"
208 );
209
210 let mut unique_files_to_fix: HashSet<FileToFix> = HashSet::new();
211 let mut commit_paths: HashMap<CommitId, HashSet<RepoPathBuf>> = HashMap::new();
212 for commit in commits.iter().rev() {
213 let mut paths: HashSet<RepoPathBuf> = HashSet::new();
214
215 // If --include-unchanged-files, we always fix every matching file in the tree.
216 // Otherwise, we fix the matching changed files in this commit, plus any that
217 // were fixed in ancestors, so we don't lose those changes. We do this
218 // instead of rebasing onto those changes, to avoid merge conflicts.
219 let parent_tree = if include_unchanged_files {
220 repo_mut.store().empty_merged_tree()
221 } else {
222 for parent_id in commit.parent_ids() {
223 if let Some(parent_paths) = commit_paths.get(parent_id) {
224 paths.extend(parent_paths.iter().cloned());
225 }
226 }
227 commit.parent_tree(repo_mut).await?
228 };
229 // TODO: handle copy tracking
230 let mut diff_stream = parent_tree.diff_stream(&commit.tree(), &matcher);
231 while let Some(TreeDiffEntry {
232 path: repo_path,
233 values,
234 }) = diff_stream.next().await
235 {
236 let after = values?.after;
237 // Deleted files have no file content to fix, and they have no terms in `after`,
238 // so we don't add any files-to-fix for them. Conflicted files produce one
239 // file-to-fix for each side of the conflict.
240 for term in after.into_iter().flatten() {
241 // We currently only support fixing the content of normal files, so we skip
242 // directories and symlinks, and we ignore the executable bit.
243 if let TreeValue::File {
244 id,
245 executable: _,
246 copy_id: _,
247 } = term
248 {
249 // TODO: Skip the file if its content is larger than some configured size,
250 // preferably without actually reading it yet.
251 let file_to_fix = FileToFix {
252 file_id: id.clone(),
253 repo_path: repo_path.clone(),
254 };
255 unique_files_to_fix.insert(file_to_fix.clone());
256 paths.insert(repo_path.clone());
257 }
258 }
259 }
260
261 commit_paths.insert(commit.id().clone(), paths);
262 }
263
264 tracing::debug!(
265 ?include_unchanged_files,
266 ?unique_files_to_fix,
267 "invoking file fixer on these files:"
268 );
269
270 // Fix all of the chosen inputs.
271 let fixed_file_ids = file_fixer.fix_files(repo_mut.store().as_ref(), &unique_files_to_fix)?;
272 tracing::debug!(?fixed_file_ids, "file fixer fixed these files:");
273
274 // Substitute the fixed file IDs into all of the affected commits. Currently,
275 // fixes cannot delete or rename files, change the executable bit, or modify
276 // other parts of the commit like the description.
277 repo_mut
278 .transform_descendants(root_commits, async |rewriter| {
279 // TODO: Build the trees in parallel before `transform_descendants()` and only
280 // keep the tree IDs in memory, so we can pass them to the rewriter.
281 let old_commit_id = rewriter.old_commit().id().clone();
282 let repo_paths = commit_paths.get(&old_commit_id).unwrap();
283 let old_tree = rewriter.old_commit().tree();
284 let mut tree_builder = MergedTreeBuilder::new(old_tree.clone());
285 let mut has_changes = false;
286 for repo_path in repo_paths {
287 let old_value = old_tree.path_value(repo_path).await?;
288 let new_value = old_value.map(|old_term| {
289 if let Some(TreeValue::File {
290 id,
291 executable,
292 copy_id,
293 }) = old_term
294 {
295 let file_to_fix = FileToFix {
296 file_id: id.clone(),
297 repo_path: repo_path.clone(),
298 };
299 if let Some(new_id) = fixed_file_ids.get(&file_to_fix) {
300 return Some(TreeValue::File {
301 id: new_id.clone(),
302 executable: *executable,
303 copy_id: copy_id.clone(),
304 });
305 }
306 }
307 old_term.clone()
308 });
309 if new_value != old_value {
310 tree_builder.set_or_remove(repo_path.clone(), new_value);
311 has_changes = true;
312 }
313 }
314 summary.num_checked_commits += 1;
315 if has_changes {
316 summary.num_fixed_commits += 1;
317 let new_tree = tree_builder.write_tree().await?;
318 let builder = rewriter.reparent();
319 let new_commit = builder.set_tree(new_tree).write().await?;
320 summary
321 .rewrites
322 .insert(old_commit_id, new_commit.id().clone());
323 } else if rewriter.parents_changed() {
324 let new_commit = rewriter.reparent().write().await?;
325 summary
326 .rewrites
327 .insert(old_commit_id, new_commit.id().clone());
328 }
329 Ok(())
330 })
331 .await?;
332
333 tracing::debug!(?summary);
334 Ok(summary)
335}