Skip to content

scottluskcis/octokit-harness

Repository files navigation

Octokit Harness

A flexible wrapper for working with GitHub API using Octokit, providing resilient API interactions with built-in retry mechanisms, authentication handling, and logging.

Installation

This package is hosted on GitHub Packages. To install it, you'll need to:

  1. Create a GitHub Personal Access Token (PAT) with the read:packages scope
  2. Configure npm to use GitHub Packages for @scottluskcis packages

Create an .npmrc file in your project with:

@scottluskcis:registry=https://npm.pkg.github.com/ //npm.pkg.github.com/:_authToken=${GITHUB_TOKEN} 

Then install the package:

# Export your GitHub token as an environment variableexport GITHUB_TOKEN=your_github_personal_access_token # Install the package npm install @scottluskcis/octokit-harness

Alternatively, you can pass the token directly during installation:

npm install @scottluskcis/octokit-harness --registry=https://npm.pkg.github.com/ --auth-token=your_github_personal_access_token

Features

  • GitHub App and PAT authentication - Supports both GitHub App installation tokens and Personal Access Tokens
  • Automatic retry with exponential backoff - Built-in resilience for API operations
  • Configurable logging - Detailed logging system based on Winston
  • Rate limit handling - Intelligent throttling and rate limit management
  • Environment-based configuration - Easy setup via environment variables or direct options
  • CLI command builder - Utilities for building consistent CLI applications

Usage

Basic Example

import{executeWithOctokit,getOptsFromEnv,}from'@scottluskcis/octokit-harness';// Load config from environment variables (.env file)constconfig=getOptsFromEnv();// Execute operations with automatic retry handlingawaitexecuteWithOctokit(config,async({ octokit, logger })=>{logger.info('Fetching repository data...');const{data: repo}=awaitoctokit.rest.repos.get({owner: config.orgName,repo: 'my-repository',});logger.info(`Retrieved repository: ${repo.name}`);returnrepo;});

CLI Command Building

The package provides utilities to create consistent CLI commands with standardized options:

import{createBaseCommand,createProgram,executeWithOctokit,}from'@scottluskcis/octokit-harness';// Create a command for a specific operationconstrepoStatsCommand=createBaseCommand('repo-stats','Gathers statistics for all repositories in an organization',);// Define the command's actionrepoStatsCommand.action(async(options)=>{console.log('Starting repo stats collection...');awaitexecuteWithOctokit(options,async({ octokit, logger })=>{logger.info(`Processing repositories for ${options.orgName}`);// Your implementation here});console.log('Repo stats completed');});// Create another command with specific option requirementsconstmissingReposCommand=createBaseCommand('missing-repos','Identify repositories missing from a previous scan',{// Make this option mandatoryoutputFileName: {mandatory: true},// Include other options with default settingsorgName: true,accessToken: true,// Don't include options we don't needextraPageSize: false,},);missingReposCommand.action(async(options)=>{console.log(`Checking for missing repos using ${options.outputFileName}`);// Command implementation});// Create a program with multiple commandsconstprogram=createProgram('github-tools','GitHub repository management tools',[repoStatsCommand,missingReposCommand],);// Parse command line argumentsprogram.parse(process.argv);

This example creates a CLI application with two commands:

  1. github-tools repo-stats - For gathering repository statistics
  2. github-tools missing-repos - For identifying missing repositories

Each command automatically includes the appropriate set of options with standardized names, environment variable support, and help documentation.

Authentication Configuration

The package supports both GitHub App authentication and Personal Access Tokens:

// Using GitHub App authentication (via environment variables)// Set in .env file:// APP_ID=123456// PRIVATE_KEY_FILE=keys/private-key.pem// APP_INSTALLATION_ID=987654// Using Personal Access Token (via environment variables)// Set in .env file:// ACCESS_TOKEN=ghp_xxxxxxxxxxxx

Custom Initialization

If you need more control over initialization:

import{init_logger,init_octokit,withRetry,}from'@scottluskcis/octokit-harness';// Initialize just the loggerconstlogger=awaitinit_logger(true,'custom-prefix');// Initialize just the Octokit clientconst{ octokit }=awaitinit_octokit({orgName: 'my-organization',baseUrl: 'https://api.github.com',verbose: true,appId: '123456',privateKeyFile: 'path/to/key.pem',appInstallationId: '987654',});// Use retry mechanism directlyconstresult=awaitwithRetry(async()=>{// API operation that might failreturnawaitoctokit.rest.repos.listForOrg({org: 'my-organization'});},{maxAttempts: 5,initialDelayMs: 1000,maxDelayMs: 30000,backoffFactor: 2,},(state)=>{logger.warn(`Retrying operation, attempt ${state.attempt}`,{error: state.error?.message,});},);

Configuration Options

OptionEnvironment VariableDescription
orgNameORG_NAMEGitHub organization name
baseUrlBASE_URLGitHub API URL (defaults to https://api.github.com)
proxyUrlPROXY_URLOptional proxy URL for API requests
verboseVERBOSEEnable verbose logging (true/false)
accessTokenACCESS_TOKENGitHub personal access token
appIdAPP_IDGitHub App ID
privateKeyPRIVATE_KEYGitHub App private key contents
privateKeyFilePRIVATE_KEY_FILEPath to GitHub App private key file
appInstallationIdAPP_INSTALLATION_IDGitHub App installation ID
retryMaxAttemptsRETRY_MAX_ATTEMPTSMaximum retry attempts (default: 3)
retryInitialDelayRETRY_INITIAL_DELAYInitial retry delay in ms (default: 1000)
retryMaxDelayRETRY_MAX_DELAYMaximum retry delay in ms (default: 30000)
retryBackoffFactorRETRY_BACKOFF_FACTORExponential backoff factor (default: 2)
retrySuccessThresholdRETRY_SUCCESS_THRESHOLDSuccessful operations needed to reset retry count (default: 5)
retryDisabledRETRY_DISABLEDDisable retry mechanism completely (true/false)
outputFileOUTPUT_FILEPath to output file
outputFileNameOUTPUT_FILE_NAMEName of the output file
repoListREPO_LISTPath to repository list file
autoProcessMissingAUTO_PROCESS_MISSINGAutomatically process missing repositories

API Reference

Main Functions

  • executeWithOctokit(options, callback): Executes operations with initialized Octokit client and automatic retry
  • getOptsFromEnv(): Loads configuration options from environment variables
  • init_client(options): Initializes both logger and Octokit client
  • init_logger(verbose, logFilePrefix?): Initializes just the logger
  • init_octokit(options): Initializes just the Octokit client
  • withRetry(operation, config, onRetry?): Implements retry mechanism with exponential backoff
  • createBaseCommand(name, description, optionsConfig?): Creates a CLI command with standard GitHub options
  • createProgram(programName, description, commands): Creates a CLI program with multiple commands

Types

  • Arguments: Configuration options for the package
  • Logger: Winston-based logger interface
  • RetryConfig: Configuration for retry mechanism
  • RetryState: Current state of retry operation
  • CommandOptionConfig: Configuration for command options
  • CommonOptionsConfig: Configuration map for command options

License

MIT

About

No description, website, or topics provided.

Resources

Stars

Watchers

Forks

Packages

 
 
 

Contributors 2

  •  
  •