@contentstack/cli-utilities
Version:
Utilities for contentstack projects
97 lines (96 loc) • 4.29 kB
JavaScript
;
Object.defineProperty(exports, "__esModule", { value: true });
exports.getSessionLogPath = void 0;
const tslib_1 = require("tslib");
const fs = tslib_1.__importStar(require("fs"));
const os = tslib_1.__importStar(require("os"));
const path = tslib_1.__importStar(require("path"));
const __1 = require("..");
const log_1 = require("./log");
/**
* Extract module name from command ID
* Example: "cm:stacks:audit" -> "audit"
*/
function extractModule(commandId) {
if (!commandId || commandId === 'unknown') {
return '';
}
// Split by colon and get the last part
const parts = commandId.split(':');
return parts[parts.length - 1] || '';
}
/**
* Generate session metadata object for session.json
* Uses createLogContext() to get base context, then adds session-specific metadata
*/
function generateSessionMetadata(commandId, sessionId, startTimestamp) {
const originalCommandId = __1.configHandler.get('currentCommandId') || commandId;
const module = extractModule(originalCommandId);
const apiKey = __1.configHandler.get('apiKey') || '';
const baseContext = (0, __1.createLogContext)(originalCommandId, apiKey);
return Object.assign(Object.assign({}, baseContext), { module: module, sessionId: sessionId, startTimestamp: startTimestamp.toISOString(), MachineEnvironment: {
nodeVersion: process.version,
os: os.platform(),
hostname: os.hostname(),
CLI_VERSION: __1.configHandler.get('CLI_VERSION') || '',
} });
}
/**
* Create session.json metadata file in the session directory
*/
function createSessionMetadataFile(sessionPath, metadata) {
const metadataPath = path.join(sessionPath, 'session.json');
try {
fs.writeFileSync(metadataPath, JSON.stringify(metadata, null, 2), 'utf8');
}
catch (error) {
// Silently fail if metadata file cannot be created
// Logging here would cause circular dependency
// The session folder and logs will still be created
}
}
/**
* Get the session-based log path for date-organized logging
* Structure: {basePath}/{YYYY-MM-DD}/{command}-{YYYYMMDD-HHMMSS}-{sessionId}/
*
* @returns The session-specific log directory path
*/
function getSessionLogPath() {
// Get base log path
const basePath = (0, log_1.getLogPath)();
// Get current date in YYYY-MM-DD format
const now = new Date();
const dateStr = now.toISOString().split('T')[0]; // YYYY-MM-DD
// Get command ID (fallback to 'unknown' if not set)
let commandId = __1.configHandler.get('currentCommandId') || 'unknown';
// Sanitize command ID - remove colons and replace with hyphens for folder name
commandId = commandId === null || commandId === void 0 ? void 0 : commandId.replace(/:/g, '-');
// Use helper methods to format date and time
const dateStrFormatted = (0, __1.formatDate)(now); // YYYYMMDD
const timeStrFormatted = (0, __1.formatTime)(now); // HHMMSS
const timestamp = `${dateStrFormatted}-${timeStrFormatted}`; // YYYYMMDD-HHMMSS
let sessionId = __1.configHandler.get('sessionId');
if (!sessionId) {
// Format: first 8 chars of command + timestamp (YYYYMMDDHHMMSS)
const timestampForId = `${dateStrFormatted}${timeStrFormatted}`; // YYYYMMDDHHMMSS
const commandHash = commandId.substring(0, 8).padEnd(8, '0'); // Use first 8 chars of command
sessionId = `${commandHash}-${timestampForId}`;
}
// Create session folder name: command-YYYYMMDD-HHMMSS-sessionId
const sessionFolderName = `${commandId}-${timestamp}-${sessionId}`;
// Build full session path
const sessionPath = path.join(basePath, dateStr, sessionFolderName);
// Ensure directory exists
const isNewSession = !fs.existsSync(sessionPath);
if (isNewSession) {
fs.mkdirSync(sessionPath, { recursive: true });
}
// Create session.json metadata file for new sessions
// This ensures metadata is created before any logs are written
if (isNewSession) {
const metadata = generateSessionMetadata(__1.configHandler.get('currentCommandId') || commandId, sessionId, now);
createSessionMetadataFile(sessionPath, metadata);
}
return sessionPath;
}
exports.getSessionLogPath = getSessionLogPath;