View Javadoc
1   /*
2    * Copyright (C) 2011, 2017 Chris Aniszczyk <caniszczyk@gmail.com>
3    * and other copyright owners as documented in the project's IP log.
4    *
5    * This program and the accompanying materials are made available
6    * under the terms of the Eclipse Distribution License v1.0 which
7    * accompanies this distribution, is reproduced below, and is
8    * available at http://www.eclipse.org/org/documents/edl-v10.php
9    *
10   * All rights reserved.
11   *
12   * Redistribution and use in source and binary forms, with or
13   * without modification, are permitted provided that the following
14   * conditions are met:
15   *
16   * - Redistributions of source code must retain the above copyright
17   *   notice, this list of conditions and the following disclaimer.
18   *
19   * - Redistributions in binary form must reproduce the above
20   *   copyright notice, this list of conditions and the following
21   *   disclaimer in the documentation and/or other materials provided
22   *   with the distribution.
23   *
24   * - Neither the name of the Eclipse Foundation, Inc. nor the
25   *   names of its contributors may be used to endorse or promote
26   *   products derived from this software without specific prior
27   *   written permission.
28   *
29   * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND
30   * CONTRIBUTORS "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES,
31   * INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES
32   * OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
33   * ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR
34   * CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
35   * SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT
36   * NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
37   * LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER
38   * CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT,
39   * STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
40   * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF
41   * ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
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.annotations.Nullable;
54  import org.eclipse.jgit.api.errors.GitAPIException;
55  import org.eclipse.jgit.api.errors.InvalidRemoteException;
56  import org.eclipse.jgit.api.errors.JGitInternalException;
57  import org.eclipse.jgit.dircache.DirCache;
58  import org.eclipse.jgit.dircache.DirCacheCheckout;
59  import org.eclipse.jgit.errors.IncorrectObjectTypeException;
60  import org.eclipse.jgit.errors.MissingObjectException;
61  import org.eclipse.jgit.internal.JGitText;
62  import org.eclipse.jgit.lib.AnyObjectId;
63  import org.eclipse.jgit.lib.BranchConfig.BranchRebaseMode;
64  import org.eclipse.jgit.lib.ConfigConstants;
65  import org.eclipse.jgit.lib.Constants;
66  import org.eclipse.jgit.lib.NullProgressMonitor;
67  import org.eclipse.jgit.lib.ObjectId;
68  import org.eclipse.jgit.lib.ProgressMonitor;
69  import org.eclipse.jgit.lib.Ref;
70  import org.eclipse.jgit.lib.RefUpdate;
71  import org.eclipse.jgit.lib.Repository;
72  import org.eclipse.jgit.revwalk.RevCommit;
73  import org.eclipse.jgit.revwalk.RevWalk;
74  import org.eclipse.jgit.submodule.SubmoduleWalk;
75  import org.eclipse.jgit.transport.FetchResult;
76  import org.eclipse.jgit.transport.RefSpec;
77  import org.eclipse.jgit.transport.RemoteConfig;
78  import org.eclipse.jgit.transport.TagOpt;
79  import org.eclipse.jgit.transport.URIish;
80  import org.eclipse.jgit.util.FileUtils;
81  import org.eclipse.jgit.util.FS;
82  
83  /**
84   * Clone a repository into a new working directory
85   *
86   * @see <a href="http://www.kernel.org/pub/software/scm/git/docs/git-clone.html"
87   *      >Git documentation about Clone</a>
88   */
89  public class CloneCommand extends TransportCommand<CloneCommand, Git> {
90  
91  	private String uri;
92  
93  	private File directory;
94  
95  	private File gitDir;
96  
97  	private boolean bare;
98  
99  	private FS fs;
100 
101 	private String remote = Constants.DEFAULT_REMOTE_NAME;
102 
103 	private String branch = Constants.HEAD;
104 
105 	private ProgressMonitor monitor = NullProgressMonitor.INSTANCE;
106 
107 	private boolean cloneAllBranches;
108 
109 	private boolean cloneSubmodules;
110 
111 	private boolean noCheckout;
112 
113 	private Collection<String> branchesToClone;
114 
115 	private Callback callback;
116 
117 	private boolean directoryExistsInitially;
118 
119 	private boolean gitDirExistsInitially;
120 
121 	/**
122 	 * Callback for status of clone operation.
123 	 *
124 	 * @since 4.8
125 	 */
126 	public interface Callback {
127 		/**
128 		 * Notify initialized submodules.
129 		 *
130 		 * @param submodules
131 		 *            the submodules
132 		 *
133 		 */
134 		void initializedSubmodules(Collection<String> submodules);
135 
136 		/**
137 		 * Notify starting to clone a submodule.
138 		 *
139 		 * @param path
140 		 *            the submodule path
141 		 */
142 		void cloningSubmodule(String path);
143 
144 		/**
145 		 * Notify checkout of commit
146 		 *
147 		 * @param commit
148 		 *            the id of the commit being checked out
149 		 * @param path
150 		 *            the submodule path
151 		 */
152 		void checkingOut(AnyObjectId commit, String path);
153 	}
154 
155 	/**
156 	 * Create clone command with no repository set
157 	 */
158 	public CloneCommand() {
159 		super(null);
160 	}
161 
162 	/**
163 	 * Get the git directory. This is primarily used for tests.
164 	 *
165 	 * @return the git directory
166 	 */
167 	@Nullable
168 	File getDirectory() {
169 		return directory;
170 	}
171 
172 	/**
173 	 * {@inheritDoc}
174 	 * <p>
175 	 * Executes the {@code Clone} command.
176 	 *
177 	 * The Git instance returned by this command needs to be closed by the
178 	 * caller to free resources held by the underlying {@link Repository}
179 	 * instance. It is recommended to call this method as soon as you don't need
180 	 * a reference to this {@link Git} instance and the underlying
181 	 * {@link Repository} instance anymore.
182 	 */
183 	@Override
184 	public Git call() throws GitAPIException, InvalidRemoteException,
185 			org.eclipse.jgit.api.errors.TransportException {
186 		URIish u = null;
187 		try {
188 			u = new URIish(uri);
189 			verifyDirectories(u);
190 		} catch (URISyntaxException e) {
191 			throw new InvalidRemoteException(
192 					MessageFormat.format(JGitText.get().invalidURL, uri));
193 		}
194 		@SuppressWarnings("resource") // Closed by caller
195 		Repository repository = init();
196 		FetchResult fetchResult = null;
197 		Thread cleanupHook = new Thread(() -> cleanup());
198 		Runtime.getRuntime().addShutdownHook(cleanupHook);
199 		try {
200 			fetchResult = fetch(repository, u);
201 		} catch (IOException ioe) {
202 			if (repository != null) {
203 				repository.close();
204 			}
205 			cleanup();
206 			throw new JGitInternalException(ioe.getMessage(), ioe);
207 		} catch (URISyntaxException e) {
208 			if (repository != null) {
209 				repository.close();
210 			}
211 			cleanup();
212 			throw new InvalidRemoteException(MessageFormat.format(
213 					JGitText.get().invalidRemote, remote));
214 		} catch (GitAPIException | RuntimeException e) {
215 			if (repository != null) {
216 				repository.close();
217 			}
218 			cleanup();
219 			throw e;
220 		} finally {
221 			Runtime.getRuntime().removeShutdownHook(cleanupHook);
222 		}
223 		if (!noCheckout) {
224 			try {
225 				checkout(repository, fetchResult);
226 			} catch (IOException ioe) {
227 				repository.close();
228 				throw new JGitInternalException(ioe.getMessage(), ioe);
229 			} catch (GitAPIException | RuntimeException e) {
230 				repository.close();
231 				throw e;
232 			}
233 		}
234 		return new Git(repository, true);
235 	}
236 
237 	private static boolean isNonEmptyDirectory(File dir) {
238 		if (dir != null && dir.exists()) {
239 			File[] files = dir.listFiles();
240 			return files != null && files.length != 0;
241 		}
242 		return false;
243 	}
244 
245 	void verifyDirectories(URIish u) {
246 		if (directory == null && gitDir == null) {
247 			directory = new File(u.getHumanishName() + (bare ? Constants.DOT_GIT_EXT : "")); //$NON-NLS-1$
248 		}
249 		directoryExistsInitially = directory != null && directory.exists();
250 		gitDirExistsInitially = gitDir != null && gitDir.exists();
251 		validateDirs(directory, gitDir, bare);
252 		if (isNonEmptyDirectory(directory)) {
253 			throw new JGitInternalException(MessageFormat.format(
254 					JGitText.get().cloneNonEmptyDirectory, directory.getName()));
255 		}
256 		if (isNonEmptyDirectory(gitDir)) {
257 			throw new JGitInternalException(MessageFormat.format(
258 					JGitText.get().cloneNonEmptyDirectory, gitDir.getName()));
259 		}
260 	}
261 
262 	private Repository init() throws GitAPIException {
263 		InitCommand command = Git.init();
264 		command.setBare(bare);
265 		if (fs != null) {
266 			command.setFs(fs);
267 		}
268 		if (directory != null) {
269 			command.setDirectory(directory);
270 		}
271 		if (gitDir != null) {
272 			command.setGitDir(gitDir);
273 		}
274 		return command.call().getRepository();
275 	}
276 
277 	private FetchResult fetch(Repository clonedRepo, URIish u)
278 			throws URISyntaxException,
279 			org.eclipse.jgit.api.errors.TransportException, IOException,
280 			GitAPIException {
281 		// create the remote config and save it
282 		RemoteConfig config = new RemoteConfig(clonedRepo.getConfig(), remote);
283 		config.addURI(u);
284 
285 		final String dst = (bare ? Constants.R_HEADS : Constants.R_REMOTES
286 				+ config.getName() + '/') + '*';
287 		boolean fetchAll = cloneAllBranches || branchesToClone == null
288 				|| branchesToClone.isEmpty();
289 
290 		config.setFetchRefSpecs(calculateRefSpecs(fetchAll, dst));
291 		config.update(clonedRepo.getConfig());
292 
293 		clonedRepo.getConfig().save();
294 
295 		// run the fetch command
296 		FetchCommand command = new FetchCommand(clonedRepo);
297 		command.setRemote(remote);
298 		command.setProgressMonitor(monitor);
299 		command.setTagOpt(fetchAll ? TagOpt.FETCH_TAGS : TagOpt.AUTO_FOLLOW);
300 		configure(command);
301 
302 		return command.call();
303 	}
304 
305 	private List<RefSpec> calculateRefSpecs(boolean fetchAll, String dst) {
306 		RefSpec heads = new RefSpec();
307 		heads = heads.setForceUpdate(true);
308 		heads = heads.setSourceDestination(Constants.R_HEADS + '*', dst);
309 		List<RefSpec> specs = new ArrayList<>();
310 		if (!fetchAll) {
311 			RefSpec tags = new RefSpec();
312 			tags = tags.setForceUpdate(true);
313 			tags = tags.setSourceDestination(Constants.R_TAGS + '*',
314 					Constants.R_TAGS + '*');
315 			for (String selectedRef : branchesToClone) {
316 				if (heads.matchSource(selectedRef)) {
317 					specs.add(heads.expandFromSource(selectedRef));
318 				} else if (tags.matchSource(selectedRef)) {
319 					specs.add(tags.expandFromSource(selectedRef));
320 				}
321 			}
322 		} else {
323 			// We'll fetch the tags anyway.
324 			specs.add(heads);
325 		}
326 		return specs;
327 	}
328 
329 	private void checkout(Repository clonedRepo, FetchResult result)
330 			throws MissingObjectException, IncorrectObjectTypeException,
331 			IOException, GitAPIException {
332 
333 		Ref head = null;
334 		if (branch.equals(Constants.HEAD)) {
335 			Ref foundBranch = findBranchToCheckout(result);
336 			if (foundBranch != null)
337 				head = foundBranch;
338 		}
339 		if (head == null) {
340 			head = result.getAdvertisedRef(branch);
341 			if (head == null)
342 				head = result.getAdvertisedRef(Constants.R_HEADS + branch);
343 			if (head == null)
344 				head = result.getAdvertisedRef(Constants.R_TAGS + branch);
345 		}
346 
347 		if (head == null || head.getObjectId() == null)
348 			return; // TODO throw exception?
349 
350 		if (head.getName().startsWith(Constants.R_HEADS)) {
351 			final RefUpdate newHead = clonedRepo.updateRef(Constants.HEAD);
352 			newHead.disableRefLog();
353 			newHead.link(head.getName());
354 			addMergeConfig(clonedRepo, head);
355 		}
356 
357 		final RevCommit commit = parseCommit(clonedRepo, head);
358 
359 		boolean detached = !head.getName().startsWith(Constants.R_HEADS);
360 		RefUpdate u = clonedRepo.updateRef(Constants.HEAD, detached);
361 		u.setNewObjectId(commit.getId());
362 		u.forceUpdate();
363 
364 		if (!bare) {
365 			DirCache dc = clonedRepo.lockDirCache();
366 			DirCacheCheckout co = new DirCacheCheckout(clonedRepo, dc,
367 					commit.getTree());
368 			co.setProgressMonitor(monitor);
369 			co.checkout();
370 			if (cloneSubmodules)
371 				cloneSubmodules(clonedRepo);
372 		}
373 	}
374 
375 	private void cloneSubmodules(Repository clonedRepo) throws IOException,
376 			GitAPIException {
377 		SubmoduleInitCommand init = new SubmoduleInitCommand(clonedRepo);
378 		Collection<String> submodules = init.call();
379 		if (submodules.isEmpty()) {
380 			return;
381 		}
382 		if (callback != null) {
383 			callback.initializedSubmodules(submodules);
384 		}
385 
386 		SubmoduleUpdateCommand update = new SubmoduleUpdateCommand(clonedRepo);
387 		configure(update);
388 		update.setProgressMonitor(monitor);
389 		update.setCallback(callback);
390 		if (!update.call().isEmpty()) {
391 			SubmoduleWalk walk = SubmoduleWalk.forIndex(clonedRepo);
392 			while (walk.next()) {
393 				try (Repository subRepo = walk.getRepository()) {
394 					if (subRepo != null) {
395 						cloneSubmodules(subRepo);
396 					}
397 				}
398 			}
399 		}
400 	}
401 
402 	private Ref findBranchToCheckout(FetchResult result) {
403 		final Ref idHEAD = result.getAdvertisedRef(Constants.HEAD);
404 		ObjectId headId = idHEAD != null ? idHEAD.getObjectId() : null;
405 		if (headId == null) {
406 			return null;
407 		}
408 
409 		Ref master = result.getAdvertisedRef(Constants.R_HEADS
410 				+ Constants.MASTER);
411 		ObjectId objectId = master != null ? master.getObjectId() : null;
412 		if (headId.equals(objectId)) {
413 			return master;
414 		}
415 
416 		Ref foundBranch = null;
417 		for (Ref r : result.getAdvertisedRefs()) {
418 			final String n = r.getName();
419 			if (!n.startsWith(Constants.R_HEADS))
420 				continue;
421 			if (headId.equals(r.getObjectId())) {
422 				foundBranch = r;
423 				break;
424 			}
425 		}
426 		return foundBranch;
427 	}
428 
429 	private void addMergeConfig(Repository clonedRepo, Ref head)
430 			throws IOException {
431 		String branchName = Repository.shortenRefName(head.getName());
432 		clonedRepo.getConfig().setString(ConfigConstants.CONFIG_BRANCH_SECTION,
433 				branchName, ConfigConstants.CONFIG_KEY_REMOTE, remote);
434 		clonedRepo.getConfig().setString(ConfigConstants.CONFIG_BRANCH_SECTION,
435 				branchName, ConfigConstants.CONFIG_KEY_MERGE, head.getName());
436 		String autosetupRebase = clonedRepo.getConfig().getString(
437 				ConfigConstants.CONFIG_BRANCH_SECTION, null,
438 				ConfigConstants.CONFIG_KEY_AUTOSETUPREBASE);
439 		if (ConfigConstants.CONFIG_KEY_ALWAYS.equals(autosetupRebase)
440 				|| ConfigConstants.CONFIG_KEY_REMOTE.equals(autosetupRebase))
441 			clonedRepo.getConfig().setEnum(
442 					ConfigConstants.CONFIG_BRANCH_SECTION, branchName,
443 					ConfigConstants.CONFIG_KEY_REBASE, BranchRebaseMode.REBASE);
444 		clonedRepo.getConfig().save();
445 	}
446 
447 	private RevCommit parseCommit(Repository clonedRepo, Ref ref)
448 			throws MissingObjectException, IncorrectObjectTypeException,
449 			IOException {
450 		final RevCommit commit;
451 		try (RevWalkRevWalk.html#RevWalk">RevWalk rw = new RevWalk(clonedRepo)) {
452 			commit = rw.parseCommit(ref.getObjectId());
453 		}
454 		return commit;
455 	}
456 
457 	/**
458 	 * Set the URI to clone from
459 	 *
460 	 * @param uri
461 	 *            the URI to clone from, or {@code null} to unset the URI. The
462 	 *            URI must be set before {@link #call} is called.
463 	 * @return this instance
464 	 */
465 	public CloneCommand setURI(String uri) {
466 		this.uri = uri;
467 		return this;
468 	}
469 
470 	/**
471 	 * The optional directory associated with the clone operation. If the
472 	 * directory isn't set, a name associated with the source uri will be used.
473 	 *
474 	 * @see URIish#getHumanishName()
475 	 * @param directory
476 	 *            the directory to clone to, or {@code null} if the directory
477 	 *            name should be taken from the source uri
478 	 * @return this instance
479 	 * @throws java.lang.IllegalStateException
480 	 *             if the combination of directory, gitDir and bare is illegal.
481 	 *             E.g. if for a non-bare repository directory and gitDir point
482 	 *             to the same directory of if for a bare repository both
483 	 *             directory and gitDir are specified
484 	 */
485 	public CloneCommand setDirectory(File directory) {
486 		validateDirs(directory, gitDir, bare);
487 		this.directory = directory;
488 		return this;
489 	}
490 
491 	/**
492 	 * Set the repository meta directory (.git)
493 	 *
494 	 * @param gitDir
495 	 *            the repository meta directory, or {@code null} to choose one
496 	 *            automatically at clone time
497 	 * @return this instance
498 	 * @throws java.lang.IllegalStateException
499 	 *             if the combination of directory, gitDir and bare is illegal.
500 	 *             E.g. if for a non-bare repository directory and gitDir point
501 	 *             to the same directory of if for a bare repository both
502 	 *             directory and gitDir are specified
503 	 * @since 3.6
504 	 */
505 	public CloneCommand setGitDir(File gitDir) {
506 		validateDirs(directory, gitDir, bare);
507 		this.gitDir = gitDir;
508 		return this;
509 	}
510 
511 	/**
512 	 * Set whether the cloned repository shall be bare
513 	 *
514 	 * @param bare
515 	 *            whether the cloned repository is bare or not
516 	 * @return this instance
517 	 * @throws java.lang.IllegalStateException
518 	 *             if the combination of directory, gitDir and bare is illegal.
519 	 *             E.g. if for a non-bare repository directory and gitDir point
520 	 *             to the same directory of if for a bare repository both
521 	 *             directory and gitDir are specified
522 	 */
523 	public CloneCommand setBare(boolean bare) throws IllegalStateException {
524 		validateDirs(directory, gitDir, bare);
525 		this.bare = bare;
526 		return this;
527 	}
528 
529 	/**
530 	 * Set the file system abstraction to be used for repositories created by
531 	 * this command.
532 	 *
533 	 * @param fs
534 	 *            the abstraction.
535 	 * @return {@code this} (for chaining calls).
536 	 * @since 4.10
537 	 */
538 	public CloneCommand setFs(FS fs) {
539 		this.fs = fs;
540 		return this;
541 	}
542 
543 	/**
544 	 * The remote name used to keep track of the upstream repository for the
545 	 * clone operation. If no remote name is set, the default value of
546 	 * <code>Constants.DEFAULT_REMOTE_NAME</code> will be used.
547 	 *
548 	 * @see Constants#DEFAULT_REMOTE_NAME
549 	 * @param remote
550 	 *            name that keeps track of the upstream repository.
551 	 *            {@code null} means to use DEFAULT_REMOTE_NAME.
552 	 * @return this instance
553 	 */
554 	public CloneCommand setRemote(String remote) {
555 		if (remote == null) {
556 			remote = Constants.DEFAULT_REMOTE_NAME;
557 		}
558 		this.remote = remote;
559 		return this;
560 	}
561 
562 	/**
563 	 * Set the initial branch
564 	 *
565 	 * @param branch
566 	 *            the initial branch to check out when cloning the repository.
567 	 *            Can be specified as ref name (<code>refs/heads/master</code>),
568 	 *            branch name (<code>master</code>) or tag name
569 	 *            (<code>v1.2.3</code>). The default is to use the branch
570 	 *            pointed to by the cloned repository's HEAD and can be
571 	 *            requested by passing {@code null} or <code>HEAD</code>.
572 	 * @return this instance
573 	 */
574 	public CloneCommand setBranch(String branch) {
575 		if (branch == null) {
576 			branch = Constants.HEAD;
577 		}
578 		this.branch = branch;
579 		return this;
580 	}
581 
582 	/**
583 	 * The progress monitor associated with the clone operation. By default,
584 	 * this is set to <code>NullProgressMonitor</code>
585 	 *
586 	 * @see NullProgressMonitor
587 	 * @param monitor
588 	 *            a {@link org.eclipse.jgit.lib.ProgressMonitor}
589 	 * @return {@code this}
590 	 */
591 	public CloneCommand setProgressMonitor(ProgressMonitor monitor) {
592 		if (monitor == null) {
593 			monitor = NullProgressMonitor.INSTANCE;
594 		}
595 		this.monitor = monitor;
596 		return this;
597 	}
598 
599 	/**
600 	 * Set whether all branches have to be fetched.
601 	 * <p>
602 	 * If {@code false}, use {@link #setBranchesToClone(Collection)} to define
603 	 * what will be cloned. If neither are set, all branches will be cloned.
604 	 * </p>
605 	 *
606 	 * @param cloneAllBranches
607 	 *            {@code true} when all branches have to be fetched (indicates
608 	 *            wildcard in created fetch refspec), {@code false} otherwise.
609 	 * @return {@code this}
610 	 */
611 	public CloneCommand setCloneAllBranches(boolean cloneAllBranches) {
612 		this.cloneAllBranches = cloneAllBranches;
613 		return this;
614 	}
615 
616 	/**
617 	 * Set whether to clone submodules
618 	 *
619 	 * @param cloneSubmodules
620 	 *            true to initialize and update submodules. Ignored when
621 	 *            {@link #setBare(boolean)} is set to true.
622 	 * @return {@code this}
623 	 */
624 	public CloneCommand setCloneSubmodules(boolean cloneSubmodules) {
625 		this.cloneSubmodules = cloneSubmodules;
626 		return this;
627 	}
628 
629 	/**
630 	 * Set the branches or tags to clone.
631 	 * <p>
632 	 * This is ignored if {@link #setCloneAllBranches(boolean)
633 	 * setCloneAllBranches(true)} is used. If {@code branchesToClone} is
634 	 * {@code null} or empty, it's also ignored and all branches will be cloned.
635 	 * </p>
636 	 *
637 	 * @param branchesToClone
638 	 *            collection of branches to clone. Must be specified as full ref
639 	 *            names (e.g. {@code refs/heads/master} or
640 	 *            {@code refs/tags/v1.0.0}).
641 	 * @return {@code this}
642 	 */
643 	public CloneCommand setBranchesToClone(Collection<String> branchesToClone) {
644 		this.branchesToClone = branchesToClone;
645 		return this;
646 	}
647 
648 	/**
649 	 * Set whether to skip checking out a branch
650 	 *
651 	 * @param noCheckout
652 	 *            if set to <code>true</code> no branch will be checked out
653 	 *            after the clone. This enhances performance of the clone
654 	 *            command when there is no need for a checked out branch.
655 	 * @return {@code this}
656 	 */
657 	public CloneCommand setNoCheckout(boolean noCheckout) {
658 		this.noCheckout = noCheckout;
659 		return this;
660 	}
661 
662 	/**
663 	 * Register a progress callback.
664 	 *
665 	 * @param callback
666 	 *            the callback
667 	 * @return {@code this}
668 	 * @since 4.8
669 	 */
670 	public CloneCommand setCallback(Callback callback) {
671 		this.callback = callback;
672 		return this;
673 	}
674 
675 	private static void validateDirs(File directory, File gitDir, boolean bare)
676 			throws IllegalStateException {
677 		if (directory != null) {
678 			if (directory.exists() && !directory.isDirectory()) {
679 				throw new IllegalStateException(MessageFormat.format(
680 						JGitText.get().initFailedDirIsNoDirectory, directory));
681 			}
682 			if (gitDir != null && gitDir.exists() && !gitDir.isDirectory()) {
683 				throw new IllegalStateException(MessageFormat.format(
684 						JGitText.get().initFailedGitDirIsNoDirectory,
685 						gitDir));
686 			}
687 			if (bare) {
688 				if (gitDir != null && !gitDir.equals(directory))
689 					throw new IllegalStateException(MessageFormat.format(
690 							JGitText.get().initFailedBareRepoDifferentDirs,
691 							gitDir, directory));
692 			} else {
693 				if (gitDir != null && gitDir.equals(directory))
694 					throw new IllegalStateException(MessageFormat.format(
695 							JGitText.get().initFailedNonBareRepoSameDirs,
696 							gitDir, directory));
697 			}
698 		}
699 	}
700 
701 	private void cleanup() {
702 		try {
703 			if (directory != null) {
704 				if (!directoryExistsInitially) {
705 					FileUtils.delete(directory, FileUtils.RECURSIVE
706 							| FileUtils.SKIP_MISSING | FileUtils.IGNORE_ERRORS);
707 				} else {
708 					deleteChildren(directory);
709 				}
710 			}
711 			if (gitDir != null) {
712 				if (!gitDirExistsInitially) {
713 					FileUtils.delete(gitDir, FileUtils.RECURSIVE
714 							| FileUtils.SKIP_MISSING | FileUtils.IGNORE_ERRORS);
715 				} else {
716 					deleteChildren(gitDir);
717 				}
718 			}
719 		} catch (IOException e) {
720 			// Ignore; this is a best-effort cleanup in error cases, and
721 			// IOException should not be raised anyway
722 		}
723 	}
724 
725 	private void deleteChildren(File file) throws IOException {
726 		File[] files = file.listFiles();
727 		if (files == null) {
728 			return;
729 		}
730 		for (File child : files) {
731 			FileUtils.delete(child, FileUtils.RECURSIVE | FileUtils.SKIP_MISSING
732 					| FileUtils.IGNORE_ERRORS);
733 		}
734 	}
735 }