java/sql-dk/src/info/globalcode/sql/dk/CLIStarter.java
branchv_0
changeset 80 c4635ab3a7af
parent 75 43aa4625ab7e
child 95 714e4fac9cd0
--- a/java/sql-dk/src/info/globalcode/sql/dk/CLIStarter.java	Fri Dec 27 16:54:10 2013 +0100
+++ b/java/sql-dk/src/info/globalcode/sql/dk/CLIStarter.java	Fri Dec 27 17:40:27 2013 +0100
@@ -23,12 +23,17 @@
 import info.globalcode.sql.dk.configuration.ConfigurationException;
 import info.globalcode.sql.dk.configuration.DatabaseDefinition;
 import info.globalcode.sql.dk.configuration.FormatterDefinition;
+import info.globalcode.sql.dk.configuration.NameIdentified;
 import info.globalcode.sql.dk.formatting.Formatter;
 import info.globalcode.sql.dk.formatting.FormatterContext;
 import info.globalcode.sql.dk.formatting.FormatterException;
+import java.io.File;
+import java.io.FileNotFoundException;
 import java.io.IOException;
 import java.io.PrintStream;
+import java.io.PrintWriter;
 import java.sql.SQLException;
+import java.util.Collection;
 import java.util.logging.Level;
 import java.util.logging.LogRecord;
 import java.util.logging.Logger;
@@ -118,6 +123,8 @@
 				log.log(Level.SEVERE, "Unsupported mode: {0}", mode);
 				break;
 		}
+
+		generateBashCompletion();
 	}
 
 	private void processQueryNow() throws ConfigurationException, SQLException, FormatterException {
@@ -168,4 +175,33 @@
 			throw new ConfigurationException("Unable to load configuration from " + Constants.CONFIG_FILE, e);
 		}
 	}
+
+	private void generateBashCompletion() {
+		if (configuration == null) {
+			log.log(Level.FINER, "Not writing Bash completion helper files. In order to generate these files please run some command which requires configuration.");
+		} else {
+			try {
+				File dir = new File(Constants.DIR, "bash-completion");
+				dir.mkdir();
+				writeBashCompletionHelperFile(configuration.getDatabases(), new File(dir, "databases"));
+				writeBashCompletionHelperFile(configuration.getAllFormatters(), new File(dir, "formatters"));
+			} catch (Exception e) {
+				log.log(Level.WARNING, "Unable to generate Bash completion helper files", e);
+			}
+		}
+	}
+
+	private void writeBashCompletionHelperFile(Collection<? extends NameIdentified> items, File target) throws FileNotFoundException {
+		if (Constants.CONFIG_FILE.lastModified() > target.lastModified()) {
+			try (PrintWriter fw = new PrintWriter(target)) {
+				for (NameIdentified dd : items) {
+					fw.println(dd.getName());
+				}
+				fw.close();
+				log.log(Level.FINE, "Bash completion helper file was written: {0}", target);
+			}
+		} else {
+			log.log(Level.FINER, "Not writing Bash completion helper file: {0} because configuration {1} has not been changed", new Object[]{target, Constants.CONFIG_FILE});
+		}
+	}
 }