Merge branch 'ref-abstract'
[jgit.git] / org.eclipse.jgit.pgm / src / org / eclipse / jgit / pgm / Clone.java
bloba6c50ff19a979e4e526571375da3d7febd8b2c0a
1 /*
2 * Copyright (C) 2008-2010, Google Inc.
3 * and other copyright owners as documented in the project's IP log.
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
10 * All rights reserved.
12 * Redistribution and use in source and binary forms, with or
13 * without modification, are permitted provided that the following
14 * conditions are met:
16 * - Redistributions of source code must retain the above copyright
17 * notice, this list of conditions and the following disclaimer.
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.
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.
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.
44 package org.eclipse.jgit.pgm;
46 import java.io.File;
47 import java.io.IOException;
48 import java.net.URISyntaxException;
49 import java.util.ArrayList;
50 import java.util.Collections;
51 import java.util.List;
53 import org.kohsuke.args4j.Argument;
54 import org.kohsuke.args4j.Option;
55 import org.eclipse.jgit.errors.NotSupportedException;
56 import org.eclipse.jgit.errors.TransportException;
57 import org.eclipse.jgit.lib.Commit;
58 import org.eclipse.jgit.lib.Constants;
59 import org.eclipse.jgit.lib.GitIndex;
60 import org.eclipse.jgit.lib.Ref;
61 import org.eclipse.jgit.lib.RefComparator;
62 import org.eclipse.jgit.lib.RefUpdate;
63 import org.eclipse.jgit.lib.Repository;
64 import org.eclipse.jgit.lib.TextProgressMonitor;
65 import org.eclipse.jgit.lib.Tree;
66 import org.eclipse.jgit.lib.WorkDirCheckout;
67 import org.eclipse.jgit.transport.FetchResult;
68 import org.eclipse.jgit.transport.RefSpec;
69 import org.eclipse.jgit.transport.RemoteConfig;
70 import org.eclipse.jgit.transport.Transport;
71 import org.eclipse.jgit.transport.URIish;
73 @Command(common = true, usage = "Clone a repository into a new directory")
74 class Clone extends AbstractFetchCommand {
75 @Option(name = "--origin", aliases = { "-o" }, metaVar = "name", usage = "use <name> instead of 'origin' to track upstream")
76 private String remoteName = Constants.DEFAULT_REMOTE_NAME;
78 @Argument(index = 0, required = true, metaVar = "uri-ish")
79 private String sourceUri;
81 @Argument(index = 1, metaVar = "directory")
82 private String localName;
84 @Override
85 protected final boolean requiresRepository() {
86 return false;
89 @Override
90 protected void run() throws Exception {
91 if (localName != null && gitdir != null)
92 throw die("conflicting usage of --git-dir and arguments");
94 final URIish uri = new URIish(sourceUri);
95 if (localName == null) {
96 try {
97 localName = uri.getHumanishName();
98 } catch (IllegalArgumentException e) {
99 throw die("cannot guess local name from " + sourceUri);
102 if (gitdir == null)
103 gitdir = new File(localName, Constants.DOT_GIT);
105 db = new Repository(gitdir);
106 db.create();
107 db.getConfig().setBoolean("core", null, "bare", false);
108 db.getConfig().save();
110 out.println("Initialized empty Git repository in "
111 + gitdir.getAbsolutePath());
112 out.flush();
114 saveRemote(uri);
115 final FetchResult r = runFetch();
116 final Ref branch = guessHEAD(r);
117 doCheckout(branch);
120 private void saveRemote(final URIish uri) throws URISyntaxException,
121 IOException {
122 final RemoteConfig rc = new RemoteConfig(db.getConfig(), remoteName);
123 rc.addURI(uri);
124 rc.addFetchRefSpec(new RefSpec().setForceUpdate(true)
125 .setSourceDestination(Constants.R_HEADS + "*",
126 Constants.R_REMOTES + remoteName + "/*"));
127 rc.update(db.getConfig());
128 db.getConfig().save();
131 private FetchResult runFetch() throws NotSupportedException,
132 URISyntaxException, TransportException {
133 final Transport tn = Transport.open(db, remoteName);
134 final FetchResult r;
135 try {
136 r = tn.fetch(new TextProgressMonitor(), null);
137 } finally {
138 tn.close();
140 showFetchResult(tn, r);
141 return r;
144 private Ref guessHEAD(final FetchResult result) {
145 final Ref idHEAD = result.getAdvertisedRef(Constants.HEAD);
146 final List<Ref> availableRefs = new ArrayList<Ref>();
147 Ref head = null;
148 for (final Ref r : result.getAdvertisedRefs()) {
149 final String n = r.getName();
150 if (!n.startsWith(Constants.R_HEADS))
151 continue;
152 availableRefs.add(r);
153 if (idHEAD == null || head != null)
154 continue;
155 if (r.getObjectId().equals(idHEAD.getObjectId()))
156 head = r;
158 Collections.sort(availableRefs, RefComparator.INSTANCE);
159 if (idHEAD != null && head == null)
160 head = idHEAD;
161 return head;
164 private void doCheckout(final Ref branch) throws IOException {
165 if (branch == null)
166 throw die("cannot checkout; no HEAD advertised by remote");
167 if (!Constants.HEAD.equals(branch.getName())) {
168 RefUpdate u = db.updateRef(Constants.HEAD);
169 u.disableRefLog();
170 u.link(branch.getName());
173 final Commit commit = db.mapCommit(branch.getObjectId());
174 final RefUpdate u = db.updateRef(Constants.HEAD);
175 u.setNewObjectId(commit.getCommitId());
176 u.forceUpdate();
178 final GitIndex index = new GitIndex(db);
179 final Tree tree = commit.getTree();
180 final WorkDirCheckout co;
182 co = new WorkDirCheckout(db, db.getWorkDir(), index, tree);
183 co.checkout();
184 index.write();