Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

BLADE-503 refactor Prompter to not assume System.in and add test for interactive mode #44

Open
wants to merge 1 commit into
base: master
Choose a base branch
from
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
126 changes: 61 additions & 65 deletions cli/src/main/java/com/liferay/blade/cli/BladeCLI.java
Original file line number Diff line number Diff line change
Expand Up @@ -33,7 +33,6 @@
import com.liferay.blade.cli.util.CombinedClassLoader;
import com.liferay.blade.cli.util.Prompter;

import java.io.Console;
import java.io.File;
import java.io.IOException;
import java.io.InputStream;
Expand Down Expand Up @@ -366,93 +365,89 @@ public void run(String[] args) throws Exception {

_validateParameters((BaseArgs)commandArgs);

Console console = System.console();
String parameterMessage = null;

if (console != null) {
String parameterMessage = null;
if (parameterException != null) {
parameterMessage = parameterException.getMessage();

if (parameterException != null) {
parameterMessage = parameterException.getMessage();
if (parameterMessage.contains("Main parameters are required") ||
parameterMessage.contains(_MESSAGE_OPTIONS_ARE_REQUIRED) ||
parameterMessage.contains(_MESSAGE_OPTION_IS_REQUIRED)) {

if (parameterMessage.contains("Main parameters are required") ||
parameterMessage.contains(_MESSAGE_OPTIONS_ARE_REQUIRED) ||
parameterMessage.contains(_MESSAGE_OPTION_IS_REQUIRED)) {

System.out.println(
"Error: The command " + command + " is missing required parameters.");
}
else {
throw parameterException;
}
System.out.println(
"Error: The command " + command + " is missing required parameters.");
}
else {
throw parameterException;
}
}

while (parameterException != null) {
parameterMessage = parameterException.getMessage();

List<String> fixedArgs = new ArrayList<>(Arrays.asList(args));

if (parameterMessage.contains(_MESSAGE_OPTIONS_ARE_REQUIRED) ||
parameterMessage.contains(_MESSAGE_OPTION_IS_REQUIRED)) {
while (parameterException != null) {
parameterMessage = parameterException.getMessage();

parameterMessage = parameterMessage.replace(_MESSAGE_OPTIONS_ARE_REQUIRED, "");
parameterMessage = parameterMessage.replace(_MESSAGE_OPTION_IS_REQUIRED, "");
List<String> fixedArgs = new ArrayList<>(Arrays.asList(args));

String[] missingParameters = parameterMessage.split(", ");
if (parameterMessage.contains(_MESSAGE_OPTIONS_ARE_REQUIRED) ||
parameterMessage.contains(_MESSAGE_OPTION_IS_REQUIRED)) {

String value = null;
parameterMessage = parameterMessage.replace(_MESSAGE_OPTIONS_ARE_REQUIRED, "");
parameterMessage = parameterMessage.replace(_MESSAGE_OPTION_IS_REQUIRED, "");

for (String missingParameter : missingParameters) {
missingParameter = _getMissingParameterUnformatted(missingParameter);
String[] missingParameters = parameterMessage.split(", ");

value = _promptForMissingParameter(commandArgs, Optional.of(missingParameter));
String value = null;

fixedArgs.add(1, missingParameter);
for (String missingParameter : missingParameters) {
missingParameter = _getMissingParameterUnformatted(missingParameter);

fixedArgs.add(2, value);
}
value = _promptForMissingParameter(commandArgs, Optional.of(missingParameter));

args = fixedArgs.toArray(new String[0]);
fixedArgs.add(1, missingParameter);

args = Extensions.sortArgs(_commands, args);
fixedArgs.add(2, value);
}
else if (parameterMessage.contains("Main parameters are required")) {
String value = _promptForMissingParameter(commandArgs, Optional.empty());

fixedArgs.add(value);
args = fixedArgs.toArray(new String[0]);

args = fixedArgs.toArray(new String[0]);
args = Extensions.sortArgs(_commands, args);
}
else if (parameterMessage.contains("Main parameters are required")) {
String value = _promptForMissingParameter(commandArgs, Optional.empty());

args = Extensions.sortArgs(_commands, args);
}
else {
throw parameterException;
}
fixedArgs.add(value);

try {
parameterException = null;
args = fixedArgs.toArray(new String[0]);

_jCommander = _buildJCommanderWithCommandMap(_commands);
args = Extensions.sortArgs(_commands, args);
}
else {
throw parameterException;
}

_jCommander.parse(args);
}
catch (ParameterException pe) {
parameterException = pe;
}
try {
parameterException = null;

jCommands = _jCommander.getCommands();
_jCommander = _buildJCommanderWithCommandMap(_commands);

jCommander = jCommands.get(command);
_jCommander.parse(args);
}
catch (ParameterException pe) {
parameterException = pe;
}

if (jCommander == null) {
printUsage();
jCommands = _jCommander.getCommands();

break;
}
jCommander = jCommands.get(command);

objects = jCommander.getObjects();
if (jCommander == null) {
printUsage();

commandArgs = objects.get(0);
break;
}

objects = jCommander.getObjects();

commandArgs = objects.get(0);
}

if (parameterException == null) {
Expand Down Expand Up @@ -1090,7 +1085,8 @@ else if (!missingParameterOptional.isPresent() &&

String message = sb.toString();

value = _promptForValueWithOptions(missingParametersFormatted, optionsMap, message);
value = _promptForValueWithOptions(
missingParametersFormatted, optionsMap, message, in(), out());

break;
}
Expand All @@ -1102,16 +1098,16 @@ else if (!missingParameterOptional.isPresent() &&
}

private String _promptForValueWithOptions(
String missingParametersFormatted, Map<String, String> optionsMap, String message) {
String missingParametersFormatted, Map<String, String> optionsMap, String message, InputStream inputStream,
PrintStream printStream) {

String value;
value = Prompter.promptString(message);
String value = Prompter.promptString(message, inputStream, printStream);

if ((optionsMap != null) && !optionsMap.isEmpty()) {
while (!optionsMap.containsKey(value) && !optionsMap.containsValue(value)) {
System.out.println("Please enter a valid value for " + missingParametersFormatted);

value = Prompter.promptString("");
value = Prompter.promptString("", inputStream, printStream);
}

if (optionsMap.containsKey(value)) {
Expand Down
5 changes: 3 additions & 2 deletions cli/src/main/java/com/liferay/blade/cli/BladeSettings.java
Original file line number Diff line number Diff line change
Expand Up @@ -24,6 +24,7 @@
import java.io.IOException;

import java.util.Objects;
import java.util.Optional;
import java.util.Properties;

/**
Expand Down Expand Up @@ -86,14 +87,14 @@ public void migrateWorkspaceIfNecessary(BladeCLI bladeCLI) throws IOException {
"WARNING: blade commands will not function properly in a Maven workspace unless the blade " +
"profile is set to \"maven\". Should the settings for this workspace be updated?";

if (Prompter.confirm(question, true)) {
if (Prompter.confirm(question, bladeCLI.in(), bladeCLI.out(), Optional.of(true))) {
setProfileName("maven");
save();
}
else {
question = "Should blade remember this setting for this workspace?";

if (Prompter.confirm(question, true)) {
if (Prompter.confirm(question, bladeCLI.in(), bladeCLI.out(), Optional.of(true))) {
_properties.setProperty("profile.prompt.disabled", "true");
save();
}
Expand Down
18 changes: 5 additions & 13 deletions cli/src/main/java/com/liferay/blade/cli/util/Prompter.java
Original file line number Diff line number Diff line change
Expand Up @@ -31,14 +31,6 @@
*/
public class Prompter {

public static boolean confirm(String question) {
return confirm(question, System.in, System.out, Optional.empty());
}

public static boolean confirm(String question, boolean defaultAnswer) {
return confirm(question, System.in, System.out, Optional.of(defaultAnswer));
}

public static boolean confirm(String question, InputStream in, PrintStream out, Optional<Boolean> defaultAnswer) {
String questionWithPrompt = _buildBooleanQuestionWithPrompt(question, defaultAnswer);

Expand All @@ -51,8 +43,8 @@ public static boolean confirm(String question, InputStream in, PrintStream out,
throw new NoSuchElementException("Unable to acquire an answer");
}

public static String promptString(String question) {
Optional<String> answer = _getStringAnswer(question, System.in, System.out, Optional.empty());
public static String promptString(String question, InputStream inputStream, PrintStream outputStream) {
Optional<String> answer = _getStringAnswer(question, inputStream, outputStream, Optional.empty());

if (answer.isPresent()) {
return answer.get();
Expand Down Expand Up @@ -143,7 +135,7 @@ private static Optional<Boolean> _getBooleanAnswer(
private static Optional<String> _getStringAnswer(
String questionWithPrompt, InputStream inputStream, PrintStream printStream, Optional<String> defaultAnswer) {

Optional<String> answer = null;
Optional<String> answer = Optional.empty();

try (CloseShieldInputStream closeShieldInputStream = new CloseShieldInputStream(inputStream);
Scanner scanner = new Scanner(closeShieldInputStream)) {
Expand All @@ -155,12 +147,12 @@ private static Optional<String> _getStringAnswer(

printStream.print("> ");

String line = null;
answer = Optional.of(scanner.nextLine());

while (((answer == null) || !answer.isPresent()) && !Objects.equals(answer, defaultAnswer) &&
scanner.hasNextLine()) {

line = scanner.nextLine();
String line = scanner.nextLine();

if (line != null) {
line = line.trim();
Expand Down
15 changes: 5 additions & 10 deletions cli/src/test/java/com/liferay/blade/cli/PrompterTest.java
Original file line number Diff line number Diff line change
Expand Up @@ -56,13 +56,8 @@ public void testConfirmDefaultQuestions() throws Exception {
correctAnswerDefaultFalseTests.put("y", true);
correctAnswerDefaultFalseTests.put("y ", true);

Optional<Boolean> trueDefaultAnswer = Optional.of(true);

_testAnswers(correctAnswerDefaultTrueTests, trueDefaultAnswer);

Optional<Boolean> falseDefaultAnswer = Optional.of(false);

_testAnswers(correctAnswerDefaultFalseTests, falseDefaultAnswer);
_testAnswers(correctAnswerDefaultTrueTests, Optional.of(true));
_testAnswers(correctAnswerDefaultFalseTests, Optional.of(false));
}

@Test
Expand All @@ -89,15 +84,15 @@ public void testConfirmQuestions() throws Exception {

@Test
public void testConfirmQuestionsOutput() throws Exception {
String answer = "y";
String answer = "y\n";

String correctResult = _question + " (y/n)";

Map.Entry<Boolean, String> confirmEntry = _confirm(_question, answer);
Map.Entry<Boolean, String> confirmEntry = _confirm(_question, answer, Optional.empty());

String output = confirmEntry.getValue();

Assert.assertEquals(output.trim(), correctResult);
Assert.assertEquals(correctResult, output.trim());

Map<String, Optional<Boolean>> correctEndingOutputTests = new HashMap<>();

Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -27,6 +27,7 @@
import com.liferay.project.templates.ProjectTemplates;

import java.io.BufferedReader;
import java.io.ByteArrayInputStream;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileReader;
Expand Down Expand Up @@ -473,22 +474,27 @@ public void testCreateMissingArgument() throws Exception {

String[] args = {"create", "foobar", "-d", tempRoot.getAbsolutePath()};

String output = null;
InputStream nullInputStream = new InputStream() {

try {
BladeTestResults bladeTestResults = TestUtil.runBlade(_rootDir, _extensionsDir, args);
@Override
public int read() throws IOException {
return -1;
}

};

String message = null;

output = bladeTestResults.getOutput();
try {
TestUtil.runBlade(_rootDir, _extensionsDir, nullInputStream, true, args);
}
catch (Throwable t) {
output = t.getMessage();
message = t.getMessage();
}

Assert.assertNotNull(output);
Assert.assertNotNull(message);

boolean containsError = output.contains("The following option is required");

Assert.assertTrue(containsError);
Assert.assertTrue(message, message.contains("Unable to acquire an answer"));
}

@Test
Expand All @@ -514,6 +520,19 @@ public void testCreateMVCPortlet() throws Exception {
_checkFileExists(projectPath + "/src/main/resources/META-INF/resources/init.jsp");
}

@Test
public void testCreateMVCPortletInteractive() throws Exception {
String[] gradleArgs = {"create", "-d", _rootDir.getAbsolutePath(), "-t", "mvc-portlet"};

ByteArrayInputStream byteArrayInputStream = new ByteArrayInputStream("foo\n".getBytes());

TestUtil.runBlade(_rootDir, _extensionsDir, byteArrayInputStream, true, gradleArgs);

File project = new File(_rootDir, "foo");

_checkGradleBuildFiles(project.getAbsolutePath());
}

@Test
public void testCreateNpmAngular71() throws Exception {
String[] args = {
Expand Down Expand Up @@ -760,6 +779,19 @@ public void testCreateSpringMvcPortlet() throws Exception {
_checkFileExists(projectPath + "/build.gradle");
}

@Test
public void testCreateSpringMVCPortletInteractive() throws Exception {
String[] gradleArgs = {"create", "-d", _rootDir.getAbsolutePath(), "-t", "spring-mvc-portlet"};

ByteArrayInputStream byteArrayInputStream = new ByteArrayInputStream("foo\n".getBytes());

TestUtil.runBlade(_rootDir, _extensionsDir, byteArrayInputStream, true, gradleArgs);

File project = new File(_rootDir, "foo");

_checkGradleBuildFiles(project.getAbsolutePath());
}

@Test
public void testCreateTemplateContextContributor() throws Exception {
String[] args = {
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -268,10 +268,7 @@ public void testInstallExtensionPathRequired() throws Exception {
error = e.getMessage();
}

Assert.assertTrue(
error,
error.contains(
"extension install: Main parameters are required (\"The path of the extension to install.\")"));
Assert.assertTrue(error, error.contains("Unable to acquire an answer"));
}

@Test
Expand Down