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