-
Notifications
You must be signed in to change notification settings - Fork 725
Add automated PR creation for Roslyn Copilot updates using a gulp task #8584
New issue
Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.
By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.
Already on GitHub? Sign in to your account
Merged
AbhitejJohn
merged 10 commits into
dotnet:main
from
AbhitejJohn:auto-createPR-forcomponentupdates
Sep 9, 2025
Merged
Changes from 8 commits
Commits
Show all changes
10 commits
Select commit
Hold shift + click to select a range
44c49db
Add automated PR creation for Roslyn Copilot updates using a gulp task
AbhitejJohn bbc19f8
Updating to use dotnet-bot creds instead.
AbhitejJohn 4d71475
Fixing prettier issues.
AbhitejJohn 82e8732
Merge branch 'main' into auto-createPR-forcomponentupdates
AbhitejJohn 8d5c807
Addressed PR feedback. I was also tired of making prettier updates so…
AbhitejJohn 0d65edb
Merge branch 'auto-createPR-forcomponentupdates' of https://github.co…
AbhitejJohn 598143b
Using PAT for the bot account
AbhitejJohn 36aa9bc
Perms for bot account PAT
AbhitejJohn 42e4cf5
Update script now knows of the roslyn language server bits as well.
AbhitejJohn b1cb959
Switching to maestro bot creds.
AbhitejJohn File filter
Filter by extension
Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
There are no files selected for viewing
This file contains hidden or 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
This file contains hidden or 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
This file contains hidden or 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
Some generated files are not rendered by default. Learn more about how customized files appear on GitHub.
Oops, something went wrong.
This file contains hidden or 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
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,112 @@ | ||
/*--------------------------------------------------------------------------------------------- | ||
* Copyright (c) Microsoft Corporation. All rights reserved. | ||
* Licensed under the MIT License. See License.txt in the project root for license information. | ||
*--------------------------------------------------------------------------------------------*/ | ||
|
||
import * as gulp from 'gulp'; | ||
import * as process from 'node:process'; | ||
import * as fs from 'fs'; | ||
import * as path from 'path'; | ||
import minimist from 'minimist'; | ||
import { | ||
configureGitUser, | ||
createCommit, | ||
pushBranch, | ||
createPullRequest, | ||
doesBranchExist, | ||
findPRByTitle, | ||
} from './gitTasks'; | ||
import { updatePackageDependencies } from '../src/tools/updatePackageDependencies'; | ||
|
||
type Options = { | ||
userName?: string; | ||
email?: string; | ||
}; | ||
|
||
/** | ||
* Extract version from file name using a provided regex pattern | ||
* @param fileName - The file name to extract version from | ||
* @param pattern - The regex pattern to match and extract version (should have a capture group) | ||
* @returns The extracted version string or null if not found | ||
*/ | ||
function extractVersion(fileName: string, pattern: RegExp): string | null { | ||
const match = fileName.match(pattern); | ||
return match && match[1] ? match[1] : null; | ||
} | ||
|
||
gulp.task('publish roslyn copilot', async () => { | ||
const parsedArgs = minimist<Options>(process.argv.slice(2)); | ||
|
||
if (!parsedArgs.stagingDirectory || !fs.existsSync(parsedArgs.stagingDirectory)) { | ||
throw new Error(`Staging directory not found at ${parsedArgs.stagingDirectory}; skipping package.json update.`); | ||
} | ||
|
||
// Find the Roslyn zip file in the staging directory (we know it was copied here) | ||
const files = fs.readdirSync(parsedArgs.stagingDirectory); | ||
const zipFile = files.find((file) => /Roslyn\.LanguageServer.*\.zip$/i.test(file)); | ||
|
||
if (!zipFile) { | ||
throw new Error(` | ||
No Roslyn LanguageServer zip file found in ${parsedArgs.stagingDirectory}; skipping package.json update.`); | ||
} | ||
|
||
const zipPath = path.join(parsedArgs.stagingDirectory, zipFile); | ||
console.log(`Using zip file: ${zipPath}`); | ||
const zipName = zipFile; | ||
|
||
// Extract version from file name | ||
const version = extractVersion(zipName, /Microsoft\.VisualStudio\.Copilot\.Roslyn\.LanguageServer-(.+)\.zip$/i); | ||
|
||
if (!version) { | ||
throw new Error(`Could not extract version from file name ${zipName}; skipping.`); | ||
} | ||
|
||
console.log(`Extracted version: ${version}`); | ||
AbhitejJohn marked this conversation as resolved.
Show resolved
Hide resolved
|
||
|
||
const safeVersion = version.replace(/[^A-Za-z0-9_.-]/g, '-'); | ||
const branch = `update/roslyn-copilot-${safeVersion}`; | ||
|
||
const pat = process.env['GitHubPAT']; | ||
if (!pat) { | ||
throw 'No GitHub PAT found.'; | ||
} | ||
|
||
const owner = 'dotnet'; | ||
const repo = 'vscode-csharp'; | ||
const title = `Update RoslynCopilot url to ${version}`; | ||
const body = `Automated update of RoslynCopilot url to ${version}`; | ||
|
||
// Bail out if a branch with the same name already exists or PR already exists for the insertion. | ||
if (await doesBranchExist('origin', branch)) { | ||
console.log(`##vso[task.logissue type=warning]${branch} already exists in origin. Skip pushing.`); | ||
return; | ||
} | ||
const existingPRUrl = await findPRByTitle(pat, owner, repo, title); | ||
if (existingPRUrl) { | ||
console.log( | ||
`##vso[task.logissue type=warning] Pull request with the same name already exists: ${existingPRUrl}` | ||
); | ||
return; | ||
} | ||
|
||
// Set environment variables for updatePackageDependencies | ||
process.env['NEW_DEPS_ID'] = 'RoslynCopilot'; | ||
process.env['NEW_DEPS_VERSION'] = version; | ||
process.env[ | ||
'NEW_DEPS_URLS' | ||
] = `https://roslyn.blob.core.windows.net/releases/Microsoft.VisualStudio.Copilot.Roslyn.LanguageServer-${version}.zip`; | ||
|
||
// Update package dependencies using the extracted utility | ||
await updatePackageDependencies(); | ||
console.log(`Updated RoslynCopilot dependency to version ${version}`); | ||
|
||
// Configure git user if provided | ||
await configureGitUser(parsedArgs.userName, parsedArgs.email); | ||
|
||
// Create commit with changes | ||
await createCommit(branch, ['package.json'], `Update RoslynCopilot version to ${version}`); | ||
|
||
// Push branch and create PR | ||
await pushBranch(branch, pat, owner, repo); | ||
await createPullRequest(pat, owner, repo, branch, title, body); | ||
}); |
This file contains hidden or 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
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,148 @@ | ||
/*--------------------------------------------------------------------------------------------- | ||
* Copyright (c) Microsoft Corporation. All rights reserved. | ||
* Licensed under the MIT License. See License.txt in the project root for license information. | ||
*--------------------------------------------------------------------------------------------*/ | ||
|
||
import { spawnSync } from 'child_process'; | ||
import { Octokit } from '@octokit/rest'; | ||
|
||
/** | ||
* Execute a git command with optional logging | ||
*/ | ||
export async function git(args: string[], printCommand: boolean = true): Promise<string> { | ||
if (printCommand) { | ||
console.log(`git ${args.join(' ')}`); | ||
} | ||
|
||
const result = spawnSync('git', args); | ||
if (result.status != 0) { | ||
const err = result.stderr ? result.stderr.toString() : ''; | ||
if (printCommand) { | ||
console.error(`Failed to execute git ${args.join(' ')}.`); | ||
} | ||
throw new Error(err || `git ${args.join(' ')} failed with code ${result.status}`); | ||
} | ||
|
||
const stdout = result.stdout ? result.stdout.toString() : ''; | ||
if (printCommand) { | ||
console.log(stdout); | ||
} | ||
return stdout; | ||
} | ||
|
||
/** | ||
* Configure git user credentials if provided | ||
*/ | ||
export async function configureGitUser(userName?: string, email?: string): Promise<void> { | ||
if (userName) { | ||
await git(['config', '--local', 'user.name', userName]); | ||
} | ||
if (email) { | ||
await git(['config', '--local', 'user.email', email]); | ||
} | ||
} | ||
|
||
/** | ||
* Create a new branch, add files, and commit changes | ||
*/ | ||
export async function createCommit(branch: string, files: string[], commitMessage: string): Promise<void> { | ||
await git(['checkout', '-b', branch]); | ||
await git(['add', ...files]); | ||
await git(['commit', '-m', commitMessage]); | ||
} | ||
|
||
/** | ||
* Check if a branch exists on the remote repository | ||
*/ | ||
export async function doesBranchExist(remoteAlias: string, branch: string): Promise<boolean> { | ||
const lsRemote = await git(['ls-remote', remoteAlias, 'refs/head/' + branch]); | ||
return lsRemote.trim() !== ''; | ||
} | ||
|
||
/** | ||
* Push branch to remote repository with authentication | ||
*/ | ||
export async function pushBranch(branch: string, pat: string, owner: string, repo: string): Promise<void> { | ||
const remoteRepoAlias = 'targetRepo'; | ||
const authRemote = `https://x-access-token:${pat}@github.com/${owner}/${repo}.git`; | ||
|
||
// Add authenticated remote | ||
await git( | ||
['remote', 'add', remoteRepoAlias, authRemote], | ||
false // Don't print PAT to console | ||
); | ||
|
||
await git(['fetch', remoteRepoAlias]); | ||
|
||
// Check if branch already exists | ||
if (await doesBranchExist(remoteRepoAlias, branch)) { | ||
console.log(`##vso[task.logissue type=error]${branch} already exists in ${owner}/${repo}. Skip pushing.`); | ||
return; | ||
} | ||
|
||
await git(['push', '-u', remoteRepoAlias, branch]); | ||
} | ||
|
||
/** | ||
* Find an existing pull request with the given title | ||
* @returns The PR URL if found, null otherwise | ||
*/ | ||
export async function findPRByTitle(pat: string, owner: string, repo: string, title: string): Promise<string | null> { | ||
try { | ||
const octokit = new Octokit({ auth: pat }); | ||
|
||
const listPullRequest = await octokit.rest.pulls.list({ | ||
owner, | ||
repo, | ||
}); | ||
|
||
if (listPullRequest.status != 200) { | ||
throw `Failed get response from GitHub, http status code: ${listPullRequest.status}`; | ||
} | ||
|
||
const existingPR = listPullRequest.data.find((pr) => pr.title === title); | ||
return existingPR ? existingPR.html_url : null; | ||
} catch (e) { | ||
console.warn('Failed to find PR by title:', e); | ||
return null; // Assume PR doesn't exist if we can't check | ||
} | ||
} | ||
|
||
/** | ||
* Create a GitHub pull request | ||
*/ | ||
export async function createPullRequest( | ||
pat: string, | ||
owner: string, | ||
repo: string, | ||
branch: string, | ||
title: string, | ||
body: string, | ||
baseBranch: string = 'main' | ||
): Promise<string | null> { | ||
try { | ||
// Check if PR with same title already exists | ||
const existingPRUrl = await findPRByTitle(pat, owner, repo, title); | ||
if (existingPRUrl) { | ||
console.log(`Pull request with the same name already exists: ${existingPRUrl}`); | ||
return existingPRUrl; | ||
} | ||
|
||
const octokit = new Octokit({ auth: pat }); | ||
console.log(`Creating PR against ${owner}/${repo}...`); | ||
const pullRequest = await octokit.rest.pulls.create({ | ||
owner, | ||
repo, | ||
title, | ||
head: branch, | ||
base: baseBranch, | ||
body, | ||
}); | ||
|
||
console.log(`Created pull request: ${pullRequest.data.html_url}`); | ||
return pullRequest.data.html_url; | ||
} catch (e) { | ||
console.warn('Failed to create PR via Octokit:', e); | ||
return null; | ||
} | ||
} |
Oops, something went wrong.
Add this suggestion to a batch that can be applied as a single commit.
This suggestion is invalid because no changes were made to the code.
Suggestions cannot be applied while the pull request is closed.
Suggestions cannot be applied while viewing a subset of changes.
Only one suggestion per line can be applied in a batch.
Add this suggestion to a batch that can be applied as a single commit.
Applying suggestions on deleted lines is not supported.
You must change the existing code in this line in order to create a valid suggestion.
Outdated suggestions cannot be applied.
This suggestion has been applied or marked resolved.
Suggestions cannot be applied from pending reviews.
Suggestions cannot be applied on multi-line comments.
Suggestions cannot be applied while the pull request is queued to merge.
Suggestion cannot be applied right now. Please check back later.
Uh oh!
There was an error while loading. Please reload this page.