Files

121 lines
5.3 KiB
JavaScript
Raw Permalink Normal View History

2026-11-12 14:03:53 +01:00
// Release archive: packs a build folder (dist, builds, release, publish …) or the
// whole project as a ZIP into <project>\releases\, so a version is kept even
// after the build folder was cleaned up. Uses tar.exe (bsdtar, part of
// Windows 10/11), which writes real ZIP files with -a and an .zip name.
const fs = require('fs')
const path = require('path')
const { run } = require('./proc')
const settings = require('./settings')
const ARCHIVE_DIR = 'releases'
const RELEASE_NAMES = /^(dist|builds?|release|releases?|publish|out)$/i
const SKIP_WALK = /^(node_modules|\.git|\.gradle|library|temp|logs|obj|__pycache__|\.venv.*|venv)$/i
// left out of a whole-project archive (on top of the backup excludes)
const PROJECT_SKIP = ['.git', ARCHIVE_DIR, 'dist', 'build', 'builds', 'out', 'bin', 'obj', 'Library', 'Temp', 'Logs', '.gradle', '.next', 'coverage', '.cache']
function dirInfo(dir, limit = 20000) {
let bytes = 0, files = 0
const stack = [dir]
while (stack.length && files < limit) {
const cur = stack.pop()
let entries
try { entries = fs.readdirSync(cur, { withFileTypes: true }) } catch { continue }
for (const e of entries) {
const full = path.join(cur, e.name)
if (e.isDirectory()) stack.push(full)
else if (e.isFile()) { files++; try { bytes += fs.statSync(full).size } catch {} }
}
}
return { bytes, files }
}
// Build folders worth archiving (two levels deep, with files in them).
// -> [{ rel, mb, files }]
function findReleaseDirs(projectPath) {
const out = []
const walk = (dir, depth) => {
let entries
try { entries = fs.readdirSync(dir, { withFileTypes: true }) } catch { return }
for (const e of entries) {
if (!e.isDirectory() || e.name.startsWith('.')) continue
const full = path.join(dir, e.name)
const rel = path.relative(projectPath, full)
if (e.name.toLowerCase() === ARCHIVE_DIR && depth === 0) continue
// bin\Release of .NET projects
const isBinRelease = /^release$/i.test(e.name) && /^bin$/i.test(path.basename(dir))
if (RELEASE_NAMES.test(e.name) || isBinRelease) {
const info = dirInfo(full)
if (info.files) out.push({ rel, mb: Math.round((info.bytes / 1048576) * 10) / 10, files: info.files })
continue
}
if (depth < 2 && !SKIP_WALK.test(e.name)) walk(full, depth + 1)
}
}
walk(projectPath, 0)
return out.sort((a, b) => b.mb - a.mb).slice(0, 12)
}
// Existing archives in <project>\releases (newest first).
function listArchives(projectPath) {
const dir = path.join(projectPath, ARCHIVE_DIR)
let entries = []
try { entries = fs.readdirSync(dir, { withFileTypes: true }) } catch { return [] }
return entries.filter((e) => e.isFile() && /\.zip$/i.test(e.name)).map((e) => {
const st = fs.statSync(path.join(dir, e.name))
return { name: e.name, mb: Math.round((st.size / 1048576) * 10) / 10, at: st.mtime.toISOString() }
}).sort((a, b) => (a.at < b.at ? 1 : -1))
}
const stamp = () => {
const d = new Date()
const p = (n) => String(n).padStart(2, '0')
return `${d.getFullYear()}-${p(d.getMonth() + 1)}-${p(d.getDate())}_${p(d.getHours())}${p(d.getMinutes())}`
}
const safe = (s) => s.replace(/[\\/:*?"<>|\s]+/g, '-').replace(/-+/g, '-').replace(/^-|-$/g, '')
let running = false
// what: a relative folder from findReleaseDirs, or 'project'. -> { name, mb, path }
async function zip(projectPath, what) {
if (running) throw new Error('Es wird gerade schon ein Archiv erstellt.')
const project = path.basename(projectPath)
let base, items, excludes = []
if (what === 'project') {
base = projectPath
items = ['.']
const b = settings.get().backup
excludes = [...new Set([...b.excludeDirs, ...PROJECT_SKIP])].map((x) => `--exclude=${x}`)
excludes.push(...b.excludeFiles.map((x) => `--exclude=${x}`))
} else {
const src = path.resolve(projectPath, String(what ?? ''))
if (!src.startsWith(projectPath + path.sep) || !fs.existsSync(src) || !fs.statSync(src).isDirectory()) throw new Error('Ordner nicht gefunden.')
// the folder itself goes into the zip (unpacks as "dist\...")
base = path.dirname(src)
items = [path.basename(src)]
}
const outDir = path.join(projectPath, ARCHIVE_DIR)
fs.mkdirSync(outDir, { recursive: true })
const label = what === 'project' ? 'projekt' : safe(String(what))
let out = path.join(outDir, `${safe(project)}_${label}_${stamp()}.zip`)
for (let i = 2; fs.existsSync(out); i++) out = out.replace(/(_\d+)?\.zip$/i, `_${i}.zip`)
running = true
try {
// tar.exe of Windows (System32) - not a tar from Git or MSYS, which can't write ZIP
const tar = path.join(process.env.SystemRoot || 'C:\\Windows', 'System32', 'tar.exe')
if (!fs.existsSync(tar)) throw new Error('tar.exe fehlt (gehört zu Windows 10/11).')
const r = await run(tar, ['-a', '-c', '-f', out, ...excludes, '-C', base, ...items], { timeout: 60 * 60 * 1000 })
if (!r.ok) {
try { fs.unlinkSync(out) } catch {}
throw new Error(`ZIP fehlgeschlagen: ${(r.stderr || r.stdout).trim().split(/\r?\n/).slice(-2).join(' ') || `Code ${r.code}`}`)
}
const st = fs.statSync(out)
return { name: path.basename(out), mb: Math.round((st.size / 1048576) * 10) / 10, path: out }
} finally {
running = false
}
}
const busy = () => running
module.exports = { findReleaseDirs, listArchives, zip, busy, ARCHIVE_DIR }