Debian Codegraph @

cli/examples/custom-working-copy/main.rs

raw
1 // Copyright 2023 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::path::Path;
16 use std::path::PathBuf;
17 use std::sync::Arc;
18
19 use async_trait::async_trait;
20 use itertools::Itertools as _;
21 use jj_cli::cli_util::CliRunner;
22 use jj_cli::cli_util::CommandHelper;
23 use jj_cli::command_error::CommandError;
24 use jj_cli::ui::Ui;
25 use jj_lib::backend::Backend;
26 use jj_lib::commit::Commit;
27 use jj_lib::git_backend::GitBackend;
28 use jj_lib::local_working_copy::LocalWorkingCopy;
29 use jj_lib::merged_tree::MergedTree;
30 use jj_lib::op_store::OperationId;
31 use jj_lib::ref_name::WorkspaceName;
32 use jj_lib::ref_name::WorkspaceNameBuf;
33 use jj_lib::repo::ReadonlyRepo;
34 use jj_lib::repo_path::RepoPath;
35 use jj_lib::repo_path::RepoPathBuf;
36 use jj_lib::settings::UserSettings;
37 use jj_lib::signing::Signer;
38 use jj_lib::store::Store;
39 use jj_lib::working_copy::CheckoutError;
40 use jj_lib::working_copy::CheckoutStats;
41 use jj_lib::working_copy::LockedWorkingCopy;
42 use jj_lib::working_copy::ResetError;
43 use jj_lib::working_copy::SnapshotError;
44 use jj_lib::working_copy::SnapshotOptions;
45 use jj_lib::working_copy::SnapshotStats;
46 use jj_lib::working_copy::WorkingCopy;
47 use jj_lib::working_copy::WorkingCopyFactory;
48 use jj_lib::working_copy::WorkingCopyStateError;
49 use jj_lib::workspace::WorkingCopyFactories;
50 use jj_lib::workspace::Workspace;
51 use jj_lib::workspace::WorkspaceInitError;
52
53 #[derive(clap::Parser, Clone, Debug)]
54 enum CustomCommand {
55 /// Initialize a workspace using the "conflicts" working copy
56 InitConflicts,
57 }
58
59 async fn run_custom_command(
60 ui: &mut Ui,
61 command_helper: &CommandHelper,
62 command: CustomCommand,
63 ) -> Result<(), CommandError> {
64 match command {
65 CustomCommand::InitConflicts => {
66 let wc_path = command_helper.cwd();
67 let settings = command_helper.settings_for_new_workspace(ui, wc_path)?.0;
68 let backend_initializer = |settings: &UserSettings, store_path: &Path| {
69 let backend: Box<dyn Backend> = Box::new(GitBackend::init_internal(
70 settings,
71 store_path,
72 gix::hash::Kind::default(),
73 )?);
74 Ok(backend)
75 };
76 Workspace::init_with_factories(
77 &settings,
78 wc_path,
79 &backend_initializer,
80 Signer::from_settings(&settings).map_err(WorkspaceInitError::SignInit)?,
81 &ReadonlyRepo::default_op_store_initializer(),
82 &ReadonlyRepo::default_op_heads_store_initializer(),
83 &ReadonlyRepo::default_index_store_initializer(),
84 &ReadonlyRepo::default_submodule_store_initializer(),
85 &ConflictsWorkingCopyFactory {},
86 WorkspaceName::DEFAULT.to_owned(),
87 )
88 .await?;
89 Ok(())
90 }
91 }
92 }
93
94 fn main() -> std::process::ExitCode {
95 let mut working_copy_factories = WorkingCopyFactories::new();
96 working_copy_factories.insert(
97 ConflictsWorkingCopy::name().to_owned(),
98 Box::new(ConflictsWorkingCopyFactory {}),
99 );
100 CliRunner::init()
101 .add_working_copy_factories(working_copy_factories)
102 .add_subcommand(run_custom_command)
103 .run()
104 .into()
105 }
106
107 /// A working copy that adds a .conflicts file with a list of unresolved
108 /// conflicts.
109 ///
110 /// Most functions below just delegate to the inner working-copy backend. The
111 /// only interesting functions are `snapshot()` and `check_out()`. The former
112 /// adds `.conflicts` to the .gitignores. The latter writes the `.conflicts`
113 /// file to the working copy.
114 struct ConflictsWorkingCopy {
115 inner: Box<dyn WorkingCopy>,
116 working_copy_path: PathBuf,
117 }
118
119 impl ConflictsWorkingCopy {
120 fn name() -> &'static str {
121 "conflicts"
122 }
123
124 fn init(
125 store: Arc<Store>,
126 working_copy_path: PathBuf,
127 state_path: PathBuf,
128 operation_id: OperationId,
129 workspace_name: WorkspaceNameBuf,
130 user_settings: &UserSettings,
131 ) -> Result<Self, WorkingCopyStateError> {
132 let inner = LocalWorkingCopy::init(
133 store,
134 working_copy_path.clone(),
135 state_path,
136 operation_id,
137 workspace_name,
138 user_settings,
139 )?;
140 Ok(Self {
141 inner: Box::new(inner),
142 working_copy_path,
143 })
144 }
145
146 fn load(
147 store: Arc<Store>,
148 working_copy_path: PathBuf,
149 state_path: PathBuf,
150 user_settings: &UserSettings,
151 ) -> Result<Self, WorkingCopyStateError> {
152 let inner =
153 LocalWorkingCopy::load(store, working_copy_path.clone(), state_path, user_settings)?;
154 Ok(Self {
155 inner: Box::new(inner),
156 working_copy_path,
157 })
158 }
159 }
160
161 #[async_trait(?Send)]
162 impl WorkingCopy for ConflictsWorkingCopy {
163 fn name(&self) -> &str {
164 Self::name()
165 }
166
167 fn workspace_name(&self) -> &WorkspaceName {
168 self.inner.workspace_name()
169 }
170
171 fn operation_id(&self) -> &OperationId {
172 self.inner.operation_id()
173 }
174
175 fn tree(&self) -> Result<&MergedTree, WorkingCopyStateError> {
176 self.inner.tree()
177 }
178
179 fn sparse_patterns(&self) -> Result<&[RepoPathBuf], WorkingCopyStateError> {
180 self.inner.sparse_patterns()
181 }
182
183 async fn start_mutation(&self) -> Result<Box<dyn LockedWorkingCopy>, WorkingCopyStateError> {
184 let inner = self.inner.start_mutation().await?;
185 Ok(Box::new(LockedConflictsWorkingCopy {
186 wc_path: self.working_copy_path.clone(),
187 inner,
188 }))
189 }
190 }
191
192 struct ConflictsWorkingCopyFactory {}
193
194 impl WorkingCopyFactory for ConflictsWorkingCopyFactory {
195 fn init_working_copy(
196 &self,
197 store: Arc<Store>,
198 working_copy_path: PathBuf,
199 state_path: PathBuf,
200 operation_id: OperationId,
201 workspace_name: WorkspaceNameBuf,
202 settings: &UserSettings,
203 ) -> Result<Box<dyn WorkingCopy>, WorkingCopyStateError> {
204 Ok(Box::new(ConflictsWorkingCopy::init(
205 store,
206 working_copy_path,
207 state_path,
208 operation_id,
209 workspace_name,
210 settings,
211 )?))
212 }
213
214 fn load_working_copy(
215 &self,
216 store: Arc<Store>,
217 working_copy_path: PathBuf,
218 state_path: PathBuf,
219 settings: &UserSettings,
220 ) -> Result<Box<dyn WorkingCopy>, WorkingCopyStateError> {
221 Ok(Box::new(ConflictsWorkingCopy::load(
222 store,
223 working_copy_path,
224 state_path,
225 settings,
226 )?))
227 }
228 }
229
230 struct LockedConflictsWorkingCopy {
231 wc_path: PathBuf,
232 inner: Box<dyn LockedWorkingCopy + Send>,
233 }
234
235 #[async_trait]
236 impl LockedWorkingCopy for LockedConflictsWorkingCopy {
237 fn old_operation_id(&self) -> &OperationId {
238 self.inner.old_operation_id()
239 }
240
241 fn old_tree(&self) -> &MergedTree {
242 self.inner.old_tree()
243 }
244
245 async fn snapshot(
246 &mut self,
247 options: &SnapshotOptions,
248 ) -> Result<(MergedTree, SnapshotStats), SnapshotError> {
249 let options = SnapshotOptions {
250 base_ignores: options.base_ignores.chain(
251 RepoPath::root(),
252 Path::new(""),
253 "/.conflicts".as_bytes(),
254 )?,
255 ..options.clone()
256 };
257 self.inner.snapshot(&options).await
258 }
259
260 async fn check_out(&mut self, commit: &Commit) -> Result<CheckoutStats, CheckoutError> {
261 let conflicts = commit
262 .tree()
263 .conflicts()
264 .map(|(path, _value)| format!("{}\n", path.as_internal_file_string()))
265 .join("");
266 std::fs::write(self.wc_path.join(".conflicts"), conflicts).unwrap();
267 self.inner.check_out(commit).await
268 }
269
270 fn rename_workspace(&mut self, new_name: WorkspaceNameBuf) {
271 self.inner.rename_workspace(new_name);
272 }
273
274 async fn reset(&mut self, commit: &Commit) -> Result<(), ResetError> {
275 self.inner.reset(commit).await
276 }
277
278 async fn recover(&mut self, commit: &Commit) -> Result<(), ResetError> {
279 self.inner.recover(commit).await
280 }
281
282 fn sparse_patterns(&self) -> Result<&[RepoPathBuf], WorkingCopyStateError> {
283 self.inner.sparse_patterns()
284 }
285
286 async fn set_sparse_patterns(
287 &mut self,
288 new_sparse_patterns: Vec<RepoPathBuf>,
289 ) -> Result<CheckoutStats, CheckoutError> {
290 self.inner.set_sparse_patterns(new_sparse_patterns).await
291 }
292
293 async fn finish(
294 self: Box<Self>,
295 operation_id: OperationId,
296 ) -> Result<Box<dyn WorkingCopy>, WorkingCopyStateError> {
297 let inner = self.inner.finish(operation_id).await?;
298 Ok(Box::new(ConflictsWorkingCopy {
299 inner,
300 working_copy_path: self.wc_path,
301 }))
302 }
303 }