main ini
This commit is contained in:
76
lib/activity.js
Normal file
76
lib/activity.js
Normal file
@@ -0,0 +1,76 @@
|
||||
// "Last change" of a project = newest modified file inside it, ignoring
|
||||
// folders that change by themselves (node_modules, build output, caches, .git).
|
||||
// The folder's own mtime is useless for this (it only changes when direct
|
||||
// children are added/removed). Bounded walk, cached for a few minutes.
|
||||
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 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 }
|
||||
|
||||
function scan(projectPath) {
|
||||
let best = 0
|
||||
let bestFile = ''
|
||||
let seen = 0
|
||||
const stack = [{ dir: projectPath, depth: 0 }]
|
||||
while (stack.length) {
|
||||
const { dir, depth } = stack.pop()
|
||||
let entries
|
||||
try { entries = fs.readdirSync(dir, { withFileTypes: true }) } catch { continue }
|
||||
for (const e of entries) {
|
||||
if (++seen > MAX_ENTRIES) return finish()
|
||||
const full = path.join(dir, e.name)
|
||||
if (e.isDirectory()) {
|
||||
if (depth < MAX_DEPTH && !SKIP.test(e.name)) stack.push({ dir: full, depth: depth + 1 })
|
||||
} else if (e.isFile() && !IGNORE_FILES.test(e.name)) {
|
||||
let m = 0
|
||||
try { m = fs.statSync(full).mtimeMs } catch { continue }
|
||||
if (m > best) { best = m; bestFile = full }
|
||||
}
|
||||
}
|
||||
}
|
||||
return finish()
|
||||
function finish() {
|
||||
return best ? { at: new Date(best).toISOString(), file: path.relative(projectPath, bestFile), partial: seen > MAX_ENTRIES } : null
|
||||
}
|
||||
}
|
||||
|
||||
// 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 = []
|
||||
const queued = new Set()
|
||||
let running = false
|
||||
|
||||
function enqueue(projectPath) {
|
||||
if (queued.has(projectPath)) return
|
||||
queued.add(projectPath)
|
||||
queue.push(projectPath)
|
||||
if (!running) { running = true; setImmediate(work) }
|
||||
}
|
||||
|
||||
function work() {
|
||||
const p = queue.shift()
|
||||
if (!p) { running = false; return }
|
||||
queued.delete(p)
|
||||
try { cache.set(p, { value: scan(p), at: Date.now() }) } catch {}
|
||||
setImmediate(work)
|
||||
}
|
||||
|
||||
// -> { at, file, partial } | null (empty project) | undefined (not known yet);
|
||||
// a stale or missing value is refreshed in the background.
|
||||
function lastChange(projectPath) {
|
||||
const c = cache.get(projectPath)
|
||||
if (!c || Date.now() - c.at > TTL_MS) enqueue(projectPath)
|
||||
return c ? c.value : undefined
|
||||
}
|
||||
|
||||
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() }
|
||||
|
||||
module.exports = { lastChange, warm, pending, forget, clear }
|
||||
344
lib/backup.js
Normal file
344
lib/backup.js
Normal file
@@ -0,0 +1,344 @@
|
||||
// Backup to one or more targets (folder / drive / NAS), in two steps like
|
||||
// _Tools\Backup\backup-projekte.ps1:
|
||||
// check: robocopy /L lists what is new/changed (missing in the backup) and
|
||||
// what exists only in the backup
|
||||
// copy: robocopy /E copies exactly that - nothing is ever deleted in the backup
|
||||
// Scope: all shown projects folders (scope = null; several can be selected,
|
||||
// see lib/settings.js) or one project (<root>\<folder> -> <dest>\<folder>).
|
||||
// Each projects folder lands in its own place on the target (settings.backupSubdir):
|
||||
// the first registered folder directly in the target, further ones in a subfolder.
|
||||
// One job at a time (for one target), in the background; the UI polls getState().
|
||||
// Excludes come from the settings, which also keep _Tools\Backup\backup-config.json
|
||||
// in sync (backup-projekte.bat uses the first target). Every projects folder keeps
|
||||
// its own "last backup" info per target.
|
||||
const fs = require('fs')
|
||||
const path = require('path')
|
||||
const { spawn } = require('child_process')
|
||||
const settings = require('./settings')
|
||||
|
||||
let roots = [] // selected projects folders (paths)
|
||||
let keyOf = (root, folder) => folder // display name of a project (set by the server)
|
||||
let logDir = null
|
||||
const STATE_FILE = path.join(settings.DATA_DIR, 'backup.json')
|
||||
|
||||
// the running / last job
|
||||
const state = {
|
||||
phase: 'idle', // idle | checking | ready | copying | done | cancelled | error
|
||||
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")
|
||||
error: null,
|
||||
check: null, // summary of the last check
|
||||
progress: null, // { files, filesTotal, bytes, bytesTotal, current }
|
||||
}
|
||||
let job = null // { scope: {root, folder} | null, items: [{ root, source, target }] }
|
||||
let all = {} // root (lower case) -> target id -> { path, last, lastByProject }
|
||||
let child = null
|
||||
|
||||
const rootKey = (r) => (r ?? '').toLowerCase()
|
||||
const targets = () => settings.get().backup.targets
|
||||
const targetById = (id) => targets().find((t) => t.id === id) ?? null
|
||||
// where a projects folder lands on a target
|
||||
const destOf = (t, root) => path.join(t.path, settings.backupSubdir(root))
|
||||
// per root and target; starts fresh when the destination changed
|
||||
function dataFor(t, root) {
|
||||
const r = (all[rootKey(root)] ??= {})
|
||||
let d = r[t.id]
|
||||
const dest = destOf(t, root)
|
||||
if (!d || d.path.toLowerCase() !== dest.toLowerCase()) d = r[t.id] = { path: dest, last: null, lastByProject: {} }
|
||||
return d
|
||||
}
|
||||
|
||||
// (Re)initialise for the current settings. rootList: selected projects folders,
|
||||
// key: (root, folder) -> name of the project in the UI.
|
||||
function init(rootList, key) {
|
||||
roots = (Array.isArray(rootList) ? rootList : [rootList]).filter(Boolean)
|
||||
if (key) keyOf = key
|
||||
const first = roots[0] ?? ''
|
||||
const own = first ? path.join(first, '_Tools', 'Backup') : ''
|
||||
logDir = own && fs.existsSync(own) ? path.join(own, 'logs') : path.join(settings.DATA_DIR, 'logs')
|
||||
if (!busy()) Object.assign(state, { phase: 'idle', target: null, scope: null, error: null, check: null, progress: null })
|
||||
all = {}
|
||||
try {
|
||||
const saved = JSON.parse(fs.readFileSync(STATE_FILE, 'utf-8'))
|
||||
if (saved.roots && typeof saved.roots === 'object') all = saved.roots
|
||||
else if (saved.targets) all[rootKey(saved.root ?? first)] = saved.targets
|
||||
else {
|
||||
// old format: one target
|
||||
const t = targets().find((x) => !saved.target || x.path.toLowerCase() === saved.target.toLowerCase())
|
||||
if (t) all[rootKey(first)] = { [t.id]: { path: t.path, last: saved.last ?? null, lastByProject: saved.lastByProject ?? {} } }
|
||||
}
|
||||
} catch {}
|
||||
const ids = new Set(targets().map((t) => t.id))
|
||||
for (const r of Object.values(all)) for (const id of Object.keys(r)) if (!ids.has(id)) delete r[id]
|
||||
}
|
||||
|
||||
function save() {
|
||||
fs.mkdirSync(path.dirname(STATE_FILE), { recursive: true })
|
||||
fs.writeFileSync(STATE_FILE, JSON.stringify({ roots: all }, null, 1))
|
||||
}
|
||||
|
||||
function config(targetId) {
|
||||
const s = settings.get()
|
||||
if (!s.backup.targets.length) throw new Error('Kein Backup-Ziel eingerichtet – in den Einstellungen (⚙) festlegen.')
|
||||
const t = targetById(targetId) ?? s.backup.targets[0]
|
||||
return { t, excludeDirs: s.backup.excludeDirs, excludeFiles: s.backup.excludeFiles }
|
||||
}
|
||||
|
||||
function baseArgs(cfg) {
|
||||
return ['/E', '/FFT', '/XJ', '/R:2', '/W:5', '/COPY:DAT', '/DCOPY:T',
|
||||
'/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) {
|
||||
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) }))
|
||||
}
|
||||
|
||||
const stamp = () => new Date().toISOString().slice(0, 16).replace('T', '_').replace(':', '-')
|
||||
const slug = (s) => (s ? '-' + s.replace(/[^\w.-]+/g, '_').slice(0, 40) : '')
|
||||
|
||||
// Runs robocopy and calls onLine for every line it writes to `logFile`.
|
||||
// robocopy's stdout uses the old OEM code page (umlauts break), but /UNILOG
|
||||
// writes real UTF-16 - so the log file is tailed while robocopy runs.
|
||||
function robocopy(args, logFile, onLine) {
|
||||
return new Promise((resolve) => {
|
||||
fs.mkdirSync(path.dirname(logFile), { recursive: true })
|
||||
try { fs.unlinkSync(logFile) } catch {}
|
||||
child = spawn('robocopy', [...args, `/UNILOG:${logFile}`], { windowsHide: true, stdio: 'ignore' })
|
||||
const decoder = new TextDecoder('utf-16le')
|
||||
let offset = 0
|
||||
let rest = ''
|
||||
const buf = Buffer.alloc(1 << 20)
|
||||
const drain = (final) => {
|
||||
let fd
|
||||
try { fd = fs.openSync(logFile, 'r') } catch { return }
|
||||
try {
|
||||
for (;;) {
|
||||
const n = fs.readSync(fd, buf, 0, buf.length, offset)
|
||||
if (n <= 0) break
|
||||
offset += n
|
||||
const lines = (rest + decoder.decode(buf.subarray(0, n), { stream: true })).split(/\r?\n/)
|
||||
rest = lines.pop()
|
||||
for (const l of lines) onLine(l)
|
||||
}
|
||||
} finally { fs.closeSync(fd) }
|
||||
if (final && rest) { onLine(rest); rest = '' }
|
||||
}
|
||||
const timer = setInterval(() => drain(false), 500)
|
||||
const finish = (code) => { clearInterval(timer); drain(true); child = null; resolve(code ?? 16) }
|
||||
child.on('close', finish)
|
||||
child.on('error', () => finish(16))
|
||||
})
|
||||
}
|
||||
|
||||
// One file line of robocopy output: "<class>\t<size>\t<full path>"
|
||||
function parseLine(line) {
|
||||
const parts = line.split('\t').map((s) => s.trim()).filter(Boolean)
|
||||
if (parts.length < 3) return null
|
||||
const size = Number(parts[parts.length - 2])
|
||||
const file = parts[parts.length - 1]
|
||||
if (!Number.isFinite(size) || file.endsWith('\\')) return null
|
||||
return { cls: parts[0], size, file }
|
||||
}
|
||||
|
||||
function busy() { return state.phase === 'checking' || state.phase === 'copying' }
|
||||
|
||||
// robocopy error line: "2026/11/10 11:17:10 FEHLER 2 (0x00000002) Verzeichnis wird kopiert D:\x\y\" -> path
|
||||
const ERR_RE = /\b(?:FEHLER|ERROR)\s+\d+\s+\(0x[0-9A-Fa-f]+\).*?\s((?:[A-Za-z]:\\|\\\\).*)$/
|
||||
// which project folder a source or target path belongs to (null = none / outside)
|
||||
function projectOfPath(p, source, target, scopeFolder) {
|
||||
if (scopeFolder) return scopeFolder
|
||||
const l = p.toLowerCase()
|
||||
for (const base of [source, target]) {
|
||||
const b = base.toLowerCase().replace(/\\$/, '') + '\\'
|
||||
if (l.startsWith(b)) return p.slice(b.length).split('\\')[0] || null
|
||||
}
|
||||
return null
|
||||
}
|
||||
// projects with errors in a finished robocopy log (for older records without a "failed" list)
|
||||
function failedFromLog(log, source, target) {
|
||||
try {
|
||||
const out = new Set()
|
||||
for (const line of fs.readFileSync(log, 'utf16le').split(/\r?\n/)) {
|
||||
const m = line.match(ERR_RE)
|
||||
const p = m && projectOfPath(m[1].trim(), source, target, null)
|
||||
if (p) out.add(p)
|
||||
}
|
||||
return [...out]
|
||||
} catch { return null }
|
||||
}
|
||||
|
||||
// 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) {
|
||||
if (busy()) return false
|
||||
const cfg = config(targetId)
|
||||
const items = itemsFor(cfg.t, scope)
|
||||
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 })
|
||||
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?`)
|
||||
const newF = { n: 0, b: 0 }, changed = { n: 0, b: 0 }, extra = { n: 0, b: 0 }
|
||||
const perProject = new Map()
|
||||
for (const it of items) {
|
||||
if (!fs.existsSync(it.source)) throw new Error(`Projektordner fehlt: ${it.source}`)
|
||||
fs.mkdirSync(it.target, { recursive: true })
|
||||
const checkLog = path.join(logDir, `pruefung-${stamp()}-${cfg.t.id}${slug(scope?.folder ?? (items.length > 1 ? path.basename(it.root) : ''))}.log`)
|
||||
const src = it.source
|
||||
const rc = await robocopy([src, it.target, ...baseArgs(cfg), '/L', '/X', '/NJH', '/NJS', '/NDL', '/NP', '/FP', '/BYTES'], checkLog, (line) => {
|
||||
const p = parseLine(line)
|
||||
if (!p) return
|
||||
if (p.cls.includes('EXTRA')) { extra.n++; extra.b += p.size; return }
|
||||
if (!p.file.toLowerCase().startsWith(src.toLowerCase())) return
|
||||
const bucket = /^(Neue Datei|New File)$/i.test(p.cls) ? newF : changed
|
||||
bucket.n++; bucket.b += p.size
|
||||
// group by project (all) or by top-level folder inside the project (one project)
|
||||
const rel = p.file.slice(src.length).replace(/^\\/, '')
|
||||
const key = scope
|
||||
? (rel.includes('\\') ? rel.split('\\')[0] : '(Projektordner)')
|
||||
: rel.includes('\\') ? keyOf(it.root, rel.split('\\')[0]) : rel
|
||||
const e = perProject.get(key) ?? { name: key, files: 0, bytes: 0 }
|
||||
e.files++; e.bytes += p.size
|
||||
perProject.set(key, e)
|
||||
})
|
||||
if (state.phase === 'cancelled') return
|
||||
if (rc >= 8) throw new Error(`Prüfung fehlgeschlagen (robocopy ${rc})`)
|
||||
}
|
||||
state.check = {
|
||||
at: new Date().toISOString(), scope: state.scope,
|
||||
source: items.map((i) => i.source).join(' + '), target: items.map((i) => i.target).join(' + '),
|
||||
files: newF.n + changed.n, bytes: newF.b + changed.b,
|
||||
newFiles: newF.n, newBytes: newF.b, changedFiles: changed.n, changedBytes: changed.b,
|
||||
extraFiles: extra.n, extraBytes: extra.b,
|
||||
projects: [...perProject.values()].sort((a, b) => b.bytes - a.bytes),
|
||||
}
|
||||
state.phase = 'ready'
|
||||
if (autoCopy) {
|
||||
if (state.check.files) startCopy()
|
||||
else { for (const it of items) record(cfg.t, it.root, scope?.folder, 0, 0, 0, null); state.phase = 'done' } // already complete
|
||||
}
|
||||
})
|
||||
return true
|
||||
}
|
||||
|
||||
function copy() {
|
||||
if (busy() || state.phase !== 'ready' || !state.check || !job) return false
|
||||
startCopy()
|
||||
return true
|
||||
}
|
||||
|
||||
function startCopy() {
|
||||
const cfg = config(state.target)
|
||||
const c = state.check
|
||||
const { scope, items } = job
|
||||
Object.assign(state, { phase: 'copying', error: null, progress: { files: 0, filesTotal: c.files, bytes: 0, bytesTotal: c.bytes, current: '' } })
|
||||
run(async () => {
|
||||
const problems = []
|
||||
for (const it of items) {
|
||||
const log = path.join(logDir, `backup-${stamp()}-${cfg.t.id}${slug(scope?.folder ?? (items.length > 1 ? path.basename(it.root) : ''))}.log`)
|
||||
const failed = new Set() // project folders with copy errors
|
||||
const before = { files: state.progress.files, bytes: state.progress.bytes }
|
||||
const rc = await robocopy([it.source, it.target, ...baseArgs(cfg), '/MT:16', '/NJH', '/NDL', '/NP', '/FP', '/BYTES'], log, (line) => {
|
||||
const err = line.match(ERR_RE)
|
||||
if (err) { const pr = projectOfPath(err[1].trim(), it.source, it.target, scope?.folder); if (pr) failed.add(pr); return }
|
||||
const p = parseLine(line)
|
||||
if (!p || p.cls.includes('EXTRA')) return
|
||||
state.progress.files++
|
||||
state.progress.bytes += p.size
|
||||
state.progress.current = p.file.slice(it.source.length + 1)
|
||||
})
|
||||
if (state.phase === 'cancelled') return
|
||||
record(cfg.t, it.root, scope?.folder, state.progress.files - before.files, state.progress.bytes - before.bytes, rc, log, [...failed])
|
||||
if (rc >= 8) problems.push({ rc, log, failed: [...failed].map((f) => keyOf(it.root, f)) })
|
||||
}
|
||||
if (problems.length) {
|
||||
const failed = problems.flatMap((p) => p.failed)
|
||||
const which = failed.length ? ` Betroffen: ${failed.slice(0, 5).join(', ')}${failed.length > 5 ? ' …' : ''} – alle anderen Projekte sind gesichert.` : ''
|
||||
throw new Error(`Backup unvollständig (robocopy ${problems[0].rc}).${which} Protokoll: ${problems.map((p) => p.log).join(', ')}`)
|
||||
}
|
||||
state.phase = 'done'
|
||||
state.check = null
|
||||
})
|
||||
}
|
||||
|
||||
function record(t, root, folder, files, bytes, rc, log, failed = []) {
|
||||
const d = dataFor(t, root)
|
||||
const entry = { at: new Date().toISOString(), files, bytes, rc, log, ok: rc < 8 }
|
||||
if (rc >= 8) entry.failed = failed
|
||||
if (folder) d.lastByProject[folder] = entry
|
||||
else d.last = entry
|
||||
save()
|
||||
}
|
||||
|
||||
function cancel() {
|
||||
if (!busy()) return false
|
||||
state.phase = 'cancelled'
|
||||
try { child?.kill() } catch {}
|
||||
return true
|
||||
}
|
||||
|
||||
// When the dashboard stops (window closed), don't leave robocopy running orphaned.
|
||||
process.on('exit', () => { try { child?.kill() } catch {} })
|
||||
|
||||
function run(fn) {
|
||||
fn().catch((e) => { state.phase = 'error'; state.error = String(e.message ?? e) })
|
||||
}
|
||||
|
||||
// Last time a project (root + folder) was backed up to a target (default: the first one):
|
||||
// its own backup or the last full one of its projects folder, whichever is newer.
|
||||
function lastFor(root, folder, targetId) {
|
||||
const t = targetById(targetId) ?? targets()[0]
|
||||
if (!t) return null
|
||||
const d = dataFor(t, root)
|
||||
const own = d.lastByProject[folder]
|
||||
// an incomplete full backup still counts for every project that had no errors
|
||||
let full = null
|
||||
if (d.last?.ok) full = { at: d.last.at, ok: true, how: 'Komplett-Backup' }
|
||||
else if (d.last) {
|
||||
if (!Array.isArray(d.last.failed) && d.last.log) d.last.failed = failedFromLog(d.last.log, root, destOf(t, root)) ?? undefined
|
||||
if (Array.isArray(d.last.failed)) {
|
||||
full = d.last.failed.includes(folder)
|
||||
? { at: d.last.at, ok: false, how: 'Komplett-Backup – Fehler in diesem Projekt' }
|
||||
: { at: d.last.at, ok: true, how: 'Komplett-Backup' }
|
||||
}
|
||||
}
|
||||
if (own && (!full || own.at > full.at)) return { ...own, how: 'Projekt' }
|
||||
return full
|
||||
}
|
||||
|
||||
// One project on every target: [{ id, name, last }]
|
||||
function lastOnAllTargets(root, folder) {
|
||||
return targets().map((t) => ({ id: t.id, name: t.name, last: lastFor(root, folder, t.id) }))
|
||||
}
|
||||
|
||||
// "Last full backup" of a target over all shown folders: the oldest of them
|
||||
// (none if one folder was never backed up there), files/bytes added up.
|
||||
function combinedLast(t) {
|
||||
const lasts = roots.map((r) => dataFor(t, r).last)
|
||||
if (!lasts.length || lasts.some((l) => !l)) return null
|
||||
if (lasts.length === 1) return lasts[0]
|
||||
const oldest = lasts.reduce((a, b) => (a.at < b.at ? a : b))
|
||||
return {
|
||||
...oldest,
|
||||
files: lasts.reduce((a, l) => a + (l.files ?? 0), 0),
|
||||
bytes: lasts.reduce((a, l) => a + (l.bytes ?? 0), 0),
|
||||
ok: lasts.every((l) => l.ok),
|
||||
}
|
||||
}
|
||||
|
||||
function getState() {
|
||||
const list = targets().map((t) => {
|
||||
// per-project entries, keyed like the projects in the UI
|
||||
const lastByProject = {}
|
||||
for (const r of roots) for (const [folder, e] of Object.entries(dataFor(t, r).lastByProject)) lastByProject[keyOf(r, folder)] = e
|
||||
return { id: t.id, name: t.name, path: roots.map((r) => destOf(t, r)).join(' + ') || t.path, short: settings.targetName(t.path), last: combinedLast(t), lastByProject }
|
||||
})
|
||||
if (!list.length) return { ...state, targets: [], configError: 'Kein Backup-Ziel eingerichtet – in den Einstellungen (⚙) festlegen.', notConfigured: true }
|
||||
return { ...state, source: roots.join(' + '), targets: list }
|
||||
}
|
||||
|
||||
module.exports = { init, check, copy, cancel, getState, lastFor, lastOnAllTargets, busy }
|
||||
73
lib/create.js
Normal file
73
lib/create.js
Normal file
@@ -0,0 +1,73 @@
|
||||
// New projects: an empty folder (with .dashboard.json and README.md) or a clone
|
||||
// of an existing project. Clones are copied with robocopy and leave out what
|
||||
// can be regenerated (node_modules, caches, optionally build output) and, unless
|
||||
// asked for, the git history - so the clone does not push to the original's remote.
|
||||
const fs = require('fs')
|
||||
const path = require('path')
|
||||
const { run } = require('./proc')
|
||||
const settings = require('./settings')
|
||||
|
||||
const STATUS_FILE = '.dashboard.json'
|
||||
// left out when "Build-Ordner und Caches weglassen" is ticked (on top of the backup excludes)
|
||||
const BUILD_DIRS = ['dist', 'build', 'out', 'bin', 'obj', 'Library', 'Temp', 'Logs', '.gradle', '.next', 'coverage', '.cache']
|
||||
const RESERVED = /^(con|prn|aux|nul|com[1-9]|lpt[1-9])(\..*)?$/i
|
||||
|
||||
let running = null // name of the project being created
|
||||
|
||||
// Throws with a German message if `name` can't be a Windows folder name.
|
||||
function checkName(raw) {
|
||||
const name = typeof raw === 'string' ? raw.trim() : ''
|
||||
if (!name) throw new Error('Bitte einen Namen eingeben.')
|
||||
if (name.length > 80) throw new Error('Name zu lang (höchstens 80 Zeichen).')
|
||||
if (/[<>:"/\\|?*\x00-\x1f%]/.test(name)) throw new Error('Diese Zeichen gehen nicht im Namen: < > : " / \\ | ? * %')
|
||||
if (/[. ]$/.test(name) || name.startsWith('.')) throw new Error('Der Name darf nicht mit einem Punkt beginnen oder mit Punkt/Leerzeichen enden.')
|
||||
if (RESERVED.test(name)) throw new Error(`„${name}“ ist unter Windows reserviert.`)
|
||||
return name
|
||||
}
|
||||
|
||||
function readMeta(dir) {
|
||||
try { return JSON.parse(fs.readFileSync(path.join(dir, STATUS_FILE), 'utf-8')) } catch { return {} }
|
||||
}
|
||||
|
||||
// opts: { rootPath, name, from (absolute project path or null), withGit, skipBuild, status }
|
||||
async function create(opts) {
|
||||
if (running) throw new Error(`Es wird gerade schon „${running}“ angelegt.`)
|
||||
const name = checkName(opts.name)
|
||||
const dest = path.join(opts.rootPath, name)
|
||||
if (fs.existsSync(dest)) throw new Error(`Es gibt schon einen Ordner „${name}“ in ${opts.rootPath}.`)
|
||||
running = name
|
||||
try {
|
||||
const now = new Date().toISOString()
|
||||
if (!opts.from) {
|
||||
fs.mkdirSync(dest)
|
||||
fs.writeFileSync(path.join(dest, STATUS_FILE), JSON.stringify({ status: 'idea', priority: 'medium', notes: '', tags: [], tasks: [], updatedAt: now }, null, 2))
|
||||
fs.writeFileSync(path.join(dest, 'README.md'), `# ${name}\n`)
|
||||
return { name, path: dest, cloned: false }
|
||||
}
|
||||
const src = opts.from
|
||||
if (dest.toLowerCase().startsWith(src.toLowerCase() + path.sep)) throw new Error('Der Klon darf nicht im Original liegen.')
|
||||
const b = settings.get().backup
|
||||
const xd = [...b.excludeDirs, ...(opts.skipBuild ? BUILD_DIRS : []), ...(opts.withGit ? [] : ['.git'])]
|
||||
const r = await run('robocopy', [src, dest, '/E', '/XJ', '/R:1', '/W:1', '/COPY:DAT', '/DCOPY:T', '/MT:8', '/NJH', '/NJS', '/NP', '/NFL', '/NDL',
|
||||
'/XD', ...xd, '/XF', ...b.excludeFiles], { timeout: 60 * 60 * 1000 })
|
||||
// robocopy: 0-7 = success, 8+ = errors
|
||||
if (r.code < 0 || r.code >= 8) throw new Error(`Kopieren fehlgeschlagen (robocopy ${r.code}). Der angefangene Ordner liegt in ${dest}.`)
|
||||
if (!fs.existsSync(dest)) fs.mkdirSync(dest)
|
||||
// the clone starts as a fresh idea: same tags/program/start, no itch link, open tasks only
|
||||
const m = readMeta(src)
|
||||
const tasks = Array.isArray(m.tasks) ? m.tasks.filter((t) => !t?.done) : []
|
||||
const note = `Klon von „${path.basename(src)}“ (${now.slice(0, 10)}).`
|
||||
fs.writeFileSync(path.join(dest, STATUS_FILE), JSON.stringify({
|
||||
...m, status: 'idea', itch: '', tasks,
|
||||
notes: m.notes ? `${note}\n\n${m.notes}` : note,
|
||||
updatedAt: now,
|
||||
}, null, 2))
|
||||
return { name, path: dest, cloned: true }
|
||||
} finally {
|
||||
running = null
|
||||
}
|
||||
}
|
||||
|
||||
const busy = () => !!running
|
||||
|
||||
module.exports = { create, checkName, busy }
|
||||
97
lib/git.js
Normal file
97
lib/git.js
Normal file
@@ -0,0 +1,97 @@
|
||||
// Git and backup status of one project: branch, remote, uncommitted changes,
|
||||
// commits not pushed, last commit. `level` drives the traffic light in the UI.
|
||||
const fs = require('fs')
|
||||
const path = require('path')
|
||||
const { run } = require('./proc')
|
||||
|
||||
// Git is optional (a friend's PC may not have it): checked once.
|
||||
let gitOk = null
|
||||
async function gitAvailable() {
|
||||
if (gitOk === null) gitOk = (await run('git', ['--version'])).ok
|
||||
return gitOk
|
||||
}
|
||||
|
||||
async function gitInfo(projectPath) {
|
||||
if (!fs.existsSync(path.join(projectPath, '.git'))) {
|
||||
return { isRepo: false, level: 'red', label: 'kein Git', lastCommit: null }
|
||||
}
|
||||
if (!(await gitAvailable())) {
|
||||
return { isRepo: true, level: 'red', label: 'Git nicht installiert', remote: '', branch: '', upstream: '', ahead: 0, behind: 0, dirty: 0, lastCommit: null }
|
||||
}
|
||||
const [st, rem, log] = await Promise.all([
|
||||
run('git', ['-C', projectPath, '-c', 'core.quotepath=off', 'status', '--porcelain=v2', '--branch'], { timeout: 8000 }),
|
||||
run('git', ['-C', projectPath, 'remote', '-v']),
|
||||
run('git', ['-C', projectPath, 'log', '-1', '--format=%ad|%s', '--date=short']),
|
||||
])
|
||||
|
||||
let branch = '', upstream = '', ahead = 0, behind = 0, dirty = 0
|
||||
for (const line of st.stdout.split('\n')) {
|
||||
if (!line) continue
|
||||
if (line.startsWith('# branch.head ')) branch = line.slice(14).trim()
|
||||
else if (line.startsWith('# branch.upstream ')) upstream = line.slice(18).trim()
|
||||
else if (line.startsWith('# branch.ab ')) {
|
||||
const m = line.match(/\+(\d+) -(\d+)/)
|
||||
if (m) { ahead = +m[1]; behind = +m[2] }
|
||||
} else if (!line.startsWith('#')) dirty++
|
||||
}
|
||||
|
||||
const remoteLine = rem.stdout.split('\n').find((l) => l.startsWith('origin\t')) ?? rem.stdout.split('\n').find(Boolean)
|
||||
const remote = remoteLine ? remoteLine.split('\t')[1].replace(/\s+\((fetch|push)\)$/, '') : ''
|
||||
|
||||
let lastCommit = null
|
||||
const out = log.stdout.trim()
|
||||
if (out) {
|
||||
const [date, ...msg] = out.split('|')
|
||||
lastCommit = { date, message: msg.join('|') }
|
||||
}
|
||||
|
||||
const parts = []
|
||||
if (dirty) parts.push(`${dirty} geändert`)
|
||||
if (ahead) parts.push(`${ahead} nicht gepusht`)
|
||||
if (behind) parts.push(`${behind} hinterher`)
|
||||
let level, label
|
||||
if (!remote) { level = 'red'; label = ['kein Remote (nur lokal)', ...parts].join(' · ') }
|
||||
else if (!upstream) { level = 'yellow'; label = ['kein Upstream', ...parts].join(' · ') }
|
||||
else if (dirty || ahead) { level = 'yellow'; label = parts.join(' · ') }
|
||||
else { level = 'green'; label = behind ? parts.join(' · ') : 'gesichert' }
|
||||
|
||||
return { isRepo: true, branch, upstream, remote, ahead, behind, dirty, level, label, lastCommit }
|
||||
}
|
||||
|
||||
// Remote URL as typed in the Info tab: SSH (git@host:user/repo.git, ssh://...) or https.
|
||||
// Never starts with "-", so it can't be taken for a git option.
|
||||
const REMOTE_RE = /^(?:[\w.-]+@[\w.-]+:[\w./~-]+|ssh:\/\/[^\s"'`]+|https?:\/\/[^\s"'`]+|git:\/\/[^\s"'`]+)$/
|
||||
|
||||
// Sets (or with '' removes) the "origin" remote.
|
||||
async function setRemote(projectPath, url) {
|
||||
if (!(await gitAvailable())) throw new Error('Git ist nicht installiert.')
|
||||
if (!fs.existsSync(path.join(projectPath, '.git'))) throw new Error('Kein Git-Repository – erst „Git einrichten“.')
|
||||
const u = String(url ?? '').trim()
|
||||
const has = (await run('git', ['-C', projectPath, 'remote'])).stdout.split(/\r?\n/).includes('origin')
|
||||
if (!u) {
|
||||
if (has) await run('git', ['-C', projectPath, 'remote', 'remove', 'origin'])
|
||||
return
|
||||
}
|
||||
if (!REMOTE_RE.test(u)) throw new Error('Remote: z. B. git@github.com:name/projekt.git (SSH) oder https://github.com/name/projekt.git')
|
||||
const r = await run('git', ['-C', projectPath, 'remote', has ? 'set-url' : 'add', 'origin', u])
|
||||
if (!r.ok) throw new Error(r.stderr.trim() || 'git remote fehlgeschlagen')
|
||||
}
|
||||
|
||||
// git init with branch "main" (no commit yet).
|
||||
async function initRepo(projectPath) {
|
||||
if (!(await gitAvailable())) throw new Error('Git ist nicht installiert.')
|
||||
if (fs.existsSync(path.join(projectPath, '.git'))) throw new Error('Ist schon ein Git-Repository.')
|
||||
const r = await run('git', ['init', '-b', 'main', projectPath])
|
||||
if (!r.ok) throw new Error(r.stderr.trim() || 'git init fehlgeschlagen')
|
||||
}
|
||||
|
||||
// The user's SSH public key (to paste into GitHub/GitLab), or null.
|
||||
function sshKey() {
|
||||
const dir = path.join(process.env.USERPROFILE || require('os').homedir(), '.ssh')
|
||||
for (const n of ['id_ed25519.pub', 'id_ecdsa.pub', 'id_rsa.pub']) {
|
||||
try { return { file: path.join(dir, n), key: fs.readFileSync(path.join(dir, n), 'utf-8').trim() } } catch {}
|
||||
}
|
||||
return null
|
||||
}
|
||||
|
||||
module.exports = { gitInfo, setRemote, initRepo, sshKey }
|
||||
70
lib/icons.js
Normal file
70
lib/icons.js
Normal file
@@ -0,0 +1,70 @@
|
||||
// Finds a real app icon in a project (Android launcher icon, .ico, icon.png, logo).
|
||||
// Bounded breadth-first walk; results are cached because the list endpoint
|
||||
// asks for every project.
|
||||
const fs = require('fs')
|
||||
const path = require('path')
|
||||
const { SKIP } = require('./tech')
|
||||
|
||||
const EXTRA_SKIP = new Set(['Packages', 'test', 'tests', 'node_modules', 'PackageCache'])
|
||||
const MAX_DEPTH = 8
|
||||
const MAX_ENTRIES = 8000
|
||||
const TTL_MS = 10 * 60 * 1000
|
||||
const cache = new Map() // projectPath -> { result, at }
|
||||
|
||||
function score(rel, fileName) {
|
||||
const lower = fileName.toLowerCase()
|
||||
const ext = path.extname(lower)
|
||||
if (!['.png', '.ico', '.webp', '.jpg', '.jpeg', '.svg'].includes(ext)) return -1
|
||||
const base = path.basename(lower, ext)
|
||||
const relL = rel.toLowerCase().replace(/\\/g, '/')
|
||||
let s = -1
|
||||
if (relL.includes('mipmap') && base.startsWith('ic_launcher')) {
|
||||
s = 100
|
||||
const m = relL.match(/mipmap-(x*)hdpi/)
|
||||
if (m) s += m[1].length * 2
|
||||
if (/foreground|background|monochrome/.test(base)) s -= 30
|
||||
if (base.includes('round')) s -= 1
|
||||
} else if (ext === '.ico') s = 85
|
||||
else if (/^(app[_-]?icon|icon|appicon|launcher[_-]?icon|store[_-]?icon|favicon)([_-]?\d+)?$/.test(base) || /^(app[_-]?icon|icon)[_-]/.test(base)) s = 75
|
||||
else if (/^logo([_-]|$)/.test(base)) s = 50
|
||||
return s
|
||||
}
|
||||
|
||||
function scan(projectPath) {
|
||||
const queue = [{ dir: projectPath, depth: 0 }]
|
||||
let seen = 0
|
||||
let best = null
|
||||
let bestScore = -1
|
||||
while (queue.length) {
|
||||
const { dir, depth } = queue.shift()
|
||||
let entries
|
||||
try { entries = fs.readdirSync(dir, { withFileTypes: true }) } catch { continue }
|
||||
for (const e of entries) {
|
||||
if (++seen > MAX_ENTRIES) return best
|
||||
if (e.isDirectory()) {
|
||||
if (depth < MAX_DEPTH && !e.name.startsWith('.') && !SKIP.has(e.name) && !EXTRA_SKIP.has(e.name)) {
|
||||
queue.push({ dir: path.join(dir, e.name), depth: depth + 1 })
|
||||
}
|
||||
continue
|
||||
}
|
||||
if (!e.isFile()) continue
|
||||
const s = score(path.relative(projectPath, dir), e.name)
|
||||
if (s > bestScore) { bestScore = s; best = path.join(dir, e.name) }
|
||||
}
|
||||
}
|
||||
return best
|
||||
}
|
||||
|
||||
// -> absolute path of the icon, or null
|
||||
function findIcon(projectPath) {
|
||||
const c = cache.get(projectPath)
|
||||
if (c && Date.now() - c.at < TTL_MS) return c.result
|
||||
const result = scan(projectPath)
|
||||
cache.set(projectPath, { result, at: Date.now() })
|
||||
return result
|
||||
}
|
||||
|
||||
function forget(projectPath) { cache.delete(projectPath) }
|
||||
function clear() { cache.clear() }
|
||||
|
||||
module.exports = { findIcon, forget, clear }
|
||||
91
lib/itch.js
Normal file
91
lib/itch.js
Normal file
@@ -0,0 +1,91 @@
|
||||
// itch.io: which projects are published. Reads the public profile page (settings
|
||||
// "itchProfile", e.g. https://sn09.itch.io) - no API key, no login - and matches the
|
||||
// game titles/links to project names. A project can override it in .dashboard.json:
|
||||
// "itch": "" automatic (match by name)
|
||||
// "itch": "<url>" this page (manual, also for games not listed on the profile)
|
||||
// "itch": "-" not on itch.io (switch the automatic match off)
|
||||
const settings = require('./settings')
|
||||
|
||||
const TTL_MS = 60 * 60 * 1000
|
||||
const state = { profile: '', games: [], at: 0, error: null }
|
||||
let pending = null
|
||||
|
||||
const norm = (s) => String(s).toLowerCase().replace(/[^a-z0-9]/g, '')
|
||||
|
||||
function profileUrl() {
|
||||
return (settings.get().itchProfile ?? '').replace(/\/+$/, '')
|
||||
}
|
||||
|
||||
// <a ... href="https://x.itch.io/slug" class="title game_link">Title</a>
|
||||
function parse(html, profile) {
|
||||
const games = []
|
||||
const seen = new Set()
|
||||
const re = /<a\b[^>]*\bclass="[^"]*\btitle game_link\b[^"]*"[^>]*>([^<]*)<\/a>/g
|
||||
for (const m of html.matchAll(re)) {
|
||||
const href = m[0].match(/\bhref="([^"]+)"/)?.[1]
|
||||
if (!href || seen.has(href)) continue
|
||||
seen.add(href)
|
||||
const title = m[1].replace(/&/g, '&').replace(/'/g, "'").replace(/"/g, '"').trim()
|
||||
games.push({ title, url: href, slug: href.replace(profile + '/', '').replace(/\/.*$/, '') })
|
||||
}
|
||||
return games
|
||||
}
|
||||
|
||||
async function refresh() {
|
||||
const profile = profileUrl()
|
||||
if (!profile) { Object.assign(state, { profile: '', games: [], at: Date.now(), error: null }); return state }
|
||||
if (pending) return pending
|
||||
pending = (async () => {
|
||||
try {
|
||||
const res = await fetch(profile + '/', { headers: { 'User-Agent': 'ProjectDashboard' }, signal: AbortSignal.timeout(10000) })
|
||||
if (!res.ok) throw new Error(`itch.io antwortet ${res.status}`)
|
||||
const games = parse(await res.text(), profile)
|
||||
Object.assign(state, { profile, games, at: Date.now(), error: null })
|
||||
} catch (e) {
|
||||
// keep the last good list; retry after a few minutes instead of an hour
|
||||
Object.assign(state, { profile, at: Date.now() - TTL_MS + 5 * 60 * 1000, error: String(e.message ?? e) })
|
||||
} finally { pending = null }
|
||||
return state
|
||||
})()
|
||||
return pending
|
||||
}
|
||||
|
||||
// For the project list: fresh enough data, but never hold the page up for long.
|
||||
async function ensure(maxWaitMs = 3000) {
|
||||
if (state.profile !== profileUrl() || Date.now() - state.at > TTL_MS) {
|
||||
const p = refresh()
|
||||
if (!state.games.length) await Promise.race([p, new Promise((r) => setTimeout(r, maxWaitMs))])
|
||||
}
|
||||
return state
|
||||
}
|
||||
|
||||
// Same name, or the itch title is the project name plus a short suffix
|
||||
// ("DataOrganizer" -> "Data Organizer Ultra"). Not the other way round, so
|
||||
// "CatMaus 2" does not take over "CatMaus".
|
||||
function autoMatch(name) {
|
||||
const pn = norm(name)
|
||||
if (!pn) return null
|
||||
return state.games.find((g) => norm(g.title) === pn || norm(g.slug) === pn)
|
||||
?? state.games.find((g) => pn.length >= 5 && norm(g.title).startsWith(pn) && norm(g.title).length - pn.length <= 6)
|
||||
?? null
|
||||
}
|
||||
|
||||
// -> { url, title, source: 'manual' | 'auto' } or null (not published / switched off)
|
||||
function forProject(name, manual) {
|
||||
const m = (manual ?? '').trim()
|
||||
if (m === '-') return null
|
||||
if (/^https?:\/\//i.test(m)) {
|
||||
const g = state.games.find((x) => x.url.replace(/\/+$/, '') === m.replace(/\/+$/, ''))
|
||||
return { url: m, title: g?.title ?? '', source: 'manual' }
|
||||
}
|
||||
const g = autoMatch(name)
|
||||
return g ? { url: g.url, title: g.title, source: 'auto' } : null
|
||||
}
|
||||
|
||||
// Games on the profile that no project claims (to spot a missing manual link).
|
||||
function unmatched(claimedUrls) {
|
||||
const set = new Set(claimedUrls.map((u) => u.replace(/\/+$/, '')))
|
||||
return state.games.filter((g) => !set.has(g.url.replace(/\/+$/, '')))
|
||||
}
|
||||
|
||||
module.exports = { ensure, refresh, forProject, unmatched, state, parse }
|
||||
81
lib/proc.js
Normal file
81
lib/proc.js
Normal file
@@ -0,0 +1,81 @@
|
||||
// Small process helpers: run a command and collect its output (never throws),
|
||||
// run async work with limited concurrency, and open a visible console window.
|
||||
const { execFile, spawn } = require('child_process')
|
||||
const fs = require('fs')
|
||||
const path = require('path')
|
||||
|
||||
const RUN_DIR = path.join(__dirname, '..', '.cache', 'run')
|
||||
|
||||
function run(cmd, args, opts = {}) {
|
||||
return new Promise((resolve) => {
|
||||
execFile(cmd, args, {
|
||||
encoding: 'utf-8',
|
||||
timeout: opts.timeout ?? 5000,
|
||||
windowsHide: true,
|
||||
maxBuffer: 64 * 1024 * 1024,
|
||||
cwd: opts.cwd,
|
||||
}, (err, stdout, stderr) => resolve({
|
||||
ok: !err,
|
||||
code: err ? (typeof err.code === 'number' ? err.code : -1) : 0,
|
||||
stdout: stdout ?? '',
|
||||
stderr: stderr ?? '',
|
||||
}))
|
||||
})
|
||||
}
|
||||
|
||||
async function pool(items, size, fn) {
|
||||
const out = new Array(items.length)
|
||||
let next = 0
|
||||
const workers = Array.from({ length: Math.min(size, items.length) }, async () => {
|
||||
while (next < items.length) {
|
||||
const i = next++
|
||||
out[i] = await fn(items[i], i)
|
||||
}
|
||||
})
|
||||
await Promise.all(workers)
|
||||
return out
|
||||
}
|
||||
|
||||
// Paths end up quoted inside a .cmd file ("cd /d "<cwd>""), so they must not
|
||||
// contain quotes, % (variable expansion) or line breaks.
|
||||
function assertSafe(s) {
|
||||
if (/["%\r\n]/.test(s)) throw new Error(`unsupported character in: ${s}`)
|
||||
}
|
||||
|
||||
// Opens a new, visible cmd window in `cwd` that runs `command` and stays open.
|
||||
// The command is written into a small .cmd file, so no shell quoting through
|
||||
// spawn is needed. `echo on` makes cmd print the command before it runs.
|
||||
// Commands may contain quotes (call "x.bat", py "main.py"); a line break is
|
||||
// refused, and % is doubled so file names with % stay literal – except for
|
||||
// the user's own start command (raw), where %VAR% may be meant.
|
||||
function openConsole(title, cwd, command, { raw = false } = {}) {
|
||||
assertSafe(cwd)
|
||||
if (/[\r\n]/.test(command)) throw new Error('Zeilenumbruch im Befehl')
|
||||
if (!raw) command = command.replace(/%/g, '%%')
|
||||
fs.mkdirSync(RUN_DIR, { recursive: true })
|
||||
const slug = title.replace(/[^\w.-]+/g, '_').slice(0, 60)
|
||||
const file = path.join(RUN_DIR, `${slug}.cmd`)
|
||||
const safeTitle = title.replace(/[^\w .:-]+/g, ' ')
|
||||
fs.writeFileSync(file, [
|
||||
'@echo off',
|
||||
`title ${safeTitle}`,
|
||||
`cd /d "${cwd}"`,
|
||||
'echo on',
|
||||
command,
|
||||
'',
|
||||
].join('\r\n'))
|
||||
spawn('cmd.exe', ['/c', `start "" cmd /k "${file}"`], {
|
||||
windowsVerbatimArguments: true, detached: true, stdio: 'ignore',
|
||||
}).unref()
|
||||
}
|
||||
|
||||
// Starts a GUI program / opens a file with its default app, detached.
|
||||
// A start error (file gone, no permission) must not crash the server: without an
|
||||
// 'error' listener Node throws it as an uncaught exception.
|
||||
function openDetached(exe, args = [], cwd) {
|
||||
const child = spawn(exe, args, { detached: true, stdio: 'ignore', cwd })
|
||||
child.on('error', (e) => console.error(`start failed: ${exe}: ${e.message}`))
|
||||
child.unref()
|
||||
}
|
||||
|
||||
module.exports = { run, pool, openConsole, openDetached, assertSafe }
|
||||
284
lib/settings.js
Normal file
284
lib/settings.js
Normal file
@@ -0,0 +1,284 @@
|
||||
// User settings: which folder holds the projects and where backups go.
|
||||
// Stored in <DATA>\settings.json. DATA is DASHBOARD_DATA (set by the portable
|
||||
// exe: %LOCALAPPDATA%\ProjectDashboard\data) or, when run from source, the
|
||||
// app's own .cache folder.
|
||||
//
|
||||
// Michi's setup (app inside <Projekte>\_Tools\ProjectDashboard) needs no
|
||||
// settings file: the projects folder is two levels up and the backup settings
|
||||
// come from <Projekte>\_Tools\Backup\backup-config.json, which is also kept in
|
||||
// sync on save because backup-projekte.bat reads it.
|
||||
const fs = require('fs')
|
||||
const path = require('path')
|
||||
|
||||
const APP_DIR = path.join(__dirname, '..')
|
||||
const DATA_DIR = process.env.DASHBOARD_DATA
|
||||
? path.resolve(process.env.DASHBOARD_DATA)
|
||||
: path.join(APP_DIR, '.cache', process.env.DASHBOARD_ROOT ? 'test' : '') // test instances never touch real data
|
||||
const FILE = path.join(DATA_DIR, 'settings.json')
|
||||
|
||||
// ".bin": build output (e.g. tests\.bin) – WD MyCloud shares hide folders with that name, so it can't be backed up there anyway
|
||||
const DEFAULT_EXCLUDE_DIRS = ['node_modules', '__pycache__', '.gradle', '.venv', 'venv', '.venv-tts', '.bin']
|
||||
const DEFAULT_EXCLUDE_FILES = ['Thumbs.db', 'desktop.ini', '~$*']
|
||||
|
||||
// <X>\_Tools\ProjectDashboard → X
|
||||
function devRoot() {
|
||||
const parent = path.dirname(APP_DIR)
|
||||
return path.basename(parent).toLowerCase() === '_tools' ? path.dirname(parent) : ''
|
||||
}
|
||||
|
||||
const legacyBackupFile = (root) => (root ? path.join(root, '_Tools', 'Backup', 'backup-config.json') : '')
|
||||
|
||||
function readJson(file) {
|
||||
// strip a BOM (PowerShell's "Out-File -Encoding utf8" writes one)
|
||||
try { return JSON.parse(fs.readFileSync(file, 'utf-8').replace(/^/, '')) } catch { return null }
|
||||
}
|
||||
|
||||
// short display name: "MYCLOUD-NESYFV" for \\MYCLOUD-NESYFV\..., "E: Backup" for E:\Backup
|
||||
function targetName(t) {
|
||||
const unc = t.match(/^\\\\([^\\]+)/)
|
||||
if (unc) return unc[1]
|
||||
const drive = t.match(/^([A-Za-z]:)/)
|
||||
return drive ? `${drive[1]} ${path.basename(t)}`.trim() : path.basename(t)
|
||||
}
|
||||
const newId = () => Math.random().toString(36).slice(2, 10)
|
||||
// one path (older settings / backup-config.json) -> target list
|
||||
const targetsFrom = (p) => (p ? [{ id: 'main', name: targetName(p), path: p }] : [])
|
||||
|
||||
// Projects folders ("roots"): several can be registered, one is active at a time.
|
||||
// Display name: folder name, "D:" for a drive root.
|
||||
const rootName = (p) => path.basename(p) || p.replace(/[\\/]+$/, '')
|
||||
const rootsFrom = (p) => (p ? [{ id: 'main', name: rootName(p), path: p }] : [])
|
||||
const MAX_ROOTS = 30
|
||||
const samePath = (a, b) => path.resolve(a).toLowerCase() === path.resolve(b).toLowerCase()
|
||||
const inside = (child, parent) => path.resolve(child).toLowerCase().startsWith(path.resolve(parent).toLowerCase().replace(/[\\/]+$/, '') + path.sep)
|
||||
|
||||
function defaults() {
|
||||
const root = process.env.DASHBOARD_ROOT ? path.resolve(process.env.DASHBOARD_ROOT) : devRoot()
|
||||
const legacy = readJson(legacyBackupFile(root))
|
||||
return {
|
||||
roots: rootsFrom(root),
|
||||
projectsRoot: root,
|
||||
// public itch.io profile ("veröffentlicht" on the cards); Michi's setup knows his
|
||||
itchProfile: devRoot() && !process.env.DASHBOARD_ROOT ? 'https://sn09.itch.io' : '',
|
||||
backup: {
|
||||
// several targets possible (NAS, USB disk, ...); each has its own backup state
|
||||
targets: Array.isArray(legacy?.targets) ? legacy.targets : targetsFrom(legacy?.target ?? ''),
|
||||
excludeDirs: legacy?.excludeDirs ?? DEFAULT_EXCLUDE_DIRS,
|
||||
excludeFiles: legacy?.excludeFiles ?? DEFAULT_EXCLUDE_FILES,
|
||||
},
|
||||
}
|
||||
}
|
||||
|
||||
let current = null
|
||||
|
||||
function load() {
|
||||
const d = defaults()
|
||||
const saved = process.env.DASHBOARD_ROOT && !process.env.DASHBOARD_DATA ? null : readJson(FILE)
|
||||
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
|
||||
// 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 }))
|
||||
: typeof saved?.projectsRoot === 'string' ? rootsFrom(saved.projectsRoot) : d.roots
|
||||
// an explicit DASHBOARD_ROOT always wins (tests)
|
||||
if (process.env.DASHBOARD_ROOT) roots = [{ id: 'env', name: rootName(path.resolve(process.env.DASHBOARD_ROOT)), path: path.resolve(process.env.DASHBOARD_ROOT) }]
|
||||
current = withActive({
|
||||
roots,
|
||||
activeRoots: Array.isArray(saved?.activeRoots) ? saved.activeRoots : [saved?.activeRoot],
|
||||
itchProfile: typeof saved?.itchProfile === 'string' ? saved.itchProfile : d.itchProfile,
|
||||
backup,
|
||||
})
|
||||
return current
|
||||
}
|
||||
|
||||
// Several folders can be shown at once: activeRoots = the selected ids (in list
|
||||
// order, at least one). activeRoot = the first of them, projectsRoot = its path.
|
||||
function withActive(s) {
|
||||
const want = new Set((s.activeRoots ?? [s.activeRoot]).filter(Boolean))
|
||||
let active = s.roots.filter((r) => want.has(r.id))
|
||||
if (!active.length && s.roots[0]) active = [s.roots[0]]
|
||||
const { activeRoot: _, ...rest } = s
|
||||
return { ...rest, activeRoots: active.map((r) => r.id), activeRoot: active[0]?.id ?? '', projectsRoot: active[0]?.path ?? '' }
|
||||
}
|
||||
|
||||
// the selected folders [{ id, name, path }]
|
||||
function activeRootList(s = get()) {
|
||||
return s.roots.filter((r) => s.activeRoots.includes(r.id))
|
||||
}
|
||||
|
||||
// What is written to settings.json (activeRoot/projectsRoot are derived, not stored).
|
||||
function persist(next) {
|
||||
const { projectsRoot, activeRoot, ...stored } = next
|
||||
fs.mkdirSync(DATA_DIR, { recursive: true })
|
||||
fs.writeFileSync(FILE, JSON.stringify(stored, null, 2))
|
||||
}
|
||||
|
||||
// Backups of several projects folders share the targets: the first folder goes
|
||||
// straight into the target (as before), the others into a subfolder - their path
|
||||
// below the first folder if they lie inside it, else their folder name.
|
||||
function backupSubdir(rootPath, s = get()) {
|
||||
const first = s.roots[0]?.path
|
||||
if (!first || !rootPath || samePath(rootPath, first)) return ''
|
||||
if (inside(rootPath, first)) return path.relative(path.resolve(first), path.resolve(rootPath))
|
||||
return rootName(path.resolve(rootPath)).replace(/[:\\/]/g, '') || 'Projekte'
|
||||
}
|
||||
|
||||
function get() { return current ?? load() }
|
||||
|
||||
function isDir(p) {
|
||||
try { return fs.statSync(p).isDirectory() } catch { return false }
|
||||
}
|
||||
|
||||
function configured() {
|
||||
const s = get()
|
||||
return !!s.projectsRoot && isDir(s.projectsRoot)
|
||||
}
|
||||
|
||||
const cleanList = (v, fallback) =>
|
||||
Array.isArray(v) ? [...new Set(v.map((x) => String(x).trim()).filter(Boolean))].slice(0, 50) : fallback
|
||||
|
||||
// Validates and stores new settings. Throws with a German message on bad input.
|
||||
function save(input) {
|
||||
const s = get()
|
||||
// path.resolve normalises ("D:\x\" → "D:\x") but keeps drive roots intact ("E:\")
|
||||
const norm = (v) => (v.trim() ? path.resolve(v.trim().replace(/^"(.*)"$/, '$1')) : '')
|
||||
let roots = s.roots
|
||||
let activeRoots = Array.isArray(input.activeRoots) ? input.activeRoots.map(String)
|
||||
: typeof input.activeRoot === 'string' ? [input.activeRoot] : s.activeRoots
|
||||
let activeRoot = activeRoots[0] // only for the old single-folder form below
|
||||
if (Array.isArray(input.roots)) {
|
||||
const renamed = new Map()
|
||||
roots = []
|
||||
for (const r of input.roots.slice(0, MAX_ROOTS)) {
|
||||
const p = typeof r?.path === 'string' ? norm(r.path) : ''
|
||||
if (!p) continue
|
||||
if (!isDir(p)) throw new Error(`Projektordner existiert nicht: ${p}`)
|
||||
if (roots.some((x) => samePath(x.path, p))) throw new Error(`Projektordner doppelt: ${p}`)
|
||||
const old = s.roots.find((x) => x.id === r.id)
|
||||
roots.push({
|
||||
id: old && samePath(old.path, p) ? old.id : newId(),
|
||||
name: String(r.name ?? '').trim().slice(0, 40) || rootName(p),
|
||||
path: p,
|
||||
})
|
||||
// a selected folder stays selected even if its path (and so its id) changed
|
||||
if (r.id) renamed.set(String(r.id), roots.at(-1).id)
|
||||
}
|
||||
if (!roots.length) throw new Error('Mindestens ein Projektordner ist nötig.')
|
||||
activeRoots = activeRoots.map((id) => renamed.get(id)).filter(Boolean)
|
||||
} else if (typeof input.projectsRoot === 'string') {
|
||||
// old single-folder form: replaces the active folder
|
||||
const p = norm(input.projectsRoot)
|
||||
if (!p || !isDir(p)) throw new Error('Der Projektordner existiert nicht.')
|
||||
const i = Math.max(0, roots.findIndex((r) => r.id === activeRoot))
|
||||
const existing = roots.find((r) => samePath(r.path, p))
|
||||
if (existing) activeRoots = [existing.id]
|
||||
else {
|
||||
roots = roots.slice()
|
||||
roots[i] = { id: newId(), name: rootName(p), path: p }
|
||||
activeRoots = [roots[i].id]
|
||||
}
|
||||
}
|
||||
const sel = withActive({ roots, activeRoots })
|
||||
const projectsRoot = sel.projectsRoot
|
||||
if (!projectsRoot || !isDir(projectsRoot)) throw new Error('Der Projektordner existiert nicht.')
|
||||
let targets = s.backup.targets
|
||||
if (Array.isArray(input.targets)) {
|
||||
targets = []
|
||||
const seen = new Set()
|
||||
for (const t of input.targets.slice(0, 10)) {
|
||||
const p = typeof t?.path === 'string' ? norm(t.path) : ''
|
||||
if (!p) continue
|
||||
const a = p.toLowerCase()
|
||||
if (seen.has(a)) throw new Error(`Backup-Ziel doppelt: ${p}`)
|
||||
seen.add(a)
|
||||
if (fs.existsSync(p) && !isDir(p)) throw new Error(`Backup-Ziel ist eine Datei, kein Ordner: ${p}`)
|
||||
if (!isDir(p) && !isDir(path.dirname(p))) throw new Error(`Backup-Ziel nicht erreichbar (Laufwerk/NAS angeschlossen?): ${p}`)
|
||||
const old = s.backup.targets.find((x) => x.id === t.id)
|
||||
targets.push({
|
||||
// a changed path is a new target (its backup state starts fresh)
|
||||
id: old && old.path.toLowerCase() === a ? old.id : newId(),
|
||||
name: String(t.name ?? '').trim().slice(0, 40) || targetName(p),
|
||||
path: p,
|
||||
})
|
||||
}
|
||||
} else if (typeof input.backupTarget === 'string') {
|
||||
targets = targetsFrom(norm(input.backupTarget)) // old single-target form
|
||||
}
|
||||
// checked for every save, so a newly added projects folder can't hold a backup target either
|
||||
for (const t of targets) {
|
||||
const clash = roots.find((r) => samePath(t.path, r.path) || inside(t.path, r.path) || inside(r.path, t.path))
|
||||
if (clash) throw new Error(`Das Backup-Ziel darf nicht in einem Projektordner liegen (und keinen enthalten): ${t.path} ↔ ${clash.path}`)
|
||||
}
|
||||
let itchProfile = s.itchProfile ?? ''
|
||||
if (typeof input.itchProfile === 'string') {
|
||||
const v = input.itchProfile.trim().replace(/\/+$/, '')
|
||||
// "sn09" or "sn09.itch.io" is enough
|
||||
itchProfile = !v ? '' : /^https?:\/\//i.test(v) ? v : `https://${v.includes('.') ? v : `${v}.itch.io`}`
|
||||
if (itchProfile && !/^https:\/\/[a-z0-9-]+\.itch\.io$/i.test(itchProfile)) throw new Error('itch.io-Profil: z. B. https://name.itch.io')
|
||||
}
|
||||
const next = withActive({
|
||||
roots,
|
||||
activeRoots: sel.activeRoots,
|
||||
itchProfile,
|
||||
backup: {
|
||||
targets,
|
||||
excludeDirs: cleanList(input.excludeDirs, s.backup.excludeDirs),
|
||||
excludeFiles: cleanList(input.excludeFiles, s.backup.excludeFiles),
|
||||
},
|
||||
})
|
||||
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)
|
||||
if (legacy && fs.existsSync(legacy)) {
|
||||
fs.writeFileSync(legacy, JSON.stringify({ source: roots[0].path, target: targets[0]?.path ?? '', targets, excludeDirs: next.backup.excludeDirs, excludeFiles: next.backup.excludeFiles }, null, 2) + '\n')
|
||||
}
|
||||
current = next
|
||||
return current
|
||||
}
|
||||
|
||||
// Quick switch (dropdown next to the logo): which folders are shown (one id or a list).
|
||||
function setActive(ids) {
|
||||
const s = get()
|
||||
const list = (Array.isArray(ids) ? ids : [ids]).map(String)
|
||||
const sel = s.roots.filter((x) => list.includes(x.id))
|
||||
if (!sel.length) throw new Error('Projektordner nicht gefunden.')
|
||||
const gone = sel.find((r) => !isDir(r.path))
|
||||
if (gone) throw new Error(`Projektordner nicht erreichbar: ${gone.path}`)
|
||||
current = withActive({ ...s, activeRoots: sel.map((r) => r.id) })
|
||||
persist(current)
|
||||
return current
|
||||
}
|
||||
|
||||
// Adds projects folders (dropdown "Ordner hinzufügen" / "Mehrere einlesen");
|
||||
// folders already in the list are skipped. activate: show (only) the new ones.
|
||||
function addRoots(paths, activate = false) {
|
||||
const s = get()
|
||||
const fresh = (Array.isArray(paths) ? paths : [])
|
||||
.filter((p) => typeof p === 'string' && p.trim())
|
||||
.filter((p, i, all) => !s.roots.some((r) => samePath(r.path, p)) && all.findIndex((q) => samePath(q, p)) === i)
|
||||
if (!fresh.length) return { settings: s, added: [] }
|
||||
const before = new Set(s.roots.map((r) => r.id))
|
||||
const next = save({ roots: [...s.roots, ...fresh.map((p) => ({ id: '', name: '', path: p }))] })
|
||||
const added = next.roots.filter((r) => !before.has(r.id))
|
||||
return { settings: activate && added[0] ? setActive(added.map((r) => r.id)) : next, added }
|
||||
}
|
||||
|
||||
// Direct subfolders of a folder (for "Mehrere einlesen"), with how many folders each holds.
|
||||
function subfolders(dir) {
|
||||
const p = typeof dir === 'string' && dir.trim() ? path.resolve(dir.trim().replace(/^"(.*)"$/, '$1')) : ''
|
||||
if (!p || !isDir(p)) throw new Error('Ordner existiert nicht.')
|
||||
const skip = new Set(['$recycle.bin', 'system volume information', 'recovery', 'config.msi', 'node_modules'])
|
||||
const list = fs.readdirSync(p, { withFileTypes: true })
|
||||
.filter((e) => e.isDirectory() && !e.name.startsWith('.') && !skip.has(e.name.toLowerCase()))
|
||||
.map((e) => {
|
||||
const full = path.join(p, e.name)
|
||||
let count = 0
|
||||
try { count = fs.readdirSync(full, { withFileTypes: true }).filter((x) => x.isDirectory() && !x.name.startsWith('.')).length } catch {}
|
||||
return { name: e.name, path: full, count }
|
||||
})
|
||||
.sort((a, b) => a.name.localeCompare(b.name, 'de'))
|
||||
return { path: p, folders: list.slice(0, 200) }
|
||||
}
|
||||
|
||||
module.exports = { get, load, save, setActive, addRoots, activeRootList, subfolders, backupSubdir, configured, targetName, DATA_DIR, APP_DIR, DEFAULT_EXCLUDE_DIRS }
|
||||
135
lib/storage.js
Normal file
135
lib/storage.js
Normal file
@@ -0,0 +1,135 @@
|
||||
// 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 }
|
||||
320
lib/tech.js
Normal file
320
lib/tech.js
Normal file
@@ -0,0 +1,320 @@
|
||||
// Detects what a project is made of (Unity, Node, .NET, ...) from marker files
|
||||
// and builds the list of start actions. Actions are always built here on the
|
||||
// server; the browser only sends back an action id.
|
||||
const fs = require('fs')
|
||||
const path = require('path')
|
||||
|
||||
const SKIP = new Set([
|
||||
'node_modules', '.git', 'dist', 'build', 'builds', 'out', 'bin', 'obj', 'target', 'venv', '.venv', 'env',
|
||||
'__pycache__', '.gradle', '.idea', '.vscode', 'Library', 'Temp', 'Logs', 'output', '_archiv', '_Archiv',
|
||||
'sprite-generator', 'Spritegenerator', 'sprite-gen', 'design-gen', '.expo', '.claude',
|
||||
])
|
||||
const NPM_SCRIPTS = ['dev', 'start', 'electron', 'android', 'web', 'build', 'preview', 'serve', 'tauri']
|
||||
const PY_MAIN = ['main.py', 'app.py', 'run.py', 'game.py', 'server.py', 'gui.py']
|
||||
const UNITY_EDITORS = 'C:\\Program Files\\Unity\\Hub\\Editor'
|
||||
const UNITY_HUB = 'C:\\Program Files\\Unity Hub\\Unity Hub.exe'
|
||||
|
||||
function ls(dir) {
|
||||
try { return fs.readdirSync(dir, { withFileTypes: true }) } catch { return [] }
|
||||
}
|
||||
function readJson(file) {
|
||||
try { return JSON.parse(fs.readFileSync(file, 'utf-8')) } catch { return null }
|
||||
}
|
||||
|
||||
// Looks at the project root and its direct subfolders (e.g. "DesktopAnt\DesktopAnt").
|
||||
function detect(projectPath) {
|
||||
const subdirs = ls(projectPath)
|
||||
.filter((e) => e.isDirectory() && !e.name.startsWith('.') && !SKIP.has(e.name))
|
||||
.map((e) => path.join(projectPath, e.name))
|
||||
const found = []
|
||||
for (const dir of [projectPath, ...subdirs]) {
|
||||
const isRoot = dir === projectPath
|
||||
const entries = ls(dir)
|
||||
const names = new Set(entries.map((e) => e.name))
|
||||
const files = entries.filter((e) => e.isFile()).map((e) => e.name)
|
||||
const rel = path.relative(projectPath, dir)
|
||||
const unity = names.has('Assets') && names.has('ProjectSettings')
|
||||
|
||||
if (unity) found.push({ type: 'unity', dir, rel })
|
||||
if (names.has('package.json')) {
|
||||
const pkg = readJson(path.join(dir, 'package.json')) ?? {}
|
||||
const deps = { ...(pkg.dependencies ?? {}), ...(pkg.devDependencies ?? {}) }
|
||||
const flavor = deps.electron ? 'electron' : deps.expo ? 'expo' : deps['@capacitor/core'] ? 'capacitor' : deps.vite ? 'vite' : deps.react ? 'react' : null
|
||||
found.push({
|
||||
type: 'node', dir, rel, flavor,
|
||||
scripts: Object.keys(pkg.scripts ?? {}),
|
||||
scriptCmds: pkg.scripts ?? {},
|
||||
needsInstall: Object.keys(deps).length > 0 && !names.has('node_modules'),
|
||||
})
|
||||
}
|
||||
if (!unity) {
|
||||
const sln = files.filter((f) => /\.sln$/i.test(f))
|
||||
const proj = files.filter((f) => /\.(cs|fs|vb)proj$/i.test(f))
|
||||
if (sln.length || proj.length) found.push({ type: 'dotnet', dir, rel, sln, proj })
|
||||
}
|
||||
if (names.has('pubspec.yaml')) found.push({ type: 'flutter', dir, rel })
|
||||
if (['build.gradle', 'build.gradle.kts', 'settings.gradle', 'settings.gradle.kts'].some((n) => names.has(n))) {
|
||||
found.push({ type: 'android', dir, rel, gradlew: names.has('gradlew.bat') })
|
||||
}
|
||||
if (names.has('CMakeLists.txt')) found.push({ type: 'cmake', dir, rel })
|
||||
const ino = files.filter((f) => /\.ino$/i.test(f))
|
||||
if (ino.length) found.push({ type: 'arduino', dir, rel, ino })
|
||||
if (isRoot) {
|
||||
const py = files.filter((f) => /\.py$/i.test(f))
|
||||
if (py.length || names.has('requirements.txt') || names.has('pyproject.toml')) {
|
||||
const venv = path.join(dir, '.venv', 'Scripts', 'python.exe')
|
||||
found.push({ type: 'python', dir, rel, py, venv: fs.existsSync(venv) ? venv : null })
|
||||
}
|
||||
}
|
||||
}
|
||||
return found
|
||||
}
|
||||
|
||||
const TYPE_LABEL = {
|
||||
unity: 'Unity', node: 'Node', dotnet: '.NET', flutter: 'Flutter', android: 'Android',
|
||||
cmake: 'C++/CMake', arduino: 'Arduino', python: 'Python', web: 'Web',
|
||||
}
|
||||
|
||||
function summary(found) {
|
||||
const labels = []
|
||||
for (const f of found) {
|
||||
const l = f.type === 'node' && f.flavor ? f.flavor[0].toUpperCase() + f.flavor.slice(1) : TYPE_LABEL[f.type]
|
||||
if (!labels.includes(l)) labels.push(l)
|
||||
}
|
||||
return { types: labels, needsInstall: found.some((f) => f.type === 'node' && f.needsInstall) }
|
||||
}
|
||||
|
||||
function unityEditor(dir) {
|
||||
try {
|
||||
const txt = fs.readFileSync(path.join(dir, 'ProjectSettings', 'ProjectVersion.txt'), 'utf-8')
|
||||
const ver = txt.match(/m_EditorVersion:\s*(\S+)/)?.[1]
|
||||
const exe = ver && path.join(UNITY_EDITORS, ver, 'Editor', 'Unity.exe')
|
||||
return { ver, exe: exe && fs.existsSync(exe) ? exe : null }
|
||||
} catch { return { ver: null, exe: null } }
|
||||
}
|
||||
|
||||
// ── startable programs & scripts ─────────────────────────────────────────
|
||||
// Folders that never hold the project's own program (tests, drivers, caches, ...)
|
||||
const EXE_SKIP_DIRS = /^(node_modules|\.git|\.gradle|\.gradle-local|gradle|Library|Temp|Logs|obj|\.venv.*|venv|env|__pycache__|tests?|Tests|symbols|CMakeFiles|_deps|drivers?|_archiv|output|sprite-?generator|spritegenerator|sprite-?gen|design-?gen|\.expo|\.idea|\.vscode|\.cache|\.claude|android|ios|packages|Packages)$/i
|
||||
// Helper executables that are not "the app"
|
||||
const EXE_SKIP_NAMES = /^(unins.*|.*setup.*|.*install.*|.*redist.*|.*crash.?handler.*|createdump|butler|adb|aapt2?|ffmpeg|ffprobe|7za?|python.*|pythonw|node|npm|remove|remover|elevate|squirrel|update|dotnet|apphost|notification_helper|chrome_.*|.*\.vshost)$/i
|
||||
// Programs that exist next to the real app but are not what you want to start first
|
||||
const EXE_SECONDARY = /(server|helper|updater|console|cli|worker|daemon|service)$/i
|
||||
const SCRIPT_SKIP = /^(gradlew|gradle|gen|ctlstisc)\.(bat|cmd)$/i
|
||||
// Where a copy of an exe came from - better sources win when the same exe exists several times
|
||||
function exeRank(rel) {
|
||||
const r = rel.toLowerCase()
|
||||
if (/(^|\\)publish[^\\]*\\/.test(r)) return 6
|
||||
if (/(^|\\)release\\/.test(r) && !/\\bin\\/.test(r)) return 5
|
||||
if (/(^|\\)(dist|builds?|spiel|game)\\/.test(r)) return 4
|
||||
if (!r.includes('\\')) return 4 // next to the project
|
||||
if (/\\bin\\release\\/.test(r) || /^bin\\release\\/.test(r)) return 3
|
||||
if (/\\bin\\debug\\/.test(r) || /^bin\\debug\\/.test(r)) return 1
|
||||
return 2
|
||||
}
|
||||
const norm = (s) => s.toLowerCase().replace(/[^a-z0-9]/g, '')
|
||||
|
||||
function walkFiles(root, maxDepth, test) {
|
||||
const out = []
|
||||
const queue = [{ dir: root, depth: 0 }]
|
||||
let seen = 0
|
||||
while (queue.length) {
|
||||
const { dir, depth } = queue.shift()
|
||||
for (const e of ls(dir)) {
|
||||
if (++seen > 20000) return out
|
||||
if (e.isDirectory()) {
|
||||
// "_name" subfolders hold vendored or archived stuff (_vbcable, _archiv, ...)
|
||||
if (depth < maxDepth && !EXE_SKIP_DIRS.test(e.name) && !e.name.startsWith('_')) queue.push({ dir: path.join(dir, e.name), depth: depth + 1 })
|
||||
} else if (e.isFile() && test(e.name)) out.push(path.join(dir, e.name))
|
||||
}
|
||||
}
|
||||
return out
|
||||
}
|
||||
|
||||
function ago(ms) {
|
||||
const d = Math.floor((Date.now() - ms) / 86400000)
|
||||
return d <= 0 ? 'heute' : d === 1 ? 'gestern' : d < 30 ? `vor ${d} T.` : d < 365 ? `vor ${Math.floor(d / 30)} Mon.` : `vor ${Math.floor(d / 365)} J.`
|
||||
}
|
||||
|
||||
// The project's own programs: one entry per exe name (best copy), the one
|
||||
// named like the project first, then newest.
|
||||
function findPrograms(name, projectPath) {
|
||||
const best = new Map()
|
||||
for (const file of walkFiles(projectPath, 6, (n) => /\.exe$/i.test(n) && !EXE_SKIP_NAMES.test(n.replace(/\.exe$/i, '')))) {
|
||||
const rel = path.relative(projectPath, file)
|
||||
let mtime = 0
|
||||
try { mtime = fs.statSync(file).mtimeMs } catch {}
|
||||
const key = path.basename(file).toLowerCase()
|
||||
const cand = { file, rel, mtime, rank: exeRank(rel) }
|
||||
const cur = best.get(key)
|
||||
if (!cur || cand.rank > cur.rank || (cand.rank === cur.rank && cand.mtime > cur.mtime)) best.set(key, cand)
|
||||
}
|
||||
const pn = norm(name)
|
||||
return [...best.values()]
|
||||
.map((c) => {
|
||||
const en = norm(path.basename(c.file, path.extname(c.file)))
|
||||
return { ...c, match: nameMatches(pn, en) ? 1 : 0, secondary: EXE_SECONDARY.test(en) ? 1 : 0 }
|
||||
})
|
||||
.sort((a, b) => (b.match - a.match) || (a.secondary - b.secondary) || (b.rank - a.rank) || (b.mtime - a.mtime))
|
||||
.slice(0, 12)
|
||||
}
|
||||
|
||||
// "TinyWold" (folder) should still match "TinyWorld.exe": contained, or a
|
||||
// common start of at least 5 letters.
|
||||
function nameMatches(projectNorm, exeNorm) {
|
||||
if (!projectNorm || !exeNorm) return false
|
||||
if (exeNorm.includes(projectNorm) || projectNorm.includes(exeNorm)) return true
|
||||
let i = 0
|
||||
while (i < projectNorm.length && i < exeNorm.length && projectNorm[i] === exeNorm[i]) i++
|
||||
return i >= 5
|
||||
}
|
||||
|
||||
// HTML pages that run by double-click: index.html up to 3 folders deep (game\index.html),
|
||||
// any .html directly in a release folder (single-file builds) and a root page named like
|
||||
// the project (Stammbaum\stammbaum.html). Pages that cannot run from file:// are left out:
|
||||
// ES modules (Vite dev page and built dist - browsers block module scripts on file://) and
|
||||
// absolute /paths. Those start via npm.
|
||||
const HTML_SKIP_PARTS = /(^|\\)(public|src|docs?|archive|_?archiv|mockups?|templates?|backups?|old|alt|kopie|copy|bak|node_modules|coverage|test-results|playwright-report|cache|\.cache)(\\|$)/i
|
||||
function findWebPages(name, projectPath) {
|
||||
const out = []
|
||||
const pn = norm(name)
|
||||
for (const file of walkFiles(projectPath, 3, (n) => /\.html?$/i.test(n))) {
|
||||
const rel = path.relative(projectPath, file)
|
||||
const dir = path.dirname(rel)
|
||||
const base = path.basename(file, path.extname(file))
|
||||
const isIndex = /^index$/i.test(base)
|
||||
const inRelease = /(^|\\)release$/i.test(dir)
|
||||
const namedRoot = dir === '.' && nameMatches(pn, norm(base))
|
||||
if (!isIndex && !inRelease && !namedRoot) continue
|
||||
if (HTML_SKIP_PARTS.test(dir)) continue
|
||||
let head = ''
|
||||
try { head = fs.readFileSync(file, 'utf-8').slice(0, 200000) } catch { continue }
|
||||
if (/<script[^>]+type=["']module["']/i.test(head) || /<script[^>]+src=["']\/(?!\/)/i.test(head) || /\/@vite\//.test(head)) continue
|
||||
let mtime = 0
|
||||
try { mtime = fs.statSync(file).mtimeMs } catch {}
|
||||
const rank = inRelease ? 3 : /^(game|spiel|web|www|app|html)(\\|$)/i.test(dir) ? 2 : dir === '.' ? 1 : 0
|
||||
out.push({ file, rel, mtime, rank })
|
||||
}
|
||||
// single-file release first, then game\index.html, then the root page
|
||||
return out.sort((a, b) => (b.rank - a.rank) || (b.mtime - a.mtime)).slice(0, 6)
|
||||
}
|
||||
|
||||
// How a file is started: exe directly, html/lnk with the default app, bat/cmd in a console.
|
||||
function fileAction(id, label, file, projectPath, detail) {
|
||||
const rel = path.relative(projectPath, file)
|
||||
const ext = path.extname(file).toLowerCase()
|
||||
const base = { id, label, group: 'Programm', rel, file, detail }
|
||||
if (ext === '.exe') return { ...base, kind: 'exe', exe: file, args: [], cwd: path.dirname(file) }
|
||||
if (ext === '.bat' || ext === '.cmd') return { ...base, kind: 'console', cwd: path.dirname(file), command: `call "${path.basename(file)}"` }
|
||||
return { ...base, kind: 'open' }
|
||||
}
|
||||
|
||||
// The program chosen in "Aktionen" (.dashboard.json "program", path inside the project)
|
||||
function resolveProgram(projectPath, program) {
|
||||
if (!program) return null
|
||||
const file = path.resolve(projectPath, program)
|
||||
if (!file.startsWith(projectPath + path.sep)) return null
|
||||
return { file, exists: fs.existsSync(file) && fs.statSync(file).isFile() }
|
||||
}
|
||||
|
||||
// .bat/.cmd in the project root and one level below (e.g. Spiel\3D-Ansicht.bat)
|
||||
function findScripts(projectPath) {
|
||||
return walkFiles(projectPath, 1, (n) => /\.(bat|cmd)$/i.test(n) && !SCRIPT_SKIP.test(n))
|
||||
.map((file) => {
|
||||
const base = path.basename(file)
|
||||
const group = /^(build|publish|deploy|release|make|compile|pack)/i.test(base) ? 'Bauen'
|
||||
: /(install|setup|einricht)/i.test(base) ? 'Einrichten' : 'Starten'
|
||||
return { file, rel: path.relative(projectPath, file), base, group }
|
||||
})
|
||||
.slice(0, 12)
|
||||
}
|
||||
|
||||
const where = (rel) => (rel ? ` (${rel})` : '')
|
||||
|
||||
// Every action: { id, label, group, kind, cwd, command | exe+args | file }
|
||||
// kind: console = visible cmd window, exe = start program, open = default app, vscode
|
||||
function actions(name, projectPath, found, meta, tools) {
|
||||
const list = [
|
||||
{ id: 'vscode', label: 'In VS Code öffnen', group: 'Öffnen', kind: 'vscode', cwd: projectPath },
|
||||
{ id: 'explorer', label: 'Ordner im Explorer', group: 'Öffnen', kind: 'open', file: projectPath },
|
||||
{ id: 'console', label: 'Konsole im Projekt', group: 'Öffnen', kind: 'console', cwd: projectPath, command: 'git status 2>nul' },
|
||||
]
|
||||
if (meta.start) list.push({ id: 'custom', label: `Eigener Start: ${meta.start}`, group: 'Starten', kind: 'console', cwd: projectPath, command: meta.start })
|
||||
|
||||
// the program chosen for ▶ comes first; a missing file stays visible so it can be fixed
|
||||
const chosen = resolveProgram(projectPath, meta.program)
|
||||
if (chosen?.exists) {
|
||||
list.push(fileAction('program', path.basename(chosen.file, path.extname(chosen.file)), chosen.file, projectPath, `${path.relative(projectPath, chosen.file)} · für ▶ festgelegt`))
|
||||
}
|
||||
const chosenFile = chosen?.exists ? chosen.file.toLowerCase() : null
|
||||
|
||||
for (const f of found) {
|
||||
const r = f.rel
|
||||
switch (f.type) {
|
||||
case 'node':
|
||||
if (f.needsInstall) list.push({ id: `npm-install:${r}`, label: `npm install${where(r)}`, group: 'Einrichten', kind: 'console', cwd: f.dir, command: 'npm install' })
|
||||
for (const s of NPM_SCRIPTS.filter((s) => f.scripts.includes(s))) {
|
||||
// a Vite dev server alone opens nothing visible - let it open the browser;
|
||||
// without node_modules the script would just fail, so install first
|
||||
const vite = /^\s*vite(\s|$)(?!.*\bbuild\b)/.test(f.scriptCmds?.[s] ?? '') && !/--open/.test(f.scriptCmds?.[s] ?? '')
|
||||
const cmd = `${f.needsInstall && s !== 'build' ? 'npm install && ' : ''}npm run ${s}${vite ? ' -- --open' : ''}`
|
||||
list.push({ id: `npm:${r}:${s}`, label: `npm run ${s}${where(r)}${vite ? ' (Browser)' : ''}`, group: s === 'build' ? 'Bauen' : 'Starten', kind: 'console', cwd: f.dir, command: cmd })
|
||||
}
|
||||
break
|
||||
case 'dotnet': {
|
||||
const target = f.sln[0] ?? f.proj[0]
|
||||
list.push({ id: `dotnet-build:${r}:${target}`, label: `dotnet build ${target}`, group: 'Bauen', kind: 'console', cwd: f.dir, command: `dotnet build "${target}"` })
|
||||
for (const p of f.proj.slice(0, 4)) list.push({ id: `dotnet-run:${r}:${p}`, label: `dotnet run ${p}`, group: 'Starten', kind: 'console', cwd: f.dir, command: `dotnet run --project "${p}"` })
|
||||
break
|
||||
}
|
||||
case 'flutter':
|
||||
list.push({ id: `flutter:${r}`, label: `flutter run${where(r)}`, group: 'Starten', kind: 'console', cwd: f.dir, command: 'flutter pub get && flutter run' })
|
||||
break
|
||||
case 'android':
|
||||
if (f.gradlew) list.push({ id: `gradle:${r}`, label: `Gradle assembleDebug${where(r)}`, group: 'Bauen', kind: 'console', cwd: f.dir, command: 'gradlew.bat assembleDebug' })
|
||||
break
|
||||
case 'unity': {
|
||||
const ed = unityEditor(f.dir)
|
||||
if (ed.exe) list.push({ id: `unity:${r}`, label: `In Unity ${ed.ver} öffnen${where(r)}`, group: 'Starten', kind: 'exe', exe: ed.exe, args: ['-projectPath', f.dir] })
|
||||
else if (fs.existsSync(UNITY_HUB)) list.push({ id: `unity-hub:${r}`, label: `Unity Hub öffnen${ed.ver ? ` (braucht ${ed.ver})` : ''}`, group: 'Starten', kind: 'exe', exe: UNITY_HUB, args: [] })
|
||||
break
|
||||
}
|
||||
case 'python': {
|
||||
const main = PY_MAIN.find((m) => f.py.includes(m)) ?? f.py.find((p) => p.toLowerCase() === `${name.toLowerCase()}.py`) ?? (f.py.length === 1 ? f.py[0] : null)
|
||||
if (main) {
|
||||
const py = f.venv ? `"${f.venv}"` : 'py -3.12'
|
||||
list.push({ id: `py:${main}`, label: `Python: ${main}${f.venv ? ' (.venv)' : ''}`, group: 'Starten', kind: 'console', cwd: f.dir, command: `${py} "${main}"` })
|
||||
}
|
||||
break
|
||||
}
|
||||
case 'arduino':
|
||||
list.push({ id: `ino:${r}:${f.ino[0]}`, label: `Arduino: ${f.ino[0]}`, group: 'Starten', kind: 'open', file: path.join(f.dir, f.ino[0]) })
|
||||
break
|
||||
}
|
||||
}
|
||||
for (const p of findPrograms(name, projectPath)) {
|
||||
if (p.file.toLowerCase() === chosenFile) continue
|
||||
list.push({
|
||||
id: `exe:${p.rel}`, label: path.basename(p.file, path.extname(p.file)), group: 'Programm', kind: 'exe',
|
||||
exe: p.file, args: [], cwd: path.dirname(p.file), rel: p.rel,
|
||||
detail: `${p.rel} · ${ago(p.mtime)}`,
|
||||
})
|
||||
}
|
||||
for (const w of findWebPages(name, projectPath)) {
|
||||
if (w.file.toLowerCase() === chosenFile) continue
|
||||
const label = /^index\.html?$/i.test(path.basename(w.file)) ? `Web: ${path.dirname(w.rel) === '.' ? name : path.dirname(w.rel)}` : `Web: ${path.basename(w.file)}`
|
||||
list.push(fileAction(`html:${w.rel}`, label, w.file, projectPath, `${w.rel} · ${ago(w.mtime)} · im Browser`))
|
||||
}
|
||||
for (const s of findScripts(projectPath)) {
|
||||
list.push({
|
||||
id: `bat:${s.rel}`, label: s.base, group: s.group, kind: 'console',
|
||||
cwd: path.dirname(s.file), command: `call "${s.base}"`, detail: s.rel,
|
||||
})
|
||||
}
|
||||
for (const g of tools.generators.filter((g) => g.kind === 'comfygen')) {
|
||||
list.push({ id: `gen:${g.rel}`, label: `Generator-Konsole (${g.rel})`, group: 'Werkzeuge', kind: 'console', cwd: path.join(projectPath, g.rel), command: 'gen' })
|
||||
}
|
||||
return list
|
||||
}
|
||||
|
||||
module.exports = { detect, summary, actions, resolveProgram, SKIP }
|
||||
32
lib/tools.js
Normal file
32
lib/tools.js
Normal file
@@ -0,0 +1,32 @@
|
||||
// Which projects use the shared generator in _Tools\ComfyGen (via gen.cmd) and
|
||||
// which still carry their own copy of generator scripts.
|
||||
const fs = require('fs')
|
||||
const path = require('path')
|
||||
|
||||
const GEN_DIR = /^(sprite-?generator|sprite-?gen|design-?gen|asset-?gen)$/i
|
||||
|
||||
function ls(dir) {
|
||||
try { return fs.readdirSync(dir, { withFileTypes: true }) } catch { return [] }
|
||||
}
|
||||
|
||||
function toolInfo(projectPath) {
|
||||
const generators = []
|
||||
const dirs = [projectPath, ...ls(projectPath).filter((e) => e.isDirectory() && !e.name.startsWith('.') && !/^(_archiv|node_modules)$/i.test(e.name)).map((e) => path.join(projectPath, e.name))]
|
||||
for (const dir of dirs) {
|
||||
for (const e of ls(dir)) {
|
||||
if (!e.isDirectory() || !GEN_DIR.test(e.name)) continue
|
||||
const gdir = path.join(dir, e.name)
|
||||
const files = ls(gdir).filter((f) => f.isFile()).map((f) => f.name)
|
||||
const shared = files.includes('gen.cmd')
|
||||
generators.push({
|
||||
rel: path.relative(projectPath, gdir),
|
||||
kind: shared ? 'comfygen' : 'copy',
|
||||
scripts: files.filter((f) => f.endsWith('.py')),
|
||||
hasOutput: fs.existsSync(path.join(gdir, 'output')),
|
||||
})
|
||||
}
|
||||
}
|
||||
return { generators }
|
||||
}
|
||||
|
||||
module.exports = { toolInfo }
|
||||
Reference in New Issue
Block a user