Java Code Examples for com.intellij.execution.configurations.GeneralCommandLine

The following are top voted examples for showing how to use com.intellij.execution.configurations.GeneralCommandLine. These examples are extracted from open source projects. You can vote up the examples you like and your votes will be used in our system to generate more good examples.
Example 1
Project: react-native-console   File: TestParseIOSDevices.java   View source code 6 votes vote down vote up
@Test
    public void listDevices() {
        System.out.println(
                System.getProperty("user.home"));
//        System.getProperties().list(System.out);

        GeneralCommandLine commandLine = RNPathUtil.cmdToGeneralCommandLine(IOSDevicesParser.LIST_Simulator_JSON);

        try {
            String json = ExecUtil.execAndGetOutput(commandLine).getStdout();
            System.out.println("json=" + json);
            Simulators result = new Gson().fromJson(json, Simulators.class);
            System.out.println(result.devices.keySet());
            System.out.println(result.devices.get("iOS 10.3")[0]);
        } catch (ExecutionException e) {
            e.printStackTrace();
            NotificationUtils.errorNotification( "xcrun invocation failed. Please check that Xcode is installed." );
        }

    }
 
Example 2
Project: react-native-console   File: TestParseIOSDevices.java   View source code 6 votes vote down vote up
@Test
    public void parseCurrentPathFromRNConsoleJsonFile() {
        //        System.out.println(
//                System.getProperty("user.home"));
//        System.getProperties().list(System.out);

        GeneralCommandLine commandLine = RNPathUtil.cmdToGeneralCommandLine(IOSDevicesParser.LIST_DEVICES);
        try {
            String json = ExecUtil.execAndGetOutput(commandLine).getStdout();
            System.out.println(json);
            Arrays.asList(json.split("\n")).forEach(line -> {
                System.out.println(line);
//                Pattern pattern = Pattern
//                        .compile("^([hH][tT]{2}[pP]://|[hH][tT]{2}[pP][sS]://)(([A-Za-z0-9-~]+).)+([A-Za-z0-9-~\\/])+$");
                boolean device = line.matches("^(.*?) \\((.*?)\\)\\ \\[(.*?)\\]");
                System.out.println("device=" + device);
//                String noSimulator = line.match(/(.*?) \((.*?)\) \[(.*?)\] \((.*?)\)/);
            });

        } catch (ExecutionException e) {
            e.printStackTrace();
            NotificationUtils.errorNotification( "xcrun invocation failed. Please check that Xcode is installed." );
            return;
        }
    }
 
Example 3
Project: educational-plugin   File: PyCCCommandLineState.java   View source code 6 votes vote down vote up
@Override
protected void buildCommandLineParameters(GeneralCommandLine commandLine) {
  commandLine.setWorkDirectory(myTaskDir.getPath());
  ParamsGroup group = commandLine.getParametersList().getParamsGroup(GROUP_SCRIPT);
  assert group != null;

  Project project = myRunConfiguration.getProject();
  Course course = StudyTaskManager.getInstance(project).getCourse();
  assert course != null;

  group.addParameter(myRunConfiguration.getPathToTest());

  String path = getCurrentTaskFilePath();
  if (path != null) {
    group.addParameter(path);
  }
}
 
Example 4
Project: roc-completion   File: FetchCompletions.java   View source code 6 votes vote down vote up
public void run() throws Exception
{
    // Prepare and run node-command which will fetch settings.
    GeneralCommandLine commandLine = createCommandLine();
    Process process = commandLine.createProcess();

    String input = readInputStream(process.getInputStream());
    Gson gson = new GsonBuilder()
        .registerTypeAdapter(DefaultValue.class, new DefaultValueDeserializer())
        .create();

    Type targetType = new TypeToken<List<SettingTreeNode>>() {}.getType();
    List<SettingTreeNode> settings = gson.fromJson(input, targetType);

    if (settings == null)
    {
        String error = readInputStream(process.getErrorStream());
        String message = error.length() > 0 ? error : input;

        throw new Exception("Error occured while fetching completions: " + message);
    }

    SettingContainer completions = new SettingContainer(settings);
    CompletionPreloader.setCompletions(completions);
}
 
Example 5
Project: roc-completion   File: FetchCompletions.java   View source code 6 votes vote down vote up
private GeneralCommandLine createCommandLine() throws Exception
{
    GeneralCommandLine commandLine = new GeneralCommandLine();
    commandLine
        .withParentEnvironmentType(GeneralCommandLine.ParentEnvironmentType.CONSOLE)
        .withCharset(StandardCharsets.UTF_8)
        .withWorkDirectory(project.getBasePath());

    NodeJsLocalInterpreter interpreter = NodeJsLocalInterpreterManager
        .getInstance()
        .detectMostRelevant();

    if (interpreter == null)
    {
        throw new Exception("Unable to create node-interpreter.");
    }
    // Move getSettings.js resource to .idea-folder within current project.
    ensureJsFile();

    commandLine.setExePath(interpreter.getInterpreterSystemDependentPath());
    commandLine.addParameter(getJsFilePath());
    commandLine.addParameter("roc-config");

    return commandLine;
}
 
Example 6
Project: intellij-ce-playground   File: PyStudyExecutor.java   View source code 6 votes vote down vote up
@Override
public void setCommandLineParameters(@NotNull final GeneralCommandLine cmd,
                                             @NotNull final Project project,
                                             @NotNull final String filePath,
                                             @NotNull final String sdkPath,
                                             @NotNull final Task currentTask) {
  final List<UserTest> userTests = StudyTaskManager.getInstance(project).getUserTests(currentTask);
  if (!userTests.isEmpty()) {
    StudyLanguageManager manager = StudyUtils.getLanguageManager(currentTask.getLesson().getCourse());
    if (manager != null) {
      cmd.addParameter(new File(project.getBaseDir().getPath(), manager.getUserTester()).getPath());
      cmd.addParameter(sdkPath);
      cmd.addParameter(filePath);
    }
  }
  else {
    cmd.addParameter(filePath);
  }
}
 
Example 7
Project: lua-for-idea   File: LuaCommandLineState.java   View source code 6 votes vote down vote up
protected GeneralCommandLine generateCommandLine() {
    GeneralCommandLine commandLine = new GeneralCommandLine();
    final LuaRunConfiguration cfg = (LuaRunConfiguration) runConfiguration;

    if (cfg.isOverrideSDKInterpreter()) {
        if (!StringUtil.isEmptyOrSpaces(cfg.getInterpreterPath()))
            commandLine.setExePath(cfg.getInterpreterPath());
    } else {
        final Sdk sdk = cfg.getSdk();

        if (sdk == null) {
            fillInterpreterCommandLine(commandLine);
        } else if (sdk.getSdkType() instanceof LuaSdkType) {
            String sdkHomePath = StringUtil.notNullize(sdk.getHomePath());
            String sdkInterpreter = getTopLevelExecutable(sdkHomePath).getAbsolutePath();
            commandLine.setExePath(sdkInterpreter);
        }
    }

    commandLine.getEnvironment().putAll(cfg.getEnvs());
    commandLine.setPassParentEnvironment(cfg.isPassParentEnvs());

    return configureCommandLine(commandLine);
}
 
Example 8
Project: intellij-ce-playground   File: PyCondaManagementService.java   View source code 6 votes vote down vote up
@Override
public void removeRepository(String repositoryUrl) {
  final String conda = PyCondaPackageService.getCondaExecutable();
  final ArrayList<String> parameters = Lists.newArrayList(conda, "config", "--remove", "channels", repositoryUrl, "--force");
  final GeneralCommandLine commandLine = new GeneralCommandLine(parameters);

  try {
    final Process process = commandLine.createProcess();
    final CapturingProcessHandler handler = new CapturingProcessHandler(process);
    final ProcessOutput result = handler.runProcess();
    final int exitCode = result.getExitCode();
    if (exitCode != 0) {
      final String message = StringUtil.isEmptyOrSpaces(result.getStdout()) && StringUtil.isEmptyOrSpaces(result.getStderr()) ?
                             "Permission denied" : "Non-zero exit code";
      LOG.warn("Failed to remove repository " + message);
    }
    PyCondaPackageService.getInstance().removeChannel(repositoryUrl);
  }
  catch (ExecutionException e) {
    LOG.warn("Failed to remove repository");
  }
}
 
Example 9
Project: teamcity-symbol-server   File: JetSymbolsExe.java   View source code 6 votes vote down vote up
public int dumpPdbGuidsToFile(Collection<File> files, File output, BuildProgressLogger buildLogger) throws IOException {
  final GeneralCommandLine commandLine = new GeneralCommandLine();
  commandLine.setExePath(myExePath.getPath());
  commandLine.addParameter(DUMP_SYMBOL_SIGN_CMD);
  commandLine.addParameter(String.format("/o=%s", output.getPath()));
  commandLine.addParameter(String.format("/i=%s", dumpPathsToFile(files).getPath()));
  buildLogger.message(String.format("Running command %s", commandLine.getCommandLineString()));
  final ExecResult execResult = SimpleCommandLineProcessRunner.runCommand(commandLine, null);
  final String stdout = execResult.getStdout();
  if(!stdout.isEmpty()){
    buildLogger.message("Stdout: " + stdout);
  }
  final int exitCode = execResult.getExitCode();
  if (exitCode != 0) {
    buildLogger.warning(String.format("%s ends with non-zero exit code %s.", SYMBOLS_EXE, execResult));
    buildLogger.warning("Stdout: " + stdout);
    buildLogger.warning("Stderr: " + execResult.getStderr());
    final Throwable exception = execResult.getException();
    if(exception != null){
      buildLogger.exception(exception);
    }
  }
  return exitCode;
}
 
Example 10
Project: intellij-ce-playground   File: ShellCommand.java   View source code 6 votes vote down vote up
public ShellCommand(@Nullable List<String> commandLine, @Nullable String dir, @Nullable Charset charset) {
  if (commandLine == null || commandLine.isEmpty()) {
    throw new IllegalArgumentException("commandLine is empty");
  }
  myCommandLine = new GeneralCommandLine(commandLine);
  if (dir != null) {
    myCommandLine.setWorkDirectory(new File(dir));
  }
  if (charset != null) {
    myCommandLine.setCharset(charset);
  }
  if (ApplicationManager.getApplication().isUnitTestMode()) {
    //ignore all hg config files except current repository config
    myCommandLine.getEnvironment().put("HGRCPATH", "");
  }
}
 
Example 11
Project: intellij-ce-playground   File: MvcConsole.java   View source code 6 votes vote down vote up
public ConsoleProcessDescriptor executeProcess(final Module module,
                                               final GeneralCommandLine commandLine,
                                               @Nullable final Runnable onDone,
                                               boolean showConsole,
                                               final boolean closeOnDone,
                                               final String... input) {
  ApplicationManager.getApplication().assertIsDispatchThread();
  assert module.getProject() == myProject;
  
  final MyProcessInConsole process = new MyProcessInConsole(module, commandLine, onDone, showConsole, closeOnDone, input);
  if (isExecuting()) {
    myProcessQueue.add(process);
  }
  else {
    executeProcessImpl(process, true);
  }
  return process;
}
 
Example 12
Project: intellij-ce-playground   File: PyRemoteProcessStarter.java   View source code 6 votes vote down vote up
protected PyRemoteProcessHandlerBase doStartRemoteProcess(@NotNull Sdk sdk,
                                                          @NotNull final GeneralCommandLine commandLine,
                                                          @NotNull final PythonRemoteInterpreterManager manager,
                                                          @Nullable final Project project,
                                                          @Nullable PyRemotePathMapper pathMapper)
  throws ExecutionException {
  SdkAdditionalData data = sdk.getSdkAdditionalData();
  assert data instanceof PyRemoteSdkAdditionalDataBase;
  final PyRemoteSdkAdditionalDataBase pyRemoteSdkAdditionalDataBase = (PyRemoteSdkAdditionalDataBase)data;

  final PyRemotePathMapper extendedPathMapper = manager.setupMappings(project, pyRemoteSdkAdditionalDataBase, pathMapper);

  try {
    return PyRemoteProcessStarterManagerUtil
      .getManager(pyRemoteSdkAdditionalDataBase).startRemoteProcess(project, commandLine, manager, pyRemoteSdkAdditionalDataBase,
                                                   extendedPathMapper);
  }
  catch (InterruptedException e) {
    throw new ExecutionException(e);
  }
}
 
Example 13
Project: intellij-ce-playground   File: BrowserLauncherAppless.java   View source code 6 votes vote down vote up
private static void addArgs(@NotNull GeneralCommandLine command, @Nullable BrowserSpecificSettings settings, @NotNull String[] additional) {
  List<String> specific = settings == null ? Collections.<String>emptyList() : settings.getAdditionalParameters();
  if (specific.size() + additional.length > 0) {
    if (isOpenCommandUsed(command)) {
      if (BrowserUtil.isOpenCommandSupportArgs()) {
        command.addParameter("--args");
      }
      else {
        LOG.warn("'open' command doesn't allow to pass command line arguments so they will be ignored: " +
                 StringUtil.join(specific, ", ") + " " + Arrays.toString(additional));
        return;
      }
    }

    command.addParameters(specific);
    command.addParameters(additional);
  }
}
 
Example 14
Project: intellij-ce-playground   File: PyCondaPackageManagerImpl.java   View source code 6 votes vote down vote up
@NotNull
public static String createVirtualEnv(@NotNull String destinationDir, String version) throws ExecutionException {
  final String condaExecutable = PyCondaPackageService.getCondaExecutable();
  if (condaExecutable == null) throw new PyExecutionException("Cannot find conda", "Conda", Collections.<String>emptyList(), new ProcessOutput());

  final ArrayList<String> parameters = Lists.newArrayList(condaExecutable, "create", "-p", destinationDir,
                                                          "python=" + version, "-y");

  final GeneralCommandLine commandLine = new GeneralCommandLine(parameters);
  final Process process = commandLine.createProcess();
  final CapturingProcessHandler handler = new CapturingProcessHandler(process);
  final ProgressIndicator indicator = ProgressManager.getInstance().getProgressIndicator();
  final ProcessOutput result = handler.runProcessWithProgressIndicator(indicator);
  if (result.isCancelled()) {
    throw new RunCanceledByUserException();
  }
  final int exitCode = result.getExitCode();
  if (exitCode != 0) {
    final String message = StringUtil.isEmptyOrSpaces(result.getStdout()) && StringUtil.isEmptyOrSpaces(result.getStderr()) ?
                           "Permission denied" : "Non-zero exit code";
    throw new PyExecutionException(message, "Conda", parameters, result);
  }
  final String binary = PythonSdkType.getPythonExecutable(destinationDir);
  final String binaryFallback = destinationDir + File.separator + "bin" + File.separator + "python";
  return (binary != null) ? binary : binaryFallback;
}
 
Example 15
Project: intellij-ce-playground   File: GitHandler.java   View source code 6 votes vote down vote up
/**
 * A constructor
 *
 * @param project   a project
 * @param directory a process directory
 * @param command   a command to execute (if empty string, the parameter is ignored)
 */
protected GitHandler(@NotNull Project project, @NotNull File directory, @NotNull GitCommand command) {
  myProject = project;
  myCommand = command;
  myAppSettings = GitVcsApplicationSettings.getInstance();
  myProjectSettings = GitVcsSettings.getInstance(myProject);
  myEnv = new HashMap<String, String>(EnvironmentUtil.getEnvironmentMap());
  myVcs = ObjectUtils.assertNotNull(GitVcs.getInstance(project));
  myWorkingDirectory = directory;
  myCommandLine = new GeneralCommandLine();
  if (myAppSettings != null) {
    myCommandLine.setExePath(myAppSettings.getPathToGit());
  }
  myCommandLine.setWorkDirectory(myWorkingDirectory);
  if (GitVersionSpecialty.CAN_OVERRIDE_GIT_CONFIG_FOR_COMMAND.existsIn(myVcs.getVersion())) {
    myCommandLine.addParameters("-c", "core.quotepath=false");
  }
  myCommandLine.addParameter(command.name());
  myStdoutSuppressed = true;
  mySilent = myCommand.lockingPolicy() == GitCommand.LockingPolicy.READ;
}
 
Example 16
Project: intellij   File: ScopedBlazeProcessHandler.java   View source code 6 votes vote down vote up
public ScopedBlazeProcessHandler(
    Project project,
    List<String> command,
    WorkspaceRoot workspaceRoot,
    ScopedProcessHandlerDelegate scopedProcessHandlerDelegate)
    throws ExecutionException {
  super(new GeneralCommandLine(command).withWorkDirectory(workspaceRoot.directory().getPath()));

  this.scopedProcessHandlerDelegate = scopedProcessHandlerDelegate;
  this.context = new BlazeContext();
  // The context is released in the ScopedProcessHandlerListener.
  this.context.hold();

  for (ProcessListener processListener :
      scopedProcessHandlerDelegate.createProcessListeners(context)) {
    addProcessListener(processListener);
  }
  addProcessListener(new ScopedProcessHandlerListener(project));
}
 
Example 17
Project: intellij-ce-playground   File: ExecutableValidator.java   View source code 6 votes vote down vote up
protected static boolean doCheckExecutable(@NotNull String executable, @NotNull List<String> processParameters) {
  try {
    GeneralCommandLine commandLine = new GeneralCommandLine();
    commandLine.setExePath(executable);
    commandLine.addParameters(processParameters);
    CapturingProcessHandler handler = new CapturingProcessHandler(commandLine.createProcess(), CharsetToolkit.getDefaultSystemCharset());
    ProcessOutput result = handler.runProcess(TIMEOUT_MS);
    boolean timeout = result.isTimeout();
    int exitCode = result.getExitCode();
    String stderr = result.getStderr();
    if (timeout) {
      LOG.warn("Validation of " + executable + " failed with a timeout");
    }
    if (exitCode != 0) {
      LOG.warn("Validation of " + executable + " failed with a non-zero exit code: " + exitCode);
    }
    if (!stderr.isEmpty()) {
      LOG.warn("Validation of " + executable + " failed with a non-empty error output: " + stderr);
    }
    return !timeout && exitCode == 0 && stderr.isEmpty();
  }
  catch (Throwable t) {
    LOG.warn(t);
    return false;
  }
}
 
Example 18
Project: intellij-ce-playground   File: SystemHealthMonitor.java   View source code 6 votes vote down vote up
private void checkIBus() {
  if (SystemInfo.isXWindow) {
    String xim = System.getenv("XMODIFIERS");
    if (xim != null && xim.contains("im=ibus")) {
      String version = ExecUtil.execAndReadLine(new GeneralCommandLine("ibus-daemon", "--version"));
      if (version != null) {
        Matcher m = Pattern.compile("ibus-daemon - Version ([0-9.]+)").matcher(version);
        if (m.find() && StringUtil.compareVersionNumbers(m.group(1), "1.5.11") < 0) {
          String fix = System.getenv("IBUS_ENABLE_SYNC_MODE");
          if (fix == null || fix.isEmpty() || fix.equals("0") || fix.equalsIgnoreCase("false")) {
            showNotification("ibus.blocking.warn.message");
          }
        }
      }
    }
  }
}
 
Example 19
Project: intellij-ce-playground   File: GeneralCommandLineTest.java   View source code 6 votes vote down vote up
@Test
public void printCommandLine() {
  GeneralCommandLine commandLine = new GeneralCommandLine();
  commandLine.setExePath("e x e path");
  commandLine.addParameter("with space");
  commandLine.addParameter("\"quoted\"");
  commandLine.addParameter("\"quoted with spaces\"");
  commandLine.addParameters("param 1", "param2");
  commandLine.addParameter("trailing slash\\");
  assertEquals("\"e x e path\"" +
               " \"with space\"" +
               " \\\"quoted\\\"" +
               " \"\\\"quoted with spaces\\\"\"" +
               " \"param 1\"" +
               " param2" +
               " \"trailing slash\\\"",
               commandLine.getCommandLineString());
}
 
Example 20
Project: intellij-ce-playground   File: GeneralCommandLineTest.java   View source code 6 votes vote down vote up
@Test
public void unicodePath() throws Exception {
  String mark = String.valueOf(new Random().nextInt());
  String prefix = "spaces 'and quotes' and " + UNICODE_RU + "_" + UNICODE_EU + " ";

  File script;
  if (SystemInfo.isWindows) {
    script = ExecUtil.createTempExecutableScript(prefix, ".cmd", "@echo " + mark + "\n");
  }
  else {
    script = ExecUtil.createTempExecutableScript(prefix, ".sh", "#!/bin/sh\n" + "echo " + mark + "\n");
  }

  try {
    String output = execAndGetOutput(new GeneralCommandLine(script.getPath()));
    assertEquals(mark + "\n", StringUtil.convertLineSeparators(output));
  }
  finally {
    FileUtil.delete(script);
  }
}
 
Example 21
Project: intellij-ce-playground   File: GeneralCommandLineTest.java   View source code 6 votes vote down vote up
@Test
public void winShellScriptQuoting() throws Exception {
  assumeTrue(SystemInfo.isWindows);

  String scriptPrefix = "my_script";
  for (String scriptExt : new String[]{".cmd", ".bat"}) {
    File script = ExecUtil.createTempExecutableScript(scriptPrefix, scriptExt, "@echo %1\n");
    String param = "a&b";
    GeneralCommandLine commandLine = new GeneralCommandLine(script.getAbsolutePath(), param);
    String text = commandLine.getPreparedCommandLine(Platform.WINDOWS);
    assertEquals(commandLine.getExePath() + "\n" + StringUtil.wrapWithDoubleQuote(param), text);
    try {
      String output = execAndGetOutput(commandLine);
      assertEquals(StringUtil.wrapWithDoubleQuote(param), output.trim());
    }
    finally {
      FileUtil.delete(script);
    }
  }
}
 
Example 22
Project: intellij-ce-playground   File: Haxm.java   View source code 6 votes vote down vote up
@Override
public void configure(@NotNull InstallContext installContext, @NotNull File sdk) {
  if (!canRun()) {
    Logger.getInstance(getClass()).error(
      String.format("Tried to install HAXM on %s OS with %s memory size", Platform.current().name(), String.valueOf(getMemorySize())));
    installContext.print("Unable to install Intel HAXM\n", ConsoleViewContentType.ERROR_OUTPUT);
    return;
  }
  try {
    GeneralCommandLine commandLine = getInstallCommandLine(sdk);
    runInstaller(installContext, commandLine);
  }
  catch (WizardException e) {
    String message = e.getMessage();
    if (!StringUtil.endsWithLineBreak(message)) {
      message += "\n";
    }
    installContext.print(message, ConsoleViewContentType.ERROR_OUTPUT);
    LOG.error(e);
  }
}
 
Example 23
Project: intellij-ce-playground   File: PydevConsoleRunner.java   View source code 6 votes vote down vote up
@NotNull
protected GeneralCommandLine doCreateConsoleCmdLine(Sdk sdk,
                                                    Map<String, String> environmentVariables,
                                                    String workingDir,
                                                    int[] ports,
                                                    PythonHelper helper) {
  PyConsoleOptions.PyConsoleSettings settings = PyConsoleOptions.getInstance(getProject()).getPythonConsoleSettings();


  GeneralCommandLine cmd =
    PythonCommandLineState.createPythonCommandLine(getProject(), new PythonConsoleRunParams(settings, workingDir, sdk,
                                                                                            environmentVariables));
  cmd.withWorkDirectory(getWorkingDir());

  ParamsGroup group = cmd.getParametersList().getParamsGroup(PythonCommandLineState.GROUP_SCRIPT);
  helper.addToGroup(group, cmd);

  for (int port : ports) {
    group.addParameter(String.valueOf(port));
  }

  return cmd;
}
 
Example 24
Project: intellij-ce-playground   File: PythonScriptCommandLineState.java   View source code 6 votes vote down vote up
@Override
protected void buildCommandLineParameters(GeneralCommandLine commandLine) {
  ParametersList parametersList = commandLine.getParametersList();
  ParamsGroup exe_options = parametersList.getParamsGroup(GROUP_EXE_OPTIONS);
  assert exe_options != null;
  exe_options.addParametersString(myConfig.getInterpreterOptions());

  ParamsGroup script_parameters = parametersList.getParamsGroup(GROUP_SCRIPT);
  assert script_parameters != null;
  if (!StringUtil.isEmptyOrSpaces(myConfig.getScriptName())) {
    script_parameters.addParameter(myConfig.getScriptName());
  }

  final String script_options_string = myConfig.getScriptParameters();
  if (script_options_string != null) script_parameters.addParametersString(script_options_string);

  if (!StringUtil.isEmptyOrSpaces(myConfig.getWorkingDirectory())) {
    commandLine.setWorkDirectory(myConfig.getWorkingDirectory());
  }
}
 
Example 25
Project: intellij-ce-playground   File: BuildoutFacet.java   View source code 6 votes vote down vote up
public void patchCommandLineForBuildout(GeneralCommandLine commandLine) {
  Map<String, String> env = commandLine.getEnvironment();
  ParametersList params = commandLine.getParametersList();
  // alter execution script
  ParamsGroup scriptParams = params.getParamsGroup(PythonCommandLineState.GROUP_SCRIPT);
  assert scriptParams != null;
  if (scriptParams.getParameters().size() > 0) {
    String normalScript = scriptParams.getParameters().get(0); // expect DjangoUtil.MANAGE_FILE
    HelperPackage engulfer = PythonHelper.BUILDOUT_ENGULFER;
    env.put("PYCHARM_ENGULF_SCRIPT", getConfiguration().getScriptName());
    scriptParams.getParametersList().replaceOrPrepend(normalScript, engulfer.asParamString());
  }
  // add pycharm helpers to pythonpath so that fixGetpass is importable

  PythonEnvUtil.addToPythonPath(env, PythonHelpersLocator.getHelpersRoot().getAbsolutePath());
  /*
  // set prependable paths
  List<String> paths = facet.getAdditionalPythonPath();
  if (paths != null) {
    path_value = PyUtil.joinWith(File.pathSeparator, paths);
    env.put("PYCHARM_PREPEND_SYSPATH", path_value);
  }
  */
}
 
Example 26
Project: react-native-console   File: RNConsoleImpl.java   View source code 5 votes vote down vote up
/**
 * 执行shell
 *
 * @param shell
 */
public void executeShell(String shell, String workDirectory) {
    GeneralCommandLine commandLine =RNPathUtil.createFullPathCommandLine(shell, workDirectory);
    commandLine.setWorkDirectory(workDirectory);
    myGeneralCommandLine = commandLine;
    try {
        processCommandline(commandLine);
    } catch (ExecutionException e) {
        NotificationUtils.showNotification("Unable to run the commandline:" + e.getMessage(),
                NotificationType.WARNING);
    }
}
 
Example 27
Project: react-native-console   File: RNConsoleImpl.java   View source code 5 votes vote down vote up
/**
 * Execute raw commands without any path or param modify.
 *
 * @param shell
 */
public void executeRawShell(String workDirectory, String[] shell) {
    GeneralCommandLine commandLine =new GeneralCommandLine(shell);
    commandLine.setWorkDirectory(workDirectory);
    myGeneralCommandLine = commandLine;
    try {
        processCommandline(commandLine);
    } catch (ExecutionException e) {
        NotificationUtils.showNotification("Unable to run the commandline:" + e.getMessage(),
                NotificationType.WARNING);
    }
}
 
Example 28
Project: react-native-console   File: RNUtil.java   View source code 5 votes vote down vote up
public static void runGradleCI(Project project, String... params) {
        String path = RNPathUtil.getRNProjectPath(project);
        String gradleLocation = RNPathUtil.getAndroidProjectPath(path);
        if (gradleLocation == null) {
            NotificationUtils.gradleFileNotFound();
        } else {
            GeneralCommandLine commandLine = new GeneralCommandLine();
//    ExecutionEnvironment environment = getEnvironment();
            commandLine.setWorkDirectory(gradleLocation);
            commandLine.setExePath("." + File.separator + "gradlew");
            commandLine.addParameters(params);

//            try {
////            Process process = commandLine.createProcess();
//                OSProcessHandler processHandler = new KillableColoredProcessHandler(commandLine);
//                RunnerUtil.showHelperProcessRunContent("Update AAR", processHandler, project, DefaultRunExecutor.getRunExecutorInstance());
//                // Run
//                processHandler.startNotify();
//            } catch (ExecutionException e) {
//                e.printStackTrace();
//                NotificationUtils.errorNotification("Can't execute command: " + e.getMessage());
//            }

            // commands process
            try {
                processCommandline(project, commandLine);
            } catch (ExecutionException e) {
                e.printStackTrace();
            }
        }
    }
 
Example 29
Project: react-native-console   File: RNUtil.java   View source code 5 votes vote down vote up
public static void build(Project project) {
    GeneralCommandLine commandLine = new GeneralCommandLine();
    commandLine.setWorkDirectory(project.getBasePath());
    commandLine.setExePath("python");
    commandLine.addParameter("freeline.py");
    // debug
    commandLine.addParameter("-d");

    // commands process
    try {
        processCommandline(project, commandLine);
    } catch (ExecutionException e) {
        e.printStackTrace();
    }
}
 
Example 30
Project: react-native-console   File: RNUtil.java   View source code 5 votes vote down vote up
private static void processCommandline(final Project project, GeneralCommandLine commandLine) throws ExecutionException {
        final OSProcessHandler processHandler = new OSProcessHandler(commandLine);
        ProcessTerminatedListener.attach(processHandler);
//        processHandler.startNotify();// Don't call this, the command content will not be shown

        ApplicationManager.getApplication().invokeLater(new Runnable() {
            @Override
            public void run() {
                processConsole(project, processHandler);
            }
        });
    }
 
Example 31
Project: AppleScript-IDEA   File: AppleScriptScriptCommandLineState.java   View source code 5 votes vote down vote up
@NotNull
@Override
protected ProcessHandler startProcess() throws ExecutionException {
  String scriptPath = runConfiguration.getScriptPath();
  String scriptParameters = runConfiguration.getScriptParameters();
  String scriptOptions = runConfiguration.getScriptOptions();

  scriptPath = scriptPath == null ? "" : scriptPath;//todo change this (and add validator to run config)
  final List<String> commandString = new ArrayList<>();
  commandString.add("/usr/bin/osascript");
  if (!StringUtil.isEmpty(scriptOptions)) {
    String[] options = scriptOptions.split(" ");
    commandString.addAll(Arrays.asList(options));
  }
  commandString.add(scriptPath);
  if (!StringUtil.isEmpty(scriptParameters)) {
    Pattern regex = Pattern.compile("\"([^\"]*)\"|(\\w+)");
    final ArrayList<String> matchedParams = new ArrayList<>();
    Matcher matcher = regex.matcher(scriptParameters);
    while (matcher.find()) {
      for (int i = 1; i <= matcher.groupCount(); i++) {
        try {
          String p = matcher.group(i);
          if (!StringUtil.isEmpty(p)) matchedParams.add(p);
        } catch (IllegalStateException | IndexOutOfBoundsException e) {
          LOG.warn("Error parsing script parameters: " + e.getMessage());
        }
      }
    }
    commandString.addAll(matchedParams);
  }

  final GeneralCommandLine commandLine = new GeneralCommandLine(commandString);
  if (runConfiguration.isShowAppleEvents()) {
    commandLine.withEnvironment("AEDebugSends", "1");
    commandLine.withEnvironment("AEDebugReceives", "1");
  }
  return new AppleScriptProcessHandler(commandLine);
}
 
Example 32
Project: LaravelStorm   File: FileMakerDlg.java   View source code 5 votes vote down vote up
@Override
protected void doOKAction() {

    Notification notification = new Notification("LaravelStorm",
            "Success", "temp content", NotificationType.INFORMATION);

    Notification errorNotification = new Notification("LaravelStorm",
            "Error", "Could not create file.", NotificationType.ERROR);

    GeneralCommandLine cmd = new GeneralCommandLine("php", "artisan");
    cmd.setWorkDirectory(project.getBasePath());

    cmd.addParameter(artisanCommand);

    if (additionCommandCheckBox.isSelected())
        cmd.addParameter(optionCmdParameter);

    cmd.addParameter(fileName.getText());

    try {
        BufferedReader reader = new BufferedReader(new InputStreamReader(cmd.createProcess().getInputStream()));
        String execResult = reader.readLine();
        if (execResult.isEmpty()){
            Notifications.Bus.notify(errorNotification, project);
        }
        else{
            notification.setContent(execResult);
            Notifications.Bus.notify(notification, project);
        }
    } catch (ExecutionException | IOException e) {
        e.printStackTrace();
    }

    super.doOKAction();
}
 
Example 33
Project: Gherkin-TS-Runner   File: GherkinIconRenderer.java   View source code 5 votes vote down vote up
private GeneralCommandLine getProtractorRunCommand(@NotNull Config config) {
    GeneralCommandLine commandLine = new GeneralCommandLine();
    commandLine.setExePath(config.getProtractorCmdPath());
    commandLine.setWorkDirectory(project.getBasePath());
    commandLine.addParameter(config.getProtractorConfigJsPath());

    StringBuilder specArg = new StringBuilder().append("--specs=").append(config.getFeaturesDirPath()).append("/").append(fileName);
    if(icon == SCENARIO_ICON) {
        specArg.append(":").append(line + 1);
    }

    commandLine.addParameter(specArg.toString());

    return commandLine;
}
 
Example 34
Project: Gherkin-TS-Runner   File: GherkinIconRenderer.java   View source code 5 votes vote down vote up
private void callProtractor() {
    try {
        Config config = Config.getInstance(project);

        if (config == null) {
            return;
        }

        GeneralCommandLine command = getProtractorRunCommand(config);
        Process p = command.createProcess();

        if (project != null) {
            ToolWindowManager manager = ToolWindowManager.getInstance(project);
            String id = "Gherkin Runner";
            TextConsoleBuilderFactory factory = TextConsoleBuilderFactory.getInstance();
            TextConsoleBuilder builder = factory.createBuilder(project);
            ConsoleView view = builder.getConsole();

            ColoredProcessHandler handler = new ColoredProcessHandler(p, command.getPreparedCommandLine());
            handler.startNotify();
            view.attachToProcess(handler);

            ToolWindow window = manager.getToolWindow(id);
            Icon cucumberIcon = IconLoader.findIcon("/resources/icons/cucumber.png");

            if (window == null) {
                window = manager.registerToolWindow(id, true, ToolWindowAnchor.BOTTOM);
                window.setIcon(cucumberIcon);
            }

            ContentFactory cf = window.getContentManager().getFactory();
            Content c = cf.createContent(view.getComponent(), "Run " + (window.getContentManager().getContentCount() + 1), true);

            window.getContentManager().addContent(c);
        }
    } catch (Exception e) {
        System.out.println(e.getMessage());
    }
}
 
Example 35
Project: teamcity-powershell   File: DetectionRunner.java   View source code 5 votes vote down vote up
/**
 * Runs detection script
 *
 * @param executablePath executable to run script with
 * @param detectionScriptPath file containing detection script
 * @return lines from stdout
 * @throws ExecutionException if there was an error during execution
 */
List<String> runDetectionScript(@NotNull final String executablePath, @NotNull final String detectionScriptPath) throws ExecutionException {
  final GeneralCommandLine cl = new GeneralCommandLine();
  cl.setExePath(executablePath);
  cl.addParameter("-NoProfile");
  cl.addParameter("-File");
  cl.addParameter(detectionScriptPath);
  if (LOG.isDebugEnabled()) {
    LOG.debug("Running detection script using command line: " + cl.getCommandLineString());
  }
  final ProcessOutput execResult = runProcess(cl);
  return execResult.getStdoutLines();
}
 
Example 36
Project: teamcity-powershell   File: DetectionRunner.java   View source code 5 votes vote down vote up
private static ProcessOutput runProcess(@NotNull final GeneralCommandLine cl) throws ExecutionException {
  final CapturingProcessHandler handler = new CapturingProcessHandler(cl.createProcess(), Charset.forName("UTF-8"));
  final ProcessOutput result = handler.runProcess(20000);
  if (result.isTimeout()) {
    throw new ExecutionException("Process execution of [" + cl.getCommandLineString() + "] has timed out");
  }
  final String errorOutput = result.getStderr();
  if (!StringUtil.isEmptyOrSpaces(errorOutput)) {
    throw new ExecutionException(errorOutput);
  }
  return result;
}
 
Example 37
Project: teamcity-powershell   File: PowerShellServiceUnix.java   View source code 5 votes vote down vote up
private static void enableExecution(@NotNull final File filePath) {
  final GeneralCommandLine commandLine = new GeneralCommandLine();
  
  commandLine.setExePath("chmod");
  commandLine.addParameter("+x");
  commandLine.addParameter(filePath.getName());
  commandLine.setWorkDirectory(filePath.getParent());

  final ExecResult execResult = SimpleCommandLineProcessRunner.runCommand(commandLine, null);
  if (execResult.getExitCode() != 0) {
    LOG.warn("Failed to set executable attribute for " + filePath + ": chmod +x exit code is " + execResult.getExitCode());
  }
}
 
Example 38
Project: teamcity-autotools-plugin   File: AutotoolsToolProvider.java   View source code 5 votes vote down vote up
/**
 * Returns True if Existed Tool myConfigName
 * @return
 */
public boolean isExistedTool(){
  final GeneralCommandLine commandLine = new GeneralCommandLine();
  commandLine.setExePath(myToolName);
  commandLine.addParameter(myVersionArg);
  final ExecResult execResult = SimpleCommandLineProcessRunner.runCommand(commandLine, (byte[])null);
  if (execResult.getExitCode() == 0){
    myVersion = findVersion(stringArrayToString(execResult.getOutLines()));
  }
  return execResult.getExitCode() == 0;
}
 
Example 39
Project: teamcity-autotools-plugin   File: AutotoolsBuildCLBService.java   View source code 5 votes vote down vote up
/**
 * Set executable attribute for file.
 * @param filePath File to be setted executable attribute
 * @param baseDir Directory to be setted Work Directory
 */
private static void enableExecution(@NotNull final String filePath, @NotNull final String baseDir) {
  final GeneralCommandLine commandLine = new GeneralCommandLine();
  commandLine.setExePath("chmod");
  commandLine.addParameter("+x");
  commandLine.addParameter(filePath);
  commandLine.setWorkDirectory(baseDir);
  final ExecResult execResult = SimpleCommandLineProcessRunner.runCommand(commandLine, null);
  if(execResult.getExitCode() != 0) {
    Loggers.AGENT.warn("Failed to set executable attribute for " + filePath + ": chmod +x exit code is " + execResult.getExitCode());
  }
}
 
Example 40
Project: educational-plugin   File: PyStudyTestRunner.java   View source code 5 votes vote down vote up
Process createCheckProcess(@NotNull final Project project, @NotNull final String executablePath) throws ExecutionException {
  final Sdk sdk = PythonSdkType.findPythonSdk(ModuleManager.getInstance(project).getModules()[0]);
  PyEduPluginConfigurator configurator = new PyEduPluginConfigurator();
  String testsFileName = configurator.getTestFileName();
  if (myTask instanceof TaskWithSubtasks) {
    testsFileName = FileUtil.getNameWithoutExtension(testsFileName);
    int index = ((TaskWithSubtasks)myTask).getActiveSubtaskIndex();
    testsFileName += EduNames.SUBTASK_MARKER + index + "." + FileUtilRt.getExtension(configurator.getTestFileName());
  }
  final File testRunner = new File(myTaskDir.getPath(), testsFileName);
  myCommandLine = new GeneralCommandLine();
  myCommandLine.withWorkDirectory(myTaskDir.getPath());
  final Map<String, String> env = myCommandLine.getEnvironment();

  final VirtualFile courseDir = project.getBaseDir();
  if (courseDir != null) {
    env.put(PYTHONPATH, courseDir.getPath());
  }
  if (sdk != null) {
    String pythonPath = sdk.getHomePath();
    if (pythonPath != null) {
      myCommandLine.setExePath(pythonPath);
      myCommandLine.addParameter(testRunner.getPath());
      myCommandLine.addParameter(FileUtil.toSystemDependentName(executablePath));
      return myCommandLine.createProcess();
    }
  }
  return null;
}