Skip to content

Commit

Permalink
Fix functionality
Browse files Browse the repository at this point in the history
The original implementation didn't work (at all really) on new files or
edits. Because `cat file` was running on the pre-saved file we were
always formatting the previous version. 🤦

This implementation uses the current contents of the document and writes
that to a temporary file to be formatted.
  • Loading branch information
johnallen3d committed Dec 19, 2021
1 parent bb18eab commit af31f28
Showing 1 changed file with 22 additions and 7 deletions.
29 changes: 22 additions & 7 deletions src/extension.ts
Original file line number Diff line number Diff line change
@@ -1,16 +1,31 @@
import { languages, Range, TextDocument, TextEdit } from 'vscode';
import * as cp from 'child_process';
import * as path from 'path';
import { spawnSync } from 'child_process';
import { join, basename } from 'path';
import { randomBytes } from 'crypto';
import { tmpdir } from 'os';
import { readFileSync, writeFileSync } from 'fs';

function provideDocumentFormattingEdits(document: TextDocument): TextEdit[] {
let tempfile = cp.spawnSync("mktemp").stdout.toString().trim();
tempfile = `${tempfile}.cue`;
const dir = tmpdir();
const currentFileName = basename(document.fileName);
const random = randomBytes(16).toString('hex');
const tmpfileName = `vscode-cue-fmt-${random}-${currentFileName}`;
const tmpfile = join(dir, tmpfileName);

const copy = cp.execSync(`cat ${document.fileName} > ${tempfile}`)
const fmt = cp.spawnSync("cue", ["fmt", tempfile], {});
const formatted = cp.spawnSync("cat", [tempfile]).stdout.toString().trim();
// copy current contents to a tempfile
writeFileSync(tmpfile, document.getText());

// run `cue fmt` on temp file
// TODO: handle errror/stderr, report to user
const fmt = spawnSync("cue", ["fmt", tmpfile], {});

// read formatted file
const formatted = readFileSync(tmpfile).toString();

// create range representing the whole document to be replaced
const range = document.validateRange(new Range(0, 0, Infinity, Infinity));

// write formatted CUE back to document
return [new TextEdit(range, formatted)];
}

Expand Down

0 comments on commit af31f28

Please sign in to comment.