Skip to content

Instantly share code, notes, and snippets.

@leolabs
Created May 8, 2022 21:22
Show Gist options
  • Save leolabs/53b279c501ad385b76008546196535be to your computer and use it in GitHub Desktop.
Save leolabs/53b279c501ad385b76008546196535be to your computer and use it in GitHub Desktop.
This script tries to automatically fix empty files in a given Google Drive folder
/** Put the root folder ID here */
const ROOT_FOLDER_ID = "";
/** Set this to false to only see reports of fixed files and errors */
const VERBOSE = true;
/** Keeps track of how many files have been fixed */
let fixedFiles = 0;
/**
* A function that deletes all versions of files in the given
* folder and subfolders that are empty (aka 0 bytes)
*/
function fixAllFilesInFolder() {
const folder = DriveApp.getFolderById(ROOT_FOLDER_ID);
handleFolder(folder, 0);
}
/**
* Deletes all bad versions of files in folder and
* calls itself with each subfolder to do the same
*/
function handleFolder(folder, treeRank, path = "") {
const folderPath = `${path}/${folder.getName()}`;
if (VERBOSE) Logger.log(`Searching ${folderPath}...`);
fixFolderFiles(folder);
const subFolders = folder.getFolders();
while (subFolders.hasNext()) {
subFolder = subFolders.next();
handleFolder(subFolder, treeRank + 1, folderPath)
}
}
/** Deletes all 'bad' versions of files in folder */
function fixFolderFiles(folder) {
const files = folder.getFiles();
while (files.hasNext()) {
const file = files.next();
const mimeType = file.getMimeType();
if (file.getSize() === 0 && !mimeType.startsWith("application/vnd.google-apps.")) {
Logger.log(`> ${file.getName()} is empty, fixing...`);
deleteEmptyRevisions(file);
}
}
}
/** Delete 'bad' version of a file */
function deleteEmptyRevisions(file) {
const fileId = file.getId();
const revisions = Drive.Revisions.list(fileId);
if (!revisions.items || revisions.items.length <= 1) {
Logger.log(`> ${file.getName()} has no older revisions`);
return;
}
// We don't want to remove the first revision, so we start at i = 1
for (let i = 0; i < revisions.items.length; i++) {
const revision = revisions.items[i];
const fileSize = Number(revision.getFileSize());
if (fileSize === 0) {
Drive.Revisions.remove(fileId, revision.id);
}
}
Logger.log(`> Fixed ${file.getName()} – ${++fixedFiles} fixed so far`);
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment