View Javadoc
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  
12  package org.eclipse.jgit.pgm.opt;
13  
14  import java.io.IOException;
15  
16  import org.eclipse.jgit.lib.ObjectId;
17  import org.eclipse.jgit.pgm.internal.CLIText;
18  import org.kohsuke.args4j.CmdLineException;
19  import org.kohsuke.args4j.CmdLineParser;
20  import org.kohsuke.args4j.OptionDef;
21  import org.kohsuke.args4j.spi.OptionHandler;
22  import org.kohsuke.args4j.spi.Parameters;
23  import org.kohsuke.args4j.spi.Setter;
24  
25  /**
26   * Custom argument handler {@link org.eclipse.jgit.lib.ObjectId} from string
27   * values.
28   * <p>
29   * Assumes the parser has been initialized with a Repository.
30   */
31  public class ObjectIdHandler extends OptionHandler<ObjectId> {
32  	private final org.eclipse.jgit.pgm.opt.CmdLineParser clp;
33  
34  	/**
35  	 * Create a new handler for the command name.
36  	 * <p>
37  	 * This constructor is used only by args4j.
38  	 *
39  	 * @param parser
40  	 *            a {@link org.kohsuke.args4j.CmdLineParser} object.
41  	 * @param option
42  	 *            a {@link org.kohsuke.args4j.OptionDef} object.
43  	 * @param setter
44  	 *            a {@link org.kohsuke.args4j.spi.Setter} object.
45  	 */
46  	public ObjectIdHandler(final CmdLineParser parser, final OptionDef option,
47  			final Setter<? super ObjectId> setter) {
48  		super(parser, option, setter);
49  		clp = (org.eclipse.jgit.pgm.opt.CmdLineParser) parser;
50  	}
51  
52  	/** {@inheritDoc} */
53  	@Override
54  	public int parseArguments(Parameters params) throws CmdLineException {
55  		final String name = params.getParameter(0);
56  		final ObjectId id;
57  		try {
58  			id = clp.getRepository().resolve(name);
59  		} catch (IOException e) {
60  			throw new CmdLineException(clp, CLIText.format(e.getMessage()));
61  		}
62  		if (id != null) {
63  			setter.addValue(id);
64  			return 1;
65  		}
66  
67  		throw new CmdLineException(clp,
68  				CLIText.format(CLIText.get().notAnObject), name);
69  	}
70  
71  	/** {@inheritDoc} */
72  	@Override
73  	public String getDefaultMetaVariable() {
74  		return CLIText.get().metaVar_object;
75  	}
76  }