fs#writeSync TypeScript Examples

The following examples show how to use fs#writeSync. 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: log.ts    From elephize with MIT License 6 votes vote down vote up
public _printLog(message: string, msgid: string, params: string[], severity: LogSeverity, context = '') {
    if (this.baseDir && severity !== LogSeverity.SPECIAL) {
      message = message.replace(this.baseDir, '[base]');
    }
    if (this.outDir && severity !== LogSeverity.SPECIAL) {
      message = message.replace(this.outDir, '[out]');
    }

    let marker: string = chalk.dim(`[i #${msgid}]`);
    switch (severity) {
      case LogSeverity.ERROR:
        marker = chalk.bgRedBright(chalk.black(`[E #${msgid}]`));
        break;
      case LogSeverity.WARN:
        marker = chalk.bgYellowBright(chalk.black(`[W #${msgid}]`));
        break;
      case LogSeverity.SPECIAL:
        marker = chalk.bgGreenBright(chalk.black(`[! #${msgid}]`));
        break;
      case LogSeverity.INFO:
      default:
        break;
    }

    message = format(message, ...params); // apply parameters to string strictly after hashing

    const dt = new Date();
    const pieces = [dt.getHours(), dt.getMinutes(), dt.getSeconds()].map((p) => p.toString().padStart(2, '0'));
    const timer = chalk.ansi(90)(`[${pieces.join(':')}:${dt.getMilliseconds().toString().padStart(3, '0')}]`);

    const str = `${marker}${timer} ${message}${context ? '\n   ' + context : ''}`;
    if (severity === LogSeverity.ERROR || this.forceStderr) {
      writeSync(STDERR_FILE_DESCRIPTOR, str + (str.endsWith('\n') ? '' : '\n'));
    } else {
      writeSync(STDOUT_FILE_DESCRIPTOR, str + (str.endsWith('\n') ? '' : '\n'));
    }
  }
Example #2
Source File: spFormat.ts    From sourcepawn-vscode with MIT License 5 votes vote down vote up
public provideDocumentFormattingEdits(
    document: TextDocument,
    options: FormattingOptions,
    token: CancellationToken
  ): ProviderResult<TextEdit[]> {
    // Get the user's settings.
    let insertSpaces: boolean =
      Workspace.getConfiguration("editor").get("insertSpaces") || false;
    let UseTab: string = insertSpaces ? "Never" : "Always";
    let tabSize: number =
      Workspace.getConfiguration("editor").get("tabSize") || 2;

    let workspaceFolder = Workspace.getWorkspaceFolder(document.uri);
    let defaultStyles: string[] =
      Workspace.getConfiguration("sourcepawn", workspaceFolder).get(
        "formatterSettings"
      ) || [];

    let default_style: string = "{" + defaultStyles.join(", ") + "}";

    // Apply user settings
    default_style = default_style
      .replace(/\${TabSize}/g, tabSize.toString())
      .replace(/\${UseTab}/g, UseTab);
    const start = new Position(0, 0);
    const end = new Position(
      document.lineCount - 1,
      document.lineAt(document.lineCount - 1).text.length
    );
    const range = new Range(start, end);
    const tempFile = join(__dirname, "temp_format.sp");
    let file = openSync(tempFile, "w", 0o765);
    writeSync(file, document.getText());
    closeSync(file);
    let text = this.clangFormat(tempFile, "utf-8", default_style);

    // If process failed,
    if (text === undefined) {
      window.showErrorMessage(
        "The formatter failed to run, check the console for more details."
      );
      return undefined;
    }
    text = fixFormatting(text);
    return [new TextEdit(range, text)];
  }
Example #3
Source File: writer.ts    From lsif-node with MIT License 5 votes vote down vote up
private writeBuffer(buffer: Buffer): void {
    let offset: number = 0
    while (offset < buffer.length) {
      offset += writeSync(this.fd, buffer, offset)
    }
  }
Example #4
Source File: conformance_ts.ts    From protobuf-ts with Apache License 2.0 5 votes vote down vote up
function writeBuffer(buffer: Buffer): void {
    let totalWritten = 0;
    while (totalWritten < buffer.length) {
        totalWritten += writeSync(1, buffer, totalWritten, buffer.length - totalWritten);
    }
}
Example #5
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);
}