Created
October 25, 2023 22:08
-
-
Save adamziel/a851a65af95623f4873ab032bacad152 to your computer and use it in GitHub Desktop.
Playground integration with GitHub for storage and workflows
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
<!DOCTYPE html> | |
<html> | |
<head> | |
<script type="module"> | |
const TOKEN_KEY = 'githubToken'; | |
// OAUTH FLOW {{{ | |
// If there is a code in the URL, store it in localStorage | |
const urlParams = new URLSearchParams(window.location.search); | |
const code = urlParams.get('code'); | |
if (code) { | |
// Fetch https://github.com/login/oauth/access_token | |
// with clientId, clientSecret and code | |
// to get the access token | |
const response = await fetch('oauth.php?code=' + code, { | |
headers: { | |
'Content-Type': 'application/json', | |
Accept: 'application/json', | |
}, | |
}); | |
const body = await response.json(); | |
localStorage.setItem(TOKEN_KEY, body.access_token); | |
// Redirect to the same page but without "code" in the URL | |
const url = new URL(window.location.href); | |
url.searchParams.delete('code'); | |
window.location = url; | |
} else if (!localStorage.getItem(TOKEN_KEY)) { | |
// If no token in localStorage, redirect to GitHub OAuth | |
window.location = 'oauth.php?redirect=1'; | |
} | |
// }}} /OAUTH FLOW | |
import { Octokit } from 'https://esm.sh/@octokit/rest'; | |
import { | |
createPullRequest, | |
DELETE_FILE, | |
} from 'https://cdn.pika.dev/octokit-plugin-create-pull-request'; | |
const MyOctokit = Octokit.plugin(createPullRequest); | |
const octokit = new MyOctokit({ | |
auth: localStorage.getItem(TOKEN_KEY), | |
}); | |
// CREATE A PULL REQUEST {{{ | |
const newBranchName = `playground-test-branch-${Date.now()}`; | |
await createBranch( | |
'adamziel', | |
'wordpress-develop', | |
newBranchName, | |
'trunk' | |
); | |
// See https://github.com/type-challenges/octokit-create-pull-request | |
await octokit | |
.createPullRequest({ | |
owner: 'adamziel', | |
repo: 'wordpress-develop', | |
title: 'Test PR from Playground', | |
body: 'This is a description', | |
head: newBranchName, | |
// base: 'trunk' /* optional: defaults to default branch */, | |
update: true /* optional: set to `true` to enable updating existing pull requests */, | |
forceFork: false /* optional: force creating fork even when user has write rights */, | |
labels: [ | |
'bug', | |
] /* optional: applies the given labels when user has permissions. When updating an existing pull request, already present labels will not be deleted. */, | |
changes: [ | |
{ | |
/* optional: if `files` is not passed, an empty commit is created instead */ | |
files: { | |
'test.txt': 'Content for file1', | |
'README.md': '# Test', | |
'src/index.php': '# Test', | |
'Gruntfile.js': DELETE_FILE, | |
}, | |
commit: 'Test commit desc file1.txt, file2.png, deleting file3.txt, updating file4.txt (if it exists), file5.sh', | |
/* optional: if not passed, will be the authenticated user and the current date */ | |
author: { | |
name: 'Adam Zielinski', | |
email: 'adam@adamziel.com', | |
date: new Date().toISOString(), // must be ISO date string | |
}, | |
/* optional: if not passed, will use the information set in author */ | |
committer: { | |
name: 'Adam Zielinski', | |
email: 'adam@adamziel.com', | |
date: new Date().toISOString(), // must be ISO date string | |
}, | |
}, | |
], | |
}) | |
.then((pr) => console.log(`PR #${pr.data.number} created`)); | |
// }}} /CREATE A PULL REQUEST | |
// Get a build artifact from the specified PR | |
console.log( | |
await getArtifact( | |
'wordpress', | |
'wordpress-develop', | |
5511, | |
'build.yml' | |
) | |
); | |
async function getArtifact(owner, repo, prNumber, workflow_id) { | |
const { data: pullRequest } = await octokit.rest.pulls.get({ | |
owner, | |
repo, | |
pull_number: prNumber, | |
}); | |
const workflowRuns = | |
await octokit.rest.actions.listWorkflowRuns({ | |
owner, | |
repo, | |
branch: pullRequest.head.ref, | |
workflow_id, | |
}); | |
const runId = workflowRuns.data.workflow_runs[0]?.id; | |
const artifacts = | |
await octokit.rest.actions.listWorkflowRunArtifacts({ | |
owner, | |
repo, | |
run_id: runId, | |
}); | |
const artifact = await octokit.rest.actions.downloadArtifact({ | |
owner, | |
repo, | |
artifact_id: artifacts.data.artifacts[0].id, | |
archive_format: 'zip', | |
}); | |
return artifact; | |
} | |
async function createBranch( | |
owner, | |
repo, | |
newBranchName, | |
baseBranchName = 'main' | |
) { | |
try { | |
// 1. Get the latest commit SHA from the base branch | |
const { data: refData } = await octokit.git.getRef({ | |
owner, | |
repo, | |
ref: `heads/${baseBranchName}`, | |
}); | |
const sha = refData.object.sha; | |
// 2. Create a new branch pointing to the obtained SHA | |
await octokit.git.createRef({ | |
owner, | |
repo, | |
ref: `refs/heads/${newBranchName}`, | |
sha, | |
}); | |
console.log( | |
`Branch ${newBranchName} created successfully!` | |
); | |
} catch (error) { | |
console.error('Error creating branch:', error); | |
} | |
} | |
</script> | |
</head> | |
<body> | |
Test | |
</body> | |
</html> |
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
<?php | |
$client_id = "b10a460fe91c5735f359"; | |
if (array_key_exists('redirect', $_GET) && $_GET["redirect"] === "1") { | |
http_response_code(302); | |
header("Location: https://github.com/login/oauth/authorize?client_id=${client_id}&scope=repo"); | |
die(); | |
} | |
$api_endpoint = 'https://github.com/login/oauth/access_token'; | |
$data = [ | |
'client_id' => $client_id, | |
'client_secret' => 'CLIENT SECRET', | |
'code' => $_GET['code'], | |
]; | |
$ch = curl_init(); | |
curl_setopt($ch, CURLOPT_URL, $api_endpoint); | |
curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1); | |
curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, false); | |
curl_setopt($ch, CURLOPT_SSL_VERIFYHOST, false); | |
curl_setopt($ch, CURLOPT_POST, true); | |
curl_setopt($ch, CURLOPT_POSTFIELDS, $data); | |
$result = curl_exec($ch); | |
parse_str($result, $auth_data); | |
header('Content-Type: application/json'); | |
echo json_encode($auth_data); |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment