### Configure OkHttp Connector with Disk Cache Source: https://github.com/hub4j/github-api/blob/main/src/test/resources/org/kohsuke/github/GHRepositoryTest/wiremock/testIssue162_raw/__files/hub4j_github-api_gh-pages_indexhtml-6.txt Example of setting up the GitHub API client with OkHttp and a persistent disk cache for efficient HTTP requests. ```java Cache cache = new Cache(cacheDirectory, 10 * 1024 * 1024); // 10MB cache GitHub gitHub = GitHubBuilder.fromCredentials() .withConnector(new OkHttpConnector(new OkUrlFactory(new OkHttpClient().setCache(cache)))) .build(); ``` -------------------------------- ### Connect to GitHub API with Authentication Source: https://context7.com/hub4j/github-api/llms.txt Demonstrates various authentication methods including OAuth token, JWT, App installation token, and anonymous access. Also shows how to validate the connection and check rate limits. ```java import org.kohsuke.github.*; // 1. Connect from ~/.github property file or GITHUB_* env vars GitHub gh = GitHub.connect(); // 2. Connect with an explicit OAuth token GitHub gh2 = new GitHubBuilder() .withOAuthToken(System.getenv("GITHUB_TOKEN")) .withRateLimitChecker(new RateLimitChecker.LiteralValue(50)) // pause when < 50 requests remain .withAbuseLimitHandler(GitHubAbuseLimitHandler.WAIT) .build(); // 3. Connect to GitHub Enterprise GitHub ghe = new GitHubBuilder() .withEndpoint("https://ghe.acme.com/api/v3") .withOAuthToken("ghe-token", "alice") .build(); // 4. Authenticate as a GitHub App via JWT, then obtain an installation token GitHub appGH = new GitHubBuilder().withJwtToken(jwtToken).build(); GHApp app = appGH.getApp(); GHAppInstallation installation = app.getInstallationById(12345678L); GHAppInstallationToken token = installation.createToken().create(); GitHub installationGH = new GitHubBuilder() .withAppInstallationToken(token.getToken()) .build(); // 5. Validate connection gh.checkApiUrlValidity(); System.out.println("Authenticated as: " + gh.getMyself().getLogin()); System.out.println("Core rate limit remaining: " + gh.getRateLimit().getCore().getRemaining()); ``` -------------------------------- ### Manage GitHub Apps Source: https://context7.com/hub4j/github-api/llms.txt Authenticate as a GitHub App using a JWT, retrieve app metadata, list installations, and create installation access tokens. This is useful for per-installation API calls. Ensure correct imports for GitHubBuilder, GHApp, GHAppInstallation, GHAppInstallationToken, and Map. ```java // Authenticate as the App using a JWT GitHub appGH = new GitHubBuilder().withJwtToken(myJwt).build(); // Get the App record GHApp app = appGH.getApp(); System.out.println("App: " + app.getName() + " (slug=" + app.getSlug() + ")"); // List all installations for (GHAppInstallation inst : app.listInstallations()) { System.out.println(" installation " + inst.getId() + " on account " + inst.getAccount().getLogin()); } // Create an installation access token scoped to specific repos GHAppInstallation installation = app.getInstallationByRepository("my-org", "my-repo"); GHAppInstallationToken token = installation.createToken() .repositoryIds(List.of(repoId)) .permissions(Map.of("contents", "read", "pull_requests", "write")) .create(); // Use the installation token GitHub installGH = new GitHubBuilder() .withAppInstallationToken(token.getToken()) .build(); GHRepository repo = installGH.getRepository("my-org/my-repo"); ``` -------------------------------- ### GitHub Apps Source: https://context7.com/hub4j/github-api/llms.txt Manage the GitHub Apps lifecycle, including reading app metadata, listing installations, and minting installation access tokens for per-installation API calls. ```APIDOC ## GitHub Apps — `GitHub.getApp()` / `GHApp` The library supports the full GitHub Apps lifecycle: reading app metadata, listing and managing installations, and minting installation access tokens for per-installation API calls. ```java // Authenticate as the App using a JWT GitHub appGH = new GitHubBuilder().withJwtToken(myJwt).build(); // Get the App record GHApp app = appGH.getApp(); System.out.println("App: " + app.getName() + " (slug=" + app.getSlug() + ")"); // List all installations for (GHAppInstallation inst : app.listInstallations()) { System.out.println(" installation " + inst.getId() + " on account " + inst.getAccount().getLogin()); } // Create an installation access token scoped to specific repos GHAppInstallation installation = app.getInstallationByRepository("my-org", "my-repo"); GHAppInstallationToken token = installation.createToken() .repositoryIds(List.of(repoId)) .permissions(Map.of("contents", "read", "pull_requests", "write")) .create(); // Use the installation token GitHub installGH = new GitHubBuilder() .withAppInstallationToken(token.getToken()) .build(); GHRepository repo = installGH.getRepository("my-org/my-repo"); ``` ``` -------------------------------- ### Manage GitHub Actions Workflows Source: https://context7.com/hub4j/github-api/llms.txt Shows how to list, get, dispatch, enable, and disable GitHub Actions workflows. Requires GHWorkflowRun for run details. ```java GHRepository repo = gh.getRepository("my-org/my-project"); // List workflows for (GHWorkflow wf : repo.listWorkflows()) { System.out.printf("%s state=%s%n", wf.getName(), wf.getState()); } // Get workflow by name/path GHWorkflow ciWorkflow = repo.getWorkflow("ci.yml"); // Trigger a manual dispatch with inputs ciWorkflow.dispatch("main", Map.of( "environment", "staging", "debug", "false")); // List recent runs for (GHWorkflowRun run : ciWorkflow.listRuns().withPageSize(5)) { System.out.printf("Run #%d status=%-12s conclusion=%s%n", run.getRunNumber(), run.getStatus(), run.getConclusion()); } // Disable a workflow ciWorkflow.disable(); // Re-enable later ciWorkflow.enable(); ``` -------------------------------- ### Releases Management Source: https://context7.com/hub4j/github-api/llms.txt Create, upload assets to, and list GitHub releases for a repository. Also includes functionality to get the latest release. ```APIDOC ## Releases — `GHRepository.createRelease()` / `GHRelease` `GHRelease` models a GitHub Release, including tag name, release notes, draft/prerelease flags, and binary asset upload. ```java GHRepository repo = gh.getRepository("my-org/my-project"); // Create a release GHRelease release = repo.createRelease("v1.2.3") .name("Version 1.2.3") .body("## What's New\n- Fixed NPE\n- Performance improvements") .draft(false) .prerelease(false) .create(); // Upload a binary asset File jar = new File("target/my-project-1.2.3.jar"); release.uploadAsset(jar, "application/java-archive"); // List all releases for (GHRelease r : repo.listReleases()) { System.out.printf("% -10s draft=% -5b pre=% -5b assets=%d%n", r.getTagName(), r.isDraft(), r.isPrerelease(), r.getAssets().size()); } // Get latest release GHRelease latest = repo.getLatestRelease(); System.out.println("Latest: " + latest.getTagName() + " published " + latest.getPublished_at()); ``` ``` -------------------------------- ### Clone GitHub API Repository Anonymously Source: https://github.com/hub4j/github-api/blob/main/src/test/resources/org/kohsuke/github/GHRepositoryTest/wiremock/testIssue162_raw/__files/hub4j_github-api_gh-pages_source-repositoryhtml-16.txt Use this command to clone the repository anonymously. Ensure Git is installed and configured. ```bash $ git clone --branch github-api-1.95 git@github.com/kohsuke/github-api.git ``` -------------------------------- ### Access and Manage Repositories Source: https://context7.com/hub4j/github-api/llms.txt Shows how to retrieve repository metadata, list branches, create new repositories, update settings, fork repositories, and delete repositories. ```java GHRepository repo = gh.getRepository("hub4j/github-api"); // Basic metadata System.out.println(repo.getFullName()); // hub4j/github-api System.out.println(repo.getDescription()); System.out.println(repo.getStargazersCount()); System.out.println(repo.getDefaultBranch()); // main System.out.println(repo.isPrivate()); // List branches for (GHBranch branch : repo.getBranches().values()) { System.out.println(branch.getName() + " @ " + branch.getSHA1()); } // Create a new repository under the authenticated user GHRepository newRepo = gh.createRepository("my-new-repo") .description("Created via API") .private_(false) .autoInit(true) .create(); // Update repository settings repo.set() .description("Updated description") .allowSquashMerge(true) .deleteBranchOnMerge(true) .done(); // Fork a repository GHRepository fork = repo.createFork().organization("my-org").create(); // Delete repository (requires admin permission) newRepo.delete(); ``` -------------------------------- ### Create a New Repository with GitHub API for Java Source: https://github.com/hub4j/github-api/blob/main/src/test/resources/org/kohsuke/github/GHRepositoryTest/wiremock/testIssue162_raw/__files/hub4j_github-api_gh-pages_indexhtml-6.txt Demonstrates how to connect to GitHub and create a new public repository with a description and website URL. Ensure you have the GitHub API library imported. ```java GitHub github = GitHub.connect(); GHRepository repo = github.createRepository( "new-repository","this is my new repository", "http://www.kohsuke.org/",true/*public*/); ``` -------------------------------- ### GitHub Credentials from Properties File Source: https://github.com/hub4j/github-api/blob/main/src/test/resources/org/kohsuke/github/GHRepositoryTest/wiremock/testIssue162_raw/__files/hub4j_github-api_gh-pages_indexhtml-6.txt Shows how to configure GitHub credentials using a properties file. ```properties login=kohsuke password=012345678 ``` ```properties oauth=4d98173f7c075527cb64878561d1fe70 ``` -------------------------------- ### Create and Manage GitHub Releases Source: https://context7.com/hub4j/github-api/llms.txt Demonstrates how to create a new GitHub release, upload assets, and list/get existing releases. ```java GHRepository repo = gh.getRepository("my-org/my-project"); // Create a release GHRelease release = repo.createRelease("v1.2.3") .name("Version 1.2.3") .body("## What's New\n- Fixed NPE\n- Performance improvements") .draft(false) .prerelease(false) .create(); // Upload a binary asset File jar = new File("target/my-project-1.2.3.jar"); release.uploadAsset(jar, "application/java-archive"); // List all releases for (GHRelease r : repo.listReleases()) { System.out.printf("% -10s draft=%-5b pre=%-5b assets=%d%n", r.getTagName(), r.isDraft(), r.isPrerelease(), r.getAssets().size()); } // Get latest release GHRelease latest = repo.getLatestRelease(); System.out.println("Latest: " + latest.getTagName() + " published " + latest.getPublished_at()); ``` -------------------------------- ### Search GitHub Repositories Source: https://context7.com/hub4j/github-api/llms.txt Demonstrates fluent query construction for searching repositories based on keywords, language, and stars. ```java // Search repositories PagedIterable repos = gh.searchRepositories() .q("machine learning") .language("python") .stars(">1000") .sort(GHRepositorySearchBuilder.Sort.STARS) .order(GHDirection.DESC) .list(); repos.withPageSize(10).iterator().forEachRemaining(r -> System.out.printf("% -40s ⭐%d%n", r.getFullName(), r.getStargazersCount())); ``` -------------------------------- ### Create and Manage GitHub Issues Source: https://context7.com/hub4j/github-api/llms.txt Demonstrates creating, listing, commenting on, labeling, assigning, and closing issues. Also shows how to search issues across GitHub. ```java GHRepository repo = gh.getRepository("my-org/my-project"); // Create an issue GHIssue issue = repo.createIssue("Bug: NullPointerException in Foo.bar()") .body("Steps to reproduce:\n1. Call `Foo.bar(null)`\n2. Observe NPE") .label("bug") .assignee("alice") .create(); System.out.println("Created issue #" + issue.getNumber()); // List open issues for (GHIssue i : repo.getIssues(GHIssueState.OPEN)) { System.out.printf("#%d [%s] %s%n", i.getNumber(), i.getState(), i.getTitle()); } // Comment, label, and close issue.comment("Confirmed — fixing in next PR."); issue.addLabels("confirmed"); issue.setMilestone(repo.getMilestone(1)); issue.close(GHIssueStateReason.COMPLETED); // Search issues across GitHub List results = gh.searchIssues() .q("label:bug language:java") .list() .withPageSize(20) .toList(); ``` -------------------------------- ### Create, Read, Update, Fork, and Star Gists Source: https://context7.com/hub4j/github-api/llms.txt Demonstrates the lifecycle of a Gist using the GitHub API for Java. Includes creating a new gist, fetching it, updating its content, forking it, and starring it. Ensure you have authenticated with the GitHub API before executing. ```java GHGist gist = gh.createGist() .description("Prime sieve in Java") .file("Sieve.java", "public class Sieve { /* ... */ }") .public_(true) .create(); System.out.println("Gist URL: " + gist.getHtmlUrl()); // Read back GHGist fetched = gh.getGist(gist.getGistId()); for (Map.Entry entry : fetched.getFiles().entrySet()) { System.out.println(entry.getKey() + " (" + entry.getValue().getSize() + " bytes)"); } // Update GHGistUpdater updater = fetched.update(); updater.updateFile("Sieve.java", "// improved\npublic class Sieve { /* v2 */ }"); GHGist updated = updater.update(); // Fork and star GHGist forked = fetched.fork(); fetched.star(); System.out.println("Starred: " + fetched.isStarred()); ``` -------------------------------- ### Apply Code Formatting Source: https://github.com/hub4j/github-api/blob/main/CONTRIBUTING.md Run this Maven command to automatically format code and fix style issues. ```bash mvn spotless:apply ``` -------------------------------- ### Manage GitHub Organizations and Teams Source: https://context7.com/hub4j/github-api/llms.txt Illustrates creating repositories, managing members, teams, and organization-level projects. ```java GHOrganization org = gh.getOrganization("my-org"); // Create an org repository GHRepository orgRepo = org.createRepository("new-service") .description("New microservice") .private_(true) .autoInit(true) .create(); // List members for (GHUser member : org.getMembers()) { System.out.println(member.getLogin()); } // Manage a team GHTeam team = org.getTeamByName("backend"); team.add(gh.getUser("dave"), GHTeam.Role.MEMBER); team.addRepository(orgRepo, GHOrganization.RepositoryRole.from(GHOrganization.Permission.PUSH)); // Invite a user to the org org.add(gh.getUser("eve"), GHOrganization.Role.MEMBER); // Org-level projects GHProject project = org.createProject("Q3 Roadmap", "Our Q3 goals"); GHProjectColumn column = project.createColumn("To Do"); column.createCard("Implement feature X"); ``` -------------------------------- ### Configure GitHub Proxy for Tests Source: https://github.com/hub4j/github-api/blob/main/CONTRIBUTING.md Enable the GitHub proxy for tests by setting the system property 'test.github.useProxy'. This directs tests to use local WireMock data files and falls back to GitHub if data is not found. Ensure GITHUB_OAUTH environment variable is set with a personal access token. ```bash mvn install -Dtest.github.useProxy -Dtest=WireMockStatusReporterTest ``` -------------------------------- ### Authentication and Connection Source: https://context7.com/hub4j/github-api/llms.txt Demonstrates various ways to authenticate and establish a connection to the GitHub API using GitHubBuilder. ```APIDOC ## Authentication and Connection — `GitHub` / `GitHubBuilder` `GitHubBuilder` constructs a `GitHub` client with the chosen authentication strategy (OAuth token, JWT, App installation token, or anonymous) and optional rate-limit and abuse-limit handlers. The completed builder produces a `GitHub` root object from which all other operations originate. ```java import org.kohsuke.github.*; // 1. Connect from ~/.github property file or GITHUB_* env vars GitHub gh = GitHub.connect(); // 2. Connect with an explicit OAuth token GitHub gh2 = new GitHubBuilder() .withOAuthToken(System.getenv("GITHUB_TOKEN")) .withRateLimitChecker(new RateLimitChecker.LiteralValue(50)) // pause when < 50 requests remain .withAbuseLimitHandler(GitHubAbuseLimitHandler.WAIT) .build(); // 3. Connect to GitHub Enterprise GitHub ghe = new GitHubBuilder() .withEndpoint("https://ghe.acme.com/api/v3") .withOAuthToken("ghe-token", "alice") .build(); // 4. Authenticate as a GitHub App via JWT, then obtain an installation token GitHub appGH = new GitHubBuilder().withJwtToken(jwtToken).build(); GHApp app = appGH.getApp(); GHAppInstallation installation = app.getInstallationById(12345678L); GHAppInstallationToken token = installation.createToken().create(); GitHub installationGH = new GitHubBuilder() .withAppInstallationToken(token.getToken()) .build(); // 5. Validate connection gh.checkApiUrlValidity(); System.out.println("Authenticated as: " + gh.getMyself().getLogin()); System.out.println("Core rate limit remaining: " + gh.getRateLimit().getCore().getRemaining()); ``` ``` -------------------------------- ### Repository Access Source: https://context7.com/hub4j/github-api/llms.txt Shows how to retrieve, create, update, fork, and delete repositories using the GHRepository object. ```APIDOC ## Repository Access — `GitHub.getRepository()` / `GHRepository` `GitHub.getRepository(String)` retrieves a repository by `"owner/name"` and returns a `GHRepository` that exposes metadata, branch/tag/commit operations, issue tracking, pull requests, releases, workflows, content, and settings. ```java GHRepository repo = gh.getRepository("hub4j/github-api"); // Basic metadata System.out.println(repo.getFullName()); // hub4j/github-api System.out.println(repo.getDescription()); System.out.println(repo.getStargazersCount()); System.out.println(repo.getDefaultBranch()); // main System.out.println(repo.isPrivate()); // List branches for (GHBranch branch : repo.getBranches().values()) { System.out.println(branch.getName() + " @ " + branch.getSHA1()); } // Create a new repository under the authenticated user GHRepository newRepo = gh.createRepository("my-new-repo") .description("Created via API") .private_(false) .autoInit(true) .create(); // Update repository settings repo.set() .description("Updated description") .allowSquashMerge(true) .deleteBranchOnMerge(true) .done(); // Fork a repository GHRepository fork = repo.createFork().organization("my-org").create(); // Delete repository (requires admin permission) newRepo.delete(); ``` ``` -------------------------------- ### Add Collaborators and Delete Repository Source: https://github.com/hub4j/github-api/blob/main/src/test/resources/org/kohsuke/github/GHRepositoryTest/wiremock/testIssue162_raw/__files/hub4j_github-api_gh-pages_indexhtml-6.txt Demonstrates adding collaborators to a repository and deleting the repository. ```java repo.addCollaborators(github.getUser("abayer"),github.getUser("rtyler")); repo.delete(); ``` -------------------------------- ### Run WireMock Tests Source: https://github.com/hub4j/github-api/blob/main/CONTRIBUTING.md Use this Maven command to run all tests that utilize WireMock for stubbing HTTP responses. ```bash mvn install -Dtest=WireMockStatusReporterTest ``` -------------------------------- ### Manage GitHub Repository File Content Source: https://context7.com/hub4j/github-api/llms.txt Shows how to read, create, update, and delete files in a repository, as well as list directory contents. Write operations require a commit message. ```java GHRepository repo = gh.getRepository("my-org/my-project"); // Read a file GHContent file = repo.getFileContent("README.md"); try (InputStream is = file.read()) { System.out.println(new String(is.readAllBytes())); } // Create a new file GHContentUpdateResponse created = repo.createContent() .path("docs/guide.md") .message("Add guide doc") .content("# Guide\nHello world!") .branch("main") .commit(); System.out.println("Created SHA: " + created.getContent().getSha()); // Update existing file (SHA of current blob is required) GHContent existing = repo.getFileContent("docs/guide.md"); GHContentUpdateResponse updated = existing.createUpdate() .message("Update guide") .content("# Guide\nUpdated content.") .branch("main") .commit(); // Delete a file existing.delete("Remove obsolete guide", "main"); // List directory contents List entries = repo.getDirectoryContent("src/main/java"); entries.forEach(e -> System.out.println(e.getType() + "\t" + e.getPath())); ``` -------------------------------- ### Gist Management Operations Source: https://context7.com/hub4j/github-api/llms.txt Demonstrates the creation, reading, updating, forking, and starring of Gists using the GitHub API for Java. ```APIDOC ## Gist Management — `GitHub.createGist()` / `GHGist` Gists are standalone code snippets hosted on GitHub. The library supports creating, reading, updating, forking, and starring gists. ```java // Create a gist GHGist gist = gh.createGist() .description("Prime sieve in Java") .file("Sieve.java", "public class Sieve { /* ... */ }") .public_(true) .create(); System.out.println("Gist URL: " + gist.getHtmlUrl()); // Read back GHGist fetched = gh.getGist(gist.getGistId()); for (Map.Entry entry : fetched.getFiles().entrySet()) { System.out.println(entry.getKey() + " (" + entry.getValue().getSize() + " bytes)"); } // Update GHGistUpdater updater = fetched.update(); updater.updateFile("Sieve.java", "// improved\npublic class Sieve { /* v2 */ }"); GHGist updated = updater.update(); // Fork and star GHGist forked = fetched.fork(); fetched.star(); System.out.println("Starred: " + fetched.isStarred()); ``` ``` -------------------------------- ### Manage Webhooks (Hooks) Source: https://context7.com/hub4j/github-api/llms.txt Create, list, and delete repository or organization webhooks. This snippet also shows how to parse incoming webhook payloads server-side. Ensure correct imports for Map, List, GHEvent, GHEventPayload, and StringReader. ```java GHRepository repo = gh.getRepository("my-org/my-project"); // Create a webhook Map config = Map.of( "url", "https://hooks.example.com/github", "content_type", "json", "secret", "s3cr3t"); GHHook hook = repo.createHook( "web", config, List.of(GHEvent.PUSH, GHEvent.PULL_REQUEST), true); System.out.println("Hook ID: " + hook.getId()); // Parse an inbound webhook payload (in a servlet, for example) // GitHub gh = GitHub.offline(); // no credentials needed for parsing GHEventPayload.Push push = gh.parseEventPayload( new StringReader(requestBody), GHEventPayload.Push.class); System.out.println("Pushed to: " + push.getRef()); push.getCommits().forEach(c -> System.out.println(" " + c.getId() + " " + c.getMessage())); // List and delete hooks for (GHHook h : repo.getHooks()) { System.out.println(h.getId() + " → " + h.getConfig().get("url")); } hook.delete(); ``` -------------------------------- ### Take a Snapshot of Test Data Source: https://github.com/hub4j/github-api/blob/main/CONTRIBUTING.md Generate WireMock snapshot data files by running tests with the '-Dtest.github.takeSnapshot' option. This is useful for creating or updating the local data files used by WireMock. If using a personal GitHub account, adjust repository targeting in your test code. ```bash mvn install -Dtest.github.takeSnapshot -Dtest.github.org=false -Dtest=YourTestClassName ``` -------------------------------- ### Run CI Checks Source: https://github.com/hub4j/github-api/blob/main/CONTRIBUTING.md Execute this Maven command to ensure all tests and build processes pass before submitting a pull request. ```bash mvn -D enable-ci clean install site "-Dsurefire.argLine=--add-opens java.base/java.net=ALL-UNNAMED" ``` -------------------------------- ### Run a Single WireMock Test Case Source: https://github.com/hub4j/github-api/blob/main/CONTRIBUTING.md Execute a specific test case within a WireMock test class by appending the method name. ```bash mvn install -Dtest=WireMockStatusReporterTest#user_whenProxying_AuthCorrectlyConfigured ``` -------------------------------- ### Create and Manage GitHub Pull Requests Source: https://context7.com/hub4j/github-api/llms.txt Covers creating pull requests, requesting reviewers, adding comments, submitting reviews, merging, and querying open pull requests. ```java GHRepository repo = gh.getRepository("my-org/my-project"); // Create a pull request GHPullRequest pr = repo.createPullRequest( "Fix NPE in Foo.bar()", // title "fix/npe-foo-bar", // head branch "main", // base branch "Resolves #42. Added null-check before calling bar().", true, // maintainers can modify false); // not a draft System.out.println("PR #" + pr.getNumber() + ": " + pr.getHtmlUrl()); // Request reviewers pr.requestReviewers(List.of(gh.getUser("bob"), gh.getUser("carol"))); // Add a line comment on the diff pr.createReviewComment() .body("Shouldn't this be `Objects.requireNonNull`?") .commitId(pr.getHead().getSha()) .path("src/main/java/com/example/Foo.java") .position(12) .create(); // Approve and submit review pr.createReview() .event(GHPullRequestReviewEvent.APPROVE) .body("LGTM!") .create(); // Merge pr.merge("Squash-merging: Fix NPE in Foo.bar()", null, GHPullRequest.MergeMethod.SQUASH); // Query open PRs for (GHPullRequest open : repo.queryPullRequests() .state(GHIssueState.OPEN) .base("main") .list()) { System.out.printf("PR #%d %s (%d commits)%n", open.getNumber(), open.getTitle(), open.getCommits()); } ``` -------------------------------- ### Search GitHub Users Source: https://context7.com/hub4j/github-api/llms.txt Demonstrates searching for users based on location, programming language, and follower count. ```java // Search users gh.searchUsers() .q("location:Berlin language:java followers:>100") .list() .withPageSize(5) .iterator() .forEachRemaining(u -> System.out.println(u.getLogin())); ``` -------------------------------- ### Search GitHub Issues and Pull Requests Source: https://context7.com/hub4j/github-api/llms.txt Shows how to search for issues and pull requests using a query string with various filters. ```java // Search issues/PRs List issues = gh.searchIssues() .q("is:issue is:open label:bug repo:hub4j/github-api") .list() .toList(); ``` -------------------------------- ### Search GitHub Commits Source: https://context7.com/hub4j/github-api/llms.txt Illustrates searching for commits within a specific repository based on keywords. ```java // Search commits gh.searchCommits() .q("fix NPE repo:hub4j/github-api") .list() .withPageSize(5) .iterator() .forEachRemaining(c -> System.out.println(c.getCommitShortInfo().getMessage())); ``` -------------------------------- ### Run Tests Against Personal GitHub Account Source: https://github.com/hub4j/github-api/blob/main/CONTRIBUTING.md To target your personal GitHub account instead of the default 'hub4j-test-org', set '-Dtest.github.org=false'. This is useful when you don't have access to the organization or prefer to use your own account for testing. ```bash mvn install -Dtest.github.org=false -Dtest=YourTestClassName ``` -------------------------------- ### Search Functionalities Source: https://context7.com/hub4j/github-api/llms.txt Utilize fluent query builders to search for repositories, issues, pull requests, users, commits, and code on GitHub. ```APIDOC ## Search — `GitHub.searchRepositories()` / `GitHub.searchIssues()` etc. The search builders provide fluent query construction for repositories, issues, pull requests, users, commits, and code. ```java // Search repositories PagedIterable repos = gh.searchRepositories() .q("machine learning") .language("python") .stars(">1000") .sort(GHRepositorySearchBuilder.Sort.STARS) .order(GHDirection.DESC) .list(); repos.withPageSize(10).iterator().forEachRemaining(r -> System.out.printf("% -40s ⭐%d%n", r.getFullName(), r.getStargazersCount())); // Search issues/PRs List issues = gh.searchIssues() .q("is:issue is:open label:bug repo:hub4j/github-api") .list() .toList(); // Search users gh.searchUsers() .q("location:Berlin language:java followers:>100") .list() .withPageSize(5) .iterator() .forEachRemaining(u -> System.out.println(u.getLogin())); // Search commits gh.searchCommits() .q("fix NPE repo:hub4j/github-api") .list() .withPageSize(5) .iterator() .forEachRemaining(c -> System.out.println(c.getCommitShortInfo().getMessage())); ``` ``` -------------------------------- ### Webhooks (Hooks) Source: https://context7.com/hub4j/github-api/llms.txt Create and manage repository and organization webhooks to forward GitHub events to external URLs, and parse incoming webhook payloads. ```APIDOC ## Webhooks (Hooks) — `GHRepository.createHook()` / `GHOrganization.createHook()` Repository and organization hooks forward GitHub events to external URLs. The library can also deserialize incoming webhook payloads server-side. ```java GHRepository repo = gh.getRepository("my-org/my-project"); // Create a webhook Map config = Map.of( "url", "https://hooks.example.com/github", "content_type", "json", "secret", "s3cr3t"); GHHook hook = repo.createHook( "web", config, List.of(GHEvent.PUSH, GHEvent.PULL_REQUEST), true); System.out.println("Hook ID: " + hook.getId()); // Parse an inbound webhook payload (in a servlet, for example) // GitHub gh = GitHub.offline(); // no credentials needed for parsing GHEventPayload.Push push = gh.parseEventPayload( new StringReader(requestBody), GHEventPayload.Push.class); System.out.println("Pushed to: " + push.getRef()); push.getCommits().forEach(c -> System.out.println(" " + c.getId() + " " + c.getMessage())); // List and delete hooks for (GHHook h : repo.getHooks()) { System.out.println(h.getId() + " → " + h.getConfig().get("url")); } hook.delete(); ``` ``` -------------------------------- ### Clone GitHub API Repository with Developer Access Source: https://github.com/hub4j/github-api/blob/main/src/test/resources/org/kohsuke/github/GHRepositoryTest/wiremock/testIssue162_raw/__files/hub4j_github-api_gh-pages_source-repositoryhtml-16.txt This command is for project developers to access the Git tree. It requires SSH authentication. ```bash $ git clone --branch github-api-1.95 ssh://git@github.com/kohsuke/github-api.git ``` -------------------------------- ### SBT Dependency for github-api Source: https://github.com/hub4j/github-api/blob/main/src/test/resources/org/kohsuke/github/GHRepositoryTest/wiremock/testIssue162_raw/__files/hub4j_github-api_gh-pages_dependency-infohtml-4.txt Configure your build.sbt with this line to add the github-api library. ```scala libraryDependencies += "org.kohsuke" % "github-api" % "1.95" ``` -------------------------------- ### Issue Management Source: https://context7.com/hub4j/github-api/llms.txt Manage GitHub issues including creation, listing, commenting, labeling, assigning, and closing. The `GHRepository.createIssue()` method initiates the issue creation process. ```APIDOC ## Issue Management — `GHRepository.createIssue()` / `GHIssue` Issues can be listed, created, commented on, labeled, assigned, and closed through `GHIssue`. The repository's `createIssue(title)` builder accepts body, labels, assignees, and milestone. ```java GHRepository repo = gh.getRepository("my-org/my-project"); // Create an issue GHIssue issue = repo.createIssue("Bug: NullPointerException in Foo.bar()") .body("Steps to reproduce:\n1. Call `Foo.bar(null)`\n2. Observe NPE") .label("bug") .assignee("alice") .create(); System.out.println("Created issue #" + issue.getNumber()); // List open issues for (GHIssue i : repo.getIssues(GHIssueState.OPEN)) { System.out.printf("#%d [%s] %s%n", i.getNumber(), i.getState(), i.getTitle()); } // Comment, label, and close issue.comment("Confirmed — fixing in next PR."); issue.addLabels("confirmed"); issue.setMilestone(repo.getMilestone(1)); issue.close(GHIssueStateReason.COMPLETED); // Search issues across GitHub List results = gh.searchIssues() .q("label:bug language:java") .list() .withPageSize(20) .toList(); ``` ``` -------------------------------- ### Leiningen Dependency for github-api Source: https://github.com/hub4j/github-api/blob/main/src/test/resources/org/kohsuke/github/GHRepositoryTest/wiremock/testIssue162_raw/__files/hub4j_github-api_gh-pages_dependency-infohtml-4.txt Add this to your project.clj for Leiningen dependency management. ```clojure [org.kohsuke/github-api "1.95"] ``` -------------------------------- ### GitHub Actions Workflows Source: https://context7.com/hub4j/github-api/llms.txt Inspect, enable/disable, and manually dispatch GitHub Actions workflows. Track individual run states, logs, and artifacts. ```APIDOC ## GitHub Actions Workflows — `GHRepository.getWorkflow()` / `GHWorkflow` `GHWorkflow` lets you inspect, enable/disable, and manually dispatch workflow runs. `GHWorkflowRun` tracks individual run state, logs, and artifacts. ```java GHRepository repo = gh.getRepository("my-org/my-project"); // List workflows for (GHWorkflow wf : repo.listWorkflows()) { System.out.printf("%s state=%s%n", wf.getName(), wf.getState()); } // Get workflow by name/path GHWorkflow ciWorkflow = repo.getWorkflow("ci.yml"); // Trigger a manual dispatch with inputs ciWorkflow.dispatch("main", Map.of( "environment", "staging", "debug", "false")); // List recent runs for (GHWorkflowRun run : ciWorkflow.listRuns().withPageSize(5)) { System.out.printf("Run #%d status=% -12s conclusion=%s%n", run.getRunNumber(), run.getStatus(), run.getConclusion()); } // Disable a workflow ciWorkflow.disable(); // Re-enable later ciWorkflow.enable(); ``` ``` -------------------------------- ### Job Execution Output Source: https://github.com/hub4j/github-api/blob/main/src/test/resources/org/kohsuke/github/GHWorkflowRunTest/wiremock/testJobs_actions-user-content/__files/1-u_a_p_1_runs_139_signedlogcontent_5.txt This snippet shows the output of a job executing a simple echo command. It includes the command itself, the shell used, and the final output. This is useful for verifying basic command execution within a workflow. ```bash ##[group]Run echo Hello from job1!\necho Hello from job1!\nshell: /usr/bin/bash -e {0}\n##[endgroup]\nHello from job1! ``` -------------------------------- ### Maven Dependency for github-api Source: https://github.com/hub4j/github-api/blob/main/src/test/resources/org/kohsuke/github/GHRepositoryTest/wiremock/testIssue162_raw/__files/hub4j_github-api_gh-pages_dependency-infohtml-4.txt Add this to your Maven pom.xml to include the github-api library. ```xml <dependency> <groupId>org.kohsuke</groupId> <artifactId>github-api</artifactId> <version>1.95</version> </dependency> ``` -------------------------------- ### File Content Management Source: https://context7.com/hub4j/github-api/llms.txt Manage file and directory content within a GitHub repository. This includes reading, creating, updating, and deleting files, as well as listing directory contents. Write operations require a commit message and optionally a branch name. ```APIDOC ## File Content Management — `GHRepository.getFileContent()` / `GHContent` `GHContent` represents a single file or directory entry in a repository's git tree. Files can be read, created, updated, and deleted; all write operations accept a commit message and optional branch name. ```java GHRepository repo = gh.getRepository("my-org/my-project"); // Read a file GHContent file = repo.getFileContent("README.md"); try (InputStream is = file.read()) { System.out.println(new String(is.readAllBytes())); } // Create a new file GHContentUpdateResponse created = repo.createContent() .path("docs/guide.md") .message("Add guide doc") .content("# Guide\nHello world!") .branch("main") .commit(); System.out.println("Created SHA: " + created.getContent().getSha()); // Update existing file (SHA of current blob is required) GHContent existing = repo.getFileContent("docs/guide.md"); GHContentUpdateResponse updated = existing.createUpdate() .message("Update guide") .content("# Guide\nUpdated content.") .branch("main") .commit(); // Delete a file existing.delete("Remove obsolete guide", "main"); // List directory contents List entries = repo.getDirectoryContent("src/main/java"); entries.forEach(e -> System.out.println(e.getType() + "\t" + e.getPath())); ``` ``` -------------------------------- ### Pull Request Management Source: https://context7.com/hub4j/github-api/llms.txt Manage GitHub pull requests, including creation, requesting reviewers, adding comments, approving, merging, and querying open pull requests. The `GHRepository.createPullRequest()` method is used for creation. ```APIDOC ## Pull Request Management — `GHRepository.createPullRequest()` / `GHPullRequest` Pull requests extend `GHIssue` and add diff/patch URLs, review management, merge operations, and CI-status-aware auto-merge via the GraphQL API. ```java GHRepository repo = gh.getRepository("my-org/my-project"); // Create a pull request GHPullRequest pr = repo.createPullRequest( "Fix NPE in Foo.bar()", // title "fix/npe-foo-bar", // head branch "main", // base branch "Resolves #42. Added null-check before calling bar().", true, // maintainers can modify false); // not a draft System.out.println("PR #" + pr.getNumber() + ": " + pr.getHtmlUrl()); // Request reviewers pr.requestReviewers(List.of(gh.getUser("bob"), gh.getUser("carol"))); // Add a line comment on the diff pr.createReviewComment() .body("Shouldn't this be `Objects.requireNonNull`?") .commitId(pr.getHead().getSha()) .path("src/main/java/com/example/Foo.java") .position(12) .create(); // Approve and submit review pr.createReview() .event(GHPullRequestReviewEvent.APPROVE) .body("LGTM!") .create(); // Merge pr.merge("Squash-merging: Fix NPE in Foo.bar()", null, GHPullRequest.MergeMethod.SQUASH); // Query open PRs for (GHPullRequest open : repo.queryPullRequests() .state(GHIssueState.OPEN) .base("main") .list()) { System.out.printf("PR #%d %s (%d commits)%n", open.getNumber(), open.getTitle(), open.getCommits()); } ``` ``` -------------------------------- ### Ivy Dependency for GitHub API Source: https://github.com/hub4j/github-api/blob/main/src/test/resources/org/kohsuke/github/GHRepositoryTest/wiremock/testIssue162_raw/__files/hub4j_github-api_gh-pages_dependency-infohtml-4.txt Configure your Apache Ivy settings with this dependency to integrate the GitHub API for Java. ```xml ``` -------------------------------- ### Buildr Dependency for GitHub API Source: https://github.com/hub4j/github-api/blob/main/src/test/resources/org/kohsuke/github/GHRepositoryTest/wiremock/testIssue162_raw/__files/hub4j_github-api_gh-pages_dependency-infohtml-4.txt Add this line to your Buildr build file to include the GitHub API for Java. ```ruby 'org.kohsuke:github-api:jar:1.95' ``` -------------------------------- ### Manage Commit Status and Branch Protection Source: https://context7.com/hub4j/github-api/llms.txt Report commit statuses for CI integrations and enforce branch protection rules. Ensure necessary imports for GHCommitState, GHBranch, GHBranchProtection, and Collections. ```java GHRepository repo = gh.getRepository("my-org/my-project"); String sha = repo.getBranch("main").getSHA1(); // Report a commit status (e.g., from a CI script) repo.createCommitStatus(sha, GHCommitState.SUCCESS, "https://ci.example.com/builds/42", "All tests passed", "ci/tests"); // Enable branch protection on main GHBranch main = repo.getBranch("main"); main.enableProtection() .requiredReviewers(1) .requireBranchIsUpToDate(true) .requireCodeOwnReviews(true) .addRequiredChecks("ci/tests") .restrictPushAccess() .teamPushAccess(Collections.singletonList(repo.getOrganization().getTeamByName("leads"))) .enable(); // Read existing protection rules GHBranchProtection protection = main.getProtection(); System.out.println("Required reviews: " + protection.getRequiredReviews().getRequiredReviewers()); ``` -------------------------------- ### Organization Management Source: https://context7.com/hub4j/github-api/llms.txt Access and manage organization details including teams, members, repositories, hooks, and projects. ```APIDOC ## Organization Management — `GitHub.getOrganization()` / `GHOrganization` `GHOrganization` provides access to teams, members, repositories, and org-level hooks and projects. ```java GHOrganization org = gh.getOrganization("my-org"); // Create an org repository GHRepository orgRepo = org.createRepository("new-service") .description("New microservice") .private_(true) .autoInit(true) .create(); // List members for (GHUser member : org.getMembers()) { System.out.println(member.getLogin()); } // Manage a team GHTeam team = org.getTeamByName("backend"); team.add(gh.getUser("dave"), GHTeam.Role.MEMBER); team.addRepository(orgRepo, GHOrganization.RepositoryRole.from(GHOrganization.Permission.PUSH)); // Invite a user to the org org.add(gh.getUser("eve"), GHOrganization.Role.MEMBER); // Org-level projects GHProject project = org.createProject("Q3 Roadmap", "Our Q3 goals"); GHProjectColumn column = project.createColumn("To Do"); column.createCard("Implement feature X"); ``` ``` -------------------------------- ### Grails Dependency for github-api Source: https://github.com/hub4j/github-api/blob/main/src/test/resources/org/kohsuke/github/GHRepositoryTest/wiremock/testIssue162_raw/__files/hub4j_github-api_gh-pages_dependency-infohtml-4.txt Include this line in your Grails BuildConfig.groovy for the github-api library. ```groovy compile 'org.kohsuke:github-api:1.95' ``` -------------------------------- ### Maven Dependency for GitHub API Source: https://github.com/hub4j/github-api/blob/main/src/test/resources/org/kohsuke/github/GHRepositoryTest/wiremock/testIssue162_raw/__files/hub4j_github-api_gh-pages_dependency-infohtml-4.txt Include this dependency in your Maven project's pom.xml to use the GitHub API for Java. ```xml org.kohsuke github-api 1.95 ```