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