Skip to content

Commit

Permalink
Apply logic for all commands
Browse files Browse the repository at this point in the history
  • Loading branch information
peter-rr committed Dec 21, 2023
1 parent 75370fc commit 6b4e76d
Show file tree
Hide file tree
Showing 6 changed files with 63 additions and 34 deletions.
27 changes: 7 additions & 20 deletions src/base.ts
Original file line number Diff line number Diff line change
Expand Up @@ -32,20 +32,7 @@ export default abstract class extends Command {
}
}

async recordActionExecuted(action: string, metadata: MetricMetadata = {}, rawDocument?: string) {
if (rawDocument !== undefined) {
try {
const {document} = await this.parser.parse(rawDocument);
if (document !== undefined) {
this.metricsMetadata = MetadataFromDocument(document, metadata);
}
} catch (e: any) {
if (e instanceof Error) {
this.log(`Skipping submitting anonymous metrics due to the following error: ${e.name}: ${e.message}`);
}
}
}

async recordActionExecuted(action: string, metadata: MetricMetadata = {}) {
const callable = async function(recorder: Recorder) {
await recorder.recordActionExecuted(action, metadata);
};
Expand All @@ -72,12 +59,6 @@ export default abstract class extends Command {
}
}

async finally(error: Error | undefined): Promise<any> {
await super.finally(error);
this.metricsMetadata['success'] = error === undefined;
await this.recordActionExecuted(this.id as string, this.metricsMetadata, this.specFile?.text());
}

recorderFromEnv(prefix: string): Recorder {
let sink: Sink = new DiscardSink();
if (process.env.ASYNCAPI_METRICS !== 'false') {
Expand All @@ -99,5 +80,11 @@ export default abstract class extends Command {

return new Recorder(prefix, sink);
}

async finally(error: Error | undefined): Promise<any> {
await super.finally(error);
this.metricsMetadata['success'] = error === undefined;
await this.recordActionExecuted(this.id as string, this.metricsMetadata);
}
}

13 changes: 12 additions & 1 deletion src/commands/bundle.ts
Original file line number Diff line number Diff line change
Expand Up @@ -6,6 +6,7 @@ import { promises } from 'fs';
import path from 'path';
import { Specification, load } from '../models/SpecificationFile';
import { Parser } from '@asyncapi/parser';
import { MetadataFromDocument } from '@smoya/asyncapi-adoption-metrics';

const { writeFile } = promises;

Expand Down Expand Up @@ -80,7 +81,17 @@ export default class Bundle extends Command {
const result = await load(output);

// Metrics recording.
await this.recordActionExecuted(result.text(), {success: true, files: AsyncAPIFiles.length});
this.metricsMetadata = {success: true, files: AsyncAPIFiles.length};
try {
const {document} = await this.parser.parse(result.text());
if (document !== undefined) {
this.metricsMetadata = MetadataFromDocument(document, this.metricsMetadata);
}
} catch (e: any) {
if (e instanceof Error) {
this.log(`Skipping submitting anonymous metrics due to the following error: ${e.name}: ${e.message}`);
}
}
}

async loadFiles(filepaths: string[]): Promise<Specification[]> {
Expand Down
10 changes: 4 additions & 6 deletions src/commands/convert.ts
Original file line number Diff line number Diff line change
Expand Up @@ -6,7 +6,7 @@ import { ValidationError } from '../errors/validation-error';
import { load } from '../models/SpecificationFile';
import { SpecificationFileNotFound } from '../errors/specification-file';
import { convert } from '@asyncapi/converter';
import { MetadataFromDocument, MetricMetadata } from '@smoya/asyncapi-adoption-metrics';
import { MetadataFromDocument } from '@smoya/asyncapi-adoption-metrics';

import type { ConvertVersion } from '@asyncapi/converter';

Expand Down Expand Up @@ -72,19 +72,17 @@ export default class Convert extends Command {
}

// Metrics recording.
let metadata: MetricMetadata = {success: true, to_version: flags['target-version']};
this.metricsMetadata = {success: true, to_version: flags['target-version']};
try {
const {document} = await this.parser.parse(specFile.text());
if (document !== undefined) {
metadata = MetadataFromDocument(document, metadata);
metadata['from_version'] = document.version();
this.metricsMetadata = MetadataFromDocument(document, this.metricsMetadata);
this.metricsMetadata['from_version'] = document.version();
}
} catch (e: any) {
if (e instanceof Error) {
this.log(`Skipping submitting anonymous metrics due to the following error: ${e.name}: ${e.message}`);
}
}

await this.recordActionExecuted('convert', metadata);
}
}
13 changes: 12 additions & 1 deletion src/commands/generate/fromTemplate.ts
Original file line number Diff line number Diff line change
Expand Up @@ -12,6 +12,7 @@ import { isLocalTemplate, Watcher } from '../../utils/generator';
import { ValidationError } from '../../errors/validation-error';
import { GeneratorError } from '../../errors/generator-error';
import { Parser } from '@asyncapi/parser';
import { MetadataFromDocument } from '@smoya/asyncapi-adoption-metrics';

import type { Example } from '@oclif/core/lib/interfaces';

Expand Down Expand Up @@ -147,7 +148,17 @@ export default class Template extends Command {
}

// Metrics recording.
await this.recordActionExecuted('generate_from_template', {success: true, template}, asyncapiInput.text());
this.metricsMetadata = {success: true, template};
try {
const {document} = await this.parser.parse(asyncapiInput.text());
if (document !== undefined) {
this.metricsMetadata = MetadataFromDocument(document, this.metricsMetadata);
}
} catch (e: any) {
if (e instanceof Error) {
this.log(`Skipping submitting anonymous metrics due to the following error: ${e.name}: ${e.message}`);
}
}
}

private parseFlags(disableHooks?: string[], params?: string[], mapBaseUrl?: string): ParsedFlags {
Expand Down
19 changes: 15 additions & 4 deletions src/commands/optimize.ts
Original file line number Diff line number Diff line change
Expand Up @@ -8,13 +8,14 @@ import chalk from 'chalk';
import { promises } from 'fs';
import { Example } from '@oclif/core/lib/interfaces';
import { Parser } from '@asyncapi/parser';
import { MetadataFromDocument } from '@smoya/asyncapi-adoption-metrics';

const { writeFile } = promises;

export enum Optimizations {
REMOVE_COMPONENTS='remove-components',
REUSE_COMPONENTS='reuse-components',
MOVE_TO_COMPONETS='move-to-components'
MOVE_TO_COMPONENTS='move-to-components'
}

export enum Outputs {
Expand Down Expand Up @@ -96,7 +97,7 @@ export default class Optimize extends Command {

try {
const optimizedDocument = optimizer.getOptimizedDocument({rules: {
moveToComponents: this.optimizations.includes(Optimizations.MOVE_TO_COMPONETS),
moveToComponents: this.optimizations.includes(Optimizations.MOVE_TO_COMPONENTS),
removeComponents: this.optimizations.includes(Optimizations.REMOVE_COMPONENTS),
reuseComponents: this.optimizations.includes(Optimizations.REUSE_COMPONENTS)
}, output: Output.YAML});
Expand Down Expand Up @@ -129,7 +130,17 @@ export default class Optimize extends Command {
}

// Metrics recording.
await this.recordActionExecuted('optimize', {success: true, optimizations: this.optimizations}, specFile.text());
this.metricsMetadata = {success: true, optimizations: this.optimizations};
try {
const {document} = await this.parser.parse(specFile.text());
if (document !== undefined) {
this.metricsMetadata = MetadataFromDocument(document, this.metricsMetadata);
}
} catch (e: any) {
if (e instanceof Error) {
this.log(`Skipping submitting anonymous metrics due to the following error: ${e.name}: ${e.message}`);
}
}
}

private showOptimizations(elements: ReportElement[] | undefined) {
Expand Down Expand Up @@ -159,7 +170,7 @@ export default class Optimize extends Command {
const totalMove = report.moveToComponents?.filter((e: ReportElement) => e.action === 'move').length;
this.log(`\n${chalk.green(totalMove)} components can be moved to the components sections.\nthe following changes will be made:`);
this.showOptimizations(report.moveToComponents);
choices.push({name: 'move to components section', value: Optimizations.MOVE_TO_COMPONETS});
choices.push({name: 'move to components section', value: Optimizations.MOVE_TO_COMPONENTS});
}
if (canRemove) {
const totalMove = report.removeComponents?.length;
Expand Down
15 changes: 13 additions & 2 deletions src/commands/validate.ts
Original file line number Diff line number Diff line change
@@ -1,10 +1,10 @@
import { Flags } from '@oclif/core';

import Command from '../base';
import { validate, validationFlags } from '../parser';
import { load } from '../models/SpecificationFile';
import { specWatcher } from '../globals';
import { watchFlag } from '../flags';
import { MetadataFromDocument } from '@smoya/asyncapi-adoption-metrics';

export default class Validate extends Command {
static description = 'validate asyncapi file';
Expand All @@ -29,8 +29,19 @@ export default class Validate extends Command {
specWatcher({ spec: specFile, handler: this, handlerName: 'validate' });
}

// Metrics recording.
const result = await validate(this, specFile, flags);

// Metrics recording.
this.metricsMetadata = {success: true, validation_result: result};
try {
const {document} = await this.parser.parse(specFile.text());
if (document !== undefined) {
this.metricsMetadata = MetadataFromDocument(document, this.metricsMetadata);
}
} catch (e: any) {
if (e instanceof Error) {
this.log(`Skipping submitting anonymous metrics due to the following error: ${e.name}: ${e.message}`);
}
}
}
}

0 comments on commit 6b4e76d

Please sign in to comment.