Keyboard shortcuts

Press ← or → to navigate between chapters

Press S or / to search in the book

Press ? to show this help

Press Esc to hide this help

cjv developer guide

This guide covers cjv builds, architecture, testing, website maintenance, and releases. See the user guide for installing and using Cangjie SDKs.

Repository layout

DirectoryContents
cmd/cjv/Go entry point for cjv, cjv-init, and SDK proxy binaries
internal/CLI command groups, installation lifecycle, distribution, transactions, and runtime environment
tests/End-to-end CLI integration, installer script, and live-download smoke tests
web/React landing page, browser platform detection, and public installer scripts (install.sh, install.ps1)
docs/User and developer guides (with Chinese in src/ and English in en/) plus the shared theme
deployment/Edge functions and site verification tools for Cloudflare Worker and Tencent Cloud EdgeOne
scripts/Platform catalog generators, CI scope filter, documentation builder, and HarmonyOS test helpers

Quick workflow for contributors

  1. Start by building cjv from source and trying out your local build in an isolated CJV_HOME directory.
  2. Read the Architecture guide to find the package that owns the behavior you want to change and understand its locking, transaction, and state-isolation invariants.
  3. Run the relevant commands in Testing and checks to verify your changes across Go packages, installer scripts, the frontend, and the bilingual mdBook manuals.
  4. Follow the Contributing guide for atomic commits, commit message conventions, and pull request expectations.
  5. For maintaining the public website, documentation build, or release pipelines, see Landing page, Documentation site, and Releases.

Build from source

go.mod declares Go 1.26.0 as the minimum version and toolchain go1.27.3 as the preferred toolchain. With the default GOTOOLCHAIN=auto, Go selects or downloads that toolchain when needed. The Go CLI builds independently of the web/ frontend. Generated platform catalogs and embedded locale resources are committed to the repository.

go build ./...
go build -o cjv ./cmd/cjv

On Windows, run go build -o cjv.exe ./cmd/cjv. The first command verifies that every package in the workspace compiles cleanly; the second produces the standalone cjv executable. If you want to install your current working tree directly into GOBIN, run go install ./cmd/cjv.

When testing changes to cjv interactively, you can isolate your development build from any existing cjv installation on your machine by pointing CJV_HOME and CJV_CONFIG_FILE at a temporary directory:

mkdir -p /tmp/cjv-dev
CJV_HOME=/tmp/cjv-dev CJV_CONFIG_FILE=/tmp/cjv-dev/settings.toml ./cjv init --no-modify-path -y

Version information and mirror builds

Ordinary local builds report their version as dev and automatically skip self-update version comparisons. For official releases, GoReleaser injects main.version and main.updateURL via linker flags (-ldflags). You can set an explicit version string locally or build the GitCode mirror variant with -tags=mirror:

go build -ldflags "-X main.version=0.0.0-local" -o cjv ./cmd/cjv
go build -tags=mirror -o cjv-mirror ./cmd/cjv

The mirror build tag selects the GitCode default manifest URL and self-update backend in internal/config/manifest_*.go and internal/selfupdate/update_*.go. Whenever you modify shared interfaces in config or selfupdate, make sure to validate both the default build and the -tags=mirror build.

Cross builds and generated files

You can cross-compile cjv for other operating systems and architectures using standard Go environment variables. For example, in Bash:

GOOS=linux GOARCH=arm64 go build -o cjv ./cmd/cjv

The authoritative catalog of release platforms lives in internal/target/catalog.go:

  • Linux: amd64 and arm64
  • macOS (darwin): amd64 and arm64
  • Windows: amd64
  • OpenHarmony (openharmony): amd64 and arm64

Whenever you update internal/target/catalog.go, regenerate the derived files across the repository:

go generate ./...

After running go generate ./..., review the generated frontend platform list in web/src/generated/platforms.ts, and check .goreleaser.yml and the CI workflow matrices to keep all platform definitions in sync. See Testing and checks for how to validate your build.

OpenHarmony

Building cjv for OpenHarmony (GOOS=openharmony) uses the Linux/amd64 toolchain from Go-HMOS go1.27.2-hmos.5 with CGO_ENABLED=0. Keep GOTOOLCHAIN=local for this build so the preferred-toolchain directive does not switch the custom Go-HMOS toolchain to standard Go.

From the repository root on a Linux x86_64 host, set the tool paths, build the host code-signing helper with your host Go toolchain, and then compile and sign the OpenHarmony executable:

export GOENV=off GOTOOLCHAIN=local
export HMOS_GO=/absolute/path/to/go-hmos/bin/go
export HMOS_SIGN=/tmp/cjv-hmos-sign
go build -tags=hmos_sign -o "$HMOS_SIGN" ./scripts/harmonyos
GOOS=openharmony GOARCH=arm64 CGO_ENABLED=0 "$HMOS_GO" build -o cjv ./cmd/cjv
"$HMOS_SIGN" cjv cjv

Use GOARCH=amd64 when targeting x86_64 OpenHarmony, and add -tags=mirror for the mirror variant.

The host signer (scripts/harmonyos) reuses internal/ohos/selfsign: it validates the ELF structure and Go build metadata, embeds the .codesign section, and verifies the resulting signature. You can also pass --verify FILE... to verify existing binaries.

During official releases, .goreleaser.yml builds both default and mirror variants and signs OpenHarmony binaries before archiving and generating checksums.txt. When cjv itself runs on an OpenHarmony host and downloads a Cangjie SDK, downloaded native executables are self-signed automatically through the platform hook in internal/dist.

Architecture

cli parses commands and renders output, lifecycle coordinates toolchain and component installations, and lower-level packages own distribution manifests, file ownership, and durable filesystem transactions. Proxy execution (cjc, cjpm, etc.) resolves the active SDK from the same local installation state without constructing the Cobra CLI command tree.

Entry point and modules

cmd/cjv/main.go dispatches execution based on the invoked executable name (os.Args[0]):

  • SDK tool names (cjc, cjpm, and others) enter proxy.Run directly.
  • cjv-init or cjv-setup prefixes launch the interactive installation wizard.
  • All other invocations enter cli.Execute.
ModuleResponsibility
cliCobra command tree, argument validation, result rendering, and error formatting
lifecycleOrchestration for SDK, cross-target, component, custom installation, rollback, and removal
toolchainInstallation identities, version selectors, host-target associations, and local recovery
resolveActive toolchain preparation and automatic installation of missing project requirements
componentComponent directory roots, file manifests, local stdx links, and batch edits
distLazy manifest loading, resumable downloads, SHA-256 verification, extraction, and staging lifetime
targetPlatform tuples, SDK/component platform mappings, and the release platform catalog
env, sdktoolsEnvironment variable merging, shell script output (envsetup), and SDK tool layout
proxy, processTool proxy forwarding, child process execution, exit codes, and signal propagation
configSettings file origins and inheritance, cangjie-sdk.toml lookup, and <CJV_HOME> data layout
reachable, selfupdateManaged cjv binary, proxy links in <CJV_HOME>/bin, PATH setup, and self-updates
fstx, fsopsDurable filesystem transactions, atomic file operations, tree merges, and platform retries
ohosPreparing and self-signing native ELF payloads for OpenHarmony hosts

Supporting packages provide shared infrastructure across the codebase:

  • progress defines progress event types and output adapters.
  • i18n, cjverr, and logging provide localized messages, structured error codes, and debug/warning logs.
  • retry implements the exponential backoff loop shared by filesystem and HTTP download retry policies.
  • testutil supplies mock distribution servers, progress recorders, and platform test helpers; config/configtest isolates settings files and cli/clitest runs command groups in unit tests.

Command state and output

Each call to cli.Execute creates an isolated clictx.Context (holding the output renderer, global +toolchain selector, and root command) along with a fresh command tree. Command groups live in their own subpackages (showcmd, componentcmd, runcmd, initcmd, toolchaincmd, settingscmd, selfcmd); each group stores its flags in its own struct and registers itself on the root command. Subcommands pass request structs to business packages, which report progress events through progress.Sink and return structured results rather than printing directly to stdout.

  • Text mode renders progress via progress.Text and prints each result’s Text() method.
  • JSON mode discards progress events and emits a single structured JSON document or error object to stdout.
  • Proxy mode reserves stdout exclusively for the invoked SDK tool, writing automatic installation progress to stderr.

The CLI layer renders each error once, and main maps the result to a process exit code. When adding or modifying CLI commands, keep invocation state strictly isolated—never move flags, io.Writer handles, or JSON mode into package-level global variables.

Installation and publication

lifecycle.OpenDistribution reads settings, platform definitions, and remote manifests without recovering or scanning local installations. As a result, remote-only queries (toolchain list-remote, check) do not depend on local transaction recovery succeeding. Mutating operations open an installation distribution session, which recovers any interrupted transactions and migrates legacy directory layouts before taking local snapshots.

A managed SDK installation proceeds through six distinct phases:

  1. dist.Preparation acquires the installation lock (<CJV_HOME>/.install.lock) and creates a private staging directory for the operation.
  2. Under HomeLock, cjv reads the target installation identity, current component selections, and host-target dependency snapshots.
  3. cjv releases HomeLock while resolving manifest versions, downloading archives, and extracting the host SDK, tracked cross targets, and components into staging (retaining the installation lock throughout).
  4. cjv reacquires HomeLock and verifies that local snapshots and dependencies did not change while the lock was released.
  5. publication.go publishes the directories and metadata changed by each member in one durable transaction through fstx.NewToolchainGroupTransaction.
  6. cjv finishes command entry point setup in <CJV_HOME>/bin, marks preparation complete, and cleans up owned downloads and staging files.

CLI install defaults to NoUpdate, preserving an installed release while ensuring the SDK and requested optional items exist; update advances channels. --allow-missing skips/removes unavailable optional items (with legacy --force compatibility), and --reinstall reinstalls the current release. Nightly resolution retains compatibility searches and explicit downgrade policy.

When the SDK release and provenance are unchanged and only components need updating, the group revalidates under the lock and copies only affected component directories and component metadata, leaving the SDK payload in place. Component manifests and installation records still commit in the same transaction as changes to other host or cross-target members of the group. SDK replacements and explicit --reinstall prepare and publish the complete SDK. All publication paths are staged in .staging trees beside their SDK, documentation, or stdx roots so interrupted operations can use the same recovery and cleanup paths.

Managed component installation batches (component add) likewise stage outside HomeLock, revalidate under HomeLock, and publish contents and file manifests in a single transaction while leaving the SDK root in place. component remove removes each requested component under HomeLock, continues after individual failures, and reports successful removals with the combined errors; the batch is not atomic. Tracked channels and pinned versions remain independent, and hard-link deduplication (link_mode = "hardlink") applies only to regular SDK files with matching provenance and SHA-256 content (metadata and components are never shared).

Custom URL and local archive installations (resolved_install.go) commit the SDK first and then process any bundled stdx archive. A failure while extracting bundled stdx preserves the committed SDK and reports partial success, unlike the all-or-nothing group publication used for managed channels.

Recovery and file ownership

fstx journals commit state, owned target paths, and backup locations on disk before moving files. If a process crashes or is interrupted, the next recovery pass replays the journal and applies the same commit or rollback decision. If a filesystem error blocks recovery, fstx retains the journal and backups and returns RecoveryError. Installation, removal, and active toolchain preparation all require recovery to succeed first—backups needed for recovery must never be treated as disposable leftovers.

Concurrent read/write locking (HomeLock and WithStableReads)

HomeLock always acquires the global writer lock before acquiring the active-lookup gate. During long-running phases that leave installed SDK roots unchanged—such as copying, verifying, or pruning update history snapshots—the writer calls WithStableReads to temporarily release the active-lookup gate while retaining the global writer lock.

This allows concurrent readers (cjc, cjv show active, cjv which) to resolve an existing SDK without blocking behind history snapshot I/O:

  • A reader holds the active-lookup gate across directory lookup and probes the writer lock without waiting.
  • If a live writer holds the writer lock during a stable-read phase, the reader resolves the installed SDK directly; if no live writer owns the writer lock (for instance, after a writer crash), ordinary transaction recovery runs instead.
  • Before mutating installed roots, the writer reacquires the active-lookup gate and atomically clears the read-phase marker.
  • Readers must never wait for the writer lock while holding the active-lookup gate, avoiding lock-order inversion. A stale marker left after a crash cannot bypass recovery, and this fast path remains disabled until the first legacy-layout migration completes.

Component manifests and path safety

Before creating snapshots or modifying files, component validates owned roots, the complete file manifest, and parent directory symlinks. Files shared with the base SDK are retained during removal; tracked leaf links can be removed without deleting their target sources; and archive merges refuse to traverse untracked symlinks. External SDK directory links cannot serve as component edit roots, and rollback validates destination roots as well.

Managed component installation batches use durable cross-process fstx journals. component remove directly removes files for each requested component. component link and custom archive component edits use backups and in-process rollback for ordinary errors, retaining backups if restoration fails. Removal and linking do not provide the same durable transaction guarantees as managed component installation.

Always derive <CJV_HOME> paths from config/layout.go, and use fsops for directory tree copies, merges, and Windows retry loops. All archive and tree operations reject paths or links that escape owned directories.

Active toolchains and cross targets

toolchain.SelectActive evaluates explicit CLI selections (+name, --toolchain), CJV_TOOLCHAIN, per-directory overrides and cangjie-sdk.toml files, and the global default. PrepareActive runs pending recovery and locates the installation on disk, invoking its auto-install callback only when a valid official SDK is missing (invalid selections, corrupt records, and I/O errors are returned directly).

run and exec share resolve.ActiveRuntime and auto_install policy; explicit run --install conflicts with --no-auto-install. which reads tool paths, while envsetup reads environments and validates project requirements without installation. toolchain.ReadHostTargets binds host identity, release, and platform for target commands, components, and proxies, preventing cross SDKs from being associated with another owner or release.

env.Runtime merges SDK paths and component variables into an explicitly supplied base environment to build a child process environment or envsetup shell script (env itself does not select toolchains; resolve.ActiveRuntime pairs active selection with env.Runtime, and sdktools owns tool paths). On Unix, proxies replace the current process via execve; on Windows—and for cjv run and cjv exec—process.Run manages child execution, exit codes, and signals.

Distribution and downloads

dist.Source lazily loads and caches versions.json for LTS/STS and nightly.json for nightly, resolving components from the same channel data. cjv consumes static manifests; upstream scraping and manifest generation live in the separate cangjie-version-manifest repository.

Preparation owns the installation lock, staging directory, and downloaded archives through publication and cleanup. Failures retain reusable partial downloads; successes clean only files owned by that operation, leaving user-supplied local archives and recovery journals untouched.

Archive downloads and nightly .sha256 sidecar requests share a cancellable retry loop. HTTP 408, 429, and 5xx responses may retry, whereas permanent 4xx errors and malformed content fail immediately (a 404 on a nightly sidecar indicates that the checksum has not been published yet). Downloads with an expected SHA-256 can resume across commands and verify the complete file; downloads without a hash resume only within a single operation.

Settings and self-management

config.SettingsFile tracks which fields were explicitly set in each file: Update writes only explicitly modified fields so unset fields continue to inherit from system fallback settings, while Save can restore both values and field presence from a snapshot. Environment overrides remain temporary, validation precedes publication, and the in-memory cache is updated after a successful write.

reachable.Ensure manages the installed cjv binary, proxy entry points, and environment scripts, configuring PATH according to caller policy. selfupdate.Check queries release metadata only, whereas selfupdate.Update verifies and replaces the executable and returns a status value for the CLI to render. Default and mirror builds implement GitHub and GitCode release discovery respectively.

Testing and checks

Choose your validation commands according to the scope of your change. CLI unit tests cover flag parsing and output rendering, while installation and update behavior is tested through production lifecycle entry points using local httptest.Server fixtures for manifests and archives. Ordinary unit and integration tests never depend on live upstream distribution servers.

Go

From the repository root, run the standard build, test, and lint suite:

go build ./...
go test -race -count=1 -timeout 300s ./...
go vet ./...
golangci-lint run

During local iteration, you can replace ./... with the specific packages you touched. -race enables Go’s race detector, and -count=1 disables cached test results. Format all modified Go files with gofmt, and use gofmt -l . to check for unformatted files. Linter rules are configured in .golangci.yml.

Whenever you touch download logic, self-update code, or shared interfaces in config or selfupdate, also validate the mirror build variant:

go build -tags=mirror ./...
go test -tags=mirror -race -count=1 ./internal/selfupdate/...
go vet -tags=mirror ./...

End-to-end CLI integration tests compile and invoke the real cjv binary in isolated child processes:

go test -race -tags integration -count=1 ./tests/integration/

When writing tests, always isolate the user home directory, CJV_HOME, and system fallback settings (using configtest). Remember that setting CJV_HOME alone does not isolate ~/.cjv/settings.toml. PATH setup tests use temporary shell profile files on Unix, and guard and restore the user PATH registry key on Windows.

Where regression tests belong

Place new regression tests in the package that owns the behavior under test:

BehaviorLocation and assertions
CLI arguments, repeated flags, JSON outputinternal/cli and its *cmd packages: run against real command trees (clitest.Root) with isolated writers, asserting one result or error
Install, update, rollback, removeinternal/lifecycle: test against a local mock distribution, asserting final directory contents, settings references, and failure recovery
Host-target isolationinternal/toolchain, internal/lifecycle: assert installation identity, host platform, and exact release matching
Component ownershipinternal/component: assert shared SDK files, path-escaping manifests, symlinks, and backup restoration
Process interruption and journalsinternal/fstx and lifecycle regressions: assert actual journal recovery after an interrupted child process exits
HTTP resume, cancellation, retriesinternal/dist: assert HTTP requests, Range headers, SHA-256 hashes, and total request counts
Runtime environment and processesinternal/env, internal/process: assert supplied base environments, real child exit codes, and signal forwarding

Always assert observable outcomes. Use testutil.ProgressRecorder to verify progress event kinds rather than matching localized text strings. In failure-recovery tests, verify that blocked recovery retains backup directories and that rejected paths leave files outside <CJV_HOME> untouched.

Installers and frontend

To run the Unix shell installer test suite:

CJV_INSTALL_TEST_SHELL=bash sh tests/install-scripts/install-sh.sh

To run the PowerShell installer test suite:

$env:CJV_INSTALL_TEST_POWERSHELL = "pwsh"
./tests/install-scripts/install-ps1.ps1

In CI, these suites also run across sh, zsh, fish, and Windows PowerShell 5.1.

For the landing page in web/, run:

pnpm install --frozen-lockfile
pnpm exec playwright install chromium
pnpm build
pnpm coverage
pnpm test:built

Vitest runs component tests in real browsers via Playwright:

  • VITEST_BROWSER selects chromium, firefox, or webkit.
  • pnpm test:integration runs every simulated OS and architecture combination in each browser.
  • pnpm coverage combines unit tests with the coverage thresholds configured in web/vitest.config.ts.
  • After pnpm build, pnpm test:built serves the built bundle and verifies installation paths using the browser’s actual platform, content visibility when font downloads are pending, and layout overflow on both desktop and narrow mobile viewports (PLAYWRIGHT_BROWSER selects its browser).

Documentation, workflows, and dependencies

Before submitting a pull request, run the documentation, workflow, and module checks from the repository root:

npx --yes markdownlint-cli2@0.22.1
python3 scripts/build-docs.py
go run github.com/rhysd/actionlint/cmd/actionlint@v1.7.12
go mod verify

After changing Go dependencies, run go mod tidy and review the diff in go.mod and go.sum—CI re-runs go mod tidy and requires a clean working tree. Vulnerability scanning in .github/workflows/ci.yml runs the pinned govulncheck version on the current stable Go release; check the project’s supported Go versions whenever upgrading the scanner.

scripts/build-docs.py builds all four mdBook manuals (user-guide and dev-guide in Chinese and English) with the shared theme and verifies all internal page links, cross-book /book/ links, static assets, and #anchor fragments. Both PR checks and production deployments use this exact entry point; see Documentation site.

Real downloads and CI

HarmonyOS emulator tests

The separate .github/workflows/hmos.yml workflow boots the official HarmonyOS 6.1.1 (API 24) PC emulator on an x86_64 Linux KVM runner. It cross-compiles a standalone self-signing test binary and executes it both unsigned and signed, and then runs the complete ohos, config, env, fsops, target, cjverr, i18n, and retry package test suites inside the emulator using go test -exec. Standard host CI continues to cover the remaining packages (including HTTP server tests). Note that this emulator workflow executes x86_64 binaries only, not ARM64.

Two helpers under scripts/harmonyos/ coordinate the emulator runs:

  • scripts/harmonyos/ci.py owns the workflow’s three stages: build compiles the host tools, install installs the pinned emulator and Ubuntu dependencies, and test runs the unsigned, signed, exit-code, and package checks. It invokes programs directly via Python’s subprocess without Bash orchestration. After running build, you can run python3 scripts/harmonyos/emulator.py python3 scripts/harmonyos/ci.py test to reproduce the CI test sequence locally.
  • scripts/harmonyos/exec is a host Go executable for go test -exec that transfers a compiled test binary through HDC, maps its package directory to a guest source checkout, supplies isolated HOME and TMPDIR directories, and propagates the guest exit code. Set HDC, HDC_TARGET, HMOS_TEST_SOURCE, and HMOS_TEST_ROOT (which must live under /data/local/tmp). Set HMOS_SIGN to sign a private copy before transfer, or leave it empty to test unsigned execution. scripts/harmonyos/emulator.py prepares the guest checkout and environment variables, runs the supplied command, and stops the emulator cleanly.

With the official HarmonyOS CLI unpacked under HMOS_EMULATOR_HOME and the tools from Build from source built:

go build -o /tmp/cjv-hmos-exec ./scripts/harmonyos/exec
python3 scripts/harmonyos/emulator.py env GOOS=openharmony GOARCH=amd64 CGO_ENABLED=0 \
  "$HMOS_GO" test -exec /tmp/cjv-hmos-exec -p 1 -count=1 ./internal/ohos/...

In this emulator image, the HDC shell runs as uid 2000 with SELinux Enforcing. It permits unsigned executables and symlinks, but denies hard links: only tests that require successful hard-link creation skip on a verified permission error (EPERM/EACCES), while deduplication tests still verify their copy fallback behavior. Because this HDC shell policy does not establish the HiShell policy on physical HarmonyOS PCs, release builds and SDK preparation retain platform-gated self-signing.

Live downloads and CI scope

Live component download smoke tests fetch real upstream artifacts and run separately from ordinary unit tests:

go test -v -tags smoke -run TestSmokeRealComponentDownloads_LTSSTS -count=1 -timeout 45m ./tests/smoke/

.github/workflows/smoke.yml runs this smoke test on a schedule. The main .github/workflows/ci.yml workflow runs on every pull request and master push, using scripts/ci-scope.py to select expensive jobs according to which files changed (changes to workflow files or scope rules run all checks). New commits pushed to a PR cancel older in-progress runs, whereas master pushes never cancel.

Normal frontend CI checks run simulated platforms across all three browsers (chromium, firefox, webkit) plus built-page smoke tests on Linux/Windows Chromium and macOS WebKit. Manual and weekly scheduled runs select all jobs and add native Linux ARM64, Windows ARM64, and macOS Intel checks. The HarmonyOS workflow uses the same path-scoping and PR cancellation policy.

To run the isolated CI scope and release-script fixture tests locally (requires bash, zip, unzip, tar, and sha256sum):

python3 scripts/test_ci_scope.py
bash tests/release-scripts/release-scripts.sh

Contributing

Create a branch from the latest master. External contributors can fork Zxilly/cjv, configure the original repository as upstream, and open a pull request against its master branch:

git fetch upstream
git switch -c fix-windows-path upstream/master

Making changes and validating locally

  1. Reproduce first — Before fixing a bug, reproduce the failure and locate the package that owns the behavior in the Architecture guide.
  2. Test through production entry points — Add or update regression tests in the owning package rather than testing private helpers in isolation. See Testing and checks for test locations and commands.
  3. Note platform coverage — When changing platform-specific behavior (such as Windows file locking, Unix shell profile edits, or OpenHarmony self-signing), mention which platforms you tested locally in your PR description and let CI verify the rest of the matrix.
  4. Keep translations and docs in sync — Keep Chinese (src/) and English (en/) documentation changes in the same commit. When adding, moving, or removing a chapter, update both SUMMARY.md files and add a redirect entry in book.toml (see Documentation site). Frontend copy in web/ uses Lingui (pnpm i18n:extract) and requires English translations in web/src/locales/en/messages.po (see Landing page).

Atomic commits and commit messages

Each commit should contain one logical change. Submit unrelated formatting, refactoring, and dependency upgrades separately.

Before committing, inspect the recent git history and follow the repository’s convention:

git log --oneline -20

Commit titles use the Conventional Commits form type(scope): description, where (scope) is optional and description is a concise imperative phrase in English:

fix(component): enforce ownership across file edits
refactor(toolchain): centralize host target associations
docs: simplify project toolchain setup

Pull requests

When opening a pull request, describe:

  • The trigger or motivation — What user command, configuration, or edge case triggered the problem.
  • The resulting behavior — How cjv behaves after your change.
  • Validation — Which test suites and platforms you ran locally.
  • Related issues — Links or #issue references to any related GitHub issues.

After pushing your branch, check the GitHub Actions results, inspect any failures, and push follow-up fixes to the same branch as code review continues.

Update the User Guide whenever a change alters CLI flags, configuration fields, or user-visible behavior. In the Developer Guide, keep Architecture focused on stable module responsibilities and invariants—low-level implementation details belong in code comments and tests.

Landing page

web/ contains the static landing page at cjv.zxilly.com and cjv.zxilly.dev, with installer commands and platform-specific downloads. It uses React Router Framework Mode, Vite, TypeScript, Tailwind CSS, and Lingui. web/package.json declares dependency ranges and the pnpm version; web/pnpm-lock.yaml locks dependency versions.

Development and files

To start the local development server, run inside web/:

cd web
pnpm install --frozen-lockfile
pnpm dev

pnpm build generates route types, checks TypeScript, and runs the official React Router build. react-router.config.ts sets ssr: false and prerender paths derived from the Blog manifest, producing static files in web/dist/client/. pnpm preview serves that output locally. Development requires Node.js 22.22.0 or newer; production needs no React SSR server.

File or directoryContents
react-router.config.ts, src/routes.tsOfficial prerender configuration and route table
src/root.tsxHTML document, SEO metadata, and framework hydration components
src/App.tsxInstallation landing page layout, mirror toggle, and download interactions
src/hooks/use-platform.tsBrowser platform detection and download recommendations
src/generated/platforms.tsFrontend platform catalog generated from Go (internal/target/catalog.go)
src/lib/i18n.ts, src/locales/Language selection and Lingui message catalogs
src/style.css, src/components/Theme tokens and UI components
public/install.sh, public/install.ps1Public Unix and PowerShell installer scripts

To change the set of supported release platforms, update internal/target/catalog.go in Go and run go generate ./... from the repository root—never edit src/generated/platforms.ts by hand.

Platform detection

Production builds prerender React into Chinese / and English /en/ HTML through React Router Framework Mode. No React SSR server runs in production. The initial hydration uses the same generic installation methods as the build; platform detection and regional mirror defaults apply afterwards. Content, commands and documentation links remain readable without JavaScript.

src/lib/seo.ts defines localized page metadata and the homepage footer links to the matching documentation and Blog language. Both domains use canonical and hreflang URLs on .com, while .dev retains its installer commands and downloads. The mdbook-seo backend renders documentation HTML with page metadata; mdbook-sitemap generates chapter sitemaps. scripts/site_map.py reads the rendered canonical URLs and merges the plugin output with the built home and Blog pages into the site sitemap, without changing HTML.

use-platform.ts computes an initial platform match synchronously from standard browser properties (navigator.userAgent and navigator.platform), and then queries User-Agent Client Hints (navigator.userAgentData) for additional CPU architecture metadata. Detection resolves to one of three states: ready, unknown, or unsupported.

  • macOS architecture ambiguity — Many macOS browsers report an Intel (x86_64) User-Agent even on Apple Silicon (arm64) Macs. When a browser cannot reliably confirm the Mac’s CPU architecture, the install.sh script command remains available (since the shell script detects the native architecture locally), while manual downloads present both Apple Silicon and Intel options side by side.
  • Mobile and tablet browsers — Mobile operating systems and architectures without prebuilt binaries are marked unsupported, including iPadOS browsers running in desktop User-Agent mode.
  • HarmonyOS and OpenHarmony — HarmonyOS detection prioritizes the version in the OpenHarmony / HarmonyOS token and preserves its version namespace (ArkWeb, HuaweiBrowser, and Chrome versions are never treated as OS versions). Phone / Mobile tokens identify phones, and Tablet alone identifies ordinary tablets (unsupported). Tablet combined with Windows NT identifies a 2-in-1 device in tablet mode, while PC or desktop Windows NT tokens identify PCs. HarmonyOS PCs and 2-in-1 devices receive the shell installer command and native ARM64 / x86_64 download choices, whereas phones, ordinary tablets, and unclassified devices show device-specific guidance.

Compatibility tokens (Windows NT, Linux, Android) and UA Client Hints are never allowed to override HarmonyOS with Windows or Android, nor are they trusted to guess a HarmonyOS device’s native CPU architecture. Instead, the download panel explains how to run uname -m in the terminal to choose the right architecture and launch cjv-init.

Whenever you modify platform detection, run the real-browser platform tests (pnpm test:integration and pnpm test:built) and verify that an unknown architecture never produces a single wrong binary recommendation. See Testing and checks.

Translation and styling

Chinese (zh) is the Lingui source language:

  • Use <Trans> from @lingui/react/macro inside JSX.
  • Use useLingui().t for string expressions inside React components.
  • Use msg from @lingui/core/macro for message descriptors outside components.

After adding or updating UI copy in web/src/, extract the message catalogs:

pnpm i18n:extract

Then fill in the new English translations in src/locales/en/messages.po. Production page URLs determine the language. Language links update the URL, content and metadata, including browser back/forward navigation. Both development and production use the route language; saved preferences never override an explicit URL. Each render tree owns its Lingui instance so concurrent prerenders cannot mix languages. During production builds, the Lingui Vite plugin compiles the catalogs automatically.

The visual theme is defined in src/style.css, dark mode follows the operating system preference, and web fonts are bundled from local dependencies. Animations should continue to respect useReducedMotion.

The homepage retains its original wordmark, short introduction, installation panel and footer styling, adding only a Blog link beside the existing documentation, GitHub, Releases and Cangjie site links. Tutorial navigation, team-workflow explanations and article recommendations belong in the manuals or Blog rather than extending the installation page.

Publishing Blog content

The Blog lives at /blog/ and /en/blog/, with paired Chinese and English article URLs. src/content/blog/posts.json defines each slug, publication date and localized title, description and category. Matching Markdown files live under src/content/blog/zh/ and en/. Blog interface strings are kept in src/lib/blog.ts, separately from the landing page’s Lingui catalogs.

Provide both languages when adding an article. Start body headings at H2 without repeating the page H1, keep slugs stable, and link to the matching language of the .com manuals. react-router.config.ts derives all Blog prerender paths from the manifest. Markdown is parsed during the build and does not need a production API. Each article has its own canonical URL, hreflang links, description and BlogPosting data. The documentation build adds the generated Blog pages to the site sitemap.

The Blog inherits the green brand, fonts and system dark mode, using a single reading column, a table of contents and horizontally scrollable code blocks. Run pnpm test, pnpm build and pnpm test:built after changes, and inspect desktop and mobile layouts. SDK and CI commands still need validation in the documented environment; website tests do not establish that those SDK workflows ran successfully.

Deployment contents

During CI deployment, .github/workflows/pages.yml builds web/ first, and then adds platform-specific cjv-init binaries under web/dist/client/dl/ and both bilingual mdBook manuals under web/dist/client/book/. A local pnpm build in web/ does not generate those extra directories on its own. See Releases for /dl/ installer artifacts and Documentation site for the mdBook build.

Documentation site

docs/user-guide/ and docs/dev-guide/ are two independent mdBook projects. Each book keeps its Chinese source chapters in src/ and its English source chapters in en/, sharing a single book.toml configuration file. Both books share the site theme and language switcher in docs/theme/.

Edit chapters

The Chinese and English chapter sources are maintained side by side—synchronize content changes across both languages in the same commit:

  • When adding, moving, or deleting chapters, update both src/SUMMARY.md and en/SUMMARY.md and keep page file paths identical across both languages.
  • Keep CLI commands, file paths, configuration keys, and code identifiers identical; prose and code comments may be translated.
  • Use relative .md links within the same book, and use full public site URLs (https://cjv.zxilly.com/book/...) when linking between the User Guide and the Developer Guide, because the two books build separately.
  • Whenever you move or rename a published page, retain its old URL under [output.seo.html.redirect] in book.toml so existing links continue to work.

docs/theme/cjv-i18n.js and cjv-i18n.css provide the top-bar language switcher. The switcher works by replacing the /zh-CN/ and /en/ path segments in the current URL, which is why both languages must have matching page paths. Because translated headings generate different HTML anchor IDs, switching languages opens the corresponding chapter at the top and strips any previous #anchor hash.

Local preview

Install mdBook 0.5.3, mdbook-sitemap 0.1.1, mdbook-seo and Python 3.9 or later, then run from the repository root:

cargo install mdbook-sitemap --version 0.1.1 --locked
cargo install --git https://github.com/Zxilly/mdbook-seo --rev de97785a384305e149dc52ac24f9f1d8f827bb9c --locked
python3 scripts/build-docs.py
python3 -m http.server --directory web/dist/client 8000

Open http://localhost:8000/book/user-guide/en/ (or /zh-CN/) in your browser to preview the published theme and language switcher. On Windows, use python if python3 is not on your PATH.

scripts/build-docs.py configures the source directory, language code, book title, and site URL for all four books (user-guide and dev-guide in zh-CN and en), stages the shared theme in a temporary directory so mdBook can fingerprint assets cleanly, and then parses all generated HTML files to verify internal page links, cross-book /book/ links, static assets, and #anchor fragments. Pass --output <dir> to write to another output directory, or --check-only to check an existing build without running mdbook. Markdown lint checks are listed in Testing and checks.

Each book uses [output.seo] to render HTML with mdbook-seo, including canonical, description, hreflang, Open Graph and Twitter metadata. HTML renderer options belong under [output.seo.html]. The shared docs/theme/head.hbs provides analytics, and docs/user-guide/seo-pages.json supplies localized installation-page overrides. The build sets each language’s canonical base URL and locale.

The mdbook-sitemap backend discovers chapters through [output.sitemap]. The full build copies seo/ output to the existing public paths. scripts/site_map.py reads the generated canonical tags, excludes noindex pages, and merges the four books with whichever home and Blog pages have actually been built. It does not modify HTML. Backend directory names do not appear in public URLs. include-lastmod remains disabled so build dates are not reported as modification dates.

Rebuilding during editing

After changing Markdown or SEO configuration, rerun python3 scripts/build-docs.py and refresh the static preview. This is the supported preview path for the complete bilingual site; it uses the same staging, theme and metadata as production. A direct mdbook serve is not part of the SEO backend’s tested compatibility.

Pages deployment

.github/workflows/pages.yml deploys the site when relevant frontend, documentation, or deployment files are pushed to master, on manual workflow_dispatch runs, or when called by the release workflow. It builds web/ first, and then populates installers and all four book outputs under web/dist/client/:

web/dist/client/
  dl/{official,mirror}/{os}_{arch}/cjv-init[.exe]
  book/user-guide/{zh-CN,en}/
  book/dev-guide/{zh-CN,en}/

Always keep this build order: running pnpm build in web/ clears web/dist/client/. Pull request checks and production deployments use the exact same mdBook version and build script entry point:

python3 scripts/build-docs.py

The assembled web/dist/client directory is uploaded as a single github-pages artifact and deployed to both GitHub Pages and Tencent Cloud EdgeOne. See Releases for installer artifacts and release ordering.

Releases

Pushing a stable vX.Y.Z tag triggers .github/workflows/release.yml. Other v* tags also start the workflow, but fail immediately at the tag format validation step.

Release order

When a vX.Y.Z tag is pushed, the release pipeline runs in four ordered stages:

  1. Validate the vX.Y.Z tag format and push the release commit and tag to GitCode.
  2. Build the default (cjv) and mirror (cjv-mirror) variants across all supported platforms with GoReleaser, and publish the GitHub Release.
  3. Call sync-gitcode-release.yml to synchronize the release archives and checksums.txt to GitCode Releases.
  4. Once both GitHub and GitCode releases finish, call .github/workflows/pages.yml to update the website’s /dl/ installers, landing page, and documentation site.

Ordinary branch and tag synchronization is handled by .github/workflows/mirror.yml. If step 3 fails due to a transient network issue, you can retry asset synchronization manually via the workflow_dispatch entry point in sync-gitcode-release.yml (see the workflow file for inputs and credentials).

Artifacts

.goreleaser.yml defines two builds—cjv and cjv-mirror (compiled with -tags=mirror)—each shipping amd64 and arm64 binaries for Linux, macOS, and OpenHarmony, plus amd64 for Windows:

ItemName
Default archivecjv_<os>_<arch>.tar.gz, or .zip on Windows
Mirror archivecjv-mirror_<os>_<arch>.tar.gz, or .zip on Windows
Checksumschecksums.txt
Executable inside archivecjv or cjv-mirror, with .exe on Windows

Release builds inject main.version and main.updateURL via -ldflags. The mirror build switches the default manifest URL and self-update backend to GitCode, while still honoring absolute artifact URLs written in manifests.

Whenever you change archive naming rules or supported platforms, update .goreleaser.yml, the installer scripts (install.sh, install.ps1), scripts/extract-init-binaries.sh, the generated frontend platform catalog (go generate ./...), and the CI matrix together.

OpenHarmony builds and signing

During release builds, .github/actions/setup-hmos installs the Go-HMOS go1.27.2-hmos.5 toolchain (HMOS_GO) and builds the host code-signing tool (HMOS_SIGN). GoReleaser compiles openharmony_arm64 and openharmony_amd64 with HMOS_GO and invokes HMOS_SIGN on each binary before packaging the archives and generating checksums.txt. The signed OpenHarmony archives are included in both GitCode synchronization and Pages /dl/ extraction.

Before running a local GoReleaser snapshot, set HMOS_GO and HMOS_SIGN and build the host signer as described in Build from source.

Website installers

The release workflow passes its current tag to Pages; ordinary website deployments resolve the latest stable release tag once before downloading (and manual Pages runs may supply an explicit release_tag input). scripts/download-release-archives.sh downloads all 14 archives and checksums.txt from that single release tag, and then runs:

ARCHIVES_DIR=archives OUT_DIR=web/dist/client/dl bash scripts/extract-init-binaries.sh

extract-init-binaries.sh verifies the SHA-256 checksum of all 14 archives against checksums.txt first—any missing, duplicate, malformed, or mismatched checksum aborts the script before extraction. Next, it extracts and renames each executable to cjv-init (cjv-init.exe on Windows) under web/dist/client/dl/{official,mirror}/{os}_{arch}/. When a user runs that downloaded executable, cmd/cjv/main.go recognizes the cjv-init prefix (including browser-added duplicate suffixes such as cjv-init (1).exe) and launches the cjv init wizard directly.

install.sh and install.ps1 download release archives directly and verify them against checksums.txt. The scripts select the latest stable release by default or accept an explicit version; website installers come from the release tag selected by the most recent website deployment. To compare the two installation methods, use the same tag and confirm that its website deployment has completed.

Rehearsal and verification

Before tagging a release, run the test and check suite and rehearse the GoReleaser build locally:

goreleaser release --snapshot --clean

Snapshot builds write all archives and checksums.txt to dist/ without publishing a release. Inspect the generated archive contents and checksums before pushing a tag. After publication finishes, verify that both GitHub and GitCode Releases contain the tag and all assets, check the live Pages download routes (node deployment/verify-site.mjs https://cjv.zxilly.dev/ https://cjv.zxilly.com/), and confirm that install.sh and install.ps1 download the intended version.