View Javadoc
1   /*
2    * Copyright (C) 2011, GitHub Inc.
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.text.MessageFormat;
48  
49  import org.eclipse.jgit.api.errors.GitAPIException;
50  import org.eclipse.jgit.api.errors.JGitInternalException;
51  import org.eclipse.jgit.api.errors.NoFilepatternException;
52  import org.eclipse.jgit.errors.ConfigInvalidException;
53  import org.eclipse.jgit.internal.JGitText;
54  import org.eclipse.jgit.lib.ConfigConstants;
55  import org.eclipse.jgit.lib.Constants;
56  import org.eclipse.jgit.lib.NullProgressMonitor;
57  import org.eclipse.jgit.lib.ProgressMonitor;
58  import org.eclipse.jgit.lib.Repository;
59  import org.eclipse.jgit.lib.StoredConfig;
60  import org.eclipse.jgit.storage.file.FileBasedConfig;
61  import org.eclipse.jgit.submodule.SubmoduleWalk;
62  import org.eclipse.jgit.treewalk.filter.PathFilter;
63  import org.eclipse.jgit.treewalk.filter.TreeFilter;
64  
65  /**
66   * A class used to execute a submodule add command.
67   *
68   * This will clone the configured submodule, register the submodule in the
69   * .gitmodules file and the repository config file, and also add the submodule
70   * and .gitmodules file to the index.
71   *
72   * @see <a
73   *      href="http://www.kernel.org/pub/software/scm/git/docs/git-submodule.html"
74   *      >Git documentation about submodules</a>
75   */
76  public class SubmoduleAddCommand extends
77  		TransportCommand<SubmoduleAddCommand, Repository> {
78  
79  	private String path;
80  
81  	private String uri;
82  
83  	private ProgressMonitor monitor;
84  
85  	/**
86  	 * @param repo
87  	 */
88  	public SubmoduleAddCommand(final Repository repo) {
89  		super(repo);
90  	}
91  
92  	/**
93  	 * Set repository-relative path of submodule
94  	 *
95  	 * @param path
96  	 *            (with <code>/</code> as separator)
97  	 * @return this command
98  	 */
99  	public SubmoduleAddCommand setPath(final String path) {
100 		this.path = path;
101 		return this;
102 	}
103 
104 	/**
105 	 * Set URI to clone submodule from
106 	 *
107 	 * @param uri
108 	 * @return this command
109 	 */
110 	public SubmoduleAddCommand setURI(final String uri) {
111 		this.uri = uri;
112 		return this;
113 	}
114 
115 	/**
116 	 * The progress monitor associated with the clone operation. By default,
117 	 * this is set to <code>NullProgressMonitor</code>
118 	 *
119 	 * @see NullProgressMonitor
120 	 * @param monitor
121 	 * @return this command
122 	 */
123 	public SubmoduleAddCommand setProgressMonitor(final ProgressMonitor monitor) {
124 		this.monitor = monitor;
125 		return this;
126 	}
127 
128 	/**
129 	 * Is the configured already a submodule in the index?
130 	 *
131 	 * @return true if submodule exists in index, false otherwise
132 	 * @throws IOException
133 	 */
134 	protected boolean submoduleExists() throws IOException {
135 		TreeFilter filter = PathFilter.create(path);
136 		return SubmoduleWalk.forIndex(repo).setFilter(filter).next();
137 	}
138 
139 	/**
140 	 * Executes the {@code SubmoduleAddCommand}
141 	 *
142 	 * The {@code Repository} instance returned by this command needs to be
143 	 * closed by the caller to free resources held by the {@code Repository}
144 	 * instance. It is recommended to call this method as soon as you don't need
145 	 * a reference to this {@code Repository} instance anymore.
146 	 *
147 	 * @return the newly created {@link Repository}
148 	 * @throws GitAPIException
149 	 */
150 	public Repository call() throws GitAPIException {
151 		checkCallable();
152 		if (path == null || path.length() == 0)
153 			throw new IllegalArgumentException(JGitText.get().pathNotConfigured);
154 		if (uri == null || uri.length() == 0)
155 			throw new IllegalArgumentException(JGitText.get().uriNotConfigured);
156 
157 		try {
158 			if (submoduleExists())
159 				throw new JGitInternalException(MessageFormat.format(
160 						JGitText.get().submoduleExists, path));
161 		} catch (IOException e) {
162 			throw new JGitInternalException(e.getMessage(), e);
163 		}
164 
165 		final String resolvedUri;
166 		try {
167 			resolvedUri = SubmoduleWalk.getSubmoduleRemoteUrl(repo, uri);
168 		} catch (IOException e) {
169 			throw new JGitInternalException(e.getMessage(), e);
170 		}
171 		// Clone submodule repository
172 		File moduleDirectory = SubmoduleWalk.getSubmoduleDirectory(repo, path);
173 		CloneCommand clone = Git.cloneRepository();
174 		configure(clone);
175 		clone.setDirectory(moduleDirectory);
176 		clone.setGitDir(new File(new File(repo.getDirectory(),
177 				Constants.MODULES), path));
178 		clone.setURI(resolvedUri);
179 		if (monitor != null)
180 			clone.setProgressMonitor(monitor);
181 		Repository subRepo = clone.call().getRepository();
182 
183 		// Save submodule URL to parent repository's config
184 		StoredConfig config = repo.getConfig();
185 		config.setString(ConfigConstants.CONFIG_SUBMODULE_SECTION, path,
186 				ConfigConstants.CONFIG_KEY_URL, resolvedUri);
187 		try {
188 			config.save();
189 		} catch (IOException e) {
190 			throw new JGitInternalException(e.getMessage(), e);
191 		}
192 
193 		// Save path and URL to parent repository's .gitmodules file
194 		FileBasedConfig modulesConfig = new FileBasedConfig(new File(
195 				repo.getWorkTree(), Constants.DOT_GIT_MODULES), repo.getFS());
196 		try {
197 			modulesConfig.load();
198 			modulesConfig.setString(ConfigConstants.CONFIG_SUBMODULE_SECTION,
199 					path, ConfigConstants.CONFIG_KEY_PATH, path);
200 			modulesConfig.setString(ConfigConstants.CONFIG_SUBMODULE_SECTION,
201 					path, ConfigConstants.CONFIG_KEY_URL, uri);
202 			modulesConfig.save();
203 		} catch (IOException e) {
204 			throw new JGitInternalException(e.getMessage(), e);
205 		} catch (ConfigInvalidException e) {
206 			throw new JGitInternalException(e.getMessage(), e);
207 		}
208 
209 		AddCommand add = new AddCommand(repo);
210 		// Add .gitmodules file to parent repository's index
211 		add.addFilepattern(Constants.DOT_GIT_MODULES);
212 		// Add submodule directory to parent repository's index
213 		add.addFilepattern(path);
214 		try {
215 			add.call();
216 		} catch (NoFilepatternException e) {
217 			throw new JGitInternalException(e.getMessage(), e);
218 		}
219 
220 		return subRepo;
221 	}
222 }