Skip to content

Commit

Permalink
python PR managing script test
Browse files Browse the repository at this point in the history
  • Loading branch information
thejoeker12 committed Oct 23, 2024
1 parent 7be10fc commit cd9e0e3
Show file tree
Hide file tree
Showing 3 changed files with 234 additions and 0 deletions.
108 changes: 108 additions & 0 deletions .github/supporting_scripts/pr.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,108 @@
const getHeadBranch = () => {
if (context.eventName === 'pull_request') {
return context.payload.pull_request.head.ref;
} else if (context.eventName === 'push') {
return context.ref.replace('refs/heads/', '');
} else {
return context.ref.replace('refs/heads/', '');
}
};

const headBranch = getHeadBranch();
const baseBranch = 'sandbox';

console.log(`Head branch: ${headBranch}`);
console.log(`Base branch: ${baseBranch}`);

// Check if PR already exists
const { data: prs } = await github.rest.pulls.list({
owner: context.repo.owner,
repo: context.repo.repo,
head: `${context.repo.owner}:${headBranch}`,
base: baseBranch,
state: 'open'
});

let pr;
if (prs.length === 0) {
// Create new PR
try {
const { data: newPr } = await github.rest.pulls.create({
owner: context.repo.owner,
repo: context.repo.repo,
title: `🔄 Terraform changes from ${headBranch}`,
head: headBranch,
base: baseBranch,
body: '🚀 This PR contains Terraform changes.'
});
pr = newPr;
} catch (error) {
console.error('Error creating PR:', error.message);
return;
}
} else {
pr = prs[0];
}

function getStatusSummary(status, planStatus, add, change, destroy) {
if (status !== 'Success') return `❌ Plan ${status}`;

switch (planStatus) {
case 'planned':
if (destroy > 0) return '🚨 Destructive changes detected';
if (change > 0) return '⚠️ Resource modifications planned';
if (add > 0) return '✨ New resources to be added';
return '✅ No changes required';
case 'pending':
return '⏳ Plan pending';
case 'running':
return '🔄 Plan in progress';
case 'errored':
return '🚫 Plan encountered an error';
case 'canceled':
return '🛑 Plan was canceled';
case 'cost_estimated':
return '💰 Cost estimation completed';
case 'policy_checked':
return '📋 Policy check completed';
case 'planned_and_finished':
return '🏁 Plan completed and finished';
default:
return `ℹ️ Plan status: ${planStatus}`;
}
}

const statusSummary = getStatusSummary(
'${{ needs.terraform-plan.outputs.status }}',
'${{ needs.terraform-plan.outputs.plan_status }}',
'${{ needs.terraform-plan.outputs.add }}',
'${{ needs.terraform-plan.outputs.change }}',
'${{ needs.terraform-plan.outputs.destroy }}'
);

const planOutput = `### 🔍 Terraform Plan Results
${statusSummary}
\`\`\`diff
+ Plan: ${{ needs.terraform-plan.outputs.add }} to add
~ ${{ needs.terraform-plan.outputs.change }} to change
- ${{ needs.terraform-plan.outputs.destroy }} to destroy
\`\`\`
📊 [View full plan details](${{ needs.terraform-plan.outputs.run_link }})
Additional Information:
- Operation Result: ${{ needs.terraform-plan.outputs.status }}
- Plan ID: ${{ needs.terraform-plan.outputs.plan_id }}
---
⚠️ Please review these changes carefully before merging.
`

await github.rest.issues.createComment({
owner: context.repo.owner,
repo: context.repo.repo,
issue_number: pr.number,
body: planOutput
});
96 changes: 96 additions & 0 deletions .github/supporting_scripts/pr.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,96 @@
"""script to update a PR or make one, update this soon."""

import os
import sys
from datetime import datetime
from github import Github
from github.GithubException import GithubException

BASE_BRANCH = "main"
HEAD_BRANCH = os.environ.get("HEAD_BRANCH")
TOKEN = os.environ.get("GITHUB_TOKEN")

if not TOKEN:
raise ValueError("GITHUB_TOKEN env var is none")

GH = Github(TOKEN)


def get_or_create_pr(repo_name, head_branch, base_branch="main", github_token=None):
"""
Get existing PR or create a new one between branches.
Args:
repo_name (str): Repository name in format "owner/repo"
head_branch (str): Branch containing changes
base_branch (str): Target branch for PR (default: main)
github_token (str): GitHub access token
Returns:
github.PullRequest.PullRequest: Pull request object
"""
try:
repo = GH.get_repo(repo_name)

existing_prs = list(repo.get_pulls(
state='open',
head=f"{repo.owner.login}:{HEAD_BRANCH}",
base=BASE_BRANCH
))

if existing_prs:
return existing_prs[0]

return repo.create_pull(
title=f"Updates from {HEAD_BRANCH}",
body=f"Automated PR created from {HEAD_BRANCH}",
head=HEAD_BRANCH,
base=BASE_BRANCH
)

except GithubException as e:
print(f"GitHub API error: {e}")
raise
except Exception as e:
print(f"Unexpected error: {e}")
raise



# def update_pr_with_text(pr, message):
# """
# Add a comment to the PR with specified text.

# Args:
# pr: github.PullRequest.PullRequest object
# message (str): Comment text to add
# """
# timestamp = datetime.utcnow().strftime('%Y-%m-%d %H:%M:%S UTC')
# comment = f"""🤖 Automated update at {timestamp}

# {message}"""

# try:
# pr.create_issue_comment(comment)
# print(f"Added comment to PR #{pr.number}")
# except GithubException as e:
# print(f"Error adding comment: {e}")
# raise

def main():
repo_name = os.getenv('GITHUB_REPOSITORY')
head_branch = os.getenv('GITHUB_HEAD_REF') or os.getenv('GITHUB_REF_NAME')
base_branch = "main"
message = "Your custom message here"

try:
pr = get_or_create_pr(repo_name, head_branch, base_branch)
print(pr)
# update_pr_with_text(pr, message)

except Exception as e:
print(f"Failed to process PR: {e}")
sys.exit(1)

if __name__ == "__main__":
main()
30 changes: 30 additions & 0 deletions .github/workflows/TEST - Python PR Script.yml
Original file line number Diff line number Diff line change
@@ -0,0 +1,30 @@
name: Apply to Staging

on:
workflow_dispatch:

jobs:
update-pr:
runs-on: ubuntu-latest
permissions:
pull-requests: write
contents: write

steps:
- uses: actions/checkout@v4

- name: Set up Python
uses: actions/setup-python@v4
with:
python-version: '3.x'

- name: Install dependencies
run: |
python -m pip install --upgrade pip
pip install PyGithub
- name: Run PR manager
env:
GITHUB_TOKEN: ${{ secrets.GITHUB_TOKEN }}
HEAD_BRANCH: "feat-test"
run: python .github/supporting_scripts/pr.py

0 comments on commit cd9e0e3

Please sign in to comment.