child_process#execFile TypeScript Examples

The following examples show how to use child_process#execFile. You can vote up the ones you like or vote down the ones you don't like, and go to the original project or source file by following the links above each example. You may check out the related API usage on the sidebar.
Example #1
Source File: docker.ts    From node-launcher with Apache License 2.0 6 votes vote down vote up
public kill(name: string): Promise<string> {
    return new Promise(resolve => {
      const command = 'docker';
      const args = ['kill', name];
      this.emit(DockerEvent.INFO, `${command} ${args.join(' ')}`);
      execFile(command, args, {}, (err, output) => {
        if(err) {
          this._logError(err);
          resolve('');
        } else {
          const outputStr = output.toString();
          resolve(outputStr);
        }
      });
    });
  }
Example #2
Source File: docker.ts    From node-launcher with Apache License 2.0 6 votes vote down vote up
public stop(name: string): Promise<string> {
    return new Promise(resolve => {
      const command = 'docker';
      const args = ['stop', name];
      this.emit(DockerEvent.INFO, `${command} ${args.join(' ')}`);
      execFile(command, args, {}, (err, output) => {
        if(err) {
          this._logError(err);
          resolve('');
        } else {
          const outputStr = output.toString();
          resolve(outputStr);
        }
      });
    });
  }
Example #3
Source File: docker.ts    From node-launcher with Apache License 2.0 6 votes vote down vote up
public rm(name: string): Promise<boolean> {
    return new Promise(resolve => {
      const command = 'docker';
      const args = ['rm', name];
      this.emit(DockerEvent.INFO, `${command} ${args.join(' ')}`);
      execFile(command, args, {}, err => {
        if(err) {
          resolve(false);
        } else {
          resolve(true);
        }
      });
    });
  }
Example #4
Source File: windowsExecutableCodeSignatureVerifier.ts    From electron-differential-updater with MIT License 6 votes vote down vote up
// $certificateInfo = (Get-AuthenticodeSignature 'xxx\yyy.exe'
// | where {$_.Status.Equals([System.Management.Automation.SignatureStatus]::Valid) -and $_.SignerCertificate.Subject.Contains("CN=siemens.com")})
// | Out-String ; if ($certificateInfo) { exit 0 } else { exit 1 }
export function verifySignature(publisherNames: Array<string>, tempUpdateFile: string, logger: Logger): Promise<string | null> {
  return new Promise<string | null>(resolve => {
    // https://github.com/electron-userland/electron-builder/issues/2421
    // https://github.com/electron-userland/electron-builder/issues/2535
    execFile("powershell.exe", ["-NoProfile", "-NonInteractive", "-InputFormat", "None", "-Command", `Get-AuthenticodeSignature '${tempUpdateFile}' | ConvertTo-Json -Compress`], {
      timeout: 20 * 1000
    }, (error, stdout, stderr) => {
      try {
        if (error != null || stderr) {
          handleError(logger, error, stderr)
          resolve(null)
          return
        }

        const data = parseOut(stdout)
        if (data.Status === 0) {
          const name = parseDn(data.SignerCertificate.Subject).get("CN")!
          if (publisherNames.includes(name)) {
            resolve(null)
            return
          }
        }

        const result = `publisherNames: ${publisherNames.join(" | ")}, raw info: ` + JSON.stringify(data, (name, value) => name === "RawData" ? undefined : value, 2)
        logger.warn(`Sign verification failed, installer signed with incorrect certificate: ${result}`)
        resolve(result)
      }
      catch (e) {
        logger.warn(`Cannot execute Get-AuthenticodeSignature: ${error}. Ignoring signature validation due to unknown error.`)
        resolve(null)
        return
      }
    })
  })
}
Example #5
Source File: custom_instance_manager.ts    From jitsi-autoscaler with Apache License 2.0 6 votes vote down vote up
execLaunch({
        ctx,
        displayName,
        groupName,
        region,
        type,
    }: {
        ctx: Context;
        displayName: string;
        groupName: string;
        region: string;
        type: string;
    }): Promise<string> {
        return new Promise((resolve, reject) => {
            execFile(
                this.customConfigurationLaunchScriptPath,
                [`--type ${type}`, `--name ${displayName}`, `--groupName ${groupName}`, `--region ${region}`],
                { timeout: this.customConfigurationLaunchScriptTimeoutMs },
                (error, stdout) => {
                    if (error) {
                        ctx.logger.error(
                            `[custom] Failed executing launch file for type ${type}, name ${displayName},  groupName ${groupName} and region ${region} with error: ${error}`,
                            { error },
                        );
                        reject(error);
                        return;
                    }

                    const instanceId = stdout.trim().split('\n').pop();
                    resolve(instanceId);
                },
            );
        });
    }
Example #6
Source File: main.ts    From desktop with GNU Affero General Public License v3.0 6 votes vote down vote up
/**
 * Close out application unless if instructed to relaunch.
 */
App.on("window-all-closed", function () {
    if (app.shouldRelaunch) {
        const options: RelaunchOptions = {
            args: process.argv.slice(1).concat(["--relaunch"]),
            execPath: process.execPath,
        };

        if (App.isPackaged && process.env.APPIMAGE) {
            execFile(process.env.APPIMAGE, options.args);
        } else {
            App.relaunch(options);
        }

        App.quit();
        return;
    }

    if (process.platform !== "darwin") App.quit();
});
Example #7
Source File: index.ts    From TidGi-Desktop with Mozilla Public License 2.0 6 votes vote down vote up
export default async function appPath(appName: string): Promise<string | null> {
  try {
    const { stdout } = await promisify(execFile)(
      isDevelopmentOrTest ? path.join(cwd, 'main') : path.join(process.resourcesPath, 'node_modules', 'app-path', 'main'),
      [appName],
    );
    return stdout.replace('\n', '');
  } catch (error) {
    throw improveError(error as Error);
  }
}
Example #8
Source File: index.ts    From lfs-warning with MIT License 5 votes vote down vote up
execFileP = promisify(execFile)
Example #9
Source File: dotnet.ts    From ide-vscode with MIT License 5 votes vote down vote up
execFileAsync = promisify(execFile)
Example #10
Source File: dafnyVersionView.ts    From ide-vscode with MIT License 5 votes vote down vote up
execFileAsync = promisify(execFile)
Example #11
Source File: docker.ts    From node-launcher with Apache License 2.0 5 votes vote down vote up
_execFile = execFile;
Example #12
Source File: limiter.d.ts    From baidupcs-batch-upload with MIT License 5 votes vote down vote up
limitexec: typeof execFile.__promisify__
Example #13
Source File: limiter.ts    From baidupcs-batch-upload with MIT License 5 votes vote down vote up
execpro = promisify(execFile)
Example #14
Source File: compileSM.ts    From sourcepawn-vscode with MIT License 4 votes vote down vote up
/**
 * Callback for the Compile file command.
 * @param  {URI} args URI of the document to be compiled. This will be overrided if MainPathCompilation is set to true.
 * @returns Promise
 */
export async function run(args: URI): Promise<void> {
  const uri = args === undefined ? window.activeTextEditor.document.uri : args;
  const workspaceFolder = Workspace.getWorkspaceFolder(uri);

  const mainPath = findMainPath(uri);
  const alwaysCompileMainPath: boolean = Workspace.getConfiguration(
    "sourcepawn",
    workspaceFolder
  ).get<boolean>("MainPathCompilation");

  // Decide which file to compile here.
  let fileToCompilePath: string;
  if (alwaysCompileMainPath && mainPath !== undefined && mainPath !== "") {
    fileToCompilePath = mainPath;
  } else {
    fileToCompilePath = uri.fsPath;
  }

  const scriptingFolderPath = dirname(fileToCompilePath);

  // Don't compile if it's not a .sp file.
  if (extname(fileToCompilePath) !== ".sp") {
    window.showErrorMessage("Not a .sp file, aborting");
    return;
  }

  // Invoke the compiler.
  const spcomp =
    Workspace.getConfiguration("sourcepawn", workspaceFolder).get<string>(
      "SpcompPath"
    ) || "";

  if (!spcomp) {
    window
      .showErrorMessage(
        "SourceMod compiler not found in the project. You need to set the spCompPath setting to be able to compile a plugin.",
        "Open Settings"
      )
      .then((choice) => {
        if (choice === "Open Settings") {
          commands.executeCommand(
            "workbench.action.openSettings",
            "@ext:sarrus.sourcepawn-vscode"
          );
        }
      });
    return;
  }

  // Decide where to output the compiled file.
  const pluginsFolderPath = join(scriptingFolderPath, "../", "plugins/");
  let outputDir: string =
    Workspace.getConfiguration("sourcepawn", workspaceFolder).get(
      "outputDirectoryPath"
    ) || pluginsFolderPath;
  if (outputDir === pluginsFolderPath) {
    if (!existsSync(outputDir)) {
      mkdirSync(outputDir);
    }
  } else {
    // If the outputDirectoryPath setting is not empty, make sure it exists before trying to write to it.
    if (!existsSync(outputDir)) {
      let workspaceFolder = Workspace.workspaceFolders[0];
      outputDir = join(workspaceFolder.uri.fsPath, outputDir);
      if (!existsSync(outputDir)) {
        window
          .showErrorMessage(
            "The output directory does not exist.",
            "Open Settings"
          )
          .then((choice) => {
            if (choice === "Open Settings") {
              commands.executeCommand(
                "workbench.action.openSettings",
                "@ext:sarrus.sourcepawn-vscode"
              );
            }
          });
        return;
      }
    }
  }
  outputDir += basename(fileToCompilePath, ".sp") + ".smx";

  // Add the compiler options from the settings.
  const compilerOptions: string[] = Workspace.getConfiguration(
    "sourcepawn",
    workspaceFolder
  ).get("compilerOptions");

  let includePaths: string[] = [
    Workspace.getConfiguration("sourcepawn", workspaceFolder).get(
      "SourcemodHome"
    ),
    join(scriptingFolderPath, "include"),
    scriptingFolderPath,
  ];

  // Add the optional includes folders.
  getAllPossibleIncludeFolderPaths(
    URI.file(fileToCompilePath),
    true
  ).forEach((e) => includePaths.push(e));

  let compilerArgs = [fileToCompilePath, `-o${outputDir}`];

  // Add include paths and compiler options to compiler args.
  includePaths.forEach((path) => compilerArgs.push(`-i${path}`));
  compilerArgs = compilerArgs.concat(compilerOptions);

  // Create Output Channel if it does not exist.
  if (!output) {
    output = window.createOutputChannel("SourcePawn Compiler");
  }

  // Clear previous data in Output Channel and show it.
  output.clear();
  output.show();

  try {
    // Compile in child process.
    let command = spcomp + "\n";
    compilerArgs.forEach((e) => {
      command += e + " ";
      if (e.length > 10) {
        command += "\n";
      }
    });
    output.appendLine(`${command}\n`);
    execFile(spcomp, compilerArgs, async (error, stdout) => {
      output.append(stdout.toString().trim());
      parseSPCompErrors(stdout.toString().trim(), compilerDiagnostics);
      if (
        Workspace.getConfiguration("sourcepawn", workspaceFolder).get(
          "uploadAfterSuccessfulCompile"
        )
      ) {
        await uploadToServerCommand(URI.file(fileToCompilePath));
      }
      if (
        Workspace.getConfiguration("sourcepawn", workspaceFolder).get<string>(
          "refreshServerPlugins"
        ) === "afterCompile"
      ) {
        refreshPluginsCommand(undefined);
      }
    });
  } catch (error) {
    console.log(error);
  }
}
Example #15
Source File: spLinter.ts    From sourcepawn-vscode with MIT License 4 votes vote down vote up
/**
 * Lint a TextDocument object and add its diagnostics to the
 * @param  {TextDocument} document    The document to lint.
 * @returns void
 */
export function refreshDiagnostics(document: TextDocument): void {
  // Check if the user specified not to enable the linter for this file.
  const range = new Range(0, 0, 1, 0);
  const text = document.getText(range);

  // Check if the setting to activate the linter is set to true.
  const workspaceFolder = Workspace.getWorkspaceFolder(document.uri);
  const enableLinter: boolean = Workspace.getConfiguration(
    "sourcepawn",
    workspaceFolder
  ).get<boolean>("enableLinter");

  // Stop early if linter is disabled.
  if (
    text === "" ||
    /\/\/linter=false/.test(text) ||
    !enableLinter ||
    extname(document.fileName) !== ".sp"
  ) {
    compilerDiagnostics.set(document.uri, []);
    return;
  }

  const tmpPath = join(
    extensions.getExtension("Sarrus.sourcepawn-vscode").extensionPath,
    "tmpCompiled.smx"
  );
  const tmpFile = join(__dirname, "temp.sp");
  const spcomp =
    Workspace.getConfiguration("sourcepawn", workspaceFolder).get<string>(
      "SpcompPath"
    ) || "";

  if (!spcomp) {
    return;
  }

  // Get the previous instance of spcomp if it exists
  let throttle = throttles[document.uri.path];
  if (throttle === undefined) {
    throttle = new TimeoutFunction();
    throttles[document.uri.path] = throttle;
  }

  // Cancel the previous instance and start a new one.
  throttle.cancel();
  throttle.start(() => {
    const mainPath = findMainPath(document.uri);

    // Separate the cases if we are using mainPath or not.
    let scriptingFolder: string;
    let filePath: string;
    if (mainPath !== undefined && mainPath !== "") {
      scriptingFolder = dirname(mainPath);
      filePath = mainPath;
    } else {
      scriptingFolder = dirname(document.uri.fsPath);
      let file = openSync(tmpFile, "w", 0o765);
      writeSync(file, document.getText());
      closeSync(file);
      filePath = tmpFile;
    }

    // Generate compiler arguments.
    const compilerArgs = [
      "-i" +
        Workspace.getConfiguration("sourcepawn", workspaceFolder).get(
          "SourcemodHome"
        ) || "",
      "-i" + scriptingFolder,
      "-i" + join(scriptingFolder, "include"),
      "-v0",
      filePath,
      "-o" + tmpPath,
    ];

    // Add a space at the beginning of every element, for security.
    Workspace.getConfiguration("sourcepawn", workspaceFolder)
      .get<string[]>("linterCompilerOptions")
      .forEach((e) => compilerArgs.push(" " + e));

    // Add the optional includes folders.
    getAllPossibleIncludeFolderPaths(document.uri, true).forEach((e) =>
      compilerArgs.push(`-i${e}`)
    );

    // Run the blank compile.
    execFile(spcomp, compilerArgs, (error, stdout) => {
      // If it compiled successfully, delete the temporary files.
      if (!error) {
        unlink(tmpPath, (err) => {
          if (err) {
            console.error(err);
          }
        });
      }
      parseSPCompErrors(
        stdout,
        compilerDiagnostics,
        mainPath === undefined ? document.uri.fsPath : undefined
      );
    });
  }, 300);
}
Example #16
Source File: image-compressor.ts    From image-optimizer with MIT License 4 votes vote down vote up
#processFile = (file: DroppedFile, output: string) => {
    const originalSize = getFileSize(file.path)

    return new Promise<void>((resolve, reject) => {
      switch (file.type) {
        case MIME_TYPE_ENUM.jpg: {
          const { quality } = store.app.get('mozjpeg')

          let originalFile: string
          const isAddTempFile =
            !store.app.get('addToSubfolder') && !store.app.get('addMinSuffix')

          if (isAddTempFile) {
            originalFile = output + '.tmp'
            copyFileSync(file.path, originalFile)
          } else {
            originalFile = file.path
          }

          execFile(
            mozjpeg,
            ['-quality', `${quality}`, '-outfile', output, originalFile],
            err => {
              if (err) {
                console.log(err)
                reject(err)
              }

              const compressedSize = getFileSize(output)
              this.#sendToRenderer(file, originalSize, compressedSize)
              if (isAddTempFile) unlinkSync(originalFile)
              resolve()
            }
          )
          break
        }

        case MIME_TYPE_ENUM.png: {
          const { qualityMin, qualityMax } = store.app.get('pngquant')

          execFile(
            pngquant,
            [
              '--quality',
              `${qualityMin}-${qualityMax}`,
              '-fo',
              output,
              file.path
            ],
            err => {
              if (err) {
                console.log(err)
                reject(err)
              }

              const compressedSize = getFileSize(output)
              this.#sendToRenderer(file, originalSize, compressedSize)
              resolve()
            }
          )
          break
        }

        case MIME_TYPE_ENUM.gif: {
          execFile(gifsicle, ['-o', output, file.path], err => {
            if (err) {
              console.log(err)
              reject(err)
            }

            const compressedSize = getFileSize(output)
            this.#sendToRenderer(file, originalSize, compressedSize)
            resolve()
          })
          break
        }

        case MIME_TYPE_ENUM.svg: {
          readFile(file.path, (err, buffer) => {
            if (err) {
              console.log(err)
              reject(err)
            }

            const { data } = svg.optimize(buffer)
            writeFile(output, data, err => {
              if (err) console.log(err)

              const compressedSize = getFileSize(output)
              this.#sendToRenderer(file, originalSize, compressedSize)
              resolve()
            })
          })
          break
        }
      }
    })
  }