Files
ProjectDashboard/lib/create.js
Michi 916d6b8685 review 06/07/08: loeschen in papierkorb, backup-erfolg ehrlich, verschieben sicher
08 Loeschen: statt fs.rmSync (endgueltig) jetzt in den Windows-Papierkorb
   (wiederherstellbar, Pfad per env an PowerShell -> keine Shell-Injektion);
   schlaegt es fehl, bleibt das Projekt. _Tools-Schutz case-insensitiv.
   Dialog nennt Papierkorb + letzten Backup-Stand.
06 Backup: Kopier-Entscheidung + Erfolg am Robocopy-Exitcode statt nur an
   geparsten Konsolenzeilen; bei unklarem Ergebnis kein gruener Stand, sondern
   'Ergebnis unklar' + sicherheitshalber kopieren. README: Wiederherstellung,
   Ueberschreiben desselben Ziels, Papierkorb.
07 Verschieben: Original erst nach verifizierter, nicht-leerer Uebernahme
   entfernen; Entfernen-Fehler laesst beide Staende nutzbar. Case-only-Umbenennen
   rollt bei Fehler im zweiten Schritt zurueck bzw. meldet den Zwischenpfad.

Getestet: Papierkorb-Loeschung eines Wegwerf-Ordners -> landet wiederherstellbar
im Papierkorb. node --check alle Dateien, i18n-Paritaet 801/801.

Co-Authored-By: Claude Opus 4.8 <noreply@anthropic.com>
2026-11-30 00:24:08 +01:00

129 lines
7.4 KiB
JavaScript
Raw Blame History

This file contains ambiguous Unicode characters
This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.
// 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: '', favorite: false, tasks,
notes: m.notes ? `${note}\n\n${m.notes}` : note,
updatedAt: now,
}, null, 2))
return { name, path: dest, cloned: true }
} finally {
running = null
}
}
// 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}.`)
// only remove the original once the copy is verifiably present at the target
if (!fs.existsSync(dest) || fs.readdirSync(dest).length === 0) throw new Error(`Kopie am Ziel „${dest}“ nicht gefunden – das Original in ${src} bleibt erhalten.`)
try { fs.rmSync(src, { recursive: true, force: true, maxRetries: 3 }) }
catch { throw new Error(`Die Kopie liegt in ${dest}, aber das Original in ${src} ließ sich nicht entfernen (in Benutzung?). Beide sind vorhanden – bitte das Original manuell löschen.`) }
}
if (process.env.DASHBOARD_TEST_FORCE_COPY && !caseOnly) await copyMove()
else {
try {
if (caseOnly) {
// Windows: a case-only rename needs a detour – roll back if the second step fails
const tmp = `${src}.__umbenennen__${Date.now()}`
fs.renameSync(src, tmp)
try { fs.renameSync(tmp, dest) }
catch (e2) {
try { fs.renameSync(tmp, src) } catch {}
if (fs.existsSync(tmp)) throw new Error(`Umbenennen fehlgeschlagen. Der Projektordner liegt vorübergehend unter „${tmp}“ – bitte manuell nach „${path.basename(dest)}“ umbenennen.`)
throw e2
}
} 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, move, checkName, busy }