Files
ProjectDashboard/lib/storage.js

136 lines
5.6 KiB
JavaScript
Raw Normal View History

2026-11-12 09:32:23 +01:00
// Disk usage and cleanup. Sizes are slow to measure, so scans run in the
// background and land in <DATA>\scan.json (per projects folder - several can
// be shown at once, see lib/settings.js). Which folders may be deleted is
// decided only by cleanup.ps1 (same safety rules as on the CLI): the one in
// <Projekte>\_Tools\Cleanup if it exists, else the copy shipped in tools\.
// A project is addressed by its projects folder (root) and folder name.
const fs = require('fs')
const path = require('path')
const { run, pool } = require('./proc')
const { DATA_DIR, APP_DIR } = require('./settings')
const CACHE_FILE = path.join(DATA_DIR, 'scan.json')
const ALL_TIERS = 'Cache,Release,Output'
let roots = [] // selected projects folders (paths)
let all = {} // root (lower case) -> { folder -> { at, sizeMB, candidates: [{Tier, MB, Skip, Path}], deletable: {Cache, Release, Output} } }
const state = { running: false, current: [], done: 0, total: 0, error: null }
const rootKey = (r) => (r ?? '').toLowerCase()
const shipped = path.join(APP_DIR, 'tools', 'cleanup.ps1')
const own = (root) => (root ? path.join(root, '_Tools', 'Cleanup', 'cleanup.ps1') : '')
function readAll(first) {
try {
const saved = JSON.parse(fs.readFileSync(CACHE_FILE, 'utf-8'))
if (saved?.roots && typeof saved.roots === 'object') return saved.roots
// older formats: { root, projects } or the bare projects map of one folder
if (saved?.projects && typeof saved.root === 'string') return { [rootKey(saved.root)]: saved.projects }
if (saved && first) return { [rootKey(first)]: saved }
} catch {}
return {}
}
let known = [] // all registered projects folders (their _Tools\Cleanup can stand in)
// rootList: paths of the selected projects folders; registered: all of them
function init(rootList, registered = []) {
roots = (Array.isArray(rootList) ? rootList : [rootList]).filter(Boolean)
known = registered.filter(Boolean)
all = readAll(roots[0])
}
function save() {
fs.mkdirSync(DATA_DIR, { recursive: true })
fs.writeFileSync(CACHE_FILE, JSON.stringify({ roots: all }, null, 1))
}
function busy() { return state.running }
// cleanup.ps1 for a folder: its own, else one of another registered folder, else the shipped copy
function scriptFor(root) {
for (const s of [own(root), ...roots.map(own), ...known.map(own), shipped]) if (s && fs.existsSync(s)) return s
return null
}
function available() { return !!scriptFor(roots[0]) }
function psArgs(root, extra) {
return ['-NoProfile', '-ExecutionPolicy', 'Bypass', '-File', scriptFor(root), '-Root', root, ...extra, '-Json']
}
function parseJson(stdout) {
const text = stdout.trim()
const start = text.search(/[[{]/)
if (start < 0) throw new Error('cleanup.ps1 gave no JSON')
return JSON.parse(text.slice(start))
}
async function dirSizeMB(dir) {
// robocopy /L only lists; fast and copes with long node_modules paths
const r = await run('robocopy', [dir, 'C:\\__nul__', '/L', '/S', '/NJH', '/BYTES', '/FP', '/NC', '/NDL', '/NFL', '/XJ', '/R:0', '/W:0'], { timeout: 10 * 60 * 1000 })
const line = r.stdout.split(/\r?\n/).find((l) => /^\s*Bytes\s*:/.test(l))
const m = line && line.match(/:\s*(\d+)/)
return m ? Math.round(+m[1] / 1048576) : null
}
async function scanProject(root, folder) {
const dir = path.join(root, folder)
const [sizeMB, cand] = await Promise.all([
dirSizeMB(dir),
scriptFor(root) ? run('powershell.exe', psArgs(root, ['-Project', folder, '-Tier', ALL_TIERS]), { timeout: 10 * 60 * 1000 }) : null,
])
const candidates = cand ? parseJson(cand.stdout) : []
const deletable = { Cache: 0, Release: 0, Output: 0 }
for (const c of candidates) if (!c.Skip) deletable[c.Tier] += c.MB
const d = (all[rootKey(root)] ??= {})
d[folder] = { at: new Date().toISOString(), sizeMB, candidates, deletable }
save()
return d[folder]
}
// Starts a background scan; returns immediately. items: [{ root, folder, key }]
function startScan(items) {
if (state.running) return false
Object.assign(state, { running: true, current: [], done: 0, total: items.length, error: null })
pool(items, 3, async (it) => {
const label = it.key ?? it.folder
state.current.push(label)
try { await scanProject(it.root, it.folder) } catch (e) { state.error = `${label}: ${e.message}` }
state.current = state.current.filter((n) => n !== label)
state.done++
}).finally(() => { state.running = false })
return true
}
// Deletes only the given paths (relative to the projects folder, as listed by
// the scan), then rescans the project. cleanup.ps1 checks every path again.
async function clean(root, folder, paths) {
const prefix = folder + path.sep
const only = paths.filter((p) => typeof p === 'string' && p.startsWith(prefix) && !p.includes('|'))
if (!only.length) throw new Error('nichts ausgewählt')
if (!scriptFor(root)) throw new Error('cleanup.ps1 nicht gefunden')
const r = await run('powershell.exe', psArgs(root, ['-Project', folder, '-Tier', ALL_TIERS, '-Only', only.join('|'), '-Apply']), { timeout: 30 * 60 * 1000 })
const result = parseJson(r.stdout)
await scanProject(root, folder)
return result
}
function get(root, folder) { return all[rootKey(root)]?.[folder] ?? null }
// items: [{ root, folder }]
function totals(items) {
let sizeMB = 0, cacheMB = 0, allMB = 0, scanned = 0
for (const it of items) {
const d = get(it.root, it.folder)
if (!d) continue
scanned++
sizeMB += d.sizeMB ?? 0
cacheMB += d.deletable.Cache
allMB += d.deletable.Cache + d.deletable.Release + d.deletable.Output
}
return { sizeMB, cacheMB, allMB, scanned }
}
module.exports = { init, startScan, clean, get, totals, state, available, busy }