|
| 1 | +/*--------------------------------------------------------------------------------------------- |
| 2 | + * Copyright (c) Microsoft Corporation. All rights reserved. |
| 3 | + * Licensed under the MIT License. See License.txt in the project root for license information. |
| 4 | + *--------------------------------------------------------------------------------------------*/ |
| 5 | + |
| 6 | +import { spawnSync } from 'child_process'; |
| 7 | +import { Octokit } from '@octokit/rest'; |
| 8 | + |
| 9 | +/** |
| 10 | + * Execute a git command with optional logging |
| 11 | + */ |
| 12 | +export async function git(args: string[], printCommand: boolean = true): Promise<string> { |
| 13 | + if (printCommand) { |
| 14 | + console.log(`git ${args.join(' ')}`); |
| 15 | + } |
| 16 | + |
| 17 | + const result = spawnSync('git', args); |
| 18 | + if (result.status != 0) { |
| 19 | + const err = result.stderr ? result.stderr.toString() : ''; |
| 20 | + if (printCommand) { |
| 21 | + console.error(`Failed to execute git ${args.join(' ')}.`); |
| 22 | + } |
| 23 | + throw new Error(err || `git ${args.join(' ')} failed with code ${result.status}`); |
| 24 | + } |
| 25 | + |
| 26 | + const stdout = result.stdout ? result.stdout.toString() : ''; |
| 27 | + if (printCommand) { |
| 28 | + console.log(stdout); |
| 29 | + } |
| 30 | + return stdout; |
| 31 | +} |
| 32 | + |
| 33 | +/** |
| 34 | + * Configure git user credentials if provided |
| 35 | + */ |
| 36 | +export async function configureGitUser(userName?: string, email?: string): Promise<void> { |
| 37 | + if (userName) { |
| 38 | + await git(['config', '--local', 'user.name', userName]); |
| 39 | + } |
| 40 | + if (email) { |
| 41 | + await git(['config', '--local', 'user.email', email]); |
| 42 | + } |
| 43 | +} |
| 44 | + |
| 45 | +/** |
| 46 | + * Create a new branch, add files, and commit changes |
| 47 | + */ |
| 48 | +export async function createCommit(branch: string, files: string[], commitMessage: string): Promise<void> { |
| 49 | + await git(['checkout', '-b', branch]); |
| 50 | + await git(['add', ...files]); |
| 51 | + await git(['commit', '-m', commitMessage]); |
| 52 | +} |
| 53 | + |
| 54 | +/** |
| 55 | + * Check if a branch exists on the remote repository |
| 56 | + */ |
| 57 | +export async function doesBranchExist(remoteAlias: string, branch: string): Promise<boolean> { |
| 58 | + const lsRemote = await git(['ls-remote', remoteAlias, 'refs/head/' + branch]); |
| 59 | + return lsRemote.trim() !== ''; |
| 60 | +} |
| 61 | + |
| 62 | +/** |
| 63 | + * Push branch to remote repository with authentication |
| 64 | + */ |
| 65 | +export async function pushBranch(branch: string, pat: string, owner: string, repo: string): Promise<void> { |
| 66 | + const remoteRepoAlias = 'targetRepo'; |
| 67 | + const authRemote = `https://x-access-token:${pat}@github.com/${owner}/${repo}.git`; |
| 68 | + |
| 69 | + // Add authenticated remote |
| 70 | + await git( |
| 71 | + ['remote', 'add', remoteRepoAlias, authRemote], |
| 72 | + false // Don't print PAT to console |
| 73 | + ); |
| 74 | + |
| 75 | + await git(['fetch', remoteRepoAlias]); |
| 76 | + |
| 77 | + // Check if branch already exists |
| 78 | + if (await doesBranchExist(remoteRepoAlias, branch)) { |
| 79 | + console.log(`##vso[task.logissue type=error]${branch} already exists in ${owner}/${repo}. Skip pushing.`); |
| 80 | + return; |
| 81 | + } |
| 82 | + |
| 83 | + await git(['push', '-u', remoteRepoAlias, branch]); |
| 84 | +} |
| 85 | + |
| 86 | +/** |
| 87 | + * Find an existing pull request with the given title |
| 88 | + * @returns The PR URL if found, null otherwise |
| 89 | + */ |
| 90 | +export async function findPRByTitle(pat: string, owner: string, repo: string, title: string): Promise<string | null> { |
| 91 | + try { |
| 92 | + const octokit = new Octokit({ auth: pat }); |
| 93 | + |
| 94 | + const listPullRequest = await octokit.rest.pulls.list({ |
| 95 | + owner, |
| 96 | + repo, |
| 97 | + }); |
| 98 | + |
| 99 | + if (listPullRequest.status != 200) { |
| 100 | + throw `Failed get response from GitHub, http status code: ${listPullRequest.status}`; |
| 101 | + } |
| 102 | + |
| 103 | + const existingPR = listPullRequest.data.find((pr) => pr.title === title); |
| 104 | + return existingPR ? existingPR.html_url : null; |
| 105 | + } catch (e) { |
| 106 | + console.warn('Failed to find PR by title:', e); |
| 107 | + return null; // Assume PR doesn't exist if we can't check |
| 108 | + } |
| 109 | +} |
| 110 | + |
| 111 | +/** |
| 112 | + * Create a GitHub pull request |
| 113 | + */ |
| 114 | +export async function createPullRequest( |
| 115 | + pat: string, |
| 116 | + owner: string, |
| 117 | + repo: string, |
| 118 | + branch: string, |
| 119 | + title: string, |
| 120 | + body: string, |
| 121 | + baseBranch: string = 'main' |
| 122 | +): Promise<string | null> { |
| 123 | + try { |
| 124 | + // Check if PR with same title already exists |
| 125 | + const existingPRUrl = await findPRByTitle(pat, owner, repo, title); |
| 126 | + if (existingPRUrl) { |
| 127 | + console.log(`Pull request with the same name already exists: ${existingPRUrl}`); |
| 128 | + return existingPRUrl; |
| 129 | + } |
| 130 | + |
| 131 | + const octokit = new Octokit({ auth: pat }); |
| 132 | + console.log(`Creating PR against ${owner}/${repo}...`); |
| 133 | + const pullRequest = await octokit.rest.pulls.create({ |
| 134 | + owner, |
| 135 | + repo, |
| 136 | + title, |
| 137 | + head: branch, |
| 138 | + base: baseBranch, |
| 139 | + body, |
| 140 | + }); |
| 141 | + |
| 142 | + console.log(`Created pull request: ${pullRequest.data.html_url}`); |
| 143 | + return pullRequest.data.html_url; |
| 144 | + } catch (e) { |
| 145 | + console.warn('Failed to create PR via Octokit:', e); |
| 146 | + return null; |
| 147 | + } |
| 148 | +} |
0 commit comments