This is a Go CLI application that synchronizes GitHub organization repositories to local storage. It provides functionality to clone and update multiple repositories from a GitHub organization in parallel, with options for filtering and customization.
Repository: xbglowx/github-org-repos-sync
Language: Go
Primary Framework: Cobra CLI framework
License: Apache License 2.0
- Repository Discovery: Fetches all repositories from a specified GitHub organization using GitHub API
- Parallel Operations: Performs git clone/update operations in parallel for efficiency
- Smart Updates: Switches to default branch, stashes if dirty, fetches and rebases
- Filtering Options: Include/exclude repositories by name patterns
- Archive Handling: Option to skip archived repositories
main.go- Entry point that calls Cobra command executioncmd/root.go- Cobra CLI configuration, flags, and command structurecmd/github-org-sync.go- Core business logic for GitHub API integration and git operations
- CLI Layer: Cobra-based command interface with flags and validation
- Service Layer: GitHub API client integration and repository operations
- Git Operations: Direct git command execution via
os/exec
- Go Version: Use Go 1.23+ features and idioms
- Error Handling: Always handle errors explicitly, no panics in user-facing code
- Context Usage: Use
context.Contextfor API calls and cancelable operations - Concurrency: Use goroutines with semaphores for controlled parallelism
- Resource Management: Proper cleanup with defer statements
- Package Structure: Follow standard Go project layout with
cmd/for applications - Naming: Use descriptive names, follow Go naming conventions (camelCase for private, PascalCase for public)
- Documentation: Use Go doc comments for exported functions and types
- Formatting: Code must pass
go fmtandgolangci-lint
- CLI Framework:
github.com/spf13/cobra- Command line interface - GitHub API:
github.com/google/go-github- GitHub API client - OAuth2:
golang.org/x/oauth2- Authentication for GitHub API
- Linting:
golangci-lint(configured via GitHub Actions) - Testing: Standard Go testing with
go test - Building: Standard Go build with
go build
GITHUB_TOKEN: Personal access token withreposcope for GitHub API access- Token must have access to the target organization's repositories
--destination-path, -d // Destination path for repositories (default: current directory)
--parallelism, -p // Number of parallel git operations (default: 1)
--skip-archived // Skip archived repositories
--exclude-repos // Exclude repositories containing specified string
--include-repos // Include only repositories containing specified string- GitHub token must be present in environment
- Git CLI must be available in PATH
- Cannot use both
--exclude-reposand--include-repossimultaneously
- New Repository: Clone from GitHub to local destination
- Existing Clean Repository: Checkout default branch, fetch, and rebase
- Existing Dirty Repository: Stash changes, then proceed with update
- Empty Repository: Skip update operations
git clone <url> <destination>- Clone new repositoriesgit -C <path> diff-index --quiet --cached HEAD --- Check for staged changesgit -C <path> diff-files --quiet- Check for unstaged changesgit -C <path> stash push- Stash dirty changesgit -C <path> fetch origin- Fetch latest changesgit -C <path> checkout <branch>- Switch to default branchgit -C <path> pull --rebase- Update with rebase
- No unit tests currently exist - This is an area for improvement
- Manual testing: Build and run against real GitHub organizations
- CI/CD: GitHub Actions for build validation and linting
- Add unit tests for core functions in
cmd/github-org-sync.go - Mock GitHub API responses for consistent testing
- Test git operations with temporary repositories
- Integration tests with test GitHub organizations
- Build Validation:
go buildmust succeed - Linting:
golangci-lintchecks for code quality - Code Analysis: CodeQL analysis for security issues
build-test.yaml- Go build and test validationgolangci-lint.yml- Code linting and style checkscodeql-analysis.yml- Security analysiscreate-release.yaml- Automated releases
- Triggered on pull requests and pushes (excluding version tags)
- Uses latest Ubuntu runners
- Go version specified in
go.modfile - All workflows must pass for PR approval
- Environment validation errors are returned early from
checkRequirements() - Git operation errors are logged but don't stop other repositories
- API errors should be handled gracefully with informative messages
- Use
fmt.Printf()for user-facing output - Include repository names in error messages for context
- Distinguish between INFO, ERROR, and success messages
- Example:
fmt.Printf("ERROR: Repo %s failed to clone: %v\n", repo.GetName(), err)
func (gh *GhOrgSync) processRepo(sem chan struct{}, repo *github.Repository) {
defer gh.wg.Done()
sem <- struct{}{}
defer func() { <-sem }()
// Repository processing logic
}cmd := exec.Command("git", "-C", repoPath, "status")
err := cmd.Run()
if err != nil {
// Handle error appropriately
}ctx := context.Background()
repos, _, err := client.Repositories.ListByOrg(ctx, org, &github.RepositoryListByOrgOptions{
ListOptions: github.ListOptions{PerPage: 100},
})- Use GitHub personal access tokens (never hardcode credentials)
- Tokens should have minimal required scopes (
repofor private repos, public access for public) - Validate token presence before making API calls
- All git commands use
-Cflag to specify working directory (safer thancd) - Repository paths are constructed safely using
fmt.Sprintf - No shell injection risks as commands use
exec.Commandwith separate arguments
- Uses
release-pleasefor automated releases - Follows conventional commits for changelog generation
- Version managed in
.release-please-manifest.json - Releases triggered by merging release PRs
- Semantic versioning (SemVer)
- Current version: 0.0.8 (as of latest release)
- Breaking changes increment minor version (pre-1.0)
- Environment Setup: Ensure Go 1.23+, git, and GitHub token configured
- Code Quality: Run
go fmt,golangci-lint, andgo buildbefore committing - Testing: Manual testing with real or test GitHub organizations
- Documentation: Update README.md for user-facing changes
- Follow conventional commits format
- Examples:
feat: add new filtering option,fix: handle empty repositories - Use imperative mood in commit messages
# Setup
export GITHUB_TOKEN=<your-token>
go mod download
# Build
go build .
# Run
./github-org-repos-sync <org-name>
# Test with options
./github-org-repos-sync --parallelism 3 --skip-archived <org-name>- Check GitHub token permissions if API calls fail
- Verify git is in PATH if git commands fail
- Use
--parallelism 1for easier debugging of git operations - Check repository permissions if clone/fetch operations fail
- Increase
--parallelismfor faster operation (default: 1, recommended: 3-5) - GitHub API has rate limits (5000 requests/hour for authenticated users)
- Large organizations may require pagination handling
- Testing: Add comprehensive unit and integration tests
- Logging: Implement structured logging with levels
- Configuration: Support for config files beyond CLI flags
- Git Integration: Use git libraries instead of shelling out to git commands
- Progress: Add progress bars for long-running operations
- Dry Run: Add option to preview what would be done without executing
- Consider separating GitHub API logic into separate package
- Abstract git operations behind an interface for testing
- Add configuration validation beyond environment checks
- Consider using channels for better error aggregation across goroutines
- Primary Maintainer: Based on repository ownership (xbglowx)
- Issue Tracking: GitHub Issues on the repository
- CI Status: Check GitHub Actions for build and lint status
- Dependencies: Renovate.json configured for automated dependency updates