您最多选择25个主题 主题必须以字母或数字开头,可以包含连字符 (-),并且长度不得超过35个字符

CommandLineParser.java 14KB

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