Files
ProjectDashboard/lib/create.js

121 lines
6.6 KiB
JavaScript
Raw Permalink Normal View History

2026-11-12 09:32:23 +01:00
// 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,
2026-11-12 09:32:23 +01:00
notes: m.notes ? `${note}\n\n${m.notes}` : note,
updatedAt: now,
}, null, 2))
return { name, path: dest, cloned: true }
} finally {
running = null
}
}
2026-11-12 14:03:53 +01:00
// 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
}
}
2026-11-12 09:32:23 +01:00
const busy = () => !!running
2026-11-12 14:03:53 +01:00
module.exports = { create, move, checkName, busy }