Skip to content

Commit

Permalink
Refactor on commands
Browse files Browse the repository at this point in the history
  • Loading branch information
erdemkosk committed Dec 10, 2023
1 parent d633a64 commit dab8e4f
Show file tree
Hide file tree
Showing 10 changed files with 77 additions and 74 deletions.
16 changes: 13 additions & 3 deletions lib/command/Command.ts
Expand Up @@ -8,9 +8,19 @@ export abstract class Command {
this.baseFolder = getBaseFolder()
}

abstract beforeExecute (): Promise<any>
abstract execute (): Promise<void>
async askForConfirmation (): Promise<boolean> {
async execute (): Promise<void> {
try {
const beforeExecuteReturnValue: any = await this.beforeExecute()
await this.onExecute(beforeExecuteReturnValue)
} catch (error) {
}
}

protected abstract beforeExecute (): Promise<any>

protected abstract onExecute (value: any): Promise<void>

protected async askForConfirmation (): Promise<boolean> {
const answer = await inquirer.prompt([
{
type: 'confirm',
Expand Down
45 changes: 21 additions & 24 deletions lib/command/commandTypes/CompareCommand.ts
Expand Up @@ -6,11 +6,12 @@ import chalk from 'chalk'
import inquirer from 'inquirer'

export class CompareCommand extends Command {
async beforeExecute (): Promise<any> {
protected async beforeExecute (): Promise<any> {
const files: string [] = await getEnvFilesRecursively({ directory: this.baseFolder })

if (files.length < 2) {
throw new Error(`You must have a minimum of ${chalk.blue('2')} services registered to compare.`)
console.log(`You must have a minimum of ${chalk.blue('2')} services registered to compare.`)
return
}

const answers = await inquirer.prompt([
Expand All @@ -36,32 +37,28 @@ export class CompareCommand extends Command {
return { source, destination }
}

async execute (): Promise<void> {
try {
const { source, destination } = await this.beforeExecute()
protected async onExecute (beforeExecuteReturnValue: any): Promise<void> {
const { source, destination } = beforeExecuteReturnValue

const {
differentVariables,
sourceServiceName,
destinationServiceName
} = await compareEnvFiles({ source, destination })
const {
differentVariables,
sourceServiceName,
destinationServiceName
} = await compareEnvFiles({ source, destination })

const table = new Table({
head: ['VALUES', sourceServiceName, destinationServiceName],
wordWrap: true,
colWidths: [20, 30, 30],
wrapOnWordBoundary: false
})
const table = new Table({
head: ['VALUES', sourceServiceName, destinationServiceName],
wordWrap: true,
colWidths: [20, 30, 30],
wrapOnWordBoundary: false
})

differentVariables.forEach(row => {
table.push(row)
})
differentVariables.forEach(row => {
table.push(row)
})

if (differentVariables.length > 0) {
console.log(table.toString())
}
} catch (error) {
console.log(error.message)
if (differentVariables.length > 0) {
console.log(table.toString())
}
}
}
34 changes: 16 additions & 18 deletions lib/command/commandTypes/LsCommand.ts
Expand Up @@ -6,7 +6,7 @@ import chalk from 'chalk'
import inquirer from 'inquirer'

export class LsCommand extends Command {
async beforeExecute (): Promise<any> {
protected async beforeExecute (): Promise<any> {
const files = await getEnvFilesRecursively({ directory: this.baseFolder })

if (files.length === 0) {
Expand All @@ -23,26 +23,24 @@ export class LsCommand extends Command {
return targetPath
}

async execute (): Promise<void> {
try {
const targetPath: string = await this.beforeExecute()
protected async onExecute (beforeExecuteReturnValue: any): Promise<void> {
const targetPath: string = beforeExecuteReturnValue

const { data } = await getValuesInEnv({ targetPath })
const { data } = await getValuesInEnv({ targetPath })

const table = new Table({
head: ['ENV', 'VALUE'],
colWidths: [20, 30],
wrapOnWordBoundary: false,
wordWrap: true
})
const terminalWidth = process.stdout.columns

data.forEach(row => {
table.push(row)
})
const table = new Table({
head: ['ENV', 'VALUE'],
colWidths: [Math.floor(terminalWidth / 2 - 5), Math.floor(terminalWidth / 2 - 5)],
wrapOnWordBoundary: false,
wordWrap: true
})

console.log(table.toString())
} catch (error) {
console.log(error.message)
}
data.forEach(row => {
table.push(row)
})

console.log(table.toString())
}
}
6 changes: 2 additions & 4 deletions lib/command/commandTypes/RestoreCommand.ts
Expand Up @@ -3,17 +3,15 @@ import { restoreEnvFile } from '../../handler/envHandler'
import chalk from 'chalk'

export class RestoreCommand extends Command {
async beforeExecute (): Promise<any> {
protected async beforeExecute (): Promise<any> {
const isConfirmed = await this.askForConfirmation()

if (!isConfirmed) {
console.log(`Operation is ${chalk.red('cancelled!')}`)
}
}

async execute (): Promise<void> {
await this.beforeExecute()

protected async onExecute (beforeExecuteReturnValue: any): Promise<void> {
const isSuccess = await restoreEnvFile()

isSuccess
Expand Down
6 changes: 3 additions & 3 deletions lib/command/commandTypes/RevertCommand.ts
Expand Up @@ -7,7 +7,7 @@ import inquirer from 'inquirer'
import { format } from 'date-fns'

export class RevertCommand extends Command {
async beforeExecute (): Promise<any> {
protected async beforeExecute (): Promise<any> {
const files = await getEnvFilesRecursively({ directory: this.baseFolder })

const { targetPath } = await inquirer.prompt({
Expand Down Expand Up @@ -53,8 +53,8 @@ export class RevertCommand extends Command {
return { targetPath, envValue, newValue: version.changes[0].oldValue }
}

async execute (): Promise<void> {
const { targetPath, envValue, newValue } = await this.beforeExecute()
protected async onExecute (beforeExecuteReturnValue: any): Promise<void> {
const { targetPath, envValue, newValue } = beforeExecuteReturnValue

await updateEnvFile({ file: targetPath, envValue, newValue })
console.log(`Environment variables restored in "${chalk.blue(targetPath)}"`)
Expand Down
6 changes: 3 additions & 3 deletions lib/command/commandTypes/SyncCommand.ts
Expand Up @@ -3,12 +3,12 @@ import { syncEnvFile } from '../../handler/envHandler'
import chalk from 'chalk'

export class SyncCommand extends Command {
async beforeExecute (): Promise<any> {
protected async beforeExecute (): Promise<any> {
return await syncEnvFile()
}

async execute (): Promise<void> {
const isSuccess: boolean = await this.beforeExecute()
protected async onExecute (beforeExecuteReturnValue: any): Promise<void> {
const isSuccess: boolean = beforeExecuteReturnValue

;(isSuccess)
? console.log(`Synchronization was ${chalk.blue('successful')}. You are ready to go!`)
Expand Down
6 changes: 3 additions & 3 deletions lib/command/commandTypes/UpdateAllCommand.ts
Expand Up @@ -4,7 +4,7 @@ import chalk from 'chalk'
import inquirer from 'inquirer'

export class UpdateAllCommand extends Command {
async beforeExecute (): Promise<any> {
protected async beforeExecute (): Promise<any> {
const envOptions = await promptForEnvVariable()

const { envValue, newValue } = await inquirer.prompt([
Expand Down Expand Up @@ -37,8 +37,8 @@ export class UpdateAllCommand extends Command {
return await updateAllEnvFile({ envValue, newValue })
}

async execute (): Promise<void> {
const effectedServices: [] = await this.beforeExecute()
protected async onExecute (beforeExecuteReturnValue: any): Promise<void> {
const effectedServices: [] = beforeExecuteReturnValue

effectedServices.forEach((service) => {
console.log(`Environment variables updated in "${chalk.blue(service)}"`)
Expand Down
6 changes: 3 additions & 3 deletions lib/command/commandTypes/UpdateCommand.ts
Expand Up @@ -5,7 +5,7 @@ import chalk from 'chalk'
import inquirer from 'inquirer'

export class UpdateCommand extends Command {
async beforeExecute (): Promise<any> {
protected async beforeExecute (): Promise<any> {
const files = await getEnvFilesRecursively({ directory: this.baseFolder })

const { targetPath } = await inquirer.prompt({
Expand Down Expand Up @@ -40,8 +40,8 @@ export class UpdateCommand extends Command {
return { targetPath, envValue, newValue }
}

async execute (): Promise<void> {
const { targetPath, envValue, newValue } = await this.beforeExecute()
protected async onExecute (beforeExecuteReturnValue: any): Promise<void> {
const { targetPath, envValue, newValue } = beforeExecuteReturnValue
await updateEnvFile({ file: targetPath, envValue, newValue })

console.log(`Environment variables updated in "${chalk.blue(targetPath)}"`)
Expand Down
20 changes: 10 additions & 10 deletions lib/handler/envHandler.ts
Expand Up @@ -22,7 +22,7 @@ function getServiceNameFromUrl ({ targetPath }: { targetPath: string }): string
return parts[parts.length - 2]
}

function splitEnvLine (line: string): [string, string] {
function extractEnvVariable (line: string): [string, string] {
const indexOfFirstEqualSign = line.indexOf('=')
if (indexOfFirstEqualSign >= 0) {
const envName = line.substring(0, indexOfFirstEqualSign)
Expand Down Expand Up @@ -83,7 +83,7 @@ export async function updateEnvFile ({
if (updatedFileContent !== undefined) {
const updatedLines = updatedFileContent.split('\n').map(line => {
// eslint-disable-next-line @typescript-eslint/no-unused-vars
const [currentEnvName, currentEnvValue] = splitEnvLine(line)
const [currentEnvName, currentEnvValue] = extractEnvVariable(line)
if (currentEnvName === envValue) {
return `${currentEnvName}=${newValue}`
}
Expand Down Expand Up @@ -151,7 +151,7 @@ export async function getValuesInEnv ({

for (const line of lines) {
if (line.trim() !== '') {
const [envName, envValue] = splitEnvLine(line)
const [envName, envValue] = extractEnvVariable(line)
data.push([envName, envValue])
}
}
Expand Down Expand Up @@ -192,17 +192,17 @@ export async function compareEnvFiles ({
const differentVariables: string[][] = [];

(sourceLines ?? []).forEach((sourceLine: string) => {
const sourceLineParts = splitEnvLine(sourceLine)
const sourceLineParts = extractEnvVariable(sourceLine)
const variableName: string = sourceLineParts[0]
const sourceValue: string = sourceLineParts[1]

const matchingDestinationLine: string | undefined = (destinationLines ?? []).find((destinationLine) => {
const destinationLineParts = splitEnvLine(destinationLine)
const destinationLineParts = extractEnvVariable(destinationLine)
return destinationLineParts[0] === variableName
})

if (matchingDestinationLine != null) {
const destinationValue = splitEnvLine(matchingDestinationLine)[1]
const destinationValue = extractEnvVariable(matchingDestinationLine)[1]
if (sourceValue !== destinationValue) {
differentVariables.push([variableName, sourceValue, destinationValue])
}
Expand Down Expand Up @@ -251,7 +251,7 @@ export async function promptForEnvVariable (): Promise<string[]> {

for (const line of sourceLines) {
if (line.trim() !== '') {
const [envName] = splitEnvLine(line)
const [envName] = extractEnvVariable(line)
variables.add(envName)
}
}
Expand All @@ -271,7 +271,7 @@ export async function getUniqueEnvNames (targetFolder: string): Promise<string[]

for (const line of sourceLines) {
if (line.trim() !== '') {
const [envName] = splitEnvLine(line)
const [envName] = extractEnvVariable(line)
envNames.add(envName)
}
}
Expand All @@ -288,7 +288,7 @@ export async function getEnvValue (targetFolder: string, envName: string): Promi

for (const line of sourceLines) {
if (line.trim() !== '') {
const [currentEnvName, value] = splitEnvLine(line)
const [currentEnvName, value] = extractEnvVariable(line)
if (currentEnvName === envName) {
return value
}
Expand All @@ -303,7 +303,7 @@ export async function restoreEnvFile (): Promise<boolean> {
const currentDirectory = process.cwd()
const directoryName = currentDirectory.split('/').pop() ?? ''
const serviceFolderPath = path.join(getBaseFolder(), directoryName)
const versionFilePath = path.join(serviceFolderPath, 'version.json')
const versionFilePath = path.join(serviceFolderPath, '.version.json')

const versionFileContent = await readFile({ file: versionFilePath })

Expand Down
6 changes: 3 additions & 3 deletions lib/handler/historyHandler.ts
Expand Up @@ -13,7 +13,7 @@ import {
} from './envHandler'

export async function saveFieldVersion (targetPath: string, fieldName: string, value: string): Promise<void> {
const versionFilePath = path.join(path.dirname(targetPath), 'version.json')
const versionFilePath = path.join(path.dirname(targetPath), '.version.json')

await createFileIfNotExists(versionFilePath)

Expand Down Expand Up @@ -50,7 +50,7 @@ export async function saveFieldVersionsInSync (serviceFolderPath: string, envVal
return
}

const versionFilePath = path.join(serviceFolderPath, 'version.json')
const versionFilePath = path.join(serviceFolderPath, '.version.json')
await createFileIfNotExists(versionFilePath)

const versionFileContent = await readFile({ file: versionFilePath })
Expand Down Expand Up @@ -79,7 +79,7 @@ export async function saveFieldVersionsInSync (serviceFolderPath: string, envVal
}

export async function getEnvVersions (targetPath: string, fieldName: string): Promise<IEnvVersion[]> {
const versionFilePath = path.join(path.dirname(targetPath), 'version.json')
const versionFilePath = path.join(path.dirname(targetPath), '.version.json')
const versionFileContent = await readFile({ file: versionFilePath })

if (versionFileContent !== undefined) {
Expand Down

0 comments on commit dab8e4f

Please sign in to comment.