Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Feat/lambda eslint config #38

Merged
merged 3 commits into from
Dec 20, 2022
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
4 changes: 2 additions & 2 deletions packages/@guidesmiths/cuckoojs-cli/src/cli.ts
Original file line number Diff line number Diff line change
Expand Up @@ -2,7 +2,7 @@
import {Option, Command} from 'commander';
import {version} from '../package.json';
import {NewCommand, GenerateCommand} from './commands';
import {NewLambdaCommand} from "./commands/new-lambda.command";
import {LambdaNewCommand} from "./commands/lambda-new.command";

const init = (): void => {
const cuckoo = new Command('cuckoo');
Expand Down Expand Up @@ -55,7 +55,7 @@ const init = (): void => {
new Option('--skip-git-init', 'Skip git repository initialization')
)
.action(async (name: string, options: any) => {
await new NewLambdaCommand(name, options.gitProvider, !!options.skipGitInit).execute();
await new LambdaNewCommand(name, options.gitProvider, !!options.skipGitInit).execute();
});

cuckoo
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -9,7 +9,7 @@ import {AbstractCommand} from './abstract.command';
import Printer from '../lib/printer/printer';
import {GitRunner} from "../lib/runners/git.runner";

export class NewLambdaCommand extends AbstractCommand {
export class LambdaNewCommand extends AbstractCommand {
private readonly schematicRunner: SchematicRunner = new SchematicRunner();
private readonly gitRunner: GitRunner = new GitRunner();
private readonly npmRunner: NpmRunner = new NpmRunner();
Expand All @@ -33,12 +33,20 @@ export class NewLambdaCommand extends AbstractCommand {
}

public async execute() {
const printer = new Printer({total: 9, step: 1});
const printer = new Printer({total: 11, step: 1});
this.printSuccess(messages.banner);

if (this.checkFileExists()) {
this.printError(`Error generating new project: Folder ${this.name} already exists`);
NewLambdaCommand.endProcess(1);
if(this.skipGitInit){
this.printNeutral(`Folder ${this.name} already exists but git won't be initialized there`);
}else{
this.printError(`Error generating new project: Folder ${this.name} already exists`);
LambdaNewCommand.endProcess(1);
}
} else {
if(this.skipGitInit) {
this.printNeutral(`Folder ${this.name} does not exist and git won't be initialized there`);
}
}

try {
Expand Down Expand Up @@ -73,6 +81,10 @@ export class NewLambdaCommand extends AbstractCommand {
await this.schematicRunner.addGitignoreFile(this.name);
printer.endStep();

printer.startStep('Setting ESlint config');
await this.schematicRunner.addESlint(this.name);
printer.endStep();

printer.startStep('Adding Pull Request template file');
await this.schematicRunner.addPullRequestTemplate(this.name, this.gitProvider);
printer.endStep();
Expand All @@ -81,6 +93,10 @@ export class NewLambdaCommand extends AbstractCommand {
await this.npmRunner.install(this.name);
printer.endStep();

printer.startStep('Applying ESlist config');
await this.npmRunner.runScript(this.name, 'lint:fix');
printer.endStep();

printer.startStep('Creating husky files');
await this.npmRunner.runScript(this.name, 'prepare');
await this.bashRunnerHusky.addHuskyCommitMsg(this.name);
Expand All @@ -91,7 +107,7 @@ export class NewLambdaCommand extends AbstractCommand {
} catch (error: unknown) {
printer.load.fail(`Error generating new project: ${(error as Error).message}`);
this.removeFolder();
NewLambdaCommand.endProcess(1);
LambdaNewCommand.endProcess(1);
}
}

Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -72,7 +72,7 @@ export class NewCommand extends AbstractCommand {
printer.endStep();

printer.startStep('Creating husky files');
await this.bashRunnerHusky.addHuskyPreCommit(this.name);
await this.bashRunnerHusky.addHuskyCommitMsg(this.name);
printer.endStep();

this.printSuccess(`\n 🐦 Your CuckooJS nest "${this.name}" is generated and ready to use 🐦`);
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -41,4 +41,9 @@ export class SchematicRunner extends GenericRunner {
const args = [`@guidesmiths/cuckoojs-schematics:lambda-quickstart --directory=${name} --service-name=${name}`];
await super.run({command: SchematicRunner.getSchematicsCliPath(), args, stdio: ['pipe', 'pipe', 'inherit']});
}

public async addESlint(name: string) {
const args = [`@guidesmiths/cuckoojs-schematics:eslint --directory=${name}`];
await super.run({command: SchematicRunner.getSchematicsCliPath(), args, stdio: ['pipe', 'pipe', 'inherit']});
}
}
Original file line number Diff line number Diff line change
Expand Up @@ -35,6 +35,11 @@
"description": "Create a quickstart project with a lambda",
"factory": "./lambda-quickstart/lambda-quickstart.factory#main",
"schema": "./lambda-quickstart/schema.json"
},
"eslint": {
"description": "Set ESlint config",
"factory": "./eslint/eslint.factory#main",
"schema": "./eslint/schema.json"
}
}
}
Original file line number Diff line number Diff line change
@@ -0,0 +1,33 @@
import {Tree} from '@angular-devkit/schematics';
import {SchematicTestRunner} from '@angular-devkit/schematics/testing';
import * as path from 'path';

const collectionPath = path.join(__dirname, '../collection.json');

describe('eslint', () => {
it('works', async () => {
const runner = new SchematicTestRunner('schematics', collectionPath);
const folder = Tree.empty();
folder.create('package.json',Buffer.from('{}'));
const tree = await runner
.runSchematicAsync('eslint', {directory: '.'}, folder)
.toPromise();

expect(tree.files).toEqual([
'/package.json',
"/.eslintrc.js"
]);

const actualPackageJson = JSON.parse(tree.readContent('./package.json'));
expect(actualPackageJson.devDependencies).toEqual({
"eslint": "^8.29.0",
"eslint-config-airbnb-base": "^15.0.0",
"eslint-plugin-import": "^2.26.0",
"eslint-plugin-jest": "^27.1.6"
})
expect(actualPackageJson.scripts).toEqual({
"lint": "eslint .",
"lint:fix": "eslint . --fix",
})
});
});
Original file line number Diff line number Diff line change
@@ -0,0 +1,65 @@
import type {
Rule,
SchematicContext,
Tree} from '@angular-devkit/schematics';
import {
apply, chain,
MergeStrategy,
mergeWith, move,
template,
url,
} from '@angular-devkit/schematics';
import {normalize} from '@angular-devkit/core';

export const main = (options: any): Rule => (tree: Tree, context: SchematicContext) => {
context.logger.info('Setting up ESlint config');
const path = normalize(options.directory);

const templateSource = apply(url('./files'), [
template({...options}),
move(path),
renameFile(options),
]);

const merged = mergeWith(templateSource, MergeStrategy.Overwrite);

return chain([
merged,
updatePackageJson(path),
])(tree, context)
};

function renameFile(options: any): Rule {
return (tree: Tree, _context: SchematicContext) => {
const normalizedPath = normalize(options.directory);
tree.rename(`${normalizedPath}/eslintrc.js`, `${normalizedPath}/.eslintrc.js`);
return tree;
};
}

function updatePackageJson(directory: string): Rule {
return (tree: Tree, _context: SchematicContext) => {
const path = `${directory}/package.json`;
const file = tree.read(path) as unknown as string;
const json = JSON.parse(file.toString()) as Record<string, any>;

if (!json.devDependencies) {
json.devDependencies = {};
}

json.devDependencies['eslint'] = '^8.29.0';
json.devDependencies['eslint-config-airbnb-base'] = '^15.0.0';
json.devDependencies['eslint-plugin-import'] = '^2.26.0';
json.devDependencies['eslint-plugin-jest'] = '^27.1.6';

if(!json.scripts) {
json.scripts = {}
}

json.scripts['lint'] = 'eslint .';
json.scripts['lint:fix'] = 'eslint . --fix';

tree.overwrite(path, JSON.stringify(json, null, 2));
return tree;
};
}
w3dani marked this conversation as resolved.
Show resolved Hide resolved
Original file line number Diff line number Diff line change
@@ -0,0 +1,17 @@
module.exports = {
env: {
commonjs: true,
es2021: true,
node: true,
'jest/globals': true
},
extends: 'airbnb-base',
overrides: [
],
parserOptions: {
ecmaVersion: 'latest',
},
plugins: ['jest'],
rules: {
},
};
Original file line number Diff line number Diff line change
@@ -0,0 +1,15 @@
{
"$schema": "http://json-schema.org/schema",
"$id": "SchematicsESlint",
"title": "ESlint Options Schema",
"type": "object",
"properties": {
"directory": {
"type": "string",
"description": "eslint config directory",
"default": ".",
"x-prompt": "Where do you want to setup eslint?"
}
},
"required": ["directory"]
}
Original file line number Diff line number Diff line change
@@ -1,12 +1,12 @@
class HelloController {
constructor({logger}) {
this.logger = logger;
}

mergeName = (firstName, lastName) => {
this.logger.info('merging name', {firstName, lastName});
const helloController = ({ logger }) => {
const mergeName = (firstName, lastName) => {
logger.info('merging name', {firstName, lastName});
return `${firstName} ${lastName}`;
};

return {
mergeName
}
}

module.exports = HelloController;
module.exports = helloController;
Original file line number Diff line number Diff line change
@@ -1,4 +1,4 @@
const SampleController = require('../helloController');
const helloController = require('../helloController');
const loggerMock = require('./mocks/logger');

describe('helloController', () => {
Expand All @@ -9,8 +9,8 @@ describe('helloController', () => {
});

test('should merge name ok', () => {
const sampleController = new SampleController({logger});
const actual = sampleController.mergeName('a', 'b');
const testHelloController = helloController({logger});
const actual = testHelloController.mergeName('a', 'b');
expect(actual).toBe('a b');
});
});
Original file line number Diff line number Diff line change
@@ -1,30 +1,31 @@
const pino = require('pino');

class Logger {
constructor({config}) {
const {serviceName} = config;
this.pinoLogger = this.#initLogger({
name: serviceName,
const logger = ({ config }) => {
const { serviceName } = config;
const pinoLogger = pino({
base: {
name: serviceName,
},
timestamp: pino.stdTimeFunctions.isoTime,
formatters: {
level: label => ({level: label}),
},
});
}

#initLogger = ({name}) => pino({
base: {
name,
},
timestamp: pino.stdTimeFunctions.isoTime,
formatters: {
level: label => ({level: label}),
},
});
const debug = (message, data) => pinoLogger.debug({msg: message, data});

debug = (message, data) => this.pinoLogger.debug({msg: message, data});
const info = (message, data) => pinoLogger.info({msg: message, data});

info = (message, data) => this.pinoLogger.info({msg: message, data});
const warn = (message, data) => pinoLogger.warn({msg: message, data});

warn = (message, data) => this.pinoLogger.warn({msg: message, data});
const error = (message, data) => pinoLogger.error({msg: message, data});

error = (message, data) => this.pinoLogger.error({msg: message, data});
return {
debug,
info,
warn,
error,
}
}

module.exports = Logger;
module.exports = logger;