diff --git a/.eslintrc.json b/.eslintrc.json deleted file mode 100644 index a20556f..0000000 --- a/.eslintrc.json +++ /dev/null @@ -1,39 +0,0 @@ -{ - "env": { - "es2021": true, - "node": true - }, - "extends": [ - "eslint:recommended", - "plugin:@typescript-eslint/recommended", - "plugin:@stylistic/all-extends" - ], - "ignorePatterns": [ - "*.js", - "*.d.ts", - "*.json", - "dist/", - "node_modules/**/*" - ], - "parser": "@typescript-eslint/parser", - "parserOptions": { - "ecmaVersion": "latest", - "sourceType": "module", - "tsconfigRootDir": ".", - "project": [ - "./tsconfig.json" - ] - }, - "plugins": [ - "import", - "@stylistic", - "@typescript-eslint" - ], - "root": true, - "rules": {}, - "settings": { - "import/resolver": { - "typescript": true - } - } -} diff --git a/.gitignore b/.gitignore index 158b756..d315ec2 100644 --- a/.gitignore +++ b/.gitignore @@ -178,5 +178,6 @@ dist .ara .private pkg +tests/playground ara-*.* bun.lockb \ No newline at end of file diff --git a/ci.ts b/ci.ts index fe821fe..676c546 100644 --- a/ci.ts +++ b/ci.ts @@ -1,6 +1,6 @@ -import {readableStreamToText} from "bun"; -import {rm, mkdir} from "node:fs/promises"; -import {doesDirectoryExist, getFileList} from "./src/utils"; +import { readableStreamToText } from "bun"; +import { rm, mkdir } from "node:fs/promises"; +import { doesDirectoryExist, getFileList } from "./src/utils"; import os from "node:os"; const packageFiles: Array = [ @@ -8,19 +8,17 @@ const packageFiles: Array = [ "ara.config.jsonc", "ara.config.toml", "LICENSE", - "README.md" + "README.md", ]; // --------------------------------------------------- -async function clean (type?: Array<"archive" | "pkg" | "wipe">) { - +async function clean(type?: Array<"archive" | "pkg" | "wipe">) { const clean: Array = []; if (type?.includes("archive") || type?.includes("wipe")) { - - // Find files with these patterns: ara-*.zip, ara-*.tar.gz - const {stdout} = Bun.spawn([ + // Find files with these patterns: ara-*.zip, ara-*.tar.gz + const { stdout } = Bun.spawn([ "find", ".", "-type", @@ -29,142 +27,106 @@ async function clean (type?: Array<"archive" | "pkg" | "wipe">) { "ara-*.zip", "-o", "-name", - "ara-*.tar.gz" + "ara-*.tar.gz", ]); if (stdout) { - const output = await readableStreamToText(stdout); const files = output.split("\n"); for (const file of files) { - if (file) { - clean.push(file); - } - } - } - } if (type?.includes("pkg") || type?.includes("wipe")) { - clean.push("pkg"); - } if (type?.includes("wipe")) { - clean.push( "node_modules", - "bun.lockb" + "bun.lockb", ); - } for (const path of clean) { - try { - await rm( path, { - "force": true, - "recursive": true - } + force: true, + recursive: true, + }, ); - - } catch (error) { - + } + catch (error) { console.error(error); - } - } - } -async function build () { - +async function build() { await clean(["pkg"]); - const {stdout, stderr} = Bun.spawn([ + const { stdout, stderr } = Bun.spawn([ "bun", "build", "./src/index.ts", "--compile", "--outfile", - "pkg/ara" + "pkg/ara", ]); if (stderr) { - const error = await readableStreamToText(stderr); console.error(error); return; - } if (stdout) { - const output = await readableStreamToText(stdout); console.log(output); - } - } -async function pkg () { - +async function pkg() { if (!await doesDirectoryExist("pkg")) { - mkdir("pkg"); - } for await (const path of packageFiles) { - const file = await Bun.file(path).exists(); if (file) { - console.log(`Copying ${path} to pkg...`); - const {stderr} = Bun.spawn([ + const { stderr } = Bun.spawn([ "cp", path, - "pkg" + "pkg", ]); if (stderr) { - const error = await readableStreamToText(stderr); console.error(error); return; - } - } - } - } -async function archive () { - +async function archive() { await clean(["archive"]); const pkgDirectory = "pkg"; if (!await doesDirectoryExist(pkgDirectory)) { - console.error(`${pkgDirectory} isn't ready yet`); return; - } const packageJSON = await Bun.file("package.json").json(); @@ -173,11 +135,9 @@ async function archive () { const arch = os.arch(); let extension = ".tar.gz"; const fileList = await getFileList("pkg"); - let cmd = ""; switch (platform) { - case "linux": case "darwin": @@ -191,44 +151,34 @@ async function archive () { default: console.error("Unsupported platform"); return; - } - const {stdout, stderr} = Bun.spawn( + const { stdout, stderr } = Bun.spawn( cmd.split(" "), { - "cwd": "pkg" - } + cwd: "pkg", + }, ); if (stderr) { - const error = await readableStreamToText(stderr); console.error(error); - } if (stdout) { - const output = await readableStreamToText(stdout); console.log(output); - } - } // --------------------------------------------------- (async () => { - if (process.argv.length > 2) { - switch (process.argv[2]) { - case "-c": case "clean": switch (process.argv[3]) { - case "-a": case "archive": await clean(["archive"]); @@ -244,10 +194,9 @@ async function archive () { default: await clean([ "archive", - "pkg" + "pkg", ]); break; - } break; case "-b": @@ -265,9 +214,6 @@ async function archive () { default: console.log("Invalid argument"); break; - } - } - })(); diff --git a/eslint.config.js b/eslint.config.js new file mode 100644 index 0000000..6a52e08 --- /dev/null +++ b/eslint.config.js @@ -0,0 +1,40 @@ +/** @type {import('eslint').Linter.FlatConfig[]} */ + +import pluginImport from "eslint-plugin-import"; +import parserTypescript from "@typescript-eslint/parser"; +import pluginTypescript from "@typescript-eslint/eslint-plugin"; +import stylistic from "@stylistic/eslint-plugin"; + +export default [ + { + files: ["*.ts"], + ignores: [ + "*.js", + "*.d.ts", + "*.json", + ".private", + "pkg/", + "node_modules/**/*", + ], + languageOptions: { + ecmaVersion: "latest", + sourceType: "module", + parser: parserTypescript, + }, + plugins: { + pluginImport, + pluginTypescript, + stylistic, + }, + settings: { + "import/resolver": { + typescript: true, + }, + }, + }, + stylistic.configs.customize({ + indent: 4, + quotes: "double", + semi: true, + }), +]; diff --git a/package.json b/package.json index 31f7e84..e8d4703 100644 --- a/package.json +++ b/package.json @@ -10,8 +10,8 @@ "builder": "bun compile && bun pkg", "archive": "bun run ./ci.ts archive", "all": "bun builder && bun archive", - "lint": "eslint \"src/**/*.ts\"", - "check": "eslint \"src/**/*.ts\" --fix" + "lint": "eslint --config eslint.config.js .", + "check": "eslint --config eslint.config.js . --fix" }, "devDependencies": { "@stylistic/eslint-plugin": "^1.5.0", diff --git a/src/constants/index.ts b/src/constants/index.ts index 16e87ee..6b075bb 100644 --- a/src/constants/index.ts +++ b/src/constants/index.ts @@ -1 +1 @@ -export {paths, configPath} from "./paths"; +export { paths, configPath } from './paths' diff --git a/src/constants/paths.ts b/src/constants/paths.ts index 126b505..ad1ee23 100644 --- a/src/constants/paths.ts +++ b/src/constants/paths.ts @@ -1,24 +1,24 @@ -import {ARAConfigPath} from "types"; +import { ARAConfigPath } from 'types' -const root = process.cwd(); -const workspace = `${root}/.ara`; -const temp = `${workspace}/.temp`; +const root = process.cwd() +const workspace = `${root}/.ara` +const temp = `${workspace}/.temp` export const paths = { - root, - workspace, - temp -}; + root, + workspace, + temp, +} export const configPath: ARAConfigPath = { - "locations": [ - root, - workspace - ], - "names": ["ara.config"], - "extensions": [ - "json", - "jsonc", - "toml" - ] -}; + locations: [ + root, + workspace, + ], + names: ['ara.config'], + extensions: [ + 'json', + 'jsonc', + 'toml', + ], +} diff --git a/src/index.ts b/src/index.ts index 20b79ec..9f147a8 100644 --- a/src/index.ts +++ b/src/index.ts @@ -1,14 +1,14 @@ -import {Command} from "commander"; +import { Command } from 'commander' -const program = new Command(); +const program = new Command() -program. - name("ara"). - description("A multi-tool for bun based projects"). - version( - "0.0.1", - "-v, --version", - "Output the current version" - ); +program + .name('ara') + .description('A multi-tool for bun based projects') + .version( + '0.0.1', + '-v, --version', + 'Output the current version', + ) -program.parse(process.argv); +program.parse(process.argv) diff --git a/src/utils/config/index.ts b/src/utils/config/index.ts index 55a16e3..4608205 100644 --- a/src/utils/config/index.ts +++ b/src/utils/config/index.ts @@ -1,7 +1,7 @@ -import {ARAConfig, ARAConfigPath} from "types"; -import {configPath, paths} from "../../constants"; -import * as JSONC from "comment-json"; -import * as TOML from "toml-patch"; +import { ARAConfig, ARAConfigPath } from 'types' +import { configPath, paths } from '../../constants' +import * as JSONC from 'comment-json' +import * as TOML from 'toml-patch' /** * Generates an array of full paths based on the provided configuration path object. @@ -9,98 +9,80 @@ import * as TOML from "toml-patch"; * @param configPath - The configuration path object containing locations, names, and extensions. * @returns An array of strings representing full paths generated from the combinations of locations, names, and extensions. */ -function generateConfigPaths (configPath: ARAConfigPath): string[] { - - const result: string[] = []; - - configPath.locations.forEach((location) => { - - configPath.names.forEach((name) => { - - configPath.extensions.forEach((extension) => { - - const _location = location === "." - ? "" - : `${location}/`; - const fullPath = `${_location}${name}.${extension}`; - result.push(fullPath); - - }); - - }); - - }); - - return result; - +function generateConfigPaths(configPath: ARAConfigPath): string[] { + const result: string[] = [] + + configPath.locations.forEach((location) => { + configPath.names.forEach((name) => { + configPath.extensions.forEach((extension) => { + const _location = location === '.' + ? '' + : `${location}/` + const fullPath = `${_location}${name}.${extension}` + result.push(fullPath) + }) + }) + }) + + return result } - /** * Retrieves and parses the configuration from specified paths asynchronously. * * @param customPath - A custom path to a configuration file. * @returns A promise that resolves to an ARAConfig object based on the configuration files found in the generated paths. */ -export async function getConfig (customPath?: string): Promise { - - const configPaths = customPath - ? [customPath] - : generateConfigPaths(configPath); - - const configs: Array = await Promise.all(configPaths.map(async (path) => { - - const filepath = `${process.cwd()}/${path}`; - const file = Bun.file(filepath); - - if (await file.exists() && path.endsWith(".json")) { - - return file.json(); - - } else if (await file.exists() && path.endsWith(".jsonc")) { - - return JSONC.parse( - await file.text(), - undefined, - true - ); - - } else if (await file.exists() && path.endsWith(".toml")) { - - return TOML.parse(await file.text()); - - } else if (await file.exists()) { +export async function getConfig(customPath?: string): Promise { + const configPaths = customPath + ? [customPath] + : generateConfigPaths(configPath) - return file.json(); + const configs: Array = await Promise.all(configPaths.map(async (path) => { + const filepath = `${process.cwd()}/${path}` + const file = Bun.file(filepath) - } - - return undefined; - - })); - - const config = configs.find((c) => c !== undefined); - - return { - "clean": config - ? config.clean - : [], - "update": { - "exclude": config?.update?.exclude - ? config.update.exclude - : [], - "force": config?.update?.force - ? config.update.force - : false, - "install": config?.update?.install - ? config.update.install - : false, - "write": config?.update?.write - ? config.update.write - : false - } - }; + if (await file.exists() && path.endsWith('.json')) { + return file.json() + } + else if (await file.exists() && path.endsWith('.jsonc')) { + return JSONC.parse( + await file.text(), + undefined, + true, + ) + } + else if (await file.exists() && path.endsWith('.toml')) { + return TOML.parse(await file.text()) + } + else if (await file.exists()) { + return file.json() + } + return undefined + })) + + const config = configs.find(c => c !== undefined) + + return { + clean: config + ? config.clean + : [], + update: { + exclude: config?.update?.exclude + ? config.update.exclude + : [], + force: config?.update?.force + ? config.update.force + : false, + install: config?.update?.install + ? config.update.install + : false, + write: config?.update?.write + ? config.update.write + : false, + }, + } } /** @@ -111,55 +93,48 @@ export async function getConfig (customPath?: string): Promise { * @param options.type - The type of the configuration file to be generated ("json", "jsonc", or "toml"). * @returns A promise that resolves when the configuration file is successfully generated or rejects with an error message. */ -export async function generateConfig ({ - dest = "root", type = "jsonc" +export async function generateConfig({ + dest = 'root', type = 'jsonc', }: { - dest: "root" | "workspace"; - type: "json" | "jsonc" | "toml"; + dest: 'root' | 'workspace' + type: 'json' | 'jsonc' | 'toml' }): Promise { - - const config = await getConfig(); - - const configPath = - dest === "root" - ? `${paths.root}/ara.config.${type}` - : `${paths.workspace}/ara.config.${type}`; - - const serializers: Record string | Promise> = { - "json": (data) => JSON.stringify( - data, - null, - 4 - ), - "jsonc": async () => { - - const result = Bun.file(`${paths.root}/ara.config.jsonc`); - return await result.exists() - ? JSONC.stringify( - JSONC.parse(await result.text()), - null, - 4 - ) - : ""; - - }, - "toml": (data) => TOML.stringify(data) - }; - - const serializer = serializers[type]; - - if (serializer) { - - const serializedData = await serializer(config); - await Bun.write( - configPath, - serializedData - ); - - } else { - - throw new Error(`Unsupported configuration type: ${type}`); - - } - + const config = await getConfig() + + const configPath + = dest === 'root' + ? `${paths.root}/ara.config.${type}` + : `${paths.workspace}/ara.config.${type}` + + const serializers: Record string | Promise> = { + json: data => JSON.stringify( + data, + null, + 4, + ), + jsonc: async () => { + const result = Bun.file(`${paths.root}/ara.config.jsonc`) + return await result.exists() + ? JSONC.stringify( + JSONC.parse(await result.text()), + null, + 4, + ) + : '' + }, + toml: data => TOML.stringify(data), + } + + const serializer = serializers[type] + + if (serializer) { + const serializedData = await serializer(config) + await Bun.write( + configPath, + serializedData, + ) + } + else { + throw new Error(`Unsupported configuration type: ${type}`) + } } diff --git a/src/utils/error/index.ts b/src/utils/error/index.ts index bfa4a1a..e19602f 100644 --- a/src/utils/error/index.ts +++ b/src/utils/error/index.ts @@ -4,27 +4,21 @@ * @param error - The error to be handled, can be of type 'Error', 'string', or 'unknown'. * @returns A string containing the error message. If the error is not of expected types, "Unknown error" is returned. */ -export function handleError (error: unknown): string { - - let _error: string; - - if (error instanceof Error) { - - // If 'error' is an instance of 'Error', extract the error message. - _error = error.message; - - } else if (typeof error === "string") { - - // If 'error' is a string, use it as the error message. - _error = error; - - } else { - - // If 'error' is of an unexpected type, set a default error message. - _error = "Unknown error"; - - } - - return _error; - +export function handleError(error: unknown): string { + let _error: string + + if (error instanceof Error) { + // If 'error' is an instance of 'Error', extract the error message. + _error = error.message + } + else if (typeof error === 'string') { + // If 'error' is a string, use it as the error message. + _error = error + } + else { + // If 'error' is of an unexpected type, set a default error message. + _error = 'Unknown error' + } + + return _error } diff --git a/src/utils/fs/index.ts b/src/utils/fs/index.ts index dd2cb70..7e1716d 100644 --- a/src/utils/fs/index.ts +++ b/src/utils/fs/index.ts @@ -1,6 +1,6 @@ -import {exists, readdir, stat} from "node:fs/promises"; -import * as tar from "tar"; -import {handleError} from ".."; +import { exists, readdir, stat } from 'node:fs/promises' +import * as tar from 'tar' +import { handleError } from '..' /** * Asynchronously checks if the specified path corresponds to a directory. @@ -8,12 +8,10 @@ import {handleError} from ".."; * @param path - The path to be checked. * @returns A promise that resolves to a boolean indicating whether the path is a directory or not. */ -export async function isDirectory (path: string): Promise { - - const stats = await stat(path); - - return stats.isDirectory(); +export async function isDirectory(path: string): Promise { + const stats = await stat(path) + return stats.isDirectory() } /** @@ -22,12 +20,10 @@ export async function isDirectory (path: string): Promise { * @param path - The path to be checked. * @returns A promise that resolves to a boolean indicating whether the path is a file or not. */ -export async function isFile (path: string): Promise { - - const stats = await stat(path); - - return stats.isFile(); +export async function isFile(path: string): Promise { + const stats = await stat(path) + return stats.isFile() } /** @@ -36,10 +32,8 @@ export async function isFile (path: string): Promise { * @param path - The path to the directory. * @returns A promise that resolves to a boolean indicating whether the directory exists or not. */ -export async function doesDirectoryExist (path: string): Promise { - - return exists(path); - +export async function doesDirectoryExist(path: string): Promise { + return exists(path) } /** @@ -48,10 +42,8 @@ export async function doesDirectoryExist (path: string): Promise { * @param path - The path to the file. * @returns A promise that resolves to a boolean indicating whether the file exists or not. */ -export async function doesFileExist (path: string): Promise { - - return Bun.file(path).exists(); - +export async function doesFileExist(path: string): Promise { + return Bun.file(path).exists() } /** @@ -61,21 +53,16 @@ export async function doesFileExist (path: string): Promise { * @param directory - The directory where the contents of the tarball will be extracted. * @returns A promise that resolves to a string indicating success or an error message in case of an error. */ -export async function extractTarball (tarball: string, directory: string): Promise { - - try { - - await tar.extract({"file": tarball, - "cwd": directory}); - - return "success"; - - } catch (error) { - - return handleError(error); - - } - +export async function extractTarball(tarball: string, directory: string): Promise { + try { + await tar.extract({ file: tarball, + cwd: directory }) + + return 'success' + } + catch (error) { + return handleError(error) + } } /** @@ -85,40 +72,33 @@ export async function extractTarball (tarball: string, directory: string): Promi * @param files - An optional array of file paths to append to. Used for recursive calls. * @returns A promise that resolves to an array of file paths in the specified directory and its subdirectories. */ -export async function getFileList (directory: string, files: string[] = []): Promise { - - const fileList = await readdir(directory); - - for await (const file of fileList) { - - const fullPath = `${directory}/${file}`; - - if ( - await isDirectory(fullPath) === true && - ![ - ".git", - "node_modules" - ].includes(file) - ) { - - await getFileList( - fullPath, - files - ); - - } else { - - const path = fullPath.replace( - /^\.\/|.*pkg\//, - "" - ); - - files.push(path); - - } - +export async function getFileList(directory: string, files: string[] = []): Promise { + const fileList = await readdir(directory) + + for await (const file of fileList) { + const fullPath = `${directory}/${file}` + + if ( + await isDirectory(fullPath) === true + && ![ + '.git', + 'node_modules', + ].includes(file) + ) { + await getFileList( + fullPath, + files, + ) } + else { + const path = fullPath.replace( + /^\.\/|.*pkg\//, + '', + ) - return files; + files.push(path) + } + } + return files } diff --git a/src/utils/http/index.ts b/src/utils/http/index.ts index 8abcacf..e4be6a9 100644 --- a/src/utils/http/index.ts +++ b/src/utils/http/index.ts @@ -1,4 +1,4 @@ -import {handleError} from ".."; +import { handleError } from '..' /** * Asynchronously fetches and downloads a file from the specified URL to the specified path. @@ -7,43 +7,38 @@ import {handleError} from ".."; * @param path - The path where the downloaded file will be saved. * @returns A promise that resolves to an object containing information about the downloaded file (path, size, type) or a string in case of an error. */ -export async function fetchDownload ( - url: string, - path: string +export async function fetchDownload( + url: string, + path: string, ): Promise< | { - path: string; - size: number; - type: string; + path: string + size: number + type: string } | string > { + try { + const response = await fetch(url) as Response - try { - - const response = await fetch(url) as Response; - - if (!response.ok) throw new Error(`Failed to download file from ${url}`); - - const blob = await response.blob(); + if (!response.ok) throw new Error(`Failed to download file from ${url}`) - await Bun.write( - path, - blob - ); + const blob = await response.blob() - const file = Bun.file(path); + await Bun.write( + path, + blob, + ) - return { - "path": file.name ?? path, - "size": file.size, - "type": file.type - }; - - } catch (error: unknown) { - - return handleError(error); + const file = Bun.file(path) + return { + path: file.name ?? path, + size: file.size, + type: file.type, } - + } + catch (error: unknown) { + return handleError(error) + } } diff --git a/src/utils/index.ts b/src/utils/index.ts index 65989ee..5ae9874 100644 --- a/src/utils/index.ts +++ b/src/utils/index.ts @@ -1,26 +1,26 @@ export { - getConfig -} from "./config"; + getConfig, +} from './config' -export {handleError} from "./error"; +export { handleError } from './error' export { - isDirectory, - isFile, - doesDirectoryExist, - doesFileExist, - extractTarball, - getFileList -} from "./fs"; + isDirectory, + isFile, + doesDirectoryExist, + doesFileExist, + extractTarball, + getFileList, +} from './fs' export { - fetchDownload -} from "./http"; + fetchDownload, +} from './http' export { - isPackageInstalled, - listPackages, - listPackagesByRegex, - getPackageJSON, - getPackageInfo -} from "./package"; + isPackageInstalled, + listPackages, + listPackagesByRegex, + getPackageJSON, + getPackageInfo, +} from './package' diff --git a/src/utils/package/index.ts b/src/utils/package/index.ts index 9cf29fd..5fc1b4c 100644 --- a/src/utils/package/index.ts +++ b/src/utils/package/index.ts @@ -1,5 +1,5 @@ -import type {PackageJSON} from "types"; -import {handleError} from ".."; +import type { PackageJSON } from 'types' +import { handleError } from '..' /** * Asynchronously checks if a package is installed by inspecting the dependencies, @@ -8,26 +8,21 @@ import {handleError} from ".."; * @param packageName - The name of the package to check for. * @returns A promise that resolves to a boolean indicating whether the package is installed or a string in case of an error. */ -export async function isPackageInstalled (packageName: string): Promise { +export async function isPackageInstalled(packageName: string): Promise { + try { + const packageJson: PackageJSON = await Bun.file(`${process.cwd()}/package.json`).json() - try { + if (packageJson.dependencies?.[packageName]) return true - const packageJson: PackageJSON = await Bun.file(`${process.cwd()}/package.json`).json(); + if (packageJson.devDependencies?.[packageName]) return true - if (packageJson.dependencies?.[packageName]) return true; - - if (packageJson.devDependencies?.[packageName]) return true; - - if (packageJson.peerDependencies?.[packageName]) return true; - - return false; - - } catch (error: unknown) { - - return handleError(error); - - } + if (packageJson.peerDependencies?.[packageName]) return true + return false + } + catch (error: unknown) { + return handleError(error) + } } /** @@ -35,42 +30,37 @@ export async function isPackageInstalled (packageName: string): Promise; - devDependencies: Array; - peerDependencies: Array; + dependencies: Array + devDependencies: Array + peerDependencies: Array } | string > { + try { + const packageJson: PackageJSON = await Bun.file(`${process.cwd()}/package.json`).json() + const packages: { + dependencies: Array + devDependencies: Array + peerDependencies: Array + } = { + dependencies: [], + devDependencies: [], + peerDependencies: [], + } - try { - - const packageJson: PackageJSON = await Bun.file(`${process.cwd()}/package.json`).json(); - const packages: { - dependencies: Array; - devDependencies: Array; - peerDependencies: Array; - } = { - "dependencies": [], - "devDependencies": [], - "peerDependencies": [] - }; - - if (packageJson.dependencies) for (const packageName in packageJson.dependencies) packages.dependencies.push(packageName); - - if (packageJson.devDependencies) for (const packageName in packageJson.devDependencies) packages.devDependencies.push(packageName); - - if (packageJson.peerDependencies) for (const packageName in packageJson.peerDependencies) packages.peerDependencies.push(packageName); - - return packages; - - } catch (error: unknown) { + if (packageJson.dependencies) for (const packageName in packageJson.dependencies) packages.dependencies.push(packageName) - return handleError(error); + if (packageJson.devDependencies) for (const packageName in packageJson.devDependencies) packages.devDependencies.push(packageName) - } + if (packageJson.peerDependencies) for (const packageName in packageJson.peerDependencies) packages.peerDependencies.push(packageName) + return packages + } + catch (error: unknown) { + return handleError(error) + } } /** @@ -79,55 +69,48 @@ export async function listPackages (): Promise< * @param regex - An array of regular expressions to match package names. * @returns A promise that resolves to an object containing arrays of matching dependencies or a string in case of an error. */ -export async function listPackagesByRegex (regex: Array): Promise< +export async function listPackagesByRegex(regex: Array): Promise< | { - dependencies: Array; - devDependencies: Array; - peerDependencies: Array; - all: Array; + dependencies: Array + devDependencies: Array + peerDependencies: Array + all: Array } | string > { + try { + const packageJson: PackageJSON = await Bun.file(`${process.cwd()}/package.json`).json() + const packages: { + dependencies: Array + devDependencies: Array + peerDependencies: Array + all: Array + } = { + dependencies: [], + devDependencies: [], + peerDependencies: [], + all: [], + } - try { - - const packageJson: PackageJSON = await Bun.file(`${process.cwd()}/package.json`).json(); - const packages: { - dependencies: Array; - devDependencies: Array; - peerDependencies: Array; - all: Array; - } = { - "dependencies": [], - "devDependencies": [], - "peerDependencies": [], - "all": [] - }; - - for (const reg of regex) { - - if (packageJson.dependencies) for (const packageName in packageJson.dependencies) if (packageName.match(reg)) packages.dependencies.push(packageName); - - if (packageJson.devDependencies) for (const packageName in packageJson.devDependencies) if (packageName.match(reg)) packages.devDependencies.push(packageName); - - if (packageJson.peerDependencies) for (const packageName in packageJson.peerDependencies) if (packageName.match(reg)) packages.peerDependencies.push(packageName); - - } - - packages.all = [ - ...packages.dependencies, - ...packages.devDependencies, - ...packages.peerDependencies - ]; - - return packages; - - } catch (error: unknown) { + for (const reg of regex) { + if (packageJson.dependencies) for (const packageName in packageJson.dependencies) if (packageName.match(reg)) packages.dependencies.push(packageName) - return handleError(error); + if (packageJson.devDependencies) for (const packageName in packageJson.devDependencies) if (packageName.match(reg)) packages.devDependencies.push(packageName) + if (packageJson.peerDependencies) for (const packageName in packageJson.peerDependencies) if (packageName.match(reg)) packages.peerDependencies.push(packageName) } + packages.all = [ + ...packages.dependencies, + ...packages.devDependencies, + ...packages.peerDependencies, + ] + + return packages + } + catch (error: unknown) { + return handleError(error) + } } /** @@ -135,20 +118,15 @@ export async function listPackagesByRegex (regex: Array): Promise< * * @returns A promise that resolves to a PackageJSON object or a string in case of an error. */ -export async function getPackageJSON (): Promise { - - try { - - const packageJson: PackageJSON = await Bun.file(`${process.cwd()}/package.json`).json(); - - return packageJson; - - } catch (error: unknown) { - - return handleError(error); - - } +export async function getPackageJSON(): Promise { + try { + const packageJson: PackageJSON = await Bun.file(`${process.cwd()}/package.json`).json() + return packageJson + } + catch (error: unknown) { + return handleError(error) + } } /** @@ -157,36 +135,31 @@ export async function getPackageJSON (): Promise { * @param packageName - The name of the package to retrieve information for. * @returns A promise that resolves to an object containing the version or a string in case of an error. */ -export async function getPackageInfo (packageName: string): Promise< +export async function getPackageInfo(packageName: string): Promise< | { - version: string; + version: string } | string > { + try { + const packageJson: PackageJSON = await Bun.file(`${process.cwd()}/package.json`).json() - try { - - const packageJson: PackageJSON = await Bun.file(`${process.cwd()}/package.json`).json(); - - let version = null; - - if (packageJson.dependencies?.[packageName]) version = packageJson.dependencies[packageName]; + let version = null - if (packageJson.devDependencies?.[packageName]) version = packageJson.devDependencies[packageName]; + if (packageJson.dependencies?.[packageName]) version = packageJson.dependencies[packageName] - if (packageJson.peerDependencies?.[packageName]) version = packageJson.peerDependencies[packageName]; + if (packageJson.devDependencies?.[packageName]) version = packageJson.devDependencies[packageName] - if (version !== null) return {"version": version.replace( - "^", - "" - )}; + if (packageJson.peerDependencies?.[packageName]) version = packageJson.peerDependencies[packageName] - throw new Error(`${packageName} not found in package.json`); - - } catch (error: unknown) { - - return handleError(error); - - } + if (version !== null) return { version: version.replace( + '^', + '', + ) } + throw new Error(`${packageName} not found in package.json`) + } + catch (error: unknown) { + return handleError(error) + } } diff --git a/tests/e2e/index.spec.ts b/tests/e2e/index.spec.ts index 519bcc9..3f41ee4 100644 --- a/tests/e2e/index.spec.ts +++ b/tests/e2e/index.spec.ts @@ -1,17 +1,14 @@ -import {describe, test} from "bun:test"; - +import { describe, test } from 'bun:test' describe( - "ara", - () => { - - test( - "--help", - async () => { - // const command = await $("pkg/ara --help"); - // expect(command).toContain("Usage: ara [options] [command]"); - } - ); - - } -); + 'ara', + () => { + test( + '--help', + async () => { + // const command = await $("pkg/ara --help"); + // expect(command).toContain("Usage: ara [options] [command]"); + }, + ) + }, +) diff --git a/tests/e2e/utils.spec.ts b/tests/e2e/utils.spec.ts index 0b440b2..7089577 100644 --- a/tests/e2e/utils.spec.ts +++ b/tests/e2e/utils.spec.ts @@ -1,29 +1,23 @@ -import {describe, expect, test} from "bun:test"; -import {getConfig} from "../../src/utils/config/index"; +import { describe, expect, test } from 'bun:test' +import { getConfig } from '../../src/utils/config/index' describe( - "ara::utils", - () => { - - describe( - "config", - () => { - - test( - "getConfig()", - async () => { - - const result = await getConfig(); - - console.log(result); - - expect(typeof result).toBe("object"); - - } - ); - - } - ); - - } -); + 'ara::utils', + () => { + describe( + 'config', + () => { + test( + 'getConfig()', + async () => { + const result = await getConfig() + + console.log(result) + + expect(typeof result).toBe('object') + }, + ) + }, + ) + }, +)