Skip to content

feat!: refactor client constructor to use options pattern#23

Open
alexandear wants to merge 2 commits into
masterfrom
client-options-pattern
Open

feat!: refactor client constructor to use options pattern#23
alexandear wants to merge 2 commits into
masterfrom
client-options-pattern

Conversation

@alexandear
Copy link
Copy Markdown
Member

@alexandear alexandear commented May 11, 2026

Signed-off-by: Steve Hipwell steve.hipwell@gmail.com

Summary by CodeRabbit

  • Breaking Changes
    • Updated GitHub API client initialization: NewClient() now returns (client, error) and requires explicit error handling
    • Client configuration now uses functional options (e.g., WithAuthToken(), WithEnterpriseURLs()) instead of method chaining
    • Examples and documentation updated to reflect new client initialization patterns

Review Change Stack

@codecov-commenter
Copy link
Copy Markdown

⚠️ Please install the 'codecov app svg image' to ensure uploads and comments are reliably processed by Codecov.

Codecov Report

❌ Patch coverage is 64.05694% with 101 lines in your changes missing coverage. Please review.

Files with missing lines Patch % Lines
github/github.go 93.04% 8 Missing and 5 partials ⚠️
example/newfilewithappauth/main.go 0.00% 11 Missing ⚠️
test/fields/fields.go 0.00% 8 Missing ⚠️
example/commitpr/main.go 0.00% 7 Missing ⚠️
example/otel/main.go 0.00% 7 Missing ⚠️
example/contents/main.go 0.00% 6 Missing ⚠️
example/basicauth/main.go 0.00% 4 Missing ⚠️
example/migrations/main.go 0.00% 4 Missing ⚠️
example/ratelimit/main.go 0.00% 4 Missing ⚠️
example/simple/main.go 0.00% 4 Missing ⚠️
... and 11 more

📢 Thoughts on this report? Let us know!

@coderabbitai
Copy link
Copy Markdown

coderabbitai Bot commented May 11, 2026

📝 Walkthrough

Walkthrough

This pull request refactors the go-github client construction API from a chainable builder pattern to a functional options pattern. NewClient signature changes to accept option functions and return an error; client configuration fields are unexported; and all code that reads or sets these fields is updated to use the new internal names and getter methods.

Changes

Client API Core Refactor

Layer / File(s) Summary
Client Options Types
github/github.go
Introduces ClientOptionsFunc type and nine exported option constructors: WithHTTPClient, WithTransport, WithUserAgent, WithEnvProxy, WithAuthToken, WithEnterpriseURLs, WithDisableRateLimitCheck, WithRateLimitRedirectionalEndpoints, WithSecondaryRateLimitOptions. Each option includes validation and applies configuration to an internal clientOptions struct.
Client Struct Unexport
github/github.go
Unexports six configuration fields (BaseURL, UploadURL, UserAgent, DisableRateLimitCheck, RateLimitRedirectionalEndpoints, MaxSecondaryRateLimitRetryAfterDuration) and replaces them with lowercase equivalents. Adds internal fields for HTTP client, redirect-ignore client, and rate-limit cache.
Internal Client Initialization
github/github.go
Implements newClient(opts clientOptions) (*Client, error) which constructs and configures the HTTP client, applies optional custom transport and environment proxy, wraps auth token via a custom RoundTripper, initializes user-agent/base/upload URLs with validation, and sets rate-limit configuration. Updates NewClient public signature to accept options and return error.
Client Getters & Clone
github/github.go
Adds public getter methods UserAgent() string, BaseURL() string, UploadURL() string to access unexported fields. Updates Clone to accept ClientOptionsFunc options, error if client is uninitialized, preserve configuration/rate-limit state, and apply new options.
Request Building
github/github.go
NewRequest, NewFormRequest, NewUploadRequest updated to use internal baseURL/uploadURL/userAgent fields; enforce trailing-slash requirements; perform URL path traversal checks; set User-Agent only when non-empty.
Rate Limit & Redirect
github/github.go
bareDo and bareDoUntilFound use internal disableRateLimitCheck, maxSecondaryRateLimitRetryAfterDuration, and baseURL fields. Cross-host redirect validation and secondary rate-limit capping logic preserved.

Test Suite

Layer / File(s) Summary
Test Helpers
github/github_test.go
Introduces mustNewClient(t, opts...) and mustParseURL(...) helpers for consistent client construction and immediate test failure on errors.
Test Setup Helper
github/github_test.go
Refactors setup helper to use mustNewClient(t, WithHTTPClient(...)) and directly set internal baseURL/uploadURL fields for test server wiring.
Option Function Tests
github/github_test.go
Individual test functions for each option: TestWithHTTPClient, TestWithTransport, TestWithUserAgent, TestWithEnvProxy, TestWithAuthToken, TestWithEnterpriseURLs, TestWithDisableRateLimitCheck, TestWithRateLimitRedirectionalEndpoints, TestWithSecondaryRateLimitOptions. Each validates error cases and configuration propagation.
NewClient Tests
github/github_test.go
TestNewClient and Test_newClient table-driven tests validate error handling, option combinations, HTTP client/transport propagation, URL initialization, and service wiring.
Clone Tests
github/github_test.go
Tests for Client.Clone with option overrides, rate-limit preservation, transport/HTTP client combinations, and configuration state mirroring.
Request Tests
github/github_test.go
Refactors existing request-construction tests to use mustNewClient, verify internal field access, validate user-agent behavior, and test path traversal checks.

Service-Level Updates

Layer / File(s) Summary
Actions Services
github/actions_artifacts.go, github/actions_workflow_jobs.go, github/actions_workflow_runs.go
DownloadArtifact, GetWorkflowJobLogs, GetWorkflowRunAttemptLogs, GetWorkflowRunLogs updated to check s.client.rateLimitRedirectionalEndpoints instead of exported field name.
Rate Limit Service
github/rate_limit.go
RateLimitService.Get updated to use s.client.disableRateLimitCheck instead of exported field.
Repositories Service
github/repos_contents.go
GetArchiveLink updated to use s.client.rateLimitRedirectionalEndpoints for conditional routing.
Actions Tests
github/actions_artifacts_test.go, github/actions_workflow_jobs_test.go, github/actions_workflow_runs_test.go
Tests updated to set internal client.rateLimitRedirectionalEndpoints field and use Clone(WithTransport(...)) for bad-client testing instead of mutating existing transport.
Workflow Tests
github/actions_workflows_test.go
Tests updated to use internal client.baseURL.Path instead of exported client.BaseURL.Path for NewRequest failure scenarios.
Copilot Tests
github/copilot_test.go
Tests updated to construct URLs using client.baseURL.String() instead of exported client.BaseURL.String().
Repository Tests
github/repos_contents_test.go, github/repos_releases_test.go
Tests updated to use client.rateLimitRedirectionalEndpoints and client.baseURL.String() for URL construction.
Rate Limit Tests
github/rate_limit_test.go
Tests updated to set internal client.disableRateLimitCheck field.

Documentation & Examples

Layer / File(s) Summary
README Usage Examples
README.md
Usage examples updated to show NewClient() with error handling and options-based configuration (WithAuthToken, WithTransport, WithHTTPClient).
README Formatting
README.md
Versioning policy section reflowed for consistency without changing policy content.
Package Documentation
github/doc.go
GoDoc examples and guidance updated to demonstrate new client initialization patterns with explicit error handling.
Example Programs
example/*/main.go
All 16 example programs updated to construct clients using functional options and error handling via log.Fatal(...).
Example Tests
github/example_iterators_test.go, github/examples_test.go
Example test functions refactored to use new client initialization and log.Fatalf error handling.
Integration Tests & Tools
test/fields/fields.go, test/integration/*.go, tools/metadata/main.go
Integration and tool files updated to use new client construction patterns with error handling.

Estimated code review effort

🎯 4 (Complex) | ⏱️ ~60 minutes

Poem

A rabbit hops through fields of code so bright,
Where options dance where chains once held their might,
From WithAuthToken flows a cleaner way,
NewClient now returns what errors say—
Unexported fields guard secrets close,
Getters reveal what once was verbose! 🐰✨

🚥 Pre-merge checks | ✅ 4 | ❌ 1

❌ Failed checks (1 warning)

Check name Status Explanation Resolution
Docstring Coverage ⚠️ Warning Docstring coverage is 19.53% which is insufficient. The required threshold is 80.00%. Write docstrings for the functions missing them to satisfy the coverage threshold.
✅ Passed checks (4 passed)
Check name Status Explanation
Description Check ✅ Passed Check skipped - CodeRabbit’s high-level summary is enabled.
Title check ✅ Passed The title 'feat!: refactor client constructor to use options pattern' directly and clearly describes the main change—replacing the client constructor with a functional options pattern.
Linked Issues check ✅ Passed Check skipped because no linked issues were found for this pull request.
Out of Scope Changes check ✅ Passed Check skipped because no linked issues were found for this pull request.

✏️ Tip: You can configure your own custom pre-merge checks in the settings.

✨ Finishing Touches
📝 Generate docstrings
  • Create stacked PR
  • Commit on current branch
🧪 Generate unit tests (beta)
  • Create PR with unit tests
  • Commit unit tests in branch client-options-pattern

Warning

Review ran into problems

🔥 Problems

Git: Failed to clone repository. Please run the @coderabbitai full review command to re-trigger a full review. If the issue persists, set path_filters to include or exclude specific files.

Tip

💬 Introducing Slack Agent: The best way for teams to turn conversations into code.

Slack Agent is built on CodeRabbit's deep understanding of your code, so your team can collaborate across the entire SDLC without losing context.

  • Generate code and open pull requests
  • Plan features and break down work
  • Investigate incidents and troubleshoot customer tickets together
  • Automate recurring tasks and respond to alerts with triggers
  • Summarize progress and report instantly

Built for teams:

  • Shared memory across your entire org—no repeating context
  • Per-thread sandboxes to safely plan and execute work
  • Governance built-in—scoped access, auditability, and budget controls

One agent for your entire SDLC. Right inside Slack.

👉 Get started


Thanks for using CodeRabbit! It's free for OSS, and your support helps us grow. If you like it, consider giving us a shout-out.

❤️ Share

Comment @coderabbitai help to get the list of available commands and usage tips.

Copy link
Copy Markdown

Copilot AI left a comment

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Pull request overview

This PR refactors the github.Client constructor to a functional options pattern (github.NewClient(opts ...ClientOptionsFunc) (*Client, error)), updates internal configuration fields, and propagates the new API through tests, tooling, docs, and examples across the repository.

Changes:

  • Replaced the old NewClient(httpClient *http.Client) *Client + chaining methods (e.g., .WithAuthToken) with NewClient(...options) and option helpers like WithAuthToken, WithHTTPClient, WithTransport, WithEnterpriseURLs.
  • Made several Client configuration fields unexported (e.g., base/upload URL, user agent, rate-limit toggles) and adjusted package code/tests accordingly.
  • Updated README, package docs, integration tests, and many examples to use the new constructor and handle errors.

Reviewed changes

Copilot reviewed 42 out of 42 changed files in this pull request and generated 5 comments.

Show a summary per file
File Description
tools/metadata/main.go Updates internal tooling to create a client via the new options-based constructor (including enterprise base + upload URL).
test/integration/github_test.go Migrates integration client initialization to new constructor and token option.
test/integration/authorizations_test.go Updates OAuth app client creation to use WithHTTPClient and handle constructor errors.
test/fields/fields.go Updates the standalone fields test harness to use the new constructor and token option.
README.md Updates documentation snippets to the new NewClient() API and options usage.
github/repos_releases_test.go Adjusts tests to use the updated base URL field access.
github/repos_contents.go Switches to the new internal redirection/rate-limit configuration field.
github/repos_contents_test.go Updates tests to set the new internal redirection/rate-limit configuration field.
github/rate_limit.go Switches to the new internal disable-rate-limit-check field.
github/rate_limit_test.go Updates tests to set the new internal disable-rate-limit-check field.
github/github.go Core refactor: introduces options types, new constructor, new clone path, internalizes configuration fields, and adds accessors.
github/github_test.go Reworks/expands tests to validate option functions, new constructor behavior, and cloning behavior.
github/examples_test.go Updates godoc examples to use the error-returning constructor.
github/example_iterators_test.go Updates iterator example to use the error-returning constructor.
github/doc.go Updates package-level docs to describe and demonstrate the new options-based constructor/auth.
github/copilot_test.go Adjusts tests that build absolute URLs to use the updated base URL access.
github/actions_workflows_test.go Updates tests that intentionally break BaseURL to use the updated internal base URL field.
github/actions_workflow_runs.go Switches to the new internal redirection/rate-limit configuration field.
github/actions_workflow_runs_test.go Updates tests to set the new internal redirection/rate-limit configuration field.
github/actions_workflow_jobs.go Switches to the new internal redirection/rate-limit configuration field.
github/actions_workflow_jobs_test.go Updates tests for new constructor behavior and uses Clone+WithTransport for “bad transport” cases.
github/actions_artifacts.go Switches to the new internal redirection/rate-limit configuration field.
github/actions_artifacts_test.go Updates tests for new constructor behavior and uses Clone+WithTransport for “bad transport” cases.
example/verifyartifact/main.go Updates example to use NewClient(WithAuthToken(...)) and handle errors.
example/uploadreleaseassetfromrelease/main.go Updates example to use NewClient(WithAuthToken(...)) and handle errors.
example/topics/main.go Updates example to use NewClient() and switches error handling to fatal logging.
example/tokenauth/main.go Updates example to use NewClient(WithAuthToken(...)) and handle errors.
example/simple/main.go Updates example to use NewClient() and switches error handling to fatal logging.
example/ratelimit/main.go Updates example to use WithHTTPClient option for the paginator client.
example/otel/main.go Updates example to use WithTransport option for OTel transport.
example/newreposecretwithxcrypto/main.go Updates example to use NewClient(WithAuthToken(...)) and handle errors.
example/newrepo/main.go Updates example to use NewClient(WithAuthToken(...)) and handle errors.
example/newfilewithappauth/main.go Updates example to compose options (WithHTTPClient, WithEnterpriseURLs, WithAuthToken).
example/migrations/main.go Updates example to use NewClient(WithAuthToken(...)) and switches error handling to fatal logging.
example/listenvironments/main.go Updates example to use NewClient(WithAuthToken(...)) and handle errors.
example/contents/main.go Updates example to use NewClient() and switches error handling to fatal logging.
example/commitpr/main.go Updates example to use NewClient(WithAuthToken(...)) and handle errors.
example/codespaces/newusersecretwithxcrypto/main.go Updates example to use NewClient(WithAuthToken(...)) and handle errors.
example/codespaces/newreposecretwithxcrypto/main.go Updates example to use NewClient(WithAuthToken(...)) and handle errors.
example/basicauth/main.go Updates example to use WithHTTPClient option and switches error handling to fatal logging.
example/auditlogstream/main.go Updates example to construct client via options (WithAuthToken, WithEnterpriseURLs).
example/actionpermissions/main.go Updates example to use NewClient(WithAuthToken(...)) and handle errors.

💡 Add Copilot custom instructions for smarter, more guided reviews. Learn how to get started.

Comment thread github/github.go
Comment thread github/github.go
Comment thread github/github.go
Comment thread test/integration/github_test.go
Comment thread README.md
Copy link
Copy Markdown

@coderabbitai coderabbitai Bot left a comment

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Actionable comments posted: 5

Caution

Some comments are outside the diff and can’t be posted inline due to platform limitations.

⚠️ Outside diff range comments (2)
github/actions_workflows_test.go (1)

266-270: ⚠️ Potential issue | 🟡 Minor | ⚡ Quick win

Update stale assertion text to match the new internal field name.

After switching to client.baseURL.Path (Line 266, Line 321, Line 414, Line 449, Line 484, Line 519), the failure messages still reference client.BaseURL.Path. Please update those strings to keep test failures accurate and less confusing.

Suggested patch
- t.Error("client.BaseURL.Path='' CreateWorkflowDispatchEventByID err = nil, want error")
+ t.Error("client.baseURL.Path='' CreateWorkflowDispatchEventByID err = nil, want error")

- t.Error("client.BaseURL.Path='' CreateWorkflowDispatchEventByFileName err = nil, want error")
+ t.Error("client.baseURL.Path='' CreateWorkflowDispatchEventByFileName err = nil, want error")

- t.Error("client.BaseURL.Path='' EnableWorkflowByID err = nil, want error")
+ t.Error("client.baseURL.Path='' EnableWorkflowByID err = nil, want error")

- t.Error("client.BaseURL.Path='' EnableWorkflowByFilename err = nil, want error")
+ t.Error("client.baseURL.Path='' EnableWorkflowByFilename err = nil, want error")

- t.Error("client.BaseURL.Path='' DisableWorkflowByID err = nil, want error")
+ t.Error("client.baseURL.Path='' DisableWorkflowByID err = nil, want error")

- t.Error("client.BaseURL.Path='' DisableWorkflowByFileName err = nil, want error")
+ t.Error("client.baseURL.Path='' DisableWorkflowByFileName err = nil, want error")

Also applies to: 321-325, 414-418, 449-453, 484-488, 519-523

🤖 Prompt for AI Agents
Verify each finding against current code. Fix only still-valid issues, skip the
rest with a brief reason, keep changes minimal, and validate.

In `@github/actions_workflows_test.go` around lines 266 - 270, Update the stale
assertion messages in the tests that still reference client.BaseURL.Path to use
the new internal field name client.baseURL.Path; locate the failing
t.Error/t.Fatalf messages (e.g., the assertion after calling
client.Actions.CreateWorkflowDispatchEventByID and the other similar assertions
in the same test file) and change the string "client.BaseURL.Path=''" (and any
other occurrences of "client.BaseURL.Path") to "client.baseURL.Path=''" so
failure output matches the actual field name used in the code.
github/examples_test.go (1)

78-82: ⚠️ Potential issue | 🟡 Minor | ⚡ Quick win

Update stale auth guidance comments to the new constructor style.

On Lines 80, 130, and 160, comments still describe providing an OAuth client “instead of nil,” which no longer matches the NewClient(opts...) API and can mislead readers.

✏️ Suggested comment update
- // github.NewClient() instead of nil. See the following documentation for more
+ // github.NewClient(github.WithAuthToken("<token>")) (or another auth option).
+ // See the following documentation for more

Apply the same wording update in the three affected comment blocks.

Also applies to: 128-132, 158-163

🤖 Prompt for AI Agents
Verify each finding against current code. Fix only still-valid issues, skip the
rest with a brief reason, keep changes minimal, and validate.

In `@github/examples_test.go` around lines 78 - 82, Update the outdated comment
wording that tells readers to pass an OAuth client "instead of nil" to
github.NewClient(); change all three comment blocks in examples_test.go so they
reference the current constructor style github.NewClient(opts...) and instruct
the reader to supply an authenticated option (e.g., an oauth2 authenticated
http.Client wrapped as an option) rather than passing nil; apply the same
replacement to each occurrence that currently mentions "instead of nil" so the
guidance matches the NewClient(opts...) API.
🧹 Nitpick comments (3)
github/github.go (1)

886-886: ⚡ Quick win

Inconsistent User-Agent handling vs. NewRequest/NewFormRequest.

NewRequest (line 776) and NewFormRequest (line 813) guard with if c.userAgent != "" before setting the header, which means a deliberately empty WithUserAgent("") results in no User-Agent header. NewUploadRequest unconditionally calls req.Header.Set("User-Agent", c.userAgent), so the same configuration yields a header with an empty value here. Either suppress in all three, or set in all three — current state is inconsistent.

♻️ Suggested fix
 	req.Header.Set("Content-Type", mediaType)
 	req.Header.Set("Accept", mediaTypeV3)
-	req.Header.Set("User-Agent", c.userAgent)
+	if c.userAgent != "" {
+		req.Header.Set("User-Agent", c.userAgent)
+	}
 	req.Header.Set(headerAPIVersion, defaultAPIVersion)
🤖 Prompt for AI Agents
Verify each finding against current code. Fix only still-valid issues, skip the
rest with a brief reason, keep changes minimal, and validate.

In `@github/github.go` at line 886, NewUploadRequest currently unconditionally
sets req.Header.Set("User-Agent", c.userAgent) which is inconsistent with
NewRequest and NewFormRequest (they only set the header when c.userAgent != ""),
so update NewUploadRequest to match by only setting the "User-Agent" header when
c.userAgent != "" (i.e., add the same guard used in NewRequest/NewFormRequest)
so a deliberate WithUserAgent("") results in no header across all request
constructors.
github/actions_artifacts_test.go (1)

294-294: Direct internal field access in tests is acceptable but couples to implementation.

Setting client.rateLimitRedirectionalEndpoints directly works for same-package tests, but if this field is frequently needed in tests, consider adding a WithRateLimitRedirectionalEndpoints option for better encapsulation and forward compatibility.

🤖 Prompt for AI Agents
Verify each finding against current code. Fix only still-valid issues, skip the
rest with a brief reason, keep changes minimal, and validate.

In `@github/actions_artifacts_test.go` at line 294, Tests are directly mutating
the internal field rateLimitRedirectionalEndpoints on the client, which couples
tests to implementation; add a constructor option like
WithRateLimitRedirectionalEndpoints(bool) and accept it in the NewClient or
client creation flow so tests can set this behavior via the public API instead
of assigning client.rateLimitRedirectionalEndpoints directly; update tests to
use WithRateLimitRedirectionalEndpoints(tc.respectRateLimits) and adjust the
client/options handling code to apply that option during initialization.
github/github_test.go (1)

1199-1213: ⚡ Quick win

Clarify misleading "as original" error messages in Clone subtests.

In initialized_client_with_transport (Line 1202–1203) and initialized_client_with_http_client_and_transport (Line 1276–1277), the assertion compares cloned.client.Transport != tr, but the error message says "is not the same instance as original". The check is actually validating that the cloned client uses the transport supplied via WithTransport(tr), not the original transport on c. Same pattern appears at Line 1238–1239 (!= h.Transport). Aligning the messages with what is being checked will make failures easier to debug.

📝 Suggested clarifications
@@ initialized_client_with_transport
 		if cloned.client.Transport != tr {
-			t.Error("Cloned Client http.Client.Transport is not the same instance as original")
+			t.Error("Cloned Client http.Client.Transport is not the same instance as provided via WithTransport")
 		}
@@ initialized_client_with_http_client
 		if cloned.client.Transport != h.Transport {
-			t.Error("Cloned Client http.Client.Transport is not the same instance as original")
+			t.Error("Cloned Client http.Client.Transport is not the same instance as the WithHTTPClient transport")
 		}
@@ initialized_client_with_http_client_and_transport
 		if cloned.client.Transport != tr {
-			t.Error("Cloned Client http.Client.Transport is not the same instance as original")
+			t.Error("Cloned Client http.Client.Transport is not the same instance as provided via WithTransport")
 		}

Also applies to: 1273-1287

🤖 Prompt for AI Agents
Verify each finding against current code. Fix only still-valid issues, skip the
rest with a brief reason, keep changes minimal, and validate.

In `@github/github_test.go` around lines 1199 - 1213, The test error messages are
misleading: the checks using cloned.client.Transport != tr (and
cloned.client.Transport != h.Transport) are verifying that Clone used the
transport passed via WithTransport(tr)/WithTransport(h.Transport), not that it
kept the "original" transport from c; update the failure strings to say "does
not equal supplied transport (tr)" or "does not equal supplied transport
(h.Transport)" respectively in the initialized_client_with_transport and
initialized_client_with_http_client_and_transport subtests (and the analogous
check comparing to h.Transport), keeping references to cloned.client.Transport,
tr, h.Transport and WithTransport to locate the assertions.
🤖 Prompt for all review comments with AI agents
Verify each finding against current code. Fix only still-valid issues, skip the
rest with a brief reason, keep changes minimal, and validate.

Inline comments:
In `@example/migrations/main.go`:
- Line 21: Replace the hardcoded placeholder token in the github client creation
with the token read from the environment; change the call that creates the
client (the line that constructs client via github.NewClient(...)) to use
os.Getenv("GITHUB_AUTH_TOKEN") and guard/handle the case when the env var is
empty (e.g., log and exit or return an error) so the example aligns with other
code that sources the token from the environment.

In `@github/github_test.go`:
- Around line 466-484: Change the nil-check in the test that uses WithHTTPClient
so it fails immediately instead of continuing: replace the t.Error call that
asserts opts.httpClient == nil with t.Fatal (or t.Fatalf) so the test aborts
before the subsequent dereference (opts.httpClient.Timeout); this reference
occurs in the clientOptions test where opts is set by WithHTTPClient and
prevents a nil-pointer panic when httpClient is unexpectedly nil.
- Around line 780-790: The table-driven test dereferences
opts.maxSecondaryRateLimitRetryAfterDuration without checking for nil; update
the subtest in github_test.go to guard before dereferencing (when calling
WithSecondaryRateLimitOptions and asserting the value) by first verifying
opts.maxSecondaryRateLimitRetryAfterDuration != nil and failing the test with
t.Fatalf or using a separate assertion if it is nil, otherwise compare
*opts.maxSecondaryRateLimitRetryAfterDuration to tt.maxRetryAfterDuration;
reference clientOptions, WithSecondaryRateLimitOptions and the
opts.maxSecondaryRateLimitRetryAfterDuration field when making the change.
- Around line 523-535: In the "empty_user_agent" subtest, avoid dereferencing
opts.userAgent without a nil check and fix the error message to print the string
value; update the test to first assert opts.userAgent != nil (or handle nil as a
failure) before accessing *opts.userAgent and change the t.Errorf placeholder to
use the dereferenced string (e.g., "%q" or "%s" with *opts.userAgent) so
failures show the actual user-agent value; reference the clientOptions type and
the WithUserAgent function when making the guard and message change.

---

Outside diff comments:
In `@github/actions_workflows_test.go`:
- Around line 266-270: Update the stale assertion messages in the tests that
still reference client.BaseURL.Path to use the new internal field name
client.baseURL.Path; locate the failing t.Error/t.Fatalf messages (e.g., the
assertion after calling client.Actions.CreateWorkflowDispatchEventByID and the
other similar assertions in the same test file) and change the string
"client.BaseURL.Path=''" (and any other occurrences of "client.BaseURL.Path") to
"client.baseURL.Path=''" so failure output matches the actual field name used in
the code.

In `@github/examples_test.go`:
- Around line 78-82: Update the outdated comment wording that tells readers to
pass an OAuth client "instead of nil" to github.NewClient(); change all three
comment blocks in examples_test.go so they reference the current constructor
style github.NewClient(opts...) and instruct the reader to supply an
authenticated option (e.g., an oauth2 authenticated http.Client wrapped as an
option) rather than passing nil; apply the same replacement to each occurrence
that currently mentions "instead of nil" so the guidance matches the
NewClient(opts...) API.

---

Nitpick comments:
In `@github/actions_artifacts_test.go`:
- Line 294: Tests are directly mutating the internal field
rateLimitRedirectionalEndpoints on the client, which couples tests to
implementation; add a constructor option like
WithRateLimitRedirectionalEndpoints(bool) and accept it in the NewClient or
client creation flow so tests can set this behavior via the public API instead
of assigning client.rateLimitRedirectionalEndpoints directly; update tests to
use WithRateLimitRedirectionalEndpoints(tc.respectRateLimits) and adjust the
client/options handling code to apply that option during initialization.

In `@github/github_test.go`:
- Around line 1199-1213: The test error messages are misleading: the checks
using cloned.client.Transport != tr (and cloned.client.Transport != h.Transport)
are verifying that Clone used the transport passed via
WithTransport(tr)/WithTransport(h.Transport), not that it kept the "original"
transport from c; update the failure strings to say "does not equal supplied
transport (tr)" or "does not equal supplied transport (h.Transport)"
respectively in the initialized_client_with_transport and
initialized_client_with_http_client_and_transport subtests (and the analogous
check comparing to h.Transport), keeping references to cloned.client.Transport,
tr, h.Transport and WithTransport to locate the assertions.

In `@github/github.go`:
- Line 886: NewUploadRequest currently unconditionally sets
req.Header.Set("User-Agent", c.userAgent) which is inconsistent with NewRequest
and NewFormRequest (they only set the header when c.userAgent != ""), so update
NewUploadRequest to match by only setting the "User-Agent" header when
c.userAgent != "" (i.e., add the same guard used in NewRequest/NewFormRequest)
so a deliberate WithUserAgent("") results in no header across all request
constructors.
🪄 Autofix (Beta)

Fix all unresolved CodeRabbit comments on this PR:

  • Push a commit to this branch (recommended)
  • Create a new PR with the fixes

ℹ️ Review info
⚙️ Run configuration

Configuration used: Organization UI

Review profile: CHILL

Plan: Pro

Run ID: a25d4c72-e72b-4c2a-800a-291f8aabf685

📥 Commits

Reviewing files that changed from the base of the PR and between 9f9ead3 and 4ee0835.

📒 Files selected for processing (42)
  • README.md
  • example/actionpermissions/main.go
  • example/auditlogstream/main.go
  • example/basicauth/main.go
  • example/codespaces/newreposecretwithxcrypto/main.go
  • example/codespaces/newusersecretwithxcrypto/main.go
  • example/commitpr/main.go
  • example/contents/main.go
  • example/listenvironments/main.go
  • example/migrations/main.go
  • example/newfilewithappauth/main.go
  • example/newrepo/main.go
  • example/newreposecretwithxcrypto/main.go
  • example/otel/main.go
  • example/ratelimit/main.go
  • example/simple/main.go
  • example/tokenauth/main.go
  • example/topics/main.go
  • example/uploadreleaseassetfromrelease/main.go
  • example/verifyartifact/main.go
  • github/actions_artifacts.go
  • github/actions_artifacts_test.go
  • github/actions_workflow_jobs.go
  • github/actions_workflow_jobs_test.go
  • github/actions_workflow_runs.go
  • github/actions_workflow_runs_test.go
  • github/actions_workflows_test.go
  • github/copilot_test.go
  • github/doc.go
  • github/example_iterators_test.go
  • github/examples_test.go
  • github/github.go
  • github/github_test.go
  • github/rate_limit.go
  • github/rate_limit_test.go
  • github/repos_contents.go
  • github/repos_contents_test.go
  • github/repos_releases_test.go
  • test/fields/fields.go
  • test/integration/authorizations_test.go
  • test/integration/github_test.go
  • tools/metadata/main.go

Comment thread example/migrations/main.go
Comment thread github/github_test.go
Comment thread github/github_test.go
Comment thread github/github_test.go
Comment thread github/github.go
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

4 participants