UNPKG

@api-buddy/plugin-utils

Version:

Shared utilities for API Buddy plugins

109 lines (94 loc) 2.45 kB
import { promises as fs } from 'fs'; import path from 'path'; import { fileURLToPath } from 'url'; import { promisify } from 'util'; import { exec as execCb } from 'child_process'; const exec = promisify(execCb); /** * Get the directory name of the current module (ESM compatible) */ export function getDirname(importMetaUrl: string): string { return path.dirname(fileURLToPath(importMetaUrl)); } /** * Check if a file or directory exists */ export async function exists(filePath: string): Promise<boolean> { try { await fs.access(filePath); return true; } catch { return false; } } /** * Create a directory if it doesn't exist */ export async function ensureDir(dirPath: string): Promise<void> { try { await fs.mkdir(dirPath, { recursive: true }); } catch (error: any) { if (error.code !== 'EEXIST') { throw error; } } } /** * Read a file as a string */ export async function readFile(filePath: string): Promise<string> { return fs.readFile(filePath, 'utf-8'); } /** * Write content to a file, creating parent directories if needed */ export async function writeFile(filePath: string, content: string): Promise<void> { await ensureDir(path.dirname(filePath)); await fs.writeFile(filePath, content, 'utf-8'); } /** * Copy a file from source to destination */ export async function copyFile(src: string, dest: string): Promise<void> { await ensureDir(path.dirname(dest)); await fs.copyFile(src, dest); } /** * Copy a directory recursively */ export async function copyDir(src: string, dest: string): Promise<void> { await ensureDir(dest); const entries = await fs.readdir(src, { withFileTypes: true }); for (const entry of entries) { const srcPath = path.join(src, entry.name); const destPath = path.join(dest, entry.name); if (entry.isDirectory()) { await copyDir(srcPath, destPath); } else { await copyFile(srcPath, destPath); } } } /** * Execute a shell command */ export async function runCommand( command: string, options: { cwd?: string; stdio?: 'inherit' | 'pipe' } = {} ): Promise<{ stdout: string; stderr: string }> { return exec(command, { cwd: options.cwd || process.cwd(), ...(options.stdio === 'inherit' ? { stdio: 'inherit' } : {}), }); } export const fsUtils = { getDirname, exists, ensureDir, readFile, writeFile, copyFile, copyDir, runCommand, }; export default fsUtils;