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
|
|
|
|
|
}
|
|
|
|
|
|
2026-11-12 14:03:53 +01:00
|
|
|
// sizes can always be measured; cleanup candidates need cleanup.ps1
|
|
|
|
|
function available() { return true }
|
|
|
|
|
const cleanupAvailable = () => !!scriptFor(roots[0])
|
2026-11-12 09:32:23 +01:00
|
|
|
|
2026-11-12 20:23:53 +01:00
|
|
|
// effRoot: the folder cleanup.ps1 treats as its root - for a project in a subfolder
|
|
|
|
|
// ("Sammel\A") its parent folder, because the script only knows direct children
|
|
|
|
|
function psArgs(root, extra, effRoot = root) {
|
|
|
|
|
return ['-NoProfile', '-ExecutionPolicy', 'Bypass', '-File', scriptFor(root), '-Root', effRoot, ...extra, '-Json']
|
|
|
|
|
}
|
|
|
|
|
// { effRoot, project, prefix } for cleanup.ps1; prefix turns its paths into "<folder>\..."
|
|
|
|
|
function scriptTarget(root, folder) {
|
|
|
|
|
const parent = path.dirname(folder)
|
|
|
|
|
if (parent === '.' || !parent) return { effRoot: root, project: folder, prefix: '' }
|
|
|
|
|
return { effRoot: path.join(root, parent), project: path.basename(folder), prefix: parent + path.sep }
|
2026-11-12 09:32:23 +01:00
|
|
|
}
|
|
|
|
|
|
|
|
|
|
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))
|
|
|
|
|
}
|
|
|
|
|
|
2026-11-12 14:03:53 +01:00
|
|
|
async function dirBytes(dir) {
|
2026-11-12 09:32:23 +01:00
|
|
|
// 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+)/)
|
2026-11-12 14:03:53 +01:00
|
|
|
return m ? +m[1] : null
|
|
|
|
|
}
|
|
|
|
|
|
|
|
|
|
const MB = (b) => Math.round((b / 1048576) * 10) / 10
|
|
|
|
|
|
|
|
|
|
// Size of a folder split by its direct subfolders (one robocopy run each, so the
|
|
|
|
|
// total costs the same as one run over the whole folder). Files directly in the
|
|
|
|
|
// folder are added up as "(Dateien)". -> { bytes, children: [{ name, mb, bytes }] }
|
|
|
|
|
async function folderSplit(dir) {
|
|
|
|
|
let entries = []
|
|
|
|
|
try { entries = fs.readdirSync(dir, { withFileTypes: true }) } catch { return { bytes: 0, children: [] } }
|
|
|
|
|
let fileBytes = 0
|
|
|
|
|
const dirs = []
|
|
|
|
|
for (const e of entries) {
|
|
|
|
|
const full = path.join(dir, e.name)
|
|
|
|
|
if (e.isFile()) { try { fileBytes += fs.statSync(full).size } catch {} }
|
|
|
|
|
else if (e.isDirectory() && !e.isSymbolicLink()) {
|
|
|
|
|
// junctions look like directories: skip them like robocopy /XJ does
|
|
|
|
|
try { if (fs.lstatSync(full).isSymbolicLink()) continue } catch { continue }
|
|
|
|
|
dirs.push(e.name)
|
|
|
|
|
}
|
|
|
|
|
}
|
|
|
|
|
const children = []
|
|
|
|
|
await pool(dirs, 4, async (name) => {
|
|
|
|
|
const b = await dirBytes(path.join(dir, name))
|
|
|
|
|
if (b) children.push({ name, bytes: b })
|
|
|
|
|
})
|
|
|
|
|
if (fileBytes) children.push({ name: '(Dateien)', bytes: fileBytes, files: true })
|
|
|
|
|
children.sort((a, b) => b.bytes - a.bytes)
|
|
|
|
|
return { bytes: children.reduce((s, c) => s + c.bytes, 0), children }
|
|
|
|
|
}
|
|
|
|
|
|
|
|
|
|
// Tree for the treemap: subfolders of the project, the biggest ones (>= 5 % and
|
|
|
|
|
// >= 50 MB, at most 3) split once more. Tiny entries are merged.
|
|
|
|
|
async function sizeTree(dir) {
|
|
|
|
|
const top = await folderSplit(dir)
|
|
|
|
|
const big = top.children.filter((c) => !c.files && c.bytes >= top.bytes * 0.05 && c.bytes >= 50 * 1048576).slice(0, 3)
|
|
|
|
|
for (const c of big) c.children = (await folderSplit(path.join(dir, c.name))).children
|
|
|
|
|
const tidy = (list, total) => {
|
|
|
|
|
const keep = [], small = { name: '(kleinere)', bytes: 0, merged: 0 }
|
|
|
|
|
for (const c of list) {
|
|
|
|
|
if (c.bytes < total * 0.002 && list.length > 12) { small.bytes += c.bytes; small.merged++ }
|
|
|
|
|
else keep.push({ name: c.name, mb: MB(c.bytes), ...(c.files ? { files: true } : {}), ...(c.children ? { children: tidy(c.children, c.bytes) } : {}) })
|
|
|
|
|
}
|
|
|
|
|
if (small.merged) keep.push({ name: `(${small.merged} kleinere)`, mb: MB(small.bytes), merged: true })
|
|
|
|
|
return keep.slice(0, 60)
|
|
|
|
|
}
|
|
|
|
|
return { bytes: top.bytes, tree: tidy(top.children, top.bytes) }
|
2026-11-12 09:32:23 +01:00
|
|
|
}
|
|
|
|
|
|
|
|
|
|
async function scanProject(root, folder) {
|
|
|
|
|
const dir = path.join(root, folder)
|
2026-11-12 20:23:53 +01:00
|
|
|
const st = scriptTarget(root, folder)
|
2026-11-12 14:03:53 +01:00
|
|
|
const [split, cand] = await Promise.all([
|
|
|
|
|
sizeTree(dir),
|
2026-11-12 20:23:53 +01:00
|
|
|
scriptFor(root) ? run('powershell.exe', psArgs(root, ['-Project', st.project, '-Tier', ALL_TIERS], st.effRoot), { timeout: 10 * 60 * 1000 }) : null,
|
2026-11-12 09:32:23 +01:00
|
|
|
])
|
2026-11-12 20:23:53 +01:00
|
|
|
const candidates = (cand ? parseJson(cand.stdout) : []).map((c) => (st.prefix && typeof c.Path === 'string' ? { ...c, Path: st.prefix + c.Path } : c))
|
2026-11-12 09:32:23 +01:00
|
|
|
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)] ??= {})
|
2026-11-12 14:03:53 +01:00
|
|
|
d[folder] = { at: new Date().toISOString(), sizeMB: Math.round(split.bytes / 1048576), candidates, deletable, tree: split.tree }
|
2026-11-12 09:32:23 +01:00
|
|
|
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')
|
2026-11-12 20:23:53 +01:00
|
|
|
const st = scriptTarget(root, folder)
|
|
|
|
|
const rel = only.map((p) => p.slice(st.prefix.length))
|
|
|
|
|
const r = await run('powershell.exe', psArgs(root, ['-Project', st.project, '-Tier', ALL_TIERS, '-Only', rel.join('|'), '-Apply'], st.effRoot), { timeout: 30 * 60 * 1000 })
|
2026-11-12 09:32:23 +01:00
|
|
|
const result = parseJson(r.stdout)
|
|
|
|
|
await scanProject(root, folder)
|
|
|
|
|
return result
|
|
|
|
|
}
|
|
|
|
|
|
|
|
|
|
function get(root, folder) { return all[rootKey(root)]?.[folder] ?? null }
|
|
|
|
|
|
2026-11-12 14:03:53 +01:00
|
|
|
// A project was renamed/moved: keep its scan result. Cleanup paths are
|
|
|
|
|
// "<folder>\..." relative to the projects folder, so they get the new name.
|
|
|
|
|
function rename(oldRoot, oldFolder, newRoot, newFolder) {
|
|
|
|
|
const d = get(oldRoot, oldFolder)
|
|
|
|
|
if (!d) return
|
|
|
|
|
delete all[rootKey(oldRoot)][oldFolder]
|
|
|
|
|
const prefix = oldFolder + path.sep
|
|
|
|
|
d.candidates = (d.candidates ?? []).map((c) => (typeof c.Path === 'string' && c.Path.startsWith(prefix) ? { ...c, Path: newFolder + path.sep + c.Path.slice(prefix.length) } : c))
|
|
|
|
|
;(all[rootKey(newRoot)] ??= {})[newFolder] = d
|
|
|
|
|
save()
|
|
|
|
|
}
|
|
|
|
|
|
2026-11-12 09:32:23 +01:00
|
|
|
// 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 }
|
|
|
|
|
}
|
|
|
|
|
|
2026-11-12 14:03:53 +01:00
|
|
|
module.exports = { init, startScan, clean, get, rename, totals, state, available, cleanupAvailable, busy }
|