@actions/github#GitHub TypeScript Examples
The following examples show how to use
@actions/github#GitHub.
You can vote up the ones you like or vote down the ones you don't like,
and go to the original project or source file by following the links above each example. You may check out the related API usage on the sidebar.
Example #1
Source File: github-pr.ts From github-actions-pr-to-work-item with MIT License | 6 votes |
export async function update(payload: Payload, token: string, workItemId: number): Promise<IResponse> {
const response: IResponse = { code: 500, message: 'failed', success: false }
const n = payload.body.includes(`AB#${workItemId}`)
if (!n) {
const octokit = new GitHub(token)
payload.body = payload.body.concat(`\r\n\r\nAB#${workItemId}`)
try {
const result = await octokit.pulls.update({
owner: payload.repo_owner,
repo: payload.repo_name,
body: payload.body,
pull_number: payload.number !== undefined ? payload.number : -1
})
if (result.status === 200) {
response.code = 200
response.message = 'Success'
response.success = true
}
} catch (error) {
response.message = JSON.stringify(error)
}
} else {
response.code = 200
response.message = `AB#${workItemId} already exists`
response.success = true
}
return response
}
Example #2
Source File: create.ts From action-deploy with MIT License | 6 votes |
async function getMainSha (client: GitHub, branch: string): Promise<string> {
try {
const response = await client.repos.getBranch({ ...context.repo, branch })
const sha = response.data.commit.sha
console.log(`${branch} branch sha: ${sha}`)
return sha
} catch (error) {
console.error(error.message)
return `no_${branch}`
}
}
Example #3
Source File: complete.ts From action-deploy with MIT License | 6 votes |
export async function complete (
client: GitHub,
deploymentId: number,
status: DeploymentStatus
): Promise<void> {
const statuses = await client.repos.listDeploymentStatuses({
...context.repo,
deployment_id: deploymentId
})
const lastStatus = statuses.data.sort((a, b) => a.id - b.id).slice(-1)[0]
console.log(
`last status for deployment_id '${deploymentId}': ${JSON.stringify(
lastStatus,
null,
2
)}`
)
const statusResult = await client.repos.createDeploymentStatus({
...context.repo,
deployment_id: deploymentId,
state: status,
environment_url: lastStatus.environment_url,
log_url: lastStatus.log_url
})
console.log(`created deployment status: ${JSON.stringify(statusResult.data, null, 2)}`)
}
Example #4
Source File: action.ts From jest-github-action with MIT License | 6 votes |
async function deletePreviousComments(octokit: GitHub) {
const { data } = await octokit.issues.listComments({
...context.repo,
per_page: 100,
issue_number: getPullId(),
})
return Promise.all(
data
.filter(
(c) =>
c.user.login === "github-actions[bot]" && c.body.startsWith(COVERAGE_HEADER),
)
.map((c) => octokit.issues.deleteComment({ ...context.repo, comment_id: c.id })),
)
}
Example #5
Source File: create.ts From action-deploy with MIT License | 6 votes |
export async function create (
client: GitHub,
logUrl: string,
description: string,
initialStatus: DeploymentStatus,
environment: string,
environmentUrl: string,
mainBranch: string
): Promise<string> {
await invalidatePreviousDeployments(client, environment)
// get main branch sha to store in payload
const mainBranchSha = await getMainSha(client, mainBranch)
const payload = JSON.stringify({ actor: context.actor, main_sha: mainBranchSha })
const deployment = await client.repos.createDeployment({
...context.repo,
ref: context.ref,
required_contexts: [],
environment,
transient_environment: true,
auto_merge: false,
description,
payload
})
console.log(`created deployment: ${JSON.stringify(deployment.data, null, 2)}`)
const status = await client.repos.createDeploymentStatus({
...context.repo,
deployment_id: deployment.data.id,
state: initialStatus,
log_url: logUrl,
environment_url: environmentUrl
})
console.log(`created deployment status: ${JSON.stringify(status.data, null, 2)}`)
return deployment.data.id.toString()
}
Example #6
Source File: delete-all.ts From action-deploy with MIT License | 6 votes |
export async function deleteAll (
client: GitHub,
environment: string
): Promise<void> {
const deployments = await client.repos.listDeployments({
...context.repo,
environment
})
await Promise.all(deployments.data.map(async (deployment) => {
// invalidate deployment first
// since we can't delete active deployment
console.log(`invalidate deployment: ${deployment.id}`)
await client.repos.createDeploymentStatus({
...context.repo,
deployment_id: deployment.id,
state: 'failure'
})
// then delete it
console.log(`delete deployment: ${deployment.url}`)
await client.request(deployment.url, { method: 'DELETE' })
}))
}
Example #7
Source File: delete.ts From action-deploy with MIT License | 6 votes |
export async function deleteDeployment (
client: GitHub,
deploymentId: number
): Promise<void> {
// invalidate deployment first
// since we can't delete active deployment
console.log(`invalidate deployment: ${deploymentId}`)
const status = await client.repos.createDeploymentStatus({
...context.repo,
deployment_id: deploymentId,
state: 'failure'
})
// then delete it
const deploymentUrl = status.data.deployment_url
console.log(`delete deployment: ${deploymentUrl}`)
await client.request(deploymentUrl, { method: 'DELETE' })
}
Example #8
Source File: pub.ts From vscode-drawio with GNU General Public License v3.0 | 6 votes |
export async function run(): Promise<void> {
const version = getChangelog().latestVersion;
if (version.kind === "unreleased") {
return;
}
await exec("yarn", [
"vsce",
"publish",
"--packagePath",
"./vscode-drawio.vsix",
"--pat",
process.env.MARKETPLACE_TOKEN!,
]);
const gitTag = `v${version.version}`;
console.log(`Creating a version tag "${gitTag}".`);
const api = new GitHub(process.env.GH_TOKEN!);
await api.git.createRef({
...context.repo,
ref: `refs/tags/${gitTag}`,
sha: context.sha,
});
console.log("Uploading to open-vsx...");
await exec("yarn", [
"ovsx",
"publish",
"./vscode-drawio.vsix",
"-p",
process.env.OPEN_VSX_TOKEN!,
]);
}
Example #9
Source File: GithubHelper.ts From file-changes-action with MIT License | 6 votes |
/**
* @function initClient
* @throws {Error} not sure what might trigger this, but it will throw an error.
* @param token github token to add to client
* @returns authenticated github client
*/
export function initClient(token: string): GitHub {
try {
return new GitHub(token)
} catch (error) {
const eString = `There was an error creating github client. Please check your token.`
throw new Error(
getErrorString(error.name, error.status, initClient.name, eString, error)
)
}
}
Example #10
Source File: main.ts From action-wait-for-check with MIT License | 6 votes |
async function run(): Promise<void> {
try {
const token = core.getInput('token', {required: true})
const result = await poll({
client: new GitHub(token),
log: msg => core.info(msg),
checkName: core.getInput('checkName', {required: true}),
owner: core.getInput('owner') || context.repo.owner,
repo: core.getInput('repo') || context.repo.repo,
ref: core.getInput('ref') || context.sha,
timeoutSeconds: parseInt(core.getInput('timeoutSeconds') || '600'),
intervalSeconds: parseInt(core.getInput('intervalSeconds') || '10')
})
core.setOutput('conclusion', result)
} catch (error) {
core.setFailed(error.message)
}
}
Example #11
Source File: main.ts From size-limit-action with ISC License | 6 votes |
async function fetchPreviousComment(
octokit: GitHub,
repo: { owner: string; repo: string },
pr: { number: number }
) {
// TODO: replace with octokit.issues.listComments when upgraded to v17
const commentList = await octokit.paginate(
"GET /repos/:owner/:repo/issues/:issue_number/comments",
{
...repo,
// eslint-disable-next-line camelcase
issue_number: pr.number
}
);
const sizeLimitComment = commentList.find(comment =>
comment.body.startsWith(SIZE_LIMIT_HEADING)
);
return !sizeLimitComment ? null : sizeLimitComment;
}
Example #12
Source File: foreman.ts From setup-foreman with MIT License | 6 votes |
async function getReleases(octokit: GitHub): Promise<GitHubRelease[]> {
const response = await octokit.repos.listReleases({
owner: "Roblox",
repo: "foreman"
});
const releases = response.data as GitHubRelease[];
releases.sort((a, b) => -semver.compare(a.tag_name, b.tag_name));
return releases;
}
Example #13
Source File: applyLabels.ts From super-labeler-action with GNU General Public License v3.0 | 6 votes |
addRemoveLabel = async ({
client,
curLabels,
label,
labelIdToName,
matches,
num,
repo,
requires,
}: {
client: GitHub;
curLabels: Labels;
label: string;
labelIdToName: { [key: string]: string };
matches: number;
num: number;
repo: Repo;
requires: number;
}) => {
const labelName = labelIdToName[label];
const hasLabel = curLabels.filter((l) => l.name === labelName).length > 0;
if (matches >= requires && !hasLabel) {
core.debug(`${matches} >= ${requires} matches, adding label "${label}"...`);
await addLabel({ client, repo, num, label: labelName });
}
if (matches < requires && hasLabel) {
core.debug(
`${matches} < ${requires} matches, removing label "${label}"...`,
);
await removeLabel({ client, repo, num, label: labelName });
}
}
Example #14
Source File: syncLabels.ts From super-labeler-action with GNU General Public License v3.0 | 6 votes |
syncLabels = async ({
client,
config,
repo,
}: {
client: GitHub;
config: Config['labels'];
repo: Repo;
}) => {
const curLabels = await getLabels({ client, repo });
core.debug(`curLabels: ${JSON.stringify(curLabels)}`);
for (const _configLabel of Object.values(config)) {
const configLabel = {
..._configLabel,
color: _configLabel.colour,
};
const curLabel = curLabels.filter((l) => l.name === configLabel.name);
if (curLabel.length > 0) {
const label = curLabel[0];
if (
label.description !== configLabel.description ||
label.color !== formatColour(configLabel.color)
) {
core.debug(
`Recreate ${JSON.stringify(configLabel)} (prev: ${JSON.stringify(
label,
)})`,
);
await updateLabel({ client, repo, label: configLabel });
}
} else {
core.debug(`Create ${JSON.stringify(configLabel)}`);
await createLabel({ client, repo, label: configLabel });
}
}
}
Example #15
Source File: parseContext.ts From super-labeler-action with GNU General Public License v3.0 | 6 votes |
parsePRContext = async (
context: Context,
client: GitHub,
repo: Repo,
): Promise<PRContext | undefined> => {
const pr = context.payload.pull_request;
if (!pr) {
return;
}
const num = pr.number;
const labels = parseLabels(pr.labels);
const files = await listFiles({ client, repo, num });
return {
labels,
num,
prProps: {
branch: pr.head.ref,
creator: pr.user.login,
description: pr.body || '',
files,
isDraft: pr.draft,
locked: pr.locked,
state: pr.state,
title: pr.title,
},
};
}
Example #16
Source File: applyLabels.ts From super-labeler-action with GNU General Public License v3.0 | 6 votes |
applyPRLabels = async ({
client,
config,
labelIdToName,
prContext,
repo,
}: {
client: GitHub;
config: Config['pr'];
labelIdToName: { [key: string]: string };
prContext: PRContext;
repo: Repo;
}) => {
const { labels: curLabels, prProps, num } = prContext;
for (const [label, opts] of Object.entries(config)) {
core.debug(`Label: ${label}`);
const matches = forConditions<PRCondition>(opts.conditions, (condition) => {
const handler = getPRConditionHandler(condition);
return handler?.(condition as any, prProps) || false;
});
await addRemoveLabel({
client,
curLabels,
label,
labelIdToName,
matches,
num,
repo,
requires: opts.requires,
});
}
}
Example #17
Source File: applyLabels.ts From super-labeler-action with GNU General Public License v3.0 | 6 votes |
applyIssueLabels = async ({
client,
config,
issueContext,
labelIdToName,
repo,
}: {
client: GitHub;
config: Config['issue'];
issueContext: IssueContext;
labelIdToName: { [key: string]: string };
repo: Repo;
}) => {
const { labels: curLabels, issueProps, num } = issueContext;
for (const [label, opts] of Object.entries(config)) {
core.debug(`Label: ${label}`);
const matches = forConditions<IssueCondition>(
opts.conditions,
(condition) => {
const handler = getIssueConditionHandler(condition);
return handler?.(condition as any, issueProps) || false;
},
);
await addRemoveLabel({
client,
curLabels,
label,
labelIdToName,
matches,
num,
repo,
requires: opts.requires,
});
}
}
Example #18
Source File: GithubHelper.ts From file-changes-action with MIT License | 5 votes |
/**
* @function getChangedFiles
* @param client client authenticated github client (possibly un-authenticated if public)
* @param repoFull repo owner/repo string. trilom/file-changes-action
* @type {Inferred} pass in iinferred type from inferInput
* @returns Promise of an array of changed PR or push files
*/
export async function getChangedFiles(
client: GitHub,
repoFull: string,
{before, after, pr = NaN}: Inferred
): Promise<GitHubFile[]> {
try {
if (repoFull.split('/').length > 2) {
throw new Error(
getErrorString(
`Bad-Repo`,
500,
'self',
`Repo input of ${repoFull} has more than 2 length after splitting.`
)
)
}
const owner = repoFull.split('/')[0]
const repo = repoFull.split('/')[1]
let files: GitHubFile[] = []
if (Number.isNaN(pr))
files = await getChangedPushFiles(
client,
repo,
owner,
before || '',
after || ''
)
else files = await getChangedPRFiles(client, repo, owner, pr)
return files
} catch (error) {
const pError = JSON.parse(error.message)
if (pError.from.includes('getChanged'))
throw new Error(
JSON.stringify(
{...pError, ...{from: `${error.status}/${error.name}`}},
null,
2
)
)
const eString = `There was an error getting change files outputs pr: ${pr} before: ${before} after: ${after}`
const ePayload: string = getErrorString(
`Unknown Error:${error.name}`,
error.status,
getChangedFiles.name,
eString,
error.message
)
throw new Error(ePayload)
}
}
Example #19
Source File: GithubHelper.ts From file-changes-action with MIT License | 5 votes |
/**
* @function getChangedPRFiles
* @throws {Error} when a 404 or other is received. 404 can be bad repo, owner, pr, or unauthenticated
* @param client authenticated github client (possibly un-authenticated if public)
* @param repo repo string. file-changes-action
* @param owner owner string. trilom
* @param pullNumber pr number to get changed files for
* @returns Promise of array of changed files
*/
export async function getChangedPRFiles(
client: GitHub,
repo: string,
owner: string,
pullNumber: number
): Promise<GitHubFile[]> {
try {
const options = client.pulls.listFiles.endpoint.merge({
owner,
repo,
pull_number: pullNumber
})
const files: GitHubFile[] = await client.paginate(
options,
response => response.data
)
return files
} catch (error) {
const eString = `There was an error getting change files for repo:${repo} owner:${owner} pr:${pullNumber}`
let ePayload: string
if (error.name === 'HttpError' && +error.status === 404)
ePayload = getErrorString(
error.name,
error.status,
getChangedPRFiles.name,
eString,
error
)
else
ePayload = getErrorString(
`Unknown Error:${error.name || ''}`,
error.status,
getChangedPRFiles.name,
eString,
error.message
)
throw new Error(ePayload)
}
}
Example #20
Source File: GithubHelper.ts From file-changes-action with MIT License | 5 votes |
/**
* @function getChangedPushFiles
* @throws {Error} when a 404 or other is received. 404 can be bad repo, owner, sha, or unauthenticated
* @param client authenticated github client (possibly un-authenticated if public)
* @param repo repo string. file-changes-action
* @param owner owner string. trilom
* @param base BASE commit sha to compare
* @param head HEAD commit sha to compare
* @returns Promise of array of changed files
*/
export async function getChangedPushFiles(
client: GitHub,
repo: string,
owner: string,
base: string,
head: string
): Promise<GitHubFile[]> {
try {
const options = client.repos.compareCommits.endpoint.merge({
owner,
repo,
base,
head
})
const files: GitHubFile[] = await client.paginate(
options,
response => response.data.files
)
return files
} catch (error) {
const eString = `There was an error getting change files for repo:${repo} owner:${owner} base:${base} head:${head}`
let ePayload: string
if (error.name === 'HttpError' && +error.status === 404)
ePayload = getErrorString(
error.name,
error.status,
getChangedPushFiles.name,
eString,
error
)
else
ePayload = getErrorString(
`Unknown Error:${error.name || ''}`,
error.status,
getChangedPushFiles.name,
eString,
error.message
)
throw new Error(ePayload)
}
}
Example #21
Source File: create.ts From action-deploy with MIT License | 5 votes |
async function invalidatePreviousDeployments (
client: GitHub,
environment: string
): Promise<void> {
const deployments = await client.repos.listDeployments({
...context.repo,
ref: context.ref,
environment
})
await Promise.all(
deployments.data.map(async deployment => {
const statuses = await client.repos.listDeploymentStatuses({
...context.repo,
deployment_id: deployment.id
})
const lastStatus = statuses.data.sort((a, b) => a.id - b.id).slice(-1)[0]
console.log(
`last status for deployment_id '${deployment.id}': ${JSON.stringify(
lastStatus,
null,
2
)}`
)
// invalidate the deployment
if (lastStatus?.state === 'success') {
console.log(`invalidating deployment: ${JSON.stringify(deployment, null, 2)}`)
await client.repos.createDeploymentStatus({
...context.repo,
deployment_id: deployment.id,
state: 'inactive',
environment_url: lastStatus.environment_url,
log_url: lastStatus.log_url
})
}
})
)
}
Example #22
Source File: action.ts From jest-github-action with MIT License | 5 votes |
export async function run() {
let workingDirectory = core.getInput("working-directory", { required: false })
let cwd = workingDirectory ? resolve(workingDirectory) : process.cwd()
const CWD = cwd + sep
const RESULTS_FILE = join(CWD, "jest.results.json")
try {
const token = process.env.GITHUB_TOKEN
if (token === undefined) {
core.error("GITHUB_TOKEN not set.")
core.setFailed("GITHUB_TOKEN not set.")
return
}
const cmd = getJestCommand(RESULTS_FILE)
await execJest(cmd, CWD)
// octokit
const octokit = new GitHub(token)
// Parse results
const results = parseResults(RESULTS_FILE)
// Checks
const checkPayload = getCheckPayload(results, CWD)
await octokit.checks.create(checkPayload)
// Coverage comments
if (getPullId() && shouldCommentCoverage()) {
const comment = getCoverageTable(results, CWD)
if (comment) {
await deletePreviousComments(octokit)
const commentPayload = getCommentPayload(comment)
await octokit.issues.createComment(commentPayload)
}
}
if (!results.success) {
core.setFailed("Some jest tests failed.")
}
} catch (error) {
console.error(error)
core.setFailed(error.message)
}
}
Example #23
Source File: main.ts From hans-landa with MIT License | 5 votes |
async function buildOnComment(props: ActionProps): Promise<void> {
console.log('>>Triggered by comment on PR')
console.log(JSON.stringify(context.payload, null, 2))
const client = new GitHub(props.githubToken)
const prNumber = context.payload.issue?.number
const repo = context.payload.repository?.name
const owner = context.payload.repository?.owner.login
console.log({
prNumber,
repo,
owner,
})
if (!prNumber || !repo || !owner) {
console.log('Unable to find PR info', {
prNumber,
repo,
owner,
})
return
}
const pr = await client.pulls.get({ pull_number: prNumber, owner, repo })
const branchName = pr.data.head.ref
const commitHash = pr.data.head.sha
const branchDestName = pr.data.base.ref
const { command, workflow } = parseComment(context.payload.comment.body)
console.log({
command,
workflow,
COMMAND_TRIGGER,
})
console.log(`command === COMMAND_TRIGGER: ${command === COMMAND_TRIGGER}`)
console.log(
`workflow === props.bitriseWorkflow : ${workflow ===
props.bitriseWorkflow}`,
)
console.log(
`workflow === props.commandAlias : ${workflow === props.commandAlias}`,
)
if (
command === COMMAND_TRIGGER &&
(workflow === props.bitriseWorkflow || workflow === props.commandAlias)
) {
triggerBuild({
...props,
branchName,
commitHash,
commitMessage: '',
pullRequestId: prNumber,
branchDestName,
})
}
}
Example #24
Source File: main.ts From setup-foreman with MIT License | 5 votes |
async function run(): Promise<void> {
try {
const versionReq: string = getInput("version");
const githubToken: string = getInput("token");
const workingDir: string = getInput("working-directory");
const octokit = new GitHub(githubToken);
const releases = await foreman.getReleases(octokit);
debug("Choosing release from GitHub API");
const release = foreman.chooseRelease(versionReq, releases);
if (release == null) {
throw new Error(
`Could not find Foreman release for version ${versionReq}`
);
}
debug(`Chose release ${release.tag_name}`);
const asset = foreman.chooseAsset(release);
if (asset == null) {
throw new Error(
`Could not find asset for version ${release.tag_name} on platform ${process.platform}`
);
}
debug(`Chose release asset ${asset.browser_download_url}`);
const zipPath = await downloadTool(asset.browser_download_url);
const extractedPath = await extractZip(zipPath, ".foreman-install");
addPath(resolve(extractedPath));
if (process.platform === "darwin" || process.platform === "linux") {
await exec("chmod +x .foreman-install/foreman");
}
await foreman.authenticate(githubToken);
foreman.addBinDirToPath();
if (workingDir !== undefined && workingDir !== null && workingDir !== "") {
process.chdir(workingDir);
}
await foreman.installTools();
} catch (error) {
if (error instanceof Error) {
setFailed(error.message);
}
}
}
Example #25
Source File: main.ts From nunit-reporter with MIT License | 5 votes |
async function run(): Promise<void> {
try {
const path = getInput("path");
const numFailures = parseInt(getInput("numFailures"));
const accessToken = getInput("access-token");
const title = getInput("reportTitle");
const results = await readResults(path);
const octokit = new GitHub(accessToken);
const summary =
results.failed > 0
? `${results.failed} tests failed`
: `${results.passed} tests passed`;
let details =
results.failed === 0
? `** ${results.passed} tests passed**`
: `
**${results.passed} tests passed**
**${results.failed} tests failed**
`;
for (const ann of results.annotations) {
const annStr = generateSummary(ann);
const newDetails = `${details}\n${annStr}`;
if (newDetails.length > 65000) {
details = `${details}\n\n ... and more.`;
break;
} else {
details = newDetails;
}
}
const pr = context.payload.pull_request;
await octokit.checks.create({
head_sha: (pr && pr["head"] && pr["head"].sha) || context.sha,
name: `Tests Report: ${title}`,
owner: context.repo.owner,
repo: context.repo.repo,
status: "completed",
conclusion:
results.failed > 0 || results.passed === 0 ? "failure" : "success",
output: {
title,
summary,
annotations: results.annotations.slice(0, numFailures),
text: details,
},
});
} catch (error) {
setFailed(error.message);
}
}
Example #26
Source File: trigger-prerelease.ts From vscode-drawio with GNU General Public License v3.0 | 4 votes |
export async function run(): Promise<void> {
const changelog = getChangelog();
if (changelog.latestVersion.kind === "unreleased") {
console.log("Nothing to publish.");
return;
}
if (changelog.latestVersion.releaseDate !== undefined) {
console.log(
`Version "${
changelog.latestVersion.version
}" already has been published on ${changelog.latestVersion.releaseDate.toDateString()}.`
);
return;
}
const prereleaseVersion = changelog.latestVersion.version;
if (!prereleaseVersion.prerelease) {
throw new Error(
`Cannot release directly! Use a prerelease version first!`
);
}
const api = new GitHub(process.env.GH_TOKEN!);
const prereleaseBranch = `pending-releases/v${prereleaseVersion}`;
const prereleaseRef = `refs/heads/${prereleaseBranch}`;
try {
await api.git.createRef({
...context.repo,
ref: prereleaseRef,
sha: context.sha,
});
} catch (e) {
if (e.toString().indexOf("Reference already exists")) {
throw new Error(
`Version "${prereleaseVersion}" has been published already!`
);
}
throw e;
}
const releaseVersion = prereleaseVersion.with({ prerelease: null });
const targetBranch = `releases/v${releaseVersion}`;
const targetRef = `refs/heads/${targetBranch}`;
try {
await api.git.deleteRef({
...context.repo,
ref: `heads/${targetBranch}`,
});
} catch (e) {
console.error("Could not delete branch: ", e);
}
await api.git.createRef({
...context.repo,
ref: targetRef,
sha: context.sha,
});
const d = (
await api.repos.getContents({
...context.repo,
path: "CHANGELOG.md",
ref: prereleaseRef,
})
).data;
if (Array.isArray(d)) {
throw new Error("Unexpected result");
}
changelog.setLatestVersion(releaseVersion, new Date());
await api.repos.createOrUpdateFile({
...context.repo,
path: "CHANGELOG.md",
branch: prereleaseBranch,
sha: d.sha,
content: Buffer.from(changelog.toString()).toString("base64"),
message: `Release of version ${releaseVersion}`,
});
await api.pulls.create({
...context.repo,
base: targetBranch,
head: prereleaseBranch,
title: `Release ${prereleaseVersion} as ${releaseVersion}`,
body:
`Please vote with **thumbs up** if this build works as expected or **thumbs down** if you found an issue.\n\n` +
`If you found issues, please describe them so they can be fixed!\n\n` +
`Once this pull request receives enough thumbs up and no issues are reported, version ${prereleaseVersion} will be released as ${releaseVersion}`,
});
}
Example #27
Source File: index.ts From vscode-drawio with GNU General Public License v3.0 | 4 votes |
export async function run(): Promise<void> {
const result = execSync("git status", { encoding: "utf-8" });
if (result.indexOf("working tree clean") === -1) {
throw new Error("Working tree is not clean!");
}
const v = getChangelog().latestVersion;
let prerelease: boolean;
let versionName: string;
let version: string;
if (v.kind === "unreleased") {
console.log(
"No need to prepare for insiders - version is not released."
);
prerelease = false;
version = "unreleased";
versionName = "unreleased";
} else if (!v.version.prerelease) {
console.log(
"No need to prepare for insiders - version is not a prerelease."
);
prerelease = false;
version = v.version.toString();
versionName = version;
} else {
// VS Code does not allow for prerelease numbers. This fixes that.
const firstPrereleaseNumber =
(v.version.prerelease.parts.find((p) => typeof p === "number") as
| number
| undefined) || 0;
prerelease = true;
versionName = v.version.toString();
version = v.version
.with({
prerelease: null,
patch: v.version.patch * 100 + firstPrereleaseNumber,
})
.toString();
}
const packageJson = readJsonFile(join(__dirname, "../../package.json"));
const patchPackageJson = readJsonFile(
join(__dirname, "./package-insiders-build.json")
);
let prLink: string | undefined = undefined;
if (prerelease) {
const api = new GitHub(process.env.GH_TOKEN!);
const data = await api.git.getRef({
ref: `heads/pending-releases/v${versionName}`,
...context.repo,
});
console.log(`Pending release commit sha is ${data.data.object.sha}.`);
const prs = await api.repos.listPullRequestsAssociatedWithCommit({
commit_sha: data.data.object.sha,
...context.repo,
});
const pr = prs.data[0];
if (pr) {
prLink = pr.html_url;
}
}
if (prerelease) {
Object.assign(packageJson, patchPackageJson);
}
Object.assign(packageJson, { version, feedbackUrl: prLink, versionName });
writeFileSync(
join(__dirname, "../../package.json"),
JSON.stringify(packageJson, undefined, 4)
);
if (prerelease) {
let content = readFileSync(
join(__dirname, "./README_INSIDERS_BUILD.md"),
{
encoding: "utf-8",
}
);
content = content.replace(/\$commit-sha\$/g, context.sha);
content = content.replace(/\$pr-link\$/g, prLink || "invalid");
writeFileSync(join(__dirname, "../../README.md"), content);
}
}
Example #28
Source File: main.ts From size-limit-action with ISC License | 4 votes |
async function run() {
try {
const { payload, repo } = context;
const pr = payload.pull_request;
if (!pr) {
throw new Error(
"No PR found. Only pull_request workflows are supported."
);
}
const token = getInput("github_token");
const skipStep = getInput("skip_step");
const buildScript = getInput("build_script");
const cleanScript = getInput("clean_script");
const script = getInput("script");
const directory = getInput("directory") || process.cwd();
const windowsVerbatimArguments =
getInput("windows_verbatim_arguments") === "true" ? true : false;
const octokit = new GitHub(token);
const term = new Term();
const limit = new SizeLimit();
const { status, output } = await term.execSizeLimit(
null,
skipStep,
buildScript,
cleanScript,
windowsVerbatimArguments,
directory,
script
);
const { output: baseOutput } = await term.execSizeLimit(
pr.base.ref,
null,
buildScript,
cleanScript,
windowsVerbatimArguments,
directory,
script
);
let base;
let current;
try {
base = limit.parseResults(baseOutput);
current = limit.parseResults(output);
} catch (error) {
console.log(
"Error parsing size-limit output. The output should be a json."
);
throw error;
}
const body = [
SIZE_LIMIT_HEADING,
table(limit.formatResults(base, current))
].join("\r\n");
const sizeLimitComment = await fetchPreviousComment(octokit, repo, pr);
if (!sizeLimitComment) {
try {
await octokit.issues.createComment({
...repo,
// eslint-disable-next-line camelcase
issue_number: pr.number,
body
});
} catch (error) {
console.log(
"Error creating comment. This can happen for PR's originating from a fork without write permissions."
);
}
} else {
try {
await octokit.issues.updateComment({
...repo,
// eslint-disable-next-line camelcase
comment_id: sizeLimitComment.id,
body
});
} catch (error) {
console.log(
"Error updating comment. This can happen for PR's originating from a fork without write permissions."
);
}
}
if (status > 0) {
setFailed("Size limit has been exceeded.");
}
} catch (error) {
setFailed(error.message);
}
}