Skip to content

Commit

Permalink
refactor: move some utils to @revili/helpers
Browse files Browse the repository at this point in the history
  • Loading branch information
recoluan committed Dec 7, 2024
1 parent cc6822d commit 407d443
Show file tree
Hide file tree
Showing 30 changed files with 185 additions and 180 deletions.
4 changes: 0 additions & 4 deletions docs/zh/docs/api/node-api.md
Original file line number Diff line number Diff line change
Expand Up @@ -72,7 +72,3 @@ interface KitOptions {

export default demoKit
```

## Kit Data Management

###
1 change: 1 addition & 0 deletions packages/@revili/helpers/package.json
Original file line number Diff line number Diff line change
Expand Up @@ -37,6 +37,7 @@
"dependencies": {
"@types/inquirer": "9.0.3",
"cac": "6.7.14",
"gitly": "3.0.0",
"vite": "3.2.3",
"vue": "3.2.45",
"vue-router": "^4.1.6",
Expand Down
3 changes: 2 additions & 1 deletion packages/@revili/helpers/src/node/index.ts
Original file line number Diff line number Diff line change
@@ -1,2 +1,3 @@
export * from "./composables/index.js";
export * from './paths.js'
export * from "./utils/index.js";
export * from "./composables/index.js";
32 changes: 32 additions & 0 deletions packages/@revili/helpers/src/node/paths.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,32 @@
import os from 'node:os'
import process from 'node:process'
import { resolve } from 'node:path'

// Environment variable for data directory
const USER_DATA_DIR_ENV = 'REVILI_DATA_DIR'

// Get the current working directory
export const CWD = process.cwd()

// Base user data directory structure
const homeDir = os.homedir()
const defaultDataDir = resolve(homeDir, '.revili')

// Allow custom data directory through environment variable
export const USER_DATA_PATH = process.env[USER_DATA_DIR_ENV]
? resolve(process.env[USER_DATA_DIR_ENV])
: defaultDataDir

// Organized data subdirectories
export const DATA_DIRS = {
// Directory for storing revili kits
kits: resolve(USER_DATA_PATH, 'kits'),
// Directory for storing kit-specific data
kitsData: resolve(USER_DATA_PATH, 'kitsData')
} as const

// Specific data file paths
export const DATA_FILES = {
package: resolve(DATA_DIRS.kits, 'package.json'),
config: resolve(USER_DATA_PATH, 'revili.config.json')
} as const
1 change: 1 addition & 0 deletions packages/@revili/helpers/src/node/utils/cac.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1 @@
export { CAC } from "cac";
2 changes: 1 addition & 1 deletion packages/@revili/helpers/src/node/utils/chalk.ts
Original file line number Diff line number Diff line change
@@ -1,3 +1,3 @@
import chalk from 'chalk';

export default chalk;
export { chalk }
4 changes: 4 additions & 0 deletions packages/@revili/helpers/src/node/utils/gitly.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,4 @@
import { default as gitlyAlias } from 'gitly'

export const gitly = gitlyAlias.default

16 changes: 9 additions & 7 deletions packages/@revili/helpers/src/node/utils/index.ts
Original file line number Diff line number Diff line change
@@ -1,7 +1,9 @@
import { ora, spinner } from './ora.js';
import chalk from './chalk.js';
import inquirer from './inquirer.js';

export { ora, spinner, chalk, inquirer }

export * from "./defineKit.js";
export * from './cac.js'
export * from './ora.js'
export * from './gitly.js'
export * from './chalk.js'
export * from './kitData.js'
export * from './inquirer.js'
export * from './defineKit.js'
export * from './reviliData.js'
export * from './childProcess.js'
2 changes: 1 addition & 1 deletion packages/@revili/helpers/src/node/utils/inquirer.ts
Original file line number Diff line number Diff line change
@@ -1,3 +1,3 @@
import inquirer from 'inquirer';

export default inquirer
export { inquirer }
Original file line number Diff line number Diff line change
@@ -1,6 +1,6 @@
import fs from 'node:fs'
import { resolve } from 'node:path'
import { DATA_DIRS } from '../alias.js'
import { DATA_DIRS } from '../paths.js'

/**
* Basic kit data structure
Expand Down Expand Up @@ -28,7 +28,7 @@ function kitNameToPath(kitName: string): string {
* @param kitName The name of the kit
* @returns The absolute path to the kit's data directory
*/
export function getKitDataPath(kitName: string) {
function getKitDataPath(kitName: string) {
const kitPath = kitNameToPath(kitName)
return resolve(DATA_DIRS.kitsData, kitPath)
}
Expand All @@ -39,7 +39,7 @@ export function getKitDataPath(kitName: string) {
* @param filename The name of the file
* @returns The absolute path to the file in the kit's data directory
*/
export function getKitDataFilePath(kitName: string, filename: string) {
function getKitDataFilePath(kitName: string, filename: string) {
return resolve(getKitDataPath(kitName), filename)
}

Expand Down Expand Up @@ -111,7 +111,7 @@ export async function writeKitData<T extends object>(kitName: string, data: T):
* @param partialData Partial data object to merge with existing data
*/
export async function updateKitData<T extends object>(kitName: string, partialData: Partial<T>): Promise<void> {
const existingData = await getKitData<T>(kitName)
const newData = { ...existingData, ...partialData }
await writeKitData(kitName, newData)
const currentData = await getKitData<T>(kitName)
const updatedData = { ...currentData, ...partialData }
await writeKitData(kitName, updatedData)
}
89 changes: 89 additions & 0 deletions packages/@revili/helpers/src/node/utils/reviliData.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,89 @@
import fs from 'node:fs'
import path from 'node:path'
import { pathToFileURL } from 'node:url'
import { CWD, DATA_FILES, DATA_DIRS, USER_DATA_PATH } from '../paths.js'

import { Kit } from './defineKit.js'

export interface ReviliConfig {
activeKit: string
kitList: string[]
}

export async function initConfigFolder() {
if (!fs.existsSync(DATA_DIRS.kits)) {
fs.mkdirSync(DATA_DIRS.kits, { recursive: true })
}

if (!fs.existsSync(DATA_FILES.package)) {
// add package.json into config folder
setPackageConfig()
}
}

export async function getReviliConfig(): Promise<ReviliConfig> {
const isExistConfigFile = fs.existsSync(DATA_FILES.config)
if (!isExistConfigFile) {
// create config folder
fs.mkdirSync(USER_DATA_PATH, { recursive: true })
setReviliConfig()
}

try {
const content = await fs.promises.readFile(DATA_FILES.config, 'utf-8')
return JSON.parse(content)
} catch (error) {
// Return default config if file doesn't exist or is invalid
return {
activeKit: '',
kitList: []
}
}
}

export async function setReviliConfig(config: ReviliConfig = {
activeKit: '',
kitList: []
}): Promise<void> {
try {
// Ensure parent directory exists
fs.mkdirSync(USER_DATA_PATH, { recursive: true })
fs.writeFileSync(DATA_FILES.config, JSON.stringify(config, null, 2))
} catch (error) {
console.error('[revili] Failed to write config')
}
}

export function setPackageConfig() {
try {
// Ensure the directory exists
fs.mkdirSync(DATA_DIRS.kits, { recursive: true })
fs.writeFileSync(DATA_FILES.package, JSON.stringify({
name: 'revili_kits',
type: 'module'
}, null, 2))
} catch (error) {
console.error('[revili] Failed to write package.json')
}
}

export async function getActiveKit(customKitDir: string) {
try {
const { activeKit: activeKitName } = await getReviliConfig();

const ACTIVE_KIT_DIR = path.join(USER_DATA_PATH, `./node_modules/${activeKitName}`);

const CLIENT_DIR = customKitDir
? path.join(CWD, `${customKitDir}/client`)
: path.join(ACTIVE_KIT_DIR, `./dist/client`);

const ACTIVE_KIT_ENTRY = customKitDir
? path.join(CWD, `${customKitDir}/node/index.js`)
: path.join(ACTIVE_KIT_DIR, `./dist/node/index.js`);
const activeKit = (await import(pathToFileURL(ACTIVE_KIT_ENTRY) as unknown as string)).default as Kit;

return { activeKit, CLIENT_DIR }
} catch(error) {
return { activeKit: null, CLIENT_DIR: '' }
}
}
3 changes: 2 additions & 1 deletion packages/@revili/helpers/tsconfig.json
Original file line number Diff line number Diff line change
Expand Up @@ -7,7 +7,8 @@
"jsx": "preserve",
"lib": ["ESNext", "DOM"],
"outDir": "./dist",
"types": ["node"]
"types": ["node"],
"rootDir": "./src"
},
"include": [
"src/**/*.ts",
Expand Down
2 changes: 0 additions & 2 deletions packages/core/package.json
Original file line number Diff line number Diff line change
Expand Up @@ -52,8 +52,6 @@
"@vitejs/plugin-vue": "5.0.4",
"@vitejs/plugin-vue-jsx": "3.1.0",
"autoprefixer": "10.4.13",
"cac": "6.7.14",
"gitly": "3.0.0",
"postcss": "8.4.21",
"postcss-each": "1.1.0",
"postcss-import": "15.0.0",
Expand Down
55 changes: 13 additions & 42 deletions packages/core/src/node/alias.ts
Original file line number Diff line number Diff line change
@@ -1,57 +1,28 @@
import os from 'node:os'
import process from 'node:process'
import { resolve } from 'node:path'
import { fileURLToPath } from 'node:url'

// Environment variable for data directory
const USER_DATA_DIR_ENV = 'REVILI_DATA_DIR'

// Get the current working directory
export const CWD = process.cwd()
import { resolve } from 'node:path'
import {
CWD,
DATA_DIRS,
DATA_FILES,
USER_DATA_PATH
} from '@revili/helpers/node'

// Get the root directory of the package
export const PKG_ROOT = resolve(fileURLToPath(import.meta.url), '../..')
const PKG_ROOT = resolve(fileURLToPath(import.meta.url), '../..')

// Path to the client distribution directory
export const DIST_CLIENT_PATH = resolve(PKG_ROOT, 'client')
const DIST_CLIENT_PATH = resolve(PKG_ROOT, 'client')

// Directory containing CLI-related files
export const CLI_FILE_DIR = resolve(fileURLToPath(import.meta.url), '..')

// Base user data directory structure
const homeDir = os.homedir()
const defaultDataDir = resolve(homeDir, '.revili')

// Allow custom data directory through environment variable
// This is useful for:
// 1. Different user profiles or workspaces
// 2. Custom deployment environments
// 3. Systems with specific data storage requirements
export const USER_DATA_PATH = process.env[USER_DATA_DIR_ENV]
? resolve(process.env[USER_DATA_DIR_ENV])
: defaultDataDir

// Organized data subdirectories
export const DATA_DIRS = {
// Directory for storing revili kits
kits: resolve(USER_DATA_PATH, 'kits'),
// Directory for storing kit-specific data
kitsData: resolve(USER_DATA_PATH, 'kitsData')
} as const

// Specific data file paths
export const DATA_FILES = {
package: resolve(DATA_DIRS.kits, 'package.json'),
config: resolve(USER_DATA_PATH, 'revili.config.json')
} as const
const CLI_FILE_DIR = resolve(fileURLToPath(import.meta.url), '..')

// Export all path constants
export const PATHS = {
CWD,
PKG_ROOT,
DIST_CLIENT_PATH,
DATA_DIRS,
DATA_FILES,
CLI_FILE_DIR,
USER_DATA_PATH,
DATA_DIRS,
DATA_FILES
DIST_CLIENT_PATH,
} as const
9 changes: 3 additions & 6 deletions packages/core/src/node/command/createAddCommand.ts
Original file line number Diff line number Diff line change
@@ -1,10 +1,6 @@
import {CAC} from 'cac'
import { spinner, chalk } from '@revili/helpers/node'
import { consoleUtil } from '../utils/index.js'
import { CAC, spinner, chalk, execPromise, initConfigFolder, getReviliConfig, setReviliConfig, type ReviliConfig, initKitData } from '@revili/helpers/node'

import { PATHS } from '../alias.js'
import { execPromise } from '../utils/childProcess.js'
import { initConfigFolder, getReviliConfig, setReviliConfig, type ReviliConfig } from '../utils/reviliData.js'
import { initKitData } from '../utils/kitData.js'

const kitRegExp = /^(@[\d_-\w\W]+\/)?([\d_-\w]+)(@.+)?$/

Expand Down Expand Up @@ -49,6 +45,7 @@ export function createAddCommand(program: CAC) {
}
}
} catch (error) {
console.error(111, error)
spinner.fail(chalk.red('[revili] ') + `${targetKit} was not found!`)
}

Expand Down
10 changes: 4 additions & 6 deletions packages/core/src/node/command/createInitKitCommand.ts
Original file line number Diff line number Diff line change
@@ -1,10 +1,8 @@
import {CAC} from 'cac'
import fs from 'node:fs'
import path from 'node:path'
import { default as gitly } from 'gitly'
import { inquirer, spinner, chalk } from '@revili/helpers/node'
import { CAC, inquirer, spinner, chalk, gitly } from '@revili/helpers/node'

import { CWD } from '../alias.js'
import { PATHS } from '../alias.js'
import { consoleUtil } from '../utils/index.js'

export function createInitKitCommand(program: CAC) {
Expand All @@ -21,7 +19,7 @@ export function createInitKitCommand(program: CAC) {
try {
const targetDir = kitName ?? gitRepo
// @ts-ignore
await gitly.default(`${gitScope}/${gitRepo}`, path.join(CWD, targetDir))
await gitly(`${gitScope}/${gitRepo}#main`, path.join(PATHS.CWD, targetDir))
spinner.succeed(`[revili] Load file from https://github.com/${gitScope}/${gitRepo}`)


Expand Down Expand Up @@ -83,7 +81,7 @@ function changePackage (kitName: string, targetDir: string) {
spinner.start(chalk.blue(`[revili] Edit kit name`))

return new Promise((resolve) => {
const packageJsonPath = `${CWD}/${targetDir}/package.json`
const packageJsonPath = `${PATHS.CWD}/${targetDir}/package.json`
fs.readFile(packageJsonPath, (err, data) => {
if (err) throw err
const _data = JSON.parse(data.toString())
Expand Down
4 changes: 1 addition & 3 deletions packages/core/src/node/command/createKitCommands.ts
Original file line number Diff line number Diff line change
@@ -1,6 +1,4 @@
import {CAC} from 'cac'

import { getActiveKit } from '../utils/getActiveKit.js'
import { CAC, getActiveKit } from '@revili/helpers/node'

export async function createKitCommands(program: CAC, customKitDir: string) {
const { activeKit } = await getActiveKit(customKitDir)
Expand Down
4 changes: 1 addition & 3 deletions packages/core/src/node/command/createListCommand.ts
Original file line number Diff line number Diff line change
@@ -1,8 +1,6 @@
import { CAC } from 'cac'
import { chalk } from '@revili/helpers/node'
import { CAC, chalk, getReviliConfig } from '@revili/helpers/node'

import { consoleUtil } from '../utils/index.js'
import { getReviliConfig } from '../utils/reviliData.js'

export function createListCommand(program: CAC) {
program
Expand Down
6 changes: 1 addition & 5 deletions packages/core/src/node/command/createRemoveCommand.ts
Original file line number Diff line number Diff line change
@@ -1,11 +1,7 @@
import { CAC } from 'cac'
import { spinner, chalk } from '@revili/helpers/node'
import { CAC, spinner, chalk, execPromise, removeKitData, getReviliConfig, setReviliConfig, type ReviliConfig } from '@revili/helpers/node'

import { PATHS } from '../alias.js'
import { consoleUtil } from '../utils/index.js'
import { execPromise } from '../utils/childProcess.js'
import { getReviliConfig, setReviliConfig, type ReviliConfig } from '../utils/reviliData.js'
import { removeKitData } from '../utils/kitData.js'

export function createRemoveCommand(program: CAC) {
program
Expand Down
2 changes: 1 addition & 1 deletion packages/core/src/node/command/createStartCommand.ts
Original file line number Diff line number Diff line change
@@ -1,4 +1,4 @@
import {CAC} from 'cac'
import {CAC} from '@revili/helpers/node'
import {createViteServer} from '../viteServer/index.js'

export function createStartCommand(program: CAC) {
Expand Down
Loading

0 comments on commit 407d443

Please sign in to comment.