View Javadoc
1   /*
2    * Copyright (C) 2011, 2021 IBM Corporation and others
3    *
4    * This program and the accompanying materials are made available under the
5    * terms of the Eclipse Distribution License v. 1.0 which is available at
6    * https://www.eclipse.org/org/documents/edl-v10.php.
7    *
8    * SPDX-License-Identifier: BSD-3-Clause
9    */
10  package org.eclipse.jgit.api;
11  
12  import java.io.File;
13  import java.io.InputStream;
14  import org.eclipse.jgit.api.errors.GitAPIException;
15  import org.eclipse.jgit.internal.JGitText;
16  import org.eclipse.jgit.lib.Repository;
17  import org.eclipse.jgit.patch.PatchApplier;
18  import org.eclipse.jgit.patch.PatchApplier.Result;
19  
20  /**
21   * Apply a patch to files and/or to the index.
22   *
23   * @see <a href="http://www.kernel.org/pub/software/scm/git/docs/git-apply.html"
24   *      >Git documentation about apply</a>
25   * @since 2.0
26   */
27  public class ApplyCommand extends GitCommand<ApplyResult> {
28  
29  	private InputStream in;
30  
31  	/**
32  	 * Constructs the command.
33  	 *
34  	 * @param local
35  	 */
36  	ApplyCommand(Repository local) {
37  		super(local);
38  		if (local == null) {
39  			throw new NullPointerException(JGitText.get().repositoryIsRequired);
40  		}
41  	}
42  
43  	/**
44  	 * Set patch
45  	 *
46  	 * @param in
47  	 *            the patch to apply
48  	 * @return this instance
49  	 */
50  	public ApplyCommand setPatch(InputStream in) {
51  		checkCallable();
52  		this.in = in;
53  		return this;
54  	}
55  
56  	/**
57  	 * {@inheritDoc}
58  	 *
59  	 * <p>
60  	 * Executes the {@code ApplyCommand} command with all the options and
61  	 * parameters collected by the setter methods (e.g.
62  	 * {@link #setPatch(InputStream)} of this class. Each instance of this class
63  	 * should only be used for one invocation of the command. Don't call this
64  	 * method twice on an instance.
65  	 */
66  	@Override
67  	public ApplyResult call() throws GitAPIException {
68  		checkCallable();
69  		setCallable(false);
70  		ApplyResult r = new ApplyResult();
71  		PatchApplier patchApplier = new PatchApplier(repo);
72  		Result applyResult = patchApplier.applyPatch(in);
73  		for (String p : applyResult.getPaths()) {
74  			r.addUpdatedFile(new File(repo.getWorkTree(), p));
75  		}
76  		return r;
77  	}
78  }