※当サイトの記事には、広告・プロモーションが含まれます。

GitHub Appsで管理しているGitリポジトリの確認はREST APIでする感じになるのか

nazology.kusuguru.co.jp

「終わりがない」というイメージで語られがちな無限。

しかし、その「終わりなさ」に多くの種類があるといったら驚くでしょうか?

数学者が「新しい種類の無限」を発見! - ナゾロジー

オーストリアのウィーン工科大学(TUW)で行われた研究により、これまで知られていなかった全く新しいタイプの無限が発見されました。

数学者が「新しい種類の無限」を発見! - ナゾロジー

⇧ amazing...

GitHub Appsとは

「GitHub」のドキュメントによりますと、

docs.github.com

⇧「Developers」に属する機能の内の1つで、

docs.github.com

About GitHub Apps

GitHub Apps are tools that extend GitHub's functionality. GitHub Apps can do things on GitHub like open issues, comment on pull requests, and manage projects. They can also do things outside of GitHub based on events that happen on GitHub. For example, a GitHub App can post on Slack when an issue is opened on GitHub.

https://docs.github.com/en

⇧ とあり、「GitHub」の機能を拡張するツールであると。

「GitHub」上で管理している「Gitリポジトリ」に対しての操作を行うことができるものであると。

「GitHub Apps」の仕組みについては、

⇧ 上記のPDFの概要図がイメージし易いかと。

「GitHub App」を作成した後に、

  1. 「GitHub App」で「秘密キー(.pemファイル)」を生成する
    「Client ID」「App ID」「Installation ID」が割り当てされる
  2. 「GitHub App」に「Gitリポジトリ」を登録する
  3. 「秘密キー(.pemファイル)」「Client ID」「Installation ID」を、REST APIを実行するアプリケーションが参照できる場所に配置する

としておくと、

  1. 「秘密キー(.pemファイル)」「Client ID」を元に「JWT(JSON WEB TOKEN)」を生成
  2. 「JWT(JSON WEB TOKEN)」と「Installation ID」を元に「Installation Access Token」の取得リクエストを実行

という形で、「Installation Access Token」が取得でき、「GitHub App」に登録している「Private Repository」に対して、

  • git clone
  • git push

など実行するために必要な「認証」用の「トークン」が取得できるようになりますと。

いろいろと制約が増えていっているのは、

ts0818.hatenablog.com

⇧ 前回の記事でちらっと触れました。

GitHub Appsで管理しているGitリポジトリの確認はREST APIでする感じになるのか

で、「GitHub App」に「Gitリポジトリ」を追加する方式としては、

docs.github.com

⇧ 公式のドキュメントによりますと、

  1. すべてのリポジトリ
  2. 選択したレポジトリのみ

の2択になるようなのだけど、

docs.github.com

⇧「Gitリポジトリ」の登録の方式については、後から変更できるのかどうかについては言及されていないのよね...

いずれにしろ、「GitHub App」で管理する「Gitリポジトリ」の数が増えてきた場合に、ブラウザのようなGUI上での確認が辛くなってきますと。

仮に、1000個の「Gitリポジトリ」を「GitHub App」で管理していたとした場合、画面でポチポチ確認するのは辛いですと。(おそらく、GUI上だと「pager(ページャ)」とかで一画面に表示できる件数を制御してる気がする)

「pager(ページャ)」はというと、

ページャ(pager、ページャーとも)とは、CUI環境でテキストファイルを閲覧するためのソフトウェア。Unix系のシステムでよく用いられる。テキストファイルの内容を標準出力に1画面単位で表示する。

ページャ - Wikipedia

⇧ 上記の説明にある通りなんだけど、昨今は、

developers.google.com

⇧「pager(ページャ)」の実装も多岐に渡るようです。

話が脱線しましたが、で、調べた感じ、「organization」で管理している「Gitリポジトリ」を例とした場合、

■organizationのGitリポジトリ一覧

docs.github.com

■GitHub Appに登録されているGitリポジトリ一覧

docs.github.com

⇧ で、

  1. 全てのGitリポジトリ
  2. GitHub Appで管理されているGitリポジトリ

の情報が取得できる想定なので、差分を比較すれば、全体の「Gitリポジトリ」の内、何割が「GitHub App」で管理できているのかを確認することはできそうですと。

で、「GitHub App」に「Gitリポジトリ」を「追加」「削除」なども「REST API」で可能らしい。

■GitHub AppにGitリポジトリを追加

docs.github.com

docs.github.com

「更新」はちょっと見つけられなかった...

とりあえず、

docs.github.com

docs.github.com

⇧「REST API のレート制限」が存在するので、要注意ですかね...

あとは、前回の記事でも触れた、

github.blog

⇧ 一度に取得できる「Gitリポジトリ」の数が、500個というのはインパクトが大きい気がしている...

「GitHub App」自体の数については、

docs.github.com

⇧『ユーザーまたは組織は、最大 100 個の GitHub Apps を登録できますが、アカウントにインストールできる GitHub Apps の数に制限はありません。』をどう解釈すれば良いのかが分からな過ぎる...

  1. アカウント(account)
  2. ユーザー(user)
  3. 組織(organization)

の関係が謎なんだが...

そもそも、

docs.github.com

⇧「アカウント(account)」の種類が3種類あると言っているのだが...

ChatGPTに質問したところ、以下の回答が返ってきた。

■「アカウント(account)」の関係

classDiagram
    class Account {
        - username: string
        - email: string
    }
    class UserAccount {
        - userName: string
        - email: string
        - role: string
    }
    class OrganizationAccount {
        - orgName: string
        - repo: string
    }
    class EnterpriseAccount {
        - enterpriseName: string
        - orgs: list
    }

    Account "1" -- "1" UserAccount: owns
    Account "1" -- "*" OrganizationAccount: owns
    Account "1" -- "*" EnterpriseAccount: owns
    OrganizationAccount "1" -- "*" UserAccount: member of
    EnterpriseAccount "1" -- "*" OrganizationAccount: contains

う~む、ChatGPTの回答の根拠が全く分からん...

結局、『ユーザーまたは組織は、最大 100 個の GitHub Apps を登録できますが、アカウントにインストールできる GitHub Apps の数に制限はありません。』は、どう解釈すれば良いのか...

「GitHub CLI」というものも存在するようなのだけど、

github.com

GitHub CLI

gh is GitHub on the command line. It brings pull requests, issues, and other GitHub concepts to the terminal next to where you are already working with git and your code.

https://github.com/cli/cli

GitHub CLI is supported for users on GitHub.com, GitHub Enterprise Cloud, and GitHub Enterprise Server 2.20+ with support for macOS, Windows, and Linux.

https://github.com/cli/cli

⇧ 今いち「GitHub App」に関する情報も取得できるのかがよく分からない...

ドキュメントを見た感じでは、

cli.github.com

⇧『List repositories owned by a user or organization.』とあるので、「Gitリポジトリ」の一覧は取得できそうではある。

archivedAt,
assignableUsers,
codeOfConduct,
contactLinks,
createdAt,
defaultBranchRef,
deleteBranchOnMerge,
description,
diskUsage,
forkCount,
fundingLinks,
hasDiscussionsEnabled,
hasIssuesEnabled,
hasProjectsEnabled,
hasWikiEnabled,
homepageUrl,
id,
isArchived,
isBlankIssuesEnabled,
isEmpty,
isFork,
isInOrganization,
isMirror,
isPrivate,
isSecurityPolicyEnabled,
isTemplate,
isUserConfigurationRepository,
issueTemplates,
issues,
labels,
languages,
latestRelease,
licenseInfo,
mentionableUsers,
mergeCommitAllowed,
milestones,
mirrorUrl,
name,
nameWithOwner,
openGraphImageUrl,
owner,
parent,
primaryLanguage,
projects,
projectsV2,
pullRequestTemplates,
pullRequests,
pushedAt,
rebaseMergeAllowed,
repositoryTopics,
securityPolicyUrl,
squashMergeAllowed,
sshUrl,
stargazerCount,
templateRepository,
updatedAt,
url,
usesCustomOpenGraphImage,
viewerCanAdminister,
viewerDefaultCommitEmail,
viewerDefaultMergeMethod,
viewerHasStarred,
viewerPermission,
viewerPossibleCommitEmails,
viewerSubscription,
visibility,
watchers    

⇧「GitHub App」で管理されている「Gitリポジトリ」なのかどうかを確認できる情報は取得でき無さそう...

後は、

⇧ 取得できる「Gitリポジトリ」の数の上限が分からない...デフォルトは「30」個らしいが、何故に、許容される最大値の説明が無いのか...

「go」で実装されてるらしいので、全く分からんのだが、

■https://github.com/cli/cli/blob/trunk/pkg/cmd/repo/list/list.go

package list

import (
	"fmt"
	"net/http"
	"strings"
	"time"

	"github.com/MakeNowJust/heredoc"
	"github.com/spf13/cobra"

	"github.com/cli/cli/v2/api"
	fd "github.com/cli/cli/v2/internal/featuredetection"
	"github.com/cli/cli/v2/internal/gh"
	"github.com/cli/cli/v2/internal/tableprinter"
	"github.com/cli/cli/v2/internal/text"
	"github.com/cli/cli/v2/pkg/cmdutil"
	"github.com/cli/cli/v2/pkg/iostreams"
)

type ListOptions struct {
	HttpClient func() (*http.Client, error)
	Config     func() (gh.Config, error)
	IO         *iostreams.IOStreams
	Exporter   cmdutil.Exporter
	Detector   fd.Detector

	Limit int
	Owner string

	Visibility  string
	Fork        bool
	Source      bool
	Language    string
	Topic       []string
	Archived    bool
	NonArchived bool

	Now func() time.Time
}

func NewCmdList(f *cmdutil.Factory, runF func(*ListOptions) error) *cobra.Command {
	opts := ListOptions{
		IO:         f.IOStreams,
		Config:     f.Config,
		HttpClient: f.HttpClient,
		Now:        time.Now,
	}

	var (
		flagPublic  bool
		flagPrivate bool
	)

	cmd := &cobra.Command{
		Use:   "list [<owner>]",
		Args:  cobra.MaximumNArgs(1),
		Short: "List repositories owned by user or organization",
		Long: heredoc.Docf(`
			List repositories owned by a user or organization.

			Note that the list will only include repositories owned by the provided argument,
			and the %[1]s--fork%[1]s or %[1]s--source%[1]s flags will not traverse ownership boundaries. For example,
			when listing the forks in an organization, the output would not include those owned by individual users.
		`, "`"),
		Aliases: []string{"ls"},
		RunE: func(c *cobra.Command, args []string) error {
			if opts.Limit < 1 {
				return cmdutil.FlagErrorf("invalid limit: %v", opts.Limit)
			}

			if err := cmdutil.MutuallyExclusive("specify only one of `--public`, `--private`, or `--visibility`", flagPublic, flagPrivate, opts.Visibility != ""); err != nil {
				return err
			}
			if opts.Source && opts.Fork {
				return cmdutil.FlagErrorf("specify only one of `--source` or `--fork`")
			}
			if opts.Archived && opts.NonArchived {
				return cmdutil.FlagErrorf("specify only one of `--archived` or `--no-archived`")
			}

			if flagPrivate {
				opts.Visibility = "private"
			} else if flagPublic {
				opts.Visibility = "public"
			}

			if len(args) > 0 {
				opts.Owner = args[0]
			}

			if runF != nil {
				return runF(&opts)
			}
			return listRun(&opts)
		},
	}

	cmd.Flags().IntVarP(&opts.Limit, "limit", "L", 30, "Maximum number of repositories to list")
	cmd.Flags().BoolVar(&opts.Source, "source", false, "Show only non-forks")
	cmd.Flags().BoolVar(&opts.Fork, "fork", false, "Show only forks")
	cmd.Flags().StringVarP(&opts.Language, "language", "l", "", "Filter by primary coding language")
	cmd.Flags().StringSliceVarP(&opts.Topic, "topic", "", nil, "Filter by topic")
	cmdutil.StringEnumFlag(cmd, &opts.Visibility, "visibility", "", "", []string{"public", "private", "internal"}, "Filter by repository visibility")
	cmd.Flags().BoolVar(&opts.Archived, "archived", false, "Show only archived repositories")
	cmd.Flags().BoolVar(&opts.NonArchived, "no-archived", false, "Omit archived repositories")
	cmdutil.AddJSONFlags(cmd, &opts.Exporter, api.RepositoryFields)

	cmd.Flags().BoolVar(&flagPrivate, "private", false, "Show only private repositories")
	cmd.Flags().BoolVar(&flagPublic, "public", false, "Show only public repositories")
	_ = cmd.Flags().MarkDeprecated("public", "use `--visibility=public` instead")
	_ = cmd.Flags().MarkDeprecated("private", "use `--visibility=private` instead")

	return cmd
}

var defaultFields = []string{"nameWithOwner", "description", "isPrivate", "isFork", "isArchived", "createdAt", "pushedAt"}

func listRun(opts *ListOptions) error {
	httpClient, err := opts.HttpClient()
	if err != nil {
		return err
	}

	cfg, err := opts.Config()
	if err != nil {
		return err
	}

	host, _ := cfg.Authentication().DefaultHost()

	if opts.Detector == nil {
		cachedClient := api.NewCachedHTTPClient(httpClient, time.Hour*24)
		opts.Detector = fd.NewDetector(cachedClient, host)
	}
	features, err := opts.Detector.RepositoryFeatures()
	if err != nil {
		return err
	}

	fields := defaultFields
	if features.VisibilityField {
		fields = append(defaultFields, "visibility")
	}

	filter := FilterOptions{
		Visibility:  opts.Visibility,
		Fork:        opts.Fork,
		Source:      opts.Source,
		Language:    opts.Language,
		Topic:       opts.Topic,
		Archived:    opts.Archived,
		NonArchived: opts.NonArchived,
		Fields:      fields,
	}
	if opts.Exporter != nil {
		filter.Fields = opts.Exporter.Fields()
	}

	listResult, err := listRepos(httpClient, host, opts.Limit, opts.Owner, filter)
	if err != nil {
		return err
	}

	if opts.Owner != "" && listResult.Owner == "" && !listResult.FromSearch {
		return fmt.Errorf("the owner handle %q was not recognized as either a GitHub user or an organization", opts.Owner)
	}

	if err := opts.IO.StartPager(); err != nil {
		fmt.Fprintf(opts.IO.ErrOut, "error starting pager: %v\n", err)
	}
	defer opts.IO.StopPager()

	if opts.Exporter != nil {
		return opts.Exporter.Write(opts.IO, listResult.Repositories)
	}

	cs := opts.IO.ColorScheme()
	tp := tableprinter.New(opts.IO, tableprinter.WithHeader("NAME", "DESCRIPTION", "INFO", "UPDATED"))

	totalMatchCount := len(listResult.Repositories)
	for _, repo := range listResult.Repositories {
		info := repoInfo(repo)
		infoColor := cs.Gray

		if repo.IsPrivate {
			infoColor = cs.Yellow
		}

		t := repo.PushedAt
		if repo.PushedAt == nil {
			t = &repo.CreatedAt
		}

		tp.AddField(repo.NameWithOwner, tableprinter.WithColor(cs.Bold))
		tp.AddField(text.RemoveExcessiveWhitespace(repo.Description))
		tp.AddField(info, tableprinter.WithColor(infoColor))
		tp.AddTimeField(opts.Now(), *t, cs.Gray)
		tp.EndRow()
	}

	if listResult.FromSearch && opts.Limit > 1000 {
		fmt.Fprintln(opts.IO.ErrOut, "warning: this query uses the Search API which is capped at 1000 results maximum")
	}
	if opts.IO.IsStdoutTTY() {
		hasFilters := filter.Visibility != "" || filter.Fork || filter.Source || filter.Language != "" || len(filter.Topic) > 0
		title := listHeader(listResult.Owner, totalMatchCount, listResult.TotalCount, hasFilters)
		fmt.Fprintf(opts.IO.Out, "\n%s\n\n", title)
	}

	if totalMatchCount > 0 {
		return tp.Render()
	}

	return nil
}

func listHeader(owner string, matchCount, totalMatchCount int, hasFilters bool) string {
	if totalMatchCount == 0 {
		if hasFilters {
			return "No results match your search"
		} else if owner != "" {
			return "There are no repositories in @" + owner
		}
		return "No results"
	}

	var matchStr string
	if hasFilters {
		matchStr = " that match your search"
	}
	return fmt.Sprintf("Showing %d of %d repositories in @%s%s", matchCount, totalMatchCount, owner, matchStr)
}

func repoInfo(r api.Repository) string {
	tags := []string{visibilityLabel(r)}

	if r.IsFork {
		tags = append(tags, "fork")
	}
	if r.IsArchived {
		tags = append(tags, "archived")
	}

	return strings.Join(tags, ", ")
}

func visibilityLabel(repo api.Repository) string {
	if repo.Visibility != "" {
		return strings.ToLower(repo.Visibility)
	} else if repo.IsPrivate {
		return "private"
	}
	return "public"
}    

⇧ 上限は「1000」個になるということなんですかね?

とりあえず、「REST API」については、制約についての仕様が頻繁に変わるのは止めて欲しい気はする...

そして、

のいずれを利用するにしろ、「1000」個以上の「Gitリポジトリ」がある場合に、「pager(ページャ)」のように、何件目から取得のような方法が用意されていないと、「1001」個目以降の「Gitリポジトリ」を取得する術が無いということになってしまうんだが...

想定が分からんのだが、

docs.github.com

⇧ 一応、ドキュメントによると「Gitリポジトリ」の数としては「100,000」個までは想定しているように見受けられるのよね...

何やら、

cli.github.com

⇧「GitHub CLI」の「gh api」のドキュメントには「--paginate」というオプションで全件取得できるとある。

「GitHub」の「REST API」の「エンドポイント」にリクエストしてるらしいのだけど、「REST API」も対応しているんだろうか?

確認したところ、

docs.github.com

docs.github.com

⇧ 対応しているっぽい。

なかなかに分かり辛い...

毎度モヤモヤ感が半端ない…

今回はこのへんで。