<commit_before>import * as vscode from 'vscode';
import { outputChannel } from './extension';
import { isTerraformDocument } from './helpers';
import { runTerraform } from './runner';

export class FormattingEditProvider implements vscode.DocumentFormattingEditProvider {
  private _ignoreNextSave = new WeakSet<vscode.TextDocument>();

  onSave(document: vscode.TextDocument) {
    if (!isTerraformDocument(document) || this._ignoreNextSave.has(document)) {
      return;
    }

    let textEditor = vscode.window.activeTextEditor;

    if (this.isFormatEnabled(document, true) && textEditor.document === document) {
      const fullRange = doc => doc.validateRange(new vscode.Range(0, 0, Number.MAX_VALUE, Number.MAX_VALUE));
      const range = fullRange(document);

      outputChannel.appendLine(`terraform.format [on-save]: running 'terraform fmt' on '${document.fileName}'`);
      return runTerraform(process.cwd(), ["fmt", "-"], {
        input: document.getText(),
      }).then((formattedText) => {
          textEditor.edit((editor) => {
            editor.replace(range, formattedText);
          });
        }).then((applied) => {
          this._ignoreNextSave.add(document);

          return document.save();
        }).then(() => {
          outputChannel.appendLine("terraform.format [on-save]: Successful.");
          this._ignoreNextSave.delete(document);
        }).catch((e) => {
          outputChannel.appendLine(`terraform.format [on-save]: Failed: '${e}'`);
          vscode.window.showWarningMessage(e);
        });
    }
  }

  private isFormatEnabled(document: vscode.TextDocument, onSave: boolean): boolean {
    let config = vscode.workspace.getConfiguration('terraform.format');
    if (config.get<boolean>('enable') !== true) {
      return false;
    }

    if (!onSave) {
      return true;
    }

    if (config.get<boolean>('formatOnSave') !== true) {
      return false;
    }

    return config.get<Array<string>>('ignoreExtensionsOnSave').map((ext) => {
      return document.fileName.endsWith(ext);
    }).indexOf(true) === -1;
  }


  provideDocumentFormattingEdits(document: vscode.TextDocument, options: vscode.FormattingOptions, token: vscode.CancellationToken): vscode.ProviderResult<vscode.TextEdit[]> {
    if (!this.isFormatEnabled(document, false)) {
      return [];
    }

    const fullRange = doc => doc.validateRange(new vscode.Range(0, 0, Number.MAX_VALUE, Number.MAX_VALUE));
    const range = fullRange(document);

    outputChannel.appendLine(`terraform.format [provider]: running 'terraform fmt' on '${document.fileName}'`);
    return runTerraform(process.cwd(), ["fmt", "-"], {
      input: document.getText(),
    }).then((formattedText) => {
        outputChannel.appendLine("terraform.format [provider]: Successful.");
        return [new vscode.TextEdit(range, formattedText)];
      }).catch((e) => {
        outputChannel.appendLine(`terraform.format [provider]: Failed: '${e}'`);
        vscode.window.showWarningMessage(e);
        return [];
      });
  }
}<commit_msg>Catch exceptions during format<commit_after>import * as vscode from 'vscode';
import { isTerraformDocument } from './helpers';
import { Logger } from './logger';
import { runTerraform } from './runner';

export class FormattingEditProvider implements vscode.DocumentFormattingEditProvider {
  private _ignoreNextSave = new WeakSet<vscode.TextDocument>();
  private logger = new Logger("formatting-provider");

  async onSave(document: vscode.TextDocument) {
    try {
      if (!isTerraformDocument(document) || this._ignoreNextSave.has(document)) {
        return;
      }

      if (!this.isFormatEnabled(document, true) || vscode.window.activeTextEditor.document !== document) {
        return;
      }

      const fullRange = doc => doc.validateRange(new vscode.Range(0, 0, Number.MAX_VALUE, Number.MAX_VALUE));
      const range = fullRange(document);

      this.logger.info(`[on-save]: running 'terraform fmt' on '${document.fileName}'`);
      let formattedText = await runTerraform(process.cwd(), ["fmt", "-"], {
        input: document.getText(),
      });

      const applied = await vscode.window.activeTextEditor.edit((editor) => {
        editor.replace(range, formattedText);
      });

      if (!applied)
        this.logger.warn("[on-save]: changes not applied");

      this._ignoreNextSave.add(document);
      await document.save();

      this.logger.info("[on-save]: successful.");
      this._ignoreNextSave.delete(document);
    } catch (error) {
      this.logger.exception("[on-save]: formatted failed.", error);
    }
  }

  private isFormatEnabled(document: vscode.TextDocument, onSave: boolean): boolean {
    let config = vscode.workspace.getConfiguration('terraform.format');
    if (config.get<boolean>('enable') !== true) {
      return false;
    }

    if (!onSave) {
      return true;
    }

    if (config.get<boolean>('formatOnSave') !== true) {
      return false;
    }

    return config.get<Array<string>>('ignoreExtensionsOnSave').map((ext) => {
      return document.fileName.endsWith(ext);
    }).indexOf(true) === -1;
  }


  async provideDocumentFormattingEdits(
    document: vscode.TextDocument,
    options: vscode.FormattingOptions,
    token: vscode.CancellationToken): Promise<vscode.TextEdit[]> {
    try {
      if (!this.isFormatEnabled(document, false)) {
        return [];
      }

      const fullRange = doc => doc.validateRange(new vscode.Range(0, 0, Number.MAX_VALUE, Number.MAX_VALUE));
      const range = fullRange(document);

      this.logger.info(`[provider]: running 'terraform fmt' on '${document.fileName}'`);
      let formattedText = await runTerraform(process.cwd(), ["fmt", "-"], {
        input: document.getText(),
      });

      this.logger.info("[provider]: successful.");
      return [new vscode.TextEdit(range, formattedText)];
    } catch (error) {
      this.logger.exception("[provider]: formatting failed.", error);
    }
  }
}
{'fraction_non_alphanumeric': 0.15196242871519625, 'fraction_numerical': 0.0016772895001677288, 'mean_word_length': 3.430163447251114, 'pattern_counts': {'":': 0, '<': 15, '<?xml version=': 0, '>': 29, 'https://': 0, 'lorem ipsum': 0, 'www.': 0, 'xml': 0}, 'pii_count': 0, 'substrings_counts': 0, 'word_list_counts': {'cursed_substrings.json': 0, 'profanity_word_list.json': 0, 'sexual_word_list.json': 0, 'zh_pornsignals.json': 0}}
{'dir': 'git-commits-cleaned', 'id': '1145359', 'n_tokens_mistral': 1776, 'n_tokens_neox': 1760, 'n_words': 334}