@octokit/rest#Octokit TypeScript Examples

The following examples show how to use @octokit/rest#Octokit. 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.util.ts    From amplication with Apache License 2.0 8 votes vote down vote up
/**
 * @see https://docs.github.com/en/rest/reference/users#list-email-addresses-for-the-authenticated-user
 */
export async function getEmail(accessToken: string): Promise<string> {
  const octokit = new Octokit({
    auth: accessToken
  });
  const {
    data: [result]
  } = await octokit.request(GITHUB_USER_EMAILS_ROUTE);

  return (result as { email: string }).email;
}
Example #2
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 #3
Source File: utils.ts    From ledokku with MIT License 7 votes vote down vote up
octoRequestWithUserToken = async (
  requestData: string,
  // requestData: InstallationParams['request'],
  userGithubAccessToken: string,
  userId: string
) => {
  const octokit = new Octokit({
    auth: userGithubAccessToken,
  });

  // let res: InstallationsResponse;

  // type OctoResponse = GetResponseTypeFromEndpointMethod<typeof octokit.request>;

  let res: any;

  try {
    res = await octokit.request(requestData);
    // res = (await octokit.request(
    //   requestData as InstallationParams['request']
    // )) as InstallationsResponse;
  } catch (e) {
    if (e.message === 'Bad credentials') {
      userGithubAccessToken = await refreshAuthToken(userId);
    }

    const octokit = new Octokit({
      auth: userGithubAccessToken,
    });

    res = (await octokit.request(requestData)) as InstallationsResponse;
  }
  return res;
}
Example #4
Source File: comment.ts    From DefinitelyTyped-tools with MIT License 6 votes vote down vote up
export function getCommentData(
  comment: Pick<Octokit.IssuesListCommentsResponseItem, "body" | "user">
): CommentData | undefined {
  if (isPerfComment(comment)) {
    try {
      const trimmed = comment.body.trimLeft();
      const dataText = trimmed
        .substring(commentTagStart.length)
        .substring(0, trimmed.indexOf(commentTagEnd) - commentTagStart.length);
      return JSON.parse(dataText).data;
    } catch {
      return undefined;
    }
  }
  return;
}
Example #5
Source File: github_client.ts    From CIAnalyzer with MIT License 6 votes vote down vote up
constructor(token: string, private options: ArgumentOptions, baseUrl?: string) {
    const MyOctokit = Octokit.plugin(throttling, retry)
    this.octokit = new MyOctokit({
      auth: token,
      baseUrl: (baseUrl) ? baseUrl : 'https://api.github.com',
      log: (options.debug) ? console : undefined,
      throttle: {
        onRateLimit: (retryAfter: number, options: any) => {
          this.octokit.log.warn(
            `Request quota exhausted for request ${options.method} ${options.url}`
          )
          // Retry twice after hitting a rate limit error, then give up
          if (options.request.retryCount <= 2) {
            this.octokit.log.warn(`Retrying after ${retryAfter} seconds!`);
            return true;
          }
        },
        onAbuseLimit: (retryAfter: number, options: any) => {
          // does not retry, only logs a warning
          this.octokit.log.warn(
            `Abuse detected for request ${options.method} ${options.url}`
          )
        },
      }
    })
  }
Example #6
Source File: complete.ts    From ms-teams-deploy-card with MIT License 6 votes vote down vote up
export function formatFilesToDisplay(
  files: Octokit.ReposGetCommitResponseFilesItem[],
  allowedLength: number,
  htmlUrl: string
) {
  const filesChanged = files
    .slice(0, allowedLength)
    .map(
      (file: any) =>
        `[${escapeMarkdownTokens(file.filename)}](${file.blob_url}) (${
          file.changes
        } changes)`
    );

  let filesToDisplay = "";
  if (files.length === 0) {
    filesToDisplay = "*No files changed.*";
  } else {
    filesToDisplay = "* " + filesChanged.join("\n\n* ");
    if (files.length > 7) {
      const moreLen = files.length - 7;
      filesToDisplay += `\n\n* and [${moreLen} more files](${htmlUrl}) changed`;
    }
  }

  return filesToDisplay;
}
Example #7
Source File: index.ts    From pulumitv with Apache License 2.0 6 votes vote down vote up
webhook = new GitHubWebhook("issue-label-check", {
    repository: "pulumitv",
    events: ["issues"],
    token: ghWebhookToken,
    handler: async (event) => {
        const issuesEvent = event.data as IssuesEvent;
        const octokit = new Octokit({
            auth: event.token,
        });

        // We only care about 'closed' actions. Ignore all others.
        if (issuesEvent.action !== "closed") {
            console.log("Ignoring non-close event.");
            return;
        }

        // re-open the issue if we're missing the 'fixed' label
        console.log("Checking labels");
        if (-1 === issuesEvent.issue.labels?.findIndex(l => l.name === "resolution/fixed")) {
            // re-open the issue
            console.log("Re-opening issue");
            await octokit.issues.update({
                owner: issuesEvent.repository.owner.login,
                repo: issuesEvent.repository.name,
                issue_number: issuesEvent.issue.number,
                state: "open",
            });
        }
    },
})
Example #8
Source File: action.ts    From action-terragrunt with MIT License 6 votes vote down vote up
getLatestVersion = async (): Promise<string | null> => {
  const octokit = new Octokit();

  const latestRelease = await octokit.repos.getLatestRelease({
    owner: 'gruntwork-io',
    repo: 'terragrunt'
  });

  return latestRelease.data.name;
}
Example #9
Source File: SingleInstanceGithubCredentialsProvider.ts    From backstage with Apache License 2.0 6 votes vote down vote up
// undefined allows all installations

  constructor(config: GithubAppConfig, baseUrl?: string) {
    this.allowedInstallationOwners = config.allowedInstallationOwners;
    this.baseUrl = baseUrl;
    this.baseAuthConfig = {
      appId: config.appId,
      privateKey: config.privateKey.replace(/\\n/gm, '\n'),
    };
    this.appClient = new Octokit({
      baseUrl,
      headers: HEADERS,
      authStrategy: createAppAuth,
      auth: this.baseAuthConfig,
    });
  }
Example #10
Source File: getOctokit.ts    From DefinitelyTyped-tools with MIT License 6 votes vote down vote up
export function getOctokit() {
  return (
    octokit ||
    (octokit = new Octokit({
      auth: config.github.typeScriptBotAuthToken,
      userAgent: config.github.userAgent,
    }))
  );
}
Example #11
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 #12
Source File: action.ts    From jest-github-action with MIT License 6 votes vote down vote up
getAnnotations = (
  results: FormattedTestResults,
  cwd: string,
): Octokit.ChecksCreateParamsOutputAnnotations[] => {
  if (results.success) {
    return []
  }
  return flatMap(results.testResults, (result) => {
    return filter(result.assertionResults, ["status", "failed"]).map((assertion) => ({
      path: result.name.replace(cwd, ""),
      start_line: assertion.location?.line ?? 0,
      end_line: assertion.location?.line ?? 0,
      annotation_level: "failure",
      title: assertion.ancestorTitles.concat(assertion.title).join(" > "),
      message: strip(assertion.failureMessages?.join("\n\n") ?? ""),
    }))
  })
}
Example #13
Source File: GitReleaseClient.ts    From backstage with Apache License 2.0 6 votes vote down vote up
private async getOctokit() {
    const token = await this.githubAuthApi.getAccessToken(['repo']);

    return {
      octokit: new Octokit({
        auth: token,
        baseUrl: this.apiBaseUrl,
      }),
    };
  }
Example #14
Source File: auth.ts    From bext with MIT License 6 votes vote down vote up
accessToken$
  .pipe(
    map((auth) => (auth ? new Octokit({ auth }) : null)),
    tap((octokit) =>
      octokit?.hook.error('request', (error: any) => {
        if (error?.status === 401) {
          notifications$.getValue()?.notify({
            status: 'warning',
            message: '登录失败,请重新登录',
          });
          accessToken$.next(undefined);
        }
        throw error;
      }),
    ),
  )
  .subscribe(octokit$);
Example #15
Source File: templateReposProvider.ts    From akashlytics with GNU General Public License v3.0 6 votes vote down vote up
async function getTemplatesFromRepo(octokit: Octokit, repoOwner: string, repoName: string, fetcher: (ocktokit, version) => Promise<any>) {
  const repoVersion = await fetchRepoVersion(octokit, repoOwner, repoName);
  const cacheFilePath = `data/templates/${repoOwner}-${repoName}-${repoVersion}.json`;

  if (fs.existsSync(cacheFilePath)) {
    console.log("Serving cached templates from", cacheFilePath);
    const fileContent = fs.readFileSync(cacheFilePath, "utf8");
    return JSON.parse(fileContent);
  } else if (generatingTasks[cacheFilePath]) {
    console.log("Waiting on existing task for", repoOwner, repoName);
    return await generatingTasks[cacheFilePath];
  } else {
    console.log("No cache found for", repoOwner, repoName, "generating...");
    generatingTasks[cacheFilePath] = fetcher(octokit, repoVersion);
    const categories = await generatingTasks[cacheFilePath];
    generatingTasks[cacheFilePath] = null;

    await fs.promises.mkdir(path.dirname(cacheFilePath), { recursive: true });
    await fs.promises.writeFile(cacheFilePath, JSON.stringify(categories, null, 2));

    return categories;
  }
}
Example #16
Source File: github.ts    From annotations-action with MIT License 6 votes vote down vote up
public constructor(token: string) {
    this.client = (new github.GitHub({
      auth: token,
    }) as unknown) as Octokit
    this.context = github.context
    this.owner = this.context.repo.owner
    this.repo = this.context.repo.repo
    this.sha = this.context.payload.pull_request?.head.sha ?? this.context.sha
  }
Example #17
Source File: templateReposProvider.ts    From akashlytics with GNU General Public License v3.0 6 votes vote down vote up
fetchRepoVersion = async (octokit: Octokit, owner: string, repo: string) => {
  const response = await octokit.rest.repos.getBranch({
    owner: owner,
    repo: repo,
    branch: "master"
  });

  githubRequestsRemaining = response.headers["x-ratelimit-remaining"];

  if (response.status !== 200) {
    throw new Error(`Failed to fetch latest version of ${owner}/${repo} from github`);
  }

  return response.data.commit.sha;
}
Example #18
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 #19
Source File: IssueService.ts    From tokenlog with MIT License 6 votes vote down vote up
async function GetRepositories(
  owner: string,
  type: RepositoryType = RepositoryType.PUBLIC,
  limit: number = 25,
  page: number = 1,
  sort: 'created' | 'updated' | 'pushed' | 'full_name' | undefined = 'updated',
  direction: 'asc' | 'desc' | undefined = 'desc'
): Promise<Array<Repository>> {
  const octokit = new Octokit();
  const result = await octokit.repos.listForOrg({ org: owner, type, per_page: limit, page, sort, direction });
  if (result.status !== 200) throw new Error("Couldn't retrieve public repositories");

  return Array.from(result.data)
    .map((i) => toRepository(i))
    .sort((a, b) => b.stargazersCount - a.stargazersCount);
}
Example #20
Source File: main.ts    From reviewer-lottery with MIT License 6 votes vote down vote up
async function run(): Promise<void> {
  try {
    if (!process.env.GITHUB_REF) throw new Error('missing GITHUB_REF')
    if (!process.env.GITHUB_REPOSITORY)
      throw new Error('missing GITHUB_REPOSITORY')
    //comes from {{secrets.GITHUB_TOKEN}}
    const token = core.getInput('repo-token', {required: true})
    const config = getConfig()

    await runLottery(new Octokit({auth: token}), config)
  } catch (error) {
    core.setFailed(error.message)
  }
}
Example #21
Source File: githubProvider.ts    From akashlytics with GNU General Public License v3.0 6 votes vote down vote up
export function getOctokit() {
  const githubPAT = process.env.AkashlyticsGithubPAT;

  if (!githubPAT) {
    throw new Error("AkashlyticsGithubPAT is missing");
  }

  return new Octokit({
    auth: githubPAT,
    userAgent: "Akashlytics API",
    baseUrl: "https://api.github.com"
  });
}
Example #22
Source File: lottery.ts    From reviewer-lottery with MIT License 6 votes vote down vote up
constructor({
    octokit,
    config,
    env
  }: {
    octokit: Octokit
    config: Config
    env: Env
  }) {
    this.octokit = octokit
    this.config = config
    this.env = {
      repository: env.repository,
      ref: env.ref
    }
    this.pr = undefined
  }
Example #23
Source File: action.ts    From jest-github-action with MIT License 5 votes vote down vote up
function getCommentPayload(body: string) {
  const payload: Octokit.IssuesCreateCommentParams = {
    ...context.repo,
    body,
    issue_number: getPullId(),
  }
  return payload
}
Example #24
Source File: repositories.ts    From ledokku with MIT License 5 votes vote down vote up
repositories: QueryResolvers['repositories'] = async (
  _,
  { installationId },
  { userId }
) => {
  if (!userId) {
    throw new Error('Unauthorized');
  }

  const auth = createAppAuth({
    appId: config.githubAppId,
    privateKey: config.githubAppPem,
    clientId: config.githubAppClientSecret,
    clientSecret: config.githubAppClientSecret,
  });

  const installationAuthentication = (await auth({
    type: 'installation',
    installationId,
  })) as AppAuthentication;

  const octo = new Octokit({
    auth: installationAuthentication.token,
  });

  const repos = await octo.request('GET /installation/repositories');

  const repositories = repos.data.repositories.map((r) => {
    const repoToPush = {
      id: r.id.toString(),
      name: r.name,
      fullName: r.full_name,
      private: r.private,
    };

    return repoToPush;
  });

  return repositories;
}
Example #25
Source File: github.ts    From harness-cli with Apache License 2.0 5 votes vote down vote up
constructor(credentials: GitCredentials, baseUrl?: string) {
        this.client = new Octokit({
            auth: credentials.token,
            userAgent: 'harness-cli v0.9.2',
            baseUrl: baseUrl,
        })
    }
Example #26
Source File: IssueService.ts    From tokenlog with MIT License 5 votes vote down vote up
async function GetRepository(owner: string, repo: string): Promise<Repository> {
  const octokit = new Octokit();
  const result = await octokit.repos.get({ owner, repo });
  if (result.status !== 200) throw new Error("Couldn't retrieve repository info");

  return toRepository(result.data);
}
Example #27
Source File: comment.ts    From DefinitelyTyped-tools with MIT License 5 votes vote down vote up
export function isPerfComment({ body, user }: Pick<Octokit.IssuesListCommentsResponseItem, "body" | "user">): boolean {
  return user.login === config.github.typeScriptBotUsername && body.trimLeft().startsWith(commentTagStart);
}
Example #28
Source File: IssueService.ts    From tokenlog with MIT License 5 votes vote down vote up
async function GetRepositoryLabels(owner: string, repo: string): Promise<Array<Label>> {
  const octokit = new Octokit();
  const result = await octokit.issues.listLabelsForRepo({ owner, repo });
  if (result.status !== 200) throw new Error("Couldn't retrieve repository labels");

  return Array.from(result.data).map((i) => toLabel(i));
}
Example #29
Source File: getOctokit.ts    From DefinitelyTyped-tools with MIT License 5 votes vote down vote up
octokit: Octokit | undefined