ApplyCommand.java

  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. import java.io.File;
  12. import java.io.InputStream;
  13. import org.eclipse.jgit.api.errors.GitAPIException;
  14. import org.eclipse.jgit.internal.JGitText;
  15. import org.eclipse.jgit.lib.Repository;
  16. import org.eclipse.jgit.patch.PatchApplier;
  17. import org.eclipse.jgit.patch.PatchApplier.Result;

  18. /**
  19.  * Apply a patch to files and/or to the index.
  20.  *
  21.  * @see <a href="http://www.kernel.org/pub/software/scm/git/docs/git-apply.html"
  22.  *      >Git documentation about apply</a>
  23.  * @since 2.0
  24.  */
  25. public class ApplyCommand extends GitCommand<ApplyResult> {

  26.     private InputStream in;

  27.     /**
  28.      * Constructs the command.
  29.      *
  30.      * @param local
  31.      */
  32.     ApplyCommand(Repository local) {
  33.         super(local);
  34.         if (local == null) {
  35.             throw new NullPointerException(JGitText.get().repositoryIsRequired);
  36.         }
  37.     }

  38.     /**
  39.      * Set patch
  40.      *
  41.      * @param in
  42.      *            the patch to apply
  43.      * @return this instance
  44.      */
  45.     public ApplyCommand setPatch(InputStream in) {
  46.         checkCallable();
  47.         this.in = in;
  48.         return this;
  49.     }

  50.     /**
  51.      * {@inheritDoc}
  52.      *
  53.      * <p>
  54.      * Executes the {@code ApplyCommand} command with all the options and
  55.      * parameters collected by the setter methods (e.g.
  56.      * {@link #setPatch(InputStream)} of this class. Each instance of this class
  57.      * should only be used for one invocation of the command. Don't call this
  58.      * method twice on an instance.
  59.      */
  60.     @Override
  61.     public ApplyResult call() throws GitAPIException {
  62.         checkCallable();
  63.         setCallable(false);
  64.         ApplyResult r = new ApplyResult();
  65.         PatchApplier patchApplier = new PatchApplier(repo);
  66.         Result applyResult = patchApplier.applyPatch(in);
  67.         for (String p : applyResult.getPaths()) {
  68.             r.addUpdatedFile(new File(repo.getWorkTree(), p));
  69.         }
  70.         return r;
  71.     }
  72. }