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

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