Replace a hard-coded default remote's name with a constant
[jgit.git] / org.eclipse.jgit.pgm / src / org / eclipse / jgit / pgm / Clone.java
bloba136df5618761b192824799c91728470232dd890
1 /*
2 * Copyright (C) 2008-2009, 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 String p = uri.getPath();
97 while (p.endsWith("/"))
98 p = p.substring(0, p.length() - 1);
99 final int s = p.lastIndexOf('/');
100 if (s < 0)
101 throw die("cannot guess local name from " + sourceUri);
102 localName = p.substring(s + 1);
103 if (localName.endsWith(".git"))
104 localName = localName.substring(0, localName.length() - 4);
106 if (gitdir == null)
107 gitdir = new File(localName, ".git");
109 db = new Repository(gitdir);
110 db.create();
111 db.getConfig().setBoolean("core", null, "bare", false);
112 db.getConfig().save();
114 out.println("Initialized empty Git repository in "
115 + gitdir.getAbsolutePath());
116 out.flush();
118 saveRemote(uri);
119 final FetchResult r = runFetch();
120 final Ref branch = guessHEAD(r);
121 doCheckout(branch);
124 private void saveRemote(final URIish uri) throws URISyntaxException,
125 IOException {
126 final RemoteConfig rc = new RemoteConfig(db.getConfig(), remoteName);
127 rc.addURI(uri);
128 rc.addFetchRefSpec(new RefSpec().setForceUpdate(true)
129 .setSourceDestination(Constants.R_HEADS + "*",
130 Constants.R_REMOTES + remoteName + "/*"));
131 rc.update(db.getConfig());
132 db.getConfig().save();
135 private FetchResult runFetch() throws NotSupportedException,
136 URISyntaxException, TransportException {
137 final Transport tn = Transport.open(db, remoteName);
138 final FetchResult r;
139 try {
140 r = tn.fetch(new TextProgressMonitor(), null);
141 } finally {
142 tn.close();
144 showFetchResult(tn, r);
145 return r;
148 private Ref guessHEAD(final FetchResult result) {
149 final Ref idHEAD = result.getAdvertisedRef(Constants.HEAD);
150 final List<Ref> availableRefs = new ArrayList<Ref>();
151 Ref head = null;
152 for (final Ref r : result.getAdvertisedRefs()) {
153 final String n = r.getName();
154 if (!n.startsWith(Constants.R_HEADS))
155 continue;
156 availableRefs.add(r);
157 if (idHEAD == null || head != null)
158 continue;
159 if (r.getObjectId().equals(idHEAD.getObjectId()))
160 head = r;
162 Collections.sort(availableRefs, RefComparator.INSTANCE);
163 if (idHEAD != null && head == null)
164 head = idHEAD;
165 return head;
168 private void doCheckout(final Ref branch) throws IOException {
169 if (branch == null)
170 throw die("cannot checkout; no HEAD advertised by remote");
171 if (!Constants.HEAD.equals(branch.getName()))
172 db.writeSymref(Constants.HEAD, branch.getName());
174 final Commit commit = db.mapCommit(branch.getObjectId());
175 final RefUpdate u = db.updateRef(Constants.HEAD);
176 u.setNewObjectId(commit.getCommitId());
177 u.forceUpdate();
179 final GitIndex index = new GitIndex(db);
180 final Tree tree = commit.getTree();
181 final WorkDirCheckout co;
183 co = new WorkDirCheckout(db, db.getWorkDir(), index, tree);
184 co.checkout();
185 index.write();