@actions/core#getInput TypeScript Examples

The following examples show how to use @actions/core#getInput. 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 vote down vote up
export function renderActions(statusUrl: string, diffUrl: string) {
  const actions: PotentialAction[] = [];
  if (getInput("enable-view-status-action").toLowerCase() === "true") {
    actions.push(
      new PotentialAction(getInput("view-status-action-text"), [statusUrl])
    );
  }
  if (getInput("enable-review-diffs-action").toLowerCase() === "true") {
    actions.push(
      new PotentialAction(getInput("review-diffs-action-text"), [diffUrl])
    );
  }

  // Set custom actions
  const customActions = getInput("custom-actions");
  if (customActions && customActions.toLowerCase() !== "null") {
    try {
      let customActionsCounter = 0;
      const customActionsList = yaml.parse(customActions);
      if (Array.isArray(customActionsList)) {
        (customActionsList as any[]).forEach((action) => {
          if (
            action.text !== undefined &&
            action.url !== undefined &&
            (action.url as string).match(/https?:\/\/\S+/g)
          ) {
            actions.push(new PotentialAction(action.text, [action.url]));
            customActionsCounter++;
          }
        });
      }
      info(`Added ${customActionsCounter} custom facts.`);
    } catch {
      warning("Invalid custom-actions value.");
    }
  }
  return actions;
}
Example #2
Source File: utils.ts    From ms-teams-deploy-card with MIT License 7 votes vote down vote up
export async function formatAndNotify(
  state: "start" | "exit",
  conclusion = "in_progress",
  elapsedSeconds?: number
) {
  let webhookBody: WebhookBody;
  const commit = await getOctokitCommit();
  const cardLayoutStart = getInput(`card-layout-${state}`);

  if (cardLayoutStart === "compact") {
    webhookBody = formatCompactLayout(commit, conclusion, elapsedSeconds);
  } else if (cardLayoutStart === "cozy") {
    webhookBody = formatCozyLayout(commit, conclusion, elapsedSeconds);
  } else {
    webhookBody = formatCompleteLayout(commit, conclusion, elapsedSeconds);
  }

  submitNotification(webhookBody);
}
Example #3
Source File: utils.ts    From ms-teams-deploy-card with MIT License 7 votes vote down vote up
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 #4
Source File: utils.ts    From ms-teams-deploy-card with MIT License 7 votes vote down vote up
export async function getOctokitCommit() {
  const runInfo = getRunInformation();
  info("Workflow run information: " + JSON.stringify(runInfo, undefined, 2));

  const githubToken = getInput("github-token", { required: true });
  const octokit = new Octokit({ auth: `token ${githubToken}` });

  return await octokit.repos.getCommit({
    owner: runInfo.owner,
    repo: runInfo.repo,
    ref: runInfo.ref || "",
  });
}
Example #5
Source File: index.ts    From write-file-action with Apache License 2.0 6 votes vote down vote up
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 #6
Source File: utils.ts    From ms-teams-deploy-card with MIT License 6 votes vote down vote up
export async function getWorkflowRunStatus() {
  const runInfo = getRunInformation();
  const githubToken = getInput("github-token", { required: true });
  const octokit = new Octokit({ auth: `token ${githubToken}` });
  const workflowJobs = await octokit.actions.listJobsForWorkflowRun({
    owner: runInfo.owner,
    repo: runInfo.repo,
    run_id: parseInt(runInfo.runId || "1"),
  });

  const job = workflowJobs.data.jobs.find(
    (job: Octokit.ActionsListJobsForWorkflowRunResponseJobsItem) =>
      job.name === process.env.GITHUB_JOB
  );

  let lastStep;
  const stoppedStep = job?.steps.find(
    (step: Octokit.ActionsListJobsForWorkflowRunResponseJobsItemStepsItem) =>
      step.conclusion === "failure" ||
      step.conclusion === "timed_out" ||
      step.conclusion === "cancelled" ||
      step.conclusion === "action_required"
  );

  if (stoppedStep) {
    lastStep = stoppedStep;
  } else {
    lastStep = job?.steps
      .reverse()
      .find(
        (
          step: Octokit.ActionsListJobsForWorkflowRunResponseJobsItemStepsItem
        ) => step.status === "completed"
      );
  }

  const startTime = moment(job?.started_at, moment.ISO_8601);
  const endTime = moment(lastStep?.completed_at, moment.ISO_8601);
  return {
    elapsedSeconds: endTime.diff(startTime, "seconds"),
    conclusion: lastStep?.conclusion,
  };
}
Example #7
Source File: compact.ts    From ms-teams-deploy-card with MIT License 6 votes vote down vote up
export function formatCompactLayout(
  commit: Octokit.Response<Octokit.ReposGetCommitResponse>,
  conclusion: string,
  elapsedSeconds?: number
) {
  const author = commit.data.author;
  const repoUrl = `https://github.com/${process.env.GITHUB_REPOSITORY}`;
  const shortSha = process.env.GITHUB_SHA?.substr(0, 7);
  const runLink = `${repoUrl}/actions/runs/${process.env.GITHUB_RUN_ID}`;
  const webhookBody = new WebhookBody();

  // Set status and elapsedSeconds
  let labels = `\`${conclusion.toUpperCase()}\``;
  if (elapsedSeconds) {
    labels = `\`${conclusion.toUpperCase()} [${elapsedSeconds}s]\``;
  }

  // Set environment name
  const environment = getInput("environment");
  if (environment !== "") {
    labels += ` \`ENV:${environment.toUpperCase()}\``;
  }

  // Set themeColor
  webhookBody.themeColor = CONCLUSION_THEMES[conclusion] || "957DAD";

  webhookBody.text =
    `${labels} &nbsp; CI [#${process.env.GITHUB_RUN_NUMBER}](${runLink}) ` +
    `(commit [${shortSha}](${commit.data.html_url})) on [${process.env.GITHUB_REPOSITORY}](${repoUrl}) ` +
    `by [@${author.login}](${author.html_url})`;

  return webhookBody;
}
Example #8
Source File: main.ts    From action-eslint with MIT License 6 votes vote down vote up
run = async ():Promise<void> => {
  try {
    const inputs: Inputs = {
      token: getInput('github-token', { required: true }),
      annotations: getBooleanInput('annotations'),
      eslintArgs: getInput('eslint-args').split(' '),
      binPath: getInput('bin-path'),
      extensions: getInput('extensions').split(',').map((ext) => ext.trim()),
    };

    await runEslint(inputs);
    process.exit(0);
  } catch (err) {
    setFailed(err.message);
  }
}
Example #9
Source File: config.ts    From action-setup-vim with MIT License 6 votes vote down vote up
export function loadConfigFromInputs(): Config {
    const neovim = getNeovim();
    return {
        version: getVersion(neovim),
        neovim,
        os: getOs(),
        token: getInput('token') ?? null,
    };
}
Example #10
Source File: config.ts    From action-setup-vim with MIT License 6 votes vote down vote up
function getVersion(neovim: boolean): string {
    const v = getInput('version');
    if (v === '') {
        return 'stable';
    }

    const l = v.toLowerCase();
    if (l === 'stable' || l === 'nightly') {
        return l;
    }

    const re = neovim ? /^v\d+\.\d+\.\d+$/ : /^v7\.\d+(?:\.\d+)?$|^v\d+\.\d+\.\d{4}$/;
    if (!re.test(v)) {
        const repo = neovim ? 'neovim/neovim' : 'vim/vim';
        let msg = `'version' input '${v}' is not a format of Git tags in ${repo} repository. It should match to regex /${re}/. NOTE: It requires 'v' prefix`;
        if (!neovim) {
            msg += ". And the patch version of Vim must be in 4-digits like 'v8.2.0126'";
        }
        throw new Error(msg);
    }

    return v;
}
Example #11
Source File: config.ts    From action-setup-vim with MIT License 6 votes vote down vote up
function getBoolean(input: string, def: boolean): boolean {
    const i = getInput(input).toLowerCase();
    switch (i) {
        case '':
            return def;
        case 'true':
            return true;
        case 'false':
            return false;
        default:
            throw new Error(`'${input}' input only accepts boolean values 'true' or 'false' but got '${i}'`);
    }
}
Example #12
Source File: index.ts    From retry with MIT License 6 votes vote down vote up
function getInputNumber(id: string, required: boolean): number | undefined {
  const input = getInput(id, { required });
  const num = Number.parseInt(input);

  // empty is ok
  if (!input && !required) {
    return;
  }

  if (!Number.isInteger(num)) {
    throw `Input ${id} only accepts numbers.  Received ${input}`;
  }

  return num;
}
Example #13
Source File: minikube.ts    From setup-minikube with MIT License 6 votes vote down vote up
export function setArgs(args: string[]) {
  const inputs: {key: string; flag: string}[] = [
    {key: 'driver', flag: '--driver'},
    {key: 'container-runtime', flag: '--container-runtime'},
    {key: 'kubernetes-version', flag: '--kubernetes-version'},
    {key: 'cpus', flag: '--cpus'},
    {key: 'memory', flag: '--memory'},
    {key: 'cni', flag: '--cni'},
  ]
  inputs.forEach((input) => {
    const value = getInput(input.key).toLowerCase()
    if (value !== '') {
      args.push(input.flag, value)
    }
  })
}
Example #14
Source File: main.ts    From setup-minikube with MIT License 6 votes vote down vote up
// main thing :)
async function run(): Promise<void> {
  try {
    let minikubeVersion = getInput('minikube-version').toLowerCase()
    minikubeVersion = minikubeVersion === 'stable' ? 'latest' : minikubeVersion
    await downloadMinikube(minikubeVersion)
    await startMinikube()
  } catch (error) {
    setFailed(error.message)
  }
}
Example #15
Source File: index.ts    From invoke-aws-lambda with MIT License 6 votes vote down vote up
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 #16
Source File: get-input-as-boolean.ts    From gh-get-current-pr with GNU General Public License v3.0 6 votes vote down vote up
export default function getInputBool(
  name: string,
  defaultValue = false
): boolean {
  const param = getInput(name)
  if (param === 'true' || param === '1') {
    return true
  } else if (param === 'false' || param === '0') {
    return false
  } else return defaultValue
}
Example #17
Source File: inputs.ts    From setup-poetry with MIT License 6 votes vote down vote up
export function getVersionInput(name: string): string | null {
  const version = getInput(name)
  if (!version) {
    return null
  }

  const coerced = semver.coerce(version)
  if (!coerced) {
    throw new Error(`Passed Poetry version '${version}' is not a valid`)
  } else if (!semver.satisfies(coerced, ">=1.0")) {
    throw new Error(
      `Passed Poetry version '${coerced}' is not supported.
       Please use any other supported version >=1.0`
    )
  }

  return version.trim()
}
Example #18
Source File: context.ts    From auto-changelog with MIT License 6 votes vote down vote up
export async function getInputs(): Promise<ActionInputsI> {
  const commitTypes = YAML.parse(getInput("commit-types", { required: true }));
  const defaultCommitType = getInput("default-commit-type", { required: true });
  const releaseName = getInput("release-name", { required: true });
  const mentionAuthors = getBooleanInput("mention-authors", { required: true });
  const mentionNewContributors = getBooleanInput("mention-new-contributors", {
    required: true,
  });
  const includeCompare = getBooleanInput("include-compare", { required: true });
  const semver = getBooleanInput("semver", { required: true });

  return Joi.object<ActionInputsI, true>()
    .keys({
      commitTypes: Joi.object<TypesI>()
        .pattern(Joi.string(), Joi.string())
        .required(),
      defaultCommitType: Joi.string().required(),
      releaseName: Joi.string().required(),
      mentionAuthors: Joi.boolean().required(),
      mentionNewContributors: Joi.boolean().required(),
      includeCompare: Joi.boolean().required(),
      semver: Joi.boolean().required(),
    })
    .validateAsync({
      commitTypes,
      defaultCommitType,
      releaseName,
      mentionAuthors,
      mentionNewContributors,
      includeCompare,
      semver,
    });
}
Example #19
Source File: index.ts    From invoke-aws-lambda with MIT License 6 votes vote down vote up
setAWSCredentials = () => {
  const accessKeyId = getInput(Credentials.AWS_ACCESS_KEY_ID);
  setSecret(accessKeyId);

  const secretAccessKey = getInput(Credentials.AWS_SECRET_ACCESS_KEY);
  setSecret(secretAccessKey);

  const sessionToken = getInput(Credentials.AWS_SESSION_TOKEN);
  // Make sure we only mask if specified
  if (sessionToken) {
    setSecret(sessionToken);
  }

  AWS.config.credentials = {
    accessKeyId,
    secretAccessKey,
    sessionToken,
  };
}
Example #20
Source File: github.ts    From hans-landa with MIT License 6 votes vote down vote up
/**
 * Validate and return the props given to the action.
 * See action.yml
 */
export function getActionProps(): ActionProps {
  const triggerOn = (getInput('trigger_on', { required: false }) ||
    'all') as TriggerType
  return {
    triggerOn,
    bitriseAppSlug: getInput('bitrise_app_slug', { required: true }),
    bitriseBuildTriggerToken: getInput('bitrise_build_trigger_token', {
      required: true,
    }),
    bitriseWorkflow: getInput('bitrise_workflow', { required: true }),
    githubToken: getInput('github_token', { required: true }),
    commandAlias: getInput('command_alias', { required: false }),
  }
}
Example #21
Source File: index.ts    From invoke-aws-lambda with MIT License 6 votes vote down vote up
setAWSConfigOptions = () => {
  const httpTimeout = getInput(ExtraOptions.HTTP_TIMEOUT);

  if (httpTimeout) {
    AWS.config.httpOptions = { timeout: parseInt(httpTimeout, 10) };
  }

  const maxRetries = getInput(ExtraOptions.MAX_RETRIES);

  if (maxRetries) {
    AWS.config.maxRetries = parseInt(maxRetries, 10);
  }
}
Example #22
Source File: misc.ts    From auto-cancel-redundant-workflow with MIT License 5 votes vote down vote up
isExcludeMerged       = (): boolean => Utils.getBoolValue(getInput('EXCLUDE_MERGED'))
Example #23
Source File: inputs.ts    From setup-poetry with MIT License 5 votes vote down vote up
export function getBooleanInput(name: string, default_ = false): boolean {
  const value = getInput(name)
  if (!value) {
    return default_
  }

  return value === "true"
}
Example #24
Source File: main.ts    From nunit-reporter with MIT License 5 votes vote down vote up
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 #25
Source File: main.ts    From setup-foreman with MIT License 5 votes vote down vote up
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 #26
Source File: cozy.ts    From ms-teams-deploy-card with MIT License 5 votes vote down vote up
export function formatCozyLayout(
  commit: Octokit.Response<Octokit.ReposGetCommitResponse>,
  conclusion: string,
  elapsedSeconds?: number
) {
  const timezone = getInput("timezone") || "UTC";
  const nowFmt = moment()
    .tz(timezone)
    .format("dddd, MMMM Do YYYY, h:mm:ss a z");
  const webhookBody = new WebhookBody();
  const repoUrl = `https://github.com/${process.env.GITHUB_REPOSITORY}`;
  const shortSha = process.env.GITHUB_SHA?.substr(0, 7);

  // Set status and elapsedSeconds
  let labels = `\`${conclusion.toUpperCase()}\``;
  if (elapsedSeconds) {
    labels = `\`${conclusion.toUpperCase()} [${elapsedSeconds}s]\``;
  }

  // Set environment name
  const environment = getInput("environment");
  if (environment !== "") {
    labels += ` \`ENV:${environment.toUpperCase()}\``;
  }

  // Set themeColor
  webhookBody.themeColor = CONCLUSION_THEMES[conclusion] || "957DAD";

  // Get potential actions
  const actions = renderActions(
    `${repoUrl}/actions/runs/${process.env.GITHUB_RUN_ID}`,
    commit.data.html_url
  );
  const actionsConcat = actions
    .map((action) => ` &nbsp; &nbsp; [${action.name}](${action.target})`)
    .join("");

  const author = commit.data.author;
  // Set sections
  webhookBody.sections = [
    {
      activityTitle: `**CI #${process.env.GITHUB_RUN_NUMBER} (commit ${shortSha})** on [${process.env.GITHUB_REPOSITORY}](${repoUrl})`,
      activityImage: author?.avatar_url || OCTOCAT_LOGO_URL,
      activitySubtitle: author
        ? `by [@${author.login}](${author.html_url}) on ${nowFmt}`
        : nowFmt,
      activityText: `${labels}${actionsConcat}`,
    },
  ];

  return webhookBody;
}
Example #27
Source File: main.ts    From setup-cpp with Apache License 2.0 5 votes vote down vote up
/** Get an object from github actions */
function maybeGetInput(key: string) {
  const value = getInput(key.toLowerCase())
  if (value !== "false" && value !== "") {
    return value
  }
  return undefined // skip installation
}
Example #28
Source File: misc.ts    From auto-cancel-redundant-workflow with MIT License 5 votes vote down vote up
getTargetRunId   = (context: Context): number => parseNumber(getInput('TARGET_RUN_ID'), context.runId)
Example #29
Source File: misc.ts    From auto-cancel-redundant-workflow with MIT License 5 votes vote down vote up
getIntervalMs    = (): number | undefined => parseNumber(getInput('INTERVAL_MS'), undefined)