I created custom script to sync data from 2 folders in Google Drive.
To be blunt this is due to me emulating gameboy/gameboy advance on both android device and PC.
The emulator on PC works fine for both GB/GBA games and it stores save files in specified location (does not diffrentiate ROM type, stores and load all .sav files from set location)
But on android I have two emulators (one for GB one for GBA) and each of them have option of syncing with google cloud, but no custom selecting target folder (these are by default named after emulators)
I of course selected one of these folder as save file location for PC emmulator, but it lacks saves from other.
I created google apps script that triggers based on timer (for testing set once every 5 minutes)
function syncFolders() {
const gbcFolderId = <link to GB folder>;
const gbaFolderId = <link to GBA folder>;
const gbcFolder = DriveApp.getFolderById(gbcFolderId);
const gbaFolder = DriveApp.getFolderById(gbaFolderId);
syncFolderFiles(gbcFolder, gbaFolder); // Sync from GBC to GBA
syncFolderFiles(gbaFolder, gbcFolder); // Sync from GBA to GBC
}
function syncFolderFiles(sourceFolder, targetFolder) {
const sourceFiles = sourceFolder.getFiles();
const targetFilesMap = createFileMap(targetFolder);
while (sourceFiles.hasNext()) {
const sourceFile = sourceFiles.next();
const sourceName = sourceFile.getName();
const sourceDate = sourceFile.getLastUpdated();
if (
targetFilesMap[sourceName] &&
targetFilesMap[sourceName].date >= sourceDate
) {
continue; // Skip if target file is newer or the same
}
// Copy or update the file in the target folder
if (targetFilesMap[sourceName]) {
targetFilesMap[sourceName].file.setTrashed(true); // Trash old version
}
sourceFile.makeCopy(sourceName, targetFolder);
}
}
function createFileMap(folder) {
const fileMap = {};
const files = folder.getFiles();
while (files.hasNext()) {
const file = files.next();
fileMap[file.getName()] = {
file: file,
date: file.getLastUpdated(),
};
}
return fileMap;
}
The issue is that even though this script indeed syncs folders with each other allowing me to have all actual saves in both folders. but some of them are appended with incremented number (1) in the name, file copy style. This also lead to having save file for one of games in literally 5000 copies overnight.
And since old files are set to be trashed many of saves were unusable before renaming and removing index from the name.
Any idea how to fix the script to not append name/ trim it after copying or any other way to make the script work as intended?