intent-cli
Version:
A fully functional CLI built with TypeScript and modern tools
530 lines ⢠22.1 kB
JavaScript
;
var __importDefault = (this && this.__importDefault) || function (mod) {
return (mod && mod.__esModule) ? mod : { "default": mod };
};
Object.defineProperty(exports, "__esModule", { value: true });
exports.sysinfoCommand = void 0;
const commander_1 = require("commander");
const chalk_1 = __importDefault(require("chalk"));
const inquirer_1 = __importDefault(require("inquirer"));
const spinner_1 = require("../utils/spinner");
const logger_1 = require("../utils/logger");
const child_process_1 = require("child_process");
const os_1 = require("os");
exports.sysinfoCommand = new commander_1.Command('sysinfo')
.description('System information and monitoring')
.option('-a, --action <action>', 'Information to display (overview, cpu, memory, disk, network, processes, uptime, watch)')
.option('-i, --interval <number>', 'Update interval in seconds for watch mode', '5')
.option('--interactive', 'Interactive mode', false)
.action(async (options) => {
try {
const result = await executeSysInfoCommand(options);
handleResult(result);
}
catch (error) {
handleError(error);
}
});
async function executeSysInfoCommand(options) {
logger_1.logger.debug('Executing sysinfo command with options:', options);
if (options.interactive || !options.action) {
return await interactiveSysInfoMode();
}
switch (options.action) {
case 'overview':
return await showSystemOverview();
case 'cpu':
return await showCPUInfo();
case 'memory':
return await showMemoryInfo();
case 'disk':
return await showDiskInfo();
case 'network':
return await showNetworkInfo();
case 'processes':
return await showProcessInfo();
case 'uptime':
return await showUptimeInfo();
case 'watch':
return await watchSystemMetrics(parseInt(String(options.interval || '5')));
default:
return {
success: false,
error: new Error(`Unknown action: ${options.action}`)
};
}
}
async function interactiveSysInfoMode() {
console.log(chalk_1.default.cyan.bold('š„ļø System Information Mode'));
console.log(chalk_1.default.dim('Choose system information to display.\n'));
const { action } = await inquirer_1.default.prompt([
{
type: 'list',
name: 'action',
message: 'What would you like to know?',
choices: [
{ name: 'š System Overview', value: 'overview' },
{ name: 'š§ CPU Information', value: 'cpu' },
{ name: 'š¾ Memory Information', value: 'memory' },
{ name: 'šæ Disk Information', value: 'disk' },
{ name: 'š Network Information', value: 'network' },
{ name: 'āļø Process Information', value: 'processes' },
{ name: 'ā° System Uptime', value: 'uptime' },
{ name: 'šļø Watch System Metrics', value: 'watch' },
],
},
]);
const options = {
action,
interactive: true,
};
if (action === 'watch') {
const { interval } = await inquirer_1.default.prompt([
{
type: 'number',
name: 'interval',
message: 'Update interval (seconds):',
default: 5,
validate: (input) => {
if (input < 1) {
return 'Interval must be at least 1 second';
}
return true;
},
},
]);
options.interval = interval;
}
return await executeSysInfoCommand(options);
}
async function showSystemOverview() {
const spinner = (0, spinner_1.createSpinner)();
spinner.start('Gathering system information...');
try {
const systemInfo = await getSystemOverviewData();
spinner.succeed('System information collected');
console.log(chalk_1.default.green.bold('\nš System Overview'));
console.log(chalk_1.default.gray('ā'.repeat(50)));
// System Information
console.log(chalk_1.default.cyan.bold('\nš„ļø System Information:'));
console.log(` Platform: ${chalk_1.default.white(systemInfo.platform)}`);
console.log(` Architecture: ${chalk_1.default.white(systemInfo.architecture)}`);
console.log(` OS Release: ${chalk_1.default.white(systemInfo.osRelease)}`);
console.log(` Hostname: ${chalk_1.default.white(systemInfo.hostname)}`);
// CPU Information
console.log(chalk_1.default.cyan.bold('\nš§ CPU Information:'));
console.log(` Model: ${chalk_1.default.white(systemInfo.cpu.model)}`);
console.log(` Cores: ${chalk_1.default.white(systemInfo.cpu.cores)}`);
console.log(` Speed: ${chalk_1.default.white(systemInfo.cpu.speed)} GHz`);
// Memory Information
console.log(chalk_1.default.cyan.bold('\nš¾ Memory Information:'));
const memUsagePercent = ((systemInfo.memory.used / systemInfo.memory.total) * 100).toFixed(1);
const memBar = createProgressBar(memUsagePercent, 20);
console.log(` Total: ${chalk_1.default.white(formatBytes(systemInfo.memory.total))}`);
console.log(` Used: ${chalk_1.default.yellow(formatBytes(systemInfo.memory.used))}`);
console.log(` Free: ${chalk_1.default.green(formatBytes(systemInfo.memory.free))}`);
console.log(` Usage: ${memBar} ${memUsagePercent}%`);
// Uptime
console.log(chalk_1.default.cyan.bold('\nā° System Uptime:'));
console.log(` Uptime: ${chalk_1.default.white(systemInfo.uptime.display)}`);
// Load Average (Unix-like systems only)
if (systemInfo.loadAverage) {
console.log(chalk_1.default.cyan.bold('\nš Load Average:'));
console.log(` 1 min: ${chalk_1.default.yellow(systemInfo.loadAverage[0].toFixed(2))}`);
console.log(` 5 min: ${chalk_1.default.yellow(systemInfo.loadAverage[1].toFixed(2))}`);
console.log(` 15 min: ${chalk_1.default.yellow(systemInfo.loadAverage[2].toFixed(2))}`);
}
return {
success: true,
message: 'System overview displayed',
data: systemInfo,
};
}
catch (error) {
spinner.fail('Failed to get system information');
throw error;
}
}
async function showCPUInfo() {
const spinner = (0, spinner_1.createSpinner)();
spinner.start('Getting CPU information...');
try {
const cpuData = (0, os_1.cpus)()[0];
spinner.succeed('CPU information collected');
console.log(chalk_1.default.green.bold('\nš§ CPU Information'));
console.log(chalk_1.default.gray('ā'.repeat(50)));
console.log(`Model: ${chalk_1.default.white(cpuData.model)}`);
console.log(`Speed: ${chalk_1.default.white(cpuData.speed)} MHz`);
console.log(`Cores: ${chalk_1.default.white((0, os_1.cpus)().length)}`);
console.log(chalk_1.default.cyan.bold('\nā” Current CPU Usage:'));
// Note: Real CPU usage calculation would require more complex monitoring
console.log(chalk_1.default.yellow(' (Real-time CPU usage monitoring requires additional libraries)'));
return {
success: true,
message: 'CPU information displayed',
data: { model: cpuData.model, speed: cpuData.speed, cores: (0, os_1.cpus)().length },
};
}
catch (error) {
spinner.fail('Failed to get CPU information');
throw error;
}
}
async function showMemoryInfo() {
const spinner = (0, spinner_1.createSpinner)();
spinner.start('Getting memory information...');
try {
const total = (0, os_1.totalmem)();
const free = (0, os_1.freemem)();
const used = total - free;
spinner.succeed('Memory information collected');
console.log(chalk_1.default.green.bold('\nš¾ Memory Information'));
console.log(chalk_1.default.gray('ā'.repeat(50)));
const usagePercent = ((used / total) * 100).toFixed(1);
const bar = createProgressBar(usagePercent, 30);
console.log(`Total Memory: ${chalk_1.default.white(formatBytes(total))}`);
console.log(`Used Memory: ${chalk_1.default.yellow(formatBytes(used))} (${usagePercent}%)`);
console.log(`Free Memory: ${chalk_1.default.green(formatBytes(free))}`);
console.log(`Usage Bar: ${bar}`);
// Additional memory details
console.log(chalk_1.default.cyan.bold('\nš Memory Details:'));
console.log(` Used: ${((used / total) * 100).toFixed(2)}%`);
console.log(` Free: ${((free / total) * 100).toFixed(2)}%`);
return {
success: true,
message: 'Memory information displayed',
data: { total, used, free, usagePercent: parseFloat(usagePercent) },
};
}
catch (error) {
spinner.fail('Failed to get memory information');
throw error;
}
}
async function showDiskInfo() {
const spinner = (0, spinner_1.createSpinner)();
spinner.start('Getting disk information...');
try {
let diskInfo;
if ((0, os_1.platform)() === 'darwin') {
// macOS
const output = (0, child_process_1.execSync)('df -h').toString();
diskInfo = parseDiskUsage(output);
}
else if ((0, os_1.platform)() === 'linux') {
// Linux
const output = (0, child_process_1.execSync)('df -h').toString();
diskInfo = parseDiskUsage(output);
}
else {
// Windows - simplified
diskInfo = [{ filesystem: 'C:', size: 'N/A', used: 'N/A', available: 'N/A', usage: 'N/A' }];
}
spinner.succeed('Disk information collected');
console.log(chalk_1.default.green.bold('\nšæ Disk Information'));
console.log(chalk_1.default.gray('ā'.repeat(70)));
console.log(chalk_1.default.cyan('Filesystem'.padEnd(20)) +
chalk_1.default.cyan('Size'.padEnd(12)) +
chalk_1.default.cyan('Used'.padEnd(12)) +
chalk_1.default.cyan('Available'.padEnd(12)) +
chalk_1.default.cyan('Usage'));
console.log(chalk_1.default.gray('ā'.repeat(70)));
diskInfo.forEach(disk => {
const usageColor = disk.usage !== 'N/A' && parseInt(disk.usage) > 80 ? chalk_1.default.red : chalk_1.default.yellow;
console.log(chalk_1.default.white(disk.filesystem.padEnd(20)) +
chalk_1.default.white(disk.size.padEnd(12)) +
chalk_1.default.yellow(disk.used.padEnd(12)) +
chalk_1.default.green(disk.available.padEnd(12)) +
usageColor(disk.usage));
});
return {
success: true,
message: 'Disk information displayed',
data: diskInfo,
};
}
catch (error) {
spinner.fail('Failed to get disk information');
throw error;
}
}
async function showNetworkInfo() {
const spinner = (0, spinner_1.createSpinner)();
spinner.start('Getting network information...');
try {
let networkInfo;
if ((0, os_1.platform)() === 'darwin') {
const output = (0, child_process_1.execSync)('ifconfig').toString();
networkInfo = parseNetworkInfo(output);
}
else if ((0, os_1.platform)() === 'linux') {
const output = (0, child_process_1.execSync)('ip addr show').toString();
networkInfo = parseNetworkInfo(output);
}
else {
networkInfo = [{ interface: 'N/A', ip: 'N/A', status: 'N/A' }];
}
spinner.succeed('Network information collected');
console.log(chalk_1.default.green.bold('\nš Network Information'));
console.log(chalk_1.default.gray('ā'.repeat(60)));
networkInfo.forEach(net => {
console.log(`${chalk_1.default.cyan('Interface:')} ${chalk_1.default.white(net.interface)}`);
console.log(`${chalk_1.default.cyan('IP Address:')} ${chalk_1.default.green(net.ip)}`);
console.log(`${chalk_1.default.cyan('Status:')} ${net.status === 'active' ? chalk_1.default.green('Active') : chalk_1.default.red('Inactive')}`);
console.log(chalk_1.default.gray('ā'.repeat(30)));
});
return {
success: true,
message: 'Network information displayed',
data: networkInfo,
};
}
catch (error) {
spinner.fail('Failed to get network information');
throw error;
}
}
async function showProcessInfo() {
const spinner = (0, spinner_1.createSpinner)();
spinner.start('Getting process information...');
try {
let processInfo;
if ((0, os_1.platform)() === 'darwin' || (0, os_1.platform)() === 'linux') {
const output = (0, child_process_1.execSync)('ps aux').toString();
processInfo = parseProcessInfo(output);
}
else {
processInfo = [{ pid: 'N/A', name: 'N/A', cpu: 'N/A', memory: 'N/A' }];
}
spinner.succeed('Process information collected');
console.log(chalk_1.default.green.bold('\nāļø Top Processes'));
console.log(chalk_1.default.gray('ā'.repeat(80)));
console.log(chalk_1.default.cyan('PID'.padEnd(10)) +
chalk_1.default.cyan('Process Name'.padEnd(30)) +
chalk_1.default.cyan('CPU%'.padEnd(10)) +
chalk_1.default.cyan('Memory%'));
console.log(chalk_1.default.gray('ā'.repeat(80)));
processInfo.slice(0, 10).forEach(process => {
console.log(chalk_1.default.white(process.pid.padEnd(10)) +
chalk_1.default.white(process.name.padEnd(30)) +
chalk_1.default.yellow(process.cpu.padEnd(10)) +
chalk_1.default.magenta(process.memory));
});
return {
success: true,
message: 'Process information displayed',
data: processInfo,
};
}
catch (error) {
spinner.fail('Failed to get process information');
throw error;
}
}
async function showUptimeInfo() {
const spinner = (0, spinner_1.createSpinner)();
spinner.start('Getting uptime information...');
try {
const uptimeSeconds = (0, os_1.uptime)();
const uptimeFormatted = formatUptime(uptimeSeconds);
spinner.succeed('Uptime information collected');
console.log(chalk_1.default.green.bold('\nā° System Uptime'));
console.log(chalk_1.default.gray('ā'.repeat(40)));
console.log(`Uptime: ${chalk_1.default.white(uptimeFormatted)}`);
console.log(`Total seconds: ${chalk_1.default.white(Math.floor(uptimeSeconds))}`);
// Boot time
const bootTime = new Date(Date.now() - uptimeSeconds * 1000);
console.log(`Boot time: ${chalk_1.default.white(bootTime.toLocaleString())}`);
return {
success: true,
message: 'Uptime information displayed',
data: { uptime: uptimeSeconds, bootTime, formatted: uptimeFormatted },
};
}
catch (error) {
spinner.fail('Failed to get uptime information');
throw error;
}
}
async function watchSystemMetrics(interval) {
console.log(chalk_1.default.green.bold(`\nšļø Watching System Metrics (Updating every ${interval}s)`));
console.log(chalk_1.default.gray('Press Ctrl+C to stop\n'));
const watchInterval = setInterval(async () => {
try {
// Clear screen
console.clear();
const systemInfo = await getSystemOverviewData();
console.log(chalk_1.default.green.bold('š„ļø System Metrics Watch'));
console.log(chalk_1.default.gray(`Last updated: ${new Date().toLocaleString()}`));
console.log(chalk_1.default.gray('ā'.repeat(50)));
// Memory with real-time bar
const memUsagePercent = ((systemInfo.memory.used / systemInfo.memory.total) * 100).toFixed(1);
const memBar = createProgressBar(memUsagePercent, 30);
console.log(`š¾ Memory: ${memBar} ${memUsagePercent}%`);
// Load average (Unix systems)
if (systemInfo.loadAverage) {
const load1 = systemInfo.loadAverage[0];
const load5 = systemInfo.loadAverage[1];
const load15 = systemInfo.loadAverage[2];
const loadColor = load1 > systemInfo.cpu.cores ? chalk_1.default.red : chalk_1.default.yellow;
console.log(`š Load: ${loadColor(`${load1.toFixed(2)}, ${load5.toFixed(2)}, ${load15.toFixed(2)}`)}`);
}
// Uptime
console.log(`ā° Uptime: ${chalk_1.default.white(systemInfo.uptime.display)}`);
console.log(chalk_1.default.gray('\nPress Ctrl+C to exit'));
}
catch (error) {
console.error(chalk_1.default.red('Error updating metrics:'), error);
}
}, interval * 1000);
// Handle Ctrl+C
process.on('SIGINT', () => {
clearInterval(watchInterval);
console.log(chalk_1.default.yellow('\n\nStopped watching system metrics'));
process.exit(0);
});
return {
success: true,
message: `Watching system metrics every ${interval} seconds`,
data: { interval, watching: true },
};
}
// Helper functions
async function getSystemOverviewData() {
const cpuInfo = (0, os_1.cpus)()[0];
const total = (0, os_1.totalmem)();
const free = (0, os_1.freemem)();
const uptimeSeconds = (0, os_1.uptime)();
return {
platform: (0, os_1.platform)(),
architecture: (0, os_1.arch)(),
osRelease: (0, os_1.release)(),
hostname: require('os').hostname(),
cpu: {
model: cpuInfo.model,
cores: (0, os_1.cpus)().length,
speed: (cpuInfo.speed / 1000).toFixed(2), // Convert to GHz
},
memory: {
total,
used: total - free,
free,
},
uptime: {
seconds: uptimeSeconds,
display: formatUptime(uptimeSeconds),
},
loadAverage: (0, os_1.platform)() !== 'win32' ? (0, os_1.loadavg)() : null,
};
}
function formatBytes(bytes) {
const sizes = ['Bytes', 'KB', 'MB', 'GB', 'TB'];
if (bytes === 0)
return '0 Bytes';
const i = Math.floor(Math.log(bytes) / Math.log(1024));
return Math.round(bytes / Math.pow(1024, i) * 100) / 100 + ' ' + sizes[i];
}
function formatUptime(seconds) {
const days = Math.floor(seconds / 86400);
const hours = Math.floor((seconds % 86400) / 3600);
const minutes = Math.floor((seconds % 3600) / 60);
const secs = Math.floor(seconds % 60);
const parts = [];
if (days > 0)
parts.push(`${days}d`);
if (hours > 0)
parts.push(`${hours}h`);
if (minutes > 0)
parts.push(`${minutes}m`);
if (secs > 0 || parts.length === 0)
parts.push(`${secs}s`);
return parts.join(' ');
}
function createProgressBar(percentage, width) {
const percent = parseFloat(percentage);
const filled = Math.round((percent / 100) * width);
const empty = width - filled;
const filledBar = 'ā'.repeat(filled);
const emptyBar = 'ā'.repeat(empty);
const color = percent > 80 ? chalk_1.default.red : percent > 60 ? chalk_1.default.yellow : chalk_1.default.green;
return color(filledBar) + chalk_1.default.gray(emptyBar);
}
function parseDiskUsage(output) {
const lines = output.split('\n').slice(1);
return lines
.filter(line => line.trim())
.map(line => {
const parts = line.trim().split(/\s+/);
return {
filesystem: parts[0],
size: parts[1],
used: parts[2],
available: parts[3],
usage: parts[4],
};
});
}
function parseNetworkInfo(output) {
// Simplified network info parsing
const interfaces = [];
const lines = output.split('\n');
let currentInterface = '';
let hasIP = false;
for (const line of lines) {
if (line.match(/^[a-zA-Z0-9]+:/) || line.match(/^[a-zA-Z0-9]+ /)) {
if (currentInterface && hasIP) {
interfaces.push({
interface: currentInterface,
ip: 'Found',
status: 'active'
});
}
currentInterface = line.split(':')[0] || line.split(' ')[0];
hasIP = false;
}
if (line.includes('inet ')) {
hasIP = true;
}
}
if (interfaces.length === 0) {
interfaces.push({ interface: 'lo0', ip: '127.0.0.1', status: 'active' });
}
return interfaces;
}
function parseProcessInfo(output) {
const lines = output.split('\n').slice(1);
return lines
.filter(line => line.trim())
.slice(0, 10) // Top 10 processes
.map(line => {
const parts = line.trim().split(/\s+/);
return {
pid: parts[1] || 'N/A',
name: parts.slice(10).join(' ') || 'N/A',
cpu: parts[2] || 'N/A',
memory: parts[3] || 'N/A',
};
});
}
function handleResult(result) {
if (result.success) {
logger_1.logger.info('SysInfo command executed successfully');
if (result.message) {
logger_1.logger.debug(`Result: ${result.message}`);
}
}
else {
handleError(result.error);
}
}
function handleError(error) {
logger_1.logger.error('SysInfo command failed:', error);
if (error instanceof Error) {
console.error(chalk_1.default.red('Error:'), error.message);
}
else {
console.error(chalk_1.default.red('An unknown error occurred'));
}
process.exit(1);
}
//# sourceMappingURL=sysinfo.js.map