gogithub

package module
v0.3.0 Latest Latest
Warning

This package is not in the latest version of its module.

Go to latest
Published: Jan 17, 2026 License: MIT Imports: 5 Imported by: 0

README

GoGitHub

Build Status Lint Status Go Report Card Docs License

gogithub is a high-level Go module for interacting with the GitHub API. It wraps go-github with convenience functions organized by operation type.

Installation

go get github.com/grokify/gogithub

Directory Structure

The package is organized into subdirectories by operation type for scalability:

gogithub/
├── gogithub.go        # Client factory, backward-compatible re-exports
├── auth/              # Authentication utilities
│   └── auth.go        # NewGitHubClient, GetAuthenticatedUser
├── config/            # Configuration utilities
│   └── config.go      # Config struct, FromEnv, GitHub Enterprise support
├── errors/            # Error types and translation
│   └── errors.go      # APIError, Translate, IsNotFound, IsRateLimited
├── pathutil/          # Path validation and normalization
│   └── pathutil.go    # Validate, Normalize, Join, Split
├── search/            # Search API operations
│   ├── search.go      # SearchIssues, SearchIssuesAll
│   ├── query.go       # Query builder, parameter constants
│   └── issues.go      # Issues type, table generation
├── repo/              # Repository operations
│   ├── fork.go        # EnsureFork, GetDefaultBranch
│   ├── branch.go      # CreateBranch, GetBranchSHA, DeleteBranch
│   ├── commit.go      # CreateCommit (Git tree API), ReadLocalFiles
│   ├── list.go        # ListOrgRepos, ListUserRepos, GetRepo
│   └── batch.go       # Batch for atomic multi-file commits
├── pr/                # Pull request operations
│   └── pullrequest.go # CreatePR, GetPR, ListPRs, MergePR, ClosePR
├── release/           # Release operations
│   └── release.go     # ListReleases, GetLatestRelease, ListReleaseAssets
├── cliutil/           # CLI utilities
│   └── status.go      # Git status helpers
└── cmd/               # Example commands
    └── searchuserpr/  # Search user PRs example

Usage

Basic Example
package main

import (
    "context"
    "fmt"

    "github.com/grokify/gogithub/auth"
    "github.com/grokify/gogithub/search"
)

func main() {
    ctx := context.Background()

    // Create authenticated client
    gh := auth.NewGitHubClient(ctx, "your-github-token")

    // Search for open pull requests
    client := search.NewClient(gh)
    issues, err := client.SearchIssuesAll(ctx, search.Query{
        search.ParamUser:  "grokify",
        search.ParamState: search.ParamStateValueOpen,
        search.ParamIs:    search.ParamIsValuePR,
    }, nil)
    if err != nil {
        panic(err)
    }

    fmt.Printf("Found %d open PRs\n", len(issues))
}
Creating a Pull Request
package main

import (
    "context"
    "fmt"

    "github.com/grokify/gogithub/auth"
    "github.com/grokify/gogithub/pr"
    "github.com/grokify/gogithub/repo"
)

func main() {
    ctx := context.Background()
    gh := auth.NewGitHubClient(ctx, "your-github-token")

    // Get branch SHA
    sha, err := repo.GetBranchSHA(ctx, gh, "owner", "repo", "main")
    if err != nil {
        panic(err)
    }

    // Create a new branch
    err = repo.CreateBranch(ctx, gh, "owner", "repo", "feature-branch", sha)
    if err != nil {
        panic(err)
    }

    // Create files and commit
    files := []repo.FileContent{
        {Path: "README.md", Content: []byte("# Hello")},
    }
    _, err = repo.CreateCommit(ctx, gh, "owner", "repo", "feature-branch", "Add README", files)
    if err != nil {
        panic(err)
    }

    // Create pull request
    pullRequest, err := pr.CreatePR(ctx, gh, "upstream-owner", "upstream-repo",
        "fork-owner", "feature-branch", "main", "My PR Title", "PR description")
    if err != nil {
        panic(err)
    }

    fmt.Printf("PR created: %s\n", pullRequest.GetHTMLURL())
}

Adding New Functionality

When adding new GitHub API functionality, follow this structure:

  1. Identify the operation category - Determine which subdirectory the functionality belongs to:

    • auth/ - Authentication, user identity
    • config/ - Configuration, environment variables, GitHub Enterprise
    • errors/ - Error types and translation utilities
    • pathutil/ - Path validation and normalization
    • search/ - Search API (issues, PRs, code, commits, etc.)
    • repo/ - Repository operations (forks, branches, commits, batch operations)
    • pr/ - Pull request operations
    • release/ - Release and asset operations
    • Create new directories for distinct API areas (e.g., issues/, actions/, gists/)
  2. Create focused files - Within each subdirectory, organize by specific functionality:

    • One file per logical grouping (e.g., fork.go, branch.go, commit.go)
    • Keep files focused and cohesive
  3. Use consistent patterns:

    • Functions take context.Context and *github.Client as first parameters
    • Return appropriate error types with context
    • Provide both low-level functions and convenience wrappers
  4. Define custom error types when needed:

    type ForkError struct {
        Owner string
        Repo  string
        Err   error
    }
    
    func (e *ForkError) Error() string {
        return "failed to fork " + e.Owner + "/" + e.Repo + ": " + e.Err.Error()
    }
    
    func (e *ForkError) Unwrap() error {
        return e.Err
    }
    
  5. Add tests in corresponding *_test.go files

Example: Adding Gist Support
gogithub/
└── gist/
    ├── gist.go       # Create, Get, List, Update, Delete
    └── gist_test.go
// gist/gist.go
package gist

import (
    "context"
    "github.com/google/go-github/v81/github"
)

func Create(ctx context.Context, gh *github.Client, description string, public bool, files map[string]string) (*github.Gist, error) {
    // Implementation
}

func Get(ctx context.Context, gh *github.Client, id string) (*github.Gist, error) {
    // Implementation
}

Backward Compatibility

The root gogithub package provides backward-compatible re-exports for existing code:

// Old style (still works)
import "github.com/grokify/gogithub"

c := gogithub.NewClient(httpClient)
issues, _ := c.SearchIssuesAll(ctx, gogithub.Query{...}, nil)

// New style (preferred)
import (
    "github.com/grokify/gogithub/auth"
    "github.com/grokify/gogithub/search"
)

gh := auth.NewGitHubClient(ctx, token)
c := search.NewClient(gh)
issues, _ := c.SearchIssuesAll(ctx, search.Query{...}, nil)

Dependencies

License

MIT License

Documentation

Overview

Package gogithub provides a Go client for the GitHub API.

This package is organized into subpackages by operation type:

  • auth: Authentication utilities
  • search: Search API (issues, PRs, code, etc.)
  • repo: Repository operations (fork, branch, commit)
  • pr: Pull request operations

Example usage:

package main

import (
    "context"
    "fmt"

    "github.com/grokify/gogithub/auth"
    "github.com/grokify/gogithub/search"
)

func main() {
    ctx := context.Background()
    gh := auth.NewGitHubClient(ctx, "your-token")

    client := search.NewClient(gh)
    issues, err := client.SearchIssuesAll(ctx, search.Query{
        search.ParamUser:  "grokify",
        search.ParamState: search.ParamStateValueOpen,
    }, nil)
    if err != nil {
        panic(err)
    }
    fmt.Printf("Found %d issues\n", len(issues))
}

Index

Constants

View Source
const (
	ParamUser            = search.ParamUser
	ParamState           = search.ParamState
	ParamStateValueOpen  = search.ParamStateValueOpen
	ParamIs              = search.ParamIs
	ParamIsValuePR       = search.ParamIsValuePR
	ParamPerPageValueMax = search.ParamPerPageValueMax

	UsernameDependabot = search.UsernameDependabot
	UserIDDependabot   = search.UserIDDependabot

	BaseURLRepoAPI  = search.BaseURLRepoAPI
	BaseURLRepoHTML = search.BaseURLRepoHTML
)

Re-export constants for backward compatibility. Deprecated: Import from subpackages directly.

Variables

This section is empty.

Functions

This section is empty.

Types

type Client

type Client struct {
	*github.Client
	Search *search.Client
}

Client wraps the GitHub client with convenience methods. For new code, prefer using the subpackages directly.

func NewClient

func NewClient(httpClient *http.Client) *Client

NewClient creates a new client from an HTTP client. Deprecated: Use auth.NewGitHubClient and search.NewClient directly.

func NewClientWithToken added in v0.3.0

func NewClientWithToken(ctx context.Context, token string) *Client

NewClientWithToken creates a new client authenticated with a token.

func (*Client) SearchIssues

func (c *Client) SearchIssues(ctx context.Context, qry Query, opts *github.SearchOptions) (*github.IssuesSearchResult, *github.Response, error)

SearchIssues is a wrapper for SearchService.Issues(). Deprecated: Use search.Client.SearchIssues directly.

func (*Client) SearchIssuesAll

func (c *Client) SearchIssuesAll(ctx context.Context, qry Query, opts *github.SearchOptions) (Issues, error)

SearchIssuesAll retrieves all issues matching the query with pagination. Deprecated: Use search.Client.SearchIssuesAll directly.

func (*Client) SearchOpenPullRequests

func (c *Client) SearchOpenPullRequests(ctx context.Context, username string, opts *github.SearchOptions) (*github.IssuesSearchResult, *github.Response, error)

SearchOpenPullRequests searches for open pull requests by username. Deprecated: Use search.Client.SearchOpenPullRequests directly.

type Issue

type Issue = search.Issue

Re-export types for backward compatibility. Deprecated: Import from subpackages directly.

type Issues

type Issues = search.Issues

Re-export types for backward compatibility. Deprecated: Import from subpackages directly.

type Query

type Query = search.Query

Re-export types for backward compatibility. Deprecated: Import from subpackages directly.

Directories

Path Synopsis
Package auth provides GitHub authentication utilities.
Package auth provides GitHub authentication utilities.
cmd/bulk_git_rm command
cmd
searchuserpr command
Package config provides configuration utilities for GitHub API clients.
Package config provides configuration utilities for GitHub API clients.
Package errors provides error types and translation utilities for GitHub API errors.
Package errors provides error types and translation utilities for GitHub API errors.
Package pathutil provides path validation and normalization utilities for GitHub repository paths.
Package pathutil provides path validation and normalization utilities for GitHub repository paths.
Package pr provides GitHub pull request operations.
Package pr provides GitHub pull request operations.
Package release provides GitHub release operations.
Package release provides GitHub release operations.
Package repo provides GitHub repository operations.
Package repo provides GitHub repository operations.
Package search provides GitHub search API functionality.
Package search provides GitHub search API functionality.

Jump to

Keyboard shortcuts

? : This menu
/ : Search site
f or F : Jump to
y or Y : Canonical URL