1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
use std::collections::{BTreeMap, BTreeSet, HashSet};
use std::fs::OpenOptions;
use std::io::{Read, Write};
use std::sync::Arc;
use git2::{Oid, RemoteCallbacks};
use itertools::Itertools;
use thiserror::Error;
use crate::backend::CommitId;
use crate::commit::Commit;
use crate::op_store::{OperationId, RefTarget};
use crate::operation::Operation;
use crate::repo::{MutableRepo, ReadonlyRepo, RepoRef};
use crate::view::RefName;
#[derive(Error, Debug, PartialEq)]
pub enum GitImportError {
#[error("Unexpected git error when importing refs: {0}")]
InternalGitError(#[from] git2::Error),
}
fn parse_git_ref(ref_name: &str) -> Option<RefName> {
if let Some(branch_name) = ref_name.strip_prefix("refs/heads/") {
Some(RefName::LocalBranch(branch_name.to_string()))
} else if let Some(remote_and_branch) = ref_name.strip_prefix("refs/remotes/") {
remote_and_branch
.split_once('/')
.map(|(remote, branch)| RefName::RemoteBranch {
remote: remote.to_string(),
branch: branch.to_string(),
})
} else {
ref_name
.strip_prefix("refs/tags/")
.map(|tag_name| RefName::Tag(tag_name.to_string()))
}
}
pub fn import_refs(
mut_repo: &mut MutableRepo,
git_repo: &git2::Repository,
) -> Result<(), GitImportError> {
let store = mut_repo.store().clone();
let git_refs = git_repo.references()?;
let mut existing_git_refs = mut_repo.view().git_refs().clone();
let mut changed_git_refs = BTreeMap::new();
for git_ref in git_refs {
let git_ref = git_ref?;
if !(git_ref.is_tag() || git_ref.is_branch() || git_ref.is_remote())
|| git_ref.name().is_none()
{
continue;
}
let full_name = git_ref.name().unwrap().to_string();
if let Some(RefName::RemoteBranch { branch, remote: _ }) = parse_git_ref(&full_name) {
if &branch == "HEAD" {
continue;
}
}
let git_commit = match git_ref.peel_to_commit() {
Ok(git_commit) => git_commit,
Err(_) => {
continue;
}
};
let id = CommitId::from_bytes(git_commit.id().as_bytes());
mut_repo.set_git_ref(full_name.clone(), RefTarget::Normal(id.clone()));
let old_target = existing_git_refs.remove(&full_name);
let new_target = Some(RefTarget::Normal(id.clone()));
if new_target != old_target {
let commit = store.get_commit(&id).unwrap();
mut_repo.add_head(&commit);
changed_git_refs.insert(full_name, (old_target, new_target));
}
}
for (full_name, target) in existing_git_refs {
mut_repo.remove_git_ref(&full_name);
changed_git_refs.insert(full_name, (Some(target), None));
}
for (full_name, (old_git_target, new_git_target)) in changed_git_refs {
if let Some(ref_name) = parse_git_ref(&full_name) {
mut_repo.merge_single_ref(&ref_name, old_git_target.as_ref(), new_git_target.as_ref());
if let RefName::RemoteBranch { branch, remote: _ } = ref_name {
mut_repo.merge_single_ref(
&RefName::LocalBranch(branch),
old_git_target.as_ref(),
new_git_target.as_ref(),
);
}
}
}
if let Ok(head_git_commit) = git_repo
.head()
.and_then(|head_ref| head_ref.peel_to_commit())
{
let head_commit_id = CommitId::from_bytes(head_git_commit.id().as_bytes());
let head_commit = store.get_commit(&head_commit_id).unwrap();
mut_repo.add_head(&head_commit);
mut_repo.set_git_head(head_commit_id);
} else {
mut_repo.clear_git_head();
}
Ok(())
}
#[derive(Error, Debug, PartialEq)]
pub enum GitExportError {
#[error("Cannot export conflicted branch '{0}'")]
ConflictedBranch(String),
#[error("Unexpected git error when exporting refs: {0}")]
InternalGitError(#[from] git2::Error),
}
pub fn export_changes(
old_repo: RepoRef,
new_repo: RepoRef,
git_repo: &git2::Repository,
) -> Result<(), GitExportError> {
let old_view = old_repo.view();
let new_view = new_repo.view();
let old_branches: HashSet<_> = old_view.branches().keys().cloned().collect();
let new_branches: HashSet<_> = new_view.branches().keys().cloned().collect();
let mut active_branches = HashSet::new();
if let Ok(head_ref) = git_repo.find_reference("HEAD") {
if let Some(head_target) = head_ref.symbolic_target() {
active_branches.insert(head_target.to_string());
}
}
let mut detach_head = false;
let mut refs_to_update = BTreeMap::new();
let mut refs_to_delete = BTreeSet::new();
for branch_name in old_branches.union(&new_branches) {
let old_branch = old_view.get_local_branch(branch_name);
let new_branch = new_view.get_local_branch(branch_name);
if new_branch == old_branch {
continue;
}
let git_ref_name = format!("refs/heads/{}", branch_name);
if let Some(new_branch) = new_branch {
match new_branch {
RefTarget::Normal(id) => {
refs_to_update.insert(
git_ref_name.clone(),
Oid::from_bytes(id.as_bytes()).unwrap(),
);
}
RefTarget::Conflict { .. } => {
return Err(GitExportError::ConflictedBranch(branch_name.to_string()));
}
}
} else {
refs_to_delete.insert(git_ref_name.clone());
}
if active_branches.contains(&git_ref_name) {
detach_head = true;
}
}
if detach_head {
if let Ok(head_ref) = git_repo.find_reference("HEAD") {
if let Ok(current_git_commit) = head_ref.peel_to_commit() {
git_repo.set_head_detached(current_git_commit.id())?;
}
}
}
for (git_ref_name, new_target) in refs_to_update {
git_repo.reference(&git_ref_name, new_target, true, "export from jj")?;
}
for git_ref_name in refs_to_delete {
if let Ok(mut git_ref) = git_repo.find_reference(&git_ref_name) {
git_ref.delete()?;
}
}
Ok(())
}
pub fn export_refs(
repo: &Arc<ReadonlyRepo>,
git_repo: &git2::Repository,
) -> Result<(), GitExportError> {
let last_export_path = repo.repo_path().join("git_export_operation_id");
if let Ok(mut last_export_file) = OpenOptions::new().read(true).open(&last_export_path) {
let mut buf = vec![];
last_export_file.read_to_end(&mut buf).unwrap();
let last_export_op_id = OperationId::from_hex(String::from_utf8(buf).unwrap().as_str());
let loader = repo.loader();
let op_store = loader.op_store();
let last_export_store_op = op_store.read_operation(&last_export_op_id).unwrap();
let last_export_op =
Operation::new(op_store.clone(), last_export_op_id, last_export_store_op);
let old_repo = repo.loader().load_at(&last_export_op);
export_changes(old_repo.as_repo_ref(), repo.as_repo_ref(), git_repo)?;
}
if let Ok(mut last_export_file) = OpenOptions::new()
.write(true)
.create(true)
.open(&last_export_path)
{
let buf = repo.op_id().hex().as_bytes().to_vec();
last_export_file.write_all(&buf).unwrap();
}
Ok(())
}
#[derive(Error, Debug, PartialEq)]
pub enum GitFetchError {
#[error("No git remote named '{0}'")]
NoSuchRemote(String),
#[error("Unexpected git error when fetching: {0}")]
InternalGitError(#[from] git2::Error),
}
pub fn fetch(
mut_repo: &mut MutableRepo,
git_repo: &git2::Repository,
remote_name: &str,
) -> Result<Option<String>, GitFetchError> {
let mut remote =
git_repo
.find_remote(remote_name)
.map_err(|err| match (err.class(), err.code()) {
(git2::ErrorClass::Config, git2::ErrorCode::NotFound) => {
GitFetchError::NoSuchRemote(remote_name.to_string())
}
(git2::ErrorClass::Config, git2::ErrorCode::InvalidSpec) => {
GitFetchError::NoSuchRemote(remote_name.to_string())
}
_ => GitFetchError::InternalGitError(err),
})?;
let mut fetch_options = git2::FetchOptions::new();
let mut proxy_options = git2::ProxyOptions::new();
proxy_options.auto();
fetch_options.proxy_options(proxy_options);
let callbacks = create_remote_callbacks();
fetch_options.remote_callbacks(callbacks);
let refspec: &[&str] = &[];
remote.download(refspec, Some(&mut fetch_options))?;
remote.update_tips(None, false, git2::AutotagOption::Unspecified, None)?;
remote.prune(None)?;
let mut default_branch = None;
if let Ok(default_ref_buf) = remote.default_branch() {
if let Some(default_ref) = default_ref_buf.as_str() {
if let Some(RefName::LocalBranch(branch_name)) = parse_git_ref(default_ref) {
default_branch = Some(branch_name);
}
}
}
remote.disconnect()?;
import_refs(mut_repo, git_repo).map_err(|err| match err {
GitImportError::InternalGitError(source) => GitFetchError::InternalGitError(source),
})?;
Ok(default_branch)
}
#[derive(Error, Debug, PartialEq)]
pub enum GitPushError {
#[error("No git remote named '{0}'")]
NoSuchRemote(String),
#[error("Push is not fast-forwardable")]
NotFastForward,
#[error("Remote reject the update of some refs")]
RefUpdateRejected(Vec<String>),
#[error("Unexpected git error when pushing: {0}")]
InternalGitError(#[from] git2::Error),
}
pub fn push_commit(
git_repo: &git2::Repository,
target: &Commit,
remote_name: &str,
remote_branch: &str,
force: bool,
) -> Result<(), GitPushError> {
push_updates(
git_repo,
remote_name,
&[GitRefUpdate {
qualified_name: format!("refs/heads/{}", remote_branch),
force,
new_target: Some(target.id().clone()),
}],
)
}
pub struct GitRefUpdate {
pub qualified_name: String,
pub force: bool,
pub new_target: Option<CommitId>,
}
pub fn push_updates(
git_repo: &git2::Repository,
remote_name: &str,
updates: &[GitRefUpdate],
) -> Result<(), GitPushError> {
let mut temp_refs = vec![];
let mut qualified_remote_refs = vec![];
let mut refspecs = vec![];
for update in updates {
qualified_remote_refs.push(update.qualified_name.as_str());
if let Some(new_target) = &update.new_target {
let temp_ref_name = format!("refs/jj/git-push/{}", new_target.hex());
temp_refs.push(git_repo.reference(
&temp_ref_name,
git2::Oid::from_bytes(new_target.as_bytes()).unwrap(),
true,
"temporary reference for git push",
)?);
refspecs.push(format!(
"{}{}:{}",
(if update.force { "+" } else { "" }),
temp_ref_name,
update.qualified_name
));
} else {
refspecs.push(format!(":{}", update.qualified_name));
}
}
let result = push_refs(git_repo, remote_name, &qualified_remote_refs, &refspecs);
for mut temp_ref in temp_refs {
temp_ref.delete()?;
}
result
}
fn push_refs(
git_repo: &git2::Repository,
remote_name: &str,
qualified_remote_refs: &[&str],
refspecs: &[String],
) -> Result<(), GitPushError> {
let mut remote =
git_repo
.find_remote(remote_name)
.map_err(|err| match (err.class(), err.code()) {
(git2::ErrorClass::Config, git2::ErrorCode::NotFound) => {
GitPushError::NoSuchRemote(remote_name.to_string())
}
(git2::ErrorClass::Config, git2::ErrorCode::InvalidSpec) => {
GitPushError::NoSuchRemote(remote_name.to_string())
}
_ => GitPushError::InternalGitError(err),
})?;
let mut remaining_remote_refs: HashSet<_> = qualified_remote_refs.iter().copied().collect();
let mut push_options = git2::PushOptions::new();
let mut proxy_options = git2::ProxyOptions::new();
proxy_options.auto();
push_options.proxy_options(proxy_options);
let mut callbacks = create_remote_callbacks();
callbacks.push_update_reference(|refname, status| {
if status.is_none() {
remaining_remote_refs.remove(refname);
}
Ok(())
});
push_options.remote_callbacks(callbacks);
remote
.push(refspecs, Some(&mut push_options))
.map_err(|err| match (err.class(), err.code()) {
(git2::ErrorClass::Reference, git2::ErrorCode::NotFastForward) => {
GitPushError::NotFastForward
}
_ => GitPushError::InternalGitError(err),
})?;
drop(push_options);
if remaining_remote_refs.is_empty() {
Ok(())
} else {
Err(GitPushError::RefUpdateRejected(
remaining_remote_refs
.iter()
.sorted()
.map(|name| name.to_string())
.collect(),
))
}
}
fn create_remote_callbacks() -> RemoteCallbacks<'static> {
let mut callbacks = git2::RemoteCallbacks::new();
callbacks.credentials(|_url, username_from_url, allowed_types| {
if allowed_types.contains(git2::CredentialType::SSH_KEY) {
if std::env::var("SSH_AGENT_PID").is_ok() {
return git2::Cred::ssh_key_from_agent(username_from_url.unwrap());
}
if let Ok(home_dir) = std::env::var("HOME") {
let key_path = std::path::Path::new(&home_dir).join(".ssh").join("id_rsa");
if key_path.is_file() {
return git2::Cred::ssh_key(username_from_url.unwrap(), None, &key_path, None);
}
}
}
git2::Cred::default()
});
callbacks
}