You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

CommandLineParser.java 12KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406
  1. /*
  2. * Copyright (c) 2006-2014 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. * @param serverManagerProvider ServerManager
  75. */
  76. @Inject
  77. public CommandLineParser(final Provider<ServerManager> serverManagerProvider) {
  78. this.serverManagerProvider = serverManagerProvider;
  79. }
  80. /**
  81. * Parses the given arguments.
  82. *
  83. * @param arguments The arguments to be parsed
  84. */
  85. public void parse(final String ... arguments) {
  86. boolean inArg = false;
  87. char previousArg = '.';
  88. for (String arg : arguments) {
  89. if (inArg) {
  90. processArgument(previousArg, arg);
  91. inArg = false;
  92. } else {
  93. if (arg.startsWith("--")) {
  94. previousArg = processLongArg(arg.substring(2));
  95. inArg = checkArgument(previousArg);
  96. } else if (arg.charAt(0) == '-') {
  97. previousArg = processShortArg(arg.substring(1));
  98. inArg = checkArgument(previousArg);
  99. } else {
  100. doUnknownArg("Unknown argument: " + arg);
  101. }
  102. }
  103. }
  104. if (inArg) {
  105. doUnknownArg("Missing parameter for argument: " + previousArg);
  106. }
  107. if (server != null) {
  108. try {
  109. server.connect(addresses);
  110. System.exit(0);
  111. } catch (RemoteException ex) {
  112. Logger.appError(ErrorLevel.MEDIUM,
  113. "Unable to execute remote connection", ex);
  114. }
  115. }
  116. new RemoteServer(serverManagerProvider).bind();
  117. }
  118. /**
  119. * Checks whether the specified arg type takes an argument. If it does,
  120. * this method returns true. If it doesn't, the method processes the
  121. * argument and returns false.
  122. *
  123. * @param argument The short code of the argument
  124. * @return True if the arg requires an argument, false otherwise
  125. */
  126. private boolean checkArgument(final char argument) {
  127. boolean needsArg = false;
  128. for (Object[] target : ARGUMENTS) {
  129. if ((Character) argument == target[0]) {
  130. needsArg = (Boolean) target[3];
  131. break;
  132. }
  133. }
  134. if (needsArg) {
  135. return true;
  136. } else {
  137. processArgument(argument, null);
  138. return false;
  139. }
  140. }
  141. /**
  142. * Processes the specified string as a single long argument.
  143. *
  144. * @param arg The string entered
  145. * @return The short form of the corresponding argument
  146. */
  147. private char processLongArg(final String arg) {
  148. for (Object[] target : ARGUMENTS) {
  149. if (arg.equalsIgnoreCase((String) target[1])) {
  150. return (Character) target[0];
  151. }
  152. }
  153. doUnknownArg("Unknown argument: " + arg);
  154. exit();
  155. return '.';
  156. }
  157. /**
  158. * Processes the specified string as a single short argument.
  159. *
  160. * @param arg The string entered
  161. * @return The short form of the corresponding argument
  162. */
  163. private char processShortArg(final String arg) {
  164. for (Object[] target : ARGUMENTS) {
  165. if (arg.equals(String.valueOf(target[0]))) {
  166. return (Character) target[0];
  167. }
  168. }
  169. doUnknownArg("Unknown argument: " + arg);
  170. exit();
  171. return '.';
  172. }
  173. /**
  174. * Processes the specified command-line argument.
  175. *
  176. * @param arg The short form of the argument used
  177. * @param param The (optional) string parameter for the option
  178. */
  179. private void processArgument(final char arg, final String param) {
  180. switch (arg) {
  181. case 'c':
  182. doConnect(param);
  183. break;
  184. case 'd':
  185. doDirectory(param);
  186. break;
  187. case 'e':
  188. doExisting();
  189. break;
  190. case 'k':
  191. doExistingCheck();
  192. break;
  193. case 'h':
  194. doHelp();
  195. break;
  196. case 'l':
  197. launcherVersion = param;
  198. break;
  199. case 'p':
  200. doDirectory(DMDircResourceManager.getCurrentWorkingDirectory());
  201. break;
  202. case 'r':
  203. disablereporting = true;
  204. break;
  205. case 'v':
  206. doVersion();
  207. break;
  208. default:
  209. // This really shouldn't ever happen, but we'll handle it nicely
  210. // anyway.
  211. doUnknownArg("Unknown argument: " + arg);
  212. break;
  213. }
  214. }
  215. /**
  216. * Informs the user that they entered an unknown argument, prints the
  217. * client help, and exits.
  218. *
  219. * @param message The message about the unknown argument to be displayed
  220. */
  221. private void doUnknownArg(final String message) {
  222. System.out.println(message);
  223. System.out.println();
  224. doHelp();
  225. }
  226. /**
  227. * Exits DMDirc.
  228. */
  229. private void exit() {
  230. System.exit(0);
  231. }
  232. /**
  233. * Handles the --connect argument.
  234. *
  235. * @param address The address the user told us to connect to
  236. */
  237. private void doConnect(final String address) {
  238. try {
  239. addresses.add(NewServer.getURI(address));
  240. } catch (URISyntaxException ex) {
  241. doUnknownArg("Invalid address specified: " + ex.getMessage());
  242. }
  243. }
  244. /**
  245. * Handles the --existing argument.
  246. */
  247. private void doExisting() {
  248. server = RemoteServer.getServer();
  249. if (server == null) {
  250. System.err.println("Unable to connect to existing instance");
  251. }
  252. }
  253. /**
  254. * Handles the --check argument.
  255. */
  256. private void doExistingCheck() {
  257. if (RemoteServer.getServer() == null) {
  258. System.out.println("Existing instance not found.");
  259. System.exit(1);
  260. } else {
  261. System.out.println("Existing instance found.");
  262. System.exit(0);
  263. }
  264. }
  265. /**
  266. * Sets the config directory to the one specified.
  267. *
  268. * @param dir The new config directory
  269. */
  270. private void doDirectory(final String dir) {
  271. if (dir.endsWith(File.separator)) {
  272. configDirectory = dir;
  273. } else {
  274. configDirectory = dir + File.separator;
  275. }
  276. }
  277. /**
  278. * Prints out the client version and exits.
  279. */
  280. private void doVersion() {
  281. System.out.println("DMDirc - a cross-platform, open-source IRC client.");
  282. System.out.println();
  283. System.out.println(" Version: " + IdentityManager.getIdentityManager()
  284. .getGlobalConfiguration().getOption("version", "version"));
  285. System.out.println(" Update channel: " + IdentityManager.getIdentityManager()
  286. .getGlobalConfiguration().getOption("updater", "channel"));
  287. exit();
  288. }
  289. /**
  290. * Prints out client help and exits.
  291. */
  292. private void doHelp() {
  293. System.out.println("Usage: java -jar DMDirc.jar [options]");
  294. System.out.println();
  295. System.out.println("Valid options:");
  296. System.out.println();
  297. int maxLength = 0;
  298. for (Object[] arg : ARGUMENTS) {
  299. final String needsArg = ((Boolean) arg[3]) ? " <argument>" : "";
  300. if ((arg[1] + needsArg).length() > maxLength) {
  301. maxLength = (arg[1] + needsArg).length();
  302. }
  303. }
  304. for (Object[] arg : ARGUMENTS) {
  305. final String needsArg = ((Boolean) arg[3]) ? " <argument>" : "";
  306. final StringBuilder desc = new StringBuilder(maxLength + 1);
  307. desc.append(arg[1]);
  308. while (desc.length() < maxLength + 1) {
  309. desc.append(' ');
  310. }
  311. System.out.print(" -" + arg[0] + needsArg);
  312. System.out.println(" --" + desc + needsArg + " " + arg[2]);
  313. System.out.println();
  314. }
  315. exit();
  316. }
  317. /**
  318. * Returns the user-supplied configuration directory.
  319. *
  320. * @return The user-supplied config directory, or {@code null} if none
  321. * was supplied.
  322. */
  323. public String getConfigDirectory() {
  324. return configDirectory;
  325. }
  326. /**
  327. * Indicates whether the user has requested error reporting be disabled.
  328. *
  329. * @return True if the user has disabled reporting, false otherwise.
  330. */
  331. public boolean getDisableReporting() {
  332. return disablereporting;
  333. }
  334. /**
  335. * Returns the provided launcher version, if any.
  336. *
  337. * @return The version supplied by the launcher, or {@code null} if no
  338. * launcher is identified.
  339. */
  340. public String getLauncherVersion() {
  341. return launcherVersion;
  342. }
  343. /**
  344. * Processes arguments once the client has been loaded properly.
  345. * This allows us to auto-connect to servers, etc.
  346. *
  347. * @param serverManager The server manager to use to connect servers.
  348. */
  349. public void processArguments(final ServerManager serverManager) {
  350. for (URI address : addresses) {
  351. serverManager.connectToAddress(address);
  352. }
  353. }
  354. }