Skip to content

Instantly share code, notes, and snippets.

@suhlig
Created July 24, 2024 21:35
Show Gist options
  • Save suhlig/52d8c31c3d3f99d58a5b625ee787bd15 to your computer and use it in GitHub Desktop.
Save suhlig/52d8c31c3d3f99d58a5b625ee787bd15 to your computer and use it in GitHub Desktop.
Fetch content of a file from GitHub at a given committish
package main
import (
"context"
"encoding/base64"
"fmt"
"log"
"os"
"github.com/google/go-github/v63/github"
)
func fileContentAt(ctx context.Context, owner, repo, filePath, committish string) ([]byte, error) {
client := github.NewClient(nil).WithAuthToken(os.Getenv("GITHUB_ACCESS_TOKEN"))
fileContent, _, _, err := client.Repositories.GetContents(ctx, owner, repo, filePath, &github.RepositoryContentGetOptions{Ref: committish})
if err != nil {
return nil, err
}
return base64.StdEncoding.DecodeString(*fileContent.Content)
}
func main() {
ctx := context.Background()
// any of these: https://github.com/google/go-github/commits/v63.0.0/example/commitpr/main.go
content, err := fileContentAt(ctx, "google", "go-github", "example/commitpr/main.go", "aa3fcbe7aabce60227eb210c0c81a8722770590d")
if err != nil {
log.Fatalf("Error fetching file content: %v", err)
}
fmt.Printf("%s", content)
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment