From d0b75306c53e951f4af25770399dff070f1521f6 Mon Sep 17 00:00:00 2001 From: AayushSaini101 Date: Tue, 19 Nov 2024 11:17:13 +0530 Subject: [PATCH] Change format of the command --- src/commands/pretty.ts | 62 +++++++++++++++++++++++++++++++++ src/core/flags/pretty.flags.ts | 10 ++++++ test/integration/pretty.test.ts | 0 3 files changed, 72 insertions(+) create mode 100644 src/commands/pretty.ts create mode 100644 src/core/flags/pretty.flags.ts create mode 100644 test/integration/pretty.test.ts diff --git a/src/commands/pretty.ts b/src/commands/pretty.ts new file mode 100644 index 00000000000..1d216584807 --- /dev/null +++ b/src/commands/pretty.ts @@ -0,0 +1,62 @@ +import { Args } from '@oclif/core'; +import { promises as fs } from 'fs'; +import * as yaml from 'js-yaml'; +import Command from '../core/base'; +import { load } from '../core/models/SpecificationFile'; +import { ValidationError } from '../core/errors/validation-error'; +import { prettyFlags } from '../core/flags/pretty.flags'; + +export default class Pretty extends Command { + static description = 'Format AsyncAPI specification file'; + + static examples = [ + 'asyncapi pretty ./asyncapi.yaml', + 'asyncapi pretty ./asyncapi.yaml --output formatted-asyncapi.yaml', + ]; + + static flags = prettyFlags(); + + static args = { + 'spec-file': Args.string({description: 'spec path, url, or context-name', required: true}), + }; + + async run() { + const { args, flags } = await this.parse(Pretty); + const filePath = args['spec-file']; + const outputPath = flags.output; + + try { + this.specFile = await load(filePath); + } catch (err) { + this.error( + new ValidationError({ + type: 'invalid-file', + filepath: filePath, + }) + ); + } + + const content = this.specFile.text(); + let formatted: string; + + try { + const parsed = yaml.load(content); + formatted = yaml.dump(parsed, { + indent: 2, + lineWidth: -1, + noRefs: true, + sortKeys: true, + }); + } catch (err) { + this.error(`Error formatting file: ${err}`); + } + + if (outputPath) { + await fs.writeFile(outputPath, formatted, 'utf8'); + this.log(`Formatted content has been written to ${outputPath}`); + } else { + await fs.writeFile(filePath, formatted, 'utf8'); + this.log(`File ${filePath} has been formatted in-place.`); + } + } +} \ No newline at end of file diff --git a/src/core/flags/pretty.flags.ts b/src/core/flags/pretty.flags.ts new file mode 100644 index 00000000000..93d28995a8c --- /dev/null +++ b/src/core/flags/pretty.flags.ts @@ -0,0 +1,10 @@ +import { Flags } from '@oclif/core'; + +export const prettyFlags = () => { + return { + output: Flags.string({ + char: 'o', + description: 'Output file path', + }), + }; +}; \ No newline at end of file diff --git a/test/integration/pretty.test.ts b/test/integration/pretty.test.ts new file mode 100644 index 00000000000..e69de29bb2d