Skip to content

Commit

Permalink
feat: create engine to add colors in logs string
Browse files Browse the repository at this point in the history
  • Loading branch information
jlenon7 committed Apr 5, 2022
1 parent 965a060 commit 85afae5
Show file tree
Hide file tree
Showing 5 changed files with 107 additions and 33 deletions.
6 changes: 3 additions & 3 deletions src/Cli.ts
Original file line number Diff line number Diff line change
Expand Up @@ -8,12 +8,12 @@
*/

import figlet from 'figlet'
import { resolve } from 'path'
import { Command } from 'commander'
import { New } from './Commands/New'
import { version } from '../package.json'
import chalkRainbow from 'chalk-rainbow'
import { Make } from './Commands/Make'
import { resolve } from 'path'
import chalkRainbow from 'chalk-rainbow'
import { version } from '../package.json'

export class Cli {
private clientFolder: string
Expand Down
34 changes: 22 additions & 12 deletions src/Commands/Make.ts
Original file line number Diff line number Diff line change
Expand Up @@ -8,25 +8,24 @@
*/

import ejs from 'ejs'
import chalk from 'chalk'
import { Logger } from '../Utils/Logger'
import { File, Folder, Path, String } from '@secjs/utils'
import { CtxLogger } from '../Utils/CtxLogger'
import { existsSync } from 'fs'
import { parse } from 'path'

export class Make {
private readonly logger: Logger
private readonly clientFolder: string
private readonly templatesFolder: Folder

public constructor(clientFolder: string) {
this.clientFolder = clientFolder

this.logger = new Logger()

this.templatesFolder = new Folder(Path.pwd('templates')).loadSync()
}

async controller(name: string, options: any): Promise<void> {
this.logger.success.bold.log('[ MAKING CONTROLLER ]\n')
new Logger().success.bold.log('[ MAKING CONTROLLER ]\n')

if (name.includes('Controller') || name.includes('Controllers')) {
name = name.split('Controller')[0]
Expand All @@ -35,21 +34,32 @@ export class Make {
const template = this.getTemplate('__name__Controller', options)

if (!template) {
// TODO Log error instead of throw
throw new Error('File not found')
CtxLogger.error(
`Template for extension ({yellow} "${options.extension}") has not been found`,
)

return
}

// TODO Resolve the path always looking to his project root
// TODO Maybe find for the package.json file in getConcretePath
const path = this.getConcretePath(name, template.base)
const content = this.normalizeTemplate(name, template.getContentSync())

const concreteController = await new File(path, content).create()
if (existsSync(path)) {
CtxLogger.error(
`The controller ({yellow} "${
parse(path).name
}") already exists. Try using another name`,
)

return
}

const controller = await new File(path, content).create()

console.log(
`\n${chalk.bold.green('[ success ]')} Controller ${
concreteController.name
} successfully created inside app/Http/Controllers`,
CtxLogger.success(
`Controller ({yellow} "${controller.name}") successfully created.`,
)
}

Expand Down
26 changes: 8 additions & 18 deletions src/Commands/New.ts
Original file line number Diff line number Diff line change
Expand Up @@ -9,26 +9,24 @@

import ora from 'ora'
import chalk from 'chalk'
import { sep } from 'path'
import Table from 'cli-table'
import { existsSync } from 'fs'
import { promisify } from 'util'
import { sep } from 'path'
import { Logger } from '../Utils/Logger'
import { Folder, Path } from '@secjs/utils'
import { CtxLogger } from '../Utils/CtxLogger'
import { NodeExecException } from '../Exceptions/NodeExecException'

const exec = promisify(require('child_process').exec)

export class New {
private readonly logger: Logger
private readonly clientFolder: string
private readonly repositoryUrl: string

public constructor(clientFolder: string) {
this.clientFolder = clientFolder

this.logger = new Logger()

this.repositoryUrl = 'https://github.com/AthennaIO/Scaffold.git'
}

Expand All @@ -37,10 +35,8 @@ export class New {
await new Folder(Path.storage()).create()

if (!this[options.type]) {
console.log(
`${chalk.bold.red('[ error ]')} The project type "${
options.type
}" doesnt exist. Try running "athenna new:project --help" to se the available project types`,
CtxLogger.error(
`The project type ({yellow} "${options.type}") doesnt exist. Try running ({yellow} "athenna new:project --help") to se the available project types`,
)

return
Expand All @@ -50,16 +46,14 @@ export class New {
}

async http(projectName: string) {
this.logger.success.bold.log('[ GENERATING HTTP SERVER ]\n')
new Logger().success.bold.log('[ GENERATING HTTP SERVER ]\n')

const projectPath = Path.storage(`project/${projectName}`)
const concretePath = `${this.clientFolder}${sep}${projectName}`

if (existsSync(concretePath)) {
console.log(
`${chalk.bold.red(
'[ error ]',
)} The folder ${projectName} already exists. Try another project name`,
CtxLogger.error(
`The directory ({yellow} "${projectName}") already exists. Try another project name`,
)

return
Expand All @@ -84,11 +78,7 @@ export class New {
await this.runCommand(runNpmInstallCommand, 'Installing dependencies')
await this.runCommand(moveProjectCommand, 'Moving project to your path')

console.log(
`\n${chalk.bold.green(
'[ success ]',
)} Project created at ${projectName} folder`,
)
CtxLogger.success(`Project created at ({yellow} "${projectName}") folder`)

const table = new Table()

Expand Down
44 changes: 44 additions & 0 deletions src/Utils/CtxLogger.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,44 @@
/**
* @athenna/cli
*
* (c) João Lenon <lenon@athenna.io>
*
* For the full copyright and license information, please view the LICENSE
* file that was distributed with this source code.
*/
import chalk from 'chalk'
import { Logger } from './Logger'

export class CtxLogger {
private static logger = new Logger()

static info(message: string): void {
const ctx = chalk.bold.cyan('[ info ]')

this.logger.log(`${ctx} ${message}`)
}

static warn(message: string): void {
const ctx = chalk.bold.yellow('[ warn ]')

this.logger.log(`${ctx} ${message}`)
}

static error(message: string): void {
const ctx = chalk.bold.red('[ error ]')

this.logger.log(`${ctx} ${message}`)
}

static debug(message: string): void {
const ctx = chalk.bold.magenta('[ debug ]')

this.logger.log(`${ctx} ${message}`)
}

static success(message: string): void {
const ctx = chalk.bold.green('\n[ success ]')

this.logger.log(`${ctx} ${message}`)
}
}
30 changes: 30 additions & 0 deletions src/Utils/Logger.ts
Original file line number Diff line number Diff line change
Expand Up @@ -8,6 +8,7 @@
*/

import chalk from 'chalk'
import { Is } from '@secjs/utils'

export class Logger {
private chalk: any
Expand Down Expand Up @@ -53,6 +54,35 @@ export class Logger {
}

log(content: any) {
if (Is.String(content)) {
const matches = content.match(/\({(.*?)} (.*?)\)/g)

if (matches) {
matches.forEach(match => {
const color = match
.split(' ')[0]
.replace('(', '')
.replace('{', '')
.replace('}', '')

if (!this.chalk[color]) {
throw new Error(`Color ${color} does not exist`)
}

const message = match
.replace(`({${color}} `, '')
.replace(')', '')
.replace('}', '')

const replacedMatch = match
.replace(`({${color}} `, '')
.replace(`${message})`, this.chalk[color](message))

content = content.replace(match, replacedMatch)
})
}
}

console.log(this.chalk(content))
this.chalk = chalk
}
Expand Down

0 comments on commit 85afae5

Please sign in to comment.