@actions/core#setOutput TypeScript Examples
The following examples show how to use
@actions/core#setOutput.
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: utils.ts From ms-teams-deploy-card with MIT License | 7 votes |
export function submitNotification(webhookBody: WebhookBody) {
const webhookUri = getInput("webhook-uri", { required: true });
const webhookBodyJson = JSON.stringify(webhookBody, undefined, 2);
return fetch(webhookUri, {
method: "POST",
headers: {
"Content-Type": "application/json",
},
body: webhookBodyJson,
})
.then((response: Response) => {
setOutput("webhook-body", webhookBodyJson);
info(webhookBodyJson);
return response;
})
.catch(console.error);
}
Example #2
Source File: index.ts From write-file-action with Apache License 2.0 | 6 votes |
async function main() {
try {
const path = getInput("path", { required: true });
const contents = getInput("contents", { required: true });
const mode = (getInput("write-mode") || "append").toLocaleLowerCase();
// Ensure the correct mode is specified
if (mode !== "append" && mode !== "overwrite" && mode !== "preserve") {
setFailed("Mode must be one of: overwrite, append, or preserve");
return;
}
// Preserve the file
if (mode === "preserve" && (await existsAsync(path))) {
const statResult = await statAsync(path);
setOutput("size", `${statResult.size}`);
return;
}
const targetDir = dirname(path);
await mkdirP(targetDir);
if (mode === "overwrite") {
await writeFileAsync(path, contents);
} else {
await appendFileAsync(path, contents);
}
const statResult = await statAsync(path);
setOutput("size", `${statResult.size}`);
} catch (error) {
setFailed(error.message);
}
}
Example #3
Source File: llvm.ts From setup-cpp with Apache License 2.0 | 6 votes |
//================================================
// Exports
//================================================
// eslint-disable-next-line @typescript-eslint/no-unused-vars
async function getLLVMPackageInfo(version: string, platform: NodeJS.Platform, _arch: string): Promise<PackageInfo> {
const [specificVersion, url] = await getSpecificVersionAndUrl(VERSIONS, platform, version, getUrl)
setOutput("version", specificVersion)
return {
url,
extractedFolderName: "",
binRelativeDir: "bin",
binFileName: addBinExtension("clang"),
extractFunction:
platform === "win32"
? extractExe
: (file: string, dest: string) => {
return extractTarByExe(file, dest, ["--strip-components=1"])
},
}
}
Example #4
Source File: index.ts From invoke-aws-lambda with MIT License | 6 votes |
main = async () => {
try {
setAWSCredentials();
setAWSConfigOptions();
const params = getParams();
const lambda = new Lambda({ apiVersion, region: getInput('REGION') });
const response = await lambda.invoke(params).promise();
setOutput('response', response);
const succeedOnFailure = getInput(ExtraOptions.SUCCEED_ON_FUNCTION_FAILURE).toLowerCase() === 'true';
if ('FunctionError' in response && !succeedOnFailure) {
throw new Error('Lambda invocation failed! See outputs.response for more information.');
}
} catch (error) {
setFailed(error instanceof Error ? error.message : JSON.stringify(error));
}
}
Example #5
Source File: index.ts From retry with MIT License | 6 votes |
async function runAction() {
await validateInputs();
for (let attempt = 1; attempt <= MAX_ATTEMPTS; attempt++) {
try {
// just keep overwriting attempts output
setOutput(OUTPUT_TOTAL_ATTEMPTS_KEY, attempt);
await runCmd(attempt);
info(`Command completed after ${attempt} attempt(s).`);
break;
} catch (error) {
if (attempt === MAX_ATTEMPTS) {
throw new Error(`Final attempt failed. ${error.message}`);
} else if (!done && RETRY_ON === 'error') {
// error: timeout
throw error;
} else if (RETRY_ON_EXIT_CODE && RETRY_ON_EXIT_CODE !== exit){
throw error;
} else if (exit > 0 && RETRY_ON === 'timeout') {
// error: error
throw error;
} else {
await runRetryCmd();
if (WARNING_ON_RETRY) {
warning(`Attempt ${attempt} failed. Reason: ${error.message}`);
} else {
info(`Attempt ${attempt} failed. Reason: ${error.message}`);
}
}
}
}
}
Example #6
Source File: index.ts From retry with MIT License | 6 votes |
runAction()
.then(() => {
setOutput(OUTPUT_EXIT_CODE_KEY, 0);
process.exit(0); // success
})
.catch((err) => {
// exact error code if available, otherwise just 1
const exitCode = exit > 0 ? exit : 1;
if (CONTINUE_ON_ERROR) {
warning(err.message);
} else {
error(err.message);
}
// these can be helpful to know if continue-on-error is true
setOutput(OUTPUT_EXIT_ERROR_KEY, err.message);
setOutput(OUTPUT_EXIT_CODE_KEY, exitCode);
// if continue_on_error, exit with exact error code else exit gracefully
// mimics native continue-on-error that is not supported in composite actions
process.exit(CONTINUE_ON_ERROR ? 0 : exitCode);
});
Example #7
Source File: index.ts From auto-changelog with MIT License | 5 votes |
async function run() {
const inputs = await getInputs();
const octokit = getOctokit(getToken());
const {
repo: { owner, repo },
sha,
} = context;
let semver: SemVer.SemVer | null = null;
if (inputs.semver) {
semver = SemVer.parse(inputs.releaseName, { includePrerelease: true });
if (semver == null)
return setFailed(
`Expected a semver compatible releaseName, got "${inputs.releaseName}" instead.`,
);
}
let prerelease = false;
if (semver != null) prerelease = semver.prerelease.length > 0;
const { sha: tagRef, name: tagName } = await getTagSha({
octokit,
owner,
repo,
sha,
semver,
prerelease,
});
let changelog = await generate({
octokit,
owner,
repo,
sha,
tagRef,
inputs,
});
if (inputs.mentionNewContributors) {
const { data } = await octokit.rest.repos.generateReleaseNotes({
owner,
repo,
tag_name: inputs.releaseName,
previous_tag_name: tagName,
});
const tokens = marked.lexer(data.body);
const index = tokens.findIndex(
(token) => token.type === "heading" && token.text === "New Contributors",
);
const token = tokens[index + 1];
if (token.type === "list")
changelog += `\n\n## New Contributors\n${token.raw}\n`;
}
if (inputs.includeCompare && tagName != null) {
changelog += `\n\n**Full Changelog**: https://github.com/${owner}/${repo}/compare/${tagName}...${inputs.releaseName}`;
}
info(`-> prerelease: ${prerelease}`);
setOutput("prerelease", prerelease);
info(`-> changelog: "${changelog}"`);
setOutput("changelog", changelog);
}
Example #8
Source File: process.ts From auto-cancel-redundant-workflow with MIT License | 5 votes |
execute = async(logger: Logger, octokit: Octokit, context: Context): Promise<void> => {
if (isExcludeContext(context)) {
logger.info('This is not target context.');
setOutput('ids', '');
return;
}
const runId = getTargetRunId(context);
logger.info('run id: %d', runId);
const run = await getWorkflowRun(runId, octokit, context);
logger.startProcess('run:');
console.log(getFilteredRun(run));
logger.endProcess();
const workflowId = await getWorkflowId(run);
logger.info('workflow id: %d', workflowId);
const runs = await getWorkflowRuns(workflowId, logger, octokit, context);
if (!runs.some(_run => _run.run_number === run.run_number)) {
runs.push(run);
}
logger.startProcess('workflow runs:');
console.log(runs.map(run => getFilteredRun(run)));
logger.endProcess();
// cancel all workflows except latest one (consider re-run)
const runsWithUpdatedAt = runs.map(run => ({...run, updatedAt: getWorkflowRunUpdatedAt(run)}));
const latestRunNumber = Math.max(...runsWithUpdatedAt.map(run => getWorkflowRunNumber(run)));
const latestUpdatedAt = Math.max(...runsWithUpdatedAt.map(run => run.updatedAt));
const targetRuns = runsWithUpdatedAt.filter(
run =>
getWorkflowRunNumber(run) < latestRunNumber && // not latest run
(!isConsiderReRun() || run.updatedAt < latestUpdatedAt), // not re-run (only updated_at seems to be updated even when re-run)
);
logger.log();
logger.startProcess('Cancelling...');
const interval = getIntervalMs();
await targetRuns.reduce(async(prev, run) => {
await prev;
logger.log('cancel: %d', run.id);
try {
await cancelWorkflowRun(run.id, octokit, context);
} catch (error) {
logger.error(error.message);
}
if (interval) {
await Utils.sleep(interval);
}
}, Promise.resolve());
logger.info('total: %d', targetRuns.length);
setOutput('ids', targetRuns.map(run => run.id).join(','));
logger.endProcess();
}
Example #9
Source File: index.ts From create-pull-request with MIT License | 5 votes |
async function run(): Promise<void> {
try {
const { reviewers, labels, ...pullParams } = getInputs();
const options: OctokitOptions = {};
options.baseUrl = process.env.GITHUB_API_URL;
const proxy = process.env.https_proxy || process.env.HTTPS_PROXY;
if (proxy) {
options.request = {
agent: new HttpsProxyAgent(proxy),
};
}
const octokit = new Octokit(options);
const pullRequest = await octokit.pulls.create(pullParams);
const pullNumber = pullRequest.data.number;
const htmlUrl = pullRequest.data.html_url;
if (reviewers.length > 0) {
await octokit.pulls.createReviewRequest({
owner: pullParams.owner,
repo: pullParams.repo,
pull_number: pullNumber,
reviewers,
});
}
if (labels.length > 0) {
await octokit.issues.addLabels({
owner: pullParams.owner,
repo: pullParams.repo,
issue_number: pullNumber,
labels: labels,
});
}
setOutput('number', pullNumber.toString());
setOutput('html_url', htmlUrl);
setOutput('created', 'true');
} catch (error) {
if (error.message && error.message.includes('A pull request already exists')) {
setOutput('created', 'false');
} else {
setFailed(error.message);
}
}
}