Skip to content

Commit

Permalink
feat: CLI command to run formatting (#824)
Browse files Browse the repository at this point in the history
Closes #702

### Summary of Changes

Add a new `format` command to format Safe-DS files.
  • Loading branch information
lars-reimann committed Jan 15, 2024
1 parent 55b5ed0 commit a74b8e0
Show file tree
Hide file tree
Showing 7 changed files with 116 additions and 0 deletions.
35 changes: 35 additions & 0 deletions packages/safe-ds-cli/src/cli/format.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,35 @@
import { createSafeDsServicesWithBuiltins } from '@safe-ds/lang';
import { NodeFileSystem } from 'langium/node';
import { extractDocuments } from '../helpers/documents.js';
import { exitIfDocumentHasSyntaxErrors } from '../helpers/diagnostics.js';
import { TextDocument } from 'vscode-languageserver-textdocument';
import { writeFile } from 'node:fs/promises';
import chalk from 'chalk';

export const format = async (fsPaths: string[]): Promise<void> => {
const services = (await createSafeDsServicesWithBuiltins(NodeFileSystem)).SafeDs;
const documents = await extractDocuments(services, fsPaths);

// Exit if any document has syntax errors before formatting code
for (const document of documents) {
exitIfDocumentHasSyntaxErrors(document);
}

// Format code
for (const document of documents) {
const edits = await services.lsp.Formatter!.formatDocument(document, {
textDocument: {
uri: document.uri.toString(),
},
options: {
tabSize: 4,
insertSpaces: true,
},
});

const editedDocument = TextDocument.applyEdits(document.textDocument, edits);
await writeFile(document.uri.fsPath, editedDocument);
}

console.log(chalk.green(`Safe-DS code formatted successfully.`));
};
8 changes: 8 additions & 0 deletions packages/safe-ds-cli/src/cli/main.ts
Original file line number Diff line number Diff line change
Expand Up @@ -3,6 +3,7 @@ import { createRequire } from 'node:module';
import { fileURLToPath } from 'node:url';
import { generate } from './generate.js';
import { check } from './check.js';
import { format } from './format.js';

const program = new Command();

Expand All @@ -19,6 +20,13 @@ program
.description('check Safe-DS code')
.action(check);

// Format command
program
.command('format')
.argument('<paths...>', `list of files or directories to format`)
.description('format Safe-DS code')
.action(format);

// Generate command
program
.command('generate')
Expand Down
18 changes: 18 additions & 0 deletions packages/safe-ds-cli/src/helpers/diagnostics.ts
Original file line number Diff line number Diff line change
Expand Up @@ -99,6 +99,24 @@ export const exitIfDocumentHasErrors = function (document: LangiumDocument): voi
}
};

/**
* Exits the process if the given document has syntax errors.
*/
export const exitIfDocumentHasSyntaxErrors = function (document: LangiumDocument): void {
const errors = getSyntaxErrors(document);
if (errors.length > 0) {
console.error(chalk.red(`The file '${uriToRelativePath(document.uri)}' has syntax errors:`));
for (const error of errors) {
console.error(diagnosticToString(document.uri, error));
}
process.exit(ExitCode.FileHasErrors);
}
};

const getErrors = (document: LangiumDocument): Diagnostic[] => {
return getDiagnostics(document).filter((it) => it.severity === DiagnosticSeverity.Error);
};

const getSyntaxErrors = (document: LangiumDocument): Diagnostic[] => {
return getErrors(document).filter((d) => d.data?.code === 'lexing-error' || d.data?.code === 'parsing-error');
};
46 changes: 46 additions & 0 deletions packages/safe-ds-cli/tests/cli/main.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -93,6 +93,52 @@ describe('safe-ds', () => {
});
});

describe('format', () => {
const testResourcesRoot = new URL('../resources/format/', import.meta.url);
const spawnFormatProcess = (additionalArguments: string[], paths: string[]) => {
const fsPaths = paths.map((p) => fileURLToPath(new URL(p, testResourcesRoot)));
return spawnSync('node', ['./bin/cli', 'format', ...additionalArguments, ...fsPaths], {
cwd: projectRoot,
});
};

it('should show an error if no paths are passed', () => {
const process = spawnFormatProcess([], []);
expect(process.stderr.toString()).toContain("error: missing required argument 'paths'");
expect(process.status).not.toBe(ExitCode.Success);
});

it('should show usage on stdout if -h flag is passed', () => {
const process = spawnFormatProcess(['-h'], []);
expect(process.stdout.toString()).toContain('Usage: cli format');
expect(process.status).toBe(ExitCode.Success);
});

it('should show errors in wrong files', () => {
const process = spawnFormatProcess([], ['.']);
expect(process.stderr.toString()).toContain('has syntax errors');
expect(process.status).toBe(ExitCode.FileHasErrors);
});

it('should show not show errors in correct files', () => {
const process = spawnFormatProcess([], ['correct.sdstest']);
expect(process.stdout.toString()).toContain('Safe-DS code formatted successfully.');
expect(process.status).toBe(ExitCode.Success);
});

it('should show an error if the file does not exist', () => {
const process = spawnFormatProcess([], ['missing.sdstest']);
expect(process.stderr.toString()).toMatch(/Path .* does not exist\./u);
expect(process.status).toBe(ExitCode.MissingPath);
});

it('should show an error if a file has the wrong extension', () => {
const process = spawnFormatProcess([], ['not safe-ds.txt']);
expect(process.stderr.toString()).toContain('does not have a Safe-DS extension');
expect(process.status).toBe(ExitCode.FileWithoutSafeDsExtension);
});
});

describe('generate', () => {
const testResourcesRoot = new URL('../resources/generate/', import.meta.url);
const spawnGenerateProcess = (additionalArguments: string[], paths: string[]) => {
Expand Down
Original file line number Diff line number Diff line change
@@ -0,0 +1,3 @@
package test

segment mySegment()
3 changes: 3 additions & 0 deletions packages/safe-ds-cli/tests/resources/format/correct.sdstest
Original file line number Diff line number Diff line change
@@ -0,0 +1,3 @@
package test

pipeline myPipeline {}
3 changes: 3 additions & 0 deletions packages/safe-ds-cli/tests/resources/format/not safe-ds.txt
Original file line number Diff line number Diff line change
@@ -0,0 +1,3 @@
package test

segment mySegment() {}

0 comments on commit a74b8e0

Please sign in to comment.