Created
October 7, 2021 18:27
-
-
Save statico/f1718f13057304e61970a41dbf7c7f02 to your computer and use it in GitHub Desktop.
GitHub Project Card Sorter using GraphQL API
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
const { graphql } = require("@octokit/graphql") | |
const REPO_OWNER = "x" | |
const REPO_NAME = "y" | |
const PROJECT_NUMBER = 2 | |
const COLUMN_TO_SORT = /To Do/ | |
const api = graphql.defaults({ | |
headers: { | |
authorization: `token ${process.env.GITHUB_TOKEN}`, | |
}, | |
}) | |
const main = async () => { | |
console.log("Fetching project data...") | |
const data = await api(` | |
query { | |
repository(owner:"${REPO_OWNER}", name:"${REPO_NAME}") { | |
project(number:${PROJECT_NUMBER}) { | |
columns(first:10) { | |
nodes { | |
id | |
name | |
cards(first:100) { | |
nodes { | |
id | |
content { | |
...cardFields | |
...labelFields | |
} | |
} | |
} | |
} | |
} | |
} | |
} | |
} | |
fragment cardFields on Issue { | |
title | |
} | |
fragment labelFields on Labelable { | |
labels(first:10) { | |
nodes { | |
name | |
} | |
} | |
} | |
`) | |
const cols = data.repository.project.columns.nodes | |
const col = cols.find((c) => COLUMN_TO_SORT.test(c.name)) | |
const cards = [] | |
let last = null | |
for (const card of col.cards.nodes) { | |
const obj = { id: card.id, priority: 99, bug: 99, good: 99 } | |
if (last) obj.lastId = last.id | |
for (const { name } of card.content.labels.nodes) { | |
if (name === "P0") obj.priority = 1 | |
if (name === "P1") obj.priority = 2 | |
if (name === "P2") obj.priority = 3 | |
if (name === "P3") obj.priority = 4 | |
if (name === "P4") obj.priority = 5 | |
if (name === "bug") obj.bug = 1 | |
if (name === "good first issue") obj.good = 1 | |
} | |
cards.push(obj) | |
last = obj | |
} | |
cards.sort( | |
(a, b) => a.priority - b.priority || a.bug - b.bug || a.good - b.good | |
) | |
last = null | |
for (const card of cards) { | |
const lastId = last ? last.id : null | |
if (lastId !== card.lastId) { | |
console.log("Moving", card.id, "after", lastId) | |
await api(` | |
mutation { | |
moveProjectCard(input:{ | |
columnId: "${col.id}", | |
cardId: "${card.id}", | |
afterCardId: "${lastId}", | |
}) { clientMutationId } | |
} | |
`) | |
} | |
last = card | |
} | |
} | |
main().catch((err) => { | |
console.log(err?.stack ?? err) | |
process.exit(1) | |
}) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment