View Javadoc
1   /*
2    * Copyright (C) 2008, Shawn O. Pearce <spearce@spearce.org>
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  
44  package org.eclipse.jgit.pgm;
45  
46  import static org.eclipse.jgit.lib.Constants.CHARSET;
47  
48  import java.io.BufferedReader;
49  import java.io.IOException;
50  import java.io.InputStreamReader;
51  import java.net.URL;
52  import java.util.ArrayList;
53  import java.util.Arrays;
54  import java.util.Collection;
55  import java.util.Comparator;
56  import java.util.Enumeration;
57  import java.util.HashMap;
58  import java.util.Map;
59  import java.util.Vector;
60  
61  /**
62   * List of all commands known by jgit's command line tools.
63   * <p>
64   * Commands are implementations of {@link org.eclipse.jgit.pgm.TextBuiltin},
65   * with an optional {@link org.eclipse.jgit.pgm.Command} class annotation to
66   * insert additional documentation or override the default command name (which
67   * is guessed from the class name).
68   * <p>
69   * Commands may be registered by adding them to a services file in the same JAR
70   * (or classes directory) as the command implementation. The service file name
71   * is <code>META-INF/services/org.eclipse.jgit.pgm.TextBuiltin</code> and it
72   * contains one concrete implementation class name per line.
73   * <p>
74   * Command registration is identical to Java 6's services, however the catalog
75   * uses a lightweight wrapper to delay creating a command instance as much as
76   * possible. This avoids initializing the AWT or SWT GUI toolkits even if the
77   * command's constructor might require them.
78   */
79  public class CommandCatalog {
80  	private static final CommandCatalog INSTANCE = new CommandCatalog();
81  
82  	/**
83  	 * Locate a single command by its user friendly name.
84  	 *
85  	 * @param name
86  	 *            name of the command. Typically in dash-lower-case-form, which
87  	 *            was derived from the DashLowerCaseForm class name.
88  	 * @return the command instance; null if no command exists by that name.
89  	 */
90  	public static CommandRef get(String name) {
91  		return INSTANCE.commands.get(name);
92  	}
93  
94  	/**
95  	 * Get all commands sorted by their name
96  	 *
97  	 * @return all known commands, sorted by command name.
98  	 */
99  	public static CommandRef[] all() {
100 		return toSortedArray(INSTANCE.commands.values());
101 	}
102 
103 	/**
104 	 * Get all common commands sorted by their name
105 	 *
106 	 * @return all common commands, sorted by command name.
107 	 */
108 	public static CommandRef[] common() {
109 		final ArrayList<CommandRef> common = new ArrayList<>();
110 		for (CommandRef c : INSTANCE.commands.values())
111 			if (c.isCommon())
112 				common.add(c);
113 		return toSortedArray(common);
114 	}
115 
116 	private static CommandRef[] toSortedArray(Collection<CommandRef> c) {
117 		final CommandRef[] r = c.toArray(new CommandRef[c.size()]);
118 		Arrays.sort(r, new Comparator<CommandRef>() {
119 			@Override
120 			public int compare(CommandRef o1, CommandRef o2) {
121 				return o1.getName().compareTo(o2.getName());
122 			}
123 		});
124 		return r;
125 	}
126 
127 	private final ClassLoader ldr;
128 
129 	private final Map<String, CommandRef> commands;
130 
131 	private CommandCatalog() {
132 		ldr = Thread.currentThread().getContextClassLoader();
133 		commands = new HashMap<>();
134 
135 		final Enumeration<URL> catalogs = catalogs();
136 		while (catalogs.hasMoreElements())
137 			scan(catalogs.nextElement());
138 	}
139 
140 	private Enumeration<URL> catalogs() {
141 		try {
142 			final String pfx = "META-INF/services/"; //$NON-NLS-1$
143 			return ldr.getResources(pfx + TextBuiltin.class.getName());
144 		} catch (IOException err) {
145 			return new Vector<URL>().elements();
146 		}
147 	}
148 
149 	private void scan(URL cUrl) {
150 		try (BufferedReader cIn = new BufferedReader(
151 				new InputStreamReader(cUrl.openStream(), CHARSET))) {
152 			String line;
153 			while ((line = cIn.readLine()) != null) {
154 				if (line.length() > 0 && !line.startsWith("#")) //$NON-NLS-1$
155 					load(line);
156 			}
157 		} catch (IOException e) {
158 			// Ignore errors
159 		}
160 	}
161 
162 	private void load(String cn) {
163 		final Class<? extends TextBuiltin> clazz;
164 		try {
165 			clazz = Class.forName(cn, false, ldr).asSubclass(TextBuiltin.class);
166 		} catch (ClassNotFoundException notBuiltin) {
167 			// Doesn't exist, even though the service entry is present.
168 			//
169 			return;
170 		} catch (ClassCastException notBuiltin) {
171 			// Isn't really a builtin, even though its listed as such.
172 			//
173 			return;
174 		}
175 
176 		final CommandRef cr;
177 		final Command a = clazz.getAnnotation(Command.class);
178 		if (a != null)
179 			cr = new CommandRef(clazz, a);
180 		else
181 			cr = new CommandRef(clazz);
182 
183 		commands.put(cr.getName(), cr);
184 	}
185 }