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 14KB

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