user-1
(User 1)
October 6, 2023, 1:43pm
1
This topic was automatically generated from Slack. You can find the original thread here .
I am creating a workflow to automatically change the labels of PRs in Github when a new PR is created and when the PR is ready for review. I also added a second trigger for every new reviews for the PR the lable will change. I have this Python code, but its not working. Its not updating the label of the PR. Here’s the code:
import requests
def handler(pd):
token = pd.inputs[‘github’][‘$auth’][‘oauth_access_token’]
authorization = f’Bearer {token}’
headers = {“Authorization”: authorization, “X-GitHub-Api-Version”: ‘2022-11-28’}
event = pd.steps[‘trigger’][‘event’]
**if** ‘pull_request’ **not** **in** event:
**print**(“The pull_request key is not present in the event object.“)
**return**
pull_request = event[‘pull_request’]
repo = event[‘repository’]
issue_number = pull_request[“number”]
title = pull_request[“title”]
update_labels(token, pull_request, repo, issue_number, title)
def update_labels(token, pull_request, repo, issue_number, title):
authorization = f”Bearer {token}”
headers = {
“Authorization”: authorization,
“X-GitHub-Api-Version”: “2022-11-28",
}
url = f”https://api.github.com/repos/{repo['owner']['login']}/{repo['name']}/issues/{issue_number}/labels”
_# Fetch existing labels_
get_labels_response = requests.get(url, headers=headers)
existing_labels = get_labels_response.json()
_# All the existing CR related names_
existing_cr_label = [label **for** label **in** existing_labels **if** label[‘name’].startswith(“CR:“)]
_# Remove the old CR related label if it exists_
labels = [label **for** label **in** existing_labels **if** **not** label[‘name’].startswith(“CR:“)]
label_name = get_label_name(pull_request)
**if** label_name:
labels.append(label_name)
**else**:
_# We cannot determine a label based on the heuristics, so just keep the existing CR labels_
labels.extend(existing_cr_label)
data = {“labels”: labels}
**print** (data)
_# Update the labels using a PUT request_
response = requests.put(url, headers=headers, json=data)
**return** response.json()
def get_label_name(pull_request):
review_state = pull_request[‘state’]
print (pull_request)
condition_met = review_state == “changes_requested”
**if** pull_request[‘draft’]:
label_name = “CR: [Creator] draft”
**elif** condition_met:
label_name = “CR: [Creator] need_to_address_comments”
**else**:
label_name = **None**
**return** label_name
user-1
(User 1)
October 6, 2023, 1:43pm
2
I see you’re trying to update the labels of PRs in GitHub using Python code. Since you’re working with Pipedream, I recommend using a Pipedream component with Node.js code instead. Here’s an example component that updates the labels of a PR when it’s created or ready for review: ```
import { axios } from “@pipedream /platform”; export default defineComponent({ props: { github: { type: “app”, app: “github”, }, repoOwner: { type: “string”, label: “Repository Owner”, }, repoName: { type: “string”, label: “Repository Name”, }, issueNumber: { type: “integer”, label: “Issue Number”, }, labelName: { type: “string”, label: “Label Name”, }, }, async run({ steps, $ }) { const url = https://api.github.com/repos/${this.repoOwner}/${this.repoName}/issues/${this.issueNumber}/labels; // Fetch existing labels const getLabelsResponse = await axios($, { method: “GET”, url, headers: { Authorization: Bearer ${this.github.$auth.oauth_access_token}, }, }); const existingLabels = getLabelsResponse.data; // Remove the old CR related label if it exists const labels = existingLabels.filter((label) => !label.name.startsWith(“CR:”)); // Add the new label labels.push(this.labelName); // Update the labels using a PUT request const response = await axios($, { method: “PUT”, url, headers: { Authorization: Bearer ${this.github.$auth.oauth_access_token}, }, data: { labels }, }); return response.data; }, });
user-1
(User 1)
October 6, 2023, 1:43pm
3
I have this Node.js code for the said workflow but its not working:
import { axios } from “@pipedream /platform”;
export default defineComponent({
async run({ steps, $ }) {
const token = steps.trigger.event.token;
const authorization = Bearer ${token};
const headers = {
Authorization: authorization,
“X-GitHub-Api-Version”: “2022-11-28”,
};
const event = steps.trigger.event;
if (!event.pull_request) {
console.log(“The pull_request key is not present in the event object.“);
return ;
}
const pull_request = event.pull_request;
const repo = event.repository;
const issue_number = pull_request.number;
const title = pull_request.title;
await updateLabels(token, pull_request, repo, issue_number, title, headers);
},
});
async function updateLabels(token, pull_request, repo, issue_number, title, headers) {
const url = https://api.github.com/repos/${repo.owner.login}/${repo.name}/issues/${issue_number}/labels;
// Fetch existing labels
const getLabelsResponse = await axios(this , { method: “GET”, url, headers });
const existingLabels = getLabelsResponse.data;
// Remove the old label if it exists
const labels = existingLabels.filter((label) => !label.name.startsWith(“CR:“));
const labelName = getLabelName(pull_request);
labels.push(labelName);
const data = { labels };
console.log(data);
// Update the labels using a PUT request
const response = await axios(this , { method: “PUT”, url, headers, data });
return response.data;
}
function getLabelName(pull_request) {
const review_state = pull_request.state;
const condition_met = review_state === “changes_requested”;
let label_name;
if (pull_request.draft) {
label_name = “CR: [Creator] draft”;
} else if (condition_met) {
label_name = “CR: [Creator] need_to_address_comments”;
} else if (review_state === “approved”) {
label_name = “CR: [Oncall] ready_to_be_merged”;
} else {
label_name = “CR: [Oncall] review_requested”;
}
return
user-1
(User 1)
October 6, 2023, 1:43pm
4
I noticed some issues with the code you provided. First, you should replace the non-standard quotes with standard single or double quotes. Also, you should use the correct arrow function syntax for the filter function. Here’s the corrected code: ``` import { axios } from “@pipedream /platform”; export default defineComponent({ async run({ steps, $ }) { const token = steps.trigger.event.token; const authorization = Bearer ${token}; const headers = { Authorization: authorization, “X-GitHub-Api-Version”: “2022-11-28”, }; const event = steps.trigger.event; if (!event.pull_request) { console.log(“The pull_request key is not present in the event object.”); return; } const pull_request = event.pull_request; const repo = event.repository; const issue_number = pull_request.number; const title = pull_request.title; await updateLabels(token, pull_request, repo, issue_number, title, headers); }, }); async function updateLabels(token, pull_request, repo, issue_number, title, headers) { const url = https://api.github.com/repos/${repo.owner.login}/${repo.name}/issues/${issue_number}/labels>; // Fetch existing labels const getLabelsResponse = await axios(this, { method: “GET”, url, headers }); const existingLabels = getLabelsResponse.data; // Remove the old label if it exists const labels = existingLabels.filter((label) => !label.name.startsWith(“CR:”)); const labelName = getLabelName(pull_request); labels.push(labelName); const data = { labels }; console.log(data); // Update the labels using a PUT request const response = await axios(this, { method: “PUT”, url, headers, data }); return response.data; } function getLabelName(pull_request) { const review_state = pull_request.state; const condition_met = review_state === “changes_requested”; let label_name; if (pull_request.draft) { label_name = “CR: [Creator] draft”; } else if (condition_met) { label_name = “CR: [Creator] need_to_address_comments”; } else if (review_state === “approved”) { label_name = “CR: [Oncall] ready_to_be_merged”;
user-1
(User 1)
October 6, 2023, 1:43pm
5
the code you provided above seems incomplete
user-1
(User 1)
October 6, 2023, 1:43pm
6
You’re right, the code I provided earlier was incomplete. I apologize for the confusion. Please provide more information about what you’re trying to achieve with the code, and I’ll do my best to help you with a complete and correct solution.
user-1
(User 1)
October 6, 2023, 1:43pm
7
complete this code:
import { axios } from “@pipedream /platform”;
export default defineComponent({
async run({ steps, $ }) {
const token = steps.trigger.event.token;
const authorization = Bearer ${token};
const headers = {
Authorization: authorization,
“X-GitHub-Api-Version”: “2022-11-28”,
};
const event = steps.trigger.event;
if (!event.pull_request) {
console.log(“The pull_request key is not present in the event object.“);
return;
}
const pull_request = event.pull_request;
const repo = event.repository;
const issue_number = pull_request.number;
const title = pull_request.title;
await updateLabels(token, pull_request, repo, issue_number, title, headers);
},
});
async function updateLabels(token, pull_request, repo, issue_number, title, headers) {
const url = https://api.github.com/repos/${repo.owner.login}/${repo.name}/issues/${issue_number}/labelshttps://api.github.com/repos/${repo.owner.login}/${repo.name}/issues/${issue_number}/labels;|>`;>
// Fetch existing labels
const getLabelsResponse = await axios(this, { method: “GET”, url, headers });
const existingLabels = getLabelsResponse.data;
// Remove the old label if it exists
const labels = existingLabels.filter((label) => !label.name.startsWith(“CR:“));
const labelName = getLabelName(pull_request);
labels.push(labelName);
const data = { labels };
console.log(data);
// Update the labels using a PUT request
const response = await axios(this, { method: “PUT”, url, headers, data });
return response.data;
}
function getLabelName(pull_request) {
const review_state = pull_request.state;
const condition_met = review_state === “changes_requested”;
let label_name;
if (pull_request.draft) {
label_name = “CR: [Creator] draft”;
} else if (condition_met) {
label_name = “CR: [Creator] need_to_address_comments”;
} else if (review_state === “approved”) {
label_name = “CR: [Oncall] ready_to_be_merged”;
user-1
(User 1)
October 6, 2023, 1:43pm
8
I apologize for the formatting issues in the code you provided. Here’s the corrected version: ```
import { axios } from “@pipedream /platform”; export default defineComponent({ async run({ steps, $ }) { const token = steps.trigger.event.token; const authorization = Bearer ${token}; const headers = { Authorization: authorization, “X-GitHub-Api-Version”: “2022-11-28”, }; const event = steps.trigger.event; if (!event.pull_request) { console.log(“The pull_request key is not present in the event object.”); return; } const pull_request = event.pull_request; const repo = event.repository; const issue_number = pull_request.number; const title = pull_request.title; await updateLabels(token, pull_request, repo, issue_number, title, headers); }, }); async function updateLabels(token, pull_request, repo, issue_number, title, headers) { const url = https://api.github.com/repos/${repo.owner.login}/${repo.name}/issues/${issue_number}/labels; // Fetch existing labels const getLabelsResponse = await axios(this, { method: “GET”, url, headers }); const existingLabels = getLabelsResponse.data; // Remove the old label if it exists const labels = existingLabels.filter((label) => !label.name.startsWith(“CR:”)); const labelName = getLabelName(pull_request); labels.push(labelName); const data = { labels }; console.log(data); // Update the labels using a PUT request const response = await axios(this, { method: “PUT”, url, headers, data }); return response.data; } function getLabelName(pull_request) { const review_state = pull_request.state; const condition_met = review_state === “changes_requested”; let label_name; if (pull_request.draft) { label_name = “CR: [Creator] draft”; } else if (condition_met) { label_name = “CR: [Creator] need_to_address_comments”; } else if (review_state === “approved”) { label_name = “CR: [Oncall] ready_to_be_merged”; } return label_name; }