Skip to content

Commit c004ed2

Browse files
committed
merge: feat/code-intelligence-everywhere into release/batch-p13
2 parents 3b84984 + 63068f9 commit c004ed2

28 files changed

Lines changed: 913 additions & 112 deletions

‎cli/src/coding_study/adapters/docker_sandbox.py‎

Lines changed: 4 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -94,6 +94,7 @@
9494
render_compose,
9595
sidecar_document,
9696
sidecar_files,
97+
sidecar_links,
9798
stack_document,
9899
)
99100

@@ -848,6 +849,9 @@ def _prepare_sidecar(plan: SidecarPlan) -> None:
848849
for path, content in sidecar_files(plan).items():
849850
Path(path).parent.mkdir(parents=True, exist_ok=True)
850851
_write_file(Path(path), content)
852+
for path, target in sidecar_links(plan).items():
853+
Path(path).parent.mkdir(parents=True, exist_ok=True)
854+
Path(path).symlink_to(target)
851855
if plan.toolchain is not None and plan.toolchain.writable_project:
852856
devcontainer = Path(plan.project.path) / DEVCONTAINER_DIRECTORY
853857
_refuse_link(devcontainer)

‎cli/src/coding_study/adapters/language_servers/lsp_directory.py‎

Lines changed: 91 additions & 20 deletions
Original file line numberDiff line numberDiff line change
@@ -16,6 +16,7 @@
1616
from datetime import date
1717
from importlib import resources
1818
from pathlib import Path
19+
from typing import cast
1920

2021
from coding_study.adapters.workspace_marker import accepted_license, record_license
2122
from coding_study.application.ports import (
@@ -34,25 +35,33 @@
3435
)
3536
from coding_study.domain.code_intelligence import (
3637
GO_RELEASE_COMMAND,
38+
KOTLIN_LSP,
3739
LSP_DIRECTORY,
3840
LSP_INSTALL_COMMAND,
41+
SIDECAR_PLATFORM,
3942
Archive,
4043
GoInstall,
4144
LanguageServer,
4245
Launch,
4346
License,
4447
build_archive,
48+
build_place,
4549
go_release,
4650
machine_of,
51+
sidecar_machine,
4752
)
53+
from coding_study.domain.problem import Language
54+
from coding_study.domain.project_manifest import MANIFESTS_DIRECTORY
4855
from coding_study.domain.server_builds import (
4956
checksum_in,
5057
expired_already,
5158
last_day,
5259
license_of,
5360
newest_build,
5461
)
62+
from coding_study.domain.service_project import INSTALL_RECORD_LANGUAGE, INSTALL_RECORD_SUFFIX
5563

64+
GRADLE_BUILD_RECEIPT = "org/gradle/build-receipt.properties"
5665
MANIFEST_PACKAGE = "coding_study.adapters.language_servers"
5766
MANIFEST_FILES = ("package.json", "pnpm-lock.yaml")
5867
LOCAL_TOOLCHAIN = {"GOTOOLCHAIN": "local"}
@@ -108,16 +117,18 @@ def today(self) -> date:
108117

109118
def newest_build(self, server: LanguageServer) -> NewestBuild | NoBuild:
110119
"""Reads the server's releases list, the `.sha256` file of the newest build for this
111-
machine and the license at its release's tag; nothing is downloaded yet."""
120+
machine, or for a sidecar's Linux on this machine's processor, and the license at its
121+
release's tag; nothing is downloaded yet."""
112122
releases, known = server.releases, server.license
113123
if releases is None or known is None:
114124
return NoBuild(f"{server.name} publishes no builds of its own")
125+
machine = sidecar_machine(platform.machine()) if server.linux_build else self.machine
115126
try:
116127
listed = json.loads(self._fetch(releases.api_url))
117-
build = newest_build(listed, releases, self.machine)
128+
build = newest_build(listed, releases, machine)
118129
if build is None:
119130
reason = f"no release of {server.name} at {releases.api_url} has a build for"
120-
return NoBuild(f"{reason} {self.machine} with a published SHA-256")
131+
return NoBuild(f"{reason} {machine} with a published SHA-256")
121132
sha256 = checksum_in(self._fetch(build.checksum_url).decode(), build.file_name)
122133
if sha256 is None:
123134
return NoBuild(f"{build.checksum_url} holds no SHA-256 of {build.file_name}")
@@ -127,7 +138,8 @@ def newest_build(self, server: LanguageServer) -> NewestBuild | NoBuild:
127138
return NoBuild(f"cannot read the releases of {server.name}: {error}")
128139
if license is None:
129140
return NoBuild(f"cannot read the license of {build.tag} at {license_url}")
130-
return NewestBuild(build, build_archive(build, sha256, self.machine), license)
141+
archive = build_archive(build, sha256, machine, build_place(server))
142+
return NewestBuild(build, archive, license)
131143

132144
def install_build(self, server: LanguageServer, newest: NewestBuild) -> ProbeResult:
133145
"""Downloads and checks the build as `download` does, then asks it the last day it runs
@@ -136,12 +148,18 @@ def install_build(self, server: LanguageServer, newest: NewestBuild) -> ProbeRes
136148
downloaded = self.download(newest.archive)
137149
if downloaded.exit_code != 0:
138150
return downloaded
139-
status = self._status(server)
140151
version = newest.build.version
141-
if expired_already(status):
142-
return ProbeResult(1, f"{server.name} {version}, JetBrains' newest, has expired\n")
143-
last = last_day(status)
144-
self._record(server, newest, last)
152+
if server.linux_build:
153+
last = self._last_day_of_this_machines(version)
154+
build = self._directory / newest.archive.directory / newest.archive.into
155+
tooling = _gradle_tooling(build)
156+
self._record(server, newest, last, tooling)
157+
else:
158+
status = self._status(server)
159+
if expired_already(status):
160+
return ProbeResult(1, f"{server.name} {version}, JetBrains' newest, has expired\n")
161+
last = last_day(status)
162+
self._record(server, newest, last)
145163
until = "" if last is None else f", runs until {last.isoformat()}"
146164
return ProbeResult(
147165
0, f"{server.name} {version} in {LSP_DIRECTORY}/{newest.archive.directory}{until}\n"
@@ -155,14 +173,28 @@ def _status(self, server: LanguageServer) -> str:
155173
result = self._commands.run(command, self._directory, server.environment(launch))
156174
return "" if result is None else result.output
157175

158-
def _record(self, server: LanguageServer, newest: NewestBuild, last: date | None) -> None:
159-
record = {
176+
def _last_day_of_this_machines(self, version: str) -> date | None:
177+
"""The last day of a Linux build, which cannot run here to say it: that of this machine's
178+
build of the same version, which `--fix` fetches first; None without one."""
179+
probe = self._fetched(KOTLIN_LSP)
180+
return probe.last_day if isinstance(probe, Fetched) and probe.version == version else None
181+
182+
def _record(
183+
self,
184+
server: LanguageServer,
185+
newest: NewestBuild,
186+
last: date | None,
187+
gradle_tooling: str | None = None,
188+
) -> None:
189+
record: dict[str, object] = {
160190
"version": newest.build.version,
161191
"last_day": None if last is None else last.isoformat(),
162192
"license": {"name": newest.license.name, "url": newest.license.url},
163193
"url": newest.archive.url,
164194
"sha256": newest.archive.sha256,
165195
}
196+
if gradle_tooling is not None:
197+
record["gradle_tooling"] = gradle_tooling
166198
(self._directory / str(server.script)).write_text(json.dumps(record, indent=2) + "\n")
167199

168200
def _fetched(self, server: LanguageServer) -> ServerProbe:
@@ -178,17 +210,34 @@ def _fetched(self, server: LanguageServer) -> ServerProbe:
178210
known.summary if known else "",
179211
)
180212
ends = None if last is None else date.fromisoformat(last)
181-
except (OSError, ValueError, KeyError, TypeError):
213+
tooling = record.get("gradle_tooling")
214+
except (OSError, ValueError, KeyError, TypeError, AttributeError):
182215
return NotInstalled()
183-
launcher = server.command(Launch(str(self._directory), platform=sys.platform))[0]
216+
on = SIDECAR_PLATFORM if server.linux_build else sys.platform
217+
launcher = server.command(Launch(str(self._directory), platform=on))[0]
184218
if not isinstance(version, str) or not Path(launcher).is_file():
185219
return NotInstalled()
186-
return Fetched(version, ends, license)
220+
return Fetched(version, ends, license, tooling if isinstance(tooling, str) else None)
187221

188222
@property
189223
def machine(self) -> str:
190224
return machine_of(sys.platform, platform.machine())
191225

226+
def installed_service_languages(self) -> frozenset[Language]:
227+
"""The languages of the service projects whose dependencies are installed here, as their
228+
install records name them (`.cs/projects/<slug>.install.json`)."""
229+
languages: set[Language] = set()
230+
for path in (self._workspace / MANIFESTS_DIRECTORY).glob(f"*{INSTALL_RECORD_SUFFIX}"):
231+
try:
232+
record: object = json.loads(path.read_text())
233+
except (OSError, ValueError):
234+
continue
235+
fields = cast(dict[str, object], record) if isinstance(record, dict) else {}
236+
named = fields.get(INSTALL_RECORD_LANGUAGE)
237+
if isinstance(named, str) and named in tuple(Language):
238+
languages.add(Language(named))
239+
return frozenset(languages)
240+
192241
def license_accepted(self, license: License) -> bool:
193242
return accepted_license(self._workspace, license.key) == (license.name, license.url)
194243

@@ -273,14 +322,36 @@ def _unpacked(archive: Archive, scratch: Path, target: Path) -> ProbeResult:
273322
build = extracted / archive.strip if archive.strip else extracted
274323
if not build.is_dir():
275324
return ProbeResult(1, f"the archive holds no {archive.strip}/\n")
276-
unpacked = scratch / "unpacked"
277-
place = unpacked / archive.into if archive.into else unpacked
325+
if archive.into:
326+
_replace(build, target / archive.into, scratch / "earlier")
327+
else:
328+
_replace(build, target, scratch / "earlier")
329+
return ProbeResult(0, f"unpacked into {LSP_DIRECTORY}/{archive.directory}\n")
330+
331+
332+
def _replace(build: Path, place: Path, earlier: Path) -> None:
333+
"""`build` in place of whatever `place` held, which goes to `earlier`; what is beside `place`
334+
stays, such as another build of the same server and its record."""
278335
place.parent.mkdir(parents=True, exist_ok=True)
336+
if place.exists():
337+
place.rename(earlier)
279338
build.rename(place)
280-
if target.exists():
281-
target.rename(scratch / "earlier")
282-
unpacked.rename(target)
283-
return ProbeResult(0, f"unpacked into {LSP_DIRECTORY}/{archive.directory}\n")
339+
340+
341+
def _gradle_tooling(directory: Path) -> str | None:
342+
"""The version of the Gradle tooling API a build bundles, as the build receipt in one of its
343+
jars says; None when none says it."""
344+
for jar in sorted(directory.rglob("*gradle*tooling*.jar")):
345+
try:
346+
with zipfile.ZipFile(jar) as archive:
347+
receipt = archive.read(GRADLE_BUILD_RECEIPT).decode()
348+
except (OSError, KeyError, zipfile.BadZipFile):
349+
continue
350+
for line in receipt.splitlines():
351+
name, _, value = line.partition("=")
352+
if name.strip() == "versionNumber" and value.strip():
353+
return value.strip()
354+
return None
284355

285356

286357
def _unzip(archive: Path, directory: Path) -> None:

‎cli/src/coding_study/application/code_intelligence.py‎

Lines changed: 34 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -37,6 +37,7 @@
3737
EXPIRY_WARNING_DAYS,
3838
LSP_DIRECTORY,
3939
NOT_AVAILABLE_YET,
40+
SIDECAR_BUILDS,
4041
SIDECAR_SERVERS,
4142
LanguageServer,
4243
License,
@@ -54,6 +55,7 @@
5455
from coding_study.domain.preferences import Preferences
5556
from coding_study.domain.problem import Language, ProblemKind, ProblemMeta
5657
from coding_study.domain.sandbox import (
58+
GRADLE_GLIBC_IMAGE,
5759
NODE_IMAGE,
5860
SIDECAR_DATA,
5961
SharedFolder,
@@ -85,6 +87,11 @@
8587
INSTALL_CACHE_FIX = "cstudy test"
8688
"""A run installs again while the install cache lacks the server, now that code intelligence is
8789
on, and builds it there."""
90+
NO_KOTLIN_IMAGE = (
91+
f"needs the Kotlin image: docker pull gradle@{GRADLE_GLIBC_IMAGE.partition('@')[2]}"
92+
)
93+
"""The Kotlin LSP's sidecar runs on an image of its own, which no run pulls: you pull it once, by
94+
its digest, which fits in a close reason where its tag beside it would not."""
8895
NO_PROJECT_IMAGE = "needs the project's image: run cstudy test or cstudy dev, which pull it"
8996
"""A Java project's server runs on the project's image, which a run pulls. Its name and digest
9097
would not fit in a close reason, whose 123 bytes would cut the digest."""
@@ -288,6 +295,8 @@ def sidecar_unavailable(engine: SidecarEngine, image: str = NODE_IMAGE) -> str |
288295
return NO_DOCKER[state.status]
289296
if engine.image_present(image):
290297
return None
298+
if image == GRADLE_GLIBC_IMAGE:
299+
return NO_KOTLIN_IMAGE
291300
return NO_SIDECAR_IMAGE if image == NODE_IMAGE else NO_PROJECT_IMAGE
292301

293302

@@ -395,17 +404,40 @@ def _sidecar(
395404
cache = None
396405
if service.app.install_cache:
397406
cache = cache_volume_of(install_stack_name(slug, workspace))
407+
project = _shared(environment.root / root)
408+
tooling = _gradle_tooling(environment, sidecar_server(server, project.path))
409+
data = f"{run}/{SIDECAR_DATA}"
398410
return SidecarPlan(
399411
identity=identity,
400412
user=engine.host_user(),
401-
project=_shared(environment.root / root),
413+
project=project,
402414
servers=_shared(environment.root / LSP_DIRECTORY),
403415
run=run,
404416
image=sidecar_image(server, service.image),
405-
toolchain=sidecar_toolchain(server, service, f"{run}/{SIDECAR_DATA}", cache),
417+
toolchain=sidecar_toolchain(server, service, data, cache, tooling),
406418
)
407419

408420

421+
def _gradle_tooling(environment: Environment, server: LanguageServer) -> str | None:
422+
"""The Gradle tooling API a fetched Linux build bundles, as its record says; None for any
423+
other server."""
424+
if not server.linux_build:
425+
return None
426+
probe = environment.language_servers.probe(server)
427+
return probe.gradle_tooling if isinstance(probe, Fetched) else None
428+
429+
430+
def sidecar_build_states(
431+
locator: LanguageServerLocator, jdk: JdkSelector
432+
) -> tuple[LanguageServerState, ...]:
433+
"""The state of each build that `cstudy doctor --fix` fetches for a sidecar and not for this
434+
machine, for the languages of the service projects installed in the workspace: the Kotlin
435+
LSP's Linux build, once a Kotlin service project is installed."""
436+
languages = locator.installed_service_languages()
437+
builds = (server for server in SIDECAR_BUILDS if server.language in languages)
438+
return tuple(_located(server, locator, jdk) for server in builds)
439+
440+
409441
def _shared(folder: Path) -> SharedFolder:
410442
return SharedFolder(path=str(folder), source=str(folder.resolve()))
411443

‎cli/src/coding_study/application/doctor.py‎

Lines changed: 24 additions & 6 deletions
Original file line numberDiff line numberDiff line change
@@ -26,6 +26,7 @@
2626
is_unpacked,
2727
is_usable,
2828
language_server_states,
29+
sidecar_build_states,
2930
)
3031
from coding_study.application.installs import (
3132
INSTALLS_CHECK,
@@ -73,6 +74,7 @@
7374
LSP_BIN,
7475
LSP_DIRECTORY,
7576
LSP_INSTALL_COMMAND,
77+
SIDECAR_BUILDS,
7678
Archive,
7779
GoInstall,
7880
LanguageServer,
@@ -363,10 +365,16 @@ def _fetch_step(server: LanguageServer) -> FixStep:
363365
)
364366

365367

366-
FETCH_STEPS = {_fetch_step(server): server for server in LANGUAGE_SERVERS if server.releases}
368+
FETCH_STEPS = {
369+
_fetch_step(server): server
370+
for server in (*LANGUAGE_SERVERS, *SIDECAR_BUILDS)
371+
if server.releases
372+
}
367373
"""Fetch the newest build of the servers whose vendor publishes early-access builds that stop,
368374
such as the Kotlin LSP, while the `code_intelligence` preference is on: the releases list, the
369-
SHA-256 published beside the build, its license, and the build unless it is the one there."""
375+
SHA-256 published beside the build, its license, and the build unless it is the one there. The
376+
Linux build of a sidecar comes after this machine's, and only once a service project of its
377+
language is installed."""
370378

371379

372380
def _warm_up_step(server: LanguageServer, root: str) -> FixStep:
@@ -707,7 +715,12 @@ def _fix_plan(
707715
plan.append((LANGUAGE_SERVERS_FIX, files.root / LSP_DIRECTORY))
708716
plan += [(step, files.root / step.project) for step in DOWNLOAD_STEPS]
709717
plan += [(step, files.root / step.project) for step in GO_INSTALL_STEPS]
710-
plan += [(step, files.root / step.project) for step in FETCH_STEPS]
718+
needed = workspace.language_servers.installed_service_languages()
719+
plan += [
720+
(step, files.root / step.project)
721+
for step, server in FETCH_STEPS.items()
722+
if not server.linux_build or server.language in needed
723+
]
711724
if jvm and files.exists(JVM_FIX.project):
712725
plan += [(step, files.root / step.project) for step in (JVM_FIX, *JVM_PROJECT_WARMUPS)]
713726
if _code_intelligence_on(workspace):
@@ -1289,11 +1302,16 @@ def _language_servers(workspace: PracticeWorkspace, jdk: JdkSelector) -> list[Ch
12891302
if not _code_intelligence_on(workspace):
12901303
return []
12911304
states = language_server_states(workspace.language_servers, jdk)
1292-
return [_language_server_row(state) for state in states if state.server is not None]
1305+
rows = [_language_server_row(state) for state in states if state.server is not None]
1306+
for state in sidecar_build_states(workspace.language_servers, jdk):
1307+
rows.append(_language_server_row(state, f"{state.language} service projects"))
1308+
return rows
12931309

12941310

1295-
def _language_server_row(state: LanguageServerState) -> CheckResult:
1296-
name = f"code intelligence {state.language}"
1311+
def _language_server_row(state: LanguageServerState, scope: str | None = None) -> CheckResult:
1312+
"""`code intelligence kotlin`; `code intelligence kotlin service projects` for the build a
1313+
sidecar runs."""
1314+
name = f"code intelligence {scope or state.language}"
12971315
if state.status is ServerStatus.INSTALLED and state.warning is not None:
12981316
return CheckResult(name, CheckStatus.WARN, state.warning, fix=FIX_COMMAND)
12991317
if state.status is ServerStatus.INSTALLED:

‎cli/src/coding_study/application/ports.py‎

Lines changed: 8 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -1122,6 +1122,9 @@ class Fetched:
11221122
"""The last day the build runs, as the build said once in place; None when it named none."""
11231123
license: License
11241124
"""The license its release came under, which you accepted."""
1125+
gradle_tooling: str | None = None
1126+
"""For a Linux build a sidecar runs, the version of the Gradle tooling API it bundles, whose
1127+
own distribution its import looks for; None when unknown."""
11251128

11261129

11271130
type ServerProbe = NotInstalled | FileMissing | VersionPrinted | VersionFailed | Unpacked | Fetched
@@ -1161,6 +1164,11 @@ def go_release(self) -> str | None:
11611164
without a Go that runs."""
11621165
...
11631166

1167+
def installed_service_languages(self) -> frozenset[Language]:
1168+
"""The languages of the service projects whose dependencies are installed in the
1169+
workspace, which say what their sidecars need of `.cs/lsp/`."""
1170+
...
1171+
11641172
def license_accepted(self, license: License) -> bool:
11651173
"""Whether the workspace's marker records that you accepted `license`, as it is now."""
11661174
...

0 commit comments

Comments
 (0)