Skip to content

Commit

Permalink
Refactor to logging (#29)
Browse files Browse the repository at this point in the history
  • Loading branch information
matthewturner authored Sep 15, 2024
1 parent 89ad4be commit 5fb8036
Show file tree
Hide file tree
Showing 8 changed files with 168 additions and 131 deletions.
25 changes: 21 additions & 4 deletions package-lock.json

Some generated files are not rendered by default. Learn more about how customized files appear on GitHub.

5 changes: 3 additions & 2 deletions package.json
Original file line number Diff line number Diff line change
@@ -1,6 +1,6 @@
{
"name": "httpyac-import",
"version": "0.5.1",
"version": "0.6.0",
"description": "CLI to convert Postman collection to httpyac files",
"homepage": "https://github.com/matthewturner/httpyac-import",
"repository": {
Expand Down Expand Up @@ -32,7 +32,8 @@
"license": "ISC",
"dependencies": {
"postman-collection": "^4.5.0",
"ts-command-line-args": "^2.5.1"
"ts-command-line-args": "^2.5.1",
"tslog": "^4.9.3"
},
"devDependencies": {
"@types/jest": "^29.5.12",
Expand Down
51 changes: 51 additions & 0 deletions src/Options.ts
Original file line number Diff line number Diff line change
@@ -1,7 +1,58 @@
import { parse } from 'ts-command-line-args';
import { rootLogger } from './logging';

const logger = rootLogger.getSubLogger();

export interface IOptions {
sourcePath: string;
targetPath: string;
ignoreHeaders?: string[];
splitRequests?: boolean,
help?: boolean;
}

export function parseOptions(): IOptions {
const options = parse<IOptions>({
sourcePath: {
type: String, alias: 's', optional: true as const, description: 'Path to the exported postman_collection.json'
},
targetPath: {
type: String, alias: 'd', optional: true as const, description: 'Path to the root directory to output the .http files'
},
ignoreHeaders: {
type: String,
alias: 'i',
multiple: true,
optional: true as const,
description: 'List of headers to ignore, useful when using default headers. Supports regex patterns',
defaultValue: []
},
splitRequests: {
type: Boolean, alias: 'f', optional: true as const, description: 'Determines whether to split requests into separate files [default: true]'
},
help: {
type: Boolean, optional: true, alias: 'h', description: 'Prints this usage guide'
},
},
{
helpArg: 'help',
headerContentSections: [{ header: 'HttpYac Import', content: 'Converts Postman collections to HttpYac format' }]
});

if (options.sourcePath === undefined) {
logger.error('Source path must be supplied with --sourcePath=path');
process.exit(1);
}

if (options.targetPath === undefined) {
logger.error('Target path must be supplied with --targetPath=path');
process.exit(2);
}

if (options.splitRequests === undefined) {
logger.warn('One file will be created per request');
options.splitRequests = true;
}

return options;
}
10 changes: 7 additions & 3 deletions src/RequestDefinitionBuilder.ts
Original file line number Diff line number Diff line change
@@ -1,15 +1,19 @@
import { Item } from 'postman-collection';
import { rootLogger } from './logging';
import { Logger, ILogObj } from 'tslog';

export class RequestDefinitionBuilder {
_definition: string;
_item: Item
_ignoreHeaders: string[];
_requestSeparator: string;
_logger: Logger<ILogObj>;

constructor() {
constructor(logger: Logger<ILogObj> = rootLogger.getSubLogger()) {
this._definition = '';
this._ignoreHeaders = [];
this._requestSeparator = '\n\n\n';
this._logger = logger;
}

from(item: Item): RequestDefinitionBuilder {
Expand Down Expand Up @@ -47,7 +51,7 @@ export class RequestDefinitionBuilder {
}

if (preRequestTest.script.exec.length == 1 && preRequestTest.script.exec[0] == '') {
console.log('Pre request script is not set');
this._logger.warn('Pre request script is not set');
return this;
}

Expand Down Expand Up @@ -156,7 +160,7 @@ export class RequestDefinitionBuilder {
shouldInclude(header: string): boolean {
for (const ignoreHeader of this._ignoreHeaders) {
if (header.match(ignoreHeader)) {
console.log(`Ignoring header ${header}...`);
this._logger.info(`Ignoring header ${header}...`);
return false;
}
}
Expand Down
92 changes: 16 additions & 76 deletions src/app.ts
Original file line number Diff line number Diff line change
Expand Up @@ -2,59 +2,18 @@

import { writeFileSync, readFileSync, mkdirSync, existsSync } from 'fs';
import { Collection, ItemGroup, Item, PropertyList } from 'postman-collection';
import { parse } from 'ts-command-line-args';
import { IOptions } from './Options'
import { join } from 'path';
import { sanitize } from './helpers';
import { sanitize, outputDirectory, outputPathFor } from './helpers';
import { RequestDefinitionBuilder } from './RequestDefinitionBuilder';
import { parseOptions } from './Options';
import { rootLogger } from './logging';

const args = parse<IOptions>({
sourcePath: {
type: String, alias: 's', optional: true as const, description: 'Path to the exported postman_collection.json'
},
targetPath: {
type: String, alias: 'd', optional: true as const, description: 'Path to the root directory to output the .http files'
},
ignoreHeaders: {
type: String,
alias: 'i',
multiple: true,
optional: true as const,
description: 'List of headers to ignore, useful when using default headers. Supports regex patterns',
defaultValue: []
},
splitRequests: {
type: Boolean, alias: 'f', optional: true as const, description: 'Determines whether to split requests into separate files [default: true]'
},
help: {
type: Boolean, optional: true, alias: 'h', description: 'Prints this usage guide'
},
},
{
helpArg: 'help',
headerContentSections: [{ header: 'HttpYac Import', content: 'Converts Postman collections to HttpYac format' }]
});
const logger = rootLogger.getSubLogger();

if (args.sourcePath === undefined) {
console.log('Source path must be supplied with --sourcePath=path');
process.exit(1);
}

if (args.targetPath === undefined) {
console.log('Target path must be supplied with --targetPath=path');
process.exit(2);
}

if (args.splitRequests === undefined) {
console.log('One file will be created per request');
args.splitRequests = true;
}

const sourcePostmanCollectionPath = args.sourcePath;
const sourcePostmanCollection = JSON.parse(readFileSync(sourcePostmanCollectionPath).toString());
const options = parseOptions();

const targetPaths = [args.targetPath];
const targetPaths = [options.targetPath];

const sourcePostmanCollection = JSON.parse(readFileSync(options.sourcePath).toString());
const sourceCollection = new Collection(sourcePostmanCollection);

function processItems(items: PropertyList<Item | ItemGroup<Item>>) {
Expand All @@ -72,46 +31,27 @@ function processItems(items: PropertyList<Item | ItemGroup<Item>>) {
}

function processItem(item: Item) {
const directory = outputDirectory();
const directory = outputDirectory(options, targetPaths);

if (!existsSync(directory)) {
console.log(`Creating directory ${directory}...`);
logger.info(`Creating directory ${directory}...`);
mkdirSync(directory, { recursive: true });
}

const path = outputPathFor(item);
const filePath = outputPathFor(item, options, targetPaths);
logger.info(`Outputting to file ${filePath}...`);

console.log('Writing request definition...');
logger.info('Writing request definition...');
const requestDefinition = new RequestDefinitionBuilder()
.ignoreHeaders(args.ignoreHeaders)
.includeSeparatorIf(existsSync(path))
.ignoreHeaders(options.ignoreHeaders)
.includeSeparatorIf(existsSync(filePath))
.from(item)
.build()
.toString();

console.log(requestDefinition);

writeFileSync(path, requestDefinition, { flag: 'a' });
}

function outputDirectory() {
if (args.splitRequests) {
return join(...targetPaths);
}

return join(...targetPaths.slice(0, -1));
}

function outputPathFor(item: Item) {
const directory = join(...targetPaths);

if (args.splitRequests) {
const filename = `${sanitize(item.name)}.http`;
console.log(`Creating file ${filename}...`);
return join(directory, filename);
}
logger.info(requestDefinition);

return `${directory}.http`;
writeFileSync(filePath, requestDefinition, { flag: 'a' });
}

processItems(sourceCollection.items);
23 changes: 23 additions & 0 deletions src/helpers.ts
Original file line number Diff line number Diff line change
@@ -1,7 +1,30 @@
import { IOptions } from './Options';
import { join } from 'path';
import { Item } from 'postman-collection';

export function sanitize(name: string) {
return name
.toLowerCase()
.replaceAll(' ', '-')
.replaceAll('"', '')
.replaceAll('/', '_');
}

export function outputDirectory(options: IOptions, targetPaths: string[]) {
if (options.splitRequests) {
return join(...targetPaths);
}

return join(...targetPaths.slice(0, -1));
}

export function outputPathFor(item: Item, options: IOptions, targetPaths: string[]) {
const directory = join(...targetPaths);

if (options.splitRequests) {
const filename = `${sanitize(item.name)}.http`;
return join(directory, filename);
}

return `${directory}.http`;
}
18 changes: 18 additions & 0 deletions src/logging.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,18 @@
import { Logger, ILogObj } from 'tslog';

export const rootLogger = new Logger<ILogObj>({
prettyLogTemplate: "{{logLevelName}}\t",
prettyLogStyles: {
logLevelName: {
"*": ["bold", "black", "bgWhiteBright", "dim"],
SILLY: ["bold", "white"],
TRACE: ["bold", "whiteBright"],
DEBUG: ["bold", "green"],
INFO: ["bold", "blue"],
WARN: ["bold", "yellow"],
ERROR: ["bold", "red"],
FATAL: ["bold", "redBright"],
}
}
});

Loading

0 comments on commit 5fb8036

Please sign in to comment.