chore: Improve code (#442)

* chore: Improve code

* Convert classes to records
This commit is contained in:
Rene Leonhardt 2024-04-10 13:47:38 +02:00 committed by GitHub
parent c29d3928db
commit 7d89650062
No known key found for this signature in database
GPG key ID: B5690EEEBB952194
86 changed files with 528 additions and 976 deletions

View file

@ -12,10 +12,6 @@ public class CodeGPTBundle extends DynamicBundle {
super("messages.codegpt");
}
public static String get(@NotNull @PropertyKey(resourceBundle = "messages.codegpt") String key) {
return INSTANCE.getMessage(key);
}
public static String get(
@NotNull @PropertyKey(resourceBundle = "messages.codegpt") String key,
Object... params) {

View file

@ -9,11 +9,13 @@ import com.knuddels.jtokkit.api.EncodingRegistry;
import com.knuddels.jtokkit.api.EncodingType;
import com.knuddels.jtokkit.api.IntArrayList;
import ee.carlrobert.codegpt.conversations.Conversation;
import ee.carlrobert.codegpt.conversations.message.Message;
import ee.carlrobert.llm.client.openai.completion.request.OpenAIChatCompletionDetailedMessage;
import ee.carlrobert.llm.client.openai.completion.request.OpenAIChatCompletionMessage;
import ee.carlrobert.llm.client.openai.completion.request.OpenAIChatCompletionStandardMessage;
import ee.carlrobert.llm.client.openai.completion.request.OpenAIMessageTextContent;
import java.util.List;
import java.util.stream.Stream;
@Service
public final class EncodingManager {
@ -31,13 +33,10 @@ public final class EncodingManager {
}
public int countConversationTokens(Conversation conversation) {
if (conversation != null) {
return conversation.getMessages().stream()
.mapToInt(
message -> countTokens(message.getPrompt()) + countTokens(message.getResponse()))
.sum();
}
return 0;
return (conversation == null ? Stream.<Message>empty() : conversation.getMessages().stream())
.mapToInt(
message -> countTokens(message.getPrompt()) + countTokens(message.getResponse()))
.sum();
}
public int countMessageTokens(OpenAIChatCompletionMessage message) {
@ -46,11 +45,11 @@ public final class EncodingManager {
}
return ((OpenAIChatCompletionDetailedMessage) message).getContent().stream()
.filter(it -> it instanceof OpenAIMessageTextContent)
.map(it -> countMessageTokens(
.filter(OpenAIMessageTextContent.class::isInstance)
.mapToInt(it -> countMessageTokens(
((OpenAIChatCompletionDetailedMessage) message).getRole(),
((OpenAIMessageTextContent) it).getText()))
.reduce(0, Integer::sum);
.sum();
}
public int countMessageTokens(String role, String content) {
@ -86,9 +85,7 @@ public final class EncodingManager {
private IntArrayList convertToIntArrayList(List<Integer> tokens) {
var result = new IntArrayList(tokens.size());
for (var integer : tokens) {
result.add(integer);
}
tokens.forEach(result::add);
return result;
}
}

View file

@ -3,7 +3,6 @@ package ee.carlrobert.codegpt;
import static ee.carlrobert.codegpt.completions.ConversationType.FIX_COMPILE_ERRORS;
import static java.lang.String.format;
import static java.util.stream.Collectors.joining;
import static java.util.stream.Collectors.toList;
import com.intellij.compiler.CompilerMessageImpl;
import com.intellij.notification.NotificationAction;
@ -68,7 +67,7 @@ public class ProjectCompilationStatusListener implements CompilationStatusListen
var message = new Message("Fix the following compile errors:\n\n" + prompt);
message.setReferencedFilePaths(errorMapping.keySet().stream()
.map(ReferencedFile::getFilePath)
.collect(toList()));
.toList());
message.setUserMessage(message.getPrompt());
message.setPrompt(CompletionRequestProvider.getPromptWithContext(
new ArrayList<>(errorMapping.keySet()),
@ -91,12 +90,12 @@ public class ProjectCompilationStatusListener implements CompilationStatusListen
}
private String getCompilerErrorDetails(CompilerMessage compilerMessage) {
if (compilerMessage instanceof CompilerMessageImpl) {
if (compilerMessage instanceof CompilerMessageImpl compilerMessageImpl) {
return format(
"%s:%d:%d - `%s`",
compilerMessage.getVirtualFile().getName(),
((CompilerMessageImpl) compilerMessage).getLine(),
((CompilerMessageImpl) compilerMessage).getColumn(),
compilerMessageImpl.getLine(),
compilerMessageImpl.getColumn(),
compilerMessage.getMessage());
}
return format(
@ -104,4 +103,4 @@ public class ProjectCompilationStatusListener implements CompilationStatusListen
compilerMessage.getVirtualFile().getName(),
compilerMessage.getMessage());
}
}
}

View file

@ -19,7 +19,9 @@ import com.intellij.openapi.editor.ex.EditorEx;
import com.intellij.openapi.project.Project;
import com.intellij.openapi.vcs.FilePath;
import com.intellij.openapi.vcs.VcsDataKeys;
import com.intellij.openapi.vcs.changes.Change;
import com.intellij.openapi.vcs.ui.CommitMessage;
import com.intellij.openapi.vfs.VirtualFile;
import com.intellij.vcs.commit.CommitWorkflowUi;
import ee.carlrobert.codegpt.CodeGPTBundle;
import ee.carlrobert.codegpt.EncodingManager;
@ -35,12 +37,11 @@ import java.io.IOException;
import java.io.InputStreamReader;
import java.nio.file.Files;
import java.nio.file.Path;
import java.util.AbstractMap;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;
import java.util.Objects;
import java.util.Optional;
import java.util.stream.Stream;
import okhttp3.sse.EventSource;
import org.jetbrains.annotations.NotNull;
@ -144,12 +145,13 @@ public class GenerateGitCommitMessageAction extends AnAction {
var newFilesContent =
getNewFilesDiff(projectBasePath, changes.getIncludedUnversionedFilePaths());
return Stream.of(
new AbstractMap.SimpleEntry<>("Git diff", gitDiff),
new AbstractMap.SimpleEntry<>("Staged git diff", stagedGitDiff),
new AbstractMap.SimpleEntry<>("New files", newFilesContent))
return Map.of(
"Git diff", gitDiff,
"Staged git diff", stagedGitDiff,
"New files", newFilesContent)
.entrySet().stream()
.filter(entry -> !entry.getValue().isEmpty())
.map(entry -> "%s:\n%s".formatted(entry.getKey(), entry.getValue()))
.map(entry -> "%s:%n%s".formatted(entry.getKey(), entry.getValue()))
.collect(joining("\n\n"));
}
@ -204,8 +206,9 @@ public class GenerateGitCommitMessageAction extends AnAction {
CommitWorkflowChanges(CommitWorkflowUi commitWorkflowUi) {
includedVersionedFilePaths = commitWorkflowUi.getIncludedChanges().stream()
.map(it -> it.getVirtualFile() == null ? null : it.getVirtualFile().getPath())
.map(Change::getVirtualFile)
.filter(Objects::nonNull)
.map(VirtualFile::getPath)
.toList();
includedUnversionedFilePaths = commitWorkflowUi.getIncludedUnversionedFiles().stream()
.map(FilePath::getPath)

View file

@ -137,8 +137,8 @@ public class IncludeFilesInContextAction extends AnAction {
private @Nullable String getNodeFileContent(CheckedTreeNode checkedNode) {
var userObject = checkedNode.getUserObject();
if (userObject instanceof PsiElement) {
var psiFile = ((PsiElement) userObject).getContainingFile();
if (userObject instanceof PsiElement psiElement) {
var psiFile = psiElement.getContainingFile();
if (psiFile != null) {
var virtualFile = psiFile.getVirtualFile();
if (virtualFile != null) {
@ -146,8 +146,8 @@ public class IncludeFilesInContextAction extends AnAction {
}
}
}
if (userObject instanceof VirtualFile) {
return getVirtualFileContent((VirtualFile) userObject);
if (userObject instanceof VirtualFile virtualFile) {
return getVirtualFileContent(virtualFile);
}
return null;
}
@ -235,4 +235,4 @@ public class IncludeFilesInContextAction extends AnAction {
});
return restoreButton;
}
}
}

View file

@ -33,13 +33,12 @@ public class CustomPromptAction extends BaseEditorAction {
@Override
protected void actionPerformed(Project project, Editor editor, String selectedText) {
if (selectedText != null && !selectedText.isEmpty()) {
var fileExtension =
FileUtil.getFileExtension(((EditorImpl) editor).getVirtualFile().getName());
var fileExtension = FileUtil.getFileExtension(editor.getVirtualFile().getName());
var dialog = new CustomPromptDialog(previousUserPrompt);
if (dialog.showAndGet()) {
previousUserPrompt = dialog.getUserPrompt();
var message = new Message(
format("%s\n```%s\n%s\n```", previousUserPrompt, fileExtension, selectedText));
format("%s%n```%s%n%s%n```", previousUserPrompt, fileExtension, selectedText));
message.setUserMessage(previousUserPrompt);
SwingUtilities.invokeLater(() ->
project.getService(ChatToolWindowContentManager.class).sendMessage(message));
@ -91,4 +90,4 @@ public class CustomPromptAction extends BaseEditorAction {
return userPromptTextArea.getText();
}
}
}
}

View file

@ -1,7 +1,6 @@
package ee.carlrobert.codegpt.actions.editor;
import static java.lang.String.format;
import static java.util.stream.Collectors.toList;
import com.intellij.openapi.actionSystem.ActionManager;
import com.intellij.openapi.actionSystem.AnAction;
@ -24,7 +23,7 @@ import org.apache.commons.text.CaseUtils;
public class EditorActionsUtil {
public static Map<String, String> DEFAULT_ACTIONS = new LinkedHashMap<>(Map.of(
public static final Map<String, String> DEFAULT_ACTIONS = new LinkedHashMap<>(Map.of(
"Find Bugs", "Find bugs and output code with bugs "
+ "fixed in the following code: {{selectedCode}}",
"Write Tests", "Write Tests for the selected code {{selectedCode}}",
@ -32,14 +31,13 @@ public class EditorActionsUtil {
"Refactor", "Refactor the selected code {{selectedCode}}",
"Optimize", "Optimize the selected code {{selectedCode}}"));
public static String[][] DEFAULT_ACTIONS_ARRAY = toArray(DEFAULT_ACTIONS);
public static final String[][] DEFAULT_ACTIONS_ARRAY = toArray(DEFAULT_ACTIONS);
public static String[][] toArray(Map<String, String> actionsMap) {
return actionsMap.entrySet()
.stream()
.map((entry) -> new String[]{entry.getKey(), entry.getValue()})
.toList()
.toArray(new String[0][0]);
.map(entry -> new String[]{entry.getKey(), entry.getValue()})
.toArray(String[][]::new);
}
public static void refreshActions() {
@ -58,11 +56,10 @@ public class EditorActionsUtil {
var action = new BaseEditorAction(label, label) {
@Override
protected void actionPerformed(Project project, Editor editor, String selectedText) {
var fileExtension = FileUtil.getFileExtension(
((EditorImpl) editor).getVirtualFile().getName());
var fileExtension = FileUtil.getFileExtension(editor.getVirtualFile().getName());
var message = new Message(prompt.replace(
"{{selectedCode}}",
format("\n```%s\n%s\n```", fileExtension, selectedText)));
format("%n```%s%n%s%n```", fileExtension, selectedText)));
message.setUserMessage(prompt.replace("{{selectedCode}}", ""));
var toolWindowContentManager =
project.getService(ChatToolWindowContentManager.class);
@ -72,7 +69,7 @@ public class EditorActionsUtil {
Stream.ofNullable(project.getUserData(CodeGPTKeys.SELECTED_FILES))
.flatMap(Collection::stream)
.map(ReferencedFile::getFilePath)
.collect(toList()));
.toList());
toolWindowContentManager.sendMessage(message);
}
};

View file

@ -46,7 +46,7 @@ public class OpenInEditorAction extends AnAction {
var fileContent = currentConversation
.getMessages()
.stream()
.map(it -> format("### User:\n%s\n### CodeGPT:\n%s\n", it.getPrompt(),
.map(it -> format("### User:%n%s%n### CodeGPT:%n%s%n", it.getPrompt(),
it.getResponse()))
.collect(Collectors.joining());
VirtualFile file = new LightVirtualFile(fileName, fileContent);

View file

@ -44,11 +44,11 @@ public class CallParameters {
return retry;
}
public String getImageMediaType() {
public @Nullable String getImageMediaType() {
return imageMediaType;
}
public void setImageMediaType(String imageMediaType) {
public void setImageMediaType(@Nullable String imageMediaType) {
this.imageMediaType = imageMediaType;
}

View file

@ -68,9 +68,9 @@ public class CompletionClientProvider {
var accessToken = "";
var youUserManager = YouUserManager.getInstance();
if (youUserManager.isAuthenticated()) {
var authenticationResponse = youUserManager.getAuthenticationResponse().getData();
sessionId = authenticationResponse.getSession().getSessionId();
accessToken = authenticationResponse.getSessionJwt();
var authenticationResponse = youUserManager.getAuthenticationResponse().data();
sessionId = authenticationResponse.session().sessionId();
accessToken = authenticationResponse.sessionJwt();
}
return new YouClient.Builder(sessionId, accessToken)
@ -116,5 +116,3 @@ public class CompletionClientProvider {
.readTimeout(advancedSettings.getReadTimeout(), TimeUnit.SECONDS);
}
}

View file

@ -1,6 +1,5 @@
package ee.carlrobert.codegpt.completions;
import com.intellij.openapi.diagnostic.Logger;
import ee.carlrobert.codegpt.settings.GeneralSettings;
import ee.carlrobert.codegpt.settings.GeneralSettingsState;
import ee.carlrobert.codegpt.telemetry.TelemetryAction;
@ -14,8 +13,6 @@ import okhttp3.sse.EventSource;
public class CompletionRequestHandler {
private static final Logger LOG = Logger.getInstance(CompletionRequestHandler.class);
private final StringBuilder messageBuilder = new StringBuilder();
private final CompletionResponseEventListener completionResponseEventListener;
private SwingWorker<Void, String> swingWorker;

View file

@ -9,7 +9,6 @@ import static java.util.stream.Collectors.toList;
import com.fasterxml.jackson.core.JsonProcessingException;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.intellij.openapi.application.ApplicationManager;
import com.intellij.openapi.diagnostic.Logger;
import ee.carlrobert.codegpt.EncodingManager;
import ee.carlrobert.codegpt.ReferencedFile;
import ee.carlrobert.codegpt.completions.llama.LlamaModel;
@ -67,8 +66,6 @@ import org.jetbrains.annotations.Nullable;
public class CompletionRequestProvider {
private static final Logger LOG = Logger.getInstance(CompletionRequestProvider.class);
public static final String COMPLETION_SYSTEM_PROMPT = getResourceContent(
"/prompts/default-completion-system-prompt.txt");
@ -92,7 +89,7 @@ public class CompletionRequestProvider {
.map(item -> includedFilesSettings.getRepeatableContext()
.replace("{FILE_PATH}", item.getFilePath())
.replace("{FILE_CONTENT}", format(
"```%s\n%s\n```",
"```%s%n%s%n```",
item.getFileExtension(),
item.getFileContent().trim())))
.collect(joining("\n\n"));
@ -183,7 +180,7 @@ public class CompletionRequestProvider {
.map(prevMessage -> new YouCompletionRequestMessage(
prevMessage.getPrompt(),
prevMessage.getResponse()))
.collect(toList()));
.toList());
if (TelemetryConfiguration.getInstance().isEnabled()
&& !ApplicationManager.getApplication().isUnitTestMode()) {
requestBuilder.setUserId(UUID.fromString(UserId.INSTANCE.get()));
@ -234,7 +231,7 @@ public class CompletionRequestProvider {
}
var value = entry.getValue();
if (value instanceof String && "$OPENAI_MESSAGES".equals(((String) value).trim())) {
if (value instanceof String string && "$OPENAI_MESSAGES".equals(string.trim())) {
return messages;
}
return value;
@ -382,6 +379,6 @@ public class CompletionRequestProvider {
}
}
return messages.stream().filter(Objects::nonNull).collect(toList());
return messages.stream().filter(Objects::nonNull).toList();
}
}

View file

@ -1,7 +1,6 @@
package ee.carlrobert.codegpt.completions.llama;
import static java.lang.String.format;
import static java.util.stream.Collectors.toList;
import static java.util.stream.Collectors.toSet;
import ee.carlrobert.codegpt.codecompletions.InfillPromptTemplate;
@ -163,6 +162,6 @@ public enum LlamaModel {
.collect(toSet())
.stream()
.sorted()
.collect(toList());
.toList();
}
}
}

View file

@ -86,7 +86,7 @@ public final class LlamaServerAgent implements Disposable {
CodeGPTBundle.get("llamaServerAgent.serverBootup.description"));
startServerProcessHandler = new OSProcessHandler.Silent(getServerCommandLine(params));
startServerProcessHandler.addProcessListener(
getProcessListener(params.getPort(), onSuccess, onServerTerminated));
getProcessListener(params.port(), onSuccess, onServerTerminated));
startServerProcessHandler.startNotify();
} catch (ExecutionException ex) {
LOG.error("Unable to start llama server", ex);
@ -127,7 +127,7 @@ public final class LlamaServerAgent implements Disposable {
try {
var serverMessage = objectMapper.readValue(event.getText(), LlamaServerMessage.class);
if ("HTTP server listening".equals(serverMessage.getMessage())) {
if ("HTTP server listening".equals(serverMessage.message())) {
LOG.info("Server up and running!");
LlamaSettings.getCurrentState().setServerPort(port);
@ -155,11 +155,11 @@ public final class LlamaServerAgent implements Disposable {
commandLine.setExePath("./server");
commandLine.withWorkDirectory(CodeGPTPlugin.getLlamaSourcePath());
commandLine.addParameters(
"-m", params.getModelPath(),
"-c", String.valueOf(params.getContextLength()),
"--port", String.valueOf(params.getPort()),
"-t", String.valueOf(params.getThreads()));
commandLine.addParameters(params.getAdditionalParameters());
"-m", params.modelPath(),
"-c", String.valueOf(params.contextLength()),
"--port", String.valueOf(params.port()),
"-t", String.valueOf(params.threads()));
commandLine.addParameters(params.additionalParameters());
commandLine.setRedirectErrorStream(false);
return commandLine;
}

View file

@ -1,26 +1,7 @@
package ee.carlrobert.codegpt.completions.llama;
import com.fasterxml.jackson.annotation.JsonIgnoreProperties;
import com.fasterxml.jackson.annotation.JsonProperty;
@JsonIgnoreProperties(ignoreUnknown = true)
public class LlamaServerMessage {
private final String level;
private final String message;
public LlamaServerMessage(
@JsonProperty("level") String level,
@JsonProperty("message") String message) {
this.level = level;
this.message = message;
}
public String getLevel() {
return level;
}
public String getMessage() {
return message;
}
public record LlamaServerMessage(String level, String message) {
}

View file

@ -2,44 +2,6 @@ package ee.carlrobert.codegpt.completions.llama;
import java.util.List;
public class LlamaServerStartupParams {
private final String modelPath;
private final int contextLength;
private final int threads;
private final int port;
private final List<String> additionalParameters;
public LlamaServerStartupParams(
String modelPath,
int contextLength,
int threads,
int port,
List<String> additionalParameters) {
this.modelPath = modelPath;
this.contextLength = contextLength;
this.threads = threads;
this.port = port;
this.additionalParameters = additionalParameters;
}
public String getModelPath() {
return modelPath;
}
public int getContextLength() {
return contextLength;
}
public int getThreads() {
return threads;
}
public int getPort() {
return port;
}
public List<String> getAdditionalParameters() {
return additionalParameters;
}
public record LlamaServerStartupParams(String modelPath, int contextLength, int threads, int port,
List<String> additionalParameters) {
}

View file

@ -101,8 +101,11 @@ public enum PromptTemplate {
public String buildPrompt(String systemPrompt, String userPrompt, List<Message> history) {
StringBuilder prompt = new StringBuilder();
prompt.append("Below is an instruction that describes a task. "
+ "Write a response that appropriately completes the request.\n\n");
prompt.append("""
Below is an instruction that describes a task. \
Write a response that appropriately completes the request.
""");
for (Message message : history) {
prompt.append("### Instruction\n")

View file

@ -7,7 +7,6 @@ import com.intellij.openapi.components.Service;
import ee.carlrobert.codegpt.completions.you.auth.response.YouAuthenticationResponse;
import java.io.IOException;
import java.util.List;
import okhttp3.Headers;
import okhttp3.OkHttpClient;
import okhttp3.Request;
import org.jetbrains.annotations.Nullable;
@ -22,8 +21,8 @@ public final class YouApiClient {
}
public @Nullable YouSubscription getSubscription(YouAuthenticationResponse auth) {
var sessionId = auth.getData().getSession().getSessionId();
var sessionJwt = auth.getData().getSessionJwt();
var sessionId = auth.data().session().sessionId();
var sessionJwt = auth.data().sessionJwt();
var request = new Request.Builder()
.url(API_BASE_URL + "/payments/orders/subscriptions/current")
.header("Accept", "application/json")

View file

@ -1,40 +1,7 @@
package ee.carlrobert.codegpt.completions.you;
import com.fasterxml.jackson.annotation.JsonCreator;
import com.fasterxml.jackson.annotation.JsonProperty;
import com.fasterxml.jackson.annotation.JsonIgnoreProperties;
public class YouSerpResult {
private final String url;
private final String name;
private final String snippet;
private final String snippetSource;
@JsonCreator(mode = JsonCreator.Mode.PROPERTIES)
public YouSerpResult(
@JsonProperty("url") String url,
@JsonProperty("name") String name,
@JsonProperty("snippet") String snippet,
@JsonProperty("snippetSource") String snippetSource) {
this.url = url;
this.name = name;
this.snippet = snippet;
this.snippetSource = snippetSource;
}
public String getUrl() {
return url;
}
public String getName() {
return name;
}
public String getSnippet() {
return snippet;
}
public String getSnippetSource() {
return snippetSource;
}
@JsonIgnoreProperties(ignoreUnknown = true)
public record YouSerpResult(String url, String name, String snippet, String snippetSource) {
}

View file

@ -1,34 +1,7 @@
package ee.carlrobert.codegpt.completions.you;
import com.fasterxml.jackson.annotation.JsonIgnoreProperties;
import com.fasterxml.jackson.annotation.JsonProperty;
@JsonIgnoreProperties(ignoreUnknown = true)
public class YouSubscription {
private final String service;
private final String tier;
private final String month;
public YouSubscription(
@JsonProperty("service") String service,
@JsonProperty("tier") String tier,
@JsonProperty("month") String month) {
this.service = service;
this.tier = tier;
this.month = month;
}
public String getService() {
return service;
}
public String getTier() {
return tier;
}
public String getMonth() {
return month;
}
public record YouSubscription(String service, String tier, String month) {
}

View file

@ -4,23 +4,6 @@ import com.fasterxml.jackson.annotation.JsonIgnoreProperties;
import com.fasterxml.jackson.annotation.JsonProperty;
@JsonIgnoreProperties(ignoreUnknown = true)
public class YouAuthenticationError {
private final String errorType;
private final String errorMessage;
public YouAuthenticationError(
@JsonProperty("error_type") String errorType,
@JsonProperty("error_message") String errorMessage) {
this.errorType = errorType;
this.errorMessage = errorMessage;
}
public String getErrorType() {
return errorType;
}
public String getErrorMessage() {
return errorMessage;
}
public record YouAuthenticationError(@JsonProperty("error_type") String errorType,
@JsonProperty("error_message") String errorMessage) {
}

View file

@ -69,7 +69,7 @@ public final class YouAuthenticationService {
var subscription =
YouApiClient.getInstance().getSubscription(authenticationResponse);
var subscribed = subscription != null && "youpro".equals(subscription.getService());
var subscribed = subscription != null && "youpro".equals(subscription.service());
userManager.setSubscribed(subscribed);
var messageBus = ApplicationManager.getApplication().getMessageBus();
if (subscribed) {

View file

@ -1,18 +1,7 @@
package ee.carlrobert.codegpt.completions.you.auth.response;
import com.fasterxml.jackson.annotation.JsonIgnoreProperties;
import com.fasterxml.jackson.annotation.JsonProperty;
@JsonIgnoreProperties(ignoreUnknown = true)
public class YouAuthenticationResponse {
private final YouAuthenticationResponseData data;
public YouAuthenticationResponse(@JsonProperty("data") YouAuthenticationResponseData data) {
this.data = data;
}
public YouAuthenticationResponseData getData() {
return data;
}
public record YouAuthenticationResponse(YouAuthenticationResponseData data) {
}

View file

@ -4,37 +4,7 @@ import com.fasterxml.jackson.annotation.JsonIgnoreProperties;
import com.fasterxml.jackson.annotation.JsonProperty;
@JsonIgnoreProperties(ignoreUnknown = true)
public class YouAuthenticationResponseData {
private final YouSession session;
private final String sessionJwt;
private final String sessionToken;
private final YouUser user;
public YouAuthenticationResponseData(
@JsonProperty("session") YouSession session,
@JsonProperty("session_jwt") String sessionJwt,
@JsonProperty("session_token") String sessionToken,
@JsonProperty("user") YouUser user) {
this.session = session;
this.sessionJwt = sessionJwt;
this.sessionToken = sessionToken;
this.user = user;
}
public YouSession getSession() {
return session;
}
public String getSessionJwt() {
return sessionJwt;
}
public String getSessionToken() {
return sessionToken;
}
public YouUser getUser() {
return user;
}
public record YouAuthenticationResponseData(
YouSession session, @JsonProperty("session_jwt") String sessionJwt,
@JsonProperty("session_token") String sessionToken, YouUser user) {
}

View file

@ -4,30 +4,5 @@ import com.fasterxml.jackson.annotation.JsonIgnoreProperties;
import com.fasterxml.jackson.annotation.JsonProperty;
@JsonIgnoreProperties(ignoreUnknown = true)
public class YouEmail {
private final String email;
private final String emailId;
private final boolean verified;
public YouEmail(
@JsonProperty("email") String email,
@JsonProperty("email_id") String emailId,
@JsonProperty("verified") boolean verified) {
this.email = email;
this.emailId = emailId;
this.verified = verified;
}
public String getEmail() {
return email;
}
public String getEmailId() {
return emailId;
}
public boolean isVerified() {
return verified;
}
public record YouEmail(String email, @JsonProperty("email_id") String emailId, boolean verified) {
}

View file

@ -4,30 +4,7 @@ import com.fasterxml.jackson.annotation.JsonIgnoreProperties;
import com.fasterxml.jackson.annotation.JsonProperty;
@JsonIgnoreProperties(ignoreUnknown = true)
public class YouName {
private final String firstName;
private final String middleName;
private final String lastName;
public YouName(
@JsonProperty("first_name") String firstName,
@JsonProperty("middle_name") String middleName,
@JsonProperty("last_name") String lastName) {
this.firstName = firstName;
this.middleName = middleName;
this.lastName = lastName;
}
public String getFirstName() {
return firstName;
}
public String getMiddleName() {
return middleName;
}
public String getLastName() {
return lastName;
}
public record YouName(@JsonProperty("first_name") String firstName,
@JsonProperty("middle_name") String middleName,
@JsonProperty("last_name") String lastName) {
}

View file

@ -4,44 +4,10 @@ import com.fasterxml.jackson.annotation.JsonIgnoreProperties;
import com.fasterxml.jackson.annotation.JsonProperty;
@JsonIgnoreProperties(ignoreUnknown = true)
public class YouSession {
private final String expiresAt;
private final String lastAccessedAt;
private final String sessionId;
private final String startedAt;
private final String userId;
public YouSession(
@JsonProperty("expires_at") String expiresAt,
@JsonProperty("last_accessed_at") String lastAccessedAt,
@JsonProperty("session_id") String sessionId,
@JsonProperty("started_at") String startedAt,
@JsonProperty("user_id") String userId) {
this.expiresAt = expiresAt;
this.lastAccessedAt = lastAccessedAt;
this.sessionId = sessionId;
this.startedAt = startedAt;
this.userId = userId;
}
public String getExpiresAt() {
return expiresAt;
}
public String getLastAccessedAt() {
return lastAccessedAt;
}
public String getSessionId() {
return sessionId;
}
public String getStartedAt() {
return startedAt;
}
public String getUserId() {
return userId;
}
public record YouSession(
@JsonProperty("expires_at") String expiresAt,
@JsonProperty("last_accessed_at") String lastAccessedAt,
@JsonProperty("session_id") String sessionId,
@JsonProperty("started_at") String startedAt,
@JsonProperty("user_id") String userId) {
}

View file

@ -5,30 +5,5 @@ import com.fasterxml.jackson.annotation.JsonProperty;
import java.util.List;
@JsonIgnoreProperties(ignoreUnknown = true)
public class YouUser {
private final List<YouEmail> emails;
private final YouName name;
private final String userId;
public YouUser(
@JsonProperty("emails") List<YouEmail> emails,
@JsonProperty("name") YouName name,
@JsonProperty("user_id") String userId) {
this.emails = emails;
this.name = name;
this.userId = userId;
}
public List<YouEmail> getEmails() {
return emails;
}
public YouName getName() {
return name;
}
public String getUserId() {
return userId;
}
public record YouUser(List<YouEmail> emails, YouName name, @JsonProperty("user_id") String userId) {
}

View file

@ -1,7 +1,5 @@
package ee.carlrobert.codegpt.conversations;
import static java.util.stream.Collectors.toList;
import ee.carlrobert.codegpt.conversations.message.Message;
import java.time.LocalDateTime;
import java.util.ArrayList;
@ -81,6 +79,6 @@ public class Conversation {
public void removeMessage(UUID messageId) {
setMessages(messages.stream()
.filter(message -> !message.getId().equals(messageId))
.collect(toList()));
.toList());
}
}

View file

@ -1,7 +1,5 @@
package ee.carlrobert.codegpt.conversations;
import static java.util.stream.Collectors.toList;
import com.intellij.openapi.application.ApplicationManager;
import com.intellij.openapi.components.Service;
import ee.carlrobert.codegpt.completions.CallParameters;
@ -39,7 +37,7 @@ public final class ConversationService {
.stream()
.flatMap(List::stream)
.sorted(Comparator.comparing(Conversation::getUpdatedOn).reversed())
.collect(toList());
.toList();
}
public Conversation createConversation(String clientCode) {
@ -92,7 +90,7 @@ public final class ConversationService {
return message;
}
return item;
}).collect(toList()));
}).toList());
if (next.getId().equals(conversation.getId())) {
iterator.set(conversation);
}
@ -188,24 +186,18 @@ public final class ConversationService {
}
private static String getModelForSelectedService(ServiceType serviceType) {
switch (serviceType) {
case OPENAI:
return OpenAISettings.getCurrentState().getModel();
case CUSTOM_OPENAI:
return "CustomService";
case ANTHROPIC:
return AnthropicSettings.getCurrentState().getModel();
case AZURE:
return AzureSettings.getCurrentState().getDeploymentId();
case YOU:
return "YouCode";
case LLAMA_CPP:
return switch (serviceType) {
case OPENAI -> OpenAISettings.getCurrentState().getModel();
case CUSTOM_OPENAI -> "CustomService";
case ANTHROPIC -> AnthropicSettings.getCurrentState().getModel();
case AZURE -> AzureSettings.getCurrentState().getDeploymentId();
case YOU -> "YouCode";
case LLAMA_CPP -> {
var llamaSettings = LlamaSettings.getCurrentState();
return llamaSettings.isUseCustomModel()
? llamaSettings.getCustomLlamaModelPath()
: llamaSettings.getHuggingFaceModel().getCode();
default:
throw new RuntimeException("Could not find corresponding service mapping");
}
yield llamaSettings.isUseCustomModel()
? llamaSettings.getCustomLlamaModelPath()
: llamaSettings.getHuggingFaceModel().getCode();
}
};
}
}
}

View file

@ -86,10 +86,9 @@ public class Message {
if (obj == this) {
return true;
}
if (!(obj instanceof Message)) {
if (!(obj instanceof Message other)) {
return false;
}
Message other = (Message) obj;
return Objects.equals(id, other.id);
}

View file

@ -6,7 +6,6 @@ import static ee.carlrobert.codegpt.settings.service.ServiceType.CUSTOM_OPENAI;
import static ee.carlrobert.codegpt.settings.service.ServiceType.LLAMA_CPP;
import static ee.carlrobert.codegpt.settings.service.ServiceType.OPENAI;
import static ee.carlrobert.codegpt.settings.service.ServiceType.YOU;
import static java.util.stream.Collectors.toList;
import com.intellij.openapi.Disposable;
import com.intellij.openapi.ui.ComboBox;
@ -46,8 +45,7 @@ public class GeneralSettingsComponent {
cards.add(serviceSelectionForm.getYouSettingsForm(), YOU.getCode());
cards.add(serviceSelectionForm.getLlamaSettingsForm(), LLAMA_CPP.getCode());
var serviceComboBoxModel = new DefaultComboBoxModel<ServiceType>();
serviceComboBoxModel.addAll(Arrays.stream(ServiceType.values())
.collect(toList()));
serviceComboBoxModel.addAll(Arrays.stream(ServiceType.values()).toList());
serviceComboBox = new ComboBox<>(serviceComboBoxModel);
serviceComboBox.setSelectedItem(OPENAI);
serviceComboBox.setPreferredSize(displayNameField.getPreferredSize());

View file

@ -2,14 +2,16 @@ package ee.carlrobert.codegpt.settings;
public class IncludedFilesSettingsState {
public static final String DEFAULT_PROMPT_TEMPLATE =
"Use the following context to answer question at the end:\n\n"
+ "{REPEATABLE_CONTEXT}\n\n"
+ "Question: {QUESTION}";
public static final String DEFAULT_REPEATABLE_CONTEXT =
"File Path: {FILE_PATH}\n"
+ "File Content:\n"
+ "{FILE_CONTENT}";
public static final String DEFAULT_PROMPT_TEMPLATE = """
Use the following context to answer question at the end:
{REPEATABLE_CONTEXT}
Question: {QUESTION}""";
public static final String DEFAULT_REPEATABLE_CONTEXT = """
File Path: {FILE_PATH}
File Content:
{FILE_CONTENT}""";
private String promptTemplate = DEFAULT_PROMPT_TEMPLATE;
private String repeatableContext = DEFAULT_REPEATABLE_CONTEXT;

View file

@ -83,10 +83,9 @@ public class AdvancedSettingsState {
if (this == o) {
return true;
}
if (!(o instanceof AdvancedSettingsState)) {
if (!(o instanceof AdvancedSettingsState that)) {
return false;
}
AdvancedSettingsState that = (AdvancedSettingsState) o;
return getProxyPort() == that.getProxyPort()
&& isProxyAuthSelected() == that.isProxyAuthSelected()
&& getConnectTimeout() == that.getConnectTimeout()

View file

@ -97,9 +97,8 @@ class CustomServiceFormTabbedPane extends JBTabbedPane {
public static Object[][] toArray(Map<?, ?> actionsMap) {
return actionsMap.entrySet()
.stream()
.map((entry) -> new Object[]{entry.getKey(), entry.getValue()})
.toList()
.toArray(new Object[0][0]);
.map(entry -> new Object[]{entry.getKey(), entry.getValue()})
.toArray(Object[][]::new);
}
private JPanel createTablePanel(JBTable table) {

View file

@ -1,7 +1,6 @@
package ee.carlrobert.codegpt.settings.service.llama.form;
import static java.lang.String.format;
import static java.util.stream.Collectors.toList;
import com.intellij.icons.AllIcons.Actions;
import com.intellij.icons.AllIcons.General;
@ -94,7 +93,7 @@ public class LlamaModelPreferencesForm {
var selectableModels = llamaModel.getHuggingFaceModels().stream()
.filter(model -> model.getParameterSize() == llm.getParameterSize())
.collect(toList());
.toList();
huggingFaceComboBoxModel.addAll(selectableModels);
huggingFaceComboBoxModel.setSelectedItem(selectableModels.get(0));
downloadModelActionLinkWrapper = new JPanel(new BorderLayout());
@ -116,7 +115,7 @@ public class LlamaModelPreferencesForm {
var modelSizeComboBoxModel = new DefaultComboBoxModel<ModelSize>();
var initialModelSizes = llamaModel.getSortedUniqueModelSizes().stream()
.map(ModelSize::new)
.collect(toList());
.toList();
modelSizeComboBoxModel.addAll(initialModelSizes);
modelSizeComboBoxModel.setSelectedItem(initialModelSizes.get(0));
var modelComboBoxModel = new EnumComboBoxModel<>(LlamaModel.class);
@ -318,7 +317,7 @@ public class LlamaModelPreferencesForm {
var selectedModel = (LlamaModel) e.getItem();
var modelSizes = selectedModel.getSortedUniqueModelSizes().stream()
.map(ModelSize::new)
.collect(toList());
.toList();
modelSizeComboBoxModel.removeAllElements();
modelSizeComboBoxModel.addAll(modelSizes);
@ -327,10 +326,11 @@ public class LlamaModelPreferencesForm {
var huggingFaceModels = selectedModel.getHuggingFaceModels().stream()
.filter(model -> {
var size = ((ModelSize) modelSizeComboBoxModel.getSelectedItem()).getSize();
return size == model.getParameterSize();
var selectedModelSize = (ModelSize) modelSizeComboBoxModel.getSelectedItem();
return selectedModelSize != null
&& selectedModelSize.size() == model.getParameterSize();
})
.collect(toList());
.toList();
huggingFaceComboBoxModel.removeAllElements();
huggingFaceComboBoxModel.addAll(huggingFaceModels);
@ -352,9 +352,9 @@ public class LlamaModelPreferencesForm {
.filter(model -> {
var selectedModelSize = (ModelSize) modelSizeComboBoxModel.getSelectedItem();
return selectedModelSize != null
&& selectedModelSize.getSize() == model.getParameterSize();
&& selectedModelSize.size() == model.getParameterSize();
})
.collect(toList());
.toList();
if (!models.isEmpty()) {
huggingFaceComboBoxModel.removeAllElements();
huggingFaceComboBoxModel.addAll(models);
@ -445,18 +445,16 @@ public class LlamaModelPreferencesForm {
return new AnActionLink(
CodeGPTBundle.get("settingsConfigurable.service.llama.downloadModelLink.label"),
new DownloadModelAction(
progressIndicator -> {
SwingUtilities.invokeLater(() -> {
configureFieldsForDownloading(true);
updateActionLink(
actionLinkWrapper,
createCancelDownloadLink(
progressLabel,
actionLinkWrapper,
huggingFaceComboBoxModel,
progressIndicator));
});
},
progressIndicator -> SwingUtilities.invokeLater(() -> {
configureFieldsForDownloading(true);
updateActionLink(
actionLinkWrapper,
createCancelDownloadLink(
progressLabel,
actionLinkWrapper,
huggingFaceComboBoxModel,
progressIndicator));
}),
() -> SwingUtilities.invokeLater(() -> {
configureFieldsForDownloading(false);
updateActionLink(
@ -488,32 +486,13 @@ public class LlamaModelPreferencesForm {
.installOn(helpIcon);
}
private static class ModelDetails {
double fileSize;
double maxRAMRequired;
public ModelDetails(double fileSize, double maxRAMRequired) {
this.fileSize = fileSize;
this.maxRAMRequired = maxRAMRequired;
}
private record ModelDetails(double fileSize, double maxRAMRequired) {
}
private static class ModelSize {
private final int size;
ModelSize(int size) {
this.size = size;
}
int getSize() {
return size;
}
private record ModelSize(int size) {
@Override
public String toString() {
return size + "B";
}
}
}
}

View file

@ -4,7 +4,6 @@ import static ee.carlrobert.codegpt.credentials.CredentialsStore.CredentialKey.L
import static ee.carlrobert.codegpt.ui.UIUtil.createComment;
import static ee.carlrobert.codegpt.ui.UIUtil.createForm;
import static ee.carlrobert.codegpt.ui.UIUtil.withEmptyLeftBorder;
import static java.util.stream.Collectors.toList;
import com.intellij.icons.AllIcons.Actions;
import com.intellij.openapi.application.ApplicationManager;
@ -35,7 +34,6 @@ import ee.carlrobert.codegpt.ui.UIUtil;
import ee.carlrobert.codegpt.ui.UIUtil.RadioButtonWithLayout;
import java.io.File;
import java.util.Arrays;
import java.util.Collections;
import java.util.List;
import java.util.Map;
import javax.swing.JButton;
@ -338,13 +336,10 @@ public class LlamaServerPreferencesForm {
}
public List<String> getListOfAdditionalParameters() {
if (additionalParametersField.getText().trim().isEmpty()) {
return Collections.emptyList();
}
var parameters = additionalParametersField.getText().split(",");
return Arrays.stream(parameters)
.map(String::trim)
.collect(toList());
return Arrays.stream(additionalParametersField.getText().split(","))
.map(String::trim)
.filter(s -> !s.isBlank())
.toList();
}
public PromptTemplate getPromptTemplate() {

View file

@ -7,7 +7,6 @@ import com.intellij.openapi.components.PersistentStateComponent;
import com.intellij.openapi.components.State;
import com.intellij.openapi.components.Storage;
import ee.carlrobert.codegpt.credentials.CredentialsStore;
import ee.carlrobert.codegpt.settings.configuration.ConfigurationSettings;
import org.apache.commons.lang3.StringUtils;
import org.jetbrains.annotations.NotNull;

View file

@ -90,7 +90,7 @@ public class YouSettingsForm extends JPanel {
if (authResponse == null) {
formBuilder.addComponent(createUserAuthenticationPanel(emailField, passwordField, null));
} else {
formBuilder.addComponent(createUserInformationPanel(authResponse.getData().getUser()));
formBuilder.addComponent(createUserInformationPanel(authResponse.data().user()));
}
return formBuilder
.addComponent(new TitledSeparator(
@ -199,7 +199,7 @@ public class YouSettingsForm extends JPanel {
.addVerticalGap(4);
if (error != null) {
var invalidCredentialsLabel = new JBLabel(error.getErrorMessage());
var invalidCredentialsLabel = new JBLabel(error.errorMessage());
invalidCredentialsLabel.setForeground(JBColor.red);
invalidCredentialsLabel.setBorder(JBUI.Borders.emptyLeft(4));
contentPanelBuilder.addComponentToRightColumn(invalidCredentialsLabel);
@ -220,7 +220,7 @@ public class YouSettingsForm extends JPanel {
var userManager = YouUserManager.getInstance();
var contentPanelBuilder = FormBuilder.createFormBuilder()
.addLabeledComponent(CodeGPTBundle.get("settingsConfigurable.service.you.email.label"),
new JBLabel(user.getEmails().get(0).getEmail()).withFont(JBFont.label().asBold()));
new JBLabel(user.emails().get(0).email()).withFont(JBFont.label().asBold()));
var signOutButton = new JButton(
CodeGPTBundle.get("settingsConfigurable.service.you.signOut.label"));
@ -260,7 +260,7 @@ public class YouSettingsForm extends JPanel {
CredentialsStore.INSTANCE.setCredential(
CredentialKey.YOU_ACCOUNT_PASSWORD,
new String(password));
refreshView(createUserInformationPanel(authenticationResponse.getData().getUser()));
refreshView(createUserInformationPanel(authenticationResponse.data().user()));
});
}

View file

@ -30,7 +30,7 @@ public class CodeGPTStatusBarWidget extends EditorBasedStatusBarPopup {
}
@Override
protected @Nullable ListPopup createPopup(DataContext context) {
protected @Nullable ListPopup createPopup(@NotNull DataContext context) {
return JBPopupFactory.getInstance()
.createActionGroupPopup(
CodeGPTBundle.get("project.label"),

View file

@ -1,7 +1,6 @@
package ee.carlrobert.codegpt.statusbar;
import com.intellij.openapi.project.Project;
import com.intellij.openapi.util.Disposer;
import com.intellij.openapi.wm.StatusBarWidget;
import com.intellij.openapi.wm.impl.status.widget.StatusBarEditorBasedWidgetFactory;
import ee.carlrobert.codegpt.CodeGPTBundle;
@ -26,8 +25,4 @@ public class CodeGPTStatusBarWidgetFactory extends StatusBarEditorBasedWidgetFac
return new CodeGPTStatusBarWidget(project);
}
@Override
public void disposeWidget(@NotNull StatusBarWidget widget) {
Disposer.dispose(widget);
}
}

View file

@ -18,6 +18,7 @@ import ee.carlrobert.codegpt.conversations.ConversationsState;
import ee.carlrobert.codegpt.conversations.message.Message;
import ee.carlrobert.codegpt.settings.configuration.ConfigurationSettings;
import java.util.Arrays;
import java.util.Objects;
import java.util.Optional;
import org.jetbrains.annotations.NotNull;
@ -110,16 +111,13 @@ public final class ChatToolWindowContentManager {
public @NotNull ToolWindow getToolWindow() {
var toolWindowManager = ToolWindowManager.getInstance(project);
var toolWindow = toolWindowManager.getToolWindow("CodeGPT");
if (toolWindow == null) {
// https://intellij-support.jetbrains.com/hc/en-us/community/posts/11533368171026/comments/11538403084562
return toolWindowManager
.registerToolWindow(RegisterToolWindowTask.closable(
"CodeGPT",
() -> "CodeGPT",
Icons.DefaultSmall,
ToolWindowAnchor.RIGHT));
}
return toolWindow;
// https://intellij-support.jetbrains.com/hc/en-us/community/posts/11533368171026/comments/11538403084562
return Objects.requireNonNullElseGet(toolWindow, () -> toolWindowManager
.registerToolWindow(RegisterToolWindowTask.closable(
"CodeGPT",
() -> "CodeGPT",
Icons.DefaultSmall,
ToolWindowAnchor.RIGHT)));
}
private Optional<Content> tryFindFirstChatTabContent() {

View file

@ -69,7 +69,7 @@ public class ChatToolWindowPanel extends SimpleToolWindowPanel {
var referencedFilePaths = referencedFiles.stream()
.map(ReferencedFile::getFilePath)
.collect(Collectors.toList());
.toList();
selectedFilesNotification.show(
referencedFiles.size() + " files selected",
selectedFilesNotificationDescription(referencedFilePaths));

View file

@ -3,7 +3,6 @@ package ee.carlrobert.codegpt.toolwindow.chat;
import static ee.carlrobert.codegpt.completions.CompletionRequestProvider.getPromptWithContext;
import static ee.carlrobert.codegpt.ui.UIUtil.createScrollPaneWithSmartScroller;
import static java.lang.String.format;
import static java.util.stream.Collectors.toList;
import com.intellij.openapi.Disposable;
import com.intellij.openapi.actionSystem.ActionPlaces;
@ -125,7 +124,7 @@ public class ChatToolWindowTabPanel implements Disposable {
if (referencedFiles != null && !referencedFiles.isEmpty()) {
var referencedFilePaths = referencedFiles.stream()
.map(ReferencedFile::getFilePath)
.collect(toList());
.toList();
message.setReferencedFilePaths(referencedFilePaths);
message.setUserMessage(message.getPrompt());
message.setPrompt(getPromptWithContext(referencedFiles, message.getPrompt()));
@ -259,9 +258,8 @@ public class ChatToolWindowTabPanel implements Disposable {
var selectionModel = editor.getSelectionModel();
var selectedText = selectionModel.getSelectedText();
if (selectedText != null && !selectedText.isEmpty()) {
var fileExtension = FileUtil.getFileExtension(
((EditorImpl) editor).getVirtualFile().getName());
message = new Message(text + format("\n```%s\n%s\n```", fileExtension, selectedText));
var fileExtension = FileUtil.getFileExtension(editor.getVirtualFile().getName());
message = new Message(text + format("%n```%s%n%s%n```", fileExtension, selectedText));
selectionModel.removeSelection();
}
}
@ -307,11 +305,10 @@ public class ChatToolWindowTabPanel implements Disposable {
return Unit.INSTANCE;
}
var fileExtension = FileUtil.getFileExtension(
((EditorImpl) editor).getVirtualFile().getName());
var fileExtension = FileUtil.getFileExtension(editor.getVirtualFile().getName());
var message = new Message(action.getPrompt().replace(
"{{selectedCode}}",
format("\n```%s\n%s\n```", fileExtension, editor.getSelectionModel().getSelectedText())));
format("%n```%s%n%s%n```", fileExtension, editor.getSelectionModel().getSelectedText())));
message.setUserMessage(action.getUserMessage());
sendMessage(message, ConversationType.DEFAULT);
@ -365,4 +362,4 @@ public class ChatToolWindowTabPanel implements Disposable {
createUserPromptPanel(GeneralSettings.getCurrentState().getSelectedService()), gbc);
return rootPanel;
}
}
}

View file

@ -52,22 +52,6 @@ public class StreamParser {
isProcessingCode = false;
}
public static class StreamParseResponse {
private final StreamResponseType type;
private final String response;
public StreamParseResponse(StreamResponseType type, String response) {
this.type = type;
this.response = response;
}
public StreamResponseType getType() {
return type;
}
public String getResponse() {
return response;
}
public record StreamParseResponse(StreamResponseType type, String response) {
}
}

View file

@ -178,7 +178,10 @@ public class ResponseEditorPanel extends JPanel implements Disposable {
actionGroup.add(new AnAction("Editor Actions", "Editor Actions", General.GearPlain) {
@Override
public void actionPerformed(@NotNull AnActionEvent e) {
menu.show(e.getInputEvent().getComponent(), 0, 0);
var inputEvent = e.getInputEvent();
if (inputEvent != null) {
menu.show(inputEvent.getComponent(), 0, 0);
}
}
});
toolbar.setLayoutPolicy(ActionToolbar.NOWRAP_LAYOUT_POLICY);

View file

@ -30,11 +30,14 @@ public class CopyAction extends TrackableAction {
Clipboard clipboard = Toolkit.getDefaultToolkit().getSystemClipboard();
clipboard.setContents(stringSelection, null);
var locationOnScreen = ((MouseEvent) event.getInputEvent()).getLocationOnScreen();
locationOnScreen.y = locationOnScreen.y - 16;
var mouseEvent = (MouseEvent) event.getInputEvent();
if (mouseEvent != null) {
var locationOnScreen = mouseEvent.getLocationOnScreen();
locationOnScreen.y = locationOnScreen.y - 16;
OverlayUtil.showInfoBalloon(
CodeGPTBundle.get("toolwindow.chat.editor.action.copy.success"),
locationOnScreen);
OverlayUtil.showInfoBalloon(
CodeGPTBundle.get("toolwindow.chat.editor.action.copy.success"),
locationOnScreen);
}
}
}

View file

@ -83,7 +83,7 @@ public class ChatMessageResponseBody extends JPanel {
public void update(String partialMessage) {
for (var item : streamParser.parse(partialMessage)) {
processResponse(item.getResponse(), CODE.equals(item.getType()), true);
processResponse(item.response(), CODE.equals(item.type()), true);
}
}

View file

@ -25,7 +25,7 @@ public class ChatToolWindowScrollablePanel extends ScrollablePanel {
public ResponsePanel getMessageResponsePanel(UUID messageId) {
return (ResponsePanel) Arrays.stream(visibleMessagePanels.get(messageId).getComponents())
.filter(component -> component instanceof ResponsePanel)
.filter(ResponsePanel.class::isInstance)
.findFirst().orElseThrow();
}

View file

@ -46,7 +46,7 @@ public class SelectedFilesAccordion extends JPanel {
.map(virtualFile -> {
var actionLink = new ActionLink(
Paths.get(virtualFile.getPath()).getFileName().toString(),
(event) -> {
event -> {
FileEditorManager.getInstance(project)
.openFile(Objects.requireNonNull(virtualFile), true);
});

View file

@ -1,6 +1,5 @@
package ee.carlrobert.codegpt.toolwindow.chat.ui;
import java.awt.Component;
import java.awt.event.AdjustmentEvent;
import java.awt.event.AdjustmentListener;
import javax.swing.BoundedRangeModel;
@ -65,11 +64,7 @@ public class SmartScroller implements AdjustmentListener {
scrollBar.addAdjustmentListener(this);
// Turn off automatic scrolling for text components
Component view = scrollPane.getViewport().getView();
if (view instanceof JTextComponent) {
JTextComponent textComponent = (JTextComponent) view;
if (scrollPane.getViewport().getView() instanceof JTextComponent textComponent) {
DefaultCaret caret = (DefaultCaret) textComponent.getCaret();
caret.setUpdatePolicy(DefaultCaret.NEVER_UPDATE);
}
@ -77,11 +72,7 @@ public class SmartScroller implements AdjustmentListener {
@Override
public void adjustmentValueChanged(final AdjustmentEvent e) {
SwingUtilities.invokeLater(new Runnable() {
public void run() {
checkScrollBar(e);
}
});
SwingUtilities.invokeLater(() -> checkScrollBar(e));
}
/*
@ -134,4 +125,4 @@ public class SmartScroller implements AdjustmentListener {
previousValue = value;
previousMaximum = maximum;
}
}
}

View file

@ -54,7 +54,6 @@ public class UserPromptTextArea extends JPanel {
private final int textAreaRadius = 16;
private final Consumer<String> onSubmit;
private IconActionButton stopButton;
private JPanel iconsPanel;
private boolean submitEnabled = true;
public UserPromptTextArea(Consumer<String> onSubmit, TotalTokensPanel totalTokensPanel) {
@ -183,7 +182,7 @@ public class UserPromptTextArea extends JPanel {
var flowLayout = new FlowLayout(FlowLayout.RIGHT);
flowLayout.setHgap(8);
iconsPanel = new JPanel(flowLayout);
JPanel iconsPanel = new JPanel(flowLayout);
iconsPanel.add(new IconActionButton(
new AnAction("Send Message", "Send message", Icons.Send) {
@Override

View file

@ -31,6 +31,9 @@ import org.jetbrains.annotations.NotNull;
public class OverlayUtil {
private OverlayUtil() {
}
public static Notification getDefaultNotification(String content, NotificationType type) {
return new Notification("CodeGPT Notification Group", "CodeGPT", content, type);
}
@ -105,9 +108,12 @@ public class OverlayUtil {
}
public static void showSelectedEditorSelectionWarning(AnActionEvent event) {
var locationOnScreen = ((MouseEvent) event.getInputEvent()).getLocationOnScreen();
locationOnScreen.y = locationOnScreen.y - 16;
showSelectedEditorSelectionWarning(requireNonNull(event.getProject()), locationOnScreen);
var mouseEvent = (MouseEvent) event.getInputEvent();
if (mouseEvent != null) {
var locationOnScreen = mouseEvent.getLocationOnScreen();
locationOnScreen.y = locationOnScreen.y - 16;
showSelectedEditorSelectionWarning(requireNonNull(event.getProject()), locationOnScreen);
}
}
public static void showSelectedEditorSelectionWarning(

View file

@ -23,8 +23,6 @@ import java.util.Arrays;
import java.util.List;
import java.util.Map;
import java.util.Map.Entry;
import java.util.Optional;
import java.util.stream.Collectors;
import javax.swing.AbstractAction;
import javax.swing.BorderFactory;
import javax.swing.Box;
@ -151,7 +149,7 @@ public class UIUtil {
String initialLayout) {
JPanel finalPanel = new JPanel(new BorderLayout());
finalPanel.add(createRadioButtonsPanel(layouts.values().stream().map(
RadioButtonWithLayout::getRadioButton).collect(Collectors.toList())),
RadioButtonWithLayout::getRadioButton).toList()),
BorderLayout.NORTH);
finalPanel.add(createRadioButtonGroupLayouts(layouts, initialLayout), BorderLayout.CENTER);
return finalPanel;
@ -172,14 +170,12 @@ public class UIUtil {
public void show(Container parent, String name) {
super.show(parent, name);
// Set height to selected components height instead of consistent height
Optional<Component> selectedComponent = Arrays.stream(parent.getComponents())
Arrays.stream(parent.getComponents())
.filter(component -> name.equals(component.getName()))
.findFirst();
if (selectedComponent.isEmpty()) {
return;
}
parent.setPreferredSize(new Dimension(parent.getPreferredSize().width,
(int) selectedComponent.get().getPreferredSize().getHeight()));
.findFirst()
.map(component -> (int) component.getPreferredSize().getHeight())
.map(height -> new Dimension(parent.getPreferredSize().width, height))
.ifPresent(parent::setPreferredSize);
}
};
@ -216,4 +212,3 @@ public class UIUtil {
}
}
}

View file

@ -1,7 +1,5 @@
package ee.carlrobert.codegpt.ui.checkbox;
import static java.util.stream.Collectors.toList;
import com.intellij.icons.AllIcons;
import com.intellij.openapi.util.Iconable;
import com.intellij.psi.PsiDirectory;
@ -36,7 +34,7 @@ public class PsiElementCheckboxTree extends FileCheckboxTree {
return Arrays.stream(checkedNodes)
.map(item -> new ReferencedFile(
new File(item.getContainingFile().getVirtualFile().getPath())))
.collect(toList());
.toList();
}
private static CheckedTreeNode createNode(PsiElement element) {

View file

@ -1,7 +1,5 @@
package ee.carlrobert.codegpt.ui.checkbox;
import static java.util.stream.Collectors.toList;
import com.intellij.icons.AllIcons;
import com.intellij.openapi.vfs.VirtualFile;
import com.intellij.ui.CheckedTreeNode;
@ -27,7 +25,7 @@ public class VirtualFileCheckboxTree extends FileCheckboxTree {
return Arrays.stream(checkedNodes)
.map(item -> new ReferencedFile(new File(item.getPath())))
.collect(toList());
.toList();
}
private static CheckedTreeNode createRootNode(VirtualFile[] files) {

View file

@ -10,6 +10,9 @@ import org.jetbrains.annotations.Nullable;
public class ApplicationUtil {
private ApplicationUtil() {
}
public static boolean isUnitTestingMode() {
Application app = ApplicationManager.getApplication();
return app != null && app.isUnitTestMode();

View file

@ -6,6 +6,9 @@ import ee.carlrobert.codegpt.util.file.FileUtil;
public class DownloadingUtil {
private DownloadingUtil() {
}
private static final int BYTES_IN_MB = 1024 * 1024;
public static String getFormattedDownloadProgress(long startTime, long fileSize, long bytesRead) {

View file

@ -27,6 +27,9 @@ import org.jetbrains.annotations.Nullable;
public final class EditorUtil {
private EditorUtil() {
}
public static Editor createEditor(@NotNull Project project, String fileExtension, String code) {
var timestamp = DateTimeFormatter.ofPattern("yyyyMMddHHmmss").format(LocalDateTime.now());
var fileName = "temp_" + timestamp + fileExtension;

View file

@ -1,7 +1,5 @@
package ee.carlrobert.codegpt.util;
import static java.util.stream.Collectors.toList;
import com.vladsch.flexmark.html.HtmlRenderer;
import com.vladsch.flexmark.parser.Parser;
import com.vladsch.flexmark.util.data.MutableDataSet;
@ -13,6 +11,9 @@ import java.util.regex.Pattern;
public class MarkdownUtil {
private MarkdownUtil() {
}
/**
* Splits a given string into a list of strings where each element is either a code block
* surrounded by triple backticks or a non-code block text.
@ -32,7 +33,7 @@ public class MarkdownUtil {
start = matcher.end();
}
result.add(inputMarkdown.substring(start));
return result.stream().filter(item -> !item.isBlank()).collect(toList());
return result.stream().filter(item -> !item.isBlank()).toList();
}
public static String convertMdToHtml(String message) {

View file

@ -32,6 +32,9 @@ import org.jetbrains.annotations.NotNull;
public class FileUtil {
private FileUtil() {
}
private static final Logger LOG = Logger.getInstance(FileUtil.class);
public static File createFile(String directoryPath, String fileName, String fileContent) {
@ -120,12 +123,11 @@ public class FileUtil {
}
return findFirstExtension(languageToExtensionMappings, language)
.orElseGet(() -> extensionToLanguageMappings.stream()
.or(() -> extensionToLanguageMappings.stream()
.filter(it -> it.getExtension().equalsIgnoreCase(language))
.findFirst()
.map(it -> findFirstExtension(languageToExtensionMappings, it.getValue())
.orElse(defaultValue))
.orElse(defaultValue));
.flatMap(it -> findFirstExtension(languageToExtensionMappings, it.getValue()))
).orElse(defaultValue);
}
public static boolean isUtf8File(String filePath) {