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 href=
73   *      "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 name;
80  
81  	private String path;
82  
83  	private String uri;
84  
85  	private ProgressMonitor monitor;
86  
87  	/**
88  	 * Constructor for SubmoduleAddCommand.
89  	 *
90  	 * @param repo
91  	 *            a {@link org.eclipse.jgit.lib.Repository} object.
92  	 */
93  	public SubmoduleAddCommand(Repository repo) {
94  		super(repo);
95  	}
96  
97  	/**
98  	 * Set the submodule name
99  	 *
100 	 * @param name
101 	 * @return this command
102 	 * @since 5.1
103 	 */
104 	public SubmoduleAddCommand setName(String name) {
105 		this.name = name;
106 		return this;
107 	}
108 
109 	/**
110 	 * Set repository-relative path of submodule
111 	 *
112 	 * @param path
113 	 *            (with <code>/</code> as separator)
114 	 * @return this command
115 	 */
116 	public SubmoduleAddCommand setPath(String path) {
117 		this.path = path;
118 		return this;
119 	}
120 
121 	/**
122 	 * Set URI to clone submodule from
123 	 *
124 	 * @param uri
125 	 *            a {@link java.lang.String} object.
126 	 * @return this command
127 	 */
128 	public SubmoduleAddCommand setURI(String uri) {
129 		this.uri = uri;
130 		return this;
131 	}
132 
133 	/**
134 	 * The progress monitor associated with the clone operation. By default,
135 	 * this is set to <code>NullProgressMonitor</code>
136 	 *
137 	 * @see NullProgressMonitor
138 	 * @param monitor
139 	 *            a {@link org.eclipse.jgit.lib.ProgressMonitor} object.
140 	 * @return this command
141 	 */
142 	public SubmoduleAddCommand setProgressMonitor(ProgressMonitor monitor) {
143 		this.monitor = monitor;
144 		return this;
145 	}
146 
147 	/**
148 	 * Is the configured already a submodule in the index?
149 	 *
150 	 * @return true if submodule exists in index, false otherwise
151 	 * @throws java.io.IOException
152 	 */
153 	protected boolean submoduleExists() throws IOException {
154 		TreeFilter filter = PathFilter.create(path);
155 		try (SubmoduleWalk w = SubmoduleWalk.forIndex(repo)) {
156 			return w.setFilter(filter).next();
157 		}
158 	}
159 
160 	/**
161 	 * {@inheritDoc}
162 	 * <p>
163 	 * Executes the {@code SubmoduleAddCommand}
164 	 *
165 	 * The {@code Repository} instance returned by this command needs to be
166 	 * closed by the caller to free resources held by the {@code Repository}
167 	 * instance. It is recommended to call this method as soon as you don't need
168 	 * a reference to this {@code Repository} instance anymore.
169 	 */
170 	@Override
171 	public Repository call() throws GitAPIException {
172 		checkCallable();
173 		if (path == null || path.length() == 0)
174 			throw new IllegalArgumentException(JGitText.get().pathNotConfigured);
175 		if (uri == null || uri.length() == 0)
176 			throw new IllegalArgumentException(JGitText.get().uriNotConfigured);
177 		if (name == null || name.length() == 0) {
178 			// Use the path as the default.
179 			name = path;
180 		}
181 		if (name.contains("/../") || name.contains("\\..\\") //$NON-NLS-1$ //$NON-NLS-2$
182 				|| name.startsWith("../") || name.startsWith("..\\") //$NON-NLS-1$ //$NON-NLS-2$
183 				|| name.endsWith("/..") || name.endsWith("\\..")) { //$NON-NLS-1$ //$NON-NLS-2$
184 			// Submodule names are used to store the submodule repositories
185 			// under $GIT_DIR/modules. Having ".." in submodule names makes a
186 			// vulnerability (CVE-2018-11235
187 			// https://bugs.eclipse.org/bugs/show_bug.cgi?id=535027#c0)
188 			// Reject the names with them. The callers need to make sure the
189 			// names free from these. We don't automatically replace these
190 			// characters or canonicalize by regarding the name as a file path.
191 			// Since Path class is platform dependent, we manually check '/' and
192 			// '\\' patterns here.
193 			throw new IllegalArgumentException(MessageFormat
194 					.format(JGitText.get().invalidNameContainsDotDot, name));
195 		}
196 
197 		try {
198 			if (submoduleExists())
199 				throw new JGitInternalException(MessageFormat.format(
200 						JGitText.get().submoduleExists, path));
201 		} catch (IOException e) {
202 			throw new JGitInternalException(e.getMessage(), e);
203 		}
204 
205 		final String resolvedUri;
206 		try {
207 			resolvedUri = SubmoduleWalk.getSubmoduleRemoteUrl(repo, uri);
208 		} catch (IOException e) {
209 			throw new JGitInternalException(e.getMessage(), e);
210 		}
211 		// Clone submodule repository
212 		File moduleDirectory = SubmoduleWalk.getSubmoduleDirectory(repo, path);
213 		CloneCommand clone = Git.cloneRepository();
214 		configure(clone);
215 		clone.setDirectory(moduleDirectory);
216 		clone.setGitDir(new File(new File(repo.getDirectory(),
217 				Constants.MODULES), path));
218 		clone.setURI(resolvedUri);
219 		if (monitor != null)
220 			clone.setProgressMonitor(monitor);
221 		Repository subRepo = null;
222 		try (Git git = clone.call()) {
223 			subRepo = git.getRepository();
224 			subRepo.incrementOpen();
225 		}
226 
227 		// Save submodule URL to parent repository's config
228 		StoredConfig config = repo.getConfig();
229 		config.setString(ConfigConstants.CONFIG_SUBMODULE_SECTION, name,
230 				ConfigConstants.CONFIG_KEY_URL, resolvedUri);
231 		try {
232 			config.save();
233 		} catch (IOException e) {
234 			throw new JGitInternalException(e.getMessage(), e);
235 		}
236 
237 		// Save path and URL to parent repository's .gitmodules file
238 		FileBasedConfig modulesConfig = new FileBasedConfig(new File(
239 				repo.getWorkTree(), Constants.DOT_GIT_MODULES), repo.getFS());
240 		try {
241 			modulesConfig.load();
242 			modulesConfig.setString(ConfigConstants.CONFIG_SUBMODULE_SECTION,
243 					name, ConfigConstants.CONFIG_KEY_PATH, path);
244 			modulesConfig.setString(ConfigConstants.CONFIG_SUBMODULE_SECTION,
245 					name, ConfigConstants.CONFIG_KEY_URL, uri);
246 			modulesConfig.save();
247 		} catch (IOException e) {
248 			throw new JGitInternalException(e.getMessage(), e);
249 		} catch (ConfigInvalidException e) {
250 			throw new JGitInternalException(e.getMessage(), e);
251 		}
252 
253 		AddCommand add = new AddCommand(repo);
254 		// Add .gitmodules file to parent repository's index
255 		add.addFilepattern(Constants.DOT_GIT_MODULES);
256 		// Add submodule directory to parent repository's index
257 		add.addFilepattern(path);
258 		try {
259 			add.call();
260 		} catch (NoFilepatternException e) {
261 			throw new JGitInternalException(e.getMessage(), e);
262 		}
263 
264 		return subRepo;
265 	}
266 }