Du kan inte välja fler än 25 ämnen Ämnen måste starta med en bokstav eller siffra, kan innehålla bindestreck ('-') och vara max 35 tecken långa.

CommandLineParser.java 12KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404
  1. /*
  2. * Copyright (c) 2006-2013 DMDirc Developers
  3. *
  4. * Permission is hereby granted, free of charge, to any person obtaining a copy
  5. * of this software and associated documentation files (the "Software"), to deal
  6. * in the Software without restriction, including without limitation the rights
  7. * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
  8. * copies of the Software, and to permit persons to whom the Software is
  9. * furnished to do so, subject to the following conditions:
  10. *
  11. * The above copyright notice and this permission notice shall be included in
  12. * all copies or substantial portions of the Software.
  13. *
  14. * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
  15. * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
  16. * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
  17. * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
  18. * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
  19. * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
  20. * SOFTWARE.
  21. */
  22. package com.dmdirc.commandline;
  23. import com.dmdirc.ServerManager;
  24. import com.dmdirc.commandparser.commands.global.NewServer;
  25. import com.dmdirc.config.IdentityManager;
  26. import com.dmdirc.logger.ErrorLevel;
  27. import com.dmdirc.logger.Logger;
  28. import com.dmdirc.util.resourcemanager.DMDircResourceManager;
  29. import java.io.File;
  30. import java.net.URI;
  31. import java.net.URISyntaxException;
  32. import java.rmi.RemoteException;
  33. import java.util.ArrayList;
  34. import java.util.List;
  35. import javax.inject.Inject;
  36. import javax.inject.Provider;
  37. import javax.inject.Singleton;
  38. /**
  39. * Parses command line arguments for the client.
  40. */
  41. @Singleton
  42. public class CommandLineParser {
  43. /**
  44. * The arguments that the client supports, in groups of four, in the
  45. * following order: short option, long option, description, whether or not
  46. * the option takes an argument.
  47. */
  48. private final Object[][] ARGUMENTS = new Object[][]{
  49. {'c', "connect", "Connect to the specified server", Boolean.TRUE},
  50. {'d', "directory", "Use the specified configuration directory", Boolean.TRUE},
  51. {'e', "existing", "Try to use an existing instance of DMDirc (use with -c)", Boolean.FALSE},
  52. {'h', "help", "Show command line options and exit", Boolean.FALSE},
  53. {'l', "launcher", "Specifies the version of DMDirc's launcher", Boolean.TRUE},
  54. {'p', "portable", "Enable portable mode", Boolean.FALSE},
  55. {'r', "disable-reporting", "Disable automatic error reporting", Boolean.FALSE},
  56. {'v', "version", "Display client version and exit", Boolean.FALSE},
  57. {'k', "check", "Check if an existing instance of DMDirc exists.", Boolean.FALSE},
  58. };
  59. /** A list of addresses to autoconnect to. */
  60. private final List<URI> addresses = new ArrayList<>();
  61. /** Provider to use to get server managers. */
  62. private final Provider<ServerManager> serverManagerProvider;
  63. /** Whether to disable error reporting or not. */
  64. private boolean disablereporting;
  65. /** The version string passed for the launcher. */
  66. private String launcherVersion;
  67. /** The configuration directory. */
  68. private String configDirectory;
  69. /** The RMI server we're using. */
  70. private RemoteInterface server;
  71. /**
  72. * Creates a new instance of CommandLineParser.
  73. */
  74. @Inject
  75. public CommandLineParser(final Provider<ServerManager> serverManagerProvider) {
  76. this.serverManagerProvider = serverManagerProvider;
  77. }
  78. /**
  79. * Parses the given arguments.
  80. *
  81. * @param arguments The arguments to be parsed
  82. */
  83. public void parse(final String ... arguments) {
  84. boolean inArg = false;
  85. char previousArg = '.';
  86. for (String arg : arguments) {
  87. if (inArg) {
  88. processArgument(previousArg, arg);
  89. inArg = false;
  90. } else {
  91. if (arg.startsWith("--")) {
  92. previousArg = processLongArg(arg.substring(2));
  93. inArg = checkArgument(previousArg);
  94. } else if (arg.charAt(0) == '-') {
  95. previousArg = processShortArg(arg.substring(1));
  96. inArg = checkArgument(previousArg);
  97. } else {
  98. doUnknownArg("Unknown argument: " + arg);
  99. }
  100. }
  101. }
  102. if (inArg) {
  103. doUnknownArg("Missing parameter for argument: " + previousArg);
  104. }
  105. if (server != null) {
  106. try {
  107. server.connect(addresses);
  108. System.exit(0);
  109. } catch (RemoteException ex) {
  110. Logger.appError(ErrorLevel.MEDIUM,
  111. "Unable to execute remote connection", ex);
  112. }
  113. }
  114. new RemoteServer(serverManagerProvider).bind();
  115. }
  116. /**
  117. * Checks whether the specified arg type takes an argument. If it does,
  118. * this method returns true. If it doesn't, the method processes the
  119. * argument and returns false.
  120. *
  121. * @param argument The short code of the argument
  122. * @return True if the arg requires an argument, false otherwise
  123. */
  124. private boolean checkArgument(final char argument) {
  125. boolean needsArg = false;
  126. for (Object[] target : ARGUMENTS) {
  127. if ((Character) argument == target[0]) {
  128. needsArg = (Boolean) target[3];
  129. break;
  130. }
  131. }
  132. if (needsArg) {
  133. return true;
  134. } else {
  135. processArgument(argument, null);
  136. return false;
  137. }
  138. }
  139. /**
  140. * Processes the specified string as a single long argument.
  141. *
  142. * @param arg The string entered
  143. * @return The short form of the corresponding argument
  144. */
  145. private char processLongArg(final String arg) {
  146. for (Object[] target : ARGUMENTS) {
  147. if (arg.equalsIgnoreCase((String) target[1])) {
  148. return (Character) target[0];
  149. }
  150. }
  151. doUnknownArg("Unknown argument: " + arg);
  152. exit();
  153. return '.';
  154. }
  155. /**
  156. * Processes the specified string as a single short argument.
  157. *
  158. * @param arg The string entered
  159. * @return The short form of the corresponding argument
  160. */
  161. private char processShortArg(final String arg) {
  162. for (Object[] target : ARGUMENTS) {
  163. if (arg.equals(String.valueOf(target[0]))) {
  164. return (Character) target[0];
  165. }
  166. }
  167. doUnknownArg("Unknown argument: " + arg);
  168. exit();
  169. return '.';
  170. }
  171. /**
  172. * Processes the specified command-line argument.
  173. *
  174. * @param arg The short form of the argument used
  175. * @param param The (optional) string parameter for the option
  176. */
  177. private void processArgument(final char arg, final String param) {
  178. switch (arg) {
  179. case 'c':
  180. doConnect(param);
  181. break;
  182. case 'd':
  183. doDirectory(param);
  184. break;
  185. case 'e':
  186. doExisting();
  187. break;
  188. case 'k':
  189. doExistingCheck();
  190. break;
  191. case 'h':
  192. doHelp();
  193. break;
  194. case 'l':
  195. launcherVersion = param;
  196. break;
  197. case 'p':
  198. doDirectory(DMDircResourceManager.getCurrentWorkingDirectory());
  199. break;
  200. case 'r':
  201. disablereporting = true;
  202. break;
  203. case 'v':
  204. doVersion();
  205. break;
  206. default:
  207. // This really shouldn't ever happen, but we'll handle it nicely
  208. // anyway.
  209. doUnknownArg("Unknown argument: " + arg);
  210. break;
  211. }
  212. }
  213. /**
  214. * Informs the user that they entered an unknown argument, prints the
  215. * client help, and exits.
  216. *
  217. * @param message The message about the unknown argument to be displayed
  218. */
  219. private void doUnknownArg(final String message) {
  220. System.out.println(message);
  221. System.out.println();
  222. doHelp();
  223. }
  224. /**
  225. * Exits DMDirc.
  226. */
  227. private void exit() {
  228. System.exit(0);
  229. }
  230. /**
  231. * Handles the --connect argument.
  232. *
  233. * @param address The address the user told us to connect to
  234. */
  235. private void doConnect(final String address) {
  236. try {
  237. addresses.add(NewServer.getURI(address));
  238. } catch (URISyntaxException ex) {
  239. doUnknownArg("Invalid address specified: " + ex.getMessage());
  240. }
  241. }
  242. /**
  243. * Handles the --existing argument.
  244. */
  245. private void doExisting() {
  246. server = RemoteServer.getServer();
  247. if (server == null) {
  248. System.err.println("Unable to connect to existing instance");
  249. }
  250. }
  251. /**
  252. * Handles the --check argument.
  253. */
  254. private void doExistingCheck() {
  255. if (RemoteServer.getServer() == null) {
  256. System.out.println("Existing instance not found.");
  257. System.exit(1);
  258. } else {
  259. System.out.println("Existing instance found.");
  260. System.exit(0);
  261. }
  262. }
  263. /**
  264. * Sets the config directory to the one specified.
  265. *
  266. * @param dir The new config directory
  267. */
  268. private void doDirectory(final String dir) {
  269. if (dir.endsWith(File.separator)) {
  270. configDirectory = dir;
  271. } else {
  272. configDirectory = dir + File.separator;
  273. }
  274. }
  275. /**
  276. * Prints out the client version and exits.
  277. */
  278. private void doVersion() {
  279. System.out.println("DMDirc - a cross-platform, open-source IRC client.");
  280. System.out.println();
  281. System.out.println(" Version: " + IdentityManager.getIdentityManager()
  282. .getGlobalConfiguration().getOption("version", "version"));
  283. System.out.println(" Update channel: " + IdentityManager.getIdentityManager()
  284. .getGlobalConfiguration().getOption("updater", "channel"));
  285. exit();
  286. }
  287. /**
  288. * Prints out client help and exits.
  289. */
  290. private void doHelp() {
  291. System.out.println("Usage: java -jar DMDirc.jar [options]");
  292. System.out.println();
  293. System.out.println("Valid options:");
  294. System.out.println();
  295. int maxLength = 0;
  296. for (Object[] arg : ARGUMENTS) {
  297. final String needsArg = ((Boolean) arg[3]) ? " <argument>" : "";
  298. if ((arg[1] + needsArg).length() > maxLength) {
  299. maxLength = (arg[1] + needsArg).length();
  300. }
  301. }
  302. for (Object[] arg : ARGUMENTS) {
  303. final String needsArg = ((Boolean) arg[3]) ? " <argument>" : "";
  304. final StringBuilder desc = new StringBuilder(maxLength + 1);
  305. desc.append(arg[1]);
  306. while (desc.length() < maxLength + 1) {
  307. desc.append(' ');
  308. }
  309. System.out.print(" -" + arg[0] + needsArg);
  310. System.out.println(" --" + desc + needsArg + " " + arg[2]);
  311. System.out.println();
  312. }
  313. exit();
  314. }
  315. /**
  316. * Returns the user-supplied configuration directory.
  317. *
  318. * @return The user-supplied config directory, or {@code null} if none
  319. * was supplied.
  320. */
  321. public String getConfigDirectory() {
  322. return configDirectory;
  323. }
  324. /**
  325. * Indicates whether the user has requested error reporting be disabled.
  326. *
  327. * @return True if the user has disabled reporting, false otherwise.
  328. */
  329. public boolean getDisableReporting() {
  330. return disablereporting;
  331. }
  332. /**
  333. * Returns the provided launcher version, if any.
  334. *
  335. * @return The version supplied by the launcher, or {@code null} if no
  336. * launcher is identified.
  337. */
  338. public String getLauncherVersion() {
  339. return launcherVersion;
  340. }
  341. /**
  342. * Processes arguments once the client has been loaded properly.
  343. * This allows us to auto-connect to servers, etc.
  344. *
  345. * @param serverManager The server manager to use to connect servers.
  346. */
  347. public void processArguments(final ServerManager serverManager) {
  348. for (URI address : addresses) {
  349. serverManager.connectToAddress(address);
  350. }
  351. }
  352. }