Debian Codegraph @

cli/src/merge_tools/diff_working_copies.rs

raw
1 use std::collections::HashMap;
2 use std::fs::File;
3 use std::io;
4 use std::io::Write as _;
5 use std::path::Path;
6 use std::path::PathBuf;
7 use std::sync::Arc;
8
9 use futures::StreamExt as _;
10 use jj_lib::conflicts::ConflictMarkerStyle;
11 use jj_lib::fsmonitor::FsmonitorSettings;
12 use jj_lib::gitignore::GitIgnoreFile;
13 use jj_lib::local_working_copy::EolConversionMode;
14 use jj_lib::local_working_copy::ExecChangeSetting;
15 use jj_lib::local_working_copy::TreeState;
16 use jj_lib::local_working_copy::TreeStateError;
17 use jj_lib::local_working_copy::TreeStateSettings;
18 use jj_lib::matchers::EverythingMatcher;
19 use jj_lib::matchers::Matcher;
20 use jj_lib::matchers::NothingMatcher;
21 use jj_lib::merge::Diff;
22 use jj_lib::merged_tree::MergedTree;
23 use jj_lib::merged_tree::TreeDiffEntry;
24 use jj_lib::repo_path::RepoPath;
25 use jj_lib::repo_path::RepoPathBuf;
26 use jj_lib::working_copy::CheckoutError;
27 use jj_lib::working_copy::SnapshotOptions;
28 use tempfile::TempDir;
29 use thiserror::Error;
30
31 use super::DiffEditError;
32 use super::external::ExternalToolError;
33
34 #[derive(Debug, Error)]
35 pub enum DiffCheckoutError {
36 #[error("Failed to write directories to diff")]
37 Checkout(#[from] CheckoutError),
38 #[error("Error setting up temporary directory")]
39 SetUpDir(#[source] std::io::Error),
40 #[error(transparent)]
41 TreeState(#[from] TreeStateError),
42 }
43
44 pub(crate) struct DiffWorkingCopies {
45 temp_dir: TempDir, // Temp dir will be deleted when this is dropped
46 left: TreeState,
47 right: TreeState,
48 output: Option<TreeState>,
49 }
50
51 impl DiffWorkingCopies {
52 pub fn set_left_readonly(&self) -> Result<(), ExternalToolError> {
53 set_readonly_recursively(self.left.working_copy_path()).map_err(ExternalToolError::SetUpDir)
54 }
55
56 pub fn set_right_readonly(&self) -> Result<(), ExternalToolError> {
57 set_readonly_recursively(self.right.working_copy_path())
58 .map_err(ExternalToolError::SetUpDir)
59 }
60
61 pub fn temp_dir(&self) -> &Path {
62 self.temp_dir.path()
63 }
64
65 /// The paths of the files that were checked out to disk.
66 pub fn checked_out_files(&self) -> &[RepoPathBuf] {
67 debug_assert_eq!(self.left.sparse_patterns(), self.right.sparse_patterns());
68 if let Some(output) = &self.output {
69 debug_assert_eq!(self.left.sparse_patterns(), output.sparse_patterns());
70 }
71 self.left.sparse_patterns()
72 }
73
74 /// Returns command variables (`$left`, `$right`, and optionally `$output`)
75 /// for a single checked-out file at `repo_path`. The paths are absolute
76 /// unless `relative` is set, in which case they're relative to
77 /// [`Self::temp_dir`].
78 pub fn to_command_variables_for_file(
79 &self,
80 repo_path: &RepoPath,
81 relative: bool,
82 ) -> HashMap<&'static str, String> {
83 let fs_path = |base: &Path, relative: bool| {
84 let base = if relative {
85 base.strip_prefix(self.temp_dir())
86 .expect("path should be relative to temp_dir")
87 } else {
88 base
89 };
90 repo_path
91 .to_fs_path(base)
92 .expect("path should have been checked out to disk")
93 .into_os_string()
94 .into_string()
95 .expect("temp_dir should be valid utf-8")
96 };
97 let mut result = maplit::hashmap! {
98 "left" => fs_path(self.left.working_copy_path(), relative),
99 "right" => fs_path(self.right.working_copy_path(), relative),
100 };
101 if let Some(output_state) = &self.output {
102 result.insert(
103 "output",
104 fs_path(output_state.working_copy_path(), relative),
105 );
106 }
107 result
108 }
109
110 pub fn to_command_variables(&self, relative: bool) -> HashMap<&'static str, String> {
111 self.to_command_variables_for_file(RepoPath::root(), relative)
112 }
113 }
114
115 pub(crate) fn new_utf8_temp_dir(prefix: &str) -> io::Result<TempDir> {
116 let temp_dir = tempfile::Builder::new().prefix(prefix).tempdir()?;
117 if temp_dir.path().to_str().is_none() {
118 // Not using .display() as we know the path contains unprintable character
119 let message = format!("path {:?} is not valid UTF-8", temp_dir.path());
120 return Err(io::Error::new(io::ErrorKind::InvalidData, message));
121 }
122 Ok(temp_dir)
123 }
124
125 pub(crate) fn set_readonly_recursively(path: &Path) -> Result<(), std::io::Error> {
126 // Directory permission is unchanged since files under readonly directory cannot
127 // be removed.
128 let metadata = path.symlink_metadata()?;
129 if metadata.is_dir() {
130 for entry in path.read_dir()? {
131 set_readonly_recursively(&entry?.path())?;
132 }
133 Ok(())
134 } else if metadata.is_file() {
135 let mut perms = metadata.permissions();
136 perms.set_readonly(true);
137 std::fs::set_permissions(path, perms)
138 } else {
139 Ok(())
140 }
141 }
142
143 /// How to prepare tree states from the working copy for a diff viewer/editor.
144 #[derive(Debug, Clone, Copy, PartialEq, Eq)]
145 pub(crate) enum DiffType {
146 /// Prepare a left and right tree.
147 TwoWay,
148 /// Prepare left, right, and output trees.
149 ThreeWay,
150 }
151
152 /// Check out the two trees in temporary directories. Only include changed files
153 /// in the sparse checkout patterns.
154 pub(crate) async fn check_out_trees(
155 trees: Diff<&MergedTree>,
156 matcher: &dyn Matcher,
157 diff_type: DiffType,
158 conflict_marker_style: ConflictMarkerStyle,
159 ) -> Result<DiffWorkingCopies, DiffCheckoutError> {
160 let store = trees.before.store();
161 let changed_files: Vec<_> = trees
162 .before
163 .diff_stream(trees.after, matcher)
164 .map(|TreeDiffEntry { path, .. }| path)
165 .collect()
166 .await;
167
168 let temp_dir = new_utf8_temp_dir("jj-diff-").map_err(DiffCheckoutError::SetUpDir)?;
169 let temp_path = temp_dir.path();
170
171 // Checkout a tree into our temp directory with the given prefix.
172 let check_out = |name: &str, tree| -> Result<TreeState, DiffCheckoutError> {
173 let wc_path = temp_path.join(name);
174 let state_dir = temp_path.join(format!("{name}_state"));
175 std::fs::create_dir(&wc_path).map_err(DiffCheckoutError::SetUpDir)?;
176 std::fs::create_dir(&state_dir).map_err(DiffCheckoutError::SetUpDir)?;
177 let tree_state_settings = TreeStateSettings {
178 conflict_marker_style,
179 eol_conversion_mode: EolConversionMode::None,
180 exec_change_setting: ExecChangeSetting::Auto,
181 fsmonitor_settings: FsmonitorSettings::None,
182 };
183 let mut state = TreeState::init(store.clone(), wc_path, state_dir, &tree_state_settings)?;
184 state.set_sparse_patterns(changed_files.clone())?;
185 state.check_out(tree)?;
186 Ok(state)
187 };
188
189 let left = check_out("left", trees.before)?;
190 let right = check_out("right", trees.after)?;
191 let output = match diff_type {
192 DiffType::TwoWay => None,
193 DiffType::ThreeWay => Some(check_out("output", trees.after)?),
194 };
195 Ok(DiffWorkingCopies {
196 temp_dir,
197 left,
198 right,
199 output,
200 })
201 }
202
203 pub(crate) struct DiffEditWorkingCopies {
204 pub working_copies: DiffWorkingCopies,
205 instructions_path_to_cleanup: Option<PathBuf>,
206 }
207
208 impl DiffEditWorkingCopies {
209 /// Checks out the trees, populates JJ_INSTRUCTIONS, and makes appropriate
210 /// sides readonly.
211 pub async fn check_out(
212 trees: Diff<&MergedTree>,
213 matcher: &dyn Matcher,
214 diff_type: DiffType,
215 instructions: Option<&str>,
216 conflict_marker_style: ConflictMarkerStyle,
217 ) -> Result<Self, DiffEditError> {
218 let working_copies =
219 check_out_trees(trees, matcher, diff_type, conflict_marker_style).await?;
220 working_copies.set_left_readonly()?;
221 if diff_type == DiffType::ThreeWay {
222 working_copies.set_right_readonly()?;
223 }
224 let instructions_path_to_cleanup =
225 Self::write_edit_instructions(&working_copies, instructions)?;
226 Ok(Self {
227 working_copies,
228 instructions_path_to_cleanup,
229 })
230 }
231
232 fn write_edit_instructions(
233 working_copies: &DiffWorkingCopies,
234 instructions: Option<&str>,
235 ) -> Result<Option<PathBuf>, DiffEditError> {
236 let Some(instructions) = instructions else {
237 return Ok(None);
238 };
239 let (right_wc_path, output_wc_path) = match &working_copies.output {
240 Some(output) => (
241 Some(working_copies.right.working_copy_path()),
242 output.working_copy_path(),
243 ),
244 None => (None, working_copies.right.working_copy_path()),
245 };
246 let output_instructions_path = output_wc_path.join("JJ-INSTRUCTIONS");
247 // In the unlikely event that the file already exists, then the user will simply
248 // not get any instructions.
249 if output_instructions_path.exists() {
250 return Ok(None);
251 }
252 let mut output_instructions_file =
253 File::create(&output_instructions_path).map_err(ExternalToolError::SetUpDir)?;
254
255 // Write out our experimental three-way merge instructions first.
256 if let Some(right_wc_path) = right_wc_path {
257 let mut right_instructions_file = File::create(right_wc_path.join("JJ-INSTRUCTIONS"))
258 .map_err(ExternalToolError::SetUpDir)?;
259 right_instructions_file
260 .write_all(
261 b"\
262 The content of this pane should NOT be edited. Any edits will be
263 lost.
264
265 You are using the experimental 3-pane diff editor config. Some of
266 the following instructions may have been written with a 2-pane
267 diff editing in mind and be a little inaccurate.
268
269 ",
270 )
271 .map_err(ExternalToolError::SetUpDir)?;
272 right_instructions_file
273 .write_all(instructions.as_bytes())
274 .map_err(ExternalToolError::SetUpDir)?;
275 // Note that some diff tools might not show this message and delete the contents
276 // of the output dir instead. Meld does show this message.
277 output_instructions_file
278 .write_all(
279 b"\
280 Please make your edits in this pane.
281
282 You are using the experimental 3-pane diff editor config. Some of
283 the following instructions may have been written with a 2-pane
284 diff editing in mind and be a little inaccurate.
285
286 ",
287 )
288 .map_err(ExternalToolError::SetUpDir)?;
289 }
290 // Now write the passed-in instructions.
291 output_instructions_file
292 .write_all(instructions.as_bytes())
293 .map_err(ExternalToolError::SetUpDir)?;
294 Ok(Some(output_instructions_path))
295 }
296
297 pub async fn snapshot_results(
298 self,
299 base_ignores: Arc<GitIgnoreFile>,
300 ) -> Result<MergedTree, DiffEditError> {
301 if let Some(path) = self.instructions_path_to_cleanup {
302 std::fs::remove_file(path).ok();
303 }
304
305 let diff_wc = self.working_copies;
306 // Snapshot changes in the temporary output directory.
307 let mut output_tree_state = diff_wc.output.unwrap_or(diff_wc.right);
308 output_tree_state
309 .snapshot(&SnapshotOptions {
310 base_ignores,
311 progress: None,
312 start_tracking_matcher: &EverythingMatcher,
313 force_tracking_matcher: &NothingMatcher,
314 max_new_file_size: u64::MAX,
315 })
316 .await?;
317 Ok(output_tree_state.current_tree().clone())
318 }
319 }