Skip to content

Commit a871581

Browse files
committed
impl: load and cache IDEs
This commit implements an IDE feed manager that depending on whether Toolbox runs in offline mode or not loads the eap and release information from two local json files or from the https://data.services.jetbrains.com/products. The feed manager is also able to intersect a list of available build versions (the IDE versions available for install on a workspace) with the list of versions fetched from the feed and return the latest version available for install. The intersection happens only after the feed was filtered by product code release type. Support for offline mode is WIP. The commit assumes that in offline mode Toolbox exposes a certain system property.
1 parent 01bcb66 commit a871581

File tree

5 files changed

+548
-0
lines changed

5 files changed

+548
-0
lines changed

build.gradle.kts

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -67,6 +67,7 @@ dependencies {
6767
testImplementation(kotlin("test"))
6868
testImplementation(libs.mokk)
6969
testImplementation(libs.bundles.toolbox.plugin.api)
70+
testImplementation(libs.coroutines.test)
7071
}
7172

7273
val extension = ExtensionJson(

gradle/libs.versions.toml

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -23,6 +23,7 @@ toolbox-core-api = { module = "com.jetbrains.toolbox:core-api", version.ref = "t
2323
toolbox-ui-api = { module = "com.jetbrains.toolbox:ui-api", version.ref = "toolbox-plugin-api" }
2424
toolbox-remote-dev-api = { module = "com.jetbrains.toolbox:remote-dev-api", version.ref = "toolbox-plugin-api" }
2525
coroutines-core = { module = "org.jetbrains.kotlinx:kotlinx-coroutines-core", version.ref = "coroutines" }
26+
coroutines-test = { module = "org.jetbrains.kotlinx:kotlinx-coroutines-test", version.ref = "coroutines" }
2627
serialization-core = { module = "org.jetbrains.kotlinx:kotlinx-serialization-core", version.ref = "serialization" }
2728
serialization-json = { module = "org.jetbrains.kotlinx:kotlinx-serialization-json", version.ref = "serialization" }
2829
serialization-json-okio = { module = "org.jetbrains.kotlinx:kotlinx-serialization-json-okio", version.ref = "serialization" }
Lines changed: 251 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,251 @@
1+
package com.coder.toolbox.feed
2+
3+
import com.coder.toolbox.CoderToolboxContext
4+
import com.coder.toolbox.plugin.PluginManager
5+
import com.coder.toolbox.sdk.CoderHttpClientBuilder
6+
import com.coder.toolbox.sdk.interceptors.Interceptors
7+
import com.coder.toolbox.util.OS
8+
import com.coder.toolbox.util.ReloadableTlsContext
9+
import com.coder.toolbox.util.getOS
10+
import com.squareup.moshi.Moshi
11+
import com.squareup.moshi.Types
12+
import kotlinx.coroutines.Dispatchers
13+
import kotlinx.coroutines.withContext
14+
import retrofit2.Retrofit
15+
import retrofit2.converter.moshi.MoshiConverterFactory
16+
import java.nio.file.Path
17+
import kotlin.io.path.exists
18+
import kotlin.io.path.readText
19+
20+
/**
21+
* Manages the caching and loading of JetBrains IDE product feeds.
22+
*
23+
* This manager handles fetching IDE information from JetBrains data services,
24+
* caching the results locally, and supporting offline mode.
25+
*
26+
* Cache files are stored in platform-specific locations:
27+
* - macOS: ~/Library/Application Support/JetBrains/Toolbox/plugins/com.coder.toolbox/
28+
* - Linux: ~/.local/share/JetBrains/Toolbox/plugins/com.coder.toolbox/
29+
* - Windows: %LOCALAPPDATA%/JetBrains/Toolbox/plugins/com.coder.toolbox/
30+
*/
31+
class IdeFeedManager(
32+
private val context: CoderToolboxContext,
33+
feedService: JetBrainsFeedService? = null
34+
) {
35+
private val moshi = Moshi.Builder()
36+
.add(IdeTypeAdapter())
37+
.build()
38+
39+
// Lazy initialization of the feed service
40+
private val feedService: JetBrainsFeedService by lazy {
41+
if (feedService != null) return@lazy feedService
42+
43+
val interceptors = buildList {
44+
add((Interceptors.userAgent(PluginManager.pluginInfo.version)))
45+
add(Interceptors.logging(context))
46+
}
47+
val okHttpClient = CoderHttpClientBuilder.build(
48+
context,
49+
interceptors,
50+
ReloadableTlsContext(context.settingsStore.readOnly().tls)
51+
)
52+
53+
val retrofit = Retrofit.Builder()
54+
.baseUrl("https://data.services.jetbrains.com/")
55+
.client(okHttpClient)
56+
.addConverterFactory(MoshiConverterFactory.create(moshi))
57+
.build()
58+
59+
val feedApi = retrofit.create(JetBrainsFeedApi::class.java)
60+
JetBrainsFeedService(context, feedApi)
61+
}
62+
63+
private var cachedIdes: List<Ide>? = null
64+
65+
/**
66+
* Lazily load the IDE list.
67+
*
68+
* This method will only execute once. Subsequent calls will return the cached result.
69+
*
70+
* If offline mode is enabled (via -Doffline=true), this will load from local cache files.
71+
* Otherwise, it will fetch from the remote feeds and save to local cache.
72+
*
73+
* @return List of IDE objects from both release and EAP feeds
74+
*/
75+
suspend fun loadIdes(): List<Ide> {
76+
// Return cached value if already loaded
77+
cachedIdes?.let { return it }
78+
79+
val isOffline = isOfflineMode()
80+
context.logger.info("Loading IDEs in ${if (isOffline) "offline" else "online"} mode")
81+
82+
val ides = if (isOffline) {
83+
loadIdesOffline()
84+
} else {
85+
loadIdesOnline()
86+
}
87+
88+
cachedIdes = ides
89+
return ides
90+
}
91+
92+
/**
93+
* Load IDEs from local cache files in offline mode.
94+
*/
95+
private suspend fun loadIdesOffline(): List<Ide> = withContext(Dispatchers.IO) {
96+
context.logger.info("Loading IDEs from local cache files")
97+
98+
val releaseIdes = loadFeedFromFile(getReleaseCachePath())
99+
val eapIdes = loadFeedFromFile(getEapCachePath())
100+
101+
val allIdes = releaseIdes + eapIdes
102+
context.logger.info("Loaded ${allIdes.size} IDEs from cache (${releaseIdes.size} release, ${eapIdes.size} EAP)")
103+
104+
allIdes
105+
}
106+
107+
/**
108+
* Fetch IDEs from remote feeds and cache them locally.
109+
*/
110+
private suspend fun loadIdesOnline(): List<Ide> {
111+
context.logger.info("Fetching IDEs from remote feeds")
112+
113+
// Fetch from both feeds
114+
val releaseIdes = try {
115+
feedService.fetchReleaseFeed()
116+
} catch (e: Exception) {
117+
context.logger.warn(e, "Failed to fetch release feed")
118+
emptyList()
119+
}
120+
121+
val eapIdes = try {
122+
feedService.fetchEapFeed()
123+
} catch (e: Exception) {
124+
context.logger.warn(e, "Failed to fetch EAP feed")
125+
emptyList()
126+
}
127+
128+
val allIdes = releaseIdes + eapIdes
129+
context.logger.info("Fetched ${allIdes.size} IDEs from remote (${releaseIdes.size} release, ${eapIdes.size} EAP)")
130+
131+
return allIdes
132+
}
133+
134+
/**
135+
* Get the platform-specific cache directory path.
136+
*/
137+
private fun getCacheDirectory(): Path {
138+
val os = getOS()
139+
val userHome = System.getProperty("user.home")
140+
141+
val basePath = when (os) {
142+
OS.MAC -> Path.of(userHome, "Library", "Application Support")
143+
OS.LINUX -> Path.of(userHome, ".local", "share")
144+
OS.WINDOWS -> {
145+
val localAppData = System.getenv("LOCALAPPDATA")
146+
?: Path.of(userHome, "AppData", "Local").toString()
147+
Path.of(localAppData)
148+
}
149+
150+
null -> {
151+
context.logger.warn("Unable to determine OS, using home directory for cache")
152+
Path.of(userHome, ".cache")
153+
}
154+
}
155+
156+
return basePath.resolve("JetBrains/Toolbox/plugins/com.coder.toolbox")
157+
}
158+
159+
/**
160+
* Get the path for the release feed cache file.
161+
*/
162+
private fun getReleaseCachePath(): Path {
163+
return getCacheDirectory().resolve(RELEASE_CACHE_FILE)
164+
}
165+
166+
/**
167+
* Get the path for the EAP feed cache file.
168+
*/
169+
private fun getEapCachePath(): Path {
170+
return getCacheDirectory().resolve(EAP_CACHE_FILE)
171+
}
172+
173+
/**
174+
* Load a list of IDEs from a JSON file.
175+
*
176+
* @return List of IDEs, or empty list if the file doesn't exist or can't be read
177+
*/
178+
private suspend fun loadFeedFromFile(path: Path): List<Ide> = withContext(Dispatchers.IO) {
179+
try {
180+
if (!path.exists()) {
181+
context.logger.info("Cache file does not exist: $path")
182+
return@withContext emptyList()
183+
}
184+
185+
val json = path.readText()
186+
val listType = Types.newParameterizedType(List::class.java, Ide::class.java)
187+
val adapter = moshi.adapter<List<Ide>>(listType)
188+
val ides = adapter.fromJson(json) ?: emptyList()
189+
190+
context.logger.info("Loaded ${ides.size} IDEs from $path")
191+
ides
192+
} catch (e: Exception) {
193+
context.logger.warn(e, "Failed to load feed from $path")
194+
emptyList()
195+
}
196+
}
197+
198+
/**
199+
* Check if offline mode is enabled via the -Doffline=true system property.
200+
*/
201+
private fun isOfflineMode(): Boolean {
202+
return System.getProperty(OFFLINE_PROPERTY)?.toBoolean() == true
203+
}
204+
205+
/**
206+
* Find the best matching IDE based on the provided query criteria.
207+
*
208+
* This method filters the loaded IDEs by product code and type, optionally
209+
* filtering by available builds, then returns the IDE with the highest build.
210+
*
211+
* Build comparison is done lexicographically (string comparison).
212+
*
213+
* @param query The query criteria specifying product code, type, and optional available builds
214+
* @return The IDE with the highest build matching the criteria, or null if no match found
215+
*/
216+
suspend fun findBestMatch(query: IdeQuery): Ide? {
217+
val ides = loadIdes()
218+
219+
return ides
220+
.filter { it.code == query.productCode }
221+
.filter { it.type == query.type }
222+
.let { filtered ->
223+
filtered.filter { it.build in query.availableBuilds }
224+
}
225+
.maxByOrNull { it.build }
226+
}
227+
228+
/**
229+
* Convenience method to find the best matching IDE.
230+
*
231+
* This is a shorthand for creating an IdeQuery and calling findBestMatch(query).
232+
*
233+
* @param productCode The IntelliJ product code (e.g., "RR" for RustRover)
234+
* @param type The type of IDE release (RELEASE or EAP)
235+
* @param availableBuilds List of acceptable builds to filter by
236+
* @return The IDE with the highest build matching the criteria, or null if no match found
237+
*/
238+
suspend fun findBestMatch(
239+
productCode: String,
240+
type: IdeType,
241+
availableBuilds: List<String>
242+
): Ide? = findBestMatch(
243+
IdeQuery(productCode, type, availableBuilds)
244+
)
245+
246+
companion object {
247+
private const val RELEASE_CACHE_FILE = "release.json"
248+
private const val EAP_CACHE_FILE = "eap.json"
249+
private const val OFFLINE_PROPERTY = "offline"
250+
}
251+
}
Lines changed: 24 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,24 @@
1+
package com.coder.toolbox.feed
2+
3+
/**
4+
* Query object for finding the best matching IDE from loaded feeds.
5+
*
6+
* This encapsulates the filtering criteria for IDE selection, including
7+
* product code, type (release/eap), and optionally available versions.
8+
*/
9+
data class IdeQuery(
10+
/**
11+
* The IntelliJ product code (e.g., "RR" for RustRover, "IU" for IntelliJ IDEA Ultimate)
12+
*/
13+
val productCode: String,
14+
15+
/**
16+
* The type of IDE release to filter for
17+
*/
18+
val type: IdeType,
19+
20+
/**
21+
* List of available builds to install.
22+
*/
23+
val availableBuilds: List<String>
24+
)

0 commit comments

Comments
 (0)