@actions/core#setFailed TypeScript Examples

The following examples show how to use @actions/core#setFailed. 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: UtilsHelper.ts    From file-changes-action with MIT License 6 votes vote down vote up
/**
 * @function getErrorString
 * @param name name of error
 * @param status status code of error
 * @param from name of function that error is thrown from
 * @param message error message
 * @param error error object to stringify and attach
 */
export function getErrorString(
  name: string,
  status = 500,
  from: string,
  message: string,
  error: any = ''
): string {
  try {
    const test = JSON.stringify(
      {
        error: `${status}/${name}`,
        from,
        message,
        payload: error
      } as ActionError,
      null,
      2
    )
    return test
  } catch (error_) {
    setFailed(`Error throwing error.\n ${JSON.stringify(error_.message)}`)
    throw new Error(
      JSON.stringify({name: '500/undefined', message: 'Error throwing error.'})
    )
  }
}
Example #2
Source File: main.ts    From setup-poetry with MIT License 6 votes vote down vote up
async function run(): Promise<void> {
  try {
    const inputs = getInputs()

    await findPoetry(inputs)
  } catch (error) {
    setFailed(error.message)
  }
}
Example #3
Source File: addEnv.ts    From setup-cpp with Apache License 2.0 6 votes vote down vote up
/** An add path function that works locally or inside GitHub Actions */
export async function addEnv(name: string, valGiven: string | undefined, shouldEscapeSpace: boolean = false) {
  const val = shouldEscapeSpace ? escapeSpace(valGiven) : valGiven
  try {
    if (isGitHubCI()) {
      try {
        exportVariable(name, val)
      } catch (err) {
        error(err as Error)
        await addEnvSystem(name, val)
      }
    } else {
      await addEnvSystem(name, val)
    }
  } catch (err) {
    error(err as Error)
    setFailed(`Failed to export environment variable ${name}=${val}. You should add it manually.`)
  }
}
Example #4
Source File: addEnv.ts    From setup-cpp with Apache License 2.0 6 votes vote down vote up
/** An add path function that works locally or inside GitHub Actions */
export async function addPath(path: string) {
  process.env.PATH = `${path}${delimiter}${process.env.PATH}`
  try {
    if (isGitHubCI()) {
      try {
        ghAddPath(path)
      } catch (err) {
        error(err as Error)
        await addPathSystem(path)
      }
    } else {
      await addPathSystem(path)
    }
  } catch (err) {
    error(err as Error)
    setFailed(`Failed to add ${path} to the percistent PATH. You should add it manually.`)
  }
}
Example #5
Source File: index.ts    From typescript-error-reporter-action with MIT License 6 votes vote down vote up
async function main() {
  try {

    const currentDir = process.cwd()
    const configPath = path.resolve(currentDir, 'tsconfig.json')
    if (!fs.existsSync(configPath)) {
      throw new Error(`could not find tsconfig.json at: ${currentDir}`)
    }

    const tsVersion = parseTSVersion(currentDir)
    const remoteTS = await loadTSModule(tsVersion)
  
    const doctor = Doctor.fromConfigFile(configPath, remoteTS)
    const diagnostics = doctor.getSemanticDiagnostics()

    if (diagnostics) {
      doctor.reporter.reportDiagnostics(diagnostics)
      const errors = diagnostics.filter(d => d.category === DiagnosticCategory.Error)
      if (errors.length) {
        setFailed(`Found ${errors.length} errors!`)
      }
    }

  } catch (e) {
    setFailed(e)
  }
}
Example #6
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 #7
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 #8
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 #9
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 #10
Source File: index.ts    From auto-changelog with MIT License 5 votes vote down vote up
run().catch(setFailed);
Example #11
Source File: index.ts    From create-pull-request with MIT License 5 votes vote down vote up
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);
    }
  }
}
Example #12
Source File: main.ts    From auto-cancel-redundant-workflow with MIT License 5 votes vote down vote up
run().catch(error => {
  console.log(error);
  setFailed(error.message);
});
Example #13
Source File: main.ts    From EIP-Bot with Creative Commons Zero v1.0 Universal 5 votes vote down vote up
_main = (_main_: () => Promise<undefined | void>) => async () => {
  try {
    return await _main_();
  } catch (error: any) {
    await processError(error, {
      critical: async (errMessage, data) => {
        const message = multiLineString("\n")(
          `A critical exception has occurred:`,
          `\tMessage: ${errMessage.toLowerCase()}`,
          data && `\tData:\n${JSON.stringify(data, null, 2)}`,
          getMaintainersString()
        );

        console.log(message);
        if (isProd()) {
          await PullRequestUseCases.postComment(message);
        }

        setFailed(message);
        throw message;
      },
      unhandled: async (error: any) => {
        // useful for making sure that auto-mocking can function (dev tool)
        if (
          isNockDisallowedNetConnect(error) ||
          isNockNoMatchingRequest(error)
        ) {
          throw error;
        }

        const message =
          getUnhandledErrorMessage(error) + getMaintainersString();

        console.log(message);
        if (isProd()) {
          await PullRequestUseCases.postComment(message);
        }

        setFailed(message);
        throw message;
      }
    });
  }
}
Example #14
Source File: main.ts    From EIP-Bot with Creative Commons Zero v1.0 Universal 5 votes vote down vote up
_main_ = async () => {
  // Verify correct environment and request context
  requireEvent();

  const pr = await requirePr();

  // Collect the changes made in the given PR from base <-> head for eip files
  const files = await requireFiles(pr);
  let results: Results = [];
  for await (const file of files) {
    try {
      const dirtyTestResults = await testFile(file);
      const testResults = await purifyTestResults(dirtyTestResults);
      results.push(testResults);
    } catch (err: any) {
      processError(err, {
        gracefulTermination: (message) => {
          results.push({
            filename: file.filename,
            successMessage: message,
            type: ChangeTypes.ambiguous
          });
        },
        requirementViolation: (message) => {
          results.push({
            filename: file.filename,
            errors: [message],
            type: ChangeTypes.ambiguous
          });
        },
        unexpectedError: (message, data) => {
          console.log(JSON.stringify(data, null, 2));
          message = `An unexpected error occurred (cc ${MAINTAINERS().join(
            ", "
          )}): ${message}`;
          results.push({
            filename: file.filename,
            errors: [message],
            type: ChangeTypes.ambiguous
          });
        }
      });
    }
  }

  // updates labels to be as expected
  const expectedLabels = _.uniq(_.map(results, "type"));
  await PullRequestUseCases.updateLabels(expectedLabels);

  if (!results.filter((res) => res.errors).length) {
    const commentMessage = getCommentMessage(
      results,
      "All tests passed; auto-merging..."
    );
    await PullRequestUseCases.postComment(commentMessage);
    console.log(commentMessage);
    return;
  }

  const commentMessage = getCommentMessage(results);

  // to avoid annoying people, it's best to only do this while running prod
  if (isProd()) {
    await PullRequestUseCases.postComment(commentMessage);
    await requestReviewers(
      uniq(results.flatMap((res) => res.mentions).filter(Boolean) as string[])
    );
  }

  console.log(commentMessage);
  return setFailed(commentMessage);
}
Example #15
Source File: index.ts    From auto-changelog with MIT License 5 votes vote down vote up
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 #16
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 #17
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 #18
Source File: index.ts    From write-file-action with Apache License 2.0 5 votes vote down vote up
main().catch((error) => setFailed(error.message));
Example #19
Source File: index.ts    From ticket-check-action with MIT License 4 votes vote down vote up
async function run(): Promise<void> {
  try {
    // Provide complete context object right away if debugging
    debug('context', JSON.stringify(context));

    // Check for a ticket reference in the title
    const title: string = context?.payload?.pull_request?.title;
    const titleRegexBase = getInput('titleRegex', { required: true });
    const titleRegexFlags = getInput('titleRegexFlags', {
      required: true
    });
    const ticketLink = getInput('ticketLink', { required: false });
    const titleRegex = new RegExp(titleRegexBase, titleRegexFlags);
    const titleCheck = titleRegex.exec(title);

    // Instantiate a GitHub Client instance
    const token = getInput('token', { required: true });
    const client = getOctokit(token);
    const { owner, repo, number } = context.issue;
    const login = context.payload.pull_request?.user.login as string;
    const senderType = context.payload.pull_request?.user.type as string;
    const sender: string = senderType === 'Bot' ? login.replace('[bot]', '') : login;

    const linkTicket = async (matchArray: RegExpMatchArray): Promise<void> => {
      debug('match array for linkTicket', JSON.stringify(matchArray));
      debug('match array groups for linkTicket', JSON.stringify(matchArray.groups));

      if (!ticketLink) {
        return;
      }

      const ticketNumber = matchArray.groups?.ticketNumber;

      if (!ticketNumber) {
        debug('ticketNumber not found', 'ticketNumber group not found in match array.');

        return;
      }

      if (!ticketLink.includes('%ticketNumber%')) {
        debug('invalid ticketLink', 'ticketLink must include "%ticketNumber%" variable to post ticket link.');

        return;
      }

      const linkToTicket = ticketLink.replace('%ticketNumber%', ticketNumber);

      const currentReviews = await client.pulls.listReviews({
        owner,
        repo,
        pull_number: number
      });

      debug('current reviews', JSON.stringify(currentReviews));

      if (
        currentReviews?.data?.length &&
        currentReviews?.data.some((review: { body?: string }) => review?.body?.includes(linkToTicket))
      ) {
        debug('already posted ticketLink', 'found an existing review that contains the ticket link');

        return;
      }

      client.pulls.createReview({
        owner,
        repo,
        pull_number: number,
        body: `See the ticket for this pull request: ${linkToTicket}`,
        event: 'COMMENT'
      });
    };

    debug('title', title);

    // Return and approve if the title includes a Ticket ID
    if (titleCheck !== null) {
      debug('success', 'Title includes a ticket ID');
      await linkTicket(titleCheck);

      return;
    }

    const quiet = getInput('quiet', { required: false }) === 'true';

    // Exempt Users
    const exemptUsers = getInput('exemptUsers', { required: false })
      .split(',')
      .map(user => user.trim());

    // Debugging Entries
    debug('sender', sender);
    debug('sender type', senderType);
    debug('quiet mode', quiet.toString());
    debug('exempt users', exemptUsers.join(','));
    debug('ticket link', ticketLink);

    if (sender && exemptUsers.includes(sender)) {
      debug('success', 'User is listed as exempt');

      return;
    }

    // get the title format and ticket prefix
    const ticketPrefix = getInput('ticketPrefix');
    const titleFormat = getInput('titleFormat', { required: true });

    // Check for a ticket reference in the branch
    const branch: string = context.payload.pull_request?.head.ref;
    const branchRegexBase = getInput('branchRegex', { required: true });
    const branchRegexFlags = getInput('branchRegexFlags', {
      required: true
    });
    const branchRegex = new RegExp(branchRegexBase, branchRegexFlags);
    const branchCheck = branchRegex.exec(branch);

    if (branchCheck !== null) {
      debug('success', 'Branch name contains a reference to a ticket, updating title');

      const id = extractId(branch);

      if (id === null) {
        setFailed('Could not extract a ticket ID reference from the branch');

        return;
      }

      client.pulls.update({
        owner,
        repo,
        pull_number: number,
        title: titleFormat
          .replace('%prefix%', ticketPrefix)
          .replace('%id%', id)
          .replace('%title%', title)
      });

      if (!quiet) {
        client.pulls.createReview({
          owner,
          repo,
          pull_number: number,
          body:
            "Hey! I noticed that your PR contained a reference to the ticket in the branch name but not in the title. I went ahead and updated that for you. Hope you don't mind! ☺️",
          event: 'COMMENT'
        });
      }

      await linkTicket(branchCheck);

      return;
    }

    // Retrieve the pull request body and verify it's not empty
    const body = context?.payload?.pull_request?.body;

    if (body === undefined) {
      debug('failure', 'Body is undefined');
      setFailed('Could not retrieve the Pull Request body');

      return;
    }

    debug('body contents', body);

    // Check for a ticket reference number in the body
    const bodyRegexBase = getInput('bodyRegex', { required: true });
    const bodyRegexFlags = getInput('bodyRegexFlags', { required: true });
    const bodyRegex = new RegExp(bodyRegexBase, bodyRegexFlags);
    const bodyCheck = bodyRegex.exec(body);

    if (bodyCheck !== null) {
      debug('success', 'Body contains a reference to a ticket, updating title');

      const id = extractId(bodyCheck[0]);

      if (id === null) {
        setFailed('Could not extract a ticket shorthand reference from the body');

        return;
      }

      client.pulls.update({
        owner,
        repo,
        pull_number: number,
        title: titleFormat
          .replace('%prefix%', ticketPrefix)
          .replace('%id%', id)
          .replace('%title%', title)
      });

      if (!quiet) {
        client.pulls.createReview({
          owner,
          repo,
          pull_number: number,
          body:
            "Hey! I noticed that your PR contained a reference to the ticket in the body but not in the title. I went ahead and updated that for you. Hope you don't mind! ☺️",
          event: 'COMMENT'
        });
      }

      await linkTicket(bodyCheck);

      return;
    }

    // Last ditch effort, check for a ticket reference URL in the body
    const bodyURLRegexBase = getInput('bodyURLRegex', { required: false });

    if (!bodyURLRegexBase) {
      debug('failure', 'Title, branch, and body do not contain a reference to a ticket, and no body URL regex was set');
      setFailed('No ticket was referenced in this pull request');

      return;
    }

    const bodyURLRegexFlags = getInput('bodyURLRegexFlags', {
      required: true
    });
    const bodyURLRegex = new RegExp(bodyURLRegexBase, bodyURLRegexFlags);
    const bodyURLCheck = bodyURLRegex.exec(body);

    if (bodyURLCheck !== null) {
      debug('success', 'Body contains a ticket URL, updating title');

      const id = extractId(bodyURLCheck[0]);

      if (id === null) {
        setFailed('Could not extract a ticket URL from the body');

        return;
      }

      client.pulls.update({
        owner,
        repo,
        pull_number: number,
        title: titleFormat
          .replace('%prefix%', ticketPrefix)
          .replace('%id%', id)
          .replace('%title%', title)
      });

      if (!quiet) {
        client.pulls.createReview({
          owner,
          repo,
          pull_number: number,
          body:
            "Hey! I noticed that your PR contained a reference to the ticket URL in the body but not in the title. I went ahead and updated that for you. Hope you don't mind! ☺️",
          event: 'COMMENT'
        });
      }
    }

    if (titleCheck === null && branchCheck === null && bodyCheck === null && bodyURLCheck === null) {
      debug('failure', 'Title, branch, and body do not contain a reference to a ticket');
      setFailed('No ticket was referenced in this pull request');

      return;
    }
  } catch (error) {
    setFailed(error.message);
  }
}
Example #20
Source File: main.ts    From size-limit-action with ISC License 4 votes vote down vote up
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);
  }
}