'use strict'; const fs = require('node:fs'); const path = require('node:path'); const { ROOT, runCommand, runCommandSafe, isGitAvailable } = require('./deploy-lib.cjs'); const VERSION_DIR = path.join(ROOT, 'versioning'); const VERSION_HISTORY_FILE = path.join(VERSION_DIR, 'package-version-history.jsonl'); const VERSION_CURRENT_FILE = path.join(VERSION_DIR, 'package-version-current.json'); function ensureVersionDir() { fs.mkdirSync(VERSION_DIR, { recursive: true }); } function getPackageMeta() { const pkg = JSON.parse(fs.readFileSync(path.join(ROOT, 'package.json'), 'utf8')); const packageVersion = String(pkg.version || '0.0.0'); let gitCommit = ''; let gitCommitShort = ''; let gitBranch = ''; if (isGitAvailable()) { try { gitCommit = runCommand('git', [ 'rev-parse', 'HEAD' ]); gitCommitShort = runCommand('git', [ 'rev-parse', '--short', 'HEAD' ]); gitBranch = runCommand('git', [ 'rev-parse', '--abbrev-ref', 'HEAD' ]); } catch (error) { gitCommit = ''; gitCommitShort = ''; gitBranch = ''; } } return { packageVersion, gitCommit, gitCommitShort, gitBranch, }; } function recordVersionUpdate(options = {}) { ensureVersionDir(); const meta = getPackageMeta(); const entry = { recordedAt: new Date().toISOString(), source: options.source || 'manual', note: options.note || '', packageVersion: meta.packageVersion, gitCommit: meta.gitCommit, gitCommitShort: meta.gitCommitShort, gitBranch: meta.gitBranch, releaseVersion: options.releaseVersion || '', deployRoot: options.deployRoot || '', remoteBackupFile: options.remoteBackupFile || '', remoteStateFile: options.remoteStateFile || '', remoteHistoryFile: options.remoteHistoryFile || '', }; fs.appendFileSync(VERSION_HISTORY_FILE, `${JSON.stringify(entry)}\n`, 'utf8'); fs.writeFileSync(VERSION_CURRENT_FILE, `${JSON.stringify(entry, null, 2)}\n`, 'utf8'); return entry; } function readVersionHistory(limit = 20) { if (!fs.existsSync(VERSION_HISTORY_FILE)) { return []; } const lines = fs.readFileSync(VERSION_HISTORY_FILE, 'utf8') .split(/\r?\n/) .map(item => item.trim()) .filter(Boolean); const take = Math.max(1, Number(limit || 20)); const selected = lines.slice(-take); const records = []; for (const line of selected) { try { records.push(JSON.parse(line)); } catch (error) { records.push({ raw: line }); } } return records; } module.exports = { VERSION_CURRENT_FILE, VERSION_DIR, VERSION_HISTORY_FILE, readVersionHistory, recordVersionUpdate, };