Skip to content

Instantly share code, notes, and snippets.

@cyranix
Created June 12, 2018 04:56
Show Gist options
  • Select an option

  • Save cyranix/b310b905322a06c240b8f0b4feee179c to your computer and use it in GitHub Desktop.

Select an option

Save cyranix/b310b905322a06c240b8f0b4feee179c to your computer and use it in GitHub Desktop.
GitLab email filtering for Gmail, based on their custom headers.
/**
Setup:
- Create a "GitLab Catch-all" label and redirect all GitLab emails to it via normal filtering
- You can hide it from the message list, so it doesn't clutter up your sidebar
- Set this catch-all filter to skip the inbox
- Create issue and merge request labels for each GitLab project
- This gist uses nested labels like "GitLab/nifty/Issues", but customize to suit your needs
*/
function processInbox() {
var threads = GmailApp.search("label:gitlab-catch-all");
for (var i = 0; i < threads.length; i++) {
processThread(threads[i]);
}
}
function processThread(thread) {
var newLabel = getLabelForThread(thread.getMessages()[0]);
var oldLabel = GmailApp.getUserLabelByName("GitLab Catch-all");
thread.addLabel(newLabel).removeLabel(oldLabel);
}
function getLabelForThread(message) {
// NOTE: If you wanted to be more precise, you could parse this string to get only the headers,
// then restrict the rest of the method to search the headers. There's no built-in method to
// fetch the headers from a GmailMessage. Why?!
var body = message.getRawContent();
// TODO: map your GitLab orgs and projects onto the project component of your Gmail label
var project = null;
if (body.indexOf("X-GitLab-Project-Path: my-awesome-org/my-nifty-project") > -1) {
project = "nifty";
}
var type = null;
if (body.indexOf("X-GitLab-MergeRequest-ID:") > -1) {
type = "Merge Requests";
} else if (body.indexOf("X-GitLab-Issue-ID:") > -1) {
type = "Issues";
}
// TODO: check project and type for null values, if you're not feeling confident
return GmailApp.getUserLabelByName("GitLab/" + project + "/" + type);
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment