Refactor argument handling a bit

This commit is contained in:
Reinhard Pointner 2016-10-19 01:02:51 +08:00
parent da7061338d
commit 4f5b1cefcc
7 changed files with 49 additions and 59 deletions

View File

@ -5,6 +5,7 @@ import static java.util.Arrays.*;
import static java.util.stream.Collectors.*; import static java.util.stream.Collectors.*;
import static net.filebot.Logging.*; import static net.filebot.Logging.*;
import static net.filebot.Settings.*; import static net.filebot.Settings.*;
import static net.filebot.util.ExceptionUtilities.*;
import static net.filebot.util.FileUtilities.*; import static net.filebot.util.FileUtilities.*;
import static net.filebot.util.XPathUtilities.*; import static net.filebot.util.XPathUtilities.*;
import static net.filebot.util.ui.SwingUI.*; import static net.filebot.util.ui.SwingUI.*;
@ -59,16 +60,16 @@ import net.miginfocom.swing.MigLayout;
public class Main { public class Main {
public static void main(String[] argumentArray) { public static void main(String[] argv) {
try { try {
// parse arguments // parse arguments
ArgumentBean args = ArgumentBean.parse(argumentArray); ArgumentBean args = new ArgumentBean(argv);
if (args.printHelp() || args.printVersion() || (!(args.runCLI() || args.clearCache() || args.clearUserData()) && isHeadless())) { if (args.printHelp() || args.printVersion() || (!(args.runCLI() || args.clearCache() || args.clearUserData()) && isHeadless())) {
System.out.format("%s / %s%n%n", getApplicationIdentifier(), getJavaRuntimeIdentifier()); log.info(format("%s / %s%n", getApplicationIdentifier(), getJavaRuntimeIdentifier()));
if (args.printHelp() || (!args.printVersion() && isHeadless())) { if (args.printHelp() || (!args.printVersion() && isHeadless())) {
ArgumentBean.printHelp(args, System.out); log.info(args.usage());
} }
// just print help message or version string and then exit // just print help message or version string and then exit
@ -78,21 +79,21 @@ public class Main {
if (args.clearCache() || args.clearUserData()) { if (args.clearCache() || args.clearUserData()) {
// clear cache must be called manually // clear cache must be called manually
if (System.console() == null) { if (System.console() == null) {
System.err.println("`filebot -clear-cache` has been disabled due to abuse."); log.severe("`filebot -clear-cache` has been disabled due to abuse.");
System.exit(1); System.exit(1);
} }
// clear persistent user preferences // clear persistent user preferences
if (args.clearUserData()) { if (args.clearUserData()) {
System.out.println("Reset preferences"); log.info("Reset preferences");
Settings.forPackage(Main.class).clear(); Settings.forPackage(Main.class).clear();
} }
// clear caches // clear caches
if (args.clearCache()) { if (args.clearCache()) {
System.out.println("Clear cache"); log.info("Clear cache");
for (File folder : getChildren(ApplicationFolder.Cache.getCanonicalFile(), FOLDERS)) { for (File folder : getChildren(ApplicationFolder.Cache.getCanonicalFile(), FOLDERS)) {
System.out.println("* Delete " + folder); log.fine("* Delete " + folder);
delete(folder); delete(folder);
} }
} }
@ -102,7 +103,7 @@ public class Main {
} }
// make sure we can access application arguments at any time // make sure we can access application arguments at any time
setApplicationArgumentArray(argumentArray); setApplicationArguments(args);
// update system properties // update system properties
initializeSystemProperties(args); initializeSystemProperties(args);
@ -125,35 +126,30 @@ public class Main {
} }
// GUI mode => start user interface // GUI mode => start user interface
SwingUtilities.invokeAndWait(() -> { SwingUtilities.invokeLater(() -> {
startUserInterface(args); startUserInterface(args);
});
// run background tasks
newSwingWorker(() -> onStart(args));
});
} catch (CmdLineException e) {
// illegal arguments => print CLI error message
log.severe(e::getMessage);
System.exit(1);
} catch (Throwable e) {
// unexpected error => dump stack
debug.log(Level.SEVERE, "Error during startup: " + getRootCause(e), e);
System.exit(1);
}
}
private static void onStart(ArgumentBean args) {
// publish file arguments // publish file arguments
List<File> files = args.getFiles(false); List<File> files = args.getFiles(false);
if (files.size() > 0) { if (files.size() > 0) {
SwingEventBus.getInstance().post(new FileTransferable(files)); SwingEventBus.getInstance().post(new FileTransferable(files));
} }
// run background tasks
new Thread(Main::onStart).start();
} catch (CmdLineException e) {
// illegal arguments => print CLI error message
System.err.println(e.getMessage());
System.exit(1);
} catch (Throwable e) {
// find root cause
while (e.getCause() != null) {
e = e.getCause();
}
// unexpected error => dump stack
debug.log(Level.SEVERE, String.format("Error during startup: %s", e.getMessage()), e);
System.exit(1);
}
}
private static void onStart() {
// preload media.types (when loaded during DnD it will freeze the UI for a few hundred milliseconds) // preload media.types (when loaded during DnD it will freeze the UI for a few hundred milliseconds)
MediaTypes.getDefault(); MediaTypes.getDefault();

View File

@ -179,18 +179,14 @@ public final class Settings {
return String.format("%s %s %s", System.getProperty("java.runtime.name"), System.getProperty("java.version"), GraphicsEnvironment.isHeadless() ? "(headless)" : "").trim(); return String.format("%s %s %s", System.getProperty("java.runtime.name"), System.getProperty("java.version"), GraphicsEnvironment.isHeadless() ? "(headless)" : "").trim();
} }
private static String[] applicationArgumentArray; private static ArgumentBean applicationArguments;
protected static void setApplicationArgumentArray(String[] args) { public static void setApplicationArguments(ArgumentBean args) {
applicationArgumentArray = args; applicationArguments = args;
} }
public static ArgumentBean getApplicationArguments() { public static ArgumentBean getApplicationArguments() {
try { return applicationArguments;
return ArgumentBean.parse(applicationArgumentArray);
} catch (Exception e) {
throw new IllegalStateException(e);
}
} }
public static File getApplicationFolder() { public static File getApplicationFolder() {

View File

@ -5,7 +5,7 @@ import static net.filebot.Logging.*;
import static net.filebot.util.FileUtilities.*; import static net.filebot.util.FileUtilities.*;
import java.io.File; import java.io.File;
import java.io.OutputStream; import java.io.StringWriter;
import java.util.ArrayList; import java.util.ArrayList;
import java.util.LinkedHashMap; import java.util.LinkedHashMap;
import java.util.List; import java.util.List;
@ -188,25 +188,24 @@ public class ArgumentBean {
return Level.parse(log.toUpperCase()); return Level.parse(log.toUpperCase());
} }
private final String[] array; private final String[] args;
private ArgumentBean(String... array) { public ArgumentBean(String... args) throws CmdLineException {
this.array = array; this.args = args;
}
public String[] getArray() { CmdLineParser parser = new CmdLineParser(this);
return array.clone();
}
public static ArgumentBean parse(String[] args) throws CmdLineException {
ArgumentBean bean = new ArgumentBean(args);
CmdLineParser parser = new CmdLineParser(bean);
parser.parseArgument(args); parser.parseArgument(args);
return bean;
} }
public static void printHelp(ArgumentBean argumentBean, OutputStream out) { public String[] getArgumentArray() {
new CmdLineParser(argumentBean, ParserProperties.defaults().withShowDefaults(false).withOptionSorter(null)).printUsage(out); return args.clone();
}
public String usage() {
StringWriter buffer = new StringWriter();
CmdLineParser parser = new CmdLineParser(this, ParserProperties.defaults().withShowDefaults(false).withOptionSorter(null));
parser.printUsage(buffer, null);
return buffer.toString();
} }
} }

View File

@ -105,7 +105,7 @@ public class ArgumentProcessor {
public void runScript(ArgumentBean args) throws Throwable { public void runScript(ArgumentBean args) throws Throwable {
Bindings bindings = new SimpleBindings(); Bindings bindings = new SimpleBindings();
bindings.put(ScriptShell.SHELL_ARGV_BINDING_NAME, args.getArray()); bindings.put(ScriptShell.SHELL_ARGV_BINDING_NAME, args.getArgumentArray());
bindings.put(ScriptShell.ARGV_BINDING_NAME, args.getFiles(false)); bindings.put(ScriptShell.ARGV_BINDING_NAME, args.getFiles(false));
ScriptSource source = ScriptSource.findScriptProvider(args.script); ScriptSource source = ScriptSource.findScriptProvider(args.script);

View File

@ -217,7 +217,7 @@ public class GroovyPad extends JFrame {
public void run() { public void run() {
try { try {
Bindings bindings = new SimpleBindings(); Bindings bindings = new SimpleBindings();
bindings.put(ScriptShell.SHELL_ARGV_BINDING_NAME, Settings.getApplicationArguments().getArray()); bindings.put(ScriptShell.SHELL_ARGV_BINDING_NAME, Settings.getApplicationArguments().getArgumentArray());
bindings.put(ScriptShell.ARGV_BINDING_NAME, Settings.getApplicationArguments().getFiles(false)); bindings.put(ScriptShell.ARGV_BINDING_NAME, Settings.getApplicationArguments().getFiles(false));
result = shell.evaluate(script, bindings); result = shell.evaluate(script, bindings);
@ -273,7 +273,7 @@ public class GroovyPad extends JFrame {
System.setOut(new TeePrintStream(new ConsoleOutputStream(), true, "UTF-8", system_out)); System.setOut(new TeePrintStream(new ConsoleOutputStream(), true, "UTF-8", system_out));
System.setErr(new TeePrintStream(new ConsoleOutputStream(), true, "UTF-8", system_err)); System.setErr(new TeePrintStream(new ConsoleOutputStream(), true, "UTF-8", system_err));
} catch (UnsupportedEncodingException e) { } catch (UnsupportedEncodingException e) {
// can't happen debug.log(Level.WARNING, e, e::getMessage);
} }
} }

View File

@ -86,8 +86,8 @@ public abstract class ScriptShellBaseClass extends Script {
public Object runScript(String input, String... argv) throws Throwable { public Object runScript(String input, String... argv) throws Throwable {
try { try {
ArgumentBean args = argv == null || argv.length == 0 ? getArgumentBean() : ArgumentBean.parse(argv); ArgumentBean args = argv == null || argv.length == 0 ? getArgumentBean() : new ArgumentBean(argv);
return executeScript(input, asList(getArgumentBean().getArray()), args.defines, args.getFiles(false)); return executeScript(input, asList(getArgumentBean().getArgumentArray()), args.defines, args.getFiles(false));
} catch (Exception e) { } catch (Exception e) {
printException(e, true); printException(e, true);
} }
@ -95,7 +95,7 @@ public abstract class ScriptShellBaseClass extends Script {
} }
public Object executeScript(String input, Map<String, ?> bindings, Object... args) throws Throwable { public Object executeScript(String input, Map<String, ?> bindings, Object... args) throws Throwable {
return executeScript(input, asList(getArgumentBean().getArray()), bindings, asFileList(args)); return executeScript(input, asList(getArgumentBean().getArgumentArray()), bindings, asFileList(args));
} }
public Object executeScript(String input, List<String> argv, Map<String, ?> bindings, List<File> args) throws Throwable { public Object executeScript(String input, List<String> argv, Map<String, ?> bindings, List<File> args) throws Throwable {
@ -483,9 +483,9 @@ public abstract class ScriptShellBaseClass extends Script {
private ArgumentBean getArgumentBean() { private ArgumentBean getArgumentBean() {
try { try {
return ArgumentBean.parse((String[]) getBinding().getVariable(ScriptShell.SHELL_ARGV_BINDING_NAME)); return new ArgumentBean((String[]) getBinding().getVariable(ScriptShell.SHELL_ARGV_BINDING_NAME));
} catch (Exception e) { } catch (Exception e) {
throw new IllegalStateException(e.getMessage()); throw new IllegalStateException(e.getMessage(), e);
} }
} }

View File

@ -769,7 +769,6 @@ public class RenamePanel extends JComponent {
} catch (Exception e) { } catch (Exception e) {
log.log(Level.INFO, e, e::getMessage); log.log(Level.INFO, e, e::getMessage);
} finally { } finally {
System.out.println("RenamePanel.ApplyPresetAction.actionPerformed()");
window.setCursor(Cursor.getDefaultCursor()); window.setCursor(Cursor.getDefaultCursor());
} }
}); });