-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathgithub-build.js
More file actions
15 lines (13 loc) · 5.27 KB
/
github-build.js
File metadata and controls
15 lines (13 loc) · 5.27 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
let Build=require("github-build"),crypto=require("crypto"),config={repo:"siddharthkp/github-build",sha:process.env.GIT_COMMIT_SHA||"6954e71d46be1ae9b0529aae6e00b64d7a1023d4",token:process.env.GITHUB_TOKEN||"secret",label:"my CI service",description:"checking some stuff",url:"http://my-ci-service.com/builds/1",clientId:process.env.GITHUB_CLIENT_ID,clientSecret:process.env.GITHUB_CLIENT_SECRET,redirectUri:process.env.GITHUB_REDIRECT_URI||"http://localhost:3000/callback"};function generateState(){return crypto.randomBytes(16).toString("hex")}function redirectToGitHub(){var e=generateState(),e="https://github.com/login/oauth/authorize?"+new URLSearchParams({client_id:config.clientId,redirect_uri:config.redirectUri,scope:"repo,user:email",state:e,allow_signup:!1}).toString();return console.log("Redirect user to:",e),e}async function handleGitHubCallback(e,o,t){if(o!==t)throw new Error("State mismatch - possible CSRF attack");o=await(await fetch("https://github.com/login/oauth/access_token",{method:"POST",headers:{"Content-Type":"application/json",Accept:"application/json"},body:JSON.stringify({client_id:config.clientId,client_secret:config.clientSecret,code:e,redirect_uri:config.redirectUri})})).json();if(o.error)throw new Error("OAuth error: "+o.error_description);console.log("Access token obtained:",o.access_token);t=await fetch("https://api.github.com/user",{headers:{Authorization:"Bearer "+o.access_token,Accept:"application/json"}});return{accessToken:o.access_token,scope:o.scope,user:await t.json()}}async function deviceFlow(){var e=await(await fetch("https://github.com/login/device/code",{method:"POST",headers:{"Content-Type":"application/json",Accept:"application/json"},body:JSON.stringify({client_id:config.clientId,scope:"repo,user"})})).json();if(e.error)throw new Error("Device flow error: "+e.error_description);console.log("\n========================================"),console.log("🔐 GitHub Authorization Required"),console.log("========================================"),console.log("1. Open this URL: "+e.verification_uri),console.log("2. Enter this code: "+e.user_code),console.log(`3. The code expires in ${Math.floor(e.expires_in/60)} minutes`),console.log("========================================\n");let o=1e3*e.interval;for(var t=Date.now(),r=1e3*e.expires_in;Date.now()-t<r;){await new Promise(e=>setTimeout(e,o));var i=await(await fetch("https://github.com/login/oauth/access_token",{method:"POST",headers:{"Content-Type":"application/json",Accept:"application/json"},body:JSON.stringify({client_id:config.clientId,device_code:e.device_code,grant_type:"urn:ietf:params:oauth:grant-type:device_code"})})).json();if(i.access_token)return console.log("\n✅ Authorization successful!"),i.access_token;if("authorization_pending"===i.error)console.log("⏳ Waiting for authorization...");else{if("slow_down"!==i.error){if("expired_token"===i.error)throw new Error("Authorization code expired. Please restart the process.");throw new Error("Polling error: "+i.error_description)}o+=5e3,console.log("🐌 Rate limited, slowing down...")}}throw new Error("Authorization timeout. Please try again.")}async function runBuild(){var o=new Build(config);try{console.log("🚀 Starting build..."),await o.start(),console.log("✅ Build status set to pending"),console.log("\n🧪 Running tests..."),await runTests(),console.log("\n✅ All tests passed!"),await o.pass(),console.log("✅ Build status set to success")}catch(e){console.error("\n❌ Build failed:",e.message),"config"===e.type?(await o.error(),console.log("⚠️ Build status set to error")):(await o.fail(),console.log("❌ Build status set to failure"))}}async function runTests(){var e;if(await new Promise(e=>setTimeout(e,2e3)),!(.3<Math.random()))throw(e=new Error("Unit tests failed: 2 failures in main.test.js")).type="test",e;console.log(" ✓ All 42 tests passed")}function validateConfig(){var e=["repo","sha","token"].filter(e=>!config[e]);0<e.length&&(console.error("Missing required configuration:",e.join(", ")),console.error("\nSet environment variables:"),console.error(" export GITHUB_TOKEN=your_token_here"),console.error(" export GIT_COMMIT_SHA=$(git rev-parse HEAD)"),process.exit(1))}async function main(){switch(validateConfig(),process.argv.slice(2)[0]){case"--web-auth":console.log("Starting web authorization flow..."),console.log("Redirect URL:",redirectToGitHub());break;case"--device-auth":try{var e=await deviceFlow();console.log("\n🔑 Access token obtained successfully!"),console.log(`Token: ${e.substring(0,10)}...`),console.log("\nSet this token in your environment:"),console.log("export GITHUB_TOKEN="+e)}catch(e){console.error("Device flow failed:",e.message),process.exit(1)}break;case"--run-build":await runBuild();break;default:console.log(`
GitHub Build CLI Tool
=====================
Usage:
node script.js --web-auth Start web OAuth flow
node script.js --device-auth Start device OAuth flow (for CLI)
node script.js --run-build Run build with status updates
Environment Variables:
GITHUB_TOKEN - Your GitHub personal access token
GITHUB_CLIENT_ID - OAuth app client ID (for OAuth flows)
GITHUB_CLIENT_SECRET - OAuth app client secret (for OAuth flows)
GIT_COMMIT_SHA - The commit SHA to update (defaults to script's value)
`)}}main().catch(e=>{console.error("Fatal error:",e.message),process.exit(1)});