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 package org.eclipse.jgit.api;
44
45 import java.io.File;
46 import java.io.IOException;
47 import java.net.URISyntaxException;
48 import java.text.MessageFormat;
49 import java.util.ArrayList;
50 import java.util.Collection;
51 import java.util.List;
52
53 import org.eclipse.jgit.api.errors.GitAPIException;
54 import org.eclipse.jgit.api.errors.InvalidRemoteException;
55 import org.eclipse.jgit.api.errors.JGitInternalException;
56 import org.eclipse.jgit.dircache.DirCache;
57 import org.eclipse.jgit.dircache.DirCacheCheckout;
58 import org.eclipse.jgit.errors.IncorrectObjectTypeException;
59 import org.eclipse.jgit.errors.MissingObjectException;
60 import org.eclipse.jgit.internal.JGitText;
61 import org.eclipse.jgit.lib.ConfigConstants;
62 import org.eclipse.jgit.lib.Constants;
63 import org.eclipse.jgit.lib.NullProgressMonitor;
64 import org.eclipse.jgit.lib.ProgressMonitor;
65 import org.eclipse.jgit.lib.Ref;
66 import org.eclipse.jgit.lib.RefUpdate;
67 import org.eclipse.jgit.lib.Repository;
68 import org.eclipse.jgit.revwalk.RevCommit;
69 import org.eclipse.jgit.revwalk.RevWalk;
70 import org.eclipse.jgit.submodule.SubmoduleWalk;
71 import org.eclipse.jgit.transport.FetchResult;
72 import org.eclipse.jgit.transport.RefSpec;
73 import org.eclipse.jgit.transport.RemoteConfig;
74 import org.eclipse.jgit.transport.TagOpt;
75 import org.eclipse.jgit.transport.URIish;
76
77
78
79
80
81
82
83 public class CloneCommand extends TransportCommand<CloneCommand, Git> {
84
85 private String uri;
86
87 private File directory;
88
89 private File gitDir;
90
91 private boolean bare;
92
93 private String remote = Constants.DEFAULT_REMOTE_NAME;
94
95 private String branch = Constants.HEAD;
96
97 private ProgressMonitor monitor = NullProgressMonitor.INSTANCE;
98
99 private boolean cloneAllBranches;
100
101 private boolean cloneSubmodules;
102
103 private boolean noCheckout;
104
105 private Collection<String> branchesToClone;
106
107
108
109
110 public CloneCommand() {
111 super(null);
112 }
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128 public Git call() throws GitAPIException, InvalidRemoteException,
129 org.eclipse.jgit.api.errors.TransportException {
130 Repository repository = null;
131 try {
132 URIish u = new URIish(uri);
133 repository = init(u);
134 FetchResult result = fetch(repository, u);
135 if (!noCheckout)
136 checkout(repository, result);
137 return new Git(repository, true);
138 } catch (IOException ioe) {
139 if (repository != null) {
140 repository.close();
141 }
142 throw new JGitInternalException(ioe.getMessage(), ioe);
143 } catch (URISyntaxException e) {
144 if (repository != null) {
145 repository.close();
146 }
147 throw new InvalidRemoteException(MessageFormat.format(
148 JGitText.get().invalidRemote, remote));
149 }
150 }
151
152 private Repository init(URIish u) throws GitAPIException {
153 InitCommand command = Git.init();
154 command.setBare(bare);
155 if (directory == null && gitDir == null)
156 directory = new File(u.getHumanishName(), Constants.DOT_GIT);
157 if (directory != null && directory.exists()
158 && directory.listFiles().length != 0)
159 throw new JGitInternalException(MessageFormat.format(
160 JGitText.get().cloneNonEmptyDirectory, directory.getName()));
161 if (gitDir != null && gitDir.exists() && gitDir.listFiles().length != 0)
162 throw new JGitInternalException(MessageFormat.format(
163 JGitText.get().cloneNonEmptyDirectory, gitDir.getName()));
164 if (directory != null)
165 command.setDirectory(directory);
166 if (gitDir != null)
167 command.setGitDir(gitDir);
168 return command.call().getRepository();
169 }
170
171 private FetchResult fetch(Repository clonedRepo, URIish u)
172 throws URISyntaxException,
173 org.eclipse.jgit.api.errors.TransportException, IOException,
174 GitAPIException {
175
176 RemoteConfig config = new RemoteConfig(clonedRepo.getConfig(), remote);
177 config.addURI(u);
178
179 final String dst = (bare ? Constants.R_HEADS : Constants.R_REMOTES
180 + config.getName() + "/") + "*";
181 RefSpec refSpec = new RefSpec();
182 refSpec = refSpec.setForceUpdate(true);
183 refSpec = refSpec.setSourceDestination(Constants.R_HEADS + "*", dst);
184
185 config.addFetchRefSpec(refSpec);
186 config.update(clonedRepo.getConfig());
187
188 clonedRepo.getConfig().save();
189
190
191 FetchCommand command = new FetchCommand(clonedRepo);
192 command.setRemote(remote);
193 command.setProgressMonitor(monitor);
194 command.setTagOpt(TagOpt.FETCH_TAGS);
195 configure(command);
196
197 List<RefSpec> specs = calculateRefSpecs(dst);
198 command.setRefSpecs(specs);
199
200 return command.call();
201 }
202
203 private List<RefSpec> calculateRefSpecs(final String dst) {
204 RefSpec wcrs = new RefSpec();
205 wcrs = wcrs.setForceUpdate(true);
206 wcrs = wcrs.setSourceDestination(Constants.R_HEADS + "*", dst);
207 List<RefSpec> specs = new ArrayList<RefSpec>();
208 if (cloneAllBranches)
209 specs.add(wcrs);
210 else if (branchesToClone != null
211 && branchesToClone.size() > 0) {
212 for (final String selectedRef : branchesToClone)
213 if (wcrs.matchSource(selectedRef))
214 specs.add(wcrs.expandFromSource(selectedRef));
215 }
216 return specs;
217 }
218
219 private void checkout(Repository clonedRepo, FetchResult result)
220 throws MissingObjectException, IncorrectObjectTypeException,
221 IOException, GitAPIException {
222
223 Ref head = null;
224 if (branch.equals(Constants.HEAD)) {
225 Ref foundBranch = findBranchToCheckout(result);
226 if (foundBranch != null)
227 head = foundBranch;
228 }
229 if (head == null) {
230 head = result.getAdvertisedRef(branch);
231 if (head == null)
232 head = result.getAdvertisedRef(Constants.R_HEADS + branch);
233 if (head == null)
234 head = result.getAdvertisedRef(Constants.R_TAGS + branch);
235 }
236
237 if (head == null || head.getObjectId() == null)
238 return;
239
240 if (head.getName().startsWith(Constants.R_HEADS)) {
241 final RefUpdate newHead = clonedRepo.updateRef(Constants.HEAD);
242 newHead.disableRefLog();
243 newHead.link(head.getName());
244 addMergeConfig(clonedRepo, head);
245 }
246
247 final RevCommit commit = parseCommit(clonedRepo, head);
248
249 boolean detached = !head.getName().startsWith(Constants.R_HEADS);
250 RefUpdate u = clonedRepo.updateRef(Constants.HEAD, detached);
251 u.setNewObjectId(commit.getId());
252 u.forceUpdate();
253
254 if (!bare) {
255 DirCache dc = clonedRepo.lockDirCache();
256 DirCacheCheckout co = new DirCacheCheckout(clonedRepo, dc,
257 commit.getTree());
258 co.checkout();
259 if (cloneSubmodules)
260 cloneSubmodules(clonedRepo);
261 }
262 }
263
264 private void cloneSubmodules(Repository clonedRepo) throws IOException,
265 GitAPIException {
266 SubmoduleInitCommand init = new SubmoduleInitCommand(clonedRepo);
267 if (init.call().isEmpty())
268 return;
269
270 SubmoduleUpdateCommand update = new SubmoduleUpdateCommand(clonedRepo);
271 configure(update);
272 update.setProgressMonitor(monitor);
273 if (!update.call().isEmpty()) {
274 SubmoduleWalk walk = SubmoduleWalk.forIndex(clonedRepo);
275 while (walk.next()) {
276 Repository subRepo = walk.getRepository();
277 if (subRepo != null) {
278 try {
279 cloneSubmodules(subRepo);
280 } finally {
281 subRepo.close();
282 }
283 }
284 }
285 }
286 }
287
288 private Ref findBranchToCheckout(FetchResult result) {
289 final Ref idHEAD = result.getAdvertisedRef(Constants.HEAD);
290 if (idHEAD == null)
291 return null;
292
293 Ref master = result.getAdvertisedRef(Constants.R_HEADS
294 + Constants.MASTER);
295 if (master != null && master.getObjectId().equals(idHEAD.getObjectId()))
296 return master;
297
298 Ref foundBranch = null;
299 for (final Ref r : result.getAdvertisedRefs()) {
300 final String n = r.getName();
301 if (!n.startsWith(Constants.R_HEADS))
302 continue;
303 if (r.getObjectId().equals(idHEAD.getObjectId())) {
304 foundBranch = r;
305 break;
306 }
307 }
308 return foundBranch;
309 }
310
311 private void addMergeConfig(Repository clonedRepo, Ref head)
312 throws IOException {
313 String branchName = Repository.shortenRefName(head.getName());
314 clonedRepo.getConfig().setString(ConfigConstants.CONFIG_BRANCH_SECTION,
315 branchName, ConfigConstants.CONFIG_KEY_REMOTE, remote);
316 clonedRepo.getConfig().setString(ConfigConstants.CONFIG_BRANCH_SECTION,
317 branchName, ConfigConstants.CONFIG_KEY_MERGE, head.getName());
318 String autosetupRebase = clonedRepo.getConfig().getString(
319 ConfigConstants.CONFIG_BRANCH_SECTION, null,
320 ConfigConstants.CONFIG_KEY_AUTOSETUPREBASE);
321 if (ConfigConstants.CONFIG_KEY_ALWAYS.equals(autosetupRebase)
322 || ConfigConstants.CONFIG_KEY_REMOTE.equals(autosetupRebase))
323 clonedRepo.getConfig().setBoolean(
324 ConfigConstants.CONFIG_BRANCH_SECTION, branchName,
325 ConfigConstants.CONFIG_KEY_REBASE, true);
326 clonedRepo.getConfig().save();
327 }
328
329 private RevCommit parseCommit(final Repository clonedRepo, final Ref ref)
330 throws MissingObjectException, IncorrectObjectTypeException,
331 IOException {
332 final RevCommit commit;
333 try (final RevWalk rw = new RevWalk(clonedRepo)) {
334 commit = rw.parseCommit(ref.getObjectId());
335 }
336 return commit;
337 }
338
339
340
341
342
343
344
345 public CloneCommand setURI(String uri) {
346 this.uri = uri;
347 return this;
348 }
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366 public CloneCommand setDirectory(File directory) {
367 validateDirs(directory, gitDir, bare);
368 this.directory = directory;
369 return this;
370 }
371
372
373
374
375
376
377
378
379
380
381
382
383
384 public CloneCommand setGitDir(File gitDir) {
385 validateDirs(directory, gitDir, bare);
386 this.gitDir = gitDir;
387 return this;
388 }
389
390
391
392
393
394
395
396
397
398
399
400 public CloneCommand setBare(boolean bare) throws IllegalStateException {
401 validateDirs(directory, gitDir, bare);
402 this.bare = bare;
403 return this;
404 }
405
406
407
408
409
410
411
412
413
414
415
416
417 public CloneCommand setRemote(String remote) {
418 if (remote == null) {
419 remote = Constants.DEFAULT_REMOTE_NAME;
420 }
421 this.remote = remote;
422 return this;
423 }
424
425
426
427
428
429
430
431
432
433
434
435 public CloneCommand setBranch(String branch) {
436 if (branch == null) {
437 branch = Constants.HEAD;
438 }
439 this.branch = branch;
440 return this;
441 }
442
443
444
445
446
447
448
449
450
451
452 public CloneCommand setProgressMonitor(ProgressMonitor monitor) {
453 if (monitor == null) {
454 monitor = NullProgressMonitor.INSTANCE;
455 }
456 this.monitor = monitor;
457 return this;
458 }
459
460
461
462
463
464
465
466 public CloneCommand setCloneAllBranches(boolean cloneAllBranches) {
467 this.cloneAllBranches = cloneAllBranches;
468 return this;
469 }
470
471
472
473
474
475
476
477 public CloneCommand setCloneSubmodules(boolean cloneSubmodules) {
478 this.cloneSubmodules = cloneSubmodules;
479 return this;
480 }
481
482
483
484
485
486
487
488
489 public CloneCommand setBranchesToClone(Collection<String> branchesToClone) {
490 this.branchesToClone = branchesToClone;
491 return this;
492 }
493
494
495
496
497
498
499
500
501 public CloneCommand setNoCheckout(boolean noCheckout) {
502 this.noCheckout = noCheckout;
503 return this;
504 }
505
506 private static void validateDirs(File directory, File gitDir, boolean bare)
507 throws IllegalStateException {
508 if (directory != null) {
509 if (bare) {
510 if (gitDir != null && !gitDir.equals(directory))
511 throw new IllegalStateException(MessageFormat.format(
512 JGitText.get().initFailedBareRepoDifferentDirs,
513 gitDir, directory));
514 } else {
515 if (gitDir != null && gitDir.equals(directory))
516 throw new IllegalStateException(MessageFormat.format(
517 JGitText.get().initFailedNonBareRepoSameDirs,
518 gitDir, directory));
519 }
520 }
521 }
522 }