Debian Codegraph @

cli/src/commands/git/mod.rs

raw
1 // Copyright 2020-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 mod clone;
16 mod colocation;
17 mod export;
18 mod fetch;
19 mod import;
20 mod init;
21 mod push;
22 mod remote;
23 mod root;
24
25 use std::io::Write as _;
26
27 use clap::Subcommand;
28 use jj_lib::config::ConfigFile;
29 use jj_lib::config::ConfigLayer;
30 use jj_lib::config::ConfigSource;
31 use jj_lib::git;
32 use jj_lib::git::UnexpectedGitBackendError;
33 use jj_lib::ref_name::RemoteName;
34 use jj_lib::ref_name::RemoteNameBuf;
35 use jj_lib::ref_name::RemoteRefSymbol;
36 use jj_lib::ref_name::RemoteRefSymbolBuf;
37 use jj_lib::revset;
38 use jj_lib::store::Store;
39
40 use self::clone::GitCloneArgs;
41 use self::clone::cmd_git_clone;
42 use self::colocation::GitColocationCommand;
43 use self::colocation::cmd_git_colocation;
44 use self::export::GitExportArgs;
45 use self::export::cmd_git_export;
46 use self::fetch::GitFetchArgs;
47 use self::fetch::cmd_git_fetch;
48 use self::import::GitImportArgs;
49 use self::import::cmd_git_import;
50 use self::init::GitInitArgs;
51 use self::init::cmd_git_init;
52 use self::push::GitPushArgs;
53 use self::push::cmd_git_push;
54 pub use self::push::is_push_operation;
55 use self::remote::RemoteCommand;
56 use self::remote::cmd_git_remote;
57 use self::root::GitRootArgs;
58 use self::root::cmd_git_root;
59 use crate::cli_util::CommandHelper;
60 use crate::cli_util::WorkspaceCommandHelper;
61 use crate::command_error::CommandError;
62 use crate::command_error::user_error_with_message;
63 use crate::config::ConfigEnv;
64 use crate::config::RawConfig;
65 use crate::config::existing_repo_config_file;
66 use crate::ui::Ui;
67
68 /// Commands for working with Git remotes and the underlying Git repo
69 ///
70 /// See this [comparison], including a [table of commands].
71 ///
72 /// [comparison]:
73 /// https://docs.jj-vcs.dev/latest/git-comparison/.
74 ///
75 /// [table of commands]:
76 /// https://docs.jj-vcs.dev/latest/git-command-table
77 #[derive(Subcommand, Clone, Debug)]
78 pub enum GitCommand {
79 Clone(GitCloneArgs),
80 #[command(subcommand)]
81 Colocation(GitColocationCommand),
82 Export(GitExportArgs),
83 Fetch(GitFetchArgs),
84 Import(GitImportArgs),
85 Init(GitInitArgs),
86 Push(GitPushArgs),
87 #[command(subcommand)]
88 Remote(RemoteCommand),
89 Root(GitRootArgs),
90 }
91
92 pub async fn cmd_git(
93 ui: &mut Ui,
94 command: &CommandHelper,
95 subcommand: &GitCommand,
96 ) -> Result<(), CommandError> {
97 match subcommand {
98 GitCommand::Clone(args) => cmd_git_clone(ui, command, args).await,
99 GitCommand::Colocation(subcommand) => cmd_git_colocation(ui, command, subcommand).await,
100 GitCommand::Export(args) => cmd_git_export(ui, command, args).await,
101 GitCommand::Fetch(args) => cmd_git_fetch(ui, command, args).await,
102 GitCommand::Import(args) => cmd_git_import(ui, command, args).await,
103 GitCommand::Init(args) => cmd_git_init(ui, command, args).await,
104 GitCommand::Push(args) => cmd_git_push(ui, command, args).await,
105 GitCommand::Remote(args) => cmd_git_remote(ui, command, args).await,
106 GitCommand::Root(args) => cmd_git_root(ui, command, args).await,
107 }
108 }
109
110 pub fn maybe_add_gitignore(workspace_command: &WorkspaceCommandHelper) -> Result<(), CommandError> {
111 if workspace_command.working_copy_shared_with_git() {
112 std::fs::write(
113 workspace_command
114 .workspace_root()
115 .join(".jj")
116 .join(".gitignore"),
117 "/*\n",
118 )
119 .map_err(|e| user_error_with_message("Failed to write .jj/.gitignore file", e))
120 } else {
121 Ok(())
122 }
123 }
124
125 fn get_single_remote(store: &Store) -> Result<Option<RemoteNameBuf>, UnexpectedGitBackendError> {
126 let mut names = git::get_all_remote_names(store)?;
127 Ok(match names.len() {
128 1 => names.pop(),
129 _ => None,
130 })
131 }
132
133 const TRUNK_CONFIG_NAME: [&str; 2] = ["revset-aliases", "trunk()"];
134
135 #[derive(Clone, Copy, Debug)]
136 struct RepoPresets<'a> {
137 remote: &'a RemoteName,
138 fetch_bookmarks: Option<&'a [String]>,
139 fetch_tags: Option<&'a [String]>,
140 trunk: Option<RemoteRefSymbol<'a>>,
141 }
142
143 impl RepoPresets<'_> {
144 fn is_default(self) -> bool {
145 let Self {
146 remote: _,
147 fetch_bookmarks,
148 fetch_tags,
149 trunk,
150 } = self;
151 fetch_bookmarks.is_none() && fetch_tags.is_none() && trunk.is_none()
152 }
153 }
154
155 /// Saves trunk and default fetch settings to repo-level config file.
156 fn write_repo_presets(
157 ui: &Ui,
158 config_env: &ConfigEnv,
159 presets: RepoPresets<'_>,
160 ) -> Result<(), CommandError> {
161 if presets.is_default() {
162 return Ok(()); // Don't initialize config directory
163 }
164 let Some(config_path) = config_env.repo_config_path(ui)? else {
165 // We couldn't find the user's home directory, so we skip this step.
166 return Ok(());
167 };
168 let mut file = ConfigFile::load_or_empty(ConfigSource::Repo, config_path)?;
169 if let Some(exprs) = presets.fetch_bookmarks {
170 file.set_value(
171 ["remotes", presets.remote.as_str(), "fetch-bookmarks"],
172 join_string_expressions(exprs),
173 )
174 .expect("initial repo config shouldn't have invalid values");
175 }
176 if let Some(exprs) = presets.fetch_tags {
177 file.set_value(
178 ["remotes", presets.remote.as_str(), "fetch-tags"],
179 join_string_expressions(exprs),
180 )
181 .expect("initial repo config shouldn't have invalid values");
182 }
183 if let Some(symbol) = presets.trunk {
184 file.set_value(TRUNK_CONFIG_NAME, symbol.to_string())
185 .expect("initial repo config shouldn't have invalid values");
186 writeln!(
187 ui.status(),
188 "Setting the revset alias `trunk()` to `{symbol}`.",
189 )?;
190 }
191 file.save()?;
192 Ok(())
193 }
194
195 /// Renames preset trunk and remote settings in repo-level config file.
196 fn rename_remote_in_repo_config(
197 ui: &Ui,
198 config: &RawConfig,
199 old_remote: &RemoteName,
200 new_remote: &RemoteName,
201 ) -> Result<(), CommandError> {
202 let Some(mut file) = existing_repo_config_file(config) else {
203 return Ok(());
204 };
205
206 // [remotes.<old_remote>] -> [remotes.<new_remote>]
207 if let Some(remotes_item) = file.data_mut().as_table_mut().get_mut("remotes")
208 && let Some(remotes_table) = remotes_item.as_table_like_mut()
209 && let Some(old_item) = remotes_table.remove(old_remote.as_str())
210 {
211 remotes_table.insert(new_remote.as_str(), old_item);
212 }
213
214 // trunk = <name>@<old_remote> -> <name>@<new_remote>
215 if let Some(old_symbol) = get_trunk_symbol(file.layer())
216 && old_symbol.remote == old_remote
217 {
218 let new_symbol = old_symbol.name.to_remote_symbol(new_remote);
219 file.set_value(TRUNK_CONFIG_NAME, new_symbol.to_string())
220 .expect("old value was string");
221 writeln!(
222 ui.status(),
223 "Updating the revset alias `trunk()` to `{new_symbol}`.",
224 )?;
225 }
226
227 file.save()?;
228 Ok(())
229 }
230
231 /// Removes preset trunk and remote settings from repo-level config file.
232 fn remove_remote_from_repo_config(
233 ui: &Ui,
234 config: &RawConfig,
235 old_remote: &RemoteName,
236 ) -> Result<(), CommandError> {
237 let Some(mut file) = existing_repo_config_file(config) else {
238 return Ok(());
239 };
240
241 // [remotes.<old_remote>]
242 if let Some(remotes_item) = file.data_mut().as_table_mut().get_mut("remotes")
243 && let Some(remotes_table) = remotes_item.as_table_like_mut()
244 {
245 remotes_table.remove(old_remote.as_str());
246 }
247
248 // trunk = <name>@<old_remote>
249 if let Some(old_symbol) = get_trunk_symbol(file.layer())
250 && old_symbol.remote == old_remote
251 {
252 file.delete_value(TRUNK_CONFIG_NAME)
253 .expect("old value was string");
254 writeln!(
255 ui.status(),
256 "Resetting the revset alias `trunk()` to default value.",
257 )?;
258 }
259
260 file.save()?;
261 Ok(())
262 }
263
264 fn get_trunk_symbol(layer: &ConfigLayer) -> Option<RemoteRefSymbolBuf> {
265 if let Ok(Some(trunk_item)) = layer.look_up_item(TRUNK_CONFIG_NAME)
266 && let Some(trunk_str) = trunk_item.as_str()
267 && let Ok(revset::ExpressionKind::RemoteSymbol(symbol)) =
268 revset::parse_program(trunk_str).map(|node| node.kind)
269 {
270 Some(symbol)
271 } else {
272 None
273 }
274 }
275
276 fn join_string_expressions(exprs: &[String]) -> String {
277 match exprs {
278 [] => "~*".to_owned(), // no matches
279 _ => exprs.join(" | "), // no parentheses since | is the weakest operator
280 }
281 }
282
283 #[derive(Debug, Clone, Copy, serde::Deserialize, clap::ValueEnum)]
284 #[serde(rename_all = "lowercase")]
285 #[value(rename_all = "lower")]
286 enum ObjectHash {
287 Sha1,
288 Sha256,
289 }
290
291 impl From<ObjectHash> for gix::hash::Kind {
292 fn from(value: ObjectHash) -> Self {
293 match value {
294 ObjectHash::Sha1 => Self::Sha1,
295 ObjectHash::Sha256 => Self::Sha256,
296 }
297 }
298 }