Skip to content

Commit dcce429

Browse files
committed
Refactor: use var for local variable type inference
Apply Java var (local variable type inference) across the codebase where the type is obvious from the right-hand side expression: - Constructor calls: Type x = new Type() -> var x = new Type() - Diamond operator fill: List<X> x = new ArrayList<>() -> var x = new ArrayList<X>() - Cast expressions: Type x = (Type) expr -> var x = (Type) expr Modified 3 main source files and 14 test files (17 files total).
1 parent e90b3f9 commit dcce429

17 files changed

Lines changed: 148 additions & 162 deletions

src/main/java/com/github/copilot/sdk/CopilotClient.java

Lines changed: 20 additions & 24 deletions
Original file line numberDiff line numberDiff line change
@@ -281,14 +281,13 @@ private void handleToolCall(JsonRpcClient rpc, String requestId, JsonNode params
281281

282282
ToolDefinition tool = session.getTool(toolName);
283283
if (tool == null || tool.getHandler() == null) {
284-
ToolResultObject result = new ToolResultObject()
285-
.setTextResultForLlm("Tool '" + toolName + "' is not supported.").setResultType("failure")
286-
.setError("tool '" + toolName + "' not supported");
284+
var result = new ToolResultObject().setTextResultForLlm("Tool '" + toolName + "' is not supported.")
285+
.setResultType("failure").setError("tool '" + toolName + "' not supported");
287286
rpc.sendResponse(Long.parseLong(requestId), Map.of("result", result));
288287
return;
289288
}
290289

291-
ToolInvocation invocation = new ToolInvocation().setSessionId(sessionId).setToolCallId(toolCallId)
290+
var invocation = new ToolInvocation().setSessionId(sessionId).setToolCallId(toolCallId)
292291
.setToolName(toolName).setArguments(arguments);
293292

294293
tool.getHandler().invoke(invocation).thenAccept(result -> {
@@ -306,7 +305,7 @@ private void handleToolCall(JsonRpcClient rpc, String requestId, JsonNode params
306305
}
307306
}).exceptionally(ex -> {
308307
try {
309-
ToolResultObject result = new ToolResultObject()
308+
var result = new ToolResultObject()
310309
.setTextResultForLlm(
311310
"Invoking this tool produced an error. Detailed information is not available.")
312311
.setResultType("failure").setError(ex.getMessage());
@@ -335,7 +334,7 @@ private void handlePermissionRequest(JsonRpcClient rpc, String requestId, JsonNo
335334

336335
CopilotSession session = sessions.get(sessionId);
337336
if (session == null) {
338-
PermissionRequestResult result = new PermissionRequestResult()
337+
var result = new PermissionRequestResult()
339338
.setKind("denied-no-approval-rule-and-could-not-request-from-user");
340339
rpc.sendResponse(Long.parseLong(requestId), Map.of("result", result));
341340
return;
@@ -349,7 +348,7 @@ private void handlePermissionRequest(JsonRpcClient rpc, String requestId, JsonNo
349348
}
350349
}).exceptionally(ex -> {
351350
try {
352-
PermissionRequestResult result = new PermissionRequestResult()
351+
var result = new PermissionRequestResult()
353352
.setKind("denied-no-approval-rule-and-could-not-request-from-user");
354353
rpc.sendResponse(Long.parseLong(requestId), Map.of("result", result));
355354
} catch (IOException e) {
@@ -381,10 +380,9 @@ private void handleUserInputRequest(JsonRpcClient rpc, String requestId, JsonNod
381380
return;
382381
}
383382

384-
com.github.copilot.sdk.json.UserInputRequest request = new com.github.copilot.sdk.json.UserInputRequest()
385-
.setQuestion(question);
383+
var request = new com.github.copilot.sdk.json.UserInputRequest().setQuestion(question);
386384
if (choicesNode != null && choicesNode.isArray()) {
387-
List<String> choices = new ArrayList<>();
385+
var choices = new ArrayList<String>();
388386
for (JsonNode choice : choicesNode) {
389387
choices.add(choice.asText());
390388
}
@@ -461,7 +459,7 @@ private void handleHooksInvoke(JsonRpcClient rpc, String requestId, JsonNode par
461459

462460
private void verifyProtocolVersion(Connection connection) throws Exception {
463461
int expectedVersion = SdkProtocolVersion.get();
464-
Map<String, Object> params = new HashMap<>();
462+
var params = new HashMap<String, Object>();
465463
params.put("message", null);
466464
PingResponse pingResponse = connection.rpc.invoke("ping", params, PingResponse.class).get(30, TimeUnit.SECONDS);
467465

@@ -484,7 +482,7 @@ private void verifyProtocolVersion(Connection connection) throws Exception {
484482
* @return A future that completes when the client is stopped
485483
*/
486484
public CompletableFuture<Void> stop() {
487-
List<CompletableFuture<Void>> closeFutures = new ArrayList<>();
485+
var closeFutures = new ArrayList<CompletableFuture<Void>>();
488486

489487
for (CopilotSession session : new ArrayList<>(sessions.values())) {
490488
closeFutures.add(CompletableFuture.runAsync(() -> {
@@ -555,7 +553,7 @@ private CompletableFuture<Void> cleanupConnection() {
555553
*/
556554
public CompletableFuture<CopilotSession> createSession(SessionConfig config) {
557555
return ensureConnected().thenCompose(connection -> {
558-
CreateSessionRequest request = new CreateSessionRequest();
556+
var request = new CreateSessionRequest();
559557
if (config != null) {
560558
request.setModel(config.getModel());
561559
request.setSessionId(config.getSessionId());
@@ -585,8 +583,7 @@ public CompletableFuture<CopilotSession> createSession(SessionConfig config) {
585583
}
586584

587585
return connection.rpc.invoke("session.create", request, CreateSessionResponse.class).thenApply(response -> {
588-
CopilotSession session = new CopilotSession(response.getSessionId(), connection.rpc,
589-
response.getWorkspacePath());
586+
var session = new CopilotSession(response.getSessionId(), connection.rpc, response.getWorkspacePath());
590587
if (config != null && config.getTools() != null) {
591588
session.registerTools(config.getTools());
592589
}
@@ -632,7 +629,7 @@ public CompletableFuture<CopilotSession> createSession() {
632629
*/
633630
public CompletableFuture<CopilotSession> resumeSession(String sessionId, ResumeSessionConfig config) {
634631
return ensureConnected().thenCompose(connection -> {
635-
ResumeSessionRequest request = new ResumeSessionRequest();
632+
var request = new ResumeSessionRequest();
636633
request.setSessionId(sessionId);
637634
if (config != null) {
638635
request.setReasoningEffort(config.getReasoningEffort());
@@ -655,8 +652,7 @@ public CompletableFuture<CopilotSession> resumeSession(String sessionId, ResumeS
655652
}
656653

657654
return connection.rpc.invoke("session.resume", request, ResumeSessionResponse.class).thenApply(response -> {
658-
CopilotSession session = new CopilotSession(response.getSessionId(), connection.rpc,
659-
response.getWorkspacePath());
655+
var session = new CopilotSession(response.getSessionId(), connection.rpc, response.getWorkspacePath());
660656
if (config != null && config.getTools() != null) {
661657
session.registerTools(config.getTools());
662658
}
@@ -960,7 +956,7 @@ private CompletableFuture<Connection> ensureConnected() {
960956

961957
private ProcessInfo startCliServer() throws IOException, InterruptedException {
962958
String cliPath = options.getCliPath() != null ? options.getCliPath() : "copilot";
963-
List<String> args = new ArrayList<>();
959+
var args = new ArrayList<String>();
964960

965961
if (options.getCliArgs() != null) {
966962
args.addAll(Arrays.asList(options.getCliArgs()));
@@ -993,7 +989,7 @@ private ProcessInfo startCliServer() throws IOException, InterruptedException {
993989

994990
List<String> command = resolveCliCommand(cliPath, args);
995991

996-
ProcessBuilder pb = new ProcessBuilder(command);
992+
var pb = new ProcessBuilder(command);
997993
pb.redirectErrorStream(false);
998994

999995
if (options.getCwd() != null) {
@@ -1014,7 +1010,7 @@ private ProcessInfo startCliServer() throws IOException, InterruptedException {
10141010
Process process = pb.start();
10151011

10161012
// Forward stderr to logger in background
1017-
Thread stderrThread = new Thread(() -> {
1013+
var stderrThread = new Thread(() -> {
10181014
try (BufferedReader reader = new BufferedReader(
10191015
new InputStreamReader(process.getErrorStream(), StandardCharsets.UTF_8))) {
10201016
String line;
@@ -1063,7 +1059,7 @@ private List<String> resolveCliCommand(String cliPath, List<String> args) {
10631059
boolean isJsFile = cliPath.toLowerCase().endsWith(".js");
10641060

10651061
if (isJsFile) {
1066-
List<String> result = new ArrayList<>();
1062+
var result = new ArrayList<String>();
10671063
result.add("node");
10681064
result.add(cliPath);
10691065
result.addAll(args);
@@ -1073,15 +1069,15 @@ private List<String> resolveCliCommand(String cliPath, List<String> args) {
10731069
// On Windows, use cmd /c to resolve the executable
10741070
String os = System.getProperty("os.name").toLowerCase();
10751071
if (os.contains("win") && !new File(cliPath).isAbsolute()) {
1076-
List<String> result = new ArrayList<>();
1072+
var result = new ArrayList<String>();
10771073
result.add("cmd");
10781074
result.add("/c");
10791075
result.add(cliPath);
10801076
result.addAll(args);
10811077
return result;
10821078
}
10831079

1084-
List<String> result = new ArrayList<>();
1080+
var result = new ArrayList<String>();
10851081
result.add(cliPath);
10861082
result.addAll(args);
10871083
return result;

src/main/java/com/github/copilot/sdk/CopilotSession.java

Lines changed: 9 additions & 10 deletions
Original file line numberDiff line numberDiff line change
@@ -13,7 +13,6 @@
1313
import java.util.concurrent.CompletableFuture;
1414
import java.util.concurrent.ConcurrentHashMap;
1515
import java.util.concurrent.Executors;
16-
import java.util.concurrent.ScheduledExecutorService;
1716
import java.util.concurrent.TimeUnit;
1817
import java.util.concurrent.TimeoutException;
1918
import java.util.concurrent.atomic.AtomicReference;
@@ -196,7 +195,7 @@ public CompletableFuture<AssistantMessageEvent> sendAndWait(String prompt) {
196195
* @see #send(String)
197196
*/
198197
public CompletableFuture<String> send(MessageOptions options) {
199-
SendMessageRequest request = new SendMessageRequest();
198+
var request = new SendMessageRequest();
200199
request.setSessionId(sessionId);
201200
request.setPrompt(options.getPrompt());
202201
request.setAttachments(options.getAttachments());
@@ -225,8 +224,8 @@ public CompletableFuture<String> send(MessageOptions options) {
225224
* @see #send(MessageOptions)
226225
*/
227226
public CompletableFuture<AssistantMessageEvent> sendAndWait(MessageOptions options, long timeoutMs) {
228-
CompletableFuture<AssistantMessageEvent> future = new CompletableFuture<>();
229-
AtomicReference<AssistantMessageEvent> lastAssistantMessage = new AtomicReference<>();
227+
var future = new CompletableFuture<AssistantMessageEvent>();
228+
var lastAssistantMessage = new AtomicReference<AssistantMessageEvent>();
230229

231230
Consumer<AbstractSessionEvent> handler = evt -> {
232231
if (evt instanceof AssistantMessageEvent msg) {
@@ -252,8 +251,8 @@ public CompletableFuture<AssistantMessageEvent> sendAndWait(MessageOptions optio
252251
});
253252

254253
// Set up timeout with daemon thread so it doesn't prevent JVM exit
255-
ScheduledExecutorService scheduler = Executors.newSingleThreadScheduledExecutor(r -> {
256-
Thread t = new Thread(r, "sendAndWait-timeout");
254+
var scheduler = Executors.newSingleThreadScheduledExecutor(r -> {
255+
var t = new Thread(r, "sendAndWait-timeout");
257256
t.setDaemon(true);
258257
return t;
259258
});
@@ -444,7 +443,7 @@ CompletableFuture<PermissionRequestResult> handlePermissionRequest(JsonNode perm
444443

445444
try {
446445
PermissionRequest request = MAPPER.treeToValue(permissionRequestData, PermissionRequest.class);
447-
PermissionInvocation invocation = new PermissionInvocation();
446+
var invocation = new PermissionInvocation();
448447
invocation.setSessionId(sessionId);
449448
return handler.handle(request, invocation).exceptionally(ex -> {
450449
LOG.log(Level.SEVERE, "Permission handler threw an exception", ex);
@@ -489,7 +488,7 @@ CompletableFuture<UserInputResponse> handleUserInputRequest(UserInputRequest req
489488
}
490489

491490
try {
492-
UserInputInvocation invocation = new UserInputInvocation().setSessionId(sessionId);
491+
var invocation = new UserInputInvocation().setSessionId(sessionId);
493492
return handler.handle(request, invocation).exceptionally(ex -> {
494493
LOG.log(Level.SEVERE, "User input handler threw an exception", ex);
495494
throw new RuntimeException("User input handler error", ex);
@@ -529,7 +528,7 @@ CompletableFuture<Object> handleHooksInvoke(String hookType, JsonNode input) {
529528
return CompletableFuture.completedFuture(null);
530529
}
531530

532-
HookInvocation invocation = new HookInvocation().setSessionId(sessionId);
531+
var invocation = new HookInvocation().setSessionId(sessionId);
533532

534533
try {
535534
switch (hookType) {
@@ -592,7 +591,7 @@ CompletableFuture<Object> handleHooksInvoke(String hookType, JsonNode input) {
592591
public CompletableFuture<List<AbstractSessionEvent>> getMessages() {
593592
return rpc.invoke("session.getMessages", Map.of("sessionId", sessionId), GetMessagesResponse.class)
594593
.thenApply(response -> {
595-
List<AbstractSessionEvent> events = new ArrayList<>();
594+
var events = new ArrayList<AbstractSessionEvent>();
596595
if (response.getEvents() != null) {
597596
for (JsonNode eventNode : response.getEvents()) {
598597
try {

src/main/java/com/github/copilot/sdk/JsonRpcClient.java

Lines changed: 9 additions & 9 deletions
Original file line numberDiff line numberDiff line change
@@ -66,7 +66,7 @@ private JsonRpcClient(InputStream inputStream, OutputStream outputStream, Socket
6666
}
6767

6868
static ObjectMapper createObjectMapper() {
69-
ObjectMapper mapper = new ObjectMapper();
69+
var mapper = new ObjectMapper();
7070
mapper.registerModule(new JavaTimeModule());
7171
mapper.configure(DeserializationFeature.FAIL_ON_UNKNOWN_PROPERTIES, false);
7272
mapper.configure(SerializationFeature.WRITE_DATES_AS_TIMESTAMPS, false);
@@ -105,10 +105,10 @@ public void registerMethodHandler(String method, BiConsumer<String, JsonNode> ha
105105
*/
106106
public <T> CompletableFuture<T> invoke(String method, Object params, Class<T> responseType) {
107107
long id = requestIdCounter.incrementAndGet();
108-
CompletableFuture<JsonNode> future = new CompletableFuture<>();
108+
var future = new CompletableFuture<JsonNode>();
109109
pendingRequests.put(id, future);
110110

111-
JsonRpcRequest request = new JsonRpcRequest();
111+
var request = new JsonRpcRequest();
112112
request.setJsonrpc("2.0");
113113
request.setId(id);
114114
request.setMethod(method);
@@ -137,7 +137,7 @@ public <T> CompletableFuture<T> invoke(String method, Object params, Class<T> re
137137
* Sends a JSON-RPC notification (no response expected).
138138
*/
139139
public void notify(String method, Object params) throws IOException {
140-
JsonRpcRequest notification = new JsonRpcRequest();
140+
var notification = new JsonRpcRequest();
141141
notification.setJsonrpc("2.0");
142142
notification.setMethod(method);
143143
notification.setParams(params);
@@ -148,7 +148,7 @@ public void notify(String method, Object params) throws IOException {
148148
* Sends a JSON-RPC response to a server request.
149149
*/
150150
public void sendResponse(Object id, Object result) throws IOException {
151-
JsonRpcResponse response = new JsonRpcResponse();
151+
var response = new JsonRpcResponse();
152152
response.setJsonrpc("2.0");
153153
response.setId(id);
154154
response.setResult(result);
@@ -159,10 +159,10 @@ public void sendResponse(Object id, Object result) throws IOException {
159159
* Sends a JSON-RPC error response to a server request.
160160
*/
161161
public void sendErrorResponse(Object id, int code, String message) throws IOException {
162-
JsonRpcResponse response = new JsonRpcResponse();
162+
var response = new JsonRpcResponse();
163163
response.setJsonrpc("2.0");
164164
response.setId(id);
165-
JsonRpcError error = new JsonRpcError();
165+
var error = new JsonRpcError();
166166
error.setCode(code);
167167
error.setMessage(message);
168168
response.setError(error);
@@ -186,12 +186,12 @@ private void startReader() {
186186
try {
187187
// We need to read bytes because Content-Length specifies bytes, not characters.
188188
// Using BufferedReader would cause issues with multi-byte UTF-8 characters.
189-
BufferedInputStream bis = new BufferedInputStream(inputStream);
189+
var bis = new BufferedInputStream(inputStream);
190190

191191
while (running) {
192192
// Read headers line by line
193193
int contentLength = -1;
194-
StringBuilder headerLine = new StringBuilder();
194+
var headerLine = new StringBuilder();
195195
boolean lastWasCR = false;
196196
boolean inHeaders = true;
197197

src/test/java/com/github/copilot/sdk/AskUserTest.java

Lines changed: 6 additions & 7 deletions
Original file line numberDiff line numberDiff line change
@@ -7,7 +7,6 @@
77
import static org.junit.jupiter.api.Assertions.*;
88

99
import java.util.ArrayList;
10-
import java.util.List;
1110
import java.util.concurrent.CompletableFuture;
1211
import java.util.concurrent.TimeUnit;
1312

@@ -54,10 +53,10 @@ static void teardown() throws Exception {
5453
void testShouldInvokeUserInputHandlerWhenModelUsesAskUserTool() throws Exception {
5554
ctx.configureForTest("ask_user", "should_invoke_user_input_handler_when_model_uses_ask_user_tool");
5655

57-
List<UserInputRequest> userInputRequests = new ArrayList<>();
56+
var userInputRequests = new ArrayList<UserInputRequest>();
5857
final String[] sessionIdHolder = new String[1];
5958

60-
SessionConfig config = new SessionConfig().setOnUserInputRequest((request, invocation) -> {
59+
var config = new SessionConfig().setOnUserInputRequest((request, invocation) -> {
6160
userInputRequests.add(request);
6261
assertEquals(sessionIdHolder[0], invocation.getSessionId());
6362

@@ -97,9 +96,9 @@ void testShouldInvokeUserInputHandlerWhenModelUsesAskUserTool() throws Exception
9796
void testShouldReceiveChoicesInUserInputRequest() throws Exception {
9897
ctx.configureForTest("ask_user", "should_receive_choices_in_user_input_request");
9998

100-
List<UserInputRequest> userInputRequests = new ArrayList<>();
99+
var userInputRequests = new ArrayList<UserInputRequest>();
101100

102-
SessionConfig config = new SessionConfig().setOnUserInputRequest((request, invocation) -> {
101+
var config = new SessionConfig().setOnUserInputRequest((request, invocation) -> {
103102
userInputRequests.add(request);
104103

105104
// Pick the first choice
@@ -135,10 +134,10 @@ void testShouldReceiveChoicesInUserInputRequest() throws Exception {
135134
void testShouldHandleFreeformUserInputResponse() throws Exception {
136135
ctx.configureForTest("ask_user", "should_handle_freeform_user_input_response");
137136

138-
final List<UserInputRequest> userInputRequests = new ArrayList<>();
137+
final var userInputRequests = new ArrayList<UserInputRequest>();
139138
String freeformAnswer = "This is my custom freeform answer that was not in the choices";
140139

141-
SessionConfig config = new SessionConfig().setOnUserInputRequest((request, invocation) -> {
140+
var config = new SessionConfig().setOnUserInputRequest((request, invocation) -> {
142141
userInputRequests.add(request);
143142

144143
// Return a freeform answer (not from choices)

src/test/java/com/github/copilot/sdk/CapiProxy.java

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -89,7 +89,7 @@ public String start() throws IOException, InterruptedException {
8989
}
9090

9191
// Start the harness server using npx tsx
92-
ProcessBuilder pb = new ProcessBuilder("npx", "tsx", "server.ts");
92+
var pb = new ProcessBuilder("npx", "tsx", "server.ts");
9393
pb.directory(harnessDir.toFile());
9494
pb.redirectErrorStream(false);
9595

0 commit comments

Comments
 (0)