Skip to content

Commit

Permalink
#121 improved names for autocompletion test and demo
Browse files Browse the repository at this point in the history
  • Loading branch information
remkop committed Aug 12, 2017
1 parent 9f044b6 commit 8bc56f0
Show file tree
Hide file tree
Showing 6 changed files with 191 additions and 182 deletions.
10 changes: 5 additions & 5 deletions src/main/java/picocli/AutoComplete.java
Original file line number Diff line number Diff line change
Expand Up @@ -204,7 +204,7 @@ public boolean equals(Object obj) {
"# =======================\n" +
"#\n" +
"# Bash completion support for the `%1$s` command,\n" +
"# generated by [picocli](http://picocli.info/).\n" +
"# generated by [picocli](http://picocli.info/) version %2$s.\n" +
"#\n" +
"# Installation\n" +
"# ------------\n" +
Expand All @@ -220,9 +220,9 @@ public boolean equals(Object obj) {
"# Documentation\n" +
"# -------------\n" +
"# The script is called by bash whenever [TAB] or [TAB][TAB] is pressed after\n" +
"# '%1$s (..)'. By reading entered command line parameters, it determines possible\n" +
"# bash completions and writes them to the COMPREPLY variable. Bash then\n" +
"# completes the user input if only one entry is listed in the variable or\n" +
"# '%1$s (..)'. By reading entered command line parameters,\n" +
"# it determines possible bash completions and writes them to the COMPREPLY variable.\n" +
"# Bash then completes the user input if only one entry is listed in the variable or\n" +
"# shows the options if more than one is listed in COMPREPLY.\n" +
"#\n" +
"# References\n" +
Expand Down Expand Up @@ -293,7 +293,7 @@ public static String bash(String scriptName, CommandLine commandLine) {
if (scriptName == null) { throw new NullPointerException("scriptName"); }
if (commandLine == null) { throw new NullPointerException("commandLine"); }
String result = "";
result += format(HEADER, scriptName);
result += format(HEADER, scriptName, CommandLine.VERSION);

Map<CommandDescriptor, CommandLine> function2command = new LinkedHashMap<CommandDescriptor, CommandLine>();
result += generateEntryPointFunction(scriptName, commandLine, function2command);
Expand Down
289 changes: 145 additions & 144 deletions src/test/java/picocli/AutoCompleteTest.java
Original file line number Diff line number Diff line change
@@ -1,144 +1,145 @@
/*
Copyright 2017 Remko Popma
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
*/
package picocli;

import java.io.BufferedReader;
import java.io.File;
import java.io.IOException;
import java.io.InputStreamReader;
import java.lang.reflect.Field;
import java.net.InetAddress;
import java.net.URL;
import java.util.List;
import java.util.concurrent.TimeUnit;

import org.junit.Test;

import picocli.CommandLine.Command;
import picocli.CommandLine.Option;

import static org.junit.Assert.*;

/**
* Tests the scripts generated by AutoComplete.
*/
// http://hayne.net/MacDev/Notes/unixFAQ.html#shellStartup
// https://apple.stackexchange.com/a/13019
public class AutoCompleteTest {
public static void main(String[] args) {
TopLevel.main(args);
}
public static class BasicExample implements Runnable {
@Option(names = {"-u", "--timeUnit"}) private TimeUnit timeUnit;
@Option(names = {"-t", "--timeout"}) private long timeout;
@Override public void run() {
System.out.printf("BasicExample was invoked with %d %s.%n", timeout, timeUnit);
}
public static void main(String[] args) { CommandLine.run(new BasicExample(), System.out, args); }
}
@Test
public void basic() throws Exception {
String script = AutoComplete.bash("basicExample", new CommandLine(new BasicExample()));
String expected = loadTextFromClasspath("/basic.bash");
assertEquals(expected, script);
}

public static class TopLevel {
@Option(names = {"-V", "--version"}, help = true) boolean versionRequested;
@Option(names = {"-h", "--help"}, help = true) boolean helpRequested;
public static void main(String[] args) {
CommandLine hierarchy = new CommandLine(new TopLevel())
.addSubcommand("sub1", new Sub1())
.addSubcommand("sub2", new CommandLine(new Sub2())
.addSubcommand("subsub1", new Sub2Child1())
.addSubcommand("subsub2", new Sub2Child2())
);
List<CommandLine> commandLines = hierarchy.parse(args);
//Collections.reverse(commandLines);
for (CommandLine cmdLine : commandLines) {
Object command = cmdLine.getCommand();
System.out.printf("Parsed command %s%n", AutoCompleteTest.toString(command));
}
}
}
@Command(description = "First level subcommand 1")
public static class Sub1 {
@Option(names = "--num", description = "a number") double number;
@Option(names = "--str", description = "a String") String str;
}
@Command(description = "First level subcommand 2")
public static class Sub2 {
@Option(names = "--num2", description = "another number") int number2;
@Option(names = {"--directory", "-d"}, description = "a directory") File directory;
}
@Command(description = "Second level sub-subcommand 1")
public static class Sub2Child1 {
@Option(names = {"-h", "--host"}, description = "a host") InetAddress host;
}
@Command(description = "Second level sub-subcommand 2")
public static class Sub2Child2 {
@Option(names = {"-u", "--timeUnit"}) private TimeUnit timeUnit;
@Option(names = {"-t", "--timeout"}) private long timeout;
}

@Test
public void nestedSubcommands() throws Exception {
CommandLine hierarchy = new CommandLine(new TopLevel())
.addSubcommand("sub1", new Sub1())
.addSubcommand("sub2", new CommandLine(new Sub2())
.addSubcommand("subsub1", new Sub2Child1())
.addSubcommand("subsub2", new Sub2Child2())
);
String script = AutoComplete.bash("hierarchy", hierarchy);
String expected = loadTextFromClasspath("/nestedSubcommands.bash");
assertEquals(expected, script);
}

private static String loadTextFromClasspath(String path) {
URL url = AutoCompleteTest.class.getResource(path);
if (url == null) { throw new IllegalArgumentException("Could not find '" + path + "' in classpath."); }
BufferedReader reader = null;
try {
reader = new BufferedReader(new InputStreamReader(url.openStream()));
StringBuilder result = new StringBuilder(512);
char[] buff = new char[4096];
int read = 0;
do {
result.append(buff, 0, read);
read = reader.read(buff);
} while (read >= 0);
return result.toString();
} catch (IOException ex) {
throw new IllegalStateException("Could not read " + url + " for '" + path + "':", ex);
} finally {
if (reader != null) { try { reader.close(); } catch (IOException e) { /* ignore */ } }
}
}

private static String toString(Object obj) {
StringBuilder sb = new StringBuilder(256);
Class<?> cls = obj.getClass();
sb.append(cls.getSimpleName()).append("[");
String sep = "";
for (Field f : cls.getDeclaredFields()) {
f.setAccessible(true);
sb.append(sep).append(f.getName()).append("=");
try { sb.append(f.get(obj)); } catch (Exception ex) { sb.append(ex); }
sep = ", ";
}
return sb.append("]").toString();
}
}
/*
Copyright 2017 Remko Popma
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
*/
package picocli;

import java.io.BufferedReader;
import java.io.File;
import java.io.IOException;
import java.io.InputStreamReader;
import java.lang.reflect.Field;
import java.net.InetAddress;
import java.net.URL;
import java.util.List;
import java.util.concurrent.TimeUnit;

import org.junit.Test;

import picocli.CommandLine.Command;
import picocli.CommandLine.Option;

import static java.lang.String.format;
import static org.junit.Assert.*;

/**
* Tests the scripts generated by AutoComplete.
*/
// http://hayne.net/MacDev/Notes/unixFAQ.html#shellStartup
// https://apple.stackexchange.com/a/13019
public class AutoCompleteTest {
public static void main(String[] args) {
TopLevel.main(args);
}
public static class BasicExample implements Runnable {
@Option(names = {"-u", "--timeUnit"}) private TimeUnit timeUnit;
@Option(names = {"-t", "--timeout"}) private long timeout;
@Override public void run() {
System.out.printf("BasicExample was invoked with %d %s.%n", timeout, timeUnit);
}
public static void main(String[] args) { CommandLine.run(new BasicExample(), System.out, args); }
}
@Test
public void basic() throws Exception {
String script = AutoComplete.bash("basicExample", new CommandLine(new BasicExample()));
String expected = format(loadTextFromClasspath("/basic.bash"), CommandLine.VERSION);
assertEquals(expected, script);
}

public static class TopLevel {
@Option(names = {"-V", "--version"}, help = true) boolean versionRequested;
@Option(names = {"-h", "--help"}, help = true) boolean helpRequested;
public static void main(String[] args) {
CommandLine hierarchy = new CommandLine(new TopLevel())
.addSubcommand("sub1", new Sub1())
.addSubcommand("sub2", new CommandLine(new Sub2())
.addSubcommand("subsub1", new Sub2Child1())
.addSubcommand("subsub2", new Sub2Child2())
);
List<CommandLine> commandLines = hierarchy.parse(args);
//Collections.reverse(commandLines);
for (CommandLine cmdLine : commandLines) {
Object command = cmdLine.getCommand();
System.out.printf("Parsed command %s%n", AutoCompleteTest.toString(command));
}
}
}
@Command(description = "First level subcommand 1")
public static class Sub1 {
@Option(names = "--num", description = "a number") double number;
@Option(names = "--str", description = "a String") String str;
}
@Command(description = "First level subcommand 2")
public static class Sub2 {
@Option(names = "--num2", description = "another number") int number2;
@Option(names = {"--directory", "-d"}, description = "a directory") File directory;
}
@Command(description = "Second level sub-subcommand 1")
public static class Sub2Child1 {
@Option(names = {"-h", "--host"}, description = "a host") InetAddress host;
}
@Command(description = "Second level sub-subcommand 2")
public static class Sub2Child2 {
@Option(names = {"-u", "--timeUnit"}) private TimeUnit timeUnit;
@Option(names = {"-t", "--timeout"}) private long timeout;
}

@Test
public void nestedSubcommands() throws Exception {
CommandLine hierarchy = new CommandLine(new TopLevel())
.addSubcommand("sub1", new Sub1())
.addSubcommand("sub2", new CommandLine(new Sub2())
.addSubcommand("subsub1", new Sub2Child1())
.addSubcommand("subsub2", new Sub2Child2())
);
String script = AutoComplete.bash("picocompletion-demo", hierarchy);
String expected = format(loadTextFromClasspath("/picocompletion-demo_completion"), CommandLine.VERSION);
assertEquals(expected, script);
}

private static String loadTextFromClasspath(String path) {
URL url = AutoCompleteTest.class.getResource(path);
if (url == null) { throw new IllegalArgumentException("Could not find '" + path + "' in classpath."); }
BufferedReader reader = null;
try {
reader = new BufferedReader(new InputStreamReader(url.openStream()));
StringBuilder result = new StringBuilder(512);
char[] buff = new char[4096];
int read = 0;
do {
result.append(buff, 0, read);
read = reader.read(buff);
} while (read >= 0);
return result.toString();
} catch (IOException ex) {
throw new IllegalStateException("Could not read " + url + " for '" + path + "':", ex);
} finally {
if (reader != null) { try { reader.close(); } catch (IOException e) { /* ignore */ } }
}
}

private static String toString(Object obj) {
StringBuilder sb = new StringBuilder(256);
Class<?> cls = obj.getClass();
sb.append(cls.getSimpleName()).append("[");
String sep = "";
for (Field f : cls.getDeclaredFields()) {
f.setAccessible(true);
sb.append(sep).append(f.getName()).append("=");
try { sb.append(f.get(obj)); } catch (Exception ex) { sb.append(ex); }
sep = ", ";
}
return sb.append("]").toString();
}
}
8 changes: 4 additions & 4 deletions src/test/resources/basic.bash
Original file line number Diff line number Diff line change
Expand Up @@ -4,7 +4,7 @@
# =======================
#
# Bash completion support for the `basicExample` command,
# generated by [picocli](http://picocli.info/).
# generated by [picocli](http://picocli.info/) version %s.
#
# Installation
# ------------
Expand All @@ -20,9 +20,9 @@
# Documentation
# -------------
# The script is called by bash whenever [TAB] or [TAB][TAB] is pressed after
# 'basicExample (..)'. By reading entered command line parameters, it determines possible
# bash completions and writes them to the COMPREPLY variable. Bash then
# completes the user input if only one entry is listed in the variable or
# 'basicExample (..)'. By reading entered command line parameters,
# it determines possible bash completions and writes them to the COMPREPLY variable.
# Bash then completes the user input if only one entry is listed in the variable or
# shows the options if more than one is listed in COMPREPLY.
#
# References
Expand Down
6 changes: 0 additions & 6 deletions src/test/resources/hierarchy

This file was deleted.

14 changes: 14 additions & 0 deletions src/test/resources/picocompletion-demo
Original file line number Diff line number Diff line change
@@ -0,0 +1,14 @@
#!/usr/bin/env bash

# This is a sample command script.
# Any script that invokes your application can function as the command script.
# Pass the name of this command script when generating the autocompletion function.
#
# For example:
# $ java -jar picocli-1.0.0.jar -n picocompletion-demo 'picocli.AutoCompleteTest$TopLevel'

LIBS=`cygpath -w "/cygdrive/c/Users/remko/IdeaProjects/pico-cli/build/libs"`
VERSION=1.0.0-SNAPSHOT
CP="${LIBS}/picocli-${VERSION}.jar;${LIBS}/picocli-${VERSION}-tests.jar"
java -cp "${CP}" 'picocli.AutoCompleteTest$TopLevel' $@

0 comments on commit 8bc56f0

Please sign in to comment.