ObjectIdHandler.java

  1. /*
  2.  * Copyright (C) 2009, Google Inc.
  3.  * Copyright (C) 2008, Shawn O. Pearce <spearce@spearce.org> and others
  4.  *
  5.  * This program and the accompanying materials are made available under the
  6.  * terms of the Eclipse Distribution License v. 1.0 which is available at
  7.  * https://www.eclipse.org/org/documents/edl-v10.php.
  8.  *
  9.  * SPDX-License-Identifier: BSD-3-Clause
  10.  */

  11. package org.eclipse.jgit.pgm.opt;

  12. import java.io.IOException;

  13. import org.eclipse.jgit.lib.ObjectId;
  14. import org.eclipse.jgit.pgm.internal.CLIText;
  15. import org.kohsuke.args4j.CmdLineException;
  16. import org.kohsuke.args4j.CmdLineParser;
  17. import org.kohsuke.args4j.OptionDef;
  18. import org.kohsuke.args4j.spi.OptionHandler;
  19. import org.kohsuke.args4j.spi.Parameters;
  20. import org.kohsuke.args4j.spi.Setter;

  21. /**
  22.  * Custom argument handler {@link org.eclipse.jgit.lib.ObjectId} from string
  23.  * values.
  24.  * <p>
  25.  * Assumes the parser has been initialized with a Repository.
  26.  */
  27. public class ObjectIdHandler extends OptionHandler<ObjectId> {
  28.     private final org.eclipse.jgit.pgm.opt.CmdLineParser clp;

  29.     /**
  30.      * Create a new handler for the command name.
  31.      * <p>
  32.      * This constructor is used only by args4j.
  33.      *
  34.      * @param parser
  35.      *            a {@link org.kohsuke.args4j.CmdLineParser} object.
  36.      * @param option
  37.      *            a {@link org.kohsuke.args4j.OptionDef} object.
  38.      * @param setter
  39.      *            a {@link org.kohsuke.args4j.spi.Setter} object.
  40.      */
  41.     public ObjectIdHandler(final CmdLineParser parser, final OptionDef option,
  42.             final Setter<? super ObjectId> setter) {
  43.         super(parser, option, setter);
  44.         clp = (org.eclipse.jgit.pgm.opt.CmdLineParser) parser;
  45.     }

  46.     /** {@inheritDoc} */
  47.     @Override
  48.     public int parseArguments(Parameters params) throws CmdLineException {
  49.         final String name = params.getParameter(0);
  50.         final ObjectId id;
  51.         try {
  52.             id = clp.getRepository().resolve(name);
  53.         } catch (IOException e) {
  54.             throw new CmdLineException(clp, CLIText.format(e.getMessage()));
  55.         }
  56.         if (id != null) {
  57.             setter.addValue(id);
  58.             return 1;
  59.         }

  60.         throw new CmdLineException(clp,
  61.                 CLIText.format(CLIText.get().notAnObject), name);
  62.     }

  63.     /** {@inheritDoc} */
  64.     @Override
  65.     public String getDefaultMetaVariable() {
  66.         return CLIText.get().metaVar_object;
  67.     }
  68. }