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 itertools::Itertools 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::MergedTreeBuilder;
30use jj_lib::merged_tree::TreeDiffEntry;
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::revset::RevsetIteratorExt as _;
36use jj_lib::store::Store;
37use rayon::iter::IntoParallelIterator as _;
38use rayon::prelude::ParallelIterator as _;
39
40use crate::revset::RevsetEvaluationError;
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        .iter()
201        .commits(repo_mut.store())
202        .try_collect()?;
203    tracing::debug!(
204        ?root_commits,
205        ?commits,
206        "looking for files to fix in commits:"
207    );
208
209    let mut unique_files_to_fix: HashSet<FileToFix> = HashSet::new();
210    let mut commit_paths: HashMap<CommitId, HashSet<RepoPathBuf>> = HashMap::new();
211    for commit in commits.iter().rev() {
212        let mut paths: HashSet<RepoPathBuf> = HashSet::new();
213
214        // If --include-unchanged-files, we always fix every matching file in the tree.
215        // Otherwise, we fix the matching changed files in this commit, plus any that
216        // were fixed in ancestors, so we don't lose those changes. We do this
217        // instead of rebasing onto those changes, to avoid merge conflicts.
218        let parent_tree = if include_unchanged_files {
219            repo_mut.store().empty_merged_tree()
220        } else {
221            for parent_id in commit.parent_ids() {
222                if let Some(parent_paths) = commit_paths.get(parent_id) {
223                    paths.extend(parent_paths.iter().cloned());
224                }
225            }
226            commit.parent_tree_async(repo_mut).await?
227        };
228        // TODO: handle copy tracking
229        let mut diff_stream = parent_tree.diff_stream(&commit.tree(), &matcher);
230        while let Some(TreeDiffEntry {
231            path: repo_path,
232            values,
233        }) = diff_stream.next().await
234        {
235            let after = values?.after;
236            // Deleted files have no file content to fix, and they have no terms in `after`,
237            // so we don't add any files-to-fix for them. Conflicted files produce one
238            // file-to-fix for each side of the conflict.
239            for term in after.into_iter().flatten() {
240                // We currently only support fixing the content of normal files, so we skip
241                // directories and symlinks, and we ignore the executable bit.
242                if let TreeValue::File {
243                    id,
244                    executable: _,
245                    copy_id: _,
246                } = term
247                {
248                    // TODO: Skip the file if its content is larger than some configured size,
249                    // preferably without actually reading it yet.
250                    let file_to_fix = FileToFix {
251                        file_id: id.clone(),
252                        repo_path: repo_path.clone(),
253                    };
254                    unique_files_to_fix.insert(file_to_fix.clone());
255                    paths.insert(repo_path.clone());
256                }
257            }
258        }
259
260        commit_paths.insert(commit.id().clone(), paths);
261    }
262
263    tracing::debug!(
264        ?include_unchanged_files,
265        ?unique_files_to_fix,
266        "invoking file fixer on these files:"
267    );
268
269    // Fix all of the chosen inputs.
270    let fixed_file_ids = file_fixer.fix_files(repo_mut.store().as_ref(), &unique_files_to_fix)?;
271    tracing::debug!(?fixed_file_ids, "file fixer fixed these files:");
272
273    // Substitute the fixed file IDs into all of the affected commits. Currently,
274    // fixes cannot delete or rename files, change the executable bit, or modify
275    // other parts of the commit like the description.
276    repo_mut.transform_descendants(root_commits, async |rewriter| {
277        // TODO: Build the trees in parallel before `transform_descendants()` and only
278        // keep the tree IDs in memory, so we can pass them to the rewriter.
279        let old_commit_id = rewriter.old_commit().id().clone();
280        let repo_paths = commit_paths.get(&old_commit_id).unwrap();
281        let old_tree = rewriter.old_commit().tree();
282        let mut tree_builder = MergedTreeBuilder::new(old_tree.clone());
283        let mut has_changes = false;
284        for repo_path in repo_paths {
285            let old_value = old_tree.path_value_async(repo_path).await?;
286            let new_value = old_value.map(|old_term| {
287                if let Some(TreeValue::File {
288                    id,
289                    executable,
290                    copy_id,
291                }) = old_term
292                {
293                    let file_to_fix = FileToFix {
294                        file_id: id.clone(),
295                        repo_path: repo_path.clone(),
296                    };
297                    if let Some(new_id) = fixed_file_ids.get(&file_to_fix) {
298                        return Some(TreeValue::File {
299                            id: new_id.clone(),
300                            executable: *executable,
301                            copy_id: copy_id.clone(),
302                        });
303                    }
304                }
305                old_term.clone()
306            });
307            if new_value != old_value {
308                tree_builder.set_or_remove(repo_path.clone(), new_value);
309                has_changes = true;
310            }
311        }
312        summary.num_checked_commits += 1;
313        if has_changes {
314            summary.num_fixed_commits += 1;
315            let new_tree = tree_builder.write_tree()?;
316            let builder = rewriter.reparent();
317            let new_commit = builder.set_tree(new_tree).write()?;
318            summary
319                .rewrites
320                .insert(old_commit_id, new_commit.id().clone());
321        } else if rewriter.parents_changed() {
322            let new_commit = rewriter.reparent().write()?;
323            summary
324                .rewrites
325                .insert(old_commit_id, new_commit.id().clone());
326        }
327        Ok(())
328    })?;
329
330    tracing::debug!(?summary);
331    Ok(summary)
332}