piral-cli
Version:
The standard CLI for creating and building a Piral instance or a Pilet.
97 lines (80 loc) • 3.03 kB
text/typescript
import { resolve } from 'path';
import { log } from '../common/log';
import { findFile } from '../common/io';
import { runCommand } from '../common/scripts';
import { MemoryStream } from '../common/MemoryStream';
// Helpers:
async function runBunProcess(args: Array<string>, target: string, output?: MemoryStream) {
log('generalDebug_0003', 'Starting the Bun process ...');
const cwd = resolve(process.cwd(), target);
return await runCommand('bun', args, cwd, output);
}
async function tryRunBunProcess(args: Array<string>, target: string, output: MemoryStream) {
try {
return await runBunProcess(args, target, output);
} catch (err) {
log('generalInfo_0000', output.value || `bun failed due to ${err}`);
throw err;
}
}
function convert(flags: Array<string>) {
return flags.map((flag) => {
switch (flag) {
case '--save-exact':
return '--exact';
case '--save-dev':
return '--dev';
case '--no-save':
// unfortunately no (https://github.com/yarnpkg/yarn/issues/1743)
return '';
default:
return flag;
}
});
}
// Client interface functions:
export async function installDependencies(target = '.', ...flags: Array<string>) {
const ms = new MemoryStream();
await tryRunBunProcess(['install', ...convert(flags)], target, ms);
log('generalDebug_0003', `Bun install dependencies result: ${ms.value}`);
return ms.value;
}
export async function uninstallPackage(packageRef: string, target = '.', ...flags: Array<string>) {
const ms = new MemoryStream();
await tryRunBunProcess(['remove', packageRef, ...convert(flags)], target, ms);
log('generalDebug_0003', `Bun remove package result: ${ms.value}`);
return ms.value;
}
export async function installPackage(packageRef: string, target = '.', ...flags: Array<string>) {
const ms = new MemoryStream();
await tryRunBunProcess(['add', packageRef, ...convert(flags)], target, ms);
log('generalDebug_0003', `Bun add package result: ${ms.value}`);
return ms.value;
}
export async function detectClient(root: string, stopDir = resolve(root, '/')) {
return !!(await findFile(root, 'bun.lockb', stopDir));
}
export async function initProject(projectName: string, target: string) {}
export async function isProject(root: string, packageRef: string) {
const details = await listProjects(root);
if (typeof details === 'object') {
// TODO this won't work right now
return typeof details?.[packageRef]?.location === 'string';
}
return false;
}
// Functions to exclusively use from Bun client:
export async function listProjects(target: string) {
const ms = new MemoryStream();
try {
await runBunProcess(['pm', 'ls', '--all'], target, ms);
log('generalDebug_0003', `Bun workspaces result: ${ms.value}`);
return ms.value
.split('\n')
.filter((m) => m.startsWith('├──'))
.map((m) => m.replace('├── ', ''));
} catch (e) {
log('generalDebug_0003', `Bun workspaces error: ${e}`);
return {};
}
}