Skip to content

Commit

Permalink
github-bot sdk: add search content of filename in repository (#681)
Browse files Browse the repository at this point in the history
I want to search for the content in proposed filenames in a repository.

Signed-off-by: hectorj2f <[email protected]>
  • Loading branch information
hectorj2f authored Jan 6, 2025
1 parent 1655bad commit fc44575
Show file tree
Hide file tree
Showing 2 changed files with 45 additions and 0 deletions.
21 changes: 21 additions & 0 deletions modules/github-bots/sdk/github.go
Original file line number Diff line number Diff line change
Expand Up @@ -586,6 +586,27 @@ func (c GitHubClient) GetFileContent(ctx context.Context, owner, repo, path, ref
return content, nil
}

// SearchContentInFilename searches for a text in a filename in a specific repository
func (c GitHubClient) SearchContentInFilename(ctx context.Context, owner, repo, path, content string, opt *github.ListOptions) (*github.CodeSearchResult, error) {
if opt == nil {
opt = &github.ListOptions{}
}
query := fmt.Sprintf("%s in:file filename:%s repo:%s/%s", content, path, owner, repo)
result, resp, err := c.inner.Search.Code(
ctx,
query,
&github.SearchOptions{
ListOptions: *opt,
},
)

if err := validateResponse(ctx, err, resp, fmt.Sprintf("search content %s in repository", content)); err != nil {
return &github.CodeSearchResult{}, err
}

return result, nil
}

// SearchFilenameInRepository searches for a filename in a specific repository
func (c GitHubClient) SearchFilenameInRepository(ctx context.Context, owner, repo, path string, opt *github.ListOptions) (*github.CodeSearchResult, error) {
if opt == nil {
Expand Down
24 changes: 24 additions & 0 deletions modules/github-bots/sdk/github_integration_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -34,3 +34,27 @@ func Test_SearchFilenameInRepository(t *testing.T) {
t.Fatalf("SearchFilenameInRepository result is zero\n")
}
}

// NOTE: This is an integration test that requires 'GITHUB_TOKEN' env variable to be set!
// It is recommended to run this test in a local environment.
func Test_SearchContentInFilename(t *testing.T) {
ctx := context.Background()

if os.Getenv("GITHUB_TOKEN") == "" {
t.Fatalf("GITHUB_TOKEN env var not set\n")
}

// create a GitHub client
repoOrg := "kserve"
repoName := "kserve"
// sdk allows an override of GIT_TOKEN env var so we can test from a local environment
cli := NewGitHubClient(ctx, repoOrg, repoName, "test")
result, err := cli.SearchContentInFilename(ctx, repoOrg, repoName, "pyproject.toml", "py37", &github.ListOptions{})
if err != nil {
t.Fatalf("SearchContentInFilename err: %v\n", err)
}

if *result.Total == 0 {
t.Fatalf("SearchContentInFilename result is zero\n")
}
}

0 comments on commit fc44575

Please sign in to comment.