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