Skip to content

codingame_tools.language

language

Per-language behavior for CodinGame solutions--file extension, local execution, comment syntax, and a cg contribution create starter stub--behind one abstract interface, CgLanguage. This is the only interface outside code should use to access a language; never import a concrete class like CgPython3Language directly, and never branch on a language ID string in puzzle_manager/contribution_manager--go through get_language/ get_language_by_extension instead.

Adding a new language is purely additive: drop in a new flat module under codingame_tools.language.languages (e.g. languages/java.py, exposing a module-level LANGUAGE: CgLanguage singleton--see codingame_tools.language.registry's module docstring for the exact discovery contract) and override whichever CgLanguage capabilities it actually supports. No changes needed anywhere else--codingame_tools.language.registry discovers every module automatically at load time by walking languages/ (no hardcoded list, no exclusion list).

codingame_tools.language.default.CgDefaultLanguage is a pure catch-all for a cg_id CodinGame might add in the future that this client has never seen--every language CodinGame is confirmed to support today has its own real module under languages/, even one that only implements extension (see languages/java.py, languages/cpp.py, etc.).

Debugging is per-language, by necessity. A debugger launch is a fundamentally different mechanism per language, not just a different command: Python runs in-process under debugpy (codingame_tools.test_runner.debug_stdin), while C++ runs gdb inside a container and is driven over a pipe by the cpptools adapter (languages/cpp.py). So CgLanguage.start_debug_session and CgLanguage.vscode_provisioning are per-language rather than shared, and a language gains debugging by implementing them--see codingame_tools.language.vscode for the generated launch-configuration contract that keeps them from colliding.

Containerized languages share one image. Anything needing a toolchain cg can't assume is installed runs in a container built from codingame_tools.language.toolchain's composable fragments--one image for every language, so a workspace runs one container rather than one per language. See _docker.py.

DEFAULT_BUILD_TIMEOUT_SECONDS module-attribute

DEFAULT_BUILD_TIMEOUT_SECONDS = 120.0

Default wall-clock timeout for CgLanguage.build--deliberately far more generous than DEFAULT_RUN_TIMEOUT_SECONDS, because a cold build can involve pulling/building a container image and compiling from scratch. Keeping the two separate is the whole reason building is its own step: a slow first compile must never be reported as a test case timing out.

DEFAULT_RUN_TIMEOUT_SECONDS module-attribute

DEFAULT_RUN_TIMEOUT_SECONDS = 10.0

Default wall-clock timeout for a single local run--a solution under active development can easily infinite-loop; this keeps a bad run from hanging indefinitely rather than reporting it as a (timed-out) failure.

DEFAULT_TOOLCHAIN_BUILD_TIMEOUT_SECONDS module-attribute

DEFAULT_TOOLCHAIN_BUILD_TIMEOUT_SECONDS = 3600.0

Default wall-clock timeout for an explicit cg docker toolchain build, as opposed to the incidental image build DEFAULT_BUILD_TIMEOUT_SECONDS covers.

An order of magnitude more generous because the work is different in kind: composing every supported language downloads a JDK, a .NET SDK and a Node tarball, and pip-builds scientific Python wheels, on a link whose speed cg cannot guess. The run path's 120s is right for "make sure the image is current before this test case"; it would be wrong for "build me the whole thing".

TOOLCHAIN_SUBDIR_NAME module-attribute

TOOLCHAIN_SUBDIR_NAME = 'docker'

Name of the per-user global toolchain directory under the cg data dir--see CgLanguageContext.toolchain_dir.

CgBuildProfile module-attribute

CgBuildProfile = Literal['run', 'debug']

Which flavor of build to produce. "run" is for normal local test execution; "debug" is built for debuggability instead of speed (no optimization, full symbols) and may compile from a different source path so a debugger's recorded paths map back to the file the user actually has open. Interpreted languages ignore this entirely.

CgRunEvent module-attribute

What CgLanguage.run_streaming() yields: zero or more CgRunOutputChunks as they're produced, followed by exactly one CgRunFinished.

BASE_IMAGE module-attribute

BASE_IMAGE = 'debian:bookworm-slim'

The one neutral base every fragment installs onto.

Deliberately not a language image such as gcc:14. A per-language base cannot compose--two of them cannot both be FROM--and it hides the toolchain version in an image tag, which is exactly how the C++ build came to be silently two major gcc releases ahead of CodinGame's.

PREAMBLE module-attribute

PREAMBLE = '# Common to every cg toolchain image, whatever languages it carries.\nENV DEBIAN_FRONTEND=noninteractive\nRUN apt-get update \\\n    && apt-get install -y --no-install-recommends ca-certificates coreutils \\\n    && rm -rf /var/lib/apt/lists/*\nRUN mkdir -p /opt/cg/env.d /build\nWORKDIR /build\n'

Statements shared by every image, before any fragment.

coreutils supplies the timeout and stdbuf the run and debug paths depend on (already present on Debian; named so a swapped base still gets them).

CgDockerCleanResult dataclass

CgDockerCleanResult(containers, images, docker_available)

What clean_managed() tore down.

docker_available instance-attribute

docker_available

False when Docker isn't installed or the daemon isn't reachable--in which case there was, by definition, nothing to clean, and that isn't an error.

CgDockerError

Bases: Exception

A docker command failed. Carries the command's own output, which is almost always the actually-useful part.

CgBuildResult dataclass

CgBuildResult(ok, output, up_to_date)

The outcome of CgLanguage.build.

A result, never an exception, even on failure: a compile error is an expected, routine outcome that callers need to display (not a crash), and raising would make cg puzzle play--which does not wrap its loop in a try/except--traceback on a typo.

ok instance-attribute

ok

Whether a usable artifact now exists. Always True for languages that need no build.

output instance-attribute

output

Compiler/build diagnostics (warnings even on success, errors on failure). Empty when there was nothing to do. Never contains program output--build is a separate subprocess from run precisely so that build noise can never contaminate a solution's stdout.

up_to_date instance-attribute

up_to_date

True when nothing had to be rebuilt because the source was unchanged since the last successful build. Lets a caller stay quiet on the common no-op path.

CgDebugSession dataclass

CgDebugSession(ok, output, details=dict())

A running, ready-to-attach debug target--see CgLanguage.start_debug_session.

ok instance-attribute

ok

Whether the target actually came up. A result rather than an exception for the same reason CgBuildResult is: this is driven by an editor's preLaunchTask, where a failed build is a routine outcome that needs displaying, not a crash.

output instance-attribute

output

What to show the user--build diagnostics when startup failed, otherwise usually empty.

details class-attribute instance-attribute

details = field(default_factory=dict)

Language-specific facts the editor's launch configuration needs, e.g. the container name and the address gdbserver is listening on. Deliberately untyped: what a debug adapter needs varies enough per language that a fixed schema would be wrong for the second one.

CgLanguage

CgLanguage(cg_id)

Bases: ABC

A single CodinGame-supported programming language's behavior: how to run a solution locally, its file extension, its single-line-comment syntax, and a starter stub for a freshly-created contribution.

Deliberately has no @abstractmethods: "not supported by this language yet" is the expected, common state (true for every language but Python3 today, and will stay true incrementally as languages are added one capability at a time), so every capability below has a graceful base-class default (raise, for the one genuinely load-bearing operation; None, for everything else) rather than forcing every new minimal language plugin to write boilerplate "not implemented" overrides. ABC here is used in the structural/ documentation sense--don't construct this directly; use a language plugin's own singleton or codingame_tools.language.get_language()/get_language_by_extension().

Source code in codingame_tools/language/base.py
227
228
def __init__(self, cg_id: str) -> None:
    self._cg_id = cg_id

cg_id property

cg_id

CodinGame's own canonical identifier for this language, e.g. "Python3", "Java", "C++"--the exact string used in TestSession/play/TestSession/submit's programmingLanguageId, and a contribution's solutionLanguage (createContribution/updateContribution).

extension property

extension

The file extension (no leading dot, e.g. "py") conventionally used for this language's solution source, or None if not known. Base implementation: None.

comment_prefix property

comment_prefix

The single-line-comment prefix for this language's source syntax (e.g. "#" for Python3), or None if not known. Base implementation: None. See format_comment.

toolchain_fragment property

toolchain_fragment

This language's contribution to a composed toolchain image, or None if it has no container support.

Usually a fragment that installs nothing and merely depends on a subsystem plus supplies its own activation script -- C and C++ both resolve to one gcc and differ only in whether they export CG_CC or CG_CXX. Installing a toolchain directly here is the exception, reserved for a language nothing else shares.

Base implementation: None, so a language that is only a name today contributes nothing to any image rather than silently inflating one.

supports_vscode property

supports_vscode

Whether build_vscode_provisioning returns anything for this language.

Exists so a caller can tell "already up to date" from "nothing to generate", which are both an empty result. Answering that by calling the builder would need a working directory to build a request from, which a caller reporting an error may not have.

format_comment

format_comment(text)

Format text as a single-line comment in this language's syntax, or None if comment_prefix isn't known for this language--callers must treat None as "no safe placeholder text can be generated," not substitute a guessed comment syntax.

Source code in codingame_tools/language/base.py
250
251
252
253
254
255
def format_comment(self, text: str) -> str | None:
    """Format `text` as a single-line comment in this language's syntax, or `None` if
       `comment_prefix` isn't known for this language--callers must treat `None` as "no safe
       placeholder text can be generated," not substitute a guessed comment syntax."""
    prefix = self.comment_prefix
    return None if prefix is None else f"{prefix} {text}"

build_contribution_create_stub_source async

build_contribution_create_stub_source()

Build a starter data/solution.src for cg contribution create, or None if this language has no suitable one.

The bar here is "a real, working solution", not "a placeholder", and None is a correct answer rather than a gap to fill. Contribution/updateContribution validates server-side: a non-null solutionSource must actually pass every provided test case, and a contribution must provide at least one local and one validator case. cg contribution create therefore seeds a trivial pair (input "1" -> output "1"), and any stub returned here must genuinely satisfy them--Python3's echoes its input for exactly that reason.

A null solutionSource is explicitly allowed and makes the server skip solution validation entirely, so returning None keeps push() working: the contribution manager writes an empty solution.src for it, and sends a blank file as null. Returning a comment-only placeholder would be strictly worse than None: non-null, failing validation, and blocking the push. Do not add one here to "fix" a language that returns None--write a real working solution or leave it.

Contrast format_comment, whose comment-only placeholder is fine for a puzzle: nothing validates a puzzle's local solution file.

Async so a plugin is free to do real work to produce this (render a template, consult a language service) rather than only ever returning a fixed string. Base implementation: None.

Source code in codingame_tools/language/base.py
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
async def build_contribution_create_stub_source(self) -> str | None:
    """Build a starter `data/solution.src` for `cg contribution create`, or `None` if this
       language has no suitable one.

       **The bar here is "a real, working solution", not "a placeholder", and `None` is a
       correct answer rather than a gap to fill.** `Contribution/updateContribution` validates
       server-side: a non-null `solutionSource` must actually pass *every* provided test case,
       and a contribution must provide at least one local and one validator case. `cg
       contribution create` therefore seeds a trivial pair (input `"1"` -> output `"1"`), and
       any stub returned here must genuinely satisfy them--Python3's echoes its input for
       exactly that reason.

       A null `solutionSource` is explicitly allowed and makes the server skip solution
       validation entirely, so returning `None` keeps `push()` working: the contribution manager
       writes an *empty* `solution.src` for it, and sends a blank file as null. Returning a
       *comment-only placeholder* would be strictly worse than `None`: non-null, failing
       validation, and blocking the push. Do not add one here to "fix" a language that returns
       `None`--write a real working solution or leave it.

       Contrast `format_comment`, whose comment-only placeholder *is* fine for a puzzle: nothing
       validates a puzzle's local solution file.

       Async so a plugin is free to do real work to produce this (render a template, consult
       a language service) rather than only ever returning a fixed string. Base
       implementation: `None`."""
    return None

start_debug_session async

start_debug_session(ctx, stdin_text, *, timeout=DEFAULT_BUILD_TIMEOUT_SECONDS)

Get the solution ready to be attached to by a debugger, with stdin_text as its stdin, and return how to reach it.

For a compiled, containerized language this builds the debug profile and starts a stopped gdbserver; the editor then attaches. Languages whose debugger launches the program itself (Python3, via debugpy running codingame_tools.puzzle_manager.debug) don't need this at all and leave it unimplemented.

Redirecting stdin from a file is the whole reason this exists as a separate step: it lets the redirection happen in a command we control, rather than relying on a debug adapter's own stdin handling. But the file has to be one the implementation materializes from stdin_text, not the test case's own file on disk.

That distinction is the entire reason this parameter is text rather than a Path. A contribution's test-case file carries a final newline this client added (see common.text_files), so redirecting from it directly would feed the solution one byte more than cg contribution play does, and one byte more than CodinGame does--verified 2026-08-03 that the server appends nothing. A puzzle's test-case file has no such addition. Taking text makes the caller resolve that, which it is already positioned to do, and leaves implementations with one unambiguous job: put exactly these bytes on stdin.

Raises:

Source code in codingame_tools/language/base.py
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
async def start_debug_session(
            self,
            ctx: CgLanguageContext,
            stdin_text: str,
            *,
            timeout: float = DEFAULT_BUILD_TIMEOUT_SECONDS,
        ) -> CgDebugSession:
    """Get the solution ready to be attached to by a debugger, with `stdin_text` as its stdin,
       and return how to reach it.

       For a compiled, containerized language this builds the debug profile and starts a stopped
       `gdbserver`; the editor then attaches. Languages whose debugger launches the program
       itself (Python3, via `debugpy` running `codingame_tools.puzzle_manager.debug`) don't need
       this at all and leave it unimplemented.

       Redirecting stdin from a *file* is the whole reason this exists as a separate step: it
       lets the redirection happen in a command we control, rather than relying on a debug
       adapter's own stdin handling. But the file has to be one the implementation *materializes*
       from `stdin_text`, not the test case's own file on disk.

       That distinction is the entire reason this parameter is text rather than a `Path`. A
       contribution's test-case file carries a final newline this client added (see
       `common.text_files`), so redirecting from it directly would feed the solution one byte
       more than `cg contribution play` does, and one byte more than CodinGame does--verified
       2026-08-03 that the server appends nothing. A puzzle's test-case file has no such
       addition. Taking text makes the caller resolve that, which it is already positioned to
       do, and leaves implementations with one unambiguous job: put exactly these bytes on stdin.

    Raises:
        CgLanguageOperationNotSupportedError: base implementation always raises.
    """
    raise CgLanguageOperationNotSupportedError(self, "start_debug_session")

stop_debug_session async

stop_debug_session(ctx)

Tear down whatever start_debug_session started. Idempotent, and safe to call when nothing is running--it's wired to a postDebugTask, which fires even if the session never really began. Base implementation: no-op, so a language that needs no teardown inherits correct behavior.

Source code in codingame_tools/language/base.py
317
318
319
320
321
322
async def stop_debug_session(self, ctx: CgLanguageContext) -> None:
    """Tear down whatever `start_debug_session` started. Idempotent, and safe to call when
       nothing is running--it's wired to a `postDebugTask`, which fires even if the session
       never really began. Base implementation: no-op, so a language that needs no teardown
       inherits correct behavior."""
    return None

build_vscode_provisioning async

build_vscode_provisioning(request)

Describe the VS Code run/debug configuration this language wants for the working directory in request, or None if it has no editor integration yet.

Returns a description; it does not write anything. Where the files go and how they merge with the user's existing config is codingame_tools.language.vscode's job--a plugin deliberately has no say in (and no knowledge of) workspace-root resolution.

Base implementation: None.

Source code in codingame_tools/language/base.py
347
348
349
350
351
352
353
354
355
356
async def build_vscode_provisioning(self, request: CgVsCodeRequest) -> CgVsCodeProvisioning | None:
    """Describe the VS Code run/debug configuration this language wants for the working
       directory in `request`, or `None` if it has no editor integration yet.

       Returns a description; it does not write anything. Where the files go and how they merge
       with the user's existing config is `codingame_tools.language.vscode`'s job--a plugin
       deliberately has no say in (and no knowledge of) workspace-root resolution.

       Base implementation: `None`."""
    return None

build async

build(ctx, *, profile='run', timeout=DEFAULT_BUILD_TIMEOUT_SECONDS)

Produce whatever artifact run_streaming() needs, if this language needs one at all.

A separate, explicit step rather than something run_streaming() does implicitly, so that a caller can display build diagnostics separately from program output, report a compile error once instead of once per test case, and give building its own (much more generous) timeout. It must be cheap to call repeatedly: a language that compiles is expected to detect that the source is unchanged since the last successful build and return up_to_date=True having done nothing.

Base implementation: an immediate no-op success, which is correct for every interpreted language.

Returns:

  • CgBuildResult

    A CgBuildResult. Never raises on a build failure (a compile error is a routine

  • CgBuildResult

    outcome, not a crash)--check .ok.

Source code in codingame_tools/language/base.py
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
async def build(
            self,
            ctx: CgLanguageContext,
            *,
            profile: CgBuildProfile = "run",
            timeout: float = DEFAULT_BUILD_TIMEOUT_SECONDS,
        ) -> CgBuildResult:
    """Produce whatever artifact `run_streaming()` needs, if this language needs one at all.

       A **separate, explicit step** rather than something `run_streaming()` does implicitly, so
       that a caller can display build diagnostics separately from program output, report a
       compile error once instead of once per test case, and give building its own (much more
       generous) timeout. It must be cheap to call repeatedly: a language that compiles is
       expected to detect that the source is unchanged since the last successful build and
       return `up_to_date=True` having done nothing.

       Base implementation: an immediate no-op success, which is correct for every interpreted
       language.

    Returns:
        A `CgBuildResult`. Never raises on a *build* failure (a compile error is a routine
        outcome, not a crash)--check `.ok`.
    """
    return CgBuildResult(ok=True, output="", up_to_date=True)

run_streaming

run_streaming(ctx, input_text, *, timeout=DEFAULT_RUN_TIMEOUT_SECONDS)

Run the solution described by ctx, feeding input_text to stdin, yielding CgRunOutputChunks tagged by stream as they're produced and ending with exactly one CgRunFinished carrying the aggregated CgRunResult. See CgRunOutputChunk for the stdout/stderr ordering caveat.

Does not build. A language that needs a build artifact expects build() to have been called first and should fail cleanly if it hasn't.

Raises:

  • CgLanguageOperationNotSupportedError

    the base implementation always raises this, immediately (not lazily on iteration); only a language that actually supports local execution overrides it.

Source code in codingame_tools/language/base.py
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
def run_streaming(
            self,
            ctx: CgLanguageContext,
            input_text: str,
            *,
            timeout: float = DEFAULT_RUN_TIMEOUT_SECONDS,
        ) -> AsyncIterator[CgRunEvent]:
    """Run the solution described by `ctx`, feeding `input_text` to stdin, yielding
       `CgRunOutputChunk`s tagged by stream as they're produced and ending with exactly one
       `CgRunFinished` carrying the aggregated `CgRunResult`. See `CgRunOutputChunk` for the
       stdout/stderr ordering caveat.

       Does **not** build. A language that needs a build artifact expects `build()` to have been
       called first and should fail cleanly if it hasn't.

    Raises:
        CgLanguageOperationNotSupportedError: the base implementation always raises this,
                                               immediately (not lazily on iteration); only a
                                               language that actually supports local
                                               execution overrides it.
    """
    raise CgLanguageOperationNotSupportedError(self, "run_streaming")

run async

run(ctx, input_text, *, timeout=DEFAULT_RUN_TIMEOUT_SECONDS)

Convenience wrapper for a caller that doesn't need progressive output: drains run_streaming() and returns its final CgRunResult. Not overridden by any language plugin--every plugin gets this for free once it implements run_streaming().

Raises:

Source code in codingame_tools/language/base.py
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
async def run(
            self,
            ctx: CgLanguageContext,
            input_text: str,
            *,
            timeout: float = DEFAULT_RUN_TIMEOUT_SECONDS,
        ) -> CgRunResult:
    """Convenience wrapper for a caller that doesn't need progressive output: drains
       `run_streaming()` and returns its final `CgRunResult`. Not overridden by any language
       plugin--every plugin gets this for free once it implements `run_streaming()`.

    Raises:
        CgLanguageOperationNotSupportedError: see `run_streaming()`.
    """
    async for event in self.run_streaming(ctx, input_text, timeout=timeout):
        if isinstance(event, CgRunFinished):
            return event.result
    raise AssertionError("run_streaming() ended without a CgRunFinished event")

CgLanguageContext dataclass

CgLanguageContext(root, solution_file, meta_dir, mount_root, toolchain_dir, toolchain_languages=None, toolchain_image=None)

Everything a CgLanguage needs to know about where a solution lives, independent of any particular run.

Deliberately infallible and identity-free: constructing one must never require a working directory to have been imported (no reading puzzle.json/contribution.json, no network, no failure modes). A manager can hand one out for a directory holding nothing but a solution file. input_text/timeout are deliberately not here--those are per-call, not per-context, and folding them in would defeat the "build once, run many" split.

root instance-attribute

root

The puzzle/contribution working directory root (resolved absolute)--the directory holding data/ and .meta/. Not data/, because .meta/ sits beside it and matters to a build.

solution_file instance-attribute

solution_file

<root>/data/solution.<ext>--the one real, editable, submittable file, carrying its language's own extension.

There is exactly one path here, and that is the point. cg used to keep a fixed data/solution.src with a solution.<ext> symlink beside it, and a debug build had to choose between them: compiling the link recorded a path the debugger then realpath'd back to the real file, so the editor navigated away from the file the breakpoints were set in, and the mapping that fixed navigation broke binding instead. One real file with the right extension removes the choice.

meta_dir instance-attribute

meta_dir

The working directory's .meta/ (always <root>/.meta)--gitignored scratch space. Used for per-root toolchain overrides and generated editor files.

mount_root instance-attribute

mount_root

The directory a containerized language bind-mounts, at its own path inside the container (see codingame_tools.language._docker). Normally the VS Code workspace root containing root, so that in-container paths and host paths are the same string--which is what lets a generated debug configuration drop sourceFileMap entirely, and lets one container serve every working directory in the workspace.

Always contains root. Falls back to root itself when there is no enclosing workspace, in which case a containerized language behaves exactly as it did when it mounted the working directory.

toolchain_dir instance-attribute

toolchain_dir

The per-user global toolchain directory (<cg data dir>/docker), holding the shared, user-tweakable per-language image definitions. Global rather than per-root so that tweaking a language's toolchain once applies to every puzzle and contribution using that language.

toolchain_languages class-attribute instance-attribute

toolchain_languages = None

Languages the container toolchain should carry, or None for every language cg supports.

Defaulted because most callers don't care: the default is the right answer, and a context is constructible without knowing anything about images.

toolchain_image class-attribute instance-attribute

toolchain_image = None

A prebuilt toolchain image tag to use instead of composing and building one locally. Skips the Dockerfile entirely -- the point of a published image being a pull rather than a build.

CgLanguageOperationNotSupportedError

CgLanguageOperationNotSupportedError(language, operation)

Bases: Exception

Raised by a CgLanguage method whose base-class default means "not implemented for this language yet" (currently only run_streaming/run). Callers are expected to catch and handle this directly--there's no manager-specific translation wrapper.

Source code in codingame_tools/language/base.py
431
432
433
434
def __init__(self, language: CgLanguage, operation: str) -> None:
    self.cg_id = language.cg_id
    self.operation = operation
    super().__init__(f"{language.cg_id!r} does not support {operation!r} yet.")

CgRunFinished dataclass

CgRunFinished(result)

The final event yielded by CgLanguage.run_streaming()--every run ends with exactly one of these, carrying the same aggregated result CgLanguage.run() returns.

CgRunOutputChunk dataclass

CgRunOutputChunk(stream, text)

A piece of output produced by a running solution, as soon as it's available.

stdout and stderr are two independent, separately-buffered OS pipes--stream says which one this chunk came from, but the order two chunks from different streams are yielded in is only the order this reader happened to receive them, not a guarantee about the target process's true relative write order between the two streams. Treat the two streams as separate; don't rely on cross-stream ordering.

CgRunResult dataclass

CgRunResult(output, stderr, returncode, timed_out)

The outcome of running a solution file against one input, once it's finished.

output instance-attribute

output

Everything the solution wrote to stdout.

stderr instance-attribute

stderr

Everything the solution wrote to stderr--not treated as failure by itself (a solution may legitimately write debug output there), but surfaced for inspection when a run does fail.

returncode instance-attribute

returncode

The subprocess's exit code (0 conventionally means "ran without crashing"). Meaningless (always -1) when timed_out is True.

timed_out instance-attribute

timed_out

Whether the run was killed for exceeding its timeout (see DEFAULT_RUN_TIMEOUT_SECONDS). output/stderr hold whatever was captured before the kill.

CgDefaultLanguage

CgDefaultLanguage(cg_id)

Bases: CgLanguage

No overrides--relies entirely on CgLanguage's base-class defaults (extension unknown, comment syntax unknown, no stub, no local execution). Used only for a cg_id CodinGame might add in the future that this client has never seen--every language CodinGame is confirmed to support today has its own real module under codingame_tools.language.languages, even one that only implements extension, so it never falls back to this. Bound to the real cg_id it was looked up with (never a generic placeholder), so error messages/logging naming .cg_id are always accurate.

Source code in codingame_tools/language/base.py
227
228
def __init__(self, cg_id: str) -> None:
    self._cg_id = cg_id

CgToolchainError

Bases: Exception

Raised for an unresolvable fragment set--an unknown slug, or a dependency cycle.

CgToolchainFragment dataclass

CgToolchainFragment(slug, version, depends_on=(), dockerfile='', env_script='')

One composable piece of a toolchain image.

slug instance-attribute

slug

Stable identifier, used in dependency edges, in the generated header, and as the activation script's filename. Lowercase, no spaces--it appears in shell and Dockerfile contexts.

version instance-attribute

version

Bumped whenever dockerfile or env_script changes, so an unmodified generated Dockerfile can be detected as stale and regenerated. Deliberately per fragment rather than one global template version: changing the Rust fragment shouldn't invalidate a C++-only image.

depends_on class-attribute instance-attribute

depends_on = ()

Slugs that must be installed before this one. The mechanism that lets several languages share a toolchain (C and C++ -> gcc11) and lets conflicting ones coexist (java -> jdk21 while scala -> jvm8).

dockerfile class-attribute instance-attribute

dockerfile = ''

Statements inserted verbatim. Legitimately empty: a language whose toolchain is entirely supplied by a subsystem contributes only its dependency edge and its activation script, and emits nothing here. An empty fragment produces no Dockerfile section and so no extra layer.

env_script class-attribute instance-attribute

env_script = ''

Body of /opt/cg/env.d/<slug>.sh, if this fragment needs one. The composer prepends the . <dep>.sh lines itself, so a fragment only writes its own exports.

CgVsCodeMergeError

Bases: Exception

Raised when an existing VS Code config file can't be safely merged into--almost always because it's JSONC (comments/trailing commas) rather than strict JSON. Refusing is deliberate: silently rewriting would drop the user's comments and any content our parser didn't understand.

CgVsCodeProvisioning dataclass

CgVsCodeProvisioning(configurations=list(), inputs=list(), tasks=list(), files=dict(), retired_names=list(), obsolete_files=list(), recommended_extensions=list())

What a language plugin wants written. Everything is optional--a plugin supplies only the pieces it actually has.

configurations class-attribute instance-attribute

configurations = field(default_factory=list)

Entries for launch.json's configurations. Each name must come from entry_name(), so re-provisioning replaces exactly cg's own entries for this language and leaves everything else--the user's, and other languages'--alone.

Must not bake in anything specific to request.ctx.root: one entry serves every working directory in the workspace (see the module docstring).

inputs class-attribute instance-attribute

inputs = field(default_factory=list)

Entries for launch.json's inputs. Each id must start with cg_ (see _OWNED_INPUT_RE), for the same reason.

Nothing populates this today: the pickString test-case pickers it existed for are what the .meta/-based selection replaced. Kept because it is a real launch.json capability a future plugin may need, and because write_provisioning must go on pruning 1.0.x leftovers.

tasks class-attribute instance-attribute

tasks = field(default_factory=list)

Entries for tasks.json's tasks. Each label must come from entry_name(), and the same "nothing per-directory" rule applies.

files class-attribute instance-attribute

files = field(default_factory=dict)

Extra files to write, keyed by path relative to the working directory root (not the workspace root)--e.g. .meta/.devcontainer/devcontainer.json.

Belongs under .meta/. These files are generated and not the user's to maintain, and .meta/ is the only part of a working directory that is gitignored, so anywhere else they'd be committed into whatever repository tracks the directory. That also rules out data/ specifically, which for a contribution is a git work tree where a stray generated file would be swept into the server tree by git add -A or deleted by git clean -fd.

retired_names class-attribute instance-attribute

retired_names = field(default_factory=list)

Configuration names / task labels earlier versions of this plugin generated and no longer do, so they are removed rather than orphaned.

Mostly a backstop. _is_owned_by_this_run already replaces everything in this language's namespace, so renaming an action is handled with no declaration at all. This is for the rarer change that moves an entry out of that namespace--a language's cg_id changing, say-- where nothing else would connect the old name to the new one.

The files equivalent is obsolete_files. Both exist for the same reason: what cg generated is cg's to clean up, and nothing else's.

obsolete_files class-attribute instance-attribute

obsolete_files = field(default_factory=list)

Paths (relative to the working directory root, like files) that earlier versions of this plugin generated and that should now be deleted.

Generated files are cg's to clean up: a user who upgrades shouldn't be left with a stale devcontainer.json in a location nothing writes to any more, silently offering VS Code a "Reopen in Container" that no longer reflects anything. The launch.json equivalent is _OWNED_NAME_RE.

Only ever names specific files, never directories, and a containing directory is removed only if deleting the file leaves it empty--so a path the user has since put their own work in is left alone.

recommended_extensions class-attribute instance-attribute

recommended_extensions = field(default_factory=list)

Extension IDs to merge into extensions.json's recommendations (union, never removing the user's own--there's no reliable way to tell which ones cg previously added).

CgVsCodeRequest dataclass

CgVsCodeRequest(ctx, workspace_root, debug_adapter_logging=False)

What a language plugin is being asked to generate configuration for.

Deliberately thin. It used to also carry the working directory's kind and its full list of test cases, because a generated debug configuration had to name both; now ${file} and .meta/selected-test.json answer those at launch time, so a plugin needs neither and the configuration it produces is the same for every working directory in the workspace.

ctx instance-attribute

ctx

The CgLanguageContext for the working directory (typed loosely to avoid a circular import with base--see codingame_tools.language.base.CgLanguageContext).

Present for the language's own needs (its toolchain paths, say), not so generated entries can bake in this directory--see the module docstring.

workspace_root instance-attribute

workspace_root

Where .vscode/ will be written--see find_workspace_root. Often not ctx.root.

Also the directory a containerized language must mount, so that paths inside the container match the paths VS Code has open--see codingame_tools.language._docker.

debug_adapter_logging class-attribute instance-attribute

debug_adapter_logging = False

Generate a configuration that logs the debug adapter's own conversation with the debugger.

Off by default because it is loud and slows a session down. It exists because the debug adapter is the one component of the stack that can't be exercised from a terminal: gdbserver, stdin redirection, stepping and symbol resolution can all be driven by hand and checked, but what VS Code's adapter actually sends and receives can only be observed from inside a real session. When a session misbehaves and everything underneath it demonstrably works, this is the remaining place to look.

A plugin should turn on whatever its adapter offers, and quieten anything so voluminous it would bury the exchange.

build_image_content async

build_image_content(content, *, tag, platforms=(), push=False, timeout, quiet=False)

Build a Dockerfile given as text, unconditionally--no "is it already built?" check.

Distinct from ensure_image, which is the hot path called before every run and skips the build whenever the content-addressed tag already exists. This is the explicit cg docker toolchain build: the user asked for a build, so they get one, and they may ask for architectures the local daemon can't even load.

Uses the same empty build context as ensure_image (see there): nothing is ever COPY'd in, because solutions are bind-mounted at run time.

Parameters:

  • platforms (Sequence[str], default: () ) –

    e.g. ["linux/amd64", "linux/arm64"]. Empty means the host's own architecture via plain docker build. Anything else requires buildx.

  • push (bool, default: False ) –

    Push to a registry instead of loading into the local daemon.

Raises:

  • CgDockerError

    if buildx is needed but missing, if more than one platform is requested without push (a hard Docker limitation--see below), or if the build fails.

Source code in codingame_tools/language/_docker.py
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
async def build_image_content(
            content: str,
            *,
            tag: str,
            platforms: Sequence[str] = (),
            push: bool = False,
            timeout: float,
            quiet: bool = False,
        ) -> None:
    """Build a Dockerfile given as text, unconditionally--no "is it already built?" check.

       Distinct from `ensure_image`, which is the hot path called before every run and skips the
       build whenever the content-addressed tag already exists. This is the explicit
       `cg docker toolchain build`: the user asked for a build, so they get one, and they may ask
       for architectures the local daemon can't even load.

       Uses the same **empty build context** as `ensure_image` (see there): nothing is ever COPY'd
       in, because solutions are bind-mounted at run time.

    Args:
        platforms: e.g. `["linux/amd64", "linux/arm64"]`. Empty means the host's own architecture
                    via plain `docker build`. Anything else requires buildx.
        push:      Push to a registry instead of loading into the local daemon.

    Raises:
        CgDockerError: if buildx is needed but missing, if more than one platform is requested
                        without `push` (a hard Docker limitation--see below), or if the build fails.
    """
    if len(platforms) > 1 and not push:
        # Not a cg restriction: `docker buildx build --load` can only load a *single* platform into
        # the local image store, because the daemon's image format has no place to put a manifest
        # list. A multi-arch build therefore has to go somewhere that does understand one, i.e. a
        # registry. Caught here with an explanation rather than letting buildx fail obscurely.
        raise CgDockerError(
                f"cannot build {len(platforms)} platforms ({', '.join(platforms)}) into the local "
                "Docker daemon: a multi-platform image is a manifest list, which `--load` cannot "
                "represent. Either build one platform at a time, or add --push to publish the "
                "multi-arch image to a registry."
            )

    if platforms and not await buildx_available():
        raise CgDockerError(
                "multi-platform builds need `docker buildx`, which isn't available. It ships with "
                "Docker Desktop and recent Docker Engine; without it, omit --platform to build for "
                "this machine's own architecture."
            )

    # --label is applied to the built image whatever the Dockerfile says, which is what lets
    # `cg docker clean` find cg's own images without guessing from tag names.
    label = ["--label", f"{_LABEL_MANAGED}=1"]
    if platforms or push:
        argv = ["buildx", "build", *label]
        if platforms:
            argv += ["--platform", ",".join(platforms)]
        # --load puts the result in the local daemon (buildx otherwise leaves it in its own cache
        # and the image would appear not to exist); --push sends it to a registry instead.
        argv += ["-t", tag, "--push" if push else "--load", "-"]
    else:
        argv = ["build", *label, "-t", tag, "-"]

    result = await _docker(argv, timeout=timeout, input_text=content, inherit_stderr=not quiet)
    if result.timed_out:
        raise CgDockerError(
                f"building the toolchain image timed out after {timeout}s. A cold multi-language "
                "build pulls a base image and several toolchains--retry, or raise the timeout."
            )
    if not result.ok:
        detail = result.combined.strip()
        detail = f"\n{detail}" if detail else " (see the docker build output above)"
        raise CgDockerError(f"failed to build the toolchain image:{detail}")

clean_managed async

clean_managed()

Remove every container and image cg created.

Always safe: a container holds nothing but build artifacts, and an image is rebuilt from Dockerfiles that live on disk--so there is no user work here to lose, and everything is recreated on the next build. That's why this neither prompts nor needs a --force.

Containers go first: an image still in use by a container can't be removed.

Source code in codingame_tools/language/_docker.py
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
async def clean_managed() -> CgDockerCleanResult:
    """Remove every container and image cg created.

       Always safe: a container holds nothing but build artifacts, and an image is rebuilt from
       Dockerfiles that live on disk--so there is no user work here to lose, and everything is
       recreated on the next build. That's why this neither prompts nor needs a --force.

       Containers go first: an image still in use by a container can't be removed."""
    if shutil.which(_DOCKER) is None:
        return CgDockerCleanResult(containers=[], images=[], docker_available=False)

    containers = [name for name, _root in await list_managed_containers()]
    for name in containers:
        await remove_container(name)

    images = await list_managed_images()
    removed_images: list[str] = []
    for image_id in images:
        # --force because an image usually carries both its content-addressed tag and the :latest
        # alias, and docker refuses an untagged removal of a multi-tag image otherwise.
        result = await _docker(["rmi", "--force", image_id], timeout=120.0)
        if result.ok:
            removed_images.append(image_id)
    return CgDockerCleanResult(
            containers=containers, images=removed_images, docker_available=True)

compose_dockerfile

compose_dockerfile(directory)

The effective Dockerfile: cg's base with the user's additions appended. Never written to disk--it's piped straight to docker build.

Source code in codingame_tools/language/_docker.py
326
327
328
329
def compose_dockerfile(directory: Path) -> str:
    """The effective Dockerfile: cg's base with the user's additions appended. Never written to
       disk--it's piped straight to `docker build`."""
    return compose_with_base(directory, (directory / BASE_DOCKERFILE_NAME).read_text(encoding="utf-8"))

compose_with_base

compose_with_base(directory, base)

compose_dockerfile, but for a base that has not been written to directory yet.

Exists so a read-only question--"what tag would these languages produce?"--can be answered without the side effect of replacing the user's base.dockerfile. The tag has to cover the composed content, since custom.dockerfile is part of what gets built; computing it from the base alone would report a tag no image ever has.

Source code in codingame_tools/language/_docker.py
332
333
334
335
336
337
338
339
340
341
342
343
344
345
def compose_with_base(directory: Path, base: str) -> str:
    """`compose_dockerfile`, but for a base that has not been written to `directory` yet.

       Exists so a read-only question--"what tag would these languages produce?"--can be answered
       without the side effect of replacing the user's base.dockerfile. The tag has to cover the
       *composed* content, since custom.dockerfile is part of what gets built; computing it from the
       base alone would report a tag no image ever has."""
    custom_path = directory / CUSTOM_DOCKERFILE_NAME
    if not custom_path.is_file():
        return base
    custom = custom_path.read_text(encoding="utf-8")
    if not custom.strip():
        return base
    return f"{base}\n# --- {CUSTOM_DOCKERFILE_NAME} ---\n{custom}"

ensure_base_dockerfile

ensure_base_dockerfile(directory, rendered)

Make sure directory holds the current base.dockerfile (and a commented starter custom.dockerfile), regenerating the base when that's safe.

  • Missing -> write it.
  • Present, unmodified, but composed from different fragments -> silently regenerate. The normal upgrade path; asks nothing of the user.
  • Present and edited -> never overwritten; a stale one produces a warning instead. That is the escape hatch for swapping FROM or pinning a toolchain outright.

Parameters:

  • rendered (str) –

    What the current fragments produce -- see codingame_tools.language.toolchain.render_dockerfile.

Returns:

  • tuple[Path, list[str]]

    The base file's path, and any warnings to surface once.

Source code in codingame_tools/language/_docker.py
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
def ensure_base_dockerfile(directory: Path, rendered: str) -> tuple[Path, list[str]]:
    """Make sure `directory` holds the current `base.dockerfile` (and a commented starter
       `custom.dockerfile`), regenerating the base when that's safe.

       - Missing -> write it.
       - Present, unmodified, but composed from different fragments -> silently regenerate. The
         normal upgrade path; asks nothing of the user.
       - Present and edited -> **never** overwritten; a stale one produces a warning instead. That
         is the escape hatch for swapping `FROM` or pinning a toolchain outright.

    Args:
        rendered: What the current fragments produce -- see
                   `codingame_tools.language.toolchain.render_dockerfile`.

    Returns:
        The base file's path, and any warnings to surface once.
    """
    directory.mkdir(parents=True, exist_ok=True)
    base_path = directory / BASE_DOCKERFILE_NAME
    custom_path = directory / CUSTOM_DOCKERFILE_NAME
    warnings: list[str] = []

    wanted = fragment_manifest(rendered)
    state = read_base_dockerfile_state(base_path)
    if not state.exists or (not state.edited and state.fragments != wanted):
        base_path.write_text(rendered, encoding="utf-8")
    elif state.edited and state.fragments != wanted:
        warnings.append(
                f"{base_path} has local edits and was composed from different toolchain fragments"
                f"{'' if state.fragments is None else f' ({state.fragments}, current {wanted})'}"
                f"--leaving it alone. Move your changes to {CUSTOM_DOCKERFILE_NAME} and delete the "
                "base to pick up the new one."
            )

    if not custom_path.exists():
        custom_path.write_text(
                _CUSTOM_DOCKERFILE_TEMPLATE.format(base_name=BASE_DOCKERFILE_NAME),
                encoding="utf-8",
            )
    return base_path, warnings

ensure_image async

ensure_image(directory, *, timeout, quiet=False)

Build (or reuse) the toolchain image for the Dockerfiles in directory, returning its tag.

Uses an empty build context (docker build -f - -): nothing is ever COPY'd in, since the solution is bind-mounted at run time instead. That keeps builds fast and means editing a solution never invalidates the image.

Docker's own layer cache makes a rebuild of an unchanged Dockerfile nearly free, so this is cheap to call before every build; the image is only genuinely rebuilt when its content- addressed tag changes.

Parameters:

  • quiet (bool, default: False ) –

    Capture docker build output instead of letting it through to stderr. Off by default because a cold build is slow and its progress is the only feedback.

Source code in codingame_tools/language/_docker.py
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
async def ensure_image(
            directory: Path, *, timeout: float, quiet: bool = False,
        ) -> str:
    """Build (or reuse) the toolchain image for the Dockerfiles in `directory`, returning its tag.

       Uses an **empty build context** (`docker build -f - -`): nothing is ever `COPY`'d in, since
       the solution is bind-mounted at run time instead. That keeps builds fast and means editing a
       solution never invalidates the image.

       Docker's own layer cache makes a rebuild of an unchanged Dockerfile nearly free, so this is
       cheap to call before every build; the image is only genuinely rebuilt when its content-
       addressed tag changes.

    Args:
        quiet: Capture `docker build` output instead of letting it through to stderr. Off by
                default because a cold build is slow and its progress is the only feedback.
    """
    content = compose_dockerfile(directory)
    tag = image_tag_for(content)

    exists = await _docker(["image", "inspect", tag], timeout=30.0)
    if exists.ok:
        # Re-point the alias even when the image is already built: switching between two existing
        # images (e.g. undoing a custom.dockerfile edit) hits this path, and :latest must follow.
        await _tag_latest(tag)
        return tag

    # `docker build -` (a bare `-`, never `-f - -`) reads the Dockerfile from stdin and uses an
    # *empty* context--docker rejects using stdin for both. An empty context is exactly right here:
    # nothing is ever COPY'd in, so editing a solution can't invalidate the image.
    result = await _docker(
            # --label is applied to the built image regardless of what the Dockerfile says, which is
            # what makes `cg docker clean` able to find cg's own images without guessing from tag
            # names (and without ever touching an unrelated image that happens to be named "cg-*").
            ["build", "--label", f"{_LABEL_MANAGED}=1", "-t", tag, "-"],
            timeout=timeout, input_text=content, inherit_stderr=not quiet,
        )
    if result.timed_out:
        raise CgDockerError(
                f"building the toolchain image timed out after {timeout}s. A cold build "
                "pulls a base image and can take a while--retry, or raise --build-timeout."
            )
    if not result.ok:
        detail = result.combined.strip()
        # With inherit_stderr, docker's own diagnostics already went straight to the terminal--say
        # so rather than reporting a failure with a suspiciously empty explanation.
        detail = f"\n{detail}" if detail else " (see the docker build output above)"
        raise CgDockerError(
                f"failed to build the toolchain image from {directory}:{detail}")
    await _tag_latest(tag)
    return tag

image_tag_for

image_tag_for(dockerfile_content)

Content-addressed image tag. Keying on the Dockerfile's content rather than on the working directory means every root sharing the global toolchain shares one image, and any change--a cg template bump or a user tweak--produces a new tag automatically, so nothing ever runs against a stale image.

Source code in codingame_tools/language/_docker.py
220
221
222
223
224
225
def image_tag_for(dockerfile_content: str) -> str:
    """Content-addressed image tag. Keying on the Dockerfile's *content* rather than on the working
       directory means every root sharing the global toolchain shares one image, and any change--a
       cg template bump or a user tweak--produces a new tag automatically, so nothing ever runs
       against a stale image."""
    return f"{IMAGE_REPOSITORY}:{_short_hash(dockerfile_content)}"

latest_alias_for

latest_alias_for()

The stable, non-content-addressed tag kept pointing at the current toolchain image.

Generated devcontainer.json files reference this rather than the real content-addressed tag: a devcontainer.json is written once and read by VS Code much later, so embedding a hash that changes on the next toolchain tweak would leave it pointing at an image that no longer exists. cg's own build/run/debug paths always use the exact tag--this alias exists purely for tools that need a name stable across rebuilds.

Source code in codingame_tools/language/_docker.py
410
411
412
413
414
415
416
417
418
def latest_alias_for() -> str:
    """The stable, *non*-content-addressed tag kept pointing at the current toolchain image.

       Generated `devcontainer.json` files reference this rather than the real content-addressed
       tag: a devcontainer.json is written once and read by VS Code much later, so embedding a hash
       that changes on the next toolchain tweak would leave it pointing at an image that no longer
       exists. cg's own build/run/debug paths always use the exact tag--this alias exists purely for
       tools that need a name stable across rebuilds."""
    return f"{IMAGE_REPOSITORY}:latest"

list_managed_containers async

list_managed_containers()

Every cg-created container on this machine, as (name, root) pairs.

Found by the cg.root label every cg container carries, so this catches containers for languages this build doesn't know about and for working directories that no longer exist.

Source code in codingame_tools/language/_docker.py
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
async def list_managed_containers() -> list[tuple[str, str]]:
    """Every cg-created container on this machine, as `(name, root)` pairs.

       Found by the `cg.root` label every cg container carries, so this catches containers for
       languages this build doesn't know about and for working directories that no longer exist."""
    if shutil.which(_DOCKER) is None:
        return []
    listed = await run_argv_capture(
            [
                _DOCKER, "ps", "-a", "--filter", f"label={_LABEL_ROOT}",
                "--format", '{{.Names}}\t{{.Label "' + _LABEL_ROOT + '"}}',
            ],
            timeout=60.0,
        )
    if not listed.ok:
        return []
    pairs: list[tuple[str, str]] = []
    for line in listed.stdout.splitlines():
        name, _, root = line.partition("\t")
        if name.strip():
            pairs.append((name.strip(), root.strip()))
    return pairs

remove_containers_for_root async

remove_containers_for_root(root, *, except_name=None)

Remove every cg container bound to root, whatever language--for use when a working directory is being deleted, and to enforce one-container-per-working-directory.

Matches on the cg.root label rather than recomputing the name, so it catches containers for languages this build doesn't know about. Silently does nothing when Docker isn't installed or the daemon is down: failing to tidy up a container must never block deleting a directory.

Parameters:

  • except_name (str | None, default: None ) –

    Leave this one alone. Used by ensure_container to sweep away containers for a working directory's previous language while keeping the current one.

Returns:

  • list[str]

    The names removed (empty if none, or if Docker is unavailable).

Source code in codingame_tools/language/_docker.py
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
async def remove_containers_for_root(root: Path, *, except_name: str | None = None) -> list[str]:
    """Remove every cg container bound to `root`, whatever language--for use when a working
       directory is being deleted, and to enforce one-container-per-working-directory.

       Matches on the `cg.root` label rather than recomputing the name, so it catches
       containers for languages this build doesn't know about. Silently does nothing when Docker
       isn't installed or the daemon is down: failing to tidy up a container must never block
       deleting a directory.

    Args:
        except_name: Leave this one alone. Used by `ensure_container` to sweep away containers for
                      a working directory's *previous* language while keeping the current one.

    Returns:
        The names removed (empty if none, or if Docker is unavailable).
    """
    if shutil.which(_DOCKER) is None:
        return []
    listed = await run_argv_capture(
            [_DOCKER, "ps", "-a", "--filter", f"label={_LABEL_ROOT}={root}", "--format", "{{.Names}}"],
            timeout=60.0,
        )
    if not listed.ok:
        return []
    names = [n for n in listed.stdout.split() if n and n != except_name]
    for name in names:
        await remove_container(name)
    return names

tag_image async

tag_image(source, target)

Point target at the image source already names. Both must be local.

Source code in codingame_tools/language/_docker.py
421
422
423
async def tag_image(source: str, target: str) -> None:
    """Point `target` at the image `source` already names. Both must be local."""
    await _docker(["tag", source, target], timeout=60.0)

get_language

get_language(cg_id)

Look up the CgLanguage for a CodinGame protocol language ID.

Always succeeds: returns the real implementation if cg_id matches a discovered language plugin, or--for a cg_id this client has no record of at all--a CgDefaultLanguage bound to that ID anyway (memoized, so repeated lookups of the same unrecognized ID return the same object).

Source code in codingame_tools/language/registry.py
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
def get_language(cg_id: str) -> CgLanguage:
    """Look up the `CgLanguage` for a CodinGame protocol language ID.

       Always succeeds: returns the real implementation if `cg_id` matches a discovered language
       plugin, or--for a `cg_id` this client has no record of at all--a `CgDefaultLanguage` bound
       to that ID anyway (memoized, so repeated lookups of the same unrecognized ID return the
       same object).
    """
    language = _by_cg_id.get(cg_id)
    if language is not None:
        return language
    unknown = _unknown_by_cg_id.get(cg_id)
    if unknown is None:
        unknown = CgDefaultLanguage(cg_id)
        _unknown_by_cg_id[cg_id] = unknown
    return unknown

get_language_by_extension

get_language_by_extension(filename_or_extension)

Look up the CgLanguage whose extension matches filename_or_extension (a bare extension, with or without a leading '.', or a full filename--only the suffix after the last '.' is considered; case-insensitive).

Returns:

  • CgLanguage | None

    The matching CgLanguage, or None if no known language claims this extension--there's

  • CgLanguage | None

    no reasonable default to fall back to, unlike get_language.

Source code in codingame_tools/language/registry.py
81
82
83
84
85
86
87
88
89
90
91
92
93
def get_language_by_extension(filename_or_extension: str) -> CgLanguage | None:
    """Look up the `CgLanguage` whose `extension` matches `filename_or_extension` (a bare
       extension, with or without a leading '.', or a full filename--only the suffix after the
       last '.' is considered; case-insensitive).

    Returns:
        The matching `CgLanguage`, or `None` if no known language claims this extension--there's
        no reasonable default to fall back to, unlike `get_language`.
    """
    ext = filename_or_extension.lower()
    if "." in ext:
        ext = ext.rsplit(".", 1)[1]
    return _by_extension.get(ext)

list_language_cg_ids

list_language_cg_ids()

The cg_ids of every discovered language plugin (sorted)--every language CodinGame is confirmed to support has one, whether or not it implements local execution.

Source code in codingame_tools/language/registry.py
96
97
98
99
def list_language_cg_ids() -> tuple[str, ...]:
    """The `cg_id`s of every discovered language plugin (sorted)--every language CodinGame is
       confirmed to support has one, whether or not it implements local execution."""
    return tuple(sorted(_by_cg_id))

all_fragments

all_fragments()

Every fragment cg knows, keyed by slug.

Built fresh rather than cached: the language registry is itself lazily discovered, and a stale copy here would be a second source of truth for something that already has one.

Source code in codingame_tools/language/toolchain/registry.py
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
def all_fragments() -> dict[str, CgToolchainFragment]:
    """Every fragment cg knows, keyed by slug.

       Built fresh rather than cached: the language registry is itself lazily discovered, and a
       stale copy here would be a second source of truth for something that already has one."""
    # Imported here, not at module scope: the language registry imports every plugin, each of which
    # imports `base`, which imports this package. At module scope that is a cycle -- the same one
    # `codingame_tools.language.vscode` resolves the same way.
    from ..registry import get_language, list_language_cg_ids

    table: dict[str, CgToolchainFragment] = {f.slug: f for f in SUBSYSTEMS}
    for cg_id in list_language_cg_ids():
        fragment = get_language(cg_id).toolchain_fragment
        if fragment is None:
            continue
        existing = table.get(fragment.slug)
        if existing is not None and existing != fragment:
            raise CgToolchainError(
                    f"two different toolchain fragments claim the slug {fragment.slug!r} "
                    f"({cg_id} collides with an existing definition)")
        table[fragment.slug] = fragment
    return table

default_languages

default_languages()

Every language cg can put in an image -- the default contents of the toolchain.

Derived, never a hardcoded list. A language is in the default set exactly when it declares a toolchain_fragment, so adding one is a single-module change and the two can never drift apart.

The default is everything rather than a minimal subset because the whole set costs about 1.9 GB: the languages that dominate (JDK, .NET, Node) share one Debian base instead of each dragging its own, so trimming saves far less than the confusion of having to choose. Subset builds remain available for anyone who wants one -- see CgSettingsData.toolchain_languages -- they are just not something a user should have to think about.

Source code in codingame_tools/language/toolchain/registry.py
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
def default_languages() -> list[str]:
    """Every language cg can put in an image -- the default contents of the toolchain.

       **Derived, never a hardcoded list.** A language is in the default set exactly when it declares
       a `toolchain_fragment`, so adding one is a single-module change and the two can never drift
       apart.

       The default is *everything* rather than a minimal subset because the whole set costs about
       1.9 GB: the languages that dominate (JDK, .NET, Node) share one Debian base instead of each
       dragging its own, so trimming saves far less than the confusion of having to choose. Subset
       builds remain available for anyone who wants one -- see `CgSettingsData.toolchain_languages`
       -- they are just not something a user should have to think about."""
    from ..registry import get_language, list_language_cg_ids

    return [
        cg_id for cg_id in list_language_cg_ids()
        if get_language(cg_id).toolchain_fragment is not None
    ]

fragments_for_languages

fragments_for_languages(languages)

Everything needed to build an image for languages, in install order.

The whole pipeline in one call: names to slugs, slugs to fragments, dependencies pulled in and ordered deterministically.

Source code in codingame_tools/language/toolchain/registry.py
100
101
102
103
104
105
def fragments_for_languages(languages: list[str]) -> list[CgToolchainFragment]:
    """Everything needed to build an image for `languages`, in install order.

       The whole pipeline in one call: names to slugs, slugs to fragments, dependencies pulled in and
       ordered deterministically."""
    return resolve_fragments(resolve_language_slugs(languages), all_fragments())

render_dockerfile

render_dockerfile(fragments, *, base_image, preamble='')

The full cg-owned Dockerfile for fragments, already in install order.

Renders cg's own base.dockerfile content. Distinct from codingame_tools.language._docker.compose_dockerfile, which composes that file on disk with the user's custom.dockerfile -- generation versus merging.

The header is machine-readable in the same spirit as the single-language one it replaces: it records every fragment and its version, so a generated file can be recognized as cg's, checked for staleness, and told apart from one the user has edited.

Parameters:

  • fragments (list[CgToolchainFragment]) –

    In install order, as returned by resolve_fragments.

  • base_image (str) –

    Value for the CG_BASE_IMAGE build arg--one pinned neutral base that every fragment installs onto, rather than a per-language base image.

  • preamble (str, default: '' ) –

    Statements common to every image, inserted before any fragment.

Source code in codingame_tools/language/toolchain/fragment.py
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
def render_dockerfile(
            fragments: list[CgToolchainFragment],
            *,
            base_image: str,
            preamble: str = "",
        ) -> str:
    """The full cg-owned Dockerfile for `fragments`, already in install order.

       *Renders* cg's own `base.dockerfile` content. Distinct from
       `codingame_tools.language._docker.compose_dockerfile`, which *composes* that file on disk with
       the user's `custom.dockerfile` -- generation versus merging.

       The header is machine-readable in the same spirit as the single-language one it replaces: it
       records every fragment and its version, so a generated file can be recognized as cg's, checked
       for staleness, and told apart from one the user has edited.

    Args:
        fragments:  In install order, as returned by `resolve_fragments`.
        base_image: Value for the `CG_BASE_IMAGE` build arg--one pinned neutral base that every
                     fragment installs onto, rather than a per-language base image.
        preamble:   Statements common to every image, inserted before any fragment.
    """
    manifest = ",".join(f"{f.slug}@{f.version}" for f in fragments)
    body_parts: list[str] = [
        f"ARG CG_BASE_IMAGE={base_image}\n",
        "FROM ${CG_BASE_IMAGE}\n",
    ]
    if preamble.strip():
        body_parts.append("\n" + preamble.strip("\n") + "\n")
    for fragment in fragments:
        section = fragment.dockerfile.strip("\n")
        env = _env_script_statements(fragment)
        if not section and not env:
            # Normal, not degenerate: a language wholly supplied by a subsystem. Emitting an empty
            # section would add a comment-only layer and, worse, make two identical images differ.
            continue
        body_parts.append(f"\n# --- {fragment.slug} ---\n")
        if section:
            body_parts.append(section + "\n")
        if env:
            body_parts.append(env)
    body = "".join(body_parts)

    header = (
            "# cg-managed toolchain--do not edit.\n"
            "# Put your own additions in custom.dockerfile instead; they're appended to this file\n"
            "# and survive every cg template upgrade.\n"
            f"# cg-toolchain: fragments={manifest} "
            f"body-sha256={hashlib.sha256(body.encode('utf-8')).hexdigest()}\n"
        )
    return header + body

resolve_language_slugs

resolve_language_slugs(languages)

Fragment slugs for CodinGame language names, e.g. ["C++"] -> ["cpp"].

Raises:

  • CgToolchainError

    if a name isn't a known language, or is one with no container support -- distinguished, because "you typed it wrong" and "cg can't containerize that yet" need different fixes.

Source code in codingame_tools/language/toolchain/registry.py
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
def resolve_language_slugs(languages: list[str]) -> list[str]:
    """Fragment slugs for CodinGame language names, e.g. `["C++"] -> ["cpp"]`.

    Raises:
        CgToolchainError: if a name isn't a known language, or is one with no container support --
                           distinguished, because "you typed it wrong" and "cg can't containerize
                           that yet" need different fixes.
    """
    # Imported here, not at module scope: the language registry imports every plugin, each of which
    # imports `base`, which imports this package. At module scope that is a cycle -- the same one
    # `codingame_tools.language.vscode` resolves the same way.
    from ..registry import get_language, list_language_cg_ids

    known = {cg_id.casefold(): cg_id for cg_id in list_language_cg_ids()}
    slugs: list[str] = []
    for name in languages:
        cg_id = known.get(name.casefold())
        if cg_id is None:
            raise CgToolchainError(
                    f"unknown language {name!r}. Known: {', '.join(sorted(known.values()))}")
        fragment = get_language(cg_id).toolchain_fragment
        if fragment is None:
            raise CgToolchainError(
                    f"{cg_id} has no toolchain fragment yet, so it can't be built into an image. "
                    "Languages gain one as they gain a real build/run backend.")
        slugs.append(fragment.slug)
    return slugs

find_workspace_root

find_workspace_root(root)

Best guess at the VS Code workspace root folder that contains root.

Walks up from root looking for a directory that already has .vscode/, then for a VCS marker (.git/.hg/.svn), stopping at the filesystem root. Falls back to root itself, which is correct when the user opens the working directory directly as their folder.

This matters because VS Code reads launch.json only from the workspace root--see the module docstring.

Source code in codingame_tools/language/vscode.py
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
def find_workspace_root(root: Path) -> Path:
    """Best guess at the VS Code workspace root folder that contains `root`.

       Walks up from `root` looking for a directory that already has `.vscode/`, then for a VCS
       marker (`.git`/`.hg`/`.svn`), stopping at the filesystem root. Falls back to `root` itself,
       which is correct when the user opens the working directory directly as their folder.

       This matters because VS Code reads `launch.json` only from the workspace root--see the
       module docstring."""
    root = root.resolve()
    candidates = [root, *root.parents]
    for marker in _WORKSPACE_MARKER_DIRS:
        for candidate in candidates:
            if (candidate / marker).is_dir():
                return candidate
    return root

write_provisioning

write_provisioning(provisioning, *, root, workspace_root, language, force=False, dry_run=False)

Write provisioning into <workspace_root>/.vscode/ (and provisioning.files into root), merging with whatever is already there.

Only files whose content would actually change are touched, so re-running when everything is already current is a no-op on disk--no diffs, no timestamps, no editor reload prompts.

Parameters:

  • provisioning (CgVsCodeProvisioning) –

    What the language plugin produced.

  • root (Path) –

    The working directory root. Only the base for provisioning.files now--entries are owned by declared name, not by a directory.

  • workspace_root (Path) –

    Where .vscode/ lives--see find_workspace_root.

  • language (str) –

    The cg_id of the language being provisioned for. Scopes which existing entries this run owns--see _is_owned_by_this_run--so provisioning one language never disturbs another's.

  • force (bool, default: False ) –

    Overwrite an existing config file that isn't strict JSON instead of refusing.

  • dry_run (bool, default: False ) –

    Work out what would change without touching anything. See check_provisioning.

Returns:

  • list[Path]

    Every path that changed (or, under dry_run, would change), in write order. Empty means

  • list[Path]

    everything was already up to date.

Raises:

Source code in codingame_tools/language/vscode.py
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
def write_provisioning(
            provisioning: CgVsCodeProvisioning,
            *,
            root: Path,
            workspace_root: Path,
            language: str,
            force: bool = False,
            dry_run: bool = False,
        ) -> list[Path]:
    """Write `provisioning` into `<workspace_root>/.vscode/` (and `provisioning.files` into
       `root`), merging with whatever is already there.

       Only files whose content would actually change are touched, so re-running when everything is
       already current is a no-op on disk--no diffs, no timestamps, no editor reload prompts.

    Args:
        provisioning:    What the language plugin produced.
        root:            The working directory root. Only the base for `provisioning.files`
                          now--entries are owned by declared name, not by a directory.
        workspace_root:  Where `.vscode/` lives--see `find_workspace_root`.
        language:        The `cg_id` of the language being provisioned for. Scopes which existing
                          entries this run owns--see `_is_owned_by_this_run`--so provisioning one
                          language never disturbs another's.
        force:           Overwrite an existing config file that isn't strict JSON instead of
                          refusing.
        dry_run:         Work out what would change without touching anything. See
                          `check_provisioning`.

    Returns:
        Every path that changed (or, under `dry_run`, would change), in write order. Empty means
        everything was already up to date.

    Raises:
        CgVsCodeMergeError: if an existing file can't be parsed and `force` is False.
    """
    written: list[Path] = []
    vscode_dir = workspace_root / _VSCODE_DIR_NAME

    if provisioning.configurations or provisioning.inputs:
        path = vscode_dir / _LAUNCH_FILE_NAME
        data = _read_json_object(path, force=force)
        data.setdefault("version", "0.2.0")
        inputs = _merge_by_key_by_pattern(
                data.get("inputs") or [], provisioning.inputs, key="id", owned=_OWNED_INPUT_RE)
        if inputs:
            data["inputs"] = inputs
        else:
            # Nothing generates inputs any more. Leaving an empty list behind would be a puzzling
            # relic in a file the user reads.
            data.pop("inputs", None)
        data["configurations"] = _merge_by_key(
                data.get("configurations") or [], provisioning.configurations,
                key="name", language=language, retired=provisioning.retired_names)
        if _write_json_if_changed(path, data, dry_run=dry_run):
            written.append(path)

    if provisioning.tasks:
        path = vscode_dir / _TASKS_FILE_NAME
        data = _read_json_object(path, force=force)
        data.setdefault("version", "2.0.0")
        data["tasks"] = _merge_by_key(
                data.get("tasks") or [], provisioning.tasks, key="label",
                language=language, retired=provisioning.retired_names)
        if _write_json_if_changed(path, data, dry_run=dry_run):
            written.append(path)

    if provisioning.recommended_extensions:
        path = vscode_dir / _EXTENSIONS_FILE_NAME
        data = _read_json_object(path, force=force)
        # Union rather than replace: there's no marker distinguishing recommendations cg added
        # previously from ones the user added, so removing any would eventually delete theirs.
        existing = [e for e in (data.get("recommendations") or []) if isinstance(e, str)]
        data["recommendations"] = existing + [
                e for e in provisioning.recommended_extensions if e not in existing]
        if _write_json_if_changed(path, data, dry_run=dry_run):
            written.append(path)

    for relative, content in provisioning.files.items():
        path = root / relative
        if _write_text_if_changed(path, content, dry_run=dry_run):
            written.append(path)

    for relative in provisioning.obsolete_files:
        stale = root / relative
        if not stale.is_file():
            continue
        written.append(stale)
        if dry_run:
            continue
        stale.unlink()
        # Only when it's left empty--never a recursive delete of something the user may have added
        # to. `rmdir` failing on a non-empty directory is exactly the check wanted.
        with suppress(OSError):
            stale.parent.rmdir()

    return written