Skip to content

Instantly share code, notes, and snippets.

Show Gist options
  • Save charlyie/6f7c5f8bd4886ff2ff354840e33dbcbf to your computer and use it in GitHub Desktop.
Save charlyie/6f7c5f8bd4886ff2ff354840e33dbcbf to your computer and use it in GitHub Desktop.
/**
* Moves the labels under PARENT/ ;
* set MAX_CHANGES = 1 for a test on 1 label.
* set PARENT = 'MY_NEW_ROOT_FOLDER' for the new root label
* set DRY_RUN = true to do a dry run
* MAX_CHANGES = 1000; // 1 → test on a single label ; null → all
*
*
* Copy code to https://script.google.com/
* In Services > Add "Gmail API"
* Run the code with the same user account than your gmail account
*/
const PARENT = 'MY_NEW_ROOT_FOLDER';
const DRY_RUN = false; // true = list only, false = apply change
const MAX_CHANGES = 1000; // 1 → run on 1 label ; null → all labels
const SKIP_PREFIX = ['[Gmail]', 'CATEGORY_'];
const SKIP_EXACT = ['INBOX', 'TRASH'];
function bulkNestLabels() {
let done = 0;
const labels = GmailApp.getUserLabels();
for (const label of labels) {
const oldName = label.getName();
if (shouldSkip_(oldName)) continue;
const newName = `${PARENT}/${oldName}`;
if (DRY_RUN) {
console.log(`[DRY] ${oldName} → ${newName}`);
} else {
Gmail.Users.Labels.update({ name: newName }, 'me', label.getId());
console.log(`${oldName} → ${newName}`);
}
done++;
if (MAX_CHANGES && done >= MAX_CHANGES) {
console.log(`\Stopping after ${done} change(s) (MAX_CHANGES).`);
break;
}
}
}
function shouldSkip_(name) {
if (name === PARENT || name.startsWith(PARENT + '/')) return true;
if (SKIP_EXACT.includes(name)) return true;
if (SKIP_PREFIX.some(p => name.startsWith(p))) return true;
return false;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment