Skip to content
Draft
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
8 changes: 7 additions & 1 deletion src/main/java/app/testlens/cli/CommandSupport.java
Original file line number Diff line number Diff line change
Expand Up @@ -9,6 +9,7 @@
import java.util.List;
import java.util.regex.Pattern;
import org.jspecify.annotations.Nullable;
import picocli.CommandLine.Model.CommandSpec;

/**
* Shared plumbing of the commands: repository resolution, token handling and API client setup. The convention
Expand All @@ -25,6 +26,11 @@ private CommandSupport() {}
return repoOption != null ? repoOption.split("/", 2) : parseRemote(gitRemoteUrl());
}

/** The root command instance, which holds the inherited connection options ({@code --repo} &c.). */
static Testlens root(@Nullable CommandSpec spec) {
return (Testlens) requireNonNull(spec).root().userObject();
}

/** Parses owner/repo from a GitHub remote URL. */
static String @Nullable [] parseRemote(@Nullable String url) {
if (url == null) {
Expand Down Expand Up @@ -54,7 +60,7 @@ public static String filterSuffix(@Nullable String branch, @Nullable String work
}

/** Display name of a test, skipping the first display name which denotes the test engine. */
static String testName(List<String> displayNames) {
public static String testName(List<String> displayNames) {
return String.join(" > ", displayNames.subList(Math.min(1, displayNames.size()), displayNames.size()));
}

Expand Down
46 changes: 6 additions & 40 deletions src/main/java/app/testlens/cli/FlakesCommand.java
Original file line number Diff line number Diff line change
Expand Up @@ -3,20 +3,17 @@

import static app.testlens.cli.CommandSupport.apiClient;
import static app.testlens.cli.CommandSupport.filterSuffix;
import static app.testlens.cli.CommandSupport.isInteractiveTerminal;
import static app.testlens.cli.CommandSupport.resolveRepo;
import static app.testlens.cli.util.Console.clearProgress;
import static app.testlens.cli.util.Console.showProgress;
import static app.testlens.cli.util.Console.styled;
import static java.util.Comparator.comparing;
import static java.util.Objects.requireNonNull;

import app.testlens.cli.TestCommand.Mode;
import app.testlens.cli.client.ApiException;
import app.testlens.cli.client.api.TestsApi;
import app.testlens.cli.client.model.FlakeResponse;
import app.testlens.cli.client.model.TestExecutionResponse;
import app.testlens.cli.tui.FlakesTui;
import app.testlens.cli.tui.controller.FlakesController;
import app.testlens.cli.tui.model.TestInfo;
import app.testlens.cli.util.Console;
Expand Down Expand Up @@ -64,41 +61,15 @@ public class FlakesCommand implements Callable<Integer> {
@Nullable
String job;

@Option(
names = "--repo",
description = "Repository as owner/repo (defaults to the GitHub remote 'origin' of the current directory)"
)
@Nullable
String repo;

@Option(
names = "--token",
description = "GitHub access token (defaults to $GITHUB_TOKEN or $GH_TOKEN)",
defaultValue = "${env:GITHUB_TOKEN:-${env:GH_TOKEN}}"
)
@Nullable
String token;

@Option(
names = "--mode",
description = "Output mode: ${COMPLETION-CANDIDATES} (default: ${DEFAULT-VALUE}, uses the TUI in an interactive terminal)",
defaultValue = "auto"
)
Mode mode = Mode.AUTO;

@Option(
names = "--base-url",
description = "API base URL",
defaultValue = "https://api.testlens.app",
hidden = true
)
@Nullable
String baseUrl;

@Override
public Integer call() throws Exception {
var out = requireNonNull(spec).commandLine().getOut();
var err = spec.commandLine().getErr();
var root = CommandSupport.root(spec);
var repo = root.repo;
var token = root.token;
var baseUrl = root.baseUrl;
var mode = root.mode;
if (token == null || token.isBlank()) {
err.println("No GitHub token provided (use --token or set GITHUB_TOKEN)");
return 2;
Expand All @@ -113,18 +84,13 @@ public Integer call() throws Exception {
var ansi = spec.commandLine().getColorScheme().ansi();
var api = new TestsApi(apiClient(token, requireNonNull(baseUrl)));
try {
var tui = mode == Mode.TUI || (mode == Mode.AUTO && isInteractiveTerminal());
showProgress(out, ansi, "Fetching test...");
var test = TestInfo.of(api.getTest(owner, repoName, id));
clearProgress(out, ansi);
showProgress(out, ansi, "Fetching flakes...");
var flakes = fetchFlakes(api, owner, repoName, id, branch, workUnit, job);
clearProgress(out, ansi);
if (tui) {
FlakesTui.run(test, branch, workUnit, job, flakes);
} else {
printFlakes(out, ansi, test, branch, workUnit, job, flakes);
}
printFlakes(out, ansi, test, branch, workUnit, job, flakes);
return 0;
} catch (ApiException e) {
clearProgress(out, ansi);
Expand Down
58 changes: 58 additions & 0 deletions src/main/java/app/testlens/cli/GitHubClient.java
Original file line number Diff line number Diff line change
@@ -0,0 +1,58 @@
// SPDX-License-Identifier: Apache-2.0
package app.testlens.cli;

import java.io.IOException;
import java.net.URI;
import java.net.http.HttpClient;
import java.net.http.HttpRequest;
import java.net.http.HttpResponse.BodyHandlers;
import java.time.Duration;
import java.util.List;
import org.jspecify.annotations.Nullable;

/**
* The minimal GitHub REST client for the TUI's discovery panes: only what the testlens API cannot serve (the list of
* open pull requests). Failures are expected and surfaced as "unavailable" panes, never as errors.
*/
public final class GitHubClient {

/** One open pull request, as shown in the home screen's PR pane. */
public record OpenPullRequest(long number, String title, boolean draft) {}

private static final Duration TIMEOUT = Duration.ofSeconds(10);

private final String baseUrl;
private final @Nullable String token;
private final HttpClient http = HttpClient.newBuilder().connectTimeout(TIMEOUT).build();

public GitHubClient(String baseUrl, @Nullable String token) {
this.baseUrl = baseUrl;
this.token = token;
}

/** The repository's open pull requests, newest first as GitHub returns them. */
public List<OpenPullRequest> openPullRequests(String owner, String repo) throws IOException, InterruptedException {
var uri = baseUrl + "/repos/" + owner + "/" + repo + "/pulls?state=open&per_page=25";
var builder = HttpRequest.newBuilder(URI.create(uri))
.timeout(TIMEOUT)
.header("Accept", "application/vnd.github+json")
.header("X-GitHub-Api-Version", "2022-11-28");
if (token != null && !token.isBlank()) {
builder.header("Authorization", "Bearer " + token);
}
var request = builder.GET().build();
var response = http.send(request, BodyHandlers.ofString());
if (response.statusCode() != 200) {
throw new IOException("GitHub returned HTTP " + response.statusCode());
}
return parsePullRequests(response.body());
}

static List<OpenPullRequest> parsePullRequests(String json) throws IOException {
try {
return List.of(new tools.jackson.databind.json.JsonMapper().readValue(json, OpenPullRequest[].class));
} catch (tools.jackson.core.JacksonException e) {
throw new IOException("Parsing the GitHub pull requests failed", e);
}
}
}
9 changes: 9 additions & 0 deletions src/main/java/app/testlens/cli/Mode.java
Original file line number Diff line number Diff line change
@@ -0,0 +1,9 @@
// SPDX-License-Identifier: Apache-2.0
package app.testlens.cli;

/** Whether a command renders the TUI or prints plain output; exposed via the hidden {@code --mode} escape hatch. */
public enum Mode {
AUTO,
TUI,
CLI,
}
63 changes: 9 additions & 54 deletions src/main/java/app/testlens/cli/PrCommand.java
Original file line number Diff line number Diff line change
@@ -1,7 +1,7 @@
// SPDX-License-Identifier: Apache-2.0
package app.testlens.cli;

import static app.testlens.cli.CommandSupport.isInteractiveTerminal;
import static app.testlens.cli.CommandSupport.apiClient;
import static app.testlens.cli.CommandSupport.resolveRepo;
import static app.testlens.cli.util.Console.clearProgress;
import static app.testlens.cli.util.Console.diffLine;
Expand All @@ -12,14 +12,12 @@
import static java.util.stream.Collectors.groupingBy;
import static java.util.stream.Collectors.toList;

import app.testlens.cli.client.ApiClient;
import app.testlens.cli.client.ApiException;
import app.testlens.cli.client.api.PullRequestsApi;
import app.testlens.cli.client.model.ExecutedTest;
import app.testlens.cli.client.model.Execution;
import app.testlens.cli.client.model.PullRequestResponse;
import app.testlens.cli.client.model.PullRequestTestsResponse;
import app.testlens.cli.tui.PrTui;
import app.testlens.cli.util.Console;
import app.testlens.cli.util.TextDiff;
import app.testlens.cli.util.TimeFormat;
Expand Down Expand Up @@ -52,46 +50,19 @@ public static boolean isStackFrame(String line) {
@Parameters(description = "Pull request number", arity = "1")
int number;

@Option(
names = "--repo",
description = "Repository as owner/repo (defaults to the GitHub remote 'origin' of the current directory)"
)
@Nullable
String repo;

@Option(
names = "--token",
description = "GitHub access token (defaults to $GITHUB_TOKEN or $GH_TOKEN)",
defaultValue = "${env:GITHUB_TOKEN:-${env:GH_TOKEN}}"
)
@Nullable
String token;

@Option(names = "--sha", description = "Commit sha to show the tests of (defaults to the head of the pull request)")
@Nullable
String sha;

@Option(
names = "--mode",
description = "Output mode: ${COMPLETION-CANDIDATES} (default: ${DEFAULT-VALUE}, uses the TUI in an interactive terminal)",
defaultValue = "auto"
)
Mode mode = Mode.AUTO;

@Option(
names = "--base-url",
description = "API base URL",
defaultValue = "https://api.testlens.app",
hidden = true
)
@Nullable
String baseUrl;

@Override
public Integer call() throws Exception {
var commandLine = requireNonNull(spec).commandLine();
var out = commandLine.getOut();
var err = commandLine.getErr();
var root = CommandSupport.root(spec);
var repo = root.repo;
var token = root.token;
var baseUrl = root.baseUrl;
if (token == null || token.isBlank()) {
err.println("No GitHub token provided (use --token or set GITHUB_TOKEN)");
return 2;
Expand All @@ -101,30 +72,20 @@ public Integer call() throws Exception {
err.println("Cannot determine repository (use --repo owner/repo)");
return 2;
}
var apiClient = new ApiClient();
apiClient.updateBaseUri(requireNonNull(baseUrl));
apiClient.setRequestInterceptor(request -> request.header("Authorization", "Bearer " + token));
var api = new PullRequestsApi(apiClient);
var api = new PullRequestsApi(apiClient(token, requireNonNull(baseUrl)));
var ansi = commandLine.getColorScheme().ansi();
try {
var tui = mode == Mode.TUI || (mode == Mode.AUTO && isInteractiveTerminal());
showProgress(out, ansi, "Fetching pull request...");
var pr = api.getPullRequest(ownerAndRepo[0], ownerAndRepo[1], number);
clearProgress(out, ansi);
var prUrl = "https://github.com/" + ownerAndRepo[0] + "/" + ownerAndRepo[1] + "/pull/" + pr.getNumber();
if (!tui) {
printPullRequest(out, ansi, pr, prUrl);
out.println();
}
printPullRequest(out, ansi, pr, prUrl);
out.println();
showProgress(out, ansi, "Fetching tests...");
var tests =
api.getPullRequestTests(ownerAndRepo[0], ownerAndRepo[1], number, sha != null ? sha : pr.getHeadSha());
clearProgress(out, ansi);
if (tui) {
PrTui.run(pr, tests);
} else {
printTests(out, ansi, tests);
}
printTests(out, ansi, tests);
return 0;
} catch (ApiException e) {
clearProgress(out, ansi);
Expand All @@ -139,12 +100,6 @@ public Integer call() throws Exception {
}
}

enum Mode {
AUTO,
TUI,
CLI
}

static String testName(ExecutedTest test) {
// skip the first display name which denotes the test engine, like in the PR comment
var displayNames = test.getDisplayNames();
Expand Down
Loading
Loading