@re-shell/cli
Version:
Full-stack development platform uniting microservices and microfrontends. Build complete applications with .NET (ASP.NET Core Web API, Minimal API), Java (Spring Boot, Quarkus, Micronaut, Vert.x), Rust (Actix-Web, Warp, Rocket, Axum), Python (FastAPI, Dja
343 lines (342 loc) โข 15.3 kB
JavaScript
;
var __importDefault = (this && this.__importDefault) || function (mod) {
return (mod && mod.__esModule) ? mod : { "default": mod };
};
Object.defineProperty(exports, "__esModule", { value: true });
exports.manageWorkspaceState = manageWorkspaceState;
const chalk_1 = __importDefault(require("chalk"));
const prompts_1 = __importDefault(require("prompts"));
const workspace_state_1 = require("../utils/workspace-state");
const error_handler_1 = require("../utils/error-handler");
const DEFAULT_WORKSPACE_FILE = 're-shell.workspaces.yaml';
async function manageWorkspaceState(options = {}) {
const { spinner, verbose, json } = options;
try {
if (options.status) {
await showStateStatus(options, spinner);
return;
}
if (options.clear) {
await clearWorkspaceState(options, spinner);
return;
}
if (options.backup) {
await backupWorkspaceState(options, spinner);
return;
}
if (options.restore) {
await restoreWorkspaceState(options, spinner);
return;
}
if (options.cache) {
await manageCacheOperations(options, spinner);
return;
}
if (options.optimize) {
await optimizeWorkspaceStorage(options, spinner);
return;
}
if (options.interactive) {
await interactiveStateManagement(options, spinner);
return;
}
// Default: show state status
await showStateStatus(options, spinner);
}
catch (error) {
if (spinner)
spinner.fail(chalk_1.default.red('Workspace state operation failed'));
throw error;
}
}
async function showStateStatus(options, spinner) {
if (spinner)
spinner.setText('Loading workspace state information...');
try {
const { stateManager, cacheManager } = await (0, workspace_state_1.initializeWorkspaceStorage)();
const stateStats = stateManager.getStateStatistics();
const cacheStats = cacheManager.getCacheStatistics();
if (spinner)
spinner.stop();
if (options.json) {
console.log(JSON.stringify({
state: stateStats,
cache: cacheStats
}, null, 2));
return;
}
console.log(chalk_1.default.cyan('\n๐พ Workspace State & Cache Status'));
console.log(chalk_1.default.gray('โ'.repeat(50)));
// State information
console.log(chalk_1.default.cyan('\n๐ State Information:'));
console.log(` Workspaces tracked: ${chalk_1.default.green(stateStats.workspaceCount)}`);
console.log(` Last modified: ${chalk_1.default.gray(new Date(stateStats.lastModified).toLocaleString())}`);
console.log(` State file size: ${chalk_1.default.yellow(formatBytes(stateStats.stateFileSize))}`);
if (stateStats.oldestWorkspace && stateStats.newestWorkspace) {
console.log(` Oldest workspace: ${chalk_1.default.gray(stateStats.oldestWorkspace)}`);
console.log(` Newest workspace: ${chalk_1.default.gray(stateStats.newestWorkspace)}`);
}
// Cache information
console.log(chalk_1.default.cyan('\n๐๏ธ Cache Information:'));
console.log(` Total entries: ${chalk_1.default.green(cacheStats.totalEntries)}`);
console.log(` Memory entries: ${chalk_1.default.yellow(cacheStats.memoryEntries)}`);
console.log(` Total size: ${chalk_1.default.yellow(formatBytes(cacheStats.totalSize))}`);
console.log(` Hit rate: ${getHitRateColor(cacheStats.hitRate)}${(cacheStats.hitRate * 100).toFixed(1)}%${chalk_1.default.reset()}`);
console.log(` Last optimized: ${chalk_1.default.gray(new Date(cacheStats.lastOptimized).toLocaleString())}`);
// Usage suggestions
console.log(chalk_1.default.cyan('\n๐ ๏ธ Available Commands:'));
console.log(' โข re-shell workspace-state clear');
console.log(' โข re-shell workspace-state backup');
console.log(' โข re-shell workspace-state cache clear');
console.log(' โข re-shell workspace-state optimize');
console.log(' โข re-shell workspace-state interactive');
}
catch (error) {
if (spinner)
spinner.fail(chalk_1.default.red('Failed to load state information'));
throw error;
}
}
async function clearWorkspaceState(options, spinner) {
if (spinner)
spinner.setText('Clearing workspace state...');
try {
const stateManager = await (0, workspace_state_1.createWorkspaceStateManager)();
await stateManager.clearState();
if (spinner)
spinner.stop();
console.log(chalk_1.default.green('โ
Workspace state cleared successfully'));
console.log(chalk_1.default.gray('All workspace tracking data has been reset'));
}
catch (error) {
if (spinner)
spinner.fail(chalk_1.default.red('Failed to clear workspace state'));
throw error;
}
}
async function backupWorkspaceState(options, spinner) {
if (spinner)
spinner.setText('Creating workspace state backup...');
try {
const stateManager = await (0, workspace_state_1.createWorkspaceStateManager)();
const backupPath = await stateManager.backupState(options.output);
if (spinner)
spinner.stop();
console.log(chalk_1.default.green('โ
Workspace state backup created'));
console.log(chalk_1.default.gray(`Backup saved to: ${backupPath}`));
}
catch (error) {
if (spinner)
spinner.fail(chalk_1.default.red('Failed to create state backup'));
throw error;
}
}
async function restoreWorkspaceState(options, spinner) {
if (!options.file) {
throw new error_handler_1.ValidationError('Backup file path is required for restore operation');
}
if (spinner)
spinner.setText(`Restoring workspace state from ${options.file}...`);
try {
const stateManager = await (0, workspace_state_1.createWorkspaceStateManager)();
await stateManager.restoreState(options.file);
if (spinner)
spinner.stop();
console.log(chalk_1.default.green('โ
Workspace state restored successfully'));
console.log(chalk_1.default.gray(`Restored from: ${options.file}`));
}
catch (error) {
if (spinner)
spinner.fail(chalk_1.default.red('Failed to restore workspace state'));
throw error;
}
}
async function manageCacheOperations(options, spinner) {
try {
const cacheManager = await (0, workspace_state_1.createWorkspaceCacheManager)();
if (options.clear) {
if (spinner)
spinner.setText('Clearing workspace cache...');
await cacheManager.clear();
if (spinner)
spinner.stop();
console.log(chalk_1.default.green('โ
Workspace cache cleared successfully'));
return;
}
if (options.pattern) {
if (spinner)
spinner.setText(`Invalidating cache entries matching: ${options.pattern}...`);
const invalidated = await cacheManager.invalidatePattern(options.pattern);
if (spinner)
spinner.stop();
console.log(chalk_1.default.green(`โ
Invalidated ${invalidated} cache entries`));
return;
}
// Default: show cache status
const stats = cacheManager.getCacheStatistics();
if (options.json) {
console.log(JSON.stringify(stats, null, 2));
return;
}
console.log(chalk_1.default.cyan('\n๐๏ธ Cache Statistics'));
console.log(chalk_1.default.gray('โ'.repeat(40)));
console.log(`Total entries: ${chalk_1.default.green(stats.totalEntries)}`);
console.log(`Memory entries: ${chalk_1.default.yellow(stats.memoryEntries)}`);
console.log(`Total size: ${chalk_1.default.yellow(formatBytes(stats.totalSize))}`);
console.log(`Hit rate: ${getHitRateColor(stats.hitRate)}${(stats.hitRate * 100).toFixed(1)}%${chalk_1.default.reset()}`);
console.log(`Miss rate: ${chalk_1.default.red((stats.missRate * 100).toFixed(1))}%`);
}
catch (error) {
if (spinner)
spinner.fail(chalk_1.default.red('Cache operation failed'));
throw error;
}
}
async function optimizeWorkspaceStorage(options, spinner) {
if (spinner)
spinner.setText('Optimizing workspace storage...');
try {
const cacheManager = await (0, workspace_state_1.createWorkspaceCacheManager)();
const result = await cacheManager.optimize();
if (spinner)
spinner.stop();
if (options.json) {
console.log(JSON.stringify(result, null, 2));
return;
}
console.log(chalk_1.default.green('โ
Workspace storage optimized'));
console.log(`Removed entries: ${chalk_1.default.yellow(result.removedEntries)}`);
console.log(`Freed space: ${chalk_1.default.yellow(formatBytes(result.freedSpace))}`);
if (result.removedEntries === 0) {
console.log(chalk_1.default.gray('No expired entries found to remove'));
}
}
catch (error) {
if (spinner)
spinner.fail(chalk_1.default.red('Storage optimization failed'));
throw error;
}
}
async function interactiveStateManagement(options, spinner) {
if (spinner)
spinner.stop();
const response = await (0, prompts_1.default)([
{
type: 'select',
name: 'action',
message: 'What would you like to do?',
choices: [
{ title: '๐ Show state & cache status', value: 'status' },
{ title: '๐๏ธ Clear workspace state', value: 'clear-state' },
{ title: '๐๏ธ Clear cache', value: 'clear-cache' },
{ title: '๐พ Backup state', value: 'backup' },
{ title: '๐ Restore state', value: 'restore' },
{ title: '๐งน Optimize storage', value: 'optimize' },
{ title: '๐ Cache pattern cleanup', value: 'pattern-cleanup' },
{ title: '๐ Detailed statistics', value: 'detailed-stats' }
]
}
]);
if (!response.action)
return;
switch (response.action) {
case 'status':
await showStateStatus({ ...options, interactive: false });
break;
case 'clear-state':
await clearWorkspaceState({ ...options, interactive: false });
break;
case 'clear-cache':
await manageCacheOperations({ ...options, interactive: false, cache: true, clear: true });
break;
case 'backup':
await backupWorkspaceState({ ...options, interactive: false });
break;
case 'restore':
const restoreResponse = await (0, prompts_1.default)({
type: 'text',
name: 'file',
message: 'Enter backup file path:'
});
if (restoreResponse.file) {
await restoreWorkspaceState({ ...options, interactive: false, file: restoreResponse.file });
}
break;
case 'optimize':
await optimizeWorkspaceStorage({ ...options, interactive: false });
break;
case 'pattern-cleanup':
const patternResponse = await (0, prompts_1.default)({
type: 'text',
name: 'pattern',
message: 'Enter pattern to match (regex supported):'
});
if (patternResponse.pattern) {
await manageCacheOperations({
...options,
interactive: false,
cache: true,
pattern: patternResponse.pattern
});
}
break;
case 'detailed-stats':
await showDetailedStatistics(options);
break;
}
}
async function showDetailedStatistics(options) {
try {
const { stateManager, cacheManager } = await (0, workspace_state_1.initializeWorkspaceStorage)();
const stateStats = stateManager.getStateStatistics();
const cacheStats = cacheManager.getCacheStatistics();
console.log(chalk_1.default.cyan('\n๐ Detailed Workspace Storage Statistics'));
console.log(chalk_1.default.gray('โ'.repeat(60)));
// State details
console.log(chalk_1.default.cyan('\n๐พ State Management:'));
console.log(` Workspaces tracked: ${chalk_1.default.green(stateStats.workspaceCount)}`);
console.log(` State file size: ${chalk_1.default.yellow(formatBytes(stateStats.stateFileSize))}`);
console.log(` Last modified: ${chalk_1.default.gray(new Date(stateStats.lastModified).toLocaleString())}`);
// Cache details
console.log(chalk_1.default.cyan('\n๐๏ธ Cache Performance:'));
console.log(` Total entries: ${chalk_1.default.green(cacheStats.totalEntries)}`);
console.log(` Memory entries: ${chalk_1.default.yellow(cacheStats.memoryEntries)}`);
console.log(` Disk entries: ${chalk_1.default.gray(cacheStats.totalEntries - cacheStats.memoryEntries)}`);
console.log(` Total size: ${chalk_1.default.yellow(formatBytes(cacheStats.totalSize))}`);
console.log(` Hit rate: ${getHitRateColor(cacheStats.hitRate)}${(cacheStats.hitRate * 100).toFixed(2)}%${chalk_1.default.reset()}`);
console.log(` Miss rate: ${chalk_1.default.red((cacheStats.missRate * 100).toFixed(2))}%`);
console.log(` Last optimized: ${chalk_1.default.gray(new Date(cacheStats.lastOptimized).toLocaleString())}`);
// Performance recommendations
console.log(chalk_1.default.cyan('\n๐ก Performance Recommendations:'));
if (cacheStats.hitRate < 0.7) {
console.log(chalk_1.default.yellow(' โข Consider increasing cache TTL values'));
}
if (cacheStats.totalSize > 100 * 1024 * 1024) { // 100MB
console.log(chalk_1.default.yellow(' โข Cache is getting large, consider optimization'));
}
if (cacheStats.memoryEntries / Math.max(cacheStats.totalEntries, 1) < 0.1) {
console.log(chalk_1.default.yellow(' โข Low memory cache usage, may need tuning'));
}
console.log(chalk_1.default.green(' โข Regular optimization helps maintain performance'));
}
catch (error) {
console.error(chalk_1.default.red('Failed to load detailed statistics'));
throw error;
}
}
// Utility functions
function formatBytes(bytes) {
if (bytes === 0)
return '0 B';
const units = ['B', 'KB', 'MB', 'GB'];
const k = 1024;
const i = Math.floor(Math.log(bytes) / Math.log(k));
return `${parseFloat((bytes / Math.pow(k, i)).toFixed(1))} ${units[i]}`;
}
function getHitRateColor(rate) {
if (rate >= 0.8)
return chalk_1.default.green;
if (rate >= 0.6)
return chalk_1.default.yellow;
return chalk_1.default.red;
}