Skip to content

Commit

Permalink
feat: 🎸 add verbose logging feature
Browse files Browse the repository at this point in the history
  • Loading branch information
nivekcode committed Dec 6, 2020
1 parent 55d7685 commit 068eb1f
Show file tree
Hide file tree
Showing 12 changed files with 125 additions and 122 deletions.
12 changes: 7 additions & 5 deletions src/bin/svg-to-ts.ts
Original file line number Diff line number Diff line change
Expand Up @@ -7,7 +7,7 @@ import {
ObjectConversionOptions,
ConstantsConversionOptions
} from '../lib/options/conversion-options';
import { generationSuccess, info, printLogo } from '../lib/helpers/log-helper';
import { Logger } from '../lib/helpers/logger';
import { setupCommander } from '../lib/options/command-line-collector';
import { convertToSingleObject } from '../lib/converters/object.converter';
import { convertToConstants } from '../lib/converters/constants.converter';
Expand All @@ -17,32 +17,34 @@ const convert = async (
conversionOptions: FileConversionOptions | ConstantsConversionOptions | ObjectConversionOptions
) => {
if (conversionOptions.conversionType === ConversionType.FILES) {
info('We are using the conversiontype "files"');
Logger.info('We are using the conversiontype "files"');
await convertToFiles(conversionOptions as FileConversionOptions);
}

if (conversionOptions.conversionType === ConversionType.CONSTANTS) {
info('We are using the conversion type "constants"');
Logger.info('We are using the conversion type "constants"');
await convertToConstants(conversionOptions as ConstantsConversionOptions);
}

if (conversionOptions.conversionType === ConversionType.OBJECT) {
info('We are using the conversion type "object"');
Logger.info('We are using the conversion type "object"');
await convertToSingleObject(conversionOptions as ObjectConversionOptions);
}
};

(async () => {
setupCommander();
printLogo();
Logger.printLogo();

const conversionOptions = await getOptions();

if (Array.isArray(conversionOptions)) {
for (const c of conversionOptions) {
Logger.changeVisibility(c.verbose);
await convert(c);
}
} else {
Logger.changeVisibility(conversionOptions.verbose);
await convert(conversionOptions);
}
})();
4 changes: 2 additions & 2 deletions src/lib/converters/constants.converter.ts
Original file line number Diff line number Diff line change
Expand Up @@ -5,7 +5,7 @@ import {
generateTypeHelper
} from '../generators/code-snippet-generators';
import { writeFile } from '../helpers/file-helpers';
import { generationSuccess } from '../helpers/log-helper';
import { Logger } from '../helpers/logger';
import { callAndMonitor, callAndMonitorAsync } from '../helpers/monitor';
import { ConstantsConversionOptions } from '../options/conversion-options';

Expand Down Expand Up @@ -40,6 +40,6 @@ export const convertToConstants = async (conversionOptions: ConstantsConversionO
writeFile.bind({}, outputDirectory, fileName, fileContent),
`Writing files to ${outputDirectory}`
);
generationSuccess(outputDirectory);
Logger.generationSuccess(outputDirectory);
}
};
14 changes: 9 additions & 5 deletions src/lib/converters/files.converter.ts
Original file line number Diff line number Diff line change
Expand Up @@ -8,7 +8,7 @@ import {
} from '../generators/code-snippet-generators';
import { generateCompleteIconSetContent } from '../helpers/complete-icon-set.helper';
import { deleteFiles, deleteFolder, writeFile } from '../helpers/file-helpers';
import { generationSuccess, info } from '../helpers/log-helper';
import { Logger } from '../helpers/logger';
import { callAndMonitor, callAndMonitorAsync } from '../helpers/monitor';
import { getFilePathsFromRegex } from '../helpers/regex-helpers';
import { FileConversionOptions } from '../options/conversion-options';
Expand All @@ -29,7 +29,7 @@ const generateSVGConstants = async (
const generatedFileName = `${svgDefinition.prefix}-${svgDefinition.filenameWithoutEnding}.icon`;
generatedFileNames.push(generatedFileName);
await writeFile(`${outputDirectory}/${iconsFolderName}`, generatedFileName, svgConstant);
info(`write file svg: ${outputDirectory}/${iconsFolderName}/${generatedFileName}.ts`);
Logger.verboseInfo(`write file svg: ${outputDirectory}/${iconsFolderName}/${generatedFileName}.ts`);
})
);
return generatedFileNames;
Expand All @@ -54,11 +54,15 @@ const generateModelFile = async (
const interfaceDefinition = generateInterfaceDefinition(conversionOptions);
const modelFile = `${typeDefinition}${interfaceDefinition}`;
await writeFile(`${outputDirectory}/${iconsFolderName}`, modelFileName, modelFile);
info(`model-file successfully generated under ${outputDirectory}/${iconsFolderName}/${modelFileName}.ts`);
Logger.verboseInfo(
`model-file successfully generated under ${outputDirectory}/${iconsFolderName}/${modelFileName}.ts`
);

if (additionalModelOutputPath) {
await writeFile(`${additionalModelOutputPath}`, modelFileName, modelFile);
info(`additional model-file successfully generated under ${additionalModelOutputPath}/${modelFileName}.ts`);
Logger.verboseInfo(
`additional model-file successfully generated under ${additionalModelOutputPath}/${modelFileName}.ts`
);
}
return modelFile;
};
Expand Down Expand Up @@ -144,5 +148,5 @@ export const convertToFiles = async (conversionOptions: FileConversionOptions):
'Compile TypeScript to JavaScript'
);
}
generationSuccess(outputDirectory);
Logger.generationSuccess(outputDirectory);
};
4 changes: 2 additions & 2 deletions src/lib/converters/object.converter.ts
Original file line number Diff line number Diff line change
@@ -1,5 +1,5 @@
import { writeFile } from '../helpers/file-helpers';
import { generationSuccess } from '../helpers/log-helper';
import { Logger } from '../helpers/logger';
import { callAndMonitorAsync } from '../helpers/monitor';
import { ObjectConversionOptions } from '../options/conversion-options';

Expand All @@ -24,5 +24,5 @@ export const convertToSingleObject = async (conversionOptions: ObjectConversionO
'Generate SVG Object'
);
await callAndMonitorAsync<void>(writeFile.bind({}, outputDirectory, fileName, fileContent), 'Write content to file');
generationSuccess(outputDirectory);
Logger.generationSuccess(outputDirectory);
};
71 changes: 30 additions & 41 deletions src/lib/converters/shared.converter.ts
Original file line number Diff line number Diff line change
Expand Up @@ -2,7 +2,7 @@ import * as path from 'path';

import { generateTypeName, generateVariableName } from '../generators/code-snippet-generators';
import { extractSvgContent } from '../helpers/file-helpers';
import { generateSpinner, info } from '../helpers/log-helper';
import { Logger } from '../helpers/logger';
import { getFilePathsFromRegex } from '../helpers/regex-helpers';
import { generateSvgOptimizer } from '../helpers/svg-optimization';

Expand All @@ -16,47 +16,36 @@ export interface SvgDefinition {
}

export const filesProcessor = async (conversionOptions): Promise<SvgDefinition[]> => {
const spinner = generateSpinner('Converting files to SVG Definition').start();
try {
const { prefix, delimiter, interfaceName, srcFiles, svgoConfig } = conversionOptions;
const svgOptimizer = generateSvgOptimizer(svgoConfig);
const filePaths = await getFilePathsFromRegex(srcFiles);
const { prefix, delimiter, interfaceName, srcFiles, svgoConfig } = conversionOptions;
const svgOptimizer = generateSvgOptimizer(svgoConfig);
const filePaths = await getFilePathsFromRegex(srcFiles);

// Using Promise.all we are making all files be processed in parallel as they have no dependency on each other
let svgDefinitions = await Promise.all(
filePaths.map(
async (filePath): Promise<SvgDefinition | null> => {
let svgDefinition: SvgDefinition = null;
const fileNameWithEnding = path.basename(filePath).replace(`'`, '');
const [filenameWithoutEnding, extension] = fileNameWithEnding.split('.');
if (extension === 'svg') {
const rawSvg = await extractSvgContent(filePath);
info(`optimize svg: ${fileNameWithEnding}`);
const optimizedSvg = await svgOptimizer.optimize(rawSvg, { path: filePath });
const variableName = generateVariableName(prefix, filenameWithoutEnding);
// Using Promise.all we are making all files be processed in parallel as they have no dependency on each other
let svgDefinitions = await Promise.all(
filePaths.map(
async (filePath): Promise<SvgDefinition | null> => {
let svgDefinition: SvgDefinition = null;
const fileNameWithEnding = path.basename(filePath).replace(`'`, '');
const [filenameWithoutEnding, extension] = fileNameWithEnding.split('.');
if (extension === 'svg') {
const rawSvg = await extractSvgContent(filePath);
Logger.verboseInfo(`optimize svg: ${fileNameWithEnding}`);
const optimizedSvg = await svgOptimizer.optimize(rawSvg, { path: filePath });
const variableName = generateVariableName(prefix, filenameWithoutEnding);

const typeName = generateTypeName(filenameWithoutEnding, delimiter);
svgDefinition = {
typeName,
prefix,
variableName,
interfaceName,
data: optimizedSvg.data,
filenameWithoutEnding
};
}
return svgDefinition;
const typeName = generateTypeName(filenameWithoutEnding, delimiter);
svgDefinition = {
typeName,
prefix,
variableName,
interfaceName,
data: optimizedSvg.data,
filenameWithoutEnding
};
}
)
);

// This will filter out null values
const definitions = svgDefinitions.filter(svgDefinition => svgDefinition);
spinner.succeed();
return definitions;
} catch (error) {
spinner.fail();
console.log(error);
process.exit(1);
}
return svgDefinition;
}
)
);
return svgDefinitions.filter(svgDefinition => svgDefinition);
};
37 changes: 0 additions & 37 deletions src/lib/helpers/log-helper.ts

This file was deleted.

43 changes: 43 additions & 0 deletions src/lib/helpers/logger.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,43 @@
import chalk from 'chalk';

import { DEFAULT_OPTIONS } from '../options/default-options';

export const messagePrefix = 'svg-to-ts:';

export class Logger {
private static verbose = DEFAULT_OPTIONS.verbose;

public static changeVisibility(verbose: boolean) {
Logger.verbose = verbose;
}

static printLogo() {
console.log(chalk.blue(`==========================================================`));
console.log(chalk.blue(`👷 Hi I am svg-to-ts - let's build an awesome icon library`));
console.log(chalk.blue(`==========================================================`));
}

static generationSuccess(path: string) {
Logger.logWithPrefix(
chalk.underline.green(`🏁 Everything is perfect: Icons succesfully generated under ${chalk.blue.underline(path)}`)
);
}

static info(message: string) {
Logger.logWithPrefix(`ℹ️ ${chalk.blueBright(message)}`);
}

static verboseInfo(message: string) {
if (Logger.verbose) {
Logger.logWithPrefix(`ℹ️ ${chalk.blueBright(message)}`);
}
}

static error(message: string) {
Logger.logWithPrefix(chalk.red(message));
}

private static logWithPrefix(messageLog: string) {
console.log(chalk.blue(messagePrefix), messageLog);
}
}
10 changes: 5 additions & 5 deletions src/lib/helpers/monitor.ts
Original file line number Diff line number Diff line change
@@ -1,7 +1,7 @@
import chalk from 'chalk';
import ora from 'ora';

import { messagePrefix } from './log-helper';
import { Logger, messagePrefix } from './logger';

export const generateSpinner = (text?: string) =>
ora({ text, spinner: 'christmas', prefixText: chalk.blue(messagePrefix) });
Expand All @@ -12,9 +12,9 @@ export const callAndMonitorAsync = async <T>(fn: (...args: any) => Promise<T>, s
const result = await fn();
spinner.succeed();
return result;
} catch (error) {
} catch (exception) {
spinner.fail();
console.error(error);
Logger.error(exception);
process.exit(1);
}
};
Expand All @@ -25,9 +25,9 @@ export const callAndMonitor = <T>(fn: (...args: any) => T, spinnerMessage: strin
const result = fn();
spinner.succeed();
return result;
} catch (error) {
} catch (exception) {
spinner.fail();
console.error(error);
Logger.error(exception);
process.exit(1);
}
};
4 changes: 2 additions & 2 deletions src/lib/helpers/regex-helpers.ts
Original file line number Diff line number Diff line change
@@ -1,7 +1,7 @@
import { Glob } from 'glob';
import * as util from 'util';

import { info } from './log-helper';
import { Logger } from './logger';

const getFilesFromRegex = util.promisify(Glob);

Expand All @@ -14,7 +14,7 @@ export const getFilePathsFromRegex = async (srcFiles: string[]) => {
nodir: true
});
if (directoryFiles.length === 0) {
info(`No matching files for regex: "${regex}"`);
Logger.verboseInfo(`No matching files for regex: "${regex}"`);
} else {
filePaths.push(...directoryFiles);
}
Expand Down
4 changes: 2 additions & 2 deletions src/lib/options/command-line-collector.ts
Original file line number Diff line number Diff line change
Expand Up @@ -2,7 +2,7 @@ import commander from 'commander';

import * as packgeJSON from '../../../package.json';
import { Delimiter } from '../generators/code-snippet-generators';
import { error } from '../helpers/log-helper';
import { Logger } from '../helpers/logger';
import { getSvgoConfig } from '../helpers/svg-optimization';

import {
Expand Down Expand Up @@ -91,7 +91,7 @@ export const collectCommandLineOptions = async (): Promise<
ConstantsConversionOptions | FileConversionOptions | ObjectConversionOptions
> => {
if (!commander.conversionType) {
error(`A conversion type is required, please specify one by passing it via --conversionType.
Logger.error(`A conversion type is required, please specify one by passing it via --conversionType.
Valid conversion types are (object, constants or files)`);
process.exit();
}
Expand Down
Loading

0 comments on commit 068eb1f

Please sign in to comment.