ConceptCreator/app/storage/storing/GamesystemStorage.ts

65 lines
2.5 KiB
TypeScript
Raw Normal View History

2024-03-20 19:35:24 +01:00
import {StoreComponent} from "../StoreComponent";
import {FileUtils} from "../FileUtils";
import * as path from "node:path";
import * as fs from "fs";
export class GamesystemStorage {
private gamesystemRootDir: string
constructor(gamesystemRootDir: string) {
this.gamesystemRootDir = gamesystemRootDir;
}
public storeGamesystems(gamesystems: StoreComponent[]) {
2024-03-21 08:43:28 +01:00
const unreferencedFiles = this.detectUnusedGamesystemFiles(gamesystems)
FileUtils.removeFiles(unreferencedFiles)
2024-03-20 19:35:24 +01:00
gamesystems.forEach(gamesystem => this.storeGamesystem(gamesystem))
}
2024-03-21 08:43:28 +01:00
private detectUnusedGamesystemFiles(gamesystems: StoreComponent[]) {
const unreferencedFiles: string[] = []
const gamesystemFiles = FileUtils.listFilesInDirectory(this.gamesystemRootDir);
while(gamesystemFiles.length > 0) {
const currentGamesystemFile = gamesystemFiles.shift()
const referencedGamesystemName = path.parse(path.basename(currentGamesystemFile!)).name
const referencedGamesystem = this.findReferencedGamesystem(referencedGamesystemName, gamesystems)
if(referencedGamesystem == undefined) {
unreferencedFiles.push(currentGamesystemFile!)
2024-03-20 19:35:24 +01:00
} else {
2024-03-21 08:43:28 +01:00
const decodedJSONData = JSON.parse(referencedGamesystem!.jsonString)
if(decodedJSONData.childsystems != undefined) {
//Check if current file is a directory. When it is a directory, everything is fine
if(fs.lstatSync(currentGamesystemFile!).isDirectory()) {
} else {
const parentDirName = path.basename(path.dirname(currentGamesystemFile!))
if(parentDirName !== referencedGamesystemName) {
unreferencedFiles.push(currentGamesystemFile!)
}
2024-03-20 19:35:24 +01:00
}
}
}
2024-03-21 08:43:28 +01:00
if(fs.lstatSync(currentGamesystemFile!).isDirectory()) {
gamesystemFiles.push(... FileUtils.listFilesInDirectory(currentGamesystemFile!))
}
}
return unreferencedFiles;
}
private findReferencedGamesystem(referencedName: string, gamesystems: StoreComponent[]): StoreComponent | undefined {
return gamesystems.find(gamesystem =>
path.basename(gamesystem.fileName) === referencedName)
2024-03-20 19:35:24 +01:00
}
private storeGamesystem(gamesystem: StoreComponent) {
const gamesystemFile = path.join(... gamesystem.fileName.split("/"))
const completeGamesystemFile = path.join(this.gamesystemRootDir, gamesystemFile)
FileUtils.prepareFileForWriting(completeGamesystemFile)
fs.writeFileSync(completeGamesystemFile + ".json", gamesystem.jsonString, 'utf-8')
}
}