add dashboard

This commit is contained in:
2026-11-12 14:03:53 +01:00
parent 53f1896d05
commit 68bb7ff810
14 changed files with 2037 additions and 280 deletions

View File

@@ -5,17 +5,27 @@
const fs = require('fs')
const path = require('path')
const SKIP = /^(node_modules|\.git|\.gradle|\.gradle-local|Library|Temp|Logs|obj|bin|build|builds|dist|out|release|publish|\.venv.*|venv|env|__pycache__|\.cache|\.expo|\.next|\.idea|\.vs|\.vscode|output|CMakeFiles|_deps|\.dart_tool|\.cxx|\.externalNativeBuild|cmake-build-.*)$/i
const SKIP = /^(node_modules|\.git|\.gradle|\.gradle-local|Library|Temp|Logs|obj|bin|build|builds|dist|out|release|releases|publish|\.venv.*|venv|env|__pycache__|\.cache|\.expo|\.next|\.idea|\.vs|\.vscode|output|CMakeFiles|_deps|\.dart_tool|\.cxx|\.externalNativeBuild|cmake-build-.*)$/i
const IGNORE_FILES = /^(\.dashboard\.json|thumbs\.db|desktop\.ini|\.ds_store)$/i
const MAX_ENTRIES = 30000
const MAX_DEPTH = 10
const TTL_MS = 5 * 60 * 1000
const cache = new Map() // projectPath -> { value, at }
// local calendar day "YYYY-MM-DD" (the heatmap shows the user's days, not UTC)
const dayOf = (ms) => {
const d = new Date(ms)
return `${d.getFullYear()}-${String(d.getMonth() + 1).padStart(2, '0')}-${String(d.getDate()).padStart(2, '0')}`
}
const YEAR_MS = 371 * 86400000
function scan(projectPath) {
let best = 0
let bestFile = ''
let seen = 0
// files changed per day within the last year (each file counts on the day of its last change)
const days = {}
const since = Date.now() - YEAR_MS
const stack = [{ dir: projectPath, depth: 0 }]
while (stack.length) {
const { dir, depth } = stack.pop()
@@ -30,15 +40,37 @@ function scan(projectPath) {
let m = 0
try { m = fs.statSync(full).mtimeMs } catch { continue }
if (m > best) { best = m; bestFile = full }
if (m >= since && m <= Date.now() + 86400000) { const k = dayOf(m); days[k] = (days[k] ?? 0) + 1 }
}
}
}
return finish()
function finish() {
return best ? { at: new Date(best).toISOString(), file: path.relative(projectPath, bestFile), partial: seen > MAX_ENTRIES } : null
return best ? { at: new Date(best).toISOString(), file: path.relative(projectPath, bestFile), partial: seen > MAX_ENTRIES, days } : null
}
}
// Commits per day of the last year (git log), cached like the scan.
const { run } = require('./proc')
const gitCache = new Map() // projectPath -> { value, at }
async function gitDays(projectPath) {
const c = gitCache.get(projectPath)
if (c && Date.now() - c.at < TTL_MS) return c.value
let value = {}
if (fs.existsSync(path.join(projectPath, '.git'))) {
const r = await run('git', ['-C', projectPath, 'log', '--since=1.year.ago', '--format=%ad', '--date=short-local'], { timeout: 15000 })
for (const line of r.stdout.split(/\r?\n/)) { const k = line.trim(); if (/^\d{4}-\d{2}-\d{2}$/.test(k)) value[k] = (value[k] ?? 0) + 1 }
}
gitCache.set(projectPath, { value, at: Date.now() })
return value
}
// Files changed per day (undefined while the background scan hasn't reached the project).
function filesPerDay(projectPath) {
const v = lastChange(projectPath)
return v === undefined ? undefined : v?.days ?? {}
}
// Scans run in the background, one project per tick, so the server stays
// responsive; the list always gets the latest known value right away.
const queue = []
@@ -71,6 +103,6 @@ function lastChange(projectPath) {
function warm(projectPaths) { for (const p of projectPaths) enqueue(p) }
function pending() { return queue.length + (running ? 1 : 0) }
function forget(projectPath) { cache.delete(projectPath) }
function clear() { cache.clear(); queue.length = 0; queued.clear() }
function clear() { cache.clear(); gitCache.clear(); queue.length = 0; queued.clear() }
module.exports = { lastChange, warm, pending, forget, clear }
module.exports = { lastChange, warm, pending, forget, clear, gitDays, filesPerDay, dayOf }

120
lib/archive.js Normal file
View File

@@ -0,0 +1,120 @@
// 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 }

View File

@@ -27,6 +27,7 @@ const state = {
target: null, // target id of the job
scope: null, // null = everything, else the project's display name
autoCopy: false, // copy right after the check (per-project "Sichern")
auto: false, // started by the automatic backup schedule
error: null,
check: null, // summary of the last check
progress: null, // { files, filesTotal, bytes, bytesTotal, current }
@@ -90,10 +91,11 @@ function baseArgs(cfg) {
'/XD', ...cfg.excludeDirs, '/XF', ...cfg.excludeFiles]
}
// robocopy runs of a job: one per projects folder, or one for a single project
function itemsFor(t, scope) {
// robocopy runs of a job: one per projects folder (the shown ones, or `rootList`),
// or one for a single project
function itemsFor(t, scope, rootList = roots) {
if (scope) return [{ root: scope.root, source: path.join(scope.root, scope.folder), target: path.join(destOf(t, scope.root), scope.folder) }]
return roots.map((root) => ({ root, source: root, target: destOf(t, root) }))
return rootList.map((root) => ({ root, source: root, target: destOf(t, root) }))
}
const stamp = () => new Date().toISOString().slice(0, 16).replace('T', '_').replace(':', '-')
@@ -173,12 +175,14 @@ function failedFromLog(log, source, target) {
// scope: null = all shown projects folders, or { root, folder } of one project.
// autoCopy: continue with the copy right away (nothing is deleted, so no question needed).
// targetId: which backup target (default: the first one).
function check(scope = null, autoCopy = false, targetId = null) {
// opts.roots: other projects folders than the shown ones (automatic backup: all of them);
// opts.auto: started by the schedule (lib/scheduler.js), shown as such in the UI.
function check(scope = null, autoCopy = false, targetId = null, opts = {}) {
if (busy()) return false
const cfg = config(targetId)
const items = itemsFor(cfg.t, scope)
const items = itemsFor(cfg.t, scope, opts.roots?.length ? opts.roots : roots)
job = { scope, items }
Object.assign(state, { phase: 'checking', target: cfg.t.id, scope: scope ? keyOf(scope.root, scope.folder) : null, autoCopy, error: null, check: null, progress: null })
Object.assign(state, { phase: 'checking', target: cfg.t.id, scope: scope ? keyOf(scope.root, scope.folder) : null, autoCopy, auto: !!opts.auto, error: null, check: null, progress: null })
run(async () => {
const share = path.dirname(cfg.t.path)
if (!fs.existsSync(cfg.t.path) && !fs.existsSync(share)) throw new Error(`Backup-Ziel „${cfg.t.name}“ nicht erreichbar: ${cfg.t.path} – Laufwerk/NAS angeschlossen und eingeschaltet?`)

View File

@@ -68,6 +68,53 @@ async function create(opts) {
}
}
// Renames a project folder and/or moves it into another projects folder.
// Same drive: a plain rename. Other drive: robocopy everything (no excludes),
// check that nothing is missing, only then delete the original.
// opts: { from (absolute project path), rootPath (target projects folder), name }
async function move(opts) {
if (running) throw new Error(`Es läuft gerade schon „${running}“.`)
const name = checkName(opts.name)
const src = path.resolve(opts.from)
const dest = path.join(path.resolve(opts.rootPath), name)
if (path.basename(src).toLowerCase() === '_tools') throw new Error('_Tools wird nicht umbenannt oder verschoben.')
if (src === dest) throw new Error('Name und Ordner sind unverändert.')
const caseOnly = src.toLowerCase() === dest.toLowerCase()
if (!caseOnly && fs.existsSync(dest)) throw new Error(`Es gibt schon einen Ordner „${name}“ in ${opts.rootPath}.`)
if (dest.toLowerCase().startsWith(src.toLowerCase() + path.sep)) throw new Error('Ein Projekt kann nicht in sich selbst verschoben werden.')
running = path.basename(src)
try {
const copyMove = async () => {
const args = [src, dest, '/E', '/XJ', '/R:1', '/W:1', '/COPY:DAT', '/DCOPY:T', '/MT:8', '/NJH', '/NJS', '/NP', '/NFL', '/NDL']
const r = await run('robocopy', args, { timeout: 2 * 60 * 60 * 1000 })
if (r.code < 0 || r.code >= 8) throw new Error(`Kopieren fehlgeschlagen (robocopy ${r.code}). Das Original in ${src} ist unverändert; die angefangene Kopie liegt in ${dest}.`)
// check: a listing run must find nothing left to copy
const chk = await run('robocopy', [src, dest, '/E', '/XJ', '/L', '/NJH', '/NJS', '/NP', '/NDL', '/FP', '/R:0', '/W:0'], { timeout: 30 * 60 * 1000 })
const missing = chk.stdout.split(/\r?\n/).filter((l) => /\t/.test(l) && !/\*EXTRA/i.test(l)).length
if (chk.code < 0 || chk.code >= 8 || missing) throw new Error(`Kopie unvollständig (${missing} Dateien fehlen). Das Original in ${src} bleibt erhalten; die Kopie liegt in ${dest}.`)
fs.rmSync(src, { recursive: true, force: true, maxRetries: 3 })
}
if (process.env.DASHBOARD_TEST_FORCE_COPY && !caseOnly) await copyMove()
else {
try {
if (caseOnly) {
// Windows: a case-only rename needs a detour
const tmp = `${src}.__umbenennen__${Date.now()}`
fs.renameSync(src, tmp)
fs.renameSync(tmp, dest)
} else fs.renameSync(src, dest)
} catch (e) {
if (e.code === 'EXDEV') await copyMove()
else if (e.code === 'EPERM' || e.code === 'EBUSY' || e.code === 'EACCES') throw new Error('Der Ordner ist in Benutzung (VS Code, Konsole, laufendes Programm, Explorer-Fenster?) – schließen und nochmal versuchen.')
else throw e
}
}
return { name, path: dest }
} finally {
running = null
}
}
const busy = () => !!running
module.exports = { create, checkName, busy }
module.exports = { create, move, checkName, busy }

143
lib/scheduler.js Normal file
View File

@@ -0,0 +1,143 @@
// Automatic backup: runs the normal backup (check → copy, never deletes) of
// all projects folders on a schedule chosen in the settings - at every start,
// hourly, daily at a time, or weekly on a day at a time. Only while the
// dashboard runs; a missed time (PC off, window closed) is made up at the next
// start. An unreachable target (NAS off, USB disk missing) is tried again after
// RETRY_MS. With target 'all' the targets are backed up one after another.
const fs = require('fs')
const path = require('path')
const settings = require('./settings')
const backup = require('./backup')
const FILE = path.join(settings.DATA_DIR, 'auto-backup.json')
const TICK_MS = 30 * 1000
const RETRY_MS = 30 * 60 * 1000
const START_DELAY_MS = 2 * 60 * 1000 // "at every start": give the PC (and the NAS) a moment
// since: when the current schedule was switched on/changed - times before that
// are not "missed" (switching on "daily 20:00" at 14:00 starts today at 20:00)
let st = { lastRun: null, lastAttempt: null, lastResult: null, since: null, plan: null }
try { st = { ...st, ...JSON.parse(fs.readFileSync(FILE, 'utf-8')) } } catch {}
const bootAt = Date.now()
let startDone = false
let queue = [] // target ids still to do in this run
let current = null // { id } of the running job
let results = [] // per target of this run: { id, name, ok, error }
let timer = null
function save() {
try { fs.mkdirSync(path.dirname(FILE), { recursive: true }); fs.writeFileSync(FILE, JSON.stringify(st, null, 1)) } catch {}
}
const ms = (iso) => (iso ? new Date(iso).getTime() : 0)
function cfg() {
const c = settings.get().backup.auto ?? { interval: 'off' }
const plan = c.interval === 'off' ? 'off' : `${c.interval}|${c.time}|${c.weekday}`
if (plan !== st.plan) { st.plan = plan; st.since = new Date().toISOString(); save() }
return c
}
// last time that counts as "done": the last run, or when the schedule was set
const base = () => Math.max(ms(st.lastRun), ms(st.since))
// the latest scheduled moment at or before `now` (daily/weekly), else null
function lastSlot(c, now) {
const [h, m] = (c.time ?? '20:00').split(':').map(Number)
const d = new Date(now)
d.setHours(h, m, 0, 0)
if (c.interval === 'daily') { if (d > now) d.setDate(d.getDate() - 1); return d }
if (c.interval === 'weekly') {
d.setDate(d.getDate() - ((d.getDay() - c.weekday + 7) % 7))
if (d > now) d.setDate(d.getDate() - 7)
return d
}
return null
}
function due(c, now = new Date()) {
if (c.interval === 'off' || !settings.get().backup.targets.length) return false
// failed last time: wait before trying again
if (ms(st.lastAttempt) > ms(st.lastRun) && now - ms(st.lastAttempt) < RETRY_MS) return false
switch (c.interval) {
case 'start': return !startDone && now - bootAt >= START_DELAY_MS
case 'hourly': return now - base() >= 60 * 60 * 1000
case 'daily':
case 'weekly': return base() < lastSlot(c, now).getTime()
}
return false
}
// when the next automatic backup will start (for the settings), or null
function nextRun(c, now = new Date()) {
if (c.interval === 'off' || !settings.get().backup.targets.length) return null
if (current || queue.length) return now.toISOString()
if (ms(st.lastAttempt) > ms(st.lastRun) && now - ms(st.lastAttempt) < RETRY_MS) return new Date(ms(st.lastAttempt) + RETRY_MS).toISOString()
if (due(c, now)) return now.toISOString()
switch (c.interval) {
case 'start': return startDone ? null : new Date(bootAt + START_DELAY_MS).toISOString()
case 'hourly': return new Date(base() + 60 * 60 * 1000).toISOString()
case 'daily':
case 'weekly': {
const s = lastSlot(c, now)
s.setDate(s.getDate() + (c.interval === 'daily' ? 1 : 7))
return s.toISOString()
}
}
return null
}
// all registered projects folders that exist (not only the ones shown right now)
const allRoots = () => settings.get().roots.map((r) => path.resolve(r.path)).filter((p) => fs.existsSync(p))
function startNext() {
if (backup.busy() || !queue.length) return
const id = queue[0]
if (!backup.check(null, true, id, { roots: allRoots(), auto: true })) return
queue.shift()
current = { id }
}
function finishRun() {
const ok = results.length > 0 && results.every((r) => r.ok)
st.lastResult = { at: new Date().toISOString(), ok, targets: results }
if (ok) st.lastRun = st.lastResult.at
save()
results = []
}
function tick() {
try {
if (current) {
if (backup.busy()) return
const s = backup.getState()
const t = settings.get().backup.targets.find((x) => x.id === current.id)
results.push({ id: current.id, name: t?.name ?? current.id, ok: s.phase === 'done', error: s.phase === 'done' ? null : s.phase === 'cancelled' ? 'abgebrochen' : s.error })
current = null
if (!queue.length) finishRun()
}
if (queue.length) return startNext()
const c = cfg()
// someone else's backup is running: the schedule waits for the next tick
if (backup.busy() || !due(c)) return
const targets = settings.get().backup.targets
queue = c.target === 'all' ? targets.map((t) => t.id) : targets.filter((t) => t.id === c.target).map((t) => t.id)
if (!queue.length) queue = targets.slice(0, 1).map((t) => t.id)
if (c.interval === 'start') startDone = true
st.lastAttempt = new Date().toISOString()
save()
startNext()
} catch (e) {
console.error('Auto-Backup:', e.message)
}
}
function start() {
if (timer) return
timer = setInterval(tick, TICK_MS)
setTimeout(tick, 5000)
}
function status() {
const c = cfg()
return { ...c, next: nextRun(c), running: !!current || queue.length > 0, lastRun: st.lastRun, lastResult: st.lastResult }
}
module.exports = { start, status, lastSlot, due }

View File

@@ -65,10 +65,26 @@ function defaults() {
targets: Array.isArray(legacy?.targets) ? legacy.targets : targetsFrom(legacy?.target ?? ''),
excludeDirs: legacy?.excludeDirs ?? DEFAULT_EXCLUDE_DIRS,
excludeFiles: legacy?.excludeFiles ?? DEFAULT_EXCLUDE_FILES,
// "Backup fällig": changed since the last backup and that is older than this
remindDays: 7,
auto: { ...AUTO_DEFAULT },
},
}
}
// Automatic backup (lib/scheduler.js): interval off | start | hourly | daily | weekly,
// time "HH:MM" (daily/weekly), weekday 0=So … 6=Sa (weekly), target 'all' or a target id.
const AUTO_DEFAULT = { interval: 'off', time: '20:00', weekday: 5, target: 'all' }
function cleanAuto(a, old) {
const o = { ...AUTO_DEFAULT, ...(old ?? {}) }
if (!a || typeof a !== 'object') return o
if (['off', 'start', 'hourly', 'daily', 'weekly'].includes(a.interval)) o.interval = a.interval
if (typeof a.time === 'string' && /^([01]\d|2[0-3]):[0-5]\d$/.test(a.time)) o.time = a.time
if (Number.isInteger(+a.weekday) && +a.weekday >= 0 && +a.weekday <= 6) o.weekday = +a.weekday
if (typeof a.target === 'string' && a.target) o.target = a.target
return o
}
let current = null
function load() {
@@ -77,6 +93,7 @@ function load() {
const backup = { ...d.backup, ...(saved?.backup ?? {}) }
if (!Array.isArray(saved?.backup?.targets) && typeof saved?.backup?.target === 'string') backup.targets = targetsFrom(saved.backup.target)
delete backup.target
backup.auto = cleanAuto(saved?.backup?.auto)
// older settings had one "projectsRoot"
let roots = Array.isArray(saved?.roots)
? saved.roots.filter((r) => r && typeof r.path === 'string' && r.path).map((r) => ({ id: String(r.id || newId()), name: String(r.name || rootName(r.path)), path: r.path }))
@@ -225,8 +242,12 @@ function save(input) {
targets,
excludeDirs: cleanList(input.excludeDirs, s.backup.excludeDirs),
excludeFiles: cleanList(input.excludeFiles, s.backup.excludeFiles),
remindDays: Number.isFinite(+input.remindDays) && +input.remindDays >= 1 ? Math.min(365, Math.round(+input.remindDays)) : (s.backup.remindDays ?? 7),
auto: cleanAuto(input.auto, s.backup.auto),
},
})
// an automatic backup to a target that was removed falls back to all targets
if (next.backup.auto.target !== 'all' && !targets.some((t) => t.id === next.backup.auto.target)) next.backup.auto.target = 'all'
persist(next)
// keep backup-projekte.bat in sync where it exists (it backs up the first folder to the first target)
const legacy = legacyBackupFile(roots[0].path)

View File

@@ -53,7 +53,9 @@ function scriptFor(root) {
return null
}
function available() { return !!scriptFor(roots[0]) }
// sizes can always be measured; cleanup candidates need cleanup.ps1
function available() { return true }
const cleanupAvailable = () => !!scriptFor(roots[0])
function psArgs(root, extra) {
return ['-NoProfile', '-ExecutionPolicy', 'Bypass', '-File', scriptFor(root), '-Root', root, ...extra, '-Json']
@@ -66,25 +68,72 @@ function parseJson(stdout) {
return JSON.parse(text.slice(start))
}
async function dirSizeMB(dir) {
async function dirBytes(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
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) }
}
async function scanProject(root, folder) {
const dir = path.join(root, folder)
const [sizeMB, cand] = await Promise.all([
dirSizeMB(dir),
const [split, cand] = await Promise.all([
sizeTree(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 }
d[folder] = { at: new Date().toISOString(), sizeMB: Math.round(split.bytes / 1048576), candidates, deletable, tree: split.tree }
save()
return d[folder]
}
@@ -118,6 +167,18 @@ async function clean(root, folder, paths) {
function get(root, folder) { return all[rootKey(root)]?.[folder] ?? null }
// 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()
}
// items: [{ root, folder }]
function totals(items) {
let sizeMB = 0, cacheMB = 0, allMB = 0, scanned = 0
@@ -132,4 +193,4 @@ function totals(items) {
return { sizeMB, cacheMB, allMB, scanned }
}
module.exports = { init, startScan, clean, get, totals, state, available, busy }
module.exports = { init, startScan, clean, get, rename, totals, state, available, cleanupAvailable, busy }

34
lib/supervisor.js Normal file
View File

@@ -0,0 +1,34 @@
// Keeps the dashboard server restartable without losing the process the
// launcher (or the console) holds: this process only runs server.js as a
// worker and starts it again when it exits with RESTART_CODE ("Neu starten"
// in the UI after the code was updated). Any other exit ends this process too.
// The worker ends itself when this process goes away (IPC disconnect), so
// closing the window never leaves a server behind.
const { fork } = require('child_process')
const RESTART_CODE = 75
function supervise(script) {
let child = null
const start = () => {
child = fork(script, process.argv.slice(2), {
env: { ...process.env, DASHBOARD_WORKER: '1' },
stdio: 'inherit',
})
child.on('exit', (code, signal) => {
if (code === RESTART_CODE) {
console.log('Dashboard wird neu gestartet …')
start()
return
}
process.exit(code ?? (signal ? 1 : 0))
})
}
// Ctrl+C / normal end: take the worker along
const stop = () => { try { child?.kill() } catch {} process.exit(0) }
process.on('SIGINT', stop)
process.on('SIGTERM', stop)
start()
}
module.exports = { supervise, RESTART_CODE }