feat(autocomplete): localize batch-4 descriptions and select Fig specs per target OS (#4180)

* feat(autocomplete): add zh-CN descriptions for small-gap utilities

Localize the remaining Fig descriptions of 22 general-purpose commands that
had 15 or fewer untranslated keys: echo, which, paste, pwd, clear, su,
crontab, env, uname, base64, date, id, split, seq, join, dig, dd, htop,
basename, dirname, readlink, and more.

- Add 159 unique zh-CN entries (160 per-command entries; basename and
  dirname share one key) and regenerate zh-TW from them.
- Preload the new specs and extend the untranslated-description audit and
  its preload assertions.
- Add batch 4 coverage, semantics, insertion-text and zh-TW terminology
  tests plus the batch research note.
- Keep upstream wording quirks documented instead of hidden: dig labels NS
  as "Query MX Record", readlink reuses stat wording, and date/su/env follow
  the BSD/macOS flags their specs actually expose.

* fix(autocomplete): align uname and dd wording with GNU output

Review the batch 4 commands against jaywcjlove/linux-command (MIT), which
Netcatty's Linux-centric sessions match better than the bundled Fig wording.

- uname -s/-r/-v now say kernel name/release/version: GNU uname prints the
  kernel, not the distribution, and macOS reports Darwin through the same
  options.
- dd cbs states the conversion record is counted in bytes.
- Document which specs in this batch expose BSD/macOS-only options (date, su,
  id, base64, split, seq, env, more, which) so their descriptions are not
  rewritten into GNU wording that the inserted option does not have, and note
  dd's upstream `files` operand artifact.

No key was added or removed; zh-TW is regenerated from zh-CN.

* feat(autocomplete): ship a GNU date spec for Linux-first completion

The bundled Fig date spec follows BSD/macOS flags (-j, -n, -t, -v, epoch
seconds for -r), so Linux hosts were offered options that do not exist there.
Local specs already override the bundled package, so add electron/specs/date.js
with the GNU option set: -d/--date, --debug, -f/--file, -I/--iso-8601,
-R/--rfc-email, --rfc-3339, -r/--reference, -s/--set, -u/--utc, plus the
+FORMAT operand.

- Translate the 13 new descriptions; zh-TW is regenerated from them.
- Remove the 13 BSD-only date entries after a repository-wide scan showed no
  other spec references them.
- Resolve local specs first in the batch 4 test, matching runtime and the
  untranslated-description audit, and spot-check the new GNU wording.

* fix(autocomplete): correct GNU wording and add local specs

Follow-up review of batch 4 found wording that would show up in the popup and
two upstream spec defects. Local specs already override @withfig/autocomplete,
so the wrong option sets are replaced rather than translated around.

- Add electron/specs/{dig,readlink,base64,htop}.js:
  dig fixes the NS label and drops the bogus TTL type; readlink replaces the
  stat wording with the real GNU options; base64 moves from BSD -b/-i/-o to
  GNU -w and --ignore-garbage; htop documents the -H delay in seconds.
- Correct awk -c (traditional mode) and -t (--lint-old) to match gawk, with
  the dictionary keys migrated alongside -n.
- Reword review findings: htop -H highlights exited processes, split -a uses
  characters and -b uses KiB/MiB/GiB, dd cbs is a conversion record length,
  join -a/-v name the file index and -o covers unpaired lines, basename -a
  accepts multiple paths, env -0 ends records with NUL, dig ANY notes RFC 8482,
  su -f/-m keep the BSD behavior without hardcoded environment claims, and
  uname uses one verb for the kernel fields.
- Extend the zh-TW generator with documented post-conversion fixes (number
  bases, extended, instance, header, TLS extension, data) and regenerate.
- Update the batch 2 and batch 4 research notes, and resolve local specs first
  in the batch 4 test so it exercises what the app loads.

* test(autocomplete): cover all preloaded specs and Apple extension term

- Assert every one of the 22 batch-4 commands in COMMON_FIG_SPECS; the old
  loop only covered 7, so dropping a preload entry could pass unnoticed.
- Keep the noun “extension” as 擴充功能: the generic 擴充套件→擴充 rule is
  right for “extended” compounds (擴充屬性, 擴充標頭, 擴充正規表示式), but
  Apple's option descriptions need the noun form.

* fix(autocomplete): choose Fig specs by target OS and correct GNU semantics

- Resolve date, base64 and readlink against the target session's OS: macOS
  keeps its BSD specs while Linux keeps the local GNU ones. The renderer now
  passes the OS over the Fig bridge, and spec contents, in-flight loads, the
  available-name list and the loaded-name index are all scoped by command and
  OS, so one renderer can serve Linux and macOS sessions without mixing them.
- Add native macOS date and readlink specs (date gains -z, readlink exposes
  only -f/-n) and keep the bundled date/base64 specs as the macOS fallback.
  The bridge spec list merges specs/macos only for macOS sessions, so a
  platform-only command is never suggested where it cannot load.
- Fix GNU readlink: -q/--quiet/-s/--silent suppress error messages, -v/--verbose
  reports them, and the nonexistent --strip is gone. Restore filepath
  completion for base64 operands and date -f/-r, and cover date -r with numeric
  prefixes so digit-leading filenames stay discoverable.
- Complete values attached to optional option arguments (-Is -> -Iseconds,
  --iso-8601=s -> --iso-8601=seconds) only for specs that opt in through
  netcattyOptionalArgAttached, leaving other commands' optional arguments and
  required-argument completion unchanged.
- Describe su -m as BSD's caller login shell versus util-linux's -s/SHELL
  order, refresh the affected zh-CN/zh-TW entries and the bundled-date fallback
  translations, and regenerate zh-TW with the repository script.
- Add focused tests for per-OS loader caching, spec listing and scoping,
  attached-argument completion, path completion, and localized descriptions;
  update the batch-4 research notes to match.

* test(autocomplete): retrigger CI after a runner cancellation

The lint-and-test job on f09b3eed0 ended with "The runner has received a
shutdown signal" during the plugin boundary step, not with a test failure.
Contributors cannot re-run that job, so this empty commit triggers a fresh
PR synchronize check.

* fix(i18n): correct zh-CN autocomplete option descriptions

- Fix 38 "registry" mistranslations: Docker/kubectl image registry vs
  npm/yarn/pnpm package source
- Fix git --source (prints a ref name, not source code)
- Fix the truncated --pathspec-file-nul key (NUL, not whitespace)
- Correct OpenCC s2twp ambiguous characters in generated zh-TW and add
  the correction table to the generator
- Add regression assertions for the corrected entries

Co-Authored-By: Claude Code <noreply@anthropic.com>

* fix(i18n): correct autocomplete option descriptions

- Fix 32 verified mistranslations across git, Docker/Kubernetes,
  package managers, and core ops commands: git pull --rebase direction,
  find primaries, scp/curl cipher terminology, git config
  --default/--system, unzip/python editorial notes, and more
- Unify git worktree on 工作树 (15 entries), Docker secret on 密钥 (7),
  and Docker buildx on 构建器 (10)
- Restore git blame's missing subcommand description with a local spec
  override and translate it
- Update batch1/batch2 expectations and the research notes for the two
  editorial notes that are now faithful translations

Co-Authored-By: Claude Code <noreply@anthropic.com>

* feat(autocomplete): add podman and ip descriptions

- Add 66 podman descriptions (325/325 coverage) and a batch5 test
- Add a local ip spec covering addresses, links, routes, neighbors,
  rules, tunnels, netns, multicast, xfrm and monitor, plus 15 root
  options; translate all 88 descriptions
- Fix podman machine terminology (虚拟机) and --log-level wording
  (指定级别及以上)
- Add a batch6 test for the ip spec

Co-Authored-By: Claude Code <noreply@anthropic.com>

* feat(autocomplete): show Chinese descriptions for command suggestions

- Generate commandDescriptions.ts from the Fig specs and the committed
  dictionaries (674 commands; 83 already translated)
- Fill source "command" suggestions with zh-CN/zh-TW descriptions
- Align cp's zh-CN description with the conventional wording
- Stop maintaining zh-TW: new entries are zh-CN only, and the tests no
  longer require zh-TW key parity, only that zh-TW has no stale keys

Co-Authored-By: Claude Code <noreply@anthropic.com>

---------

Co-authored-by: Claude Code <noreply@anthropic.com>
This commit is contained in:
rnaranyandClaude Code authored and GitHub committed 2026-11-23 18:42:12 +08:00
1 parent 2ca3ae0e28
commit 2ddb6f2bee
35 files changed
+4298 -482

No files matched your search

@@ -8,6 +8,8 @@
* OpenCC s2twp via scripts/generate-autocomplete-descriptions-zh-TW.mjs.
*/
import { COMMAND_DESCRIPTIONS } from "./commandDescriptions";
type DescriptionDictionary = Record<string, string>;
let zhCnDictionaryPromise: Promise<DescriptionDictionary> | undefined;
@@ -65,3 +67,29 @@ export async function localizeSpecSuggestionDescriptions<T extends { description
});
return changed ? localized : suggestions;
}
/**
* Command-name suggestions have no description until the command's spec is
* loaded. Fill them from the generated command description map so the popup
* can show a short Chinese hint (e.g. "cp 复制文件或目录") without loading
* every spec. Non-Chinese locales keep their existing behaviour.
*/
export function localizeCommandSuggestionDescriptions<
T extends { source?: string; displayText?: string; description?: string },
>(suggestions: readonly T[], locale: string | undefined): readonly T[] {
if (locale !== "zh-CN" && locale !== "zh-TW") return suggestions;
let changed = false;
const localized = suggestions.map((suggestion) => {
if (suggestion.source !== "command" || suggestion.description) return suggestion;
const entry = COMMAND_DESCRIPTIONS[suggestion.displayText ?? ""];
if (!entry) return suggestion;
const description =
locale === "zh-CN"
? entry.zhCN ?? entry.en
: entry.zhTW ?? entry.zhCN ?? entry.en;
if (!description) return suggestion;
changed = true;
return { ...suggestion, description };
});
return changed ? localized : suggestions;
}
@@ -0,0 +1,680 @@
// Generated from @withfig/autocomplete + local specs and the committed
// zh-CN/zh-TW autocomplete dictionaries. Regenerate when specs change.
export type CommandDescription = { en: string; zhCN?: string; zhTW?: string };
export const COMMAND_DESCRIPTIONS: Record<string, CommandDescription> = {
"-": { en: "ZSH pre-command modifier that prepends a '-' to the argv[0] string" },
"act": { en: "Run GitHub actions locally by specifying the event name (e.g. `push`) or an action name directly" },
"adb": { en: "Android Debug Bridge" },
"adr": { en: "Manage Architectural Design Records" },
"afplay": { en: "Audio File Play" },
"aftman": { en: "A toolchain manager, enabling project-specific command line tools" },
"ag": { en: "Recursively search for PATTERN in PATH. Like grep or ack, but faster" },
"airflow": { en: "Subcommand" },
"aliases": { en: "Bash aliases on steroids, dynamic alias functions for bash" },
"amplify": { en: "A set of tools and services to help front-end web and mobile developers build scalable full stack applications" },
"ampx": { en: "CLI for Amplify Gen 2" },
"ansible": { en: "Define and run a single Ansible task 'playbook' against a set of hosts" },
"ansible-config": { en: "View ansible configuration" },
"ansible-doc": { en: "Displays information on modules installed in Ansible libraries" },
"ansible-galaxy": { en: "Perform various Role and Collection related operations" },
"ansible-lint": { en: "Ansible static code analysis" },
"ansible-playbook": { en: "Runs Ansible playbooks, executing the defined tasks on the targeted hosts" },
"ant": { en: "A software tool for automating software build processes" },
"appwrite": { en: "Appwrite - Open-Source End-to-End Backend Server" },
"apt": { en: "Package manager for Debian-based Linux distributions", zhCN: "基于 Debian 的 Linux 发行版的软件包管理器", zhTW: "基於 Debian 的 Linux 發行版的軟體包管理器" },
"arch": { en: "Print architecture type or run select architecture" },
"arduino-cli": { en: "Arduino Command Line Interface" },
"asar": { en: "A simple extensive tar-like archive format with indexing" },
"asciinema": { en: "Terminal session recorder" },
"asdf": { en: "Extendable version manager with support for Ruby, Node.js, Elixir, Erlang & more" },
"asr": { en: "Asr efficiently copies disk images onto volumes, either directly or via a multicast network stream" },
"assimp": { en: "Open Asset Import Library" },
"astro": { en: "CLI provided by Astro to develop, build, and preview your project from a terminal window" },
"atlas": { en: "CLI tool to manage MongoDB Atlas" },
"atuin": { en: "Magical shell history" },
"authchanger": { en: "Authchanger is a utility included with Jamf Connect to help you manage the authorization database used by macOS to determine how the login process progresses" },
"autocannon": { en: "Fast HTTP/1.1 benchmarking tool written in Node.js" },
"autojump": { en: "A faster way to navigate your filesystem" },
"awk": { en: "Pattern scanning and text processing language", zhCN: "模式扫描和文本处理语言", zhTW: "模式掃描和文字處理語言" },
"aws-vault": { en: "A vault for securely storing and accessing AWS credentials in development environments" },
"awsume": { en: "Awsume" },
"banner": { en: "Prints a large, high quality banner on the standard output" },
"base32": { en: "Base32 encode/decode data and print to standard output" },
"base64": { en: "Encode and decode using Base64 representation", zhCN: "使用 Base64 表示法编码与解码", zhTW: "使用 Base64 表示法編碼與解碼" },
"basename": { en: "Return filename portion of pathname", zhCN: "返回路径名的文件名部分", zhTW: "返回路徑名的檔名部分" },
"basenc": { en: "Encode/decode data and print to standard output" },
"bat": { en: "A cat(1) clone with syntax highlighting and Git integration" },
"bazel": { en: "Bazel the build system!" },
"bc": { en: "An arbitrary precision calculator language" },
"bcd": { en: "Bookmark directories and move to them" },
"bit": { en: "Bit documentation: https://bit.dev/docs" },
"black": { en: "Python code formatter" },
"blitz": { en: "Blitz.js CLI is your single access point for interacting with your app, from database management to code generation" },
"bosh": { en: "Bosh cli to managed your bosh deployment" },
"br": { en: "Broot lets you explore file hierarchies with a tree-like view, manipulate files, launch actions, and define your own shortcuts. broot is best launched as br: this shell function gives you access to more commands, especially cd. The br shell function is interactively installed on first broot launch. Flags and options can be classically passed on launch but also written in the configuration file. Each flag has a counter-flag so that you can cancel at command line a flag which has been set in the configuration file" },
"brew": { en: "Package manager for macOS", zhCN: "macOS 的软件包管理器", zhTW: "macOS 的軟體包管理器" },
"broot": { en: "Broot lets you explore file hierarchies with a tree-like view, manipulate files, launch actions, and define your own shortcuts. broot is best launched as br: this shell function gives you access to more commands, especially cd. The br shell function is interactively installed on first broot launch. Flags and options can be classically passed on launch but also written in the configuration file. Each flag has a counter-flag so that you can cancel at command line a flag which has been set in the configuration file" },
"browser-sync": { en: "Keep multiple browsers & devices in sync when building websites" },
"btop": { en: "Beautifuler htop (interactive process viewer)" },
"build-storybook": { en: "Storybook build CLI tools" },
"bun": { en: "A fast bundler, transpiler, JavaScript Runtime and package manager for web software" },
"bundle": { en: "Ruby Dependency Management" },
"bwdc": { en: "Bitwarden Directory Connector" },
"c++": { en: "C++ compiler" },
"caffeinate": { en: "Prevent the system from sleeping on behalf of a utility" },
"cal": { en: "Displays a calendar and the date of Easter" },
"cap": { en: "The Capacitor command-line interface (CLI) tool is used to develop Capacitor apps" },
"capacitor": { en: "The Capacitor command-line interface (CLI) tool is used to develop Capacitor apps" },
"cargo": { en: "CLI Interface for Cargo" },
"cat": { en: "Concatenate and print files", zhCN: "连接并打印文件", zhTW: "連線並列印檔案" },
"cci": { en: "CumulusCI command line interface" },
"cd": { en: "Change the shell working directory", zhCN: "更改 shell 工作目录", zhTW: "更改 shell 工作目錄" },
"cdk": { en: "AWS CDK CLI" },
"cdk8s": { en: "CDK for K8s" },
"cf": { en: "Cloudfoundry cli" },
"charm": { en: "Do Charm stuff; run without arguments for a TUI or use the sub-commands like a pro" },
"checkov": { en: "Checkov scans cloud infrastructure configurations to find misconfigurations before they're deployed" },
"chezmoi": { en: "Manage your dotfiles across multiple diverse machines, securely" },
"chmod": { en: "Change file modes or Access Control Lists", zhCN: "更改文件模式或访问控制列表", zhTW: "更改檔案模式或訪問控制列表" },
"chown": { en: "Change the user and/or group ownership of a given file, directory, or symbolic link", zhCN: "更改给定文件、目录或符号链接的用户和/或组所有权", zhTW: "更改給定檔案、目錄或符號連結的使用者和/或組所有權" },
"chsh": { en: "Change your login shell" },
"cicada": { en: "Write CI/CD Pipelines in TypeScript" },
"circleci": { en: "CircleCI CLI" },
"clang": { en: "Clang LLVM compiler" },
"clang++": { en: "Clang LLVM compiler for C++" },
"clear": { en: "Clear the terminal screen", zhCN: "清空终端屏幕", zhTW: "清空終端螢幕" },
"cliff-jumper": { en: "A small CLI tool to create a semantic release and git-cliff powered Changelog" },
"clilol": { en: "A cli for omg.lol" },
"clion": { en: "CLion cli" },
"clojure": { en: "Use the Clojure tools to run Clojure programs on the JVM, start a REPL, or invoke a specific function with data" },
"cloudflared": { en: "Cloudflared connects your machine or user identity to Cloudflare's global network" },
"cmake": { en: "Command-line interface of the cross-platform buildsystem generator CMake" },
"coda": { en: "Coda Local development CLI tool. It comes bundled with the Pack SDK and makes it easy to build and manage Packs from the CLI" },
"code": { en: "Visual Studio Code" },
"code-insiders": { en: "Visual Studio Code" },
"codesign": { en: "Create and manipulate code signatures" },
"command": { en: "Run an external command" },
"composer": { en: "Composer Command" },
"conda": { en: "Conda package manager" },
"copilot": { en: "👩‍✈️ Launch and manage containerized applications on AWS" },
"copyfile": { en: "Oh-My-Zsh plugin that copies the contents of a file to the clipboard" },
"copypath": { en: "Oh-My-Zsh plugin that copies the path of given directory or file to the clipboard" },
"cordova": { en: "Manage your Cordova application" },
"cot": { en: "Command-line utility for CotEditor" },
"cp": { en: "Copy files and directories", zhCN: "复制文件或目录", zhTW: "複製檔案和目錄" },
"create-completion-spec": { en: "Setup fig folder and create spec with the given name" },
"create-nx-workspace": { en: "Create a new Nx workspace" },
"create-react-app": { en: "Creates a new React project" },
"create-react-native-app": { en: "Creates a new React Native project" },
"create-t3-app": { en: "A CLI for creating web applications with the t3 stack" },
"create-video": { en: "CLI used to create remotion video project" },
"create-vite": { en: "Create a new project powered by Vite" },
"create-web3-frontend": { en: "Quickly create a Next.js project with wagmi and TailwindCSS ready to go" },
"croc": { en: "Croc is a tool that allows any two computers to simply and securely transfer files and folders" },
"crontab": { en: "Maintain crontab file for individual users", zhCN: "为单个用户维护 crontab 文件", zhTW: "為單個使用者維護 crontab 檔案" },
"csdx": { en: "Content Stack CLI" },
"curl": { en: "Transfer a URL", zhCN: "传输 URL", zhTW: "傳輸 URL" },
"cut": { en: "Cut out selected portions of each line of a file", zhCN: "从文件的每一行中截取选定部分", zhTW: "從檔案的每一行中擷取選定部分" },
"cw": { en: "Top level cli commands" },
"dapr": { en: "Dapr CLI" },
"dart": { en: "A command-line utility for Dart development" },
"date": { en: "Display or set date and time", zhCN: "显示或设置日期和时间", zhTW: "顯示或設定日期和時間" },
"dateseq": { en: "Nifty command line date and time utilities; fast date calculations and conversion in the shell" },
"datree": { en: "Datree can be used on the command line to run policies against Kubernetes manifests YAML files or Helm charts" },
"dbt": { en: "CLI for dbt - Data Build Tool" },
"dcli": { en: "Dashlane CLI" },
"dd": { en: "Convert and copy a file", zhCN: "转换并复制文件", zhTW: "轉換並複製檔案" },
"ddev": { en: "DDEV-Local local development environment" },
"ddosify": { en: "High-performance load testing tool, written in Golang" },
"defaultbrowser": { en: "Change your default browser from the CLI" },
"defaults": { en: "Command line interface to a user's defaults" },
"degit": { en: "Straightforward project scaffolding" },
"deno": { en: "A modern JavaScript and TypeScript runtime" },
"deployctl": { en: "Command line tool for Deno Deploy" },
"deta": { en: "Deta CLI for managing Deta Micros" },
"df": { en: "Display free disk space", zhCN: "显示可用磁盘空间", zhTW: "顯示可用磁碟空間" },
"diff": { en: "Compare files line by line" },
"dig": { en: "Domain Information Groper", zhCN: "域名信息查询工具(Domain Information Groper)", zhTW: "域名資訊查詢工具(Domain Information Groper)" },
"direnv": { en: "Unclutter your .profile" },
"dirname": { en: "Return directory portion of pathname", zhCN: "返回路径名的目录部分", zhTW: "返回路徑名的目錄部分" },
"ditto": { en: "Copy directory hierarchies, create and extract archives" },
"django-admin": { en: "Utility script for the Django Web framework" },
"dnf": { en: "DNF package manager (RHEL/Rocky/Alma/Fedora)", zhCN: "DNF 软件包管理器(RHEL/Rocky/Alma/Fedora)", zhTW: "DNF 軟體包管理器(RHEL/Rocky/Alma/Fedora)" },
"do": { en: "Do the command" },
"do-release-upgrade": { en: "Upgrade Ubuntu to latest release" },
"docker": { en: "A self-sufficient runtime for containers", zhCN: "自给自足的容器运行时", zhTW: "自給自足的容器執行時" },
"docker-compose": { en: "Define and run multi-container applications with Docker", zhCN: "使用 Docker 定义并运行多容器应用", zhTW: "使用 Docker 定義並執行多容器應用" },
"doctl": { en: "The official DigitalOcean command line interface (CLI)" },
"dog": { en: "A command-line DNS client" },
"doggo": { en: "DNS Client for Humans" },
"doppler": { en: "The official Doppler CLI" },
"dos2unix": { en: "DOS to Unix file format converter" },
"dotenv": { en: "Loads environment variables from .env" },
"dotenv-vault": { en: "CLI for dotenv-vault" },
"dotnet": { en: "The dotnet cli" },
"dpkg": { en: "Debian package management system" },
"dprint": { en: "A pluggable and configurable code formatting platform written in Rust" },
"drush": { en: "Drush is a command line shell and Unix scripting interface for Drupal" },
"dscacheutil": { en: "Utility for managing the Directory Service cache" },
"dscl": { en: "Directory Service command line utility" },
"dtm": { en: "DevStream is an open-source DevOps toolchain manager" },
"du": { en: "Display disk usage statistics", zhCN: "显示磁盘用量统计", zhTW: "顯示磁碟用量統計" },
"dust": { en: "Like du but more intuitive" },
"eas": { en: "EAS CLI is the command-line app that you will use to interact with EAS services from your terminal" },
"eb": { en: "AWS Elastic Beanstalk" },
"echo": { en: "Write arguments to the standard output", zhCN: "将参数写入标准输出", zhTW: "將引數寫入標準輸出" },
"electron": { en: "Build cross platform desktop apps with JavaScript, HTML and CSS" },
"eleventy": { en: "Eleventy is a simpler static site generator" },
"elif": { en: "Execute if the previous condition returned 0" },
"elixir": { en: "Elixir Language" },
"elm": { en: "Fig spec for the Elm language cli" },
"elm-format": { en: "Format your code in the Elm idiomatic way" },
"elm-json": { en: "Deal with your elm.json" },
"else": { en: "Execute this command if the test returned 1" },
"emacs": { en: "An extensible, customizable, free/libre text editor — and more" },
"enapter": { en: "Cross-platform device management command-line tool for Enapter Energy Management System Toolkit" },
"encore": { en: "Encore is the fastest way of developing backend applications" },
"env": { en: "Set environment and execute command, or print environment", zhCN: "设置环境并执行命令,或打印环境变量", zhTW: "設定環境並執行命令,或列印環境變數" },
"envchain": { en: "Set environment variables with macOS keychain or D-Bus secret service" },
"esbuild": { en: "An extremely fast JavaScript bundler" },
"eslint": { en: "Pluggable JavaScript linter" },
"exa": { en: "A modern replacement for ls" },
"exec": { en: "Replace the current shell with a program" },
"exercism": { en: "Solve coding exercises in your chosen programming languages" },
"expo": { en: "Tools for creating, running, and deploying Universal Expo and React Native apps" },
"expo-cli": { en: "Tools for creating, running, and deploying Universal Expo and React Native apps" },
"export": { en: "Export variables" },
"expressots": { en: "ExpressoTS CLI" },
"eza": { en: "A modern replacement for ls" },
"fastlane": { en: "Fastlane is an open source platform aimed at simplifying Android and iOS deployment" },
"fastly": { en: "A CLI for interacting with the Fastly platform" },
"fd": { en: "A simple, fast and user-friendly alternative to 'find'" },
"fdisk": { en: "Manipulate disk partition table" },
"ffmpeg": { en: "Play, record, convert, and stream audio and video" },
"figterm": { en: "Fig's terminal layer" },
"file": { en: "Determine file type" },
"fin": { en: "Docksal command line utility" },
"find": { en: "Walk a file hierarchy", zhCN: "遍历文件层次结构", zhTW: "遍歷檔案層次結構" },
"firefox": { en: "Free open-source web browser developer by Mozilla" },
"fisher": { en: "A plugin manager for Fish" },
"flutter": { en: "Run flutter command" },
"fly": { en: "The flyctl is a command-line interface for fly.io" },
"flyctl": { en: "The flyctl is a command-line interface for fly.io" },
"fmt": { en: "Simple text formatter" },
"fnm": { en: "Fast Node Manager" },
"fold": { en: "Fold long lines for finite width output device" },
"for": { en: "Perform a set of commands multiple times" },
"forc": { en: "Fuel Orchestrator" },
"forge": { en: "A command line interface for managing Atlassian-hosted apps" },
"fvm": { en: "Flutter Version Management: A cli to manage Flutter SDK versions" },
"fzf": { en: "A general-purpose command-line fuzzy finder" },
"fzf-tmux": { en: "Opens a fuzzy finder in a tmux pane" },
"g++": { en: "The default C++ compiler for most linux distributions" },
"ganache-cli": { en: "Fast Ethereum RPC client" },
"gatsby": { en: "Gatsby CLI" },
"gcc": { en: "The default compiler for most linux distributions" },
"gcloud": { en: "Manage Google Cloud Platform resources and developer workflow" },
"gem": { en: "Ruby package manager" },
"gh": { en: "GitHub's CLI tool" },
"ghq": { en: "'ghq' provides a way to organize remote repository clones, like go get does. When you clone a remote repository by ghq get, ghq makes a directory under a specific root directory (by default ~/ghq) using the remote repository URL’s host and path" },
"gibo": { en: "Easy access to gitignore boilerplates" },
"git": { en: "Distributed version control system", zhCN: "分布式版本控制系统", zhTW: "分散式版本控制系統" },
"git-cliff": { en: "A highly customizable changelog generator ⛰️" },
"git-flow": { en: "A collection of Git extensions to provide high-level repository operations for Vincent Driessen's branching model" },
"git-profile": { en: "Switch profiles" },
"git-quick-stats": { en: "Git quick statistics is a simple and efficient way to access various statistics in git repository" },
"github": { en: "Open a git repository in GitHub Desktop" },
"glow": { en: "Render markdown on the CLI, with pizzazz!" },
"gltfjsx": { en: "GLTF to JSX converter" },
"go": { en: "Go is a tool for managing Go source code" },
"goctl": { en: "A cli tool to generate go-zero code" },
"goland": { en: "GoLand cli" },
"googler": { en: "Google from the command-line" },
"goreleaser": { en: "Deliver Go binaries as fast and easily as possible" },
"gource": { en: "Gource is an OpenGL-based 3D visualisation tool for source control repositories" },
"gpg": { en: "Encryption and signing tool" },
"gradle": { en: "Gradle is an open-source build automation tool that is designed to be flexible enough to build almost any type of software" },
"graphcdn": { en: "GraphCDN CLI" },
"grep": { en: "Matches patterns in input text. Supports simple patterns and regular expressions", zhCN: "匹配输入文本中的模式。支持简单模式和正则表达式", zhTW: "匹配輸入文字中的模式。支援簡單模式和正規表示式" },
"grex": { en: "Command-line tool for generating regular expressions from user-provided test cases" },
"gron": { en: "Gron is a tool to make it easier to understand big blobs of JSON" },
"gt": { en: "Graphite.dev CLI" },
"gum": { en: "A tool for glamorous shell scripts" },
"hardhat": { en: "Ethereum development environment" },
"hasura": { en: "Hasura GraphQL engine command line tool" },
"hb-service": { en: "The hb-service command is provided by homebridge-config-ui-x" },
"head": { en: "Output the first part of files", zhCN: "输出文件的开头部分", zhTW: "輸出檔案的開頭部分" },
"helm": { en: "The Helm package manager for Kubernetes" },
"helmfile": { en: "Deploy helm charts" },
"herd": { en: "Herd is a blazing fast, native Laravel and PHP development environment for macOS. It provides everything that you need to get started with Laravel development" },
"hexo": { en: "Command line interface for Hexo, a static site generator" },
"hop": { en: "Interact with Hop in your terminal" },
"hostname": { en: "Set or print name of current host system" },
"htop": { en: "Improved top (interactive process viewer)", zhCN: "增强版 top(交互式进程查看器)", zhTW: "增強版 top(互動式行程檢視器)" },
"http": { en: "HTTPie: command-line HTTP client for the API era" },
"https": { en: "HTTPie: command-line HTTP client for the API era" },
"httpy": { en: "Programmable command-line HTTP client for the API" },
"hub": { en: "Distributed version control system", zhCN: "分布式版本控制系统", zhTW: "分散式版本控制系統" },
"hugo": { en: "Hugo builds your site" },
"hx": { en: "A post-modern text editor" },
"hyper": { en: "Hyper is an Electron-based terminal" },
"hyperfine": { en: "A command-line benchmarking tool" },
"iconv": { en: "Character set conversion" },
"id": { en: "The id utility displays the user and group names and numeric IDs, of the calling process, to the standard output. If the real and effective IDs are different, both are displayed, otherwise only the real ID is displayed. If a user (login name or user ID) is specified, the user and group IDs of that user are displayed. In this case, the real and effective IDs are assumed to be the same", zhCN: "id 工具把调用进程的用户名、组名和数字 ID 输出到标准输出。若真实 ID 与有效 ID 不同,两者都会显示,否则只显示真实 ID。若指定了用户(登录名或用户 ID),则显示该用户的用户和组 ID,此时假定真实 ID 与有效 ID 相同", zhTW: "id 工具把呼叫行程的使用者名稱、組名和數字 ID 輸出到標準輸出。若真實 ID 與有效 ID 不同,兩者都會顯示,否則只顯示真實 ID。若指定了使用者(登入名或使用者 ID),則顯示該使用者的使用者和組 ID,此時假定真實 ID 與有效 ID 相同" },
"idea": { en: "InteliJ IDEA cli" },
"iex": { en: "Elixir Interactive Shell" },
"if": { en: "Conditionally execute based on the return value of a command" },
"ignite-cli": { en: "Ignite is a CLI that helps you spin up a new React Native app using a battle-tested tech stack" },
"install": { en: "The file(s) are copied to the target file or directory. If the destination is a directory, then the file is copied into directory with its original filename. If the target file already exists, it is either renamed to file.old if the -b option is given or overwritten if permissions allow. An alternate backup suffix may be specified via the -B option's argument" },
"ionic": { en: "The Ionic command-line interface (CLI) is the go-to tool for developing Ionic apps" },
"ip": { en: "Show / manipulate routing, network devices, interfaces and tunnels", zhCN: "显示/操作路由、网络设备、接口和隧道", zhTW: "顯示/操作路由、網路裝置、介面和隧道" },
"ipatool": { en: "IPATool is a command line tool that allows you to search for iOS apps on the App Store and download a copy of the app package, known as an ipa file" },
"j": { en: "A faster way to navigate your filesystem" },
"java": { en: "Launch a Java application" },
"jenv": { en: "Manage your Java environment" },
"jest": { en: "A delightful JavaScript Testing Framework with a focus on simplicity" },
"jmeter": { en: "Apache JMeter - 100% Java Load Testing Tool" },
"join": { en: "The join utility performs an 'equality join' on the specified files and writes the result to the standard output. The 'join field' is the field in each file by which the files are compared. The first field in each line is used by default. There is one line in the output for each pair of lines in file1 and file2 which have identical join fields. Each output line consists of the join field, the remaining fields from file1 and then the remaining fields from file2", zhCN: "join 工具对指定文件执行“等值连接”,并将结果写入标准输出。“连接字段”是各文件中用于比较的字段,默认使用每行的第一个字段。file1 与 file2 中连接字段相同的每一对行都会输出一行;每行由连接字段、file1 的其余字段和 file2 的其余字段组成", zhTW: "join 工具對指定檔案執行“等值連線”,並將結果寫入標準輸出。“連線欄位”是各檔案中用於比較的欄位,預設使用每行的第一個欄位。file1 與 file2 中連線欄位相同的每一對行都會輸出一行;每行由連線欄位、file1 的其餘欄位和 file2 的其餘欄位組成" },
"journalctl": { en: "Query the systemd journal", zhCN: "查询 systemd 日志", zhTW: "查詢 systemd 日誌" },
"jq": { en: "Command-line JSON processor" },
"julia": { en: "The Julia Programming Language" },
"jupyter": { en: "An interactive computing environment for notebook programming" },
"just": { en: "Just a command runner" },
"k3d": { en: "K3d is a lightweight wrapper to run k3s in Docker" },
"k6": { en: "Grafana k6 is an open-source load testing tool that makes performance testing easy" },
"k9s": { en: "K9s is a terminal based UI to interact with your Kubernetes clusters" },
"kafkactl": { en: "Command-line interface for Apache Kafka" },
"kamal": { en: "Deploy web apps anywhere" },
"kdoctor": { en: "Tool that helps to set up the environment for Kotlin Multiplatform Mobile app development" },
"keytool": { en: "Key and Certificate Management Tool" },
"kill": { en: "Terminate or signal a process", zhCN: "终止进程或向其发送信号", zhTW: "終止行程或向其傳送訊號" },
"killall": { en: "Kill processes by name" },
"kind": { en: "Kubernetes IN Docker - local clusters for testing Kubernetes" },
"klist": { en: "Reads and displays the current tickets in the credential cache (also known as the ticket file)" },
"knex": { en: "SQL query builder for JavaScript" },
"kool": { en: "Cloud and docker environments made easy" },
"kotlinc": { en: "Kotlin compiler for JVM" },
"kubectx": { en: "Switch between Kubernetes-contexts" },
"kubens": { en: "Switch between Kubernetes-namespaces" },
"laravel": { en: "Laravel Installer" },
"launchctl": { en: "Interfaces with launchd" },
"ldd": { en: "Print shared library dependencies" },
"leaf": { en: "Create and interact with your leaf projects" },
"lerna": { en: "A tool for managing JavaScript projects with multiple packages" },
"less": { en: "Opposite of more", zhCN: "与 more 相反", zhTW: "與 more 相反" },
"lima": { en: "Lima is an alias for \"limactl shell $LIMA_INSTANCE\"" },
"limactl": { en: "Control the Lima(Linux virtual machines)" },
"ln": { en: "Create (default hard) symbolic links to files", zhCN: "为文件创建符号链接(默认为硬链接)", zhTW: "為檔案建立符號連結(預設為硬連結)" },
"locust": { en: "Locust is an easy to use, scriptable and scalable Python-based performance testing tool" },
"login": { en: "Begin session on the system" },
"lp": { en: "Print files" },
"lpass": { en: "Command line interface for LastPass" },
"ls": { en: "List directory contents", zhCN: "列出目录内容", zhTW: "列出目錄內容" },
"lsblk": { en: "List block devices" },
"lsd": { en: "An ls command with a lot of pretty colors and some other stuff" },
"lsof": { en: "List open files" },
"luz": { en: "A next-generation build system for Apple Darwin-based systems" },
"lvim": { en: "Hyperextensible Vim-based text editor" },
"m": { en: "Swiss Army Knife for macOS" },
"mackup": { en: "Mackup" },
"magento": { en: "Open-source E-commerce" },
"maigret": { en: "Maigret is an easy-to-use and powerful OSINT tool for collecting a dossier on a person by username only" },
"mailsy": { en: "⚡️ Quickly generate a disposable email straight from terminal" },
"mamba": { en: "Mamba is a reimplementation of the conda package manager in C++" },
"man": { en: "Format and display the on-line manual pages" },
"mas": { en: "A simple command line interface for the Mac App Store" },
"mdfind": { en: "Finds files matching a given query" },
"mdls": { en: "Lists the metadata attributes for the specified file" },
"meroxa": { en: "The Meroxa CLI" },
"meteor": { en: "Run the meteor command-line tool" },
"mgnl": { en: "Magnolia CLI is a command line interface (CLI) tool to set up and facilitate light development with Magnolia" },
"micro": { en: "A modern and intuitive terminal-based text editor" },
"mikro-orm": { en: "TypeScript ORM for Node.js based on Data Mapper, Unit of Work and Identity Map patterns. Supports MongoDB, MySQL, MariaDB, PostgreSQL and SQLite databases" },
"minectl": { en: "Create Minecraft Server on different cloud provider" },
"minikube": { en: "Minikube provisions and manages local Kubernetes clusters optimized for development workflows" },
"mix": { en: "Build tool for Elixir" },
"mkdir": { en: "Make directories", zhCN: "创建目录", zhTW: "建立目錄" },
"mkdocs": { en: "Project documentation with Markdown" },
"mkfifo": { en: "Make FIFOs (first-in, first-out)" },
"mkinitcpio": { en: "Create an initial ramdisk environment" },
"mknod": { en: "Create device special file" },
"mob": { en: "Fast git handover for remote collaboration with mob.sh" },
"molecule": { en: "Molecule aids in the development and testing of Ansible roles" },
"mongocli": { en: "CLI tool to manage your MongoDB Cloud" },
"mongoimport": { en: "Import data from a JSON, CSV, or TSV file into a MongoDB instance" },
"mongosh": { en: "The MongoDB Shell, mongosh is a fully functional JavaScript and Node.js 14.x REPL environment for interacting with MongoDB deployments" },
"more": { en: "Opposite of less", zhCN: "与 less 相对的翻页查看工具", zhTW: "與 less 相對的翻頁檢視工具" },
"mount": { en: "Mount disks and manage subtrees" },
"multipass": { en: "Create, control and connect to Ubuntu instances" },
"mv": { en: "Move & rename files and folders", zhCN: "移动并重命名文件和文件夹", zhTW: "移動並重命名檔案和資料夾" },
"mvn": { en: "Maven - a Java based project management and comprehension tool" },
"mypy": { en: "Mypy is a static type checker for Python" },
"mysql": { en: "Mysql is a terminal-based front-end to MySQL" },
"n": { en: "Node version management" },
"nano": { en: "Nano's ANOther editor, an enhanced free Pico clone", zhCN: "Nano 的 ANOther 编辑器,一个增强的免费 Pico 克隆", zhTW: "Nano 的 ANOther 編輯器,一個增強的免費 Pico 克隆" },
"nativescript": { en: "The NativeScript CLI lets you create, build, and deploy NativeScript based apps on iOS and Android devices" },
"nc": { en: "Arbitrary TCP and UDP connections and listens" },
"ncal": { en: "Displays a calendar and the date of Easter" },
"ncu": { en: "Upgrade your npm package.json dependencies to the latest versions, ignoring specified versions" },
"neofetch": { en: "The most complete system information CLI tool" },
"nest": { en: "Nest CLI" },
"netlify": { en: "Netlify command line tool" },
"networkQuality": { en: "Measure the different aspects of network quality" },
"networksetup": { en: "Configuration tool for network settings in System Preferences" },
"newman": { en: "Newman is a command-line collection runner for Postman" },
"next": { en: "Next.js CLI to start, build and export your application" },
"nextflow": { en: "Nextflow enables scalable and reproducible scientific workflows using software containers. It allows the adaptation of pipelines written in the most common scripting languages" },
"ng": { en: "CLI interface for Angular" },
"nginx": { en: "Nginx (pronounced ``engine x'') is an HTTP and reverse proxy server, a mail proxy server, and a generic TCP/UDP proxy server. It is known for its high performance, stability, rich feature set, simple configuration, and low resource consumption" },
"ngrok": { en: "Tunnel local ports to public URLs and inspect traffic" },
"nhost": { en: "Nhost's command-line" },
"ni": { en: "Use the right package manager - install" },
"nl": { en: "Line numbering filter" },
"nmap": { en: "Network exploration tool and security / port scanner" },
"nocorrect": { en: "ZSH pre-command modifier that disables correction" },
"node": { en: "Run the node interpreter", zhCN: "运行 Node.js 解释器", zhTW: "執行 Node.js 直譯器" },
"noglob": { en: "ZSH pre-command modifier that disables glob expansion" },
"northflank": { en: "Manage your Northflank resources from the command line" },
"np": { en: "A better npm publish" },
"npm": { en: "Node package manager", zhCN: "Node 软件包管理器", zhTW: "Node 軟體包管理器" },
"npx": { en: "Execute binaries from npm packages" },
"nr": { en: "Use the right package manager - run" },
"nrm": { en: "Use the right package manage - remove" },
"ns": { en: "The NativeScript CLI lets you create, build, and deploy NativeScript based apps on iOS and Android devices" },
"nu": { en: "Use the right package manage - upgrade" },
"nuxi": { en: "Nuxt 3 CLI" },
"nvim": { en: "Hyperextensible Vim-based text editor" },
"nvm": { en: "Node Package Manager" },
"nx": { en: "Fig completions for Nx by Nrwl" },
"nylas": { en: "A command line interface for Nylas's API" },
"oci": { en: "Oracle Cloud Infrastructure CLI" },
"od": { en: "Octal, decimal, hex, ASCII dump" },
"okta": { en: "The Okta CLI is the easiest way to get started with Okta!" },
"okteto": { en: "Okteto - Remote Development Environments powered by Kubernetes" },
"ollama": { en: "A command-line tool for managing and deploying machine learning models" },
"omz": { en: "Oh My Zsh" },
"onboardbase": { en: "Onboardbase manages app secrets and credentials securely with team work and contractors in mind" },
"op": { en: "Official 1Password CLI" },
"opa": { en: "Open Policy Agent (OPA)" },
"open": { en: "Open files, apps, or URLs using default application" },
"osascript": { en: "Execute OSA scripts (AppleScript, JavaScript, etc.)" },
"osqueryi": { en: "Your OS as a high-performance relational database" },
"oxlint": { en: "A high performance linter for the Oxidation Compiler" },
"pac": { en: "Power Platform CLI" },
"pageres": { en: "Capture website screenshots" },
"palera1n": { en: "Jailbreaking tool for iOS/iPadOS 15.x-16.x arm64" },
"pandoc": { en: "A universal document converter" },
"paper": { en: "The Paper CLI" },
"pass": { en: "Pass - stores, retrieves, generates, and synchronizes passwords securely" },
"passwd": { en: "Modify a user's password" },
"paste": { en: "The paste utility concatenates the corresponding lines of the given input files, replacing all but the last file's newline characters with a single tab character, and writes the resulting lines to standard output. If end-of-file is reached on an input file while other input files still contain data, the file is treated as if it were an endless source of empty lines", zhCN: "paste 工具把各输入文件对应的行拼接起来,除最后一个文件外,把换行符替换为单个制表符,并将结果写入标准输出。若某个输入文件已到末尾而其他文件仍有数据,该文件被视作无限的空行来源", zhTW: "paste 工具把各輸入檔案對應的行拼接起來,除最後一個檔案外,把換行符替換為單個製表符,並將結果寫入標準輸出。若某個輸入檔案已到末尾而其他檔案仍有資料,該檔案被視作無限的空行來源" },
"pathchk": { en: "Check pathnames for POSIX portability" },
"pdfunite": { en: "Combine multiple pdfs" },
"pg_dump": { en: "Dumps a database as a text file or to other formats" },
"php": { en: "Run the PHP interpreter" },
"phpstorm": { en: "PhpStorm cli" },
"phpunit": { en: "The PHPUnit is a command-line test runner that can be invoked through the phpunit command" },
"phpunit-watcher": { en: "Automatically rerun PHPUnit tests when source code changes" },
"pijul": { en: "A distributed version control system that is at the same time theoretically sound, fast and easy to learn and use" },
"ping": { en: "Send ICMP ECHO_REQUEST to network hosts", zhCN: "向网络主机发送 ICMP ECHO_REQUEST", zhTW: "向網路主機發送 ICMP ECHO_REQUEST" },
"pip": { en: "Python package manager", zhCN: "Python 软件包管理器", zhTW: "Python 軟體包管理器" },
"pip3": { en: "Python package manager", zhCN: "Python 软件包管理器", zhTW: "Python 軟體包管理器" },
"pipenv": { en: "Python package manager", zhCN: "Python 软件包管理器", zhTW: "Python 軟體包管理器" },
"pipx": { en: "Install and Run Python Applications in Isolated Environments" },
"pkg-config": { en: "Return metainformation about installed libraries" },
"pkgutil": { en: "Query and manipulate for macOS Installer packages and receipts" },
"pkill": { en: "Send the specified signal (by default SIGTERM) to each specified process" },
"plutil": { en: "Check the syntax of property list files, or convert a plist file from one format to another. Specifying - as an input file reads from stdin" },
"pm2": { en: "Daemon process manager" },
"pmset": { en: "Power management settings" },
"pnpm": { en: "Fast, disk space efficient package manager", zhCN: "快速、节省磁盘空间的软件包管理器", zhTW: "快速、節省磁碟空間的軟體包管理器" },
"pnpx": { en: "Execute binaries from npm packages" },
"pocketbase": { en: "PocketBase CLI" },
"pod": { en: "CocoaPods, the Cocoa library package manager" },
"podman": { en: "Manage containers, pods, and images with Podman", zhCN: "使用 Podman 管理容器、Pod 和镜像", zhTW: "使用 Podman 管理容器、Pod 和映象" },
"poetry": { en: "Poetry is a tool for dependency management and packaging in Python" },
"pre-commit": { en: "Pre-commit" },
"premake": { en: "Premake CLI" },
"preset": { en: "Elegant, ecosystem-agnostic scaffolding tool" },
"prettier": { en: "Run Prettier from the command line" },
"prisma": { en: "Prisma is a modern DB toolkit to query, migrate and model your database" },
"pro": { en: "Manage Ubuntu Pro services from Canonical" },
"progressline": { en: "⏳Track commands progress in a compact one-line format" },
"projj": { en: "Manage repository easily" },
"pry": { en: "Interactive Ruby" },
"ps": { en: "Report a snapshot of the current processes", zhCN: "报告当前进程的快照", zhTW: "報告當前行程的快照" },
"pscale": { en: "Pscale is a CLI library for communicating with PlanetScale's API" },
"psql": { en: "Psql is a terminal-based front-end to PostgreSQL" },
"pulumi": { en: "Pulumi's open source infrastructure as code SDK enables you to create, deploy, and manage infrastructure on any cloud, using your favorite languages" },
"pushd": { en: "Change the current directory, and push the old current directory onto the directory stack" },
"pwd": { en: "Return working directory name", zhCN: "返回工作目录名称", zhTW: "返回工作目錄名稱" },
"pycharm": { en: "PyCharm cli" },
"pyenv": { en: "Pyenv" },
"python": { en: "Run the python interpreter", zhCN: "运行 Python 解释器", zhTW: "執行 Python 直譯器" },
"python3": { en: "Run the python interpreter", zhCN: "运行 Python 解释器", zhTW: "執行 Python 直譯器" },
"q": { en: "The Amazon Q CLI" },
"qodana": { en: "Run Qodana as fast as possible, with minimum effort required" },
"quasar": { en: "Quasar Framework CLI" },
"quickmail": { en: "Quickmail is a terminal-based solution to send mails" },
"r": { en: "Start R or invoke an R tool using CMD" },
"rails": { en: "Ruby on Rails CLI" },
"railway": { en: "CLI for managing Railway Apps" },
"rake": { en: "A ruby build program with capabilities similar to make" },
"rancher": { en: "The Rancher CLI (Command Line Interface) is a unified tool that you can use to interact with Rancher" },
"rbenv": { en: "Pick a Ruby version for your application and guarantee that your development environment matches production" },
"rclone": { en: "The Swiss army knife of cloud storage" },
"react-native": { en: "Command line tools that ship with react-native in form of the @react-native-community/cli package" },
"readlink": { en: "Print resolved symbolic links or canonical file names", zhCN: "打印解析后的符号链接或规范文件名", zhTW: "列印解析後的符號連結或規範檔案名" },
"redwood": { en: "Redwood provides a first-class CLI that helps you at every stage of development, from your first commit to your first deploy" },
"remix": { en: "Remix CLI to start, build and export your application" },
"remotion": { en: "Create videos programmatically in React" },
"repeat": { en: "Interpret the result as a number and repeat the commands this many times" },
"rg": { en: "Recursively searches current directory for lines matching a pattern" },
"rich": { en: "Rich text and formatting in the terminal" },
"rm": { en: "Remove directory entries", zhCN: "移除目录条目", zhTW: "移除目錄條目" },
"rmdir": { en: "Remove directories" },
"robot": { en: "CLI for running Robot Framework automation tests" },
"rojo": { en: "Enables professional-grade development tools for Roblox developers" },
"rollup": { en: "Next-generation ES module bundler" },
"rome": { en: "Rome CLI" },
"rscript": { en: "Scripting Front-End for R" },
"rsync": { en: "Rsync is a file transfer program capable of efficient remote update via a fast differencing algorithm", zhCN: "Rsync 是一种文件传输程序,能通过快速差异算法高效地进行远程更新", zhTW: "Rsync 是一種檔案傳輸程式,能通過快速差異演算法高效地進行遠端更新" },
"rubocop": { en: "A Ruby static code analyzer and formatter, based on the community Ruby style guide" },
"ruby": { en: "Interpreted object-oriented scripting language" },
"rubymine": { en: "RubyMine cli" },
"ruff": { en: "Ruff: An extremely fast Python linter" },
"rugby": { en: "Cache Cocoa 🌱 pods for faster rebuild and indexing Xcode project. https://github.com/swiftyfinch/Rugby" },
"rush": { en: "Multi-Project Build Tool" },
"rushx": { en: "Run arbitrary package scripts for rush project. analogous to npm run" },
"rustc": { en: "CLI for rustc" },
"rustrover": { en: "RustRover cli" },
"rustup": { en: "The Rust toolchain installer" },
"rvm": { en: "Ruby version manager" },
"sake": { en: "🍶 Swift-based utility for managing project commands, inspired by Make" },
"sam": { en: "AWS Serverless Application Model CLI" },
"sanity": { en: "Sanity CLI tool for managing Sanity installations, managing plugins, schemas and datasets" },
"sapphire": { en: "CLI for the Sapphire Framework" },
"scarb": { en: "Scarb, The build toolchain and package manager for Cairo and Starknet ecosystems" },
"scc": { en: "Sloc, Cloc and Code. Count lines of code in a directory with complexity estimation" },
"scp": { en: "Copies files or directories between hosts on a network", zhCN: "在网络上的主机之间复制文件或目录", zhTW: "在網路上的主機之間複製檔案或目錄" },
"screen": { en: "Screen manager with VT100/ANSI terminal emulation" },
"sed": { en: "Stream editor", zhCN: "流编辑器", zhTW: "流編輯器" },
"seq": { en: "Print sequences of numbers. (Defaults to increments of 1)", zhCN: "打印数字序列(默认按 1 递增;BSD/macOS 在起始值大于结束值时按 -1 递减)", zhTW: "列印數字序列(預設按 1 遞增;BSD/macOS 在起始值大於結束值時按 -1 遞減)" },
"sequelize": { en: "The Sequelize Command Line Interface" },
"serve": { en: "Static file serving and directory listing" },
"serverless": { en: "Zero-friction serverless development" },
"sftp": { en: "OpenSSH secure file transfer" },
"sha1sum": { en: "Print or check SHA1 (160-bit) checksums" },
"shadcn-ui": { en: "Shadcn UI CLI" },
"shasum": { en: "Print or Check SHA Checksums" },
"shelve": { en: "Shelve CLI a command-line interface designed for the Shelve platform. This tool enables users to authenticate with Shelve, facilitating the seamless transfer of environment variables for project collaboration within a team directly through the terminal interface" },
"shortcuts": { en: "Command-line utility for running shortcuts" },
"shred": { en: "Overwrite a file to hide its contents, and optionally delete it" },
"sidekiq": { en: "Background job framework for Ruby" },
"sips": { en: "Scriptable image processing system" },
"sl": { en: "A highly advanced animation program for curing your bad habit of mistyping" },
"sls": { en: "Zero-friction serverless development" },
"snaplet": { en: "Create and share PostgreSQL snapshots with schema, data transformation, and preview databases for collaborative development (see: https://docs.snaplet.dev)" },
"softwareupdate": { en: "Software Update checks for new and updated versions of your software based on information about your computer and current software" },
"sort": { en: "Sort or merge records (lines) of text and binary files", zhCN: "对文本和二进制文件中的记录(行)进行排序或合并", zhTW: "對文字和二進位檔案中的記錄(行)進行排序或合併" },
"source": { en: "Source files in shell" },
"space": { en: "Deta Space CLI for mananging Deta Space projects" },
"speedtest-cli": { en: "Command line interface for testing internet bandwidth using speedtest.net" },
"splash": { en: "Get stunning wallpapers from Unsplash" },
"split": { en: "The split utility reads the given file and breaks it up into files of 1000 lines each (if no options are specified), leaving the file unchanged. If file is a single dash ('-') or absent, split reads from the standard input", zhCN: "split 工具读取指定文件,并按每 1000 行一个(未指定选项时)拆分成多个文件,原文件保持不变。若 file 为单个短横线('-')或省略,split 从标准输入读取", zhTW: "split 工具讀取指定檔案,並按每 1000 行一個(未指定選項時)拆分成多個檔案,原檔案保持不變。若 file 為單個短橫線('-')或省略,split 從標準輸入讀取" },
"spotify": { en: "CLI to use Spotify from the terminal" },
"spring": { en: "The Spring Boot CLI is a command line tool that you can use to bootstrap a new project from start.spring.io or encode a password" },
"sqlfluff": { en: "A dialect-flexible and configurable SQL linter" },
"sqlite3": { en: "A command line interface for SQLite version 3" },
"sqlmesh": { en: "SQLMesh command line tool" },
"src": { en: "Interact with Sourcegraph from the command line" },
"ssh": { en: "Log into a remote machine", zhCN: "登录远程机器", zhTW: "登入遠端機器" },
"ssh-keygen": { en: "Generates, manages and converts authentication keys for ssh" },
"st2": { en: "CLI for StackStorm event-driven automation platform" },
"sta": { en: "Generate api via swagger scheme" },
"stack": { en: "The Haskell Tool Stack" },
"starkli": { en: "Starkli, a ⚡ blazing ⚡ fast ⚡ CLI tool for Starknet powered by 🦀 starknet-rs 🦀" },
"start-storybook": { en: "Storybook start CLI tools" },
"stat": { en: "Display file status", zhCN: "显示文件状态", zhTW: "顯示檔案狀態" },
"steadybit": { en: "Command-line interface to interact with the Steadybit API" },
"stencil": { en: "CLI to build Stencil projects and generate components" },
"stepzen": { en: "The StepZen CLI is the primary way to build, deploy and test your schemas on StepZen" },
"stow": { en: "Manage farms of symbolic links" },
"streamlit": { en: "Streamlit" },
"stripe": { en: "CLI interface for Stripe.com" },
"subl": { en: "Sublime Text" },
"sudo": { en: "Execute a command as the superuser or another user", zhCN: "以超级用户或其他用户身份执行命令", zhTW: "以超級使用者或其他使用者身份執行命令" },
"suitecloud": { en: "SuiteCloud CLI" },
"supabase": { en: "Supabase CLI" },
"surreal": { en: "SurrealDB is the ultimate cloud database for tomorrow's applications - https://surrealdb.com/" },
"svn": { en: "The first content tracker" },
"svokit": { en: "Runs built svokit project" },
"svtplay-dl": { en: "Download videos from your favourite play services" },
"sw_vers": { en: "Print macOS version information" },
"swagger-typescript-api": { en: "Generate api via swagger scheme" },
"swc": { en: "SWC is a super-fast compiler written in rust; producing widely-supported javascript from modern standards and typescript" },
"swift": { en: "Swift compiler" },
"symfony": { en: "Symfony Binary" },
"sysctl": { en: "Get or set kernel state" },
"tac": { en: "Concatenate and print files in reverse" },
"tail": { en: "Display the last part of a file", zhCN: "显示文件的末尾部分", zhTW: "顯示檔案的末尾部分" },
"tailcall": { en: "TailCall CLI for managing and optimizing GraphQL configurations" },
"tailwindcss": { en: "Tailwindcss CLI tools" },
"taplo": { en: "Tool for validation, formatting, and querying TOML documents with a jq-like fashion" },
"tar": { en: "Manipulating archive files", zhCN: "操作归档文件", zhTW: "操作歸檔檔案" },
"tb": { en: "Tinybird CLI" },
"tccutil": { en: "Manage the privacy database" },
"tee": { en: "Duplicate standard input", zhCN: "复制标准输入", zhTW: "複製標準輸入" },
"terraform": { en: "Terraform CLI" },
"terragrunt": { en: "Terragrunt CLI" },
"tfenv": { en: "Terraform version manager" },
"tfsec": { en: "Tfsec is a simple tool to detect potential security vulnerabilities in your terraformed infrastructure" },
"then": { en: "Execute this command if the test returned 0" },
"time": { en: "Time how long a command takes!" },
"tkn": { en: "CLI for tekton pipelines" },
"tldr": { en: "A simpler man page than the existing man page" },
"tmutil": { en: "Time Machine utility" },
"tmux": { en: "A terminal multiplexer" },
"tmuxinator": { en: "Create and manage tmux sessions easily" },
"tns": { en: "The NativeScript CLI lets you create, build, and deploy NativeScript based apps on iOS and Android devices" },
"tokei": { en: "Count your code, quickly" },
"top": { en: "Display Linux tasks", zhCN: "显示 Linux 任务", zhTW: "顯示 Linux 任務" },
"touch": { en: "Change file access and modification times", zhCN: "更改文件的访问时间和修改时间", zhTW: "更改檔案的訪問時間和修改時間" },
"tr": { en: "Translate characters" },
"traceroute": { en: "Print the route packets take to network host" },
"trap": { en: "Automatically execute commands after receiving signals by processes or the operating system" },
"trash": { en: "Trash, move files/folders to the trash" },
"tree": { en: "Display directories as trees (with optional color/HTML output)" },
"trex": { en: "Advanced package management for deno, based on import_map.json" },
"trivy": { en: "A simple and comprehensive vulnerability scanner" },
"truffle": { en: "A world class development environment, testing framework and asset pipeline for blockchains using the Ethereum Virtual Machine (EVM), aiming to make life as a developer easier" },
"truncate": { en: "Shrink or extend the size of a file to the specified size" },
"trunk": { en: "An all-in-one tool for scalably checking, formatting, and monitoring code" },
"ts-node": { en: "Run the TypeScript interpreter for Node.JS" },
"tsc": { en: "CLI tool for TypeScript compiler" },
"tsh": { en: "TSH: Teleport Authentication Gateway Client" },
"tsuru": { en: "Tsuru is the command line utility used by application developers, that will allow users to create, list, bind and manage apps" },
"tsx": { en: "Run TypeScript file using tsx" },
"tuist": { en: "Generate, build and test your Xcode projects. For more info please see https://docs.tuist.io/" },
"turbo": { en: "Turborepo is a high-performance build system for JavaScript and TypeScript codebases" },
"twiggy": { en: "A code-size profiler for WebAssembly" },
"twilio": { en: "Manage your Twilio resources from your terminal" },
"typeorm": { en: "TypeORM CLI" },
"typos": { en: "Source code spelling correction" },
"typst": { en: "The Typst compiler" },
"ua": { en: "Manage Ubuntu Pro services from Canonical" },
"ubuntu-advantage": { en: "Manage Ubuntu Pro services from Canonical" },
"uname": { en: "Print operating system name", zhCN: "显示系统信息(无选项时输出内核名称)", zhTW: "顯示系統資訊(無選項時輸出核心名稱)" },
"uniq": { en: "Report or omit repeated line", zhCN: "报告或省略重复行", zhTW: "報告或省略重複行" },
"unix2dos": { en: "Unix to DOS text file format convertor" },
"unset": { en: "Named variable shall be undefined" },
"until": { en: "Repeat a command until this is true" },
"unzip": { en: "Extract compressed files in a ZIP archive", zhCN: "解压 ZIP 压缩包中的文件", zhTW: "解壓 ZIP 壓縮包中的檔案" },
"uv": { en: "An extremely fast Python package manager" },
"v": { en: "The V Programming Language" },
"vale": { en: "A syntax-aware linter for prose built with speed and extensibility in mind" },
"valet": { en: "Valet is a Laravel development environment for macOS minimalists" },
"vapor": { en: "Vapor Toolbox (Server-side Swift web framework)" },
"vault": { en: "Interact with HashiCorp Vault" },
"vela": { en: "A Highly Extensible Platform Engine based on Kubernetes and Open Application Model" },
"vercel": { en: "CLI Interface for Vercel.com" },
"vi": { en: "Vi[m] is an one of two powerhouse text editors in the Unix world, the other being EMACS" },
"vim": { en: "Vi IMproved, a programmer's text editor", zhCN: "Vi IMproved,程序员的文本编辑器", zhTW: "Vi IMproved,程式設計師的文字編輯器" },
"vimr": { en: "VimR — Neovim GUI for macOS in Swift" },
"visudo": { en: "Visudo edits the sudoers file, which defines the users and groups with administrator rights" },
"vite": { en: "Native ESM-powered web dev build tool" },
"volta": { en: "The JavaScript Launcher" },
"vr": { en: "The npm-style script runner for Deno" },
"vsce": { en: "The Visual Studio Code Extension Manager" },
"vtex": { en: "Fig autocomplete for VTEX IO's CLI - VTEX IO's CLI allows you to perform any action necessary to your development process, such as linking local files to the VTEX platform, managing workspaces, and releasing new app versions" },
"vue": { en: "Vue cli tools" },
"vultr-cli": { en: "Official command line interface for the Vultr API" },
"w": { en: "Display who is logged in and what they are doing" },
"wasm-bindgen": { en: "Generate bindings between WebAssembly and JavaScript" },
"watchman": { en: "A file watching service" },
"watson": { en: "A wonderful CLI to track your time" },
"wc": { en: "World, line, character, and byte count", zhCN: "统计单词数、行数、字符数和字节数", zhTW: "統計單詞數、行數、字元數和位元組數" },
"wd": { en: "Warp to directories without using cd" },
"webstorm": { en: "WebStorm cli" },
"wezterm": { en: "Wez's Terminal Emulator" },
"wget": { en: "A non-interactive network retriever", zhCN: "非交互式网络检索器", zhTW: "非互動式網路檢索器" },
"whence": { en: "For each name, indicate how it should be interpreted" },
"where": { en: "For each name, indicate how it should be interpreted" },
"whereis": { en: "Locate the binary, source, and manual page files for a command" },
"which": { en: "Locate a program in the user's PATH", zhCN: "在用户的 PATH 中定位程序", zhTW: "在使用者的 PATH 中定位程式" },
"while": { en: "Repeat a command while this is true" },
"who": { en: "Display who is logged in" },
"whois": { en: "Query a database for information about a domain registrant" },
"wifi-password": { en: "People ask you for the Wi-Fi password. Answer quickly. macOS only" },
"wp": { en: "WP-CLI is the command-line interface for WordPress" },
"wrangler": { en: "Wrangler CLI for Cloudflare Workers" },
"wrk": { en: "Wrk - a HTTP benchmarking tool" },
"wscat": { en: "Communicate over websocket" },
"xargs": { en: "Execute a command with whitespace-delimited strings (from stdin) as arguments", zhCN: "将标准输入中以空白分隔的字符串作为参数执行命令", zhTW: "將標準輸入中以空白分隔的字串作為引數執行命令" },
"xc": { en: "List tasks from an xc-compatible markdown file" },
"xcode-select": { en: "Active developer directory for Xcode tools" },
"xcodebuild": { en: "Build Xcode projects" },
"xcodeproj": { en: "Xcodeproj lets you create and modify Xcode projects" },
"xcodes": { en: "Manage the Xcode versions installed on your Mac" },
"xcrun": { en: "Find and execute the named command line tool from the active xCode developer directory" },
"xdg-mime": { en: "Command line tool for querying information about file type handling and adding descriptions for new file types" },
"xdg-open": { en: "Opens a file or URL in the user's preferred application" },
"xed": { en: "Xcode text editor invocation tool" },
"xxd": { en: "Make a hexdump or do the reverse" },
"yalc": { en: "Work with yarn/npm packages locally like a boss" },
"yank": { en: "Yank terminal output to clipboard" },
"yarn": { en: "Manage packages and run scripts", zhCN: "管理软件包并运行脚本", zhTW: "管理軟體包並執行指令碼" },
"ykman": { en: "Configure your YubiKey via the command line" },
"yo": { en: "Yeoman generator" },
"yomo": { en: "CLI interface for YoMo" },
"youtube-dl": { en: "Download videos from YouTube" },
"yum": { en: "RPM package manager (RHEL/CentOS)", zhCN: "RPM 软件包管理器(RHEL/CentOS)", zhTW: "RPM 軟體包管理器(RHEL/CentOS)" },
"zapier": { en: "The Zapier CLI is a developer-focused way to create and maintain Zapier integrations. See more at https://github.com/zapier/zapier-platform" },
"zed": { en: "A lightning-fast, collaborative code editor written in Rust" },
"zellij": { en: "A terminal workspace with batteries included" },
"zig": { en: "Zig is a general-purpose programming language and toolchain for maintaining robust, optimal, and reusable software" },
"zip": { en: "Package and compress (archive) files into zip file", zhCN: "将文件打包并压缩为 zip 文件", zhTW: "將檔案打包並壓縮為 zip 檔案" },
"zipcloak": { en: "Encrypt entries in a zipfile" },
"zoxide": { en: "A smarter cd command for your terminal" },
};
@@ -21,6 +21,7 @@ import {
getAvailableSpecs,
normalizeCommandName,
resolveNames,
type FigHostOs,
type FigSpec,
type FigSubcommand,
type FigOption,
@@ -31,7 +32,10 @@ import {
resolvePathComponents,
} from "./remotePathCompleter";
import { getSnippetSuggestions } from "./snippetCompleter";
import { localizeSpecSuggestionDescriptions } from "./autocompleteDescriptionI18n";
import {
localizeCommandSuggestionDescriptions,
localizeSpecSuggestionDescriptions,
} from "./autocompleteDescriptionI18n";
import type { AutocompleteHistoryScope, Snippet } from "../../../domain/models";
import type { AutocompleteCwdSource } from "./terminalAutocompleteLayout";
@@ -246,7 +250,7 @@ export async function getCompletions(
options: {
hostId?: string;
hostGroup?: string;
os?: "linux" | "windows" | "macos";
os?: FigHostOs;
maxResults?: number;
/** Session ID for remote path completion */
sessionId?: string;
@@ -288,7 +292,7 @@ export async function getCompletions(
const ctx = parseCommandLine(input);
const specResult: SpecSuggestionResult = ctx.commandName && ctx.wordIndex >= 0
? await getSpecSuggestions(ctx)
? await getSpecSuggestions(ctx, options.os)
: { suggestions: [] };
const suggestions: CompletionSuggestion[] = [];
const seenSuggestionTexts = new Set<string>();
@@ -459,7 +463,7 @@ export async function getCompletions(
if (unique.length >= resultLimit) break;
}
return unique;
return [...localizeCommandSuggestionDescriptions(unique, options.locale)];
}
function normalizeHistoryPathPrefix(token: string): string {
@@ -473,18 +477,21 @@ function normalizeHistoryPathPrefix(token: string): string {
/**
* Get suggestions from Fig spec + return resolved args (for path detection reuse).
*/
async function getSpecSuggestions(ctx: CompletionContext): Promise<SpecSuggestionResult> {
async function getSpecSuggestions(
ctx: CompletionContext,
os?: FigHostOs,
): Promise<SpecSuggestionResult> {
const suggestions: CompletionSuggestion[] = [];
const specAvailable = await hasSpec(ctx.commandName);
const specAvailable = await hasSpec(ctx.commandName, os);
if (!specAvailable) {
if (ctx.wordIndex === 0 && ctx.currentWord.length >= 1) {
return { suggestions: await getCommandNameSuggestions(ctx.currentWord) };
return { suggestions: await getCommandNameSuggestions(ctx.currentWord, os) };
}
return { suggestions };
}
const spec = await loadSpec(ctx.commandName);
const spec = await loadSpec(ctx.commandName, os);
if (!spec) return { suggestions };
// If we're still typing the command name (partial match, not yet complete)
@@ -580,6 +587,15 @@ async function getSpecSuggestions(ctx: CompletionContext): Promise<SpecSuggestio
appendOptionSuggestions(suggestions, ctx, currentToken, resolved.fallbackOptions);
}
const hasAttachedArgumentSuggestions = appendAttachedOptionalArgumentSuggestions(
suggestions,
ctx,
resolved.options,
);
if (!hasAttachedArgumentSuggestions) {
appendAttachedOptionalArgumentSuggestions(suggestions, ctx, resolved.fallbackOptions);
}
// Suggest argument values from suggestions in the spec
if (resolved.args) {
const args = Array.isArray(resolved.args) ? resolved.args : [resolved.args];
@@ -609,11 +625,14 @@ async function getSpecSuggestions(ctx: CompletionContext): Promise<SpecSuggestio
}
/**
* Get command name suggestions by matching against available specs.
* Uses the already-imported getAvailableSpecs directly (no dynamic self-import).
* Get command name suggestions by matching against the specs available for the
* target OS, so a platform-specific command is never suggested to another one.
*/
async function getCommandNameSuggestions(prefix: string): Promise<CompletionSuggestion[]> {
const specs = await getAvailableSpecs();
async function getCommandNameSuggestions(
prefix: string,
os?: FigHostOs,
): Promise<CompletionSuggestion[]> {
const specs = await getAvailableSpecs(os);
const lower = prefix.toLowerCase();
const suggestions: CompletionSuggestion[] = [];
@@ -731,6 +750,55 @@ function mergeOptionLists(
return merged;
}
function appendAttachedOptionalArgumentSuggestions(
suggestions: CompletionSuggestion[],
ctx: CompletionContext,
options: FigOption[] | undefined,
): boolean {
const currentToken = ctx.currentWord;
if (!options?.length || !currentToken) return false;
// An existing option name takes precedence over interpreting a short option
// prefix as an attached value.
if (options.some((option) => resolveNames(option.name).some((name) => name.startsWith(currentToken)))) {
return false;
}
let added = false;
for (const option of options) {
if (option.netcattyOptionalArgAttached !== true) continue;
const args = Array.isArray(option.args) ? option.args : option.args ? [option.args] : [];
const arg = args[0];
if (!arg?.isOptional || !arg.suggestions?.length) continue;
for (const name of resolveNames(option.name)) {
const shortOption = /^-[a-zA-Z0-9]$/.test(name);
const longOption = name.startsWith("--") && name.length > 2;
if (!shortOption && !longOption) continue;
const prefix = longOption ? `${name}=` : name;
if (!currentToken.startsWith(prefix)) continue;
const typedValue = currentToken.slice(prefix.length);
if (shortOption && !typedValue) continue;
for (const suggestion of arg.suggestions) {
const value = typeof suggestion === "string"
? suggestion
: (Array.isArray(suggestion.name) ? suggestion.name[0] : suggestion.name);
if (!value.startsWith(typedValue) || value === typedValue) continue;
suggestions.push({
text: rebuildCommand(ctx.tokens, ctx.wordIndex, `${prefix}${value}`),
displayText: value,
description: typeof suggestion === "string" ? undefined : suggestion.description,
source: "arg",
score: 600,
});
added = true;
}
}
}
return added;
}
function appendOptionSuggestions(
suggestions: CompletionSuggestion[],
ctx: CompletionContext,
File diff suppressed because it is too large. Load diff
File diff suppressed because it is too large. Load diff
@@ -12,6 +12,8 @@ export interface FigOption {
isRequired?: boolean;
isPersistent?: boolean;
exclusiveOn?: string[];
/** Local extension: optional short values attach directly; long values use '='. */
netcattyOptionalArgAttached?: boolean;
}
export interface FigArg {
@@ -44,10 +46,12 @@ export interface FigSpec extends FigSubcommand {
// Top-level spec may include additional metadata
}
export type FigHostOs = "linux" | "windows" | "macos";
// Bridge type augmentation
interface FigSpecBridge {
listFigSpecs?: () => Promise<string[]>;
loadFigSpec?: (commandName: string) => Promise<FigSpec | null>;
listFigSpecs?: (hostOs?: FigHostOs) => Promise<string[]>;
loadFigSpec?: (commandName: string, hostOs?: FigHostOs) => Promise<FigSpec | null>;
}
function getBridge(): FigSpecBridge | undefined {
@@ -55,30 +59,48 @@ function getBridge(): FigSpecBridge | undefined {
return (window as Window & { netcatty?: FigSpecBridge }).netcatty;
}
// Cache loaded specs
const specCache = new Map<string, FigSpec | null>();
// Cache by command and target OS: one renderer can contain both Linux and
// macOS sessions, whose option names and meanings can differ.
const specCache = new Map<string, FigSpec>();
// In-flight loading promises to avoid duplicate loads
// In-flight loading promises to avoid duplicate loads for the same target OS.
const inFlightLoads = new Map<string, Promise<FigSpec | null>>();
// All available spec names
let availableSpecs: string[] | null = null;
let availableSpecsSet: Set<string> | null = null;
function specCacheKey(commandName: string, hostOs?: FigHostOs): string {
return JSON.stringify([commandName, hostOs ?? null]);
}
// Spec names and successfully loaded commands, both scoped by target OS so a
// macOS-only command never reports as available to a Linux session.
const availableSpecs = new Map<string, { names: string[]; set: Set<string> }>();
const loadedSpecNames = new Map<string, Set<string>>();
function hostKey(hostOs?: FigHostOs): string {
return hostOs ?? "";
}
function rememberLoadedSpecName(commandName: string, hostOs?: FigHostOs): void {
const key = hostKey(hostOs);
const loaded = loadedSpecNames.get(key);
if (loaded) loaded.add(commandName);
else loadedSpecNames.set(key, new Set([commandName]));
}
/**
* Get the list of all available command specs via IPC.
* Get the list of all command specs available for one target OS via IPC.
*/
export async function getAvailableSpecs(): Promise<string[]> {
export async function getAvailableSpecs(hostOs?: FigHostOs): Promise<string[]> {
const key = hostKey(hostOs);
// Only return cache if it has actual specs (not an empty failure)
if (availableSpecs && availableSpecs.length > 0) return availableSpecs;
const cached = availableSpecs.get(key);
if (cached && cached.names.length > 0) return cached.names;
try {
const bridge = getBridge();
if (bridge?.listFigSpecs) {
const specs = await bridge.listFigSpecs();
const specs = await bridge.listFigSpecs(hostOs);
if (Array.isArray(specs) && specs.length > 0) {
availableSpecs = specs;
availableSpecsSet = new Set(specs);
availableSpecs.set(key, { names: specs, set: new Set(specs) });
return specs;
}
}
@@ -94,15 +116,17 @@ export async function getAvailableSpecs(): Promise<string[]> {
* Load a command specification by name via IPC.
* Uses in-flight deduplication to avoid loading the same spec twice concurrently.
*/
export async function loadSpec(commandName: string): Promise<FigSpec | null> {
if (specCache.has(commandName)) {
return specCache.get(commandName) ?? null;
}
export async function loadSpec(commandName: string, hostOs?: FigHostOs): Promise<FigSpec | null> {
const cacheKey = specCacheKey(commandName, hostOs);
const cached = specCache.get(cacheKey);
if (cached) return cached;
const existing = inFlightLoads.get(commandName);
const existing = inFlightLoads.get(cacheKey);
if (existing) return existing;
const loadPromise = (async (): Promise<FigSpec | null> => {
// Defer the bridge lookup so even a missing bridge or synchronous throw
// clears the in-flight entry after it has been registered.
const loadPromise = Promise.resolve().then(async (): Promise<FigSpec | null> => {
try {
const bridge = getBridge();
if (!bridge?.loadFigSpec) {
@@ -110,36 +134,33 @@ export async function loadSpec(commandName: string): Promise<FigSpec | null> {
return null;
}
const spec = await bridge.loadFigSpec(commandName);
const spec = await bridge.loadFigSpec(commandName, hostOs);
if (spec) {
specCache.set(commandName, spec);
specCache.set(cacheKey, spec);
rememberLoadedSpecName(commandName, hostOs);
}
// Don't cache null — the load may have failed transiently (bridge not ready, etc.)
// Only cache null when we're confident the spec doesn't exist (hasSpec returned false)
return spec;
} catch {
// Don't cache failures — allow retry on next request
return null;
} finally {
inFlightLoads.delete(commandName);
inFlightLoads.delete(cacheKey);
}
})();
});
inFlightLoads.set(commandName, loadPromise);
inFlightLoads.set(cacheKey, loadPromise);
return loadPromise;
}
/**
* Check if a spec exists for a given command name (without loading it).
* Check if a spec exists for a given command name and target OS.
*/
export async function hasSpec(commandName: string): Promise<boolean> {
// Only trust positive cache hits (spec loaded successfully).
// Null entries may be stale failures from preload — ignore them.
const cached = specCache.get(commandName);
if (cached) return true;
export async function hasSpec(commandName: string, hostOs?: FigHostOs): Promise<boolean> {
if (loadedSpecNames.get(hostKey(hostOs))?.has(commandName)) return true;
await getAvailableSpecs();
return availableSpecsSet?.has(commandName) ?? false;
await getAvailableSpecs(hostOs);
return availableSpecs.get(hostKey(hostOs))?.set.has(commandName) ?? false;
}
/**
@@ -155,13 +176,16 @@ export const COMMON_FIG_SPECS = [
"vim", "nano", "less", "head", "tail", "sort",
"awk", "sed", "chmod", "chown", "cp", "mv", "rm", "mkdir",
"ln", "stat", "wc", "cut", "uniq", "tee", "xargs",
"echo", "which", "pwd", "clear", "su", "crontab", "env",
"uname", "base64", "date", "id", "split", "seq", "join",
"dig", "dd", "htop", "basename", "dirname", "readlink", "more", "paste",
] as const;
/**
* Preload commonly used specs in batches to avoid overwhelming IPC.
* Only call this when autocomplete is enabled.
*/
export function preloadCommonSpecs(): void {
export function preloadCommonSpecs(hostOs?: FigHostOs): void {
const BATCH_SIZE = 8;
let offset = 0;
@@ -170,7 +194,7 @@ export function preloadCommonSpecs(): void {
if (batch.length === 0) return;
for (const name of batch) {
loadSpec(name).catch(() => {});
loadSpec(name, hostOs).catch(() => {});
}
offset += BATCH_SIZE;
@@ -390,13 +390,12 @@ export function useTerminalAutocomplete(
*/
const typedBufferReliableRef = useRef<boolean>(true);
// Preload common specs on first mount (only if enabled)
// Warm the cache for this session's target OS, including when it changes.
useEffect(() => {
if (settings.enabled) {
preloadCommonSpecs();
preloadCommonSpecs(hostOs);
}
// eslint-disable-next-line react-hooks/exhaustive-deps
}, []);
}, [settings.enabled, hostOs]);
// Local Terminal: seed autocomplete history from ~/.zsh_history (etc.) once
// per stable hostId so prefix suggestions match Ghostty-style histfile recall
@@ -106,11 +106,11 @@ test("batch zh-TW spot checks cover corrected semantics", () => {
);
assert.equal(
traditional["Extract a zip file created in windows, containing files with non-ascii (chinese) filenames"],
"上游選項疑似錯誤,請核對當前 unzip 版本支援的引數",
"解壓由 Windows 建立、包含非 ASCII(中文)檔名的 zip 檔案",
);
assert.equal(
traditional["Turn on value of next option"],
"啟用指定的 NeXT 相容選項(Apple 擴充套件)",
"啟用指定的 NeXT 相容選項(Apple 擴充功能)",
);
});
@@ -122,7 +122,7 @@ test("zip, unzip, and make options localize without changing insertion text", as
{
input: "unzip -",
option: "-0",
zhCn: "上游选项疑似错误,请核对当前 unzip 版本支持的参数",
zhCn: "解压由 Windows 创建、包含非 ASCII(中文)文件名的 zip 文件",
},
{ input: "make -", option: "-N", zhCn: "启用指定的 NeXT 兼容选项(Apple 扩展)" },
{ input: "make --", option: "--warn-undefined-variables", zhCn: "引用未定义变量时发出警告" },
@@ -100,7 +100,7 @@ test("batch specs cover every description except the documented node shared-key
test("batch zh-TW spot checks cover generated terminology", () => {
assert.equal(
traditional["Don’t display the copyright and version messages even in interactive mode"],
"上游選項疑似錯誤:互動模式下不顯示版權和版本資訊請用 -q",
"即使在互動模式下也不顯示版權和版本訊息",
);
assert.equal(traditional["Watch input files"], "監視輸入檔案");
assert.equal(
@@ -116,12 +116,12 @@ test("batch zh-TW spot checks cover generated terminology", () => {
"未停用自動列印時,先列印模式空間;隨後用下一行輸入替換模式空間。若無更多輸入則退出。",
);
assert.equal(
traditional["Run in POSIX compatibility mode (gawk)"],
traditional["Run in traditional compatibility mode (gawk)"],
"以傳統相容模式執行,行為等同 Brian Kernighan 的 awk(gawk)",
);
assert.equal(
traditional["Interprets regular expressions as extended (modern) regular expressions rather than basic regular expressions"],
"將正規表示式解釋為擴充套件(現代)正規表示式,而不是基本正規表示式",
"將正規表示式解釋為擴充(現代)正規表示式,而不是基本正規表示式",
);
});
@@ -143,7 +143,7 @@ test("python, node, vim, sort, awk, and sed options localize without changing in
input: "python -",
option: "-g",
key: "Don’t display the copyright and version messages even in interactive mode",
zhCn: "上游选项疑似错误:交互模式下不显示版权和版本信息请用 -q",
zhCn: "即使在交互模式下也不显示版权和版本消息",
},
{
input: "python3 -",
@@ -202,19 +202,19 @@ test("python, node, vim, sort, awk, and sed options localize without changing in
{
input: "awk -",
option: "-c",
key: "Run in POSIX compatibility mode (gawk)",
key: "Run in traditional compatibility mode (gawk)",
zhCn: "以传统兼容模式运行,行为等同 Brian Kernighan 的 awk(gawk)",
},
{
input: "awk -",
option: "-n",
key: "Disable automatic input record splitting (gawk)",
key: "Recognize octal and hexadecimal values in input data (gawk)",
zhCn: "识别输入数据中的八进制和十六进制值,请谨慎使用(gawk)",
},
{
input: "awk -",
option: "-t",
key: "Enable type checking (gawk)",
key: "Warn about constructs not portable to the original Unix awk (gawk)",
zhCn: "对无法移植到原始 UNIX awk 的构造发出警告(gawk)",
},
{
@@ -0,0 +1,310 @@
import test from "node:test";
import assert from "node:assert/strict";
import fs from "node:fs";
import path from "node:path";
import { fileURLToPath, pathToFileURL } from "node:url";
import type { FigSpec } from "./autocomplete/figSpecLoader.ts";
const HERE = path.dirname(fileURLToPath(import.meta.url));
const ROOT = path.resolve(HERE, "../..");
const FIG_SPEC_DIR = path.join(ROOT, "node_modules/@withfig/autocomplete/build");
// Runtime prefers local specs (electron/specs) over the bundled package, so the
// tests must resolve the same file the popup will load.
const LOCAL_SPEC_DIR = path.join(ROOT, "electron/specs");
function resolveSpecPath(name: string): string {
const local = path.join(LOCAL_SPEC_DIR, `${name}.js`);
return fs.existsSync(local) ? local : path.join(FIG_SPEC_DIR, `${name}.js`);
}
const DICT_DIR = path.join(HERE, "autocomplete");
const COMMANDS = [
"echo",
"which",
"pwd",
"clear",
"su",
"crontab",
"env",
"uname",
"base64",
"date",
"id",
"split",
"seq",
"join",
"dig",
"dd",
"htop",
"basename",
"dirname",
"readlink",
"more",
"paste",
] as const;
const specs = Object.fromEntries(
await Promise.all(
COMMANDS.map(async (name) => {
const mod = await import(pathToFileURL(resolveSpecPath(name)).href);
return [name, mod.default?.default ?? mod.default] as const;
}),
),
) as Record<(typeof COMMANDS)[number], FigSpec>;
const simplified = JSON.parse(
fs.readFileSync(path.join(DICT_DIR, "descriptions.zh-CN.json"), "utf8"),
) as Record<string, string>;
const traditional = JSON.parse(
fs.readFileSync(path.join(DICT_DIR, "descriptions.zh-TW.json"), "utf8"),
) as Record<string, string>;
Object.defineProperty(globalThis, "localStorage", {
value: {
getItem: () => null,
setItem: () => {},
removeItem: () => {},
clear: () => {},
},
configurable: true,
});
Object.defineProperty(globalThis, "window", {
value: {
netcatty: {
listFigSpecs: async () => [...COMMANDS],
loadFigSpec: async (commandName: string) =>
(specs as Record<string, FigSpec>)[commandName] ?? null,
},
},
configurable: true,
});
const { getCompletions } = await import("./autocomplete/completionEngine.ts");
function collectDescriptions(
node: unknown,
out = new Set<string>(),
seen = new WeakSet<object>(),
): Set<string> {
if (!node || typeof node !== "object" || seen.has(node)) return out;
seen.add(node);
const record = node as { description?: unknown };
if (typeof record.description === "string" && record.description.trim()) {
out.add(record.description);
}
for (const value of Object.values(node)) {
if (Array.isArray(value)) {
for (const item of value) collectDescriptions(item, out, seen);
} else if (value && typeof value === "object") {
collectDescriptions(value, out, seen);
}
}
return out;
}
const batchDescriptions = [
...new Set(COMMANDS.flatMap((name) => [...collectDescriptions(specs[name])])),
];
function suggestionNamed(
suggestions: Awaited<ReturnType<typeof getCompletions>>,
displayText: string,
) {
return suggestions.find((suggestion) => suggestion.displayText === displayText);
}
test("batch 4 specs have complete zh-CN and zh-TW description coverage", () => {
const missing = batchDescriptions.filter(
(description) =>
!(typeof simplified[description] === "string" && simplified[description].length > 0),
);
const missingTraditional = batchDescriptions.filter(
(description) =>
!(typeof traditional[description] === "string" && traditional[description].length > 0),
);
assert.deepEqual(missing, []);
assert.deepEqual(missingTraditional, []);
assert.ok(batchDescriptions.length >= 150);
});
test("batch 4 spot checks preserve verified semantics, placeholders and upstream typos", () => {
assert.equal(
simplified["Write arguments to the standard output"],
"将参数写入标准输出",
);
assert.equal(
simplified["Locate a program in the user's PATH"],
"在用户的 PATH 中定位程序",
);
assert.equal(
simplified["Equalize the widths of all numbers by padding with zeros as necessary"],
"必要时用零填充,使所有数字宽度一致",
);
assert.equal(
simplified["Display or set the date in UTC (Coordinated Universal) time"],
"以 UTC(协调世界时)显示或设置日期",
);
assert.equal(
simplified["Return filename portion of pathname"],
"返回路径名的文件名部分",
);
assert.equal(
simplified["Symbolic link or path to resolve"],
"要解析的符号链接或路径",
);
assert.equal(
simplified["Resolve every symbolic link in the given path and print the canonical path (all but the last component must exist)"],
"解析路径中的每个符号链接并打印规范路径(除最后一段外都必须存在)",
);
// Review fixes: platform, units and scope wording.
assert.equal(simplified["Highlight new and old processes"], "高亮新启动和已退出的进程");
assert.equal(simplified["Highlight duration in seconds"], "高亮持续时间,单位为秒");
assert.equal(
simplified["Use suffix_length letters to form the suffix of the file name"],
"使用 suffix_length 个字符构成文件名后缀",
);
assert.ok(
simplified["Create split files byte_count bytes in length. If k or K is appended to the number, the file is split into byte_count kilobyte pieces. If m or M is appended to the number, the file is split into byte_count megabyte pieces. If g or G is appended to the number, the file is split into byte_count gigabyte pieces"].includes("KiB"),
);
assert.equal(
simplified["Set the conversion record size"],
"设置转换记录长度(字节),供 block/unblock 等记录转换使用",
);
assert.equal(
simplified["In addition to the default output, produce a line for each unpairable line in file file_number"],
"除默认输出外,还为第 file_number 个文件中无法配对的行各输出一行",
);
assert.equal(
simplified["Treat every argument as a string"],
"支持多个路径名,将每个参数作为路径名处理",
);
assert.equal(
simplified["End each output line with NUL, not newline"],
"每条环境变量记录以 NUL 而非换行符结束",
);
assert.equal(simplified["Decode input instead of encoding it"], "解码输入而不是编码");
assert.equal(
simplified["When decoding, ignore non-alphabet characters"],
"解码时忽略不属于字母表的字符",
);
assert.ok(
simplified["Leave the environment unmodified. The invoked shell is your login shell, and no directory changes are made. As a security precaution, if the target user's shell is a non-standard shell (as defined by getusershell(3)) and the caller's real uid is non-zero, su will fail"].includes("getusershell(3)"),
);
// dig shares A/MX/CNAME/TXT/SOA/ANY/filter keys with dog, so the caveats
// live in the zh-CN values while the English keys stay untouched.
assert.equal(
simplified["Query ALL DNS Records"],
"查询所有 DNS 记录(ANY 结果可能不完整,见 RFC 8482)",
);
assert.equal(
simplified["Query only answer section"],
"隐藏注释、问题、权威和附加区段及统计信息",
);
assert.equal(
simplified["Count logical lines, rather than screen lines"],
"按逻辑行计数,而不是按屏幕行",
);
// The local dig spec fixes the upstream NS label and drops the bogus TTL type.
assert.equal(
simplified["Query NS records (authoritative name servers)"],
"查询 NS 记录(权威名称服务器)",
);
assert.equal(simplified["Query SOA Record"], "查询 SOA 记录");
// The local GNU date spec replaces the bundled BSD option set.
assert.equal(
simplified["Display the last modification time of the given file"],
"显示给定文件的最后修改时间",
);
assert.equal(
traditional["Display the last modification time of the given file"],
"顯示給定檔案的最後修改時間",
);
assert.equal(
simplified["Set the system time from the given string"],
"按给定字符串设置系统时间",
);
// Placeholder-bearing keys stay literal.
assert.equal(simplified["N[K|k|M|m|G|g]"], "N[K|k|M|m|G|g]");
});
test("batch 4 descriptions localize without changing insertion text", async () => {
const cases = [
{ command: "echo", option: "-n", key: "Do not print the trailing newline character", zhCn: "不输出末尾的换行符" },
{ command: "which", option: "-a", key: "List all instances of executables found, instead of just the first", zhCn: "列出找到的所有可执行文件实例,而不只是第一个" },
{ command: "pwd", option: "-P", key: "Display the physical current working directory", zhCn: "显示物理当前工作目录" },
{ command: "seq", option: "-w", key: "Equalize the widths of all numbers by padding with zeros as necessary", zhCn: "必要时用零填充,使所有数字宽度一致" },
{ command: "basename", option: "-a", key: "Treat every argument as a string", zhCn: "支持多个路径名,将每个参数作为路径名处理" },
{ command: "more", option: "-s", key: "Squeeze multiple blank lines into one", zhCn: "把多个空行压缩为一行" },
{ command: "clear", option: "-T", key: "Indicates the type of terminal", zhCn: "指定终端类型" },
{ command: "date", option: "-u", key: "Display or set the date in UTC (Coordinated Universal) time", zhCn: "以 UTC(协调世界时)显示或设置日期" },
] as const;
for (const { command, option, key, zhCn } of cases) {
const localized = await getCompletions(`${command} -`, {
locale: "zh-CN",
skipPathCompletion: true,
maxResults: 100,
});
const suggestion = suggestionNamed(localized, option);
assert.equal(suggestion?.text, `${command} ${option}`);
assert.equal(suggestion?.displayText, option);
assert.equal(suggestion?.description, zhCn);
for (const locale of ["en", "ru", undefined]) {
const fallback = await getCompletions(`${command} -`, {
locale,
skipPathCompletion: true,
maxResults: 100,
});
const fallbackSuggestion = suggestionNamed(fallback, option);
assert.equal(fallbackSuggestion?.text, `${command} ${option}`);
assert.equal(fallbackSuggestion?.description, key);
}
}
});
test("batch 4 zh-TW uses Taiwan terminology and mirrors zh-CN keys", () => {
assert.equal(traditional["Write arguments to the standard output"], "將引數寫入標準輸出");
assert.equal(traditional["Locate a program in the user's PATH"], "在使用者的 PATH 中定位程式");
assert.equal(
traditional["Return filename portion of pathname"],
"返回路徑名的檔名部分",
);
assert.equal(traditional["Symbolic link or path to resolve"], "要解析的符號連結或路徑");
assert.equal(traditional["Join on the field'th field of file1"], "按 file1 的第 field 個欄位聯結");
assert.equal(traditional["Use a numeric suffix instead of a alphabetic suffix"], "使用數字字尾而不是字母字尾");
assert.equal(
traditional["List all instances of executables found, instead of just the first"],
"列出找到的所有執行檔,而不只是第一個",
);
assert.equal(
traditional["Instead, clear the whole screen and then display the text"],
"改為清空整個螢幕後再顯示文字",
);
assert.ok(
traditional["The file is split whenever an input line matches pattern, which is interpreted as an extended regular expression. The matching line will be the first line of the next output file. This option is incompatible with the -b and -l options"].includes("擴充正規表示式"),
);
assert.ok(
traditional["Do not attempt to clear terminal's scrollback buffer using the extended E3 capability"].includes("擴充 E3"),
);
assert.equal(traditional["Decode input instead of encoding it"], "解碼輸入而不是編碼");
// s2twp merges 打印 + 机器 into 印表機 when the boundary is not guarded, so
// the zh-CN wording avoids that sequence instead of holding it out.
assert.equal(traditional["Print the machine hardware name"], "顯示機器硬體名稱");
assert.equal(
traditional["Print the machine processor architecture name"],
"顯示機器處理器架構名稱",
);
assert.equal(simplified["Print the machine hardware name"], "显示机器硬件名称");
assert.equal(
traditional["Query NS records (authoritative name servers)"],
"查詢 NS 記錄(權威名稱伺服器)",
);
// zh-TW is community-maintained; only reject stale zh-TW keys here.
assert.deepEqual(
Object.keys(traditional).filter((key) => !(key in simplified)),
[],
);
});
@@ -0,0 +1,182 @@
import test from "node:test";
import assert from "node:assert/strict";
import fs from "node:fs";
import path from "node:path";
import { fileURLToPath, pathToFileURL } from "node:url";
import type { FigSpec } from "./autocomplete/figSpecLoader.ts";
const HERE = path.dirname(fileURLToPath(import.meta.url));
const ROOT = path.resolve(HERE, "../..");
const FIG_SPEC_DIR = path.join(ROOT, "node_modules/@withfig/autocomplete/build");
const LOCAL_SPEC_DIR = path.join(ROOT, "electron/specs");
function resolveSpecPath(name: string): string {
const local = path.join(LOCAL_SPEC_DIR, `${name}.js`);
return fs.existsSync(local) ? local : path.join(FIG_SPEC_DIR, `${name}.js`);
}
const DICT_DIR = path.join(HERE, "autocomplete");
const COMMANDS = ["podman"] as const;
const specs = Object.fromEntries(
await Promise.all(
COMMANDS.map(async (name) => {
const mod = await import(pathToFileURL(resolveSpecPath(name)).href);
return [name, mod.default?.default ?? mod.default] as const;
}),
),
) as Record<(typeof COMMANDS)[number], FigSpec>;
const simplified = JSON.parse(
fs.readFileSync(path.join(DICT_DIR, "descriptions.zh-CN.json"), "utf8"),
) as Record<string, string>;
const traditional = JSON.parse(
fs.readFileSync(path.join(DICT_DIR, "descriptions.zh-TW.json"), "utf8"),
) as Record<string, string>;
Object.defineProperty(globalThis, "localStorage", {
value: {
getItem: () => null,
setItem: () => {},
removeItem: () => {},
clear: () => {},
},
configurable: true,
});
Object.defineProperty(globalThis, "window", {
value: {
netcatty: {
listFigSpecs: async () => [...COMMANDS],
loadFigSpec: async (commandName: string) =>
(specs as Record<string, FigSpec>)[commandName] ?? null,
},
},
configurable: true,
});
const { getCompletions } = await import("./autocomplete/completionEngine.ts");
function collectDescriptions(
node: unknown,
out = new Set<string>(),
seen = new WeakSet<object>(),
): Set<string> {
if (!node || typeof node !== "object" || seen.has(node)) return out;
seen.add(node);
const record = node as { description?: unknown };
if (typeof record.description === "string" && record.description.trim()) {
out.add(record.description);
}
for (const value of Object.values(node)) {
if (Array.isArray(value)) {
for (const item of value) collectDescriptions(item, out, seen);
} else if (value && typeof value === "object") {
collectDescriptions(value, out, seen);
}
}
return out;
}
const batchDescriptions = [
...new Set(COMMANDS.flatMap((name) => [...collectDescriptions(specs[name])])),
];
function suggestionNamed(
suggestions: Awaited<ReturnType<typeof getCompletions>>,
displayText: string,
) {
return suggestions.find((suggestion) => suggestion.displayText === displayText);
}
test("batch 5 podman specs have complete zh-CN and zh-TW description coverage", () => {
const missing = batchDescriptions.filter(
(description) =>
!(typeof simplified[description] === "string" && simplified[description].length > 0),
);
const missingTraditional = batchDescriptions.filter(
(description) =>
!(typeof traditional[description] === "string" && traditional[description].length > 0),
);
assert.deepEqual(missing, []);
assert.deepEqual(missingTraditional, []);
assert.ok(batchDescriptions.length >= 60);
});
test("batch 5 spot checks podman terminology", () => {
assert.equal(
simplified["Manage containers, pods, and images with Podman"],
"使用 Podman 管理容器、Pod 和镜像",
);
assert.equal(simplified["Log in to a container registry"], "登录容器镜像仓库");
assert.equal(simplified["List images in local storage"], "列出本地存储中的镜像");
assert.equal(simplified["The Podman image to use"], "要使用的 Podman 镜像");
assert.equal(simplified["Manage a virtual machine"], "管理虚拟机");
assert.equal(simplified["Display machine host info"], "显示虚拟机主机信息");
assert.equal(simplified["Set a virtual machine setting"], "设置虚拟机配置项");
assert.equal(simplified["List machines"], "列出虚拟机");
assert.equal(simplified["Inspect an existing machine"], "检查现有虚拟机");
assert.equal(simplified["Remove an existing machine"], "移除现有虚拟机");
assert.equal(simplified["SSH into an existing machine"], "通过 SSH 登录现有虚拟机");
assert.equal(simplified["Start an existing machine"], "启动现有虚拟机");
assert.equal(simplified["Stop an existing machine"], "停止现有虚拟机");
assert.equal(
simplified["Manipulate manifest lists and image indexes"],
"操作清单列表和镜像索引",
);
assert.equal(traditional["Log in to a container registry"], "登入容器映象倉庫");
assert.equal(traditional["Manage a virtual machine"], "管理虛擬機器");
assert.deepEqual(Object.keys(traditional), Object.keys(simplified));
});
test("podman descriptions localize without changing insertion text", async () => {
const cases = [
{
input: "podman ",
option: "attach",
key: "Attach to a running container",
zhCn: "附加到正在运行的容器",
},
{
input: "podman ",
option: "build",
key: "Build an image using instructions from Containerfiles",
zhCn: "使用 Containerfile 中的指令构建镜像",
},
{
input: "podman -",
option: "--log-level",
key: "Log messages above specified level (trace, debug, info, warn, warning, error, fatal, panic) (default 'warn')",
zhCn: "记录指定级别及以上的日志消息(trace、debug、info、warn、warning、error、fatal、panic)(默认 'warn')",
},
{
input: "podman -",
option: "--url",
key: "URL to access Podman service (CONTAINER_HOST)",
zhCn: "访问 Podman 服务的 URL(CONTAINER_HOST)",
},
] as const;
for (const { input, option, key, zhCn } of cases) {
const localized = await getCompletions(input, {
locale: "zh-CN",
skipPathCompletion: true,
maxResults: 100,
});
const suggestion = suggestionNamed(localized, option);
assert.equal(suggestion?.displayText, option);
assert.equal(suggestion?.description, zhCn);
for (const locale of ["en", "ru", undefined]) {
const fallback = await getCompletions(input, {
locale,
skipPathCompletion: true,
maxResults: 100,
});
assert.equal(suggestionNamed(fallback, option)?.description, key);
}
}
});
@@ -0,0 +1,175 @@
import test from "node:test";
import assert from "node:assert/strict";
import fs from "node:fs";
import path from "node:path";
import { fileURLToPath, pathToFileURL } from "node:url";
import type { FigSpec } from "./autocomplete/figSpecLoader.ts";
const HERE = path.dirname(fileURLToPath(import.meta.url));
const ROOT = path.resolve(HERE, "../..");
const FIG_SPEC_DIR = path.join(ROOT, "node_modules/@withfig/autocomplete/build");
const LOCAL_SPEC_DIR = path.join(ROOT, "electron/specs");
function resolveSpecPath(name: string): string {
const local = path.join(LOCAL_SPEC_DIR, `${name}.js`);
return fs.existsSync(local) ? local : path.join(FIG_SPEC_DIR, `${name}.js`);
}
const DICT_DIR = path.join(HERE, "autocomplete");
const COMMANDS = ["ip"] as const;
const specs = Object.fromEntries(
await Promise.all(
COMMANDS.map(async (name) => {
const mod = await import(pathToFileURL(resolveSpecPath(name)).href);
return [name, mod.default?.default ?? mod.default] as const;
}),
),
) as Record<(typeof COMMANDS)[number], FigSpec>;
const simplified = JSON.parse(
fs.readFileSync(path.join(DICT_DIR, "descriptions.zh-CN.json"), "utf8"),
) as Record<string, string>;
const traditional = JSON.parse(
fs.readFileSync(path.join(DICT_DIR, "descriptions.zh-TW.json"), "utf8"),
) as Record<string, string>;
Object.defineProperty(globalThis, "localStorage", {
value: {
getItem: () => null,
setItem: () => {},
removeItem: () => {},
clear: () => {},
},
configurable: true,
});
Object.defineProperty(globalThis, "window", {
value: {
netcatty: {
listFigSpecs: async () => [...COMMANDS],
loadFigSpec: async (commandName: string) =>
(specs as Record<string, FigSpec>)[commandName] ?? null,
},
},
configurable: true,
});
const { getCompletions } = await import("./autocomplete/completionEngine.ts");
function collectDescriptions(
node: unknown,
out = new Set<string>(),
seen = new WeakSet<object>(),
): Set<string> {
if (!node || typeof node !== "object" || seen.has(node)) return out;
seen.add(node);
const record = node as { description?: unknown };
if (typeof record.description === "string" && record.description.trim()) {
out.add(record.description);
}
for (const value of Object.values(node)) {
if (Array.isArray(value)) {
for (const item of value) collectDescriptions(item, out, seen);
} else if (value && typeof value === "object") {
collectDescriptions(value, out, seen);
}
}
return out;
}
const batchDescriptions = [
...new Set(COMMANDS.flatMap((name) => [...collectDescriptions(specs[name])])),
];
function suggestionNamed(
suggestions: Awaited<ReturnType<typeof getCompletions>>,
displayText: string,
) {
return suggestions.find((suggestion) => suggestion.displayText === displayText);
}
test("batch 6 ip spec has complete zh-CN and zh-TW description coverage", () => {
const missing = batchDescriptions.filter(
(description) =>
!(typeof simplified[description] === "string" && simplified[description].length > 0),
);
const missingTraditional = batchDescriptions.filter(
(description) =>
!(typeof traditional[description] === "string" && traditional[description].length > 0),
);
assert.deepEqual(missing, []);
assert.deepEqual(missingTraditional, []);
assert.ok(batchDescriptions.length >= 80);
});
test("batch 6 spot checks ip terminology", () => {
assert.equal(
simplified["Show / manipulate routing, network devices, interfaces and tunnels"],
"显示/操作路由、网络设备、接口和隧道",
);
assert.equal(simplified["Manage addresses"], "管理地址");
assert.equal(simplified["Display addresses"], "显示地址");
assert.equal(simplified["Manage network devices"], "管理网络设备");
assert.equal(simplified["Specify the protocol family"], "指定协议族");
assert.equal(simplified["Watch for netlink messages"], "监视 netlink 消息");
assert.equal(
traditional["Show / manipulate routing, network devices, interfaces and tunnels"],
"顯示/操作路由、網路裝置、介面和隧道",
);
assert.equal(traditional["Manage addresses"], "管理地址");
assert.equal(traditional["Manage network devices"], "管理網路裝置");
assert.deepEqual(Object.keys(traditional), Object.keys(simplified));
});
test("ip descriptions localize without changing insertion text", async () => {
const cases = [
{
input: "ip ",
option: "address",
key: "Manage addresses",
zhCn: "管理地址",
},
{
input: "ip addr ",
option: "show",
key: "Display addresses",
zhCn: "显示地址",
},
{
input: "ip -",
option: "-4",
key: "Use IPv4",
zhCn: "使用 IPv4",
},
{
input: "ip -",
option: "-f",
key: "Specify the protocol family",
zhCn: "指定协议族",
},
] as const;
for (const { input, option, key, zhCn } of cases) {
const localized = await getCompletions(input, {
locale: "zh-CN",
skipPathCompletion: true,
maxResults: 100,
});
const suggestion = suggestionNamed(localized, option);
assert.equal(suggestion?.displayText, option);
assert.equal(suggestion?.description, zhCn);
for (const locale of ["en", "ru", undefined]) {
const fallback = await getCompletions(input, {
locale,
skipPathCompletion: true,
maxResults: 100,
});
assert.equal(suggestionNamed(fallback, option)?.description, key);
}
}
});
@@ -0,0 +1,216 @@
import test from "node:test";
import assert from "node:assert/strict";
import fs from "node:fs";
import path from "node:path";
import { fileURLToPath, pathToFileURL } from "node:url";
import { createRequire } from "node:module";
import type { FigSpec } from "./autocomplete/figSpecLoader.ts";
const ROOT = path.resolve(path.dirname(fileURLToPath(import.meta.url)), "../..");
async function loadFixture(relativePath: string): Promise<FigSpec> {
const mod = await import(pathToFileURL(path.join(ROOT, relativePath)).href);
return mod.default?.default ?? mod.default;
}
const [su, linuxReadlink, macReadlink, linuxDate, macDate, bundledDate, linuxBase64, macBase64] = await Promise.all([
loadFixture("node_modules/@withfig/autocomplete/build/su.js"),
loadFixture("electron/specs/readlink.js"),
loadFixture("electron/specs/macos/readlink.js"),
loadFixture("electron/specs/date.js"),
loadFixture("electron/specs/macos/date.js"),
loadFixture("node_modules/@withfig/autocomplete/build/date.js"),
loadFixture("electron/specs/base64.js"),
loadFixture("node_modules/@withfig/autocomplete/build/base64.js"),
]);
const byPlatform: Record<string, Record<string, FigSpec>> = {
linux: { su, readlink: linuxReadlink, date: linuxDate, base64: linuxBase64 },
macos: { su, readlink: macReadlink, date: macDate, base64: macBase64 },
};
const descriptionsDir = path.join(ROOT, "components/terminal/autocomplete");
const dictionaries = {
"zh-CN": JSON.parse(fs.readFileSync(path.join(descriptionsDir, "descriptions.zh-CN.json"), "utf8")) as Record<string, string>,
"zh-TW": JSON.parse(fs.readFileSync(path.join(descriptionsDir, "descriptions.zh-TW.json"), "utf8")) as Record<string, string>,
};
Object.defineProperty(globalThis, "localStorage", {
value: { getItem: () => null, setItem: () => {}, removeItem: () => {}, clear: () => {} },
configurable: true,
});
Object.defineProperty(globalThis, "window", {
value: {
netcatty: {
listFigSpecs: async () => ["su", "readlink", "date", "base64"],
loadFigSpec: async (name: string, hostOs?: string) =>
byPlatform[hostOs ?? "linux"]?.[name] ?? null,
},
},
configurable: true,
});
const { getCompletions } = await import("./autocomplete/completionEngine.ts");
type Locale = "en" | "zh-CN" | "zh-TW";
async function suggestions(input: string, os: "linux" | "macos", locale: Locale) {
return getCompletions(input, { os, locale, skipPathCompletion: true, maxResults: 100 });
}
function collectDescriptions(node: unknown, out = new Set<string>(), seen = new WeakSet<object>()): Set<string> {
if (!node || typeof node !== "object" || seen.has(node)) return out;
seen.add(node);
const entry = node as Record<string, unknown>;
if (typeof entry.description === "string" && entry.description.trim()) out.add(entry.description);
for (const value of Object.values(entry)) {
if (Array.isArray(value)) value.forEach((child) => collectDescriptions(child, out, seen));
else if (value && typeof value === "object") collectDescriptions(value, out, seen);
}
return out;
}
test("su -m distinguishes BSD login shells from util-linux shell selection", async () => {
const expected: Record<Locale, string> = {
en: "Leave the environment unmodified. The invoked shell is your login shell, and no directory changes are made. As a security precaution, if the target user's shell is a non-standard shell (as defined by getusershell(3)) and the caller's real uid is non-zero, su will fail",
"zh-CN": "尝试保留环境并通常保持当前工作目录。BSD 使用调用者的登录 shell;目标 shell 不在 getusershell(3) 列表且调用者非 root 时会失败。Linux util-linux 优先使用 -s 指定的 shell,其次使用 SHELL;受限 shell、登录选项及 PAM 可能影响结果",
"zh-TW": "嘗試保留環境並通常保持當前工作目錄。BSD 使用呼叫者的登入 shell;目標 shell 不在 getusershell(3) 列表且呼叫者非 root 時會失敗。Linux util-linux 優先使用 -s 指定的 shell,其次使用 SHELL;受限 shell、登入選項及 PAM 可能影響結果",
};
for (const os of ["linux", "macos"] as const) {
for (const locale of ["en", "zh-CN", "zh-TW"] as const) {
const option = (await suggestions("su -", os, locale)).find((item) => item.displayText === "-m");
assert.equal(option?.text, "su -m");
assert.equal(option?.description, expected[locale]);
}
}
});
test("GNU readlink quiet and verbose suggestions use the correct descriptions", async () => {
const expected: Record<Locale, { quiet: string; verbose: string }> = {
en: { quiet: "Suppress most error messages", verbose: "Report error messages" },
"zh-CN": { quiet: "抑制大多数错误消息", verbose: "显示错误消息" },
"zh-TW": { quiet: "抑制大多數錯誤訊息", verbose: "顯示錯誤訊息" },
};
for (const locale of ["en", "zh-CN", "zh-TW"] as const) {
const result = await suggestions("readlink -", "linux", locale);
for (const option of ["-q", "--quiet", "-s", "--silent"]) {
const item = result.find((value) => value.displayText === option);
assert.equal(item?.text, `readlink ${option}`);
assert.equal(item?.description, expected[locale].quiet);
}
for (const option of ["-v", "--verbose"]) {
const item = result.find((value) => value.displayText === option);
assert.equal(item?.text, `readlink ${option}`);
assert.equal(item?.description, expected[locale].verbose);
}
assert.equal(result.some((item) => item.displayText === "--strip"), false);
}
});
test("all descriptions in macOS date and base64 specs have both translations", () => {
for (const [name, spec] of Object.entries({ macDate, bundledDate, macBase64, macReadlink })) {
for (const [locale, dictionary] of Object.entries(dictionaries)) {
const missing = [...collectDescriptions(spec)].filter((description) => !dictionary[description]?.trim());
assert.deepEqual(missing, [], `${name}: missing ${locale} translations`);
}
}
});
test("macOS date falls back to the bundled spec and keeps its original option semantics", async () => {
const { loadFigSpec } = createRequire(import.meta.url)("../../electron/main/registerBridges.cjs") as {
loadFigSpec: (electronDir: string, name: string, os: string) => Promise<FigSpec | null>;
};
// This existing directory has no local specs but shares the real node_modules.
const electronDirWithoutOverrides = path.join(ROOT, "scripts");
assert.equal(fs.existsSync(path.join(electronDirWithoutOverrides, "specs/macos/date.js")), false);
const fallback = await loadFigSpec(electronDirWithoutOverrides, "date", "macos");
assert.ok(fallback);
const option = (name: string) => fallback.options?.find((item) =>
(Array.isArray(item.name) ? item.name : [item.name]).includes(name));
const cases = [
["-d", "Set the kernel's value for daylight saving time", "设置内核的夏令时标志", "設定核心的夏令時標誌"],
["-t", "Set the system's value for minutes west of GMT", "设置系统中相对于 GMT 向西的分钟数", "設定系統中相對於 GMT 向西的分鐘數"],
["-n", "Only set time on the current machine, instead of all machines in the local group", "仅设置当前机器的时间,不设置本地组内其他机器的时间", "僅設定當前機器的時間,不設定本地組內其他機器的時間"],
["-r", "Print the date and time represented by the specified number of seconds since the Epoch", "显示自纪元起指定秒数所对应的日期和时间", "顯示自紀元起指定秒數所對應的日期和時間"],
];
const { localizeSpecSuggestionDescriptions } = await import("./autocomplete/autocompleteDescriptionI18n.ts");
for (const [name, english, simplified, traditional] of cases) {
const entry = option(name);
assert.equal(entry?.description, english);
assert.equal((await localizeSpecSuggestionDescriptions([entry!], "en"))[0].description, english);
assert.equal((await localizeSpecSuggestionDescriptions([entry!], "zh-CN"))[0].description, simplified);
assert.equal((await localizeSpecSuggestionDescriptions([entry!], "zh-TW"))[0].description, traditional);
}
const referenceArg = option("-r")?.args;
assert.ok(referenceArg && !Array.isArray(referenceArg));
const seconds = "Number of seconds since the Epoch (00:00:00 UTC, January 1, 1970)";
assert.equal(referenceArg.description, seconds);
assert.equal(dictionaries["zh-CN"][seconds], "自纪元(1970 年 1 月 1 日 00:00:00 UTC)起的秒数");
assert.equal(dictionaries["zh-TW"][seconds], "自紀元(1970 年 1 月 1 日 00:00:00 UTC)起的秒數");
});
test("macOS date and base64 show localized BSD semantics", async () => {
const expected: Record<Locale, { obsolete: string; reference: string; zone: string; input: string; wrap: string }> = {
en: {
obsolete: "Obsolete option, accepted and ignored for compatibility",
reference: "Display a file's modification time or a time expressed in seconds since the Epoch",
zone: "Display the time in the specified output time zone",
input: "Read input from input_file. Default is stdin; passing - also represents stdin",
wrap: "Insert line breaks every count characters. Default is 0, which generates an unbroken stream",
},
"zh-CN": {
obsolete: "过时选项;为兼容而接受,但会被忽略",
reference: "显示文件的最后修改时间,或自纪元起指定秒数对应的时间",
zone: "按指定的输出时区显示时间",
input: "从 input_file 读取输入;默认为标准输入,'-' 也表示标准输入",
wrap: "每 count 个字符插入换行符;默认为 0,输出不换行",
},
"zh-TW": {
obsolete: "過時選項;為相容而接受,但會被忽略",
reference: "顯示檔案的最後修改時間,或自紀元起指定秒數對應的時間",
zone: "按指定的輸出時區顯示時間",
input: "從 input_file 讀取輸入;預設為標準輸入,'-' 也表示標準輸入",
wrap: "每 count 個字元插入換行符;預設為 0,輸出不換行",
},
};
assert.deepEqual(macDate.options?.find((option) => option.name === "-z")?.args, { name: "output_zone" });
for (const locale of ["en", "zh-CN", "zh-TW"] as const) {
const dateOptions = await suggestions("date -", "macos", locale);
assert.equal(dateOptions.find((item) => item.displayText === "-n")?.description, expected[locale].obsolete);
assert.equal(dateOptions.find((item) => item.displayText === "-r")?.description, expected[locale].reference);
const zone = dateOptions.find((item) => item.displayText === "-z");
assert.equal(zone?.text, "date -z");
assert.equal(zone?.description, expected[locale].zone);
const base64Options = await suggestions("base64 -", "macos", locale);
assert.equal(base64Options.find((item) => item.displayText === "-i")?.description, expected[locale].input);
assert.equal(base64Options.find((item) => item.displayText === "-b")?.description, expected[locale].wrap);
}
});
test("macOS readlink shows the localized BSD canonicalization option", async () => {
const expected: Record<Locale, string> = {
en: "Resolve symbolic links and print the canonical path only if all components exist",
"zh-CN": "解析符号链接,仅当所有路径组件都存在时才打印规范路径",
"zh-TW": "解析符號連結,僅當所有路徑元件都存在時才打印規範路徑",
};
for (const locale of ["en", "zh-CN", "zh-TW"] as const) {
const result = await suggestions("readlink -", "macos", locale);
const option = result.find((item) => item.displayText === "-f");
assert.equal(option?.text, "readlink -f");
assert.equal(option?.description, expected[locale]);
assert.equal(result.some((item) => item.displayText === "-s"), false);
}
});
test("macOS description translations retain their argument and format literals", () => {
const literalCases: Array<[string, string[]]> = [
["Read input from input_file. Default is stdin; passing - also represents stdin", ["input_file", "'-'"]],
["Write output to output_file. Default is stdout; passing - also represents stdout", ["output_file", "'-'"]],
["[+|-]val[ymwdHMS]", ["[+|-]val[ymwdHMS]"]],
["Use specified format for input instead of the default [[[mm]dd]HH]MM[[cc]yy][.ss] format", ["[[[mm]dd]HH]MM[[cc]yy][.ss]"]],
];
for (const dictionary of Object.values(dictionaries)) {
for (const [key, literals] of literalCases) {
for (const literal of literals) assert.ok(dictionary[key]?.includes(literal), `${key}: missing ${literal}`);
}
}
});
@@ -61,6 +61,16 @@ const touchSpec: FigSpec = {
],
};
const catSpec: FigSpec = {
name: "cat",
description: "Concatenate and print files",
};
const cpSpec: FigSpec = {
name: "cp",
description: "Copy files and directories",
};
Object.defineProperty(globalThis, "localStorage", {
value: {
getItem: () => null,
@@ -74,10 +84,12 @@ Object.defineProperty(globalThis, "localStorage", {
Object.defineProperty(globalThis, "window", {
value: {
netcatty: {
listFigSpecs: async () => ["docker", "touch"],
listFigSpecs: async () => ["docker", "touch", "cat", "cp"],
loadFigSpec: async (commandName: string) => ({
docker: dockerSpec,
touch: touchSpec,
cat: catSpec,
cp: cpSpec,
} as Record<string, FigSpec>)[commandName] ?? null,
},
},
@@ -200,7 +212,10 @@ test("committed zh-TW dictionary keeps zh-CN keys and Taiwan terminology", () =>
const simplified = JSON.parse(fs.readFileSync(path.join(dictDir, "descriptions.zh-CN.json"), "utf8"));
const traditional = JSON.parse(fs.readFileSync(path.join(dictDir, "descriptions.zh-TW.json"), "utf8"));
assert.deepEqual(Object.keys(traditional), Object.keys(simplified));
// zh-TW is community-maintained: new zh-CN keys may not have a zh-TW value
// yet, but zh-TW must not keep keys that no longer exist in zh-CN.
const staleTraditionalKeys = Object.keys(traditional).filter((key) => !(key in simplified));
assert.deepEqual(staleTraditionalKeys, []);
assert.equal(simplified[DEFAULT_LABEL], "(默认)");
assert.equal(traditional[DEFAULT_LABEL], "(預設)");
assert.equal(traditional[NETWORK], "新增網路");
@@ -209,12 +224,87 @@ test("committed zh-TW dictionary keeps zh-CN keys and Taiwan terminology", () =>
assert.equal(traditional[SINCE], SINCE_TW);
assert.equal(traditional[COMPRESSION_PROGRAM], "不根據歸檔字尾判斷壓縮程式");
// Semantic fixes: registry is a package source or image registry, not the
// Windows Registry; git --source prints a ref name, not source code.
assert.equal(simplified["Log in to a Docker registry"], "登录 Docker 镜像仓库");
assert.equal(traditional["Log in to a Docker registry"], "登入 Docker 映象倉庫");
assert.equal(simplified["Publishes a package to the npm registry"], "将软件包发布到 npm 软件源");
assert.equal(traditional["Publishes a package to the npm registry"], "將軟體包釋出到 npm 軟體源");
assert.equal(simplified["Show source"], "显示来源");
assert.equal(traditional["Show source"], "顯示來源");
// git worktree is a working tree (工作树), not a workspace (工作区); the
// two Docker capability options must use one term.
assert.equal(simplified["Manage multiple working trees"], "管理多个工作树");
assert.equal(simplified["Remove a working tree"], "移除工作树");
assert.equal(simplified["Add Linux capabilities"], "添加 Linux 能力");
assert.equal(simplified["Drop Linux capabilities"], "丢弃 Linux 能力");
// Truncated upstream keys and semantic fixes verified against the local
// man pages and upstream help text.
assert.equal(
simplified["Fetch the remote’s copy of current branch and rebases it into the local copy"],
"获取远程上当前分支的副本,并将本地当前分支变基到该副本之上",
);
assert.equal(
simplified["Composition of primaries and operands"],
"主项(primaries)与操作数的组合",
);
assert.equal(
simplified["Selects the cipher to use for encrypting the data transfer. This option is directly passed to ssh(1)"],
"选择用于加密数据传输的密码规格。此选项直接传递给 ssh(1)",
);
assert.equal(
simplified["Extract a zip file created in windows, containing files with non-ascii (chinese) filenames"],
"解压由 Windows 创建、包含非 ASCII(中文)文件名的 zip 文件",
);
assert.equal(
simplified["For writing options: write to system-wide $(prefix)/etc/gitconfig rather than"],
"对于写入选项:写入系统级 $(prefix)/etc/gitconfig,而不是仓库的 .git/config",
);
assert.equal(
simplified["Don’t display the copyright and version messages even in interactive mode"],
"即使在交互模式下也不显示版权和版本消息",
);
assert.equal(simplified["List details of each working tree"], "列出每个工作树的详细信息");
assert.equal(
simplified["Show what revision and author last modified each line of a file"],
"显示文件中每一行的最后修改版本和作者",
);
const pathspecNulKey =
"Only meaningful with --pathspec-from-file. Pathspec elements are separated wi";
assert.equal(
simplified[pathspecNulKey],
"仅与 --pathspec-from-file 一起使用时有意义。路径规格元素以 NUL 字符分隔",
);
assert.match(traditional[pathspecNulKey], /NUL 字元/);
// OpenCC s2twp mis-resolves these ambiguous characters in command copy;
// the generator's correction table must keep them out of the dictionary.
for (const bad of ["隻", "髮", "錶", "複用", "后", "登錄檔", "註冊表"]) {
assert.equal(
Object.values(traditional).filter((value) => value.includes(bad)).length,
0,
`zh-TW still contains ${bad}`,
);
}
assert.equal(
Object.values(traditional).filter((value) => /(?<!合)併為/.test(value)).length,
0,
"zh-TW still contains 併為 where 並為 is required",
);
assert.equal(
Object.values(simplified).filter((value) => value.includes("注册表")).length,
0,
"zh-CN still contains 注册表 for a package/image registry",
);
let processCount = 0;
let tripCount = 0;
for (const key of Object.keys(simplified)) {
const source = simplified[key];
const converted = traditional[key];
assert.equal(typeof converted, "string");
// zh-TW is community-maintained; skip entries that have not been
// translated yet instead of failing the zh-CN work on them.
if (typeof converted !== "string") continue;
assert.equal(converted.includes("进程"), false);
assert.equal(converted.includes("默认"), false);
assert.equal(converted.includes("网络"), false);
@@ -224,3 +314,28 @@ test("committed zh-TW dictionary keeps zh-CN keys and Taiwan terminology", () =>
assert.ok(processCount > 0);
assert.equal(tripCount, processCount);
});
test("command-name suggestions carry Chinese descriptions", async () => {
const simplified = await getCompletions("c", {
locale: "zh-CN",
skipPathCompletion: true,
maxResults: 10,
});
assert.equal(suggestionNamed(simplified, "cat")?.description, "连接并打印文件");
assert.equal(suggestionNamed(simplified, "cp")?.description, "复制文件或目录");
const traditional = await getCompletions("c", {
locale: "zh-TW",
skipPathCompletion: true,
maxResults: 10,
});
assert.equal(suggestionNamed(traditional, "cat")?.description, "連線並列印檔案");
assert.equal(suggestionNamed(traditional, "cp")?.description, "複製檔案和目錄");
const english = await getCompletions("c", {
locale: "en",
skipPathCompletion: true,
maxResults: 10,
});
assert.equal(suggestionNamed(english, "cat")?.description, undefined);
});
@@ -0,0 +1,144 @@
import test from "node:test";
import assert from "node:assert/strict";
import path from "node:path";
import { fileURLToPath, pathToFileURL } from "node:url";
const ROOT = path.resolve(path.dirname(fileURLToPath(import.meta.url)), "../..");
const dateSpec = (await import(pathToFileURL(path.join(ROOT, "electron/specs/date.js")).href)).default;
const macosDateSpec = (await import(pathToFileURL(path.join(ROOT, "electron/specs/macos/date.js")).href)).default;
const loadRequests: Array<{ name: string; os?: string }> = [];
const overlappingOptionsSpec = {
name: "fixture",
options: [
{ name: "-f", netcattyOptionalArgAttached: true, args: { isOptional: true, suggestions: ["astest"] } },
{ name: "-fast" },
],
};
const ordinaryOptionalSpec = {
name: "ordinary",
options: [
{ name: ["-o", "--output"], args: { isOptional: true, suggestions: ["json"] } },
{ name: ["-t", "--type"], netcattyOptionalArgAttached: false, args: { isOptional: true, suggestions: ["json"] } },
{ name: ["-q", "--quality"], netcattyOptionalArgAttached: "true", args: { isOptional: true, suggestions: ["json"] } },
],
};
Object.defineProperty(globalThis, "localStorage", {
value: { getItem: () => null, setItem: () => {}, removeItem: () => {} },
configurable: true,
});
Object.defineProperty(globalThis, "window", {
value: {
netcatty: {
listFigSpecs: async () => ["date", "fixture", "ordinary"],
loadFigSpec: async (name: string, os?: string) => {
loadRequests.push({ name, os });
if (name === "date") return os === "macos" ? macosDateSpec : dateSpec;
if (name === "fixture") return overlappingOptionsSpec;
return name === "ordinary" ? ordinaryOptionalSpec : null;
},
},
},
configurable: true,
});
const { getCompletions } = await import("./autocomplete/completionEngine.ts");
test("GNU date completes an optional format attached to the short option", async () => {
const suggestions = await getCompletions("date -Is", {
os: "linux",
skipPathCompletion: true,
});
const seconds = suggestions.find((suggestion) => suggestion.text === "date -Iseconds");
assert.equal(seconds?.displayText, "seconds");
});
test("GNU date completes the value after the long option's equals sign", async () => {
const suggestions = await getCompletions("date --iso-8601=s", {
os: "linux",
skipPathCompletion: true,
});
assert.equal(
suggestions.find((suggestion) => suggestion.text === "date --iso-8601=seconds")?.displayText,
"seconds",
);
const allFormats = await getCompletions("date --iso-8601=", {
os: "linux",
skipPathCompletion: true,
});
assert.deepEqual(
allFormats.filter((suggestion) => suggestion.source === "arg").map((suggestion) => suggestion.text),
["date --iso-8601=date", "date --iso-8601=hours", "date --iso-8601=minutes", "date --iso-8601=seconds", "date --iso-8601=ns"],
);
});
test("a bare -I remains a complete option and other options stay available", async () => {
const bare = await getCompletions("date -I", { os: "linux", skipPathCompletion: true });
assert.equal(bare.some((suggestion) => suggestion.text.startsWith("date -Iseconds")), false);
const afterShort = await getCompletions("date -I ", { os: "linux", skipPathCompletion: true, maxResults: 100 });
assert.equal(afterShort.some((suggestion) => suggestion.text === "date -I seconds"), false);
const afterLong = await getCompletions("date --iso-8601 ", { os: "linux", skipPathCompletion: true, maxResults: 100 });
assert.equal(afterLong.some((suggestion) => suggestion.text === "date --iso-8601 seconds"), false);
const next = await getCompletions("date -I -", { os: "linux", skipPathCompletion: true, maxResults: 100 });
assert.ok(next.some((suggestion) => suggestion.text === "date -I --utc"));
});
test("required option arguments retain their existing separated completion", async () => {
const suggestions = await getCompletions("date --rfc-3339 s", {
os: "linux",
skipPathCompletion: true,
});
assert.ok(suggestions.some((suggestion) => suggestion.text === "date --rfc-3339 seconds"));
const attached = await getCompletions("date --rfc-3339=s", {
os: "linux",
skipPathCompletion: true,
});
assert.equal(attached.some((suggestion) => suggestion.text === "date --rfc-3339=seconds"), false);
});
test("optional arguments without the explicit attached-value marker do not add attached suggestions", async () => {
for (const [input, unwanted] of [
["ordinary -oj", "ordinary -ojson"],
["ordinary --output=j", "ordinary --output=json"],
["ordinary -tj", "ordinary -tjson"],
["ordinary --type=j", "ordinary --type=json"],
["ordinary -qj", "ordinary -qjson"],
["ordinary --quality=j", "ordinary --quality=json"],
]) {
const suggestions = await getCompletions(input, { os: "linux", skipPathCompletion: true });
assert.equal(suggestions.some((suggestion) => suggestion.text === unwanted), false, input);
}
});
test("an option name takes precedence over an overlapping short-option argument", async () => {
const suggestions = await getCompletions("fixture -fa", {
os: "linux",
skipPathCompletion: true,
});
assert.ok(suggestions.some((suggestion) => suggestion.text === "fixture -fast"));
assert.equal(suggestions.some((suggestion) => suggestion.text === "fixture -fastest"), false);
});
test("date completion uses the selected host OS even after another host loaded a spec", async () => {
const linux = await getCompletions("date -", { os: "linux", skipPathCompletion: true, maxResults: 100 });
const macos = await getCompletions("date -", { os: "macos", skipPathCompletion: true, maxResults: 100 });
assert.ok(linux.some((suggestion) => suggestion.text === "date --date"));
assert.equal(linux.some((suggestion) => suggestion.text === "date -j"), false);
assert.ok(macos.some((suggestion) => suggestion.text === "date -j"));
assert.equal(macos.some((suggestion) => suggestion.text === "date --date"), false);
assert.ok(loadRequests.some((request) => request.name === "date" && request.os === "linux"));
assert.ok(loadRequests.some((request) => request.name === "date" && request.os === "macos"));
});
test("macOS date completes the supported short option without GNU long options", async () => {
const short = await getCompletions("date -Is", { os: "macos", skipPathCompletion: true });
assert.ok(short.some((suggestion) => suggestion.text === "date -Iseconds"));
const long = await getCompletions("date --iso-8601=s", { os: "macos", skipPathCompletion: true });
assert.equal(long.some((suggestion) => suggestion.text === "date --iso-8601=seconds"), false);
});
+72 -1
View File
@@ -1,6 +1,6 @@
import assert from "node:assert/strict";
import test from "node:test";
import { COMMON_FIG_SPECS, normalizeCommandName } from "./autocomplete/figSpecLoader";
import { COMMON_FIG_SPECS, getAvailableSpecs, hasSpec, loadSpec, normalizeCommandName } from "./autocomplete/figSpecLoader";
test("preload common specs includes dnf alongside yum and apt", () => {
assert.ok(COMMON_FIG_SPECS.includes("apt"));
@@ -9,9 +9,80 @@ test("preload common specs includes dnf alongside yum and apt", () => {
for (const command of ["ln", "stat", "wc", "cut", "uniq", "tee", "xargs"]) {
assert.ok(COMMON_FIG_SPECS.includes(command), `${command} should be preloaded`);
}
const batch4Commands = [
"echo", "which", "paste", "pwd", "clear", "su", "crontab", "env", "uname",
"base64", "date", "id", "split", "seq", "join", "dig", "dd", "htop",
"basename", "dirname", "readlink", "more",
];
for (const command of batch4Commands) {
assert.ok(COMMON_FIG_SPECS.includes(command), `${command} should be preloaded`);
}
});
test("normalizeCommandName strips path and extension", () => {
assert.equal(normalizeCommandName("/usr/bin/dnf"), "dnf");
assert.equal(normalizeCommandName("DNF"), "dnf");
});
test("caches and deduplicates specs separately for each target OS", async () => {
const calls: string[] = [];
Object.defineProperty(globalThis, "window", {
configurable: true,
value: { netcatty: { loadFigSpec: async (name: string, hostOs: string) => {
calls.push(`${name}:${hostOs}`);
return { name, description: hostOs };
} } },
});
const [linux, linuxAgain, macos] = await Promise.all([
loadSpec("platform-cache-fixture", "linux"),
loadSpec("platform-cache-fixture", "linux"),
loadSpec("platform-cache-fixture", "macos"),
]);
assert.equal(linux?.description, "linux");
assert.equal(linuxAgain, linux);
assert.equal(macos?.description, "macos");
assert.deepEqual(calls, ["platform-cache-fixture:linux", "platform-cache-fixture:macos"]);
assert.equal(await loadSpec("platform-cache-fixture", "macos"), macos);
assert.equal(calls.length, 2);
});
test("retries a spec load after the bridge becomes available", async () => {
Object.defineProperty(globalThis, "window", { configurable: true, value: {} });
assert.equal(await loadSpec("retry-fixture", "linux"), null);
Object.defineProperty(globalThis, "window", {
configurable: true,
value: { netcatty: { loadFigSpec: async (name: string) => ({ name }) } },
});
assert.equal((await loadSpec("retry-fixture", "linux"))?.name, "retry-fixture");
});
test("available specs are cached and resolved per target OS", async () => {
const listCalls: Array<string | undefined> = [];
Object.defineProperty(globalThis, "window", {
configurable: true,
value: { netcatty: {
listFigSpecs: async (hostOs?: string) => {
listCalls.push(hostOs);
return hostOs === "macos" ? ["common-fixture", "mac-only-fixture"] : ["common-fixture"];
},
loadFigSpec: async (name: string, hostOs?: string) =>
(name === "mac-only-fixture" && hostOs === "macos" ? { name } : null),
} },
});
assert.deepEqual(await getAvailableSpecs("linux"), ["common-fixture"]);
assert.deepEqual(await getAvailableSpecs("linux"), ["common-fixture"]);
assert.deepEqual(listCalls, ["linux"], "the Linux list should be fetched once");
assert.deepEqual(await getAvailableSpecs("macos"), ["common-fixture", "mac-only-fixture"]);
assert.deepEqual(listCalls, ["linux", "macos"]);
assert.equal(await hasSpec("mac-only-fixture", "linux"), false);
assert.equal(await hasSpec("mac-only-fixture", "macos"), true);
assert.equal(await hasSpec("common-fixture", "linux"), true);
// A successful macOS load must not advertise the command to Linux.
assert.equal((await loadSpec("mac-only-fixture", "macos"))?.name, "mac-only-fixture");
assert.equal(await hasSpec("mac-only-fixture", "linux"), false);
assert.equal(await loadSpec("mac-only-fixture", "linux"), null);
});
@@ -38,7 +38,12 @@ behavior and the discrepancy is recorded below.
| --- | --- | --- |
| command | Extract compressed files in a ZIP archive | 解压 ZIP 压缩包中的文件 |
| `-l` | List the contents of a zip file without extracting | 列出 zip 文件内容而不解压 |
| `-0` | Extract a zip file created in windows, containing files with non-ascii (chinese) filenames | 上游选项疑似错误,请核对当前 unzip 版本支持的参数 |
| `-0` | Extract a zip file created in windows, containing files with non-ascii (chinese) filenames | 解压由 Windows 创建、包含非 ASCII(中文)文件名的 zip 文件 |
> Note: the Fig spec's `-0` option is dubious (Info-ZIP unzip 6.00 has no
> `-0`). The zh-CN value translates the English key faithfully instead of
> showing an editorial note in the completion popup; fix the option name in a
> local spec override if the upstream entry is confirmed wrong.
### make
@@ -65,8 +65,9 @@ Total adopted: 177 unique English keys.
- **awk**: the local macOS `awk` is BSD awk, while the spec also exposes
gawk-specific options. The gawk manual confirms that `-c` is traditional
compatibility mode (not POSIX), `-n` is `--non-decimal-data`, and `-t` is
`--lint-old` (not type checking). The zh-CN text follows the gawk manual;
`electron/specs/awk.js` itself is left unchanged.
`--lint-old` (not type checking). The zh-CN text follows the gawk manual, and
`electron/specs/awk.js` now carries matching English for `-n`, `-c` and `-t`
instead of the earlier Fig wording; the dictionary keys moved with the spec.
- **sed**: the local macOS sed is BSD sed. Fig mixes BSD/Apple options
(`-a`, `-I`, `-i`, `-l`) with GNU extensions (`e`, `F`, `v`, `z`) and shared
options. In particular, BSD `-i` requires an extension while GNU `-i` treats
@@ -104,11 +105,11 @@ unique English strings.
| --- | --- | --- |
| awk | Assign a variable (var=value) | 赋值一个变量(var=value) |
| awk | AWK program text (e.g. '{print $1}') | AWK 程序文本(例如 '{print $1}') |
| awk | Disable automatic input record splitting (gawk) | 识别输入数据中的八进制和十六进制值,请谨慎使用(gawk) |
| awk | Recognize octal and hexadecimal values in input data (gawk) | 识别输入数据中的八进制和十六进制值,请谨慎使用(gawk) |
| awk | Dump variables to file (gawk) | 将变量转储到文件(gawk) |
| awk | e.g. ',' or '\t' | 例如 ',' 或 '\t' |
| awk | Enable pretty-printed output | 启用美化(pretty-print)输出 |
| awk | Enable type checking (gawk) | 对无法移植到原始 UNIX awk 的构造发出警告(gawk) |
| awk | Warn about constructs not portable to the original Unix awk (gawk) | 对无法移植到原始 UNIX awk 的构造发出警告(gawk) |
| awk | Include AWK source library | 包含 AWK 源库 |
| awk | Input file(s) | 输入文件 |
| awk | Load dynamic extension (gawk) | 加载动态扩展(gawk) |
@@ -119,7 +120,7 @@ unique English strings.
| awk | Profile execution and write to file (gawk) | 分析执行情况并写入文件(gawk) |
| awk | Read AWK program from file | 从文件读取 AWK 程序 |
| awk | Read AWK program from file (like -f but disables command-line variable assignments) | 从文件读取 AWK 程序(类似 -f,但禁用命令行变量赋值) |
| awk | Run in POSIX compatibility mode (gawk) | 以传统兼容模式运行,行为等同 Brian Kernighan 的 awk(gawk) |
| awk | Run in traditional compatibility mode (gawk) | 以传统兼容模式运行,行为等同 Brian Kernighan 的 awk(gawk) |
| awk | Sandbox mode — disable system(), I/O redirection (gawk) | 沙箱模式——禁用 system() 和 I/O 重定向(gawk) |
| awk | Set field separator | 设置字段分隔符 |
| awk | Specify AWK program text | 指定 AWK 程序文本 |
@@ -142,7 +143,12 @@ unique English strings.
| python, python3 | Disable the import of the module site and the site-dependent manipulations of sys.path that it entails | 禁用 site 模块的导入,以及随之进行的 sys.path 站点相关调整 |
| python, python3 | Do -O and also discard docstrings | 执行 -O 的操作,并丢弃文档字符串 |
| python, python3 | Don’t add the user site-packages directory to sys.path | 不将用户 site-packages 目录加入 sys.path |
| python, python3 | Don’t display the copyright and version messages even in interactive mode | 上游选项疑似错误:交互模式下不显示版权和版本信息请用 -q |
| python, python3 | Don’t display the copyright and version messages even in interactive mode | 即使在交互模式下也不显示版权和版本消息 |
> Note: the Fig spec's `-g` option is not a real CPython flag (use `-q`). The
> zh-CN value translates the English key faithfully instead of showing an
> editorial note in the completion popup; fix the option name in a local spec
> override if the upstream entry is confirmed wrong.
| python, python3 | Execute the Python code in command. command can be one or more statements separated by newlines, with significant leading whitespace as in normal module code | 执行 command 中的 Python 代码。command 可以是用换行分隔的一条或多条语句,并像普通模块代码一样保留有意义的行首空白 |
| python, python3 | Force the stdout and stderr streams to be unbuffered. This option has no effect on the stdin stream | 强制 stdout 和 stderr 不缓冲;此选项对 stdin 无效 |
| python, python3 | If given, Python won’t try to write .pyc files on the import of source modules | 指定后,Python 在导入源模块时不会写入 .pyc 文件 |
@@ -0,0 +1,243 @@
# Autocomplete description overlay: small-gap utility batch
This batch closes the 22 general-purpose commands that the translation audit
listed with 15 or fewer missing descriptions. The same numeric tier also
contains 184 vendor-specific or niche specs (for example `sapphire`, `yomo`,
`tangram`, `mailsy`, `streamlit`); those are intentionally left to a later pass
because their semantics need per-tool verification. Descriptions are localized
for `zh-CN` and generated into `zh-TW`; local Fig specs also correct option
semantics where the bundled specs do not match the target operating system.
Scope: `echo`, `which`, `paste`, `pwd`, `clear`, `su`, `crontab`, `env`,
`uname`, `base64`, `date`, `id`, `split`, `seq`, `join`, `dig`, `dd`, `htop`,
`basename`, `dirname`, `readlink`, and `more`. The batch adopts 159 unique
English keys from 160 per-command entries (`String to operate on (typically
filenames)` is shared by `basename` and `dirname`).
## Sources
| Source | Version / location | Used for |
| --- | --- | --- |
| `@withfig/autocomplete` | `2.692.3`; compiled `build/{echo,which,paste,pwd,clear,su,crontab,env,uname,base64,date,id,split,seq,join,dig,dd,htop,basename,dirname,readlink,more}.js` | English keys, option names, and arguments |
| GNU Coreutils | documented `echo`, `env`, `base64`, `date`, `id`, `split`, `seq`, `join`, `dd`, `pwd`, `basename`, `dirname`, `readlink` behavior | Option semantics shared with GNU |
| BSD/macOS manuals | local macOS `man su`, `date`, `crontab`, `clear`, `more`, `id`, `paste` | Flags the Fig specs actually expose (several are BSD-only) |
| `jaywcjlove/linux-command` | MIT, `master` fetched 2026-11-07 (sparse clone of `command/`) | GNU option wording for the Linux-first review, and the option set of the local GNU `date` spec |
Checked on 2026-11-07 against `@withfig/autocomplete@2.692.3` by scanning all 714
bundled specs for each adopted key. Eleven keys are shared outside this batch
and were reviewed for wording that stays correct in every owner:
| Shared key | Also used by | Resolution |
| --- | --- | --- |
| `Query Domain A/MX/CNAME/TXT Record`, `Query SOA/TTL Record`, `Query ALL DNS Records`, `Query only answer section` | `dog` | DNS-record wording is command-neutral |
| `String to operate on (typically filenames)` | `basename`, `dirname` | shared inside the batch |
| `Print version info` | `ag` | generic version wording |
| `Display version information` | `ampx`, `hexo`, `julia`, `mkinitcpio`, `mvn`, `premake` | generic version wording |
## Coverage
| Command | Descriptions | Notes |
| --- | ---: | --- |
| `echo` | 4 | newline suppression and escape handling |
| `which` | 3 | PATH lookup, `-a`, `-s` |
| `paste` | 3 | line concatenation, `-d` circular list, `-s` |
| `pwd` | 3 | logical vs physical directory |
| `clear` | 4 | terminal type, ncurses version, E3 scrollback |
| `su` | 4 | BSD `-f`/`-l`/`-`/`-m` |
| `crontab` | 5 | maintain, edit, list, remove, `-u` |
| `env` | 9 | NUL-terminated output, `-i`, `-v`, `-u`, `-P`, `-S` |
| `uname` | 8 | `-a`, `-m`, `-n`, `-p`, `-r`, `-s`, `-v` |
| `base64` | 8 | local GNU spec: `-d`, `-i`, `-w` and file operands |
| `date` | 17 | local GNU spec: `-d`, `--debug`, `-f`, `-I`, `-R`, `--rfc-3339`, `-r`, `-s`, `-u` |
| `id` | 10 | audit, full name, groups, MAC label, `-n`, `-p` |
| `split` | 9 | suffix length, `-b`, `-d`, `-l`, `-p`, file, prefix |
| `seq` | 11 | start/step/last, `-w`, `-s`, `-f`, `-t` |
| `join` | 11 | equality join, `-a`, `-e`, `-o`, `-t`, `-v`, file/field |
| `dig` | 10 | local spec: record types and output filters |
| `dd` | 14 | block sizes, seek/skip, conversions |
| `htop` | 14 | delay, filter, highlight, sort, tree, user |
| `basename` | 4 | `-a`, `-s`, operand |
| `dirname` | 2 | operand |
| `readlink` | 11 | local GNU spec: canonicalize, quiet, verbose, zero; separate macOS spec |
| `more` | 11 | `-d`, `-l`, `-f`, `-p`, `-c`, `-s`, `-u`, `-n` |
The table counts the descriptions each command reaches with the specs in this
change, so later corrections are already reflected there (`dig` no longer
carries the removed `TTL` shortcut, for example). Totals: 175 reachable
descriptions on Linux; platform variants add descriptions beyond these numbers.
The local `date`, `dig`, `readlink` and `base64` specs replace bundled option
sets on Linux, while `htop` corrects the `-H` delay unit.
All 22 commands are added to `COVERED_COMMANDS` and `COMMON_FIG_SPECS`. They are
small, general-purpose utilities, so preloading them costs little and removes the
on-demand spec load for the most common shell sessions.
## Semantic notes
- **dig**: the bundled spec labels the `NS` type as “Query MX Record” and offers
`TTL` as a record type. Both are spec defects rather than wording problems, so
`electron/specs/dig.js` replaces them: NS is described as authoritative name
servers, the bogus TTL shortcut is gone, and ANY carries the RFC 8482 caveat.
- **more**: the Fig spec maps `-l` to “Do not pause after any line containing a
^L (form feed)” and `-f` to “Count logical lines, rather than screen lines”.
This matches GNU `more`; the translations follow the option each description
belongs to, not the numeric order of the list.
- **date**: Linux uses the local GNU spec (`electron/specs/date.js`), with
`-d/--date`, `--debug`, `-f/--file`, `-I/--iso-8601`, `-R/--rfc-email`,
`--rfc-3339`, `-r/--reference`, `-s/--set` and `-u/--utc`. macOS uses
`electron/specs/macos/date.js` for its BSD arguments, including `-f` input
format, `-j`, `-r` file or epoch seconds, `-v` adjustment and `-z` output
timezone. File suggestions for `-r` also appear for numeric prefixes so that
filenames beginning with digits remain discoverable. The bundled macOS
spec's obsolete `-d` and `-t` switches are omitted from the local one. If the
native spec is ever missing, the loader falls back to the bundled spec and its
descriptions keep the older BSD meanings they quote.
- **su**: the four descriptions no longer hardcode BSD-only environment claims.
`-l` says it switches to the target home and rebuilds the login environment as
the implementation and PAM decide. With `-m`, BSD selects the caller's
login shell, while util-linux normally consults `SHELL`; explicit shell and
restricted-shell rules affect the latter. `-f` prevents a csh/tcsh login
shell from reading `.cshrc`.
- **env**: `-P` searches an alternate directory list instead of `PATH`, `-S`
splits a string into arguments, and the trailing “Utility to run” describes
the command operand. These are three separate keys and are not conflated.
- **readlink**: the bundled spec reuses `stat` wording for the command root and
`-f` (“printf”, “struct stat”). `electron/specs/readlink.js` supplies the GNU
options (`-f/-e/-m/-n/-q/-s/-v/-z`), while the macOS variant supplies its
native `-f` and `-n`. `-s/--silent` suppresses errors; there is no `--strip`.
- **paste**: `-d` replaces newlines with characters drawn circularly from the
list; the translation keeps the “wrap around the list” behavior explicit.
- **split**: `-p` starts a new output file on each matching extended regular
expression and is incompatible with `-b`/`-l`; the translation states both.
- **id**: the long root description distinguishes real and effective IDs; the
translation preserves that distinction and the “assumed identical when a user
is named” clause.
## Platform coverage (GNU/Linux vs BSD/macOS)
Netcatty sessions usually target Linux hosts, so GNU semantics were checked
against `jaywcjlove/linux-command` (MIT, `master` fetched 2026-11-07) for every
command in this batch that the reference covers (21 of 22; `readlink` is absent).
That review changed four entries, confirmed the rest, and produced the GNU
`date` spec described in the semantic notes.
Local specs cover five commands whose bundled Fig data was wrong or macOS-only.
Linux hosts load the following local versions:
| Command | Local spec | Bundled spec problem |
| --- | --- | --- |
| `date` | `electron/specs/date.js` | `-j`, `-n`, `-t`, `-v`; `-d` meant DST, `-r` meant epoch seconds |
| `dig` | `electron/specs/dig.js` | `NS` labelled as an MX query, `TTL` offered as a record type |
| `readlink` | `electron/specs/readlink.js` | root and `-f` reused `stat` wording (`printf`, `struct stat`) |
| `base64` | `electron/specs/base64.js` | BSD `-b`/`-i`/`-o`; GNU uses `-w`, and `-i` means ignore garbage while decoding |
| `htop` | `electron/specs/htop.js` | `-H` delay described as tenths of a second; htop stores seconds |
For macOS sessions, the loader uses separate native `date` and `readlink`
specs and the bundled BSD `base64` spec. If the native `date` spec is missing,
the loader falls back to the bundled BSD `date` spec, whose descriptions retain
translations matching their English keys. `dig` and `htop` use their common
local specs. The renderer passes the target session's OS over the Fig bridge,
and loaded/in-flight spec caches, the available-spec list and the loaded-name
index are all scoped by command and OS. For macOS the bridge's spec list merges
`specs/` with `specs/macos/`; other sessions see only `specs/`, so a
macOS-only command is never suggested where it cannot load.
The remaining specs include options or meanings that depend on the platform.
The table records examples from the bundled BSD-oriented specs; some flags also
exist in GNU or util-linux tools but have different semantics:
| Command | Platform-dependent options |
| --- | --- |
| `su` | `-f`, `-l`, `-m`, `-` |
| `id` | `-A`, `-F`, `-M`, `-P` |
| `split` | `-p` |
| `seq` | `-t` |
| `env` | `-P` |
| `more` | `-u` (GNU uses it for underlining; the spec follows BSD “ignored”) |
| `which` | `-s` |
`su` is a special case: its spec is close to util-linux, but the wording no
longer hardcodes `PATH=/bin:/usr/bin` or a fixed variable list, because Linux
`su -l` setup depends on the implementation and PAM configuration. The `-m`
description calls out the BSD and util-linux shell-selection difference; the
`-l` and `-f` descriptions avoid fixed environment claims.
`dd` also carries an upstream artifact: an operand named `files` with “Copy this
many files before terminating”, which real `dd` does not have; the literal
translation is kept and flagged here instead of inventing behavior.
The loader now supports per-OS spec selection. The remaining commands listed
above still use their existing shared specs and need separate review before
adding platform-specific overrides.
## Review fixes (2026-11-08)
A second review pass over the 159 new entries found wording that would be
visible in the completion menu. Every item below was applied:
| Item | Resolution |
| --- | --- |
| `htop -H` “new and old processes” | 高亮新启动和已退出的进程 (old entries are processes that just exited and linger for highlighting) |
| `htop` highlight delay | The Fig text says “in tenths of sec”, but htop 3.2.2 compares `1000 * highlightDelaySecs`; `electron/specs/htop.js` corrects the English for every locale and the zh-CN text says seconds |
| `split -a` “letters” | 字符, because `-d` produces numeric suffixes |
| `split -b` units | KiB / MiB / GiB, matching GNU's 1024-based suffixes instead of KB |
| `dd cbs` | 转换记录长度(字节),供 block/unblock 等记录转换使用 |
| `join -a` / `-v` | 第 file_number 个文件中的行, because `file_number` is a file index |
| `join -o` | No longer limited to matched lines; `-o` also formats unpaired output from `-a`/`-v` |
| `basename -a` | 支持多个路径名,将每个参数作为路径名处理 |
| `env -0` | 每条环境变量记录以 NUL 而非换行符结束 |
| `dig` answer filter | The zh-CN value describes hiding comments, question, authority, additional and statistics; the English key stays unchanged because `dog` shares it |
| `dig ANY` | The shared `Query ALL DNS Records` key stays; the zh-CN value carries the RFC 8482 caveat |
| `dig TTL` | Removed from the `dig` spec; the dictionary key stays because `dog` still offers TTL |
| `readlink -f` | Fixed by the local spec; no longer shows `printf`/`struct stat` wording |
| `base64 -i` | GNU uses `--ignore-garbage`; macOS takes an input file and uses the bundled BSD spec |
| `su -l` / `-m` / `-f` | Removed hardcoded environment claims; see the platform note |
| `seq` root | 默认按 1 递增;BSD/macOS 在起始值大于结束值时按 -1 递减 |
| `uname` root | 显示系统信息(无选项时输出内核名称) |
Taiwan wording that OpenCC s2twp could not resolve is handled by a documented
post-conversion table in the generator (not by hand-editing `zh-TW`):
`擴充套件正規表示式`→`擴充正規表示式`, `擴充套件 E3`→`擴充 E3`,
`欄位連線`→`欄位聯結`, `二進位制資料`→`二進位資料`, `后綴`→`字尾`,
`執行檔例項`→`執行檔`, `屏幕`→`螢幕`, `文本`→`文字`.
Shared keys: `dig` keeps `A`, `MX`, `CNAME`, `TXT`, `SOA`, `ANY +noall +answer`
and the section-filter descriptions byte-identical to the bundled spec because
`dog` reuses them, so their corrections live in the zh-CN values. `NS` is the
one dig-specific key (`Query NS records (authoritative name servers)`), and
`Query TTL Record` remains in the dictionary for `dog` only.
## Adopted entries (excerpt)
| Command | English | zh-CN |
| --- | --- | --- |
| `echo` | Write arguments to the standard output | 将参数写入标准输出 |
| `which` | Locate a program in the user's PATH | 在用户的 PATH 中定位程序 |
| `pwd` | Return working directory name | 返回工作目录名称 |
| `seq -w` | Equalize the widths of all numbers by padding with zeros as necessary | 必要时用零填充,使所有数字宽度一致 |
| `basename` | Return filename portion of pathname | 返回路径名的文件名部分 |
| `dirname` | Return directory portion of pathname | 返回路径名的目录部分 |
| `readlink` | Symbolic link or path to resolve | 要解析的符号链接或路径 |
| `date -u` | Display or set the date in UTC (Coordinated Universal) time | 以 UTC(协调世界时)显示或设置日期 |
| `more -f` | Count logical lines, rather than screen lines | 按逻辑行计数,而不是按屏幕行 |
| `dig` (NS) | Query NS records (authoritative name servers) | 查询 NS 记录(权威名称服务器) |
| `split -p` | The file is split whenever an input line matches pattern, which is interpreted as an extended regular expression. The matching line will be the first line of the next output file. This option is incompatible with the -b and -l options | 每当输入行匹配 pattern(按扩展正则表达式解释)时就拆分成新文件。匹配行会成为下一个输出文件的第一行。该选项与 -b 和 -l 不兼容 |
| `dd bs` | Set input and output block size | 同时设置输入和输出块大小 |
| `htop -H` delay | Highlight duration in seconds | 高亮持续时间,单位为秒 |
`zh-TW` is generated from these values with
`node scripts/generate-autocomplete-descriptions-zh-TW.mjs` (OpenCC s2twp), not
edited by hand. Spot checks include `引數`, `檔案`, `程式`, `連結`, `預設`, and `列印`.
## Verification
| Command | Result |
| --- | --- |
| `node scripts/list-untranslated-autocomplete-descriptions.mjs` | only the known `node` shared key and `NO_SPEC ip netstat ss` remain |
| `node --test --import tsx components/terminal/autocompleteDescriptionI18n.batch4.test.ts` | 4 tests, 4 pass |
| `node --test --import tsx components/terminal/{figSpecLoader,autocompleteDescriptionI18n,batch,batch2,batch3}.test.ts` | 19 tests, 19 pass |
| `node scripts/generate-autocomplete-descriptions-zh-TW.mjs` re-run | idempotent, no diff |
| `git diff --check` | clean |
The generator was re-run after the merge and produced no further diff, so the
committed `zh-TW` file is exactly its output.
@@ -1,11 +1,37 @@
const test = require("node:test");
const assert = require("node:assert/strict");
const fs = require("node:fs");
const path = require("node:path");
const { pathToFileURL } = require("node:url");
const { getTempFilePath } = require("./tempDirBridge.cjs");
const {
filterExcludedFigSpecs,
isExcludedFigSpec,
loadFigSpec,
registerFigSpecHandlers,
} = require("../main/registerBridges.cjs");
function createSpecFixture(t) {
const root = fs.mkdtempSync(`${getTempFilePath("fig-spec-test")}-`);
t.after(() => fs.rmSync(root, { recursive: true, force: true }));
const electronDir = path.join(root, "electron");
const specDir = path.join(electronDir, "specs");
const macSpecDir = path.join(specDir, "macos");
fs.mkdirSync(macSpecDir, { recursive: true });
fs.writeFileSync(path.join(root, "package.json"), JSON.stringify({ type: "module" }));
return { electronDir, specDir, macSpecDir };
}
function createFigHandlers(electronDir) {
const handlers = new Map();
registerFigSpecHandlers({ handle: (name, handler) => handlers.set(name, handler) }, electronDir);
return {
list: (os) => handlers.get("netcatty:figspec:list")(null, os),
load: (name, os) => handlers.get("netcatty:figspec:load")(null, name, os),
};
}
test("filters cloud fig specs removed from packaged builds", () => {
assert.equal(isExcludedFigSpec("aws"), true);
assert.equal(isExcludedFigSpec("aws/s3"), true);
@@ -20,3 +46,169 @@ test("filters cloud fig specs removed from packaged builds", () => {
["git", "aws-vault"],
);
});
test("selects GNU or native macOS specifications for the target session", async () => {
const electronDir = path.resolve(__dirname, "..");
const option = (spec, flag) => spec.options.find(({ name }) =>
(Array.isArray(name) ? name : [name]).includes(flag));
const [linuxDate, macDate, linuxBase64, macBase64, linuxReadlink, macReadlink] = await Promise.all([
loadFigSpec(electronDir, "date", "linux"),
loadFigSpec(electronDir, "date", "macos"),
loadFigSpec(electronDir, "base64", "linux"),
loadFigSpec(electronDir, "base64", "macos"),
loadFigSpec(electronDir, "readlink", "linux"),
loadFigSpec(electronDir, "readlink", "macos"),
]);
assert.ok(option(linuxDate, "--date"));
assert.equal(option(linuxDate, "-j"), undefined);
assert.ok(option(macDate, "-j"));
assert.ok(option(macDate, "-v"));
assert.equal(option(macDate, "-d"), undefined);
assert.equal(option(macDate, "--date"), undefined);
assert.equal(option(macDate, "-r").args.template, "filepaths");
assert.equal(option(linuxBase64, "-i").args, undefined);
assert.equal(option(macBase64, "-i").args.template, "filepaths");
assert.ok(option(macBase64, "-o"));
assert.ok(option(linuxReadlink, "--silent"));
assert.equal(option(macReadlink, "--silent"), undefined);
assert.equal(option(macReadlink, "-f").args, undefined);
assert.equal(macReadlink.args.template, "filepaths");
});
test("rejects excluded and invalid specification names", async () => {
const electronDir = path.resolve(__dirname, "..");
for (const name of ["../date", "/date", "aws/s3", "gcloud", 42]) {
assert.equal(await loadFigSpec(electronDir, name, "macos"), null);
}
});
test("IPC list discovers platform-only specs through renderer hasSpec", async (t) => {
const { electronDir, specDir, macSpecDir } = createSpecFixture(t);
const writeSpec = (dir, name) => fs.writeFileSync(
path.join(dir, `${name}.js`),
`export default { name: ${JSON.stringify(name)}, options: [] };`,
);
writeSpec(specDir, "fixture-root-only");
writeSpec(macSpecDir, "fixture-macos-only");
writeSpec(specDir, "fixture-both");
writeSpec(macSpecDir, "fixture-both");
writeSpec(specDir, "date");
writeSpec(macSpecDir, "date");
writeSpec(specDir, "aws");
writeSpec(macSpecDir, "gcloud");
writeSpec(macSpecDir, "az");
fs.mkdirSync(path.join(specDir, "fixture-directory.js"));
fs.mkdirSync(path.join(macSpecDir, "fixture-macos-directory.js"));
const handlers = createFigHandlers(electronDir);
const list = await handlers.list("macos");
assert.ok(list.includes("fixture-root-only"));
assert.ok(list.includes("fixture-macos-only"));
assert.equal(list.filter((name) => name === "fixture-both").length, 1);
assert.equal(list.filter((name) => name === "date").length, 1);
for (const name of ["aws", "gcloud", "az", "fixture-directory", "fixture-macos-directory"]) {
assert.equal(list.includes(name), false, name);
}
// A platform-only command must never be suggested to another session.
const linuxList = await handlers.list("linux");
assert.ok(linuxList.includes("fixture-root-only"));
assert.ok(linuxList.includes("fixture-both"));
assert.equal(linuxList.includes("fixture-macos-only"), false);
const unspecifiedList = await handlers.list();
assert.equal(unspecifiedList.includes("fixture-macos-only"), false);
const previousWindow = Object.getOwnPropertyDescriptor(globalThis, "window");
t.after(() => {
if (previousWindow) Object.defineProperty(globalThis, "window", previousWindow);
else delete globalThis.window;
});
Object.defineProperty(globalThis, "window", {
configurable: true,
value: { netcatty: { listFigSpecs: handlers.list, loadFigSpec: handlers.load } },
});
const rendererModule = path.resolve(__dirname, "../../components/terminal/autocomplete/figSpecLoader.ts");
const { hasSpec, loadSpec } = await import(pathToFileURL(rendererModule).href);
assert.equal(await hasSpec("fixture-macos-only", "macos"), true);
assert.equal(await hasSpec("fixture-macos-only", "linux"), false);
assert.equal(await hasSpec("fixture-root-only", "linux"), true);
assert.equal(await loadSpec("fixture-macos-only", "linux"), null);
assert.equal((await loadSpec("fixture-macos-only", "macos"))?.name, "fixture-macos-only");
// Loading for macOS must not make the command available to Linux.
assert.equal(await hasSpec("fixture-macos-only", "linux"), false);
});
test("spec listing keeps symlinked files but ignores directories and dangling links", async (t) => {
const { electronDir, specDir, macSpecDir } = createSpecFixture(t);
fs.writeFileSync(path.join(specDir, "fixture-target.js"), 'export default {name: "fixture-target"};');
fs.mkdirSync(path.join(specDir, "fixture-directory"));
try {
fs.symlinkSync(path.join(specDir, "fixture-target.js"), path.join(macSpecDir, "fixture-link.js"), "file");
fs.symlinkSync(path.join(specDir, "fixture-directory"), path.join(macSpecDir, "fixture-dir-link.js"), "dir");
fs.symlinkSync(path.join(specDir, "not-present.js"), path.join(macSpecDir, "fixture-dangling.js"), "file");
} catch (error) {
if (["EPERM", "EACCES", "ENOSYS"].includes(error.code)) return t.skip("symbolic links are unavailable");
throw error;
}
const names = await createFigHandlers(electronDir).list("macos");
assert.ok(names.includes("fixture-link"));
assert.equal(names.includes("fixture-dir-link"), false);
assert.equal(names.includes("fixture-dangling"), false);
});
test("each local specification directory can fail independently", async (t) => {
const { electronDir, specDir, macSpecDir } = createSpecFixture(t);
fs.writeFileSync(path.join(specDir, "fixture-root-only.js"), 'export default {name: "fixture-root-only"};');
const handlers = createFigHandlers(electronDir);
fs.rmSync(macSpecDir, { recursive: true });
assert.ok((await handlers.list("macos")).includes("fixture-root-only"));
fs.mkdirSync(macSpecDir);
fs.writeFileSync(path.join(macSpecDir, "fixture-macos-only.js"), 'export default {name: "fixture-macos-only"};');
const originalReaddir = fs.readdirSync;
t.mock.method(fs, "readdirSync", (dir, ...args) => {
if (dir === specDir) {
const error = new Error("fixture root is unreadable");
error.code = "EACCES";
throw error;
}
return originalReaddir(dir, ...args);
});
const list = await handlers.list("macos");
assert.ok(list.includes("fixture-macos-only"));
assert.equal(list.includes("fixture-root-only"), false);
});
test("local git spec restores the missing blame description", async () => {
const electronDir = path.resolve(__dirname, "..");
const spec = await loadFigSpec(electronDir, "git", "linux");
const blame = spec.subcommands.find((subcommand) => subcommand.name === "blame");
assert.equal(
blame.description,
"Show what revision and author last modified each line of a file",
);
assert.ok(blame.options.length > 0);
});
test("missing specs return null while broken spec modules stay visible", async (t) => {
const { electronDir, specDir } = createSpecFixture(t);
fs.writeFileSync(path.join(specDir, "missing-import.js"), 'export { default } from "./absent-dependency.js";');
fs.writeFileSync(path.join(specDir, "syntax-error.js"), "export default {");
assert.equal(await loadFigSpec(electronDir, "not-present", "linux"), null);
assert.equal(await loadFigSpec(electronDir, "not-present", "macos"), null);
await assert.rejects(loadFigSpec(electronDir, "missing-import", "linux"), { code: "ERR_MODULE_NOT_FOUND" });
await assert.rejects(loadFigSpec(electronDir, "syntax-error", "linux"), SyntaxError);
const handlers = createFigHandlers(electronDir);
const warn = t.mock.method(console, "warn", () => {});
assert.equal(await handlers.load("not-present", "linux"), null);
assert.equal(warn.mock.calls.length, 0);
// The bridge resolves broken modules to null so invoke never rejects.
assert.equal(await handlers.load("missing-import", "linux"), null);
assert.equal(await handlers.load("syntax-error", "linux"), null);
assert.equal(warn.mock.calls.length, 2);
});
+122
View File
@@ -0,0 +1,122 @@
const test = require("node:test");
const assert = require("node:assert/strict");
const path = require("node:path");
const { pathToFileURL } = require("node:url");
const { loadFigSpec } = require("../main/registerBridges.cjs");
const repoRoot = path.resolve(__dirname, "../..");
const specNames = ["base64", "date", "readlink"];
Object.defineProperty(globalThis, "localStorage", {
value: { getItem: () => null, setItem: () => {}, removeItem: () => {}, clear: () => {} },
configurable: true,
});
Object.defineProperty(globalThis, "window", {
value: {
netcatty: {
listFigSpecs: async () => specNames,
loadFigSpec: async (name, hostOs) => loadFigSpec(path.join(repoRoot, "electron"), name, hostOs),
listAutocompleteLocalDir: async (_dir, foldersOnly, prefix = "") => ({
success: true,
entries: [
{ name: "sample.txt", type: "file" },
{ name: "2024-report.txt", type: "file" },
].filter((entry) => !foldersOnly && entry.name.startsWith(prefix)),
}),
listAutocompleteRemoteDir: async (_sessionId, _dir, foldersOnly, prefix = "") => ({
success: true,
entries: [
{ name: "sample.txt", type: "file" },
{ name: "2024-report.txt", type: "file" },
].filter((entry) => !foldersOnly && entry.name.startsWith(prefix)),
}),
},
},
configurable: true,
});
const enginePromise = import(pathToFileURL(
path.join(repoRoot, "components/terminal/autocomplete/completionEngine.ts"),
).href);
const completionOptions = {
os: "linux",
protocol: "local",
cwd: "/repo",
maxResults: 100,
pathBudgetMs: Infinity,
};
test("GNU readlink offers supported quiet and verbose options with their real meanings", async () => {
const { getCompletions } = await enginePromise;
const options = await getCompletions("readlink -", completionOptions);
for (const name of ["-q", "--quiet", "-s", "--silent"]) {
const option = options.find((item) => item.source === "option" && item.displayText === name);
assert.equal(option?.text, `readlink ${name}`);
assert.equal(option?.description, "Suppress most error messages");
}
for (const name of ["-v", "--verbose"]) {
const option = options.find((item) => item.source === "option" && item.displayText === name);
assert.equal(option?.text, `readlink ${name}`);
assert.equal(option?.description, "Report error messages");
}
assert.equal(options.some((item) => item.displayText === "--strip"), false);
const silent = await getCompletions("readlink --s", completionOptions);
assert.equal(silent.some((item) => item.text === "readlink --silent"), true);
assert.equal(silent.some((item) => item.text === "readlink --strip"), false);
});
test("GNU base64 and date file arguments complete plain relative paths", async () => {
const { getCompletions } = await enginePromise;
for (const input of [
"base64 sam",
"base64 -d sam",
"date -f sam",
"date --file sam",
"date -r sam",
"date --reference sam",
]) {
const options = await getCompletions(input, completionOptions);
assert.ok(
options.some((item) => item.source === "path" && item.text === input.replace(/sam$/, "sample.txt")),
`expected a file path suggestion for ${input}`,
);
}
const dateString = await getCompletions("date --date sam", completionOptions);
assert.equal(dateString.some((item) => item.source === "path"), false);
});
test("real loader keeps Linux and macOS completions isolated in one renderer", async () => {
const { getCompletions } = await enginePromise;
const linux = await getCompletions("date -", completionOptions);
const macosOptions = { ...completionOptions, os: "macos" };
const macos = await getCompletions("date -", macosOptions);
assert.ok(linux.some((item) => item.text === "date --date"));
assert.ok(macos.some((item) => item.text === "date -j"));
assert.equal(macos.some((item) => item.text === "date --date" || item.text === "date -d"), false);
const macBase64 = await getCompletions("base64 -i sam", macosOptions);
assert.ok(macBase64.some((item) => item.source === "path" && item.text === "base64 -i sample.txt"));
const macInputFormat = await getCompletions("date -f sam", macosOptions);
assert.equal(macInputFormat.some((item) => item.source === "path"), false);
const macReference = await getCompletions("date -r sam", macosOptions);
assert.ok(macReference.some((item) => item.source === "path" && item.text === "date -r sample.txt"));
const macNumericPrefix = await getCompletions("date -r 2024", macosOptions);
assert.ok(macNumericPrefix.some((item) => item.source === "path" && item.text === "date -r 2024-report.txt"));
const macReadlink = await getCompletions("readlink -", macosOptions);
assert.ok(macReadlink.some((item) => item.text === "readlink -f"));
assert.equal(macReadlink.some((item) => item.text === "readlink --silent"), false);
for (const [input, os] of [["base64 -i sam", "macos"], ["date --reference sam", "linux"]]) {
const remote = await getCompletions(input, {
...completionOptions,
os,
protocol: "ssh",
sessionId: `${os}-fixture`,
cwd: "/remote",
});
assert.ok(remote.some((item) => item.source === "path" && item.text === input.replace(/sam$/, "sample.txt")));
}
});
+83 -51
View File
@@ -19,6 +19,85 @@ function filterExcludedFigSpecs(specNames) {
return specNames.filter((name) => !isExcludedFigSpec(name));
}
// The bundled specs for these commands describe the native BSD tools. Their
// root-level local overrides describe GNU tools, so they must not replace the
// bundled versions in macOS sessions.
const macBundledFigSpecs = new Set(["base64", "date"]);
async function loadFigSpec(electronDir, commandName, hostOs) {
// The renderer supplies command names; never allow them to escape the specs
// directory or resolve to excluded packages.
if (typeof commandName !== "string" || !commandName || commandName.startsWith("/") ||
commandName.startsWith("\\") || commandName.includes("..") ||
!/^[@a-zA-Z0-9._/+-]+$/.test(commandName) || isExcludedFigSpec(commandName)) return null;
const fs = require("fs");
const path = require("path");
const { pathToFileURL } = require("url");
const specDir = path.join(electronDir, "specs");
const platformSpec = hostOs === "macos" ? path.join(specDir, "macos", `${commandName}.js`) : null;
const localSpec = path.join(specDir, `${commandName}.js`);
const bundledSpec = path.join(electronDir, "..", "node_modules", "@withfig", "autocomplete", "build", `${commandName}.js`);
const specFile = platformSpec && fs.existsSync(platformSpec)
? platformSpec
: !(hostOs === "macos" && macBundledFigSpecs.has(commandName)) && fs.existsSync(localSpec)
? localSpec
: bundledSpec;
if (!fs.existsSync(specFile)) return null;
const mod = await import(pathToFileURL(specFile).href);
const spec = mod.default?.default ?? mod.default ?? null;
// IPC requires serializable data — JSON round-trip strips functions/symbols.
return spec ? JSON.parse(JSON.stringify(spec)) : null;
}
async function listFigSpecs(electronDir, hostOs) {
const fs = require("fs");
const path = require("path");
const mod = await import("@withfig/autocomplete");
const figSpecs = mod.default || [];
const specDir = path.join(electronDir, "specs");
const localNames = [];
// A macOS-only command must not appear in another session's command list:
// it would be suggested, then always load as null.
const dirs = hostOs === "macos" ? [specDir, path.join(specDir, "macos")] : [specDir];
// Every directory is optional and must be read independently.
for (const dir of dirs) {
try {
for (const entry of fs.readdirSync(dir, { withFileTypes: true })) {
if (!entry.name.endsWith(".js")) continue;
let isFile = entry.isFile();
if (entry.isSymbolicLink()) {
try { isFile = fs.statSync(path.join(dir, entry.name)).isFile(); } catch { /* dangling or inaccessible */ }
}
if (isFile) localNames.push(entry.name.slice(0, -3));
}
} catch { /* optional specs directory is unavailable */ }
}
return filterExcludedFigSpecs([...new Set([...figSpecs, ...localNames])]);
}
function registerFigSpecHandlers(ipcMain, electronDir) {
ipcMain.handle("netcatty:figspec:list", async (_event, hostOs) => {
try {
return await listFigSpecs(electronDir, hostOs);
} catch (err) {
console.warn("[Main] Failed to load fig spec list:", err?.message || err);
return [];
}
});
ipcMain.handle("netcatty:figspec:load", async (_event, commandName, hostOs) => {
try {
return await loadFigSpec(electronDir, commandName, hostOs);
} catch (err) {
// A broken spec module must not reject the renderer's invoke; completion
// degrades to "no suggestions" while the main log keeps the cause.
console.warn("[Main] Failed to load fig spec:", commandName, err?.message);
return null;
}
});
}
function waitForApplicationSpawn(child, requireCleanLauncherExit = false) {
return new Promise((resolve, reject) => {
const onSpawn = () => {
@@ -634,57 +713,8 @@ function createBridgeRegistrar(context) {
}
});
// Fig autocomplete spec loader — uses dynamic import() since @withfig/autocomplete is ESM
ipcMain.handle("netcatty:figspec:list", async () => {
try {
const fs = require("fs");
const mod = await import("@withfig/autocomplete");
const figSpecs = mod.default || [];
// Merge local specs (covers commands missing from @withfig/autocomplete)
const localSpecDir = path.join(electronDir, "specs");
let localNames = [];
try {
localNames = fs.readdirSync(localSpecDir)
.filter(f => f.endsWith(".js"))
.map(f => f.slice(0, -3));
} catch { /* no local specs dir */ }
const merged = filterExcludedFigSpecs([...new Set([...figSpecs, ...localNames])]);
return merged;
} catch (err) {
console.warn("[Main] Failed to load fig spec list:", err?.message || err);
return [];
}
});
ipcMain.handle("netcatty:figspec:load", async (_event, commandName) => {
try {
// Sanitize: reject absolute paths, path traversal, and non-spec characters
if (!commandName || commandName.startsWith("/") || commandName.startsWith("\\") ||
commandName.includes("..") || !/^[@a-zA-Z0-9._/+-]+$/.test(commandName)) return null;
if (isExcludedFigSpec(commandName)) return null;
const { pathToFileURL } = require("url");
const fs = require("fs");
// Try local specs first (covers commands missing from @withfig/autocomplete)
const localSpec = path.join(electronDir, "specs", `${commandName}.js`);
if (fs.existsSync(localSpec)) {
const mod = await import(pathToFileURL(localSpec).href);
const spec = mod.default?.default ?? mod.default ?? null;
return spec ? JSON.parse(JSON.stringify(spec)) : null;
}
// Fall back to @withfig/autocomplete
// Can't use `import("@withfig/autocomplete/build/...")` because the package's
// "exports" field restricts allowed import paths. Use file URL to bypass.
const specFile = path.join(electronDir, "..", "node_modules", "@withfig", "autocomplete", "build", `${commandName}.js`);
const mod = await import(pathToFileURL(specFile).href);
const spec = mod.default?.default ?? mod.default ?? null;
// IPC requires serializable data — JSON round-trip strips functions/symbols
return spec ? JSON.parse(JSON.stringify(spec)) : null;
} catch (err) {
console.warn("[Main] Failed to load fig spec:", commandName, err?.message);
return null;
}
});
// Fig specifications are shared by every terminal session.
registerFigSpecHandlers(ipcMain, electronDir);
// Local directory listing for autocomplete (local terminal sessions)
ipcMain.handle("netcatty:local:listdir", async (_event, payload) => {
@@ -1354,5 +1384,7 @@ module.exports = {
createBridgeRegistrar,
filterExcludedFigSpecs,
isExcludedFigSpec,
loadFigSpec,
registerFigSpecHandlers,
_waitForApplicationSpawnForTests: waitForApplicationSpawn,
};
+2 -2
View File
@@ -945,8 +945,8 @@ const api = createPreloadApi({
// Fig autocomplete spec loading via main process
const figSpecApi = {
listFigSpecs: () => ipcRenderer.invoke("netcatty:figspec:list"),
loadFigSpec: (commandName) => ipcRenderer.invoke("netcatty:figspec:load", commandName),
listFigSpecs: (hostOs) => ipcRenderer.invoke("netcatty:figspec:list", hostOs),
loadFigSpec: (commandName, hostOs) => ipcRenderer.invoke("netcatty:figspec:load", commandName, hostOs),
listAutocompleteRemoteDir: (sessionId, dirPath, foldersOnly, filterPrefix, limit) => ipcRenderer.invoke("netcatty:ssh:listdir", {
sessionId,
path: dirPath,
+3 -3
View File
@@ -12,19 +12,19 @@ const completionSpec = {
{ name: "-f", description: "Read AWK program from file", args: { name: "progfile", template: "filepaths" } },
{ name: "-o", description: "Enable pretty-printed output", args: { name: "file", isOptional: true, template: "filepaths" } },
{ name: "-b", description: "Treat all input data as single-byte characters (gawk)" },
{ name: "-c", description: "Run in POSIX compatibility mode (gawk)" },
{ name: "-c", description: "Run in traditional compatibility mode (gawk)" },
{ name: "-C", description: "Print copyright information" },
{ name: "-d", description: "Dump variables to file (gawk)", args: { name: "file", isOptional: true, template: "filepaths" } },
{ name: "-e", description: "Specify AWK program text", args: { name: "program" } },
{ name: "-E", description: "Read AWK program from file (like -f but disables command-line variable assignments)", args: { name: "file", template: "filepaths" } },
{ name: "-i", description: "Include AWK source library", args: { name: "source-file", template: "filepaths" } },
{ name: "-l", description: "Load dynamic extension (gawk)", args: { name: "ext" } },
{ name: "-n", description: "Disable automatic input record splitting (gawk)" },
{ name: "-n", description: "Recognize octal and hexadecimal values in input data (gawk)" },
{ name: "-N", description: "Use locale decimal point for parsing input data (gawk)" },
{ name: "-p", description: "Profile execution and write to file (gawk)", args: { name: "file", isOptional: true, template: "filepaths" } },
{ name: "-P", description: "POSIX compatibility mode (gawk)" },
{ name: "-S", description: "Sandbox mode — disable system(), I/O redirection (gawk)" },
{ name: "-t", description: "Enable type checking (gawk)" },
{ name: "-t", description: "Warn about constructs not portable to the original Unix awk (gawk)" },
{ name: "--help", description: "Show help" },
{ name: "--version", description: "Print version information" },
],
+24
View File
@@ -0,0 +1,24 @@
// base64 spec - GNU coreutils. The bundled Fig spec follows BSD flags
// (-b line length, -i input file, -o output file); GNU uses -w, -i for
// ignoring invalid bytes while decoding, and positional files.
const completionSpec = {
name: "base64",
description: "Encode and decode using Base64 representation",
options: [
{ name: ["-d", "--decode"], description: "Decode input instead of encoding it" },
{
name: ["-i", "--ignore-garbage"],
description: "When decoding, ignore non-alphabet characters",
},
{
name: ["-w", "--wrap"],
description: "Wrap encoded lines after the given number of characters (0 disables wrapping)",
args: { name: "cols", description: "Characters per line; 0 disables wrapping" },
},
{ name: "--help", description: "Display help text" },
{ name: "--version", description: "Display version information" },
],
args: { name: "file", description: "File to read; standard input when omitted or '-'", isOptional: true, isVariadic: true, template: "filepaths" },
};
export default completionSpec;
+62
View File
@@ -0,0 +1,62 @@
// date spec - GNU coreutils date (Linux hosts). The bundled Fig spec follows
// BSD/macOS flags (-j, -n, -t, -v) that GNU date does not have, so this local
// spec describes the GNU option set instead. Local specs win over the bundled
// package at runtime and in the translation audit.
const completionSpec = {
name: "date",
description: "Display or set date and time",
options: [
{
name: ["-d", "--date"],
description: "Display the date and time described by the given string instead of the current time",
args: { name: "string", description: "Date string, for example '2024-01-01 12:00:00' or 'next friday'" },
},
{
name: "--debug",
description: "Annotate the parsed date and warn about questionable usage on standard error",
},
{
name: ["-f", "--file"],
description: "Parse each line of the given file like --date",
args: { name: "datefile", description: "File with one date string per line", template: "filepaths" },
},
{
name: ["-I", "--iso-8601"],
netcattyOptionalArgAttached: true,
description: "Output an ISO 8601 date/time string; the optional format is date, hours, minutes, seconds or ns",
args: { name: "format", isOptional: true, suggestions: ["date", "hours", "minutes", "seconds", "ns"] },
},
{
name: ["-R", "--rfc-email"],
description: "Output an RFC 5322 email-style date and time string",
},
{
name: "--rfc-3339",
description: "Output an RFC 3339 date/time string in the given format",
args: { name: "format", suggestions: ["date", "seconds", "ns"] },
},
{
name: ["-r", "--reference"],
description: "Display the last modification time of the given file",
args: { name: "file", description: "File whose modification time is displayed", template: "filepaths" },
},
{
name: ["-s", "--set"],
description: "Set the system time from the given string",
args: { name: "string", description: "Date string to set the system clock to" },
},
{
name: ["-u", "--utc", "--universal"],
description: "Display or set the date in UTC (Coordinated Universal) time",
},
{ name: "--help", description: "Display help text" },
{ name: "--version", description: "Display version information" },
],
args: {
name: "+FORMAT",
description: "Output format beginning with '+', using strftime escapes such as +%Y-%m-%d",
isOptional: true,
},
};
export default completionSpec;
+37
View File
@@ -0,0 +1,37 @@
// dig spec. The bundled spec labels the NS shortcut as "Query MX Record" and
// offers "TTL" as a record type, but TTL is a record field. The English keys
// for A/MX/CNAME/TXT/SOA, ANY and the section filter stay byte-identical to
// the bundled spec because dog shares them; the ANY and filter caveats live in
// the zh-CN values instead of new English keys.
const shortOption = {
name: ["+short", ""],
insertValue: "+short {cursor}",
description: "Only print meaningful results",
args: {},
};
const record = (name, description) => ({
name,
description,
options: [shortOption],
});
const completionSpec = {
name: "dig",
description: "Domain Information Groper",
subcommands: [
record("A", "Query Domain A Record"),
record("MX", "Query Domain MX Record"),
record("CNAME", "Query Domain CNAME Record"),
record("TXT", "Query Domain TXT Record"),
record("NS", "Query NS records (authoritative name servers)"),
record("SOA", "Query SOA Record"),
{ name: "ANY +noall +answer", description: "Query ALL DNS Records" },
{
name: "+nocomments +noquestion +noauthority +noadditional +nostats",
description: "Query only answer section",
},
],
};
export default completionSpec;
+19
View File
@@ -0,0 +1,19 @@
// git spec override.
//
// The bundled @withfig/autocomplete build leaves git blame without a
// description — it is the only git subcommand in the build that has none — so
// the completion popup shows a blank row for it. Patch the bundled spec here
// (instead of copying 1,500 descriptions) so the zh-CN/zh-TW overlay can
// translate the description like every other subcommand.
import { createRequire } from "node:module";
const require = createRequire(import.meta.url);
const bundled = require("../../node_modules/@withfig/autocomplete/build/git.js");
const completionSpec = bundled.default?.default ?? bundled.default;
const blame = completionSpec.subcommands?.find((subcommand) => subcommand.name === "blame");
if (blame && !blame.description) {
blame.description = "Show what revision and author last modified each line of a file";
}
export default completionSpec;
+37
View File
@@ -0,0 +1,37 @@
// htop spec. The bundled Fig spec gives the -H delay the wrong unit ("tenths
// of sec"). htop 3.2.2 parses it as highlightDelaySecs and compares it as
// 1000 * highlightDelaySecs, so the value is seconds. Every other description
// and argument matches the bundled spec.
const completionSpec = {
name: "htop",
description: "Improved top (interactive process viewer)",
options: [
{ name: ["--help", "-h"], description: "Show help for htop" },
{ name: ["--no-color", "-C"], description: "Use a monochrome color scheme" },
{
name: ["--delay", "-d"],
description: "Delay between updates, in tenths of sec",
args: { name: "delay", suggestions: ["10", "1", "60"] },
},
{ name: ["--filter", "-F"], description: "Filter commands", args: { name: "filter" } },
{
name: ["--highlight-changes", "-H"],
description: "Highlight new and old processes",
args: {
name: "delay",
description: "Highlight duration in seconds",
suggestions: ["10", "1", "60"],
isOptional: true,
},
},
{ name: ["--no-mouse", "-M"], description: "Disable the mouse" },
{ name: ["--pid", "-p"], description: "Show only the given PIDs", args: { name: "PID", isVariadic: true } },
{ name: ["--sort-key", "-s"], description: "Sort by COLUMN in list view", args: { name: "column" } },
{ name: ["--tree", "-t"], description: "Show the tree view" },
{ name: ["--user", "-u"], description: "Show only processes for a given user (or $USER)", args: { name: "user", isOptional: true, suggestions: ["$USER"] } },
{ name: ["--no-unicode", "-U"], description: "Do not use unicode but plain ASCII" },
{ name: ["--version", "-V"], description: "Print version info" },
],
};
export default completionSpec;
+161
View File
@@ -0,0 +1,161 @@
// ip spec — iproute2 networking configuration.
//
// @withfig/autocomplete has no ip/netstat/ss specs, so the completion popup
// has no subcommand or option data for them. This local spec covers the
// common iproute2 objects and actions; descriptions are translated by the
// zh-CN/zh-TW autocomplete overlay like every other spec.
const action = (name, description) => ({ name, description });
const addressActions = [
action("show", "Display addresses"),
action("add", "Add a new address"),
action("del", "Delete an address"),
action("change", "Change an address"),
action("replace", "Add a new address or change an existing one"),
action("flush", "Flush addresses"),
action("save", "Save address configuration"),
action("restore", "Restore address configuration"),
];
const linkActions = [
action("show", "Display network devices"),
action("add", "Add a new network device"),
action("del", "Delete a network device"),
action("set", "Change device attributes"),
action("change", "Change device attributes"),
action("replace", "Add a new device or change an existing one"),
action("up", "Enable a network device"),
action("down", "Disable a network device"),
action("save", "Save device configuration"),
action("restore", "Restore device configuration"),
];
const routeActions = [
action("show", "Display routes"),
action("add", "Add a new route"),
action("del", "Delete a route"),
action("change", "Change a route"),
action("replace", "Add a new route or change an existing one"),
action("append", "Append a new route"),
action("prepend", "Prepend a new route"),
action("flush", "Flush routes"),
action("get", "Get a single route"),
];
const neighborActions = [
action("show", "Display neighbor entries"),
action("add", "Add a new neighbor entry"),
action("del", "Delete a neighbor entry"),
action("change", "Change a neighbor entry"),
action("replace", "Add a new entry or change an existing one"),
action("flush", "Flush neighbor entries"),
];
const ruleActions = [
action("show", "Display routing policy rules"),
action("add", "Add a new rule"),
action("del", "Delete a rule"),
action("flush", "Flush rules"),
];
const tunnelActions = [
action("show", "Display tunnels"),
action("add", "Add a new tunnel"),
action("del", "Delete a tunnel"),
action("change", "Change a tunnel"),
action("replace", "Add a new tunnel or change an existing one"),
action("flush", "Flush tunnels"),
];
const netnsActions = [
action("list", "List network namespaces"),
action("add", "Add a new network namespace"),
action("del", "Delete a network namespace"),
action("identify", "Identify a network namespace"),
action("pids", "List processes in a network namespace"),
action("exec", "Run a command in a network namespace"),
action("monitor", "Monitor network namespace changes"),
];
const maddressActions = [
action("show", "Display multicast addresses"),
action("add", "Add a multicast address"),
action("del", "Delete a multicast address"),
action("flush", "Flush multicast addresses"),
];
const mrouteActions = [
action("show", "Display multicast routes"),
action("add", "Add a multicast route"),
action("del", "Delete a multicast route"),
action("flush", "Flush multicast routes"),
];
const completionSpec = {
name: "ip",
description: "Show / manipulate routing, network devices, interfaces and tunnels",
options: [
{ name: ["-V", "-Version"], description: "Print the version and exit" },
{ name: ["-h", "-human"], description: "Output statistics with human-readable values" },
{ name: ["-s", "-stats", "-statistics"], description: "Output more information" },
{ name: ["-d", "-details"], description: "Output more detailed information" },
{ name: ["-r", "-resolve"], description: "Resolve host names" },
{ name: ["-4"], description: "Use IPv4" },
{ name: ["-6"], description: "Use IPv6" },
{ name: ["-br", "-brief"], description: "Print human-readable output" },
{ name: ["-j", "-json"], description: "Output JSON" },
{ name: ["-p", "-pretty"], description: "Pretty-print JSON output" },
{ name: ["-c", "-color"], description: "Use color output" },
{ name: ["-o", "-oneline"], description: "Output each record on a single line" },
{
name: ["-n", "-netns"],
description: "Switch to a network namespace",
args: { name: "NETNS" },
},
{
name: ["-N", "-Numeric"],
description: "Print the raw priority, protocol and scope values",
},
{
name: ["-f", "-family"],
description: "Specify the protocol family",
args: { name: "FAMILY", suggestions: ["inet", "inet6", "bridge", "link", "mpls"] },
},
],
subcommands: [
{ name: ["address", "a", "addr"], description: "Manage addresses", subcommands: addressActions },
{ name: ["link", "l"], description: "Manage network devices", subcommands: linkActions },
{ name: ["route", "r", "ro"], description: "Manage the routing table", subcommands: routeActions },
{
name: ["neighbor", "n", "neigh"],
description: "Manage the neighbor table",
subcommands: neighborActions,
},
{ name: ["rule", "ru"], description: "Manage routing policy rules", subcommands: ruleActions },
{ name: ["tunnel", "tun"], description: "Manage tunnels", subcommands: tunnelActions },
{ name: ["netns"], description: "Manage network namespaces", subcommands: netnsActions },
{
name: ["maddress", "maddr"],
description: "Manage multicast addresses",
subcommands: maddressActions,
},
{
name: ["mroute", "mr"],
description: "Manage the multicast routing table",
subcommands: mrouteActions,
},
{
name: ["xfrm"],
description: "Manage IPsec policies and states",
subcommands: [
action("state", "Manage IPsec states"),
action("policy", "Manage IPsec policies"),
action("monitor", "Monitor IPsec events"),
],
},
{ name: ["monitor"], description: "Watch for netlink messages" },
{ name: ["help"], description: "Show help" },
],
};
export default completionSpec;
+49
View File
@@ -0,0 +1,49 @@
// macOS date uses BSD options. In current macOS releases, the old -d/-t
// timezone switches are no longer available; time zones are handled by tzdata.
const completionSpec = {
name: "date",
description: "Display or set date and time",
options: [
{
name: "-f",
description: "Use specified format for input instead of the default [[[mm]dd]HH]MM[[cc]yy][.ss] format",
args: [
{ name: "input_fmt", description: "The format with which to parse the new date value" },
{ name: "new_date", description: "The new date to set" },
],
},
{
name: "-I",
netcattyOptionalArgAttached: true,
description: "Output an ISO 8601 date/time string; the optional format is date, hours, minutes, seconds or ns",
args: { name: "format", isOptional: true, suggestions: ["date", "hours", "minutes", "seconds", "ns"] },
},
{ name: "-j", description: "Don't try to set the date" },
{ name: "-n", description: "Obsolete option, accepted and ignored for compatibility" },
{ name: "-R", description: "Use RFC 2822 date and time output format" },
{
name: "-r",
description: "Display a file's modification time or a time expressed in seconds since the Epoch",
// Keep path completion for numeric prefixes: filenames can start with digits.
args: { name: "file or seconds", template: "filepaths" },
},
{ name: "-u", description: "Display or set the date in UTC (Coordinated Universal) time" },
{
name: "-z",
description: "Display the time in the specified output time zone",
args: { name: "output_zone" },
},
{
name: "-v",
description: "Adjust and print (but don't set) the second, minute, hour, month day, week day, month, or year according to val",
args: { name: "val", description: "[+|-]val[ymwdHMS]" },
},
],
args: {
name: "new_time OR output_fmt",
description: "New_time: [[[mm]dd]HH]MM[[cc]yy][.ss], output_fmt: '+' followed by user-defined format string",
isOptional: true,
},
};
export default completionSpec;
+15
View File
@@ -0,0 +1,15 @@
// macOS readlink follows BSD options, not GNU's -e/-m/-s/-v flags.
const completionSpec = {
name: "readlink",
description: "Print resolved symbolic links or canonical file names",
options: [
{
name: "-f",
description: "Resolve symbolic links and print the canonical path only if all components exist",
},
{ name: "-n", description: "Do not print a trailing newline" },
],
args: { name: "file", description: "Symbolic link or path to resolve", isVariadic: true, template: "filepaths" },
};
export default completionSpec;
+29
View File
@@ -0,0 +1,29 @@
// readlink spec - GNU coreutils. The bundled Fig spec reuses stat wording for
// the command root and -f, so this local spec describes the real GNU options.
const completionSpec = {
name: "readlink",
description: "Print resolved symbolic links or canonical file names",
options: [
{
name: ["-f", "--canonicalize"],
description: "Resolve every symbolic link in the given path and print the canonical path (all but the last component must exist)",
},
{
name: ["-e", "--canonicalize-existing"],
description: "Resolve symbolic links and print the canonical path only if all components exist",
},
{
name: ["-m", "--canonicalize-missing"],
description: "Resolve symbolic links and print the canonical path even if components are missing",
},
{ name: ["-n", "--no-newline"], description: "Do not print a trailing newline" },
{ name: ["-q", "--quiet", "-s", "--silent"], description: "Suppress most error messages" },
{ name: ["-v", "--verbose"], description: "Report error messages" },
{ name: ["-z", "--zero"], description: "End each output path with NUL instead of a newline" },
{ name: "--help", description: "Display help text" },
{ name: "--version", description: "Display version information" },
],
args: { name: "file", description: "Symbolic link or path to resolve", isVariadic: true },
};
export default completionSpec;
@@ -39,6 +39,63 @@ function printfTokens(text) {
// Private-use mark so s2twp cannot rewrite 进程 before it becomes 行程.
const PROCESS_MARK = "\u{E000}";
// s2twp picks the wrong Taiwan term where the zh-CN phrase is ambiguous at a
// word boundary or where OpenCC only has a mainland form. Each entry is a
// literal post-conversion fix, applied after the 进程 placeholder is restored.
const TAIWAN_PHRASE_FIXES = [
["擴充套件正規表示式", "擴充正規表示式"],
["擴充套件 E3", "擴充 E3"],
["欄位連線", "欄位聯結"],
["二進位制資料", "二進位資料"],
["后綴", "字尾"],
["執行檔例項", "執行檔"],
["屏幕", "螢幕"],
["文本", "文字"],
// Number bases and generic “extended” wording; Taiwan drops 制 and 套件.
["進位制", "進位"],
["擴充套件", "擴充"],
// “instance” in the cloud-resource sense.
["例項", "執行個體"],
// Side effects of the generic 擴充套件→擴充 rule.
["擴充頭", "擴充標頭"],
["ALPN TLS 擴充", "ALPN TLS 擴充功能"],
["NPN TLS 擴充", "NPN TLS 擴充功能"],
["數據", "資料"],
// “extension” as a noun keeps 功能; the generic rule above only covers the
// adjective “extended” (擴充屬性, 擴充正規表示式, 擴充標頭).
["Apple 的擴充", "Apple 的擴充功能"],
["(Apple 擴充)", "(Apple 擴充功能)"],
];
/**
* OpenCC s2twp resolves a few ambiguous simplified characters to the wrong
* Traditional form in command descriptions. Each pattern below is limited to
* the sense these descriptions use; the committed-dictionary test asserts the
* bad forms never reach descriptions.zh-TW.json.
*/
const POST_CONVERSION_CORRECTIONS = [
// 隻 is a measure word (一隻鳥); these descriptions mean "only" (只).
[/隻/g, "只"],
// 髮 means hair; the source is 发送 (send).
[/髮/g, "發"],
// 錶 means a wristwatch; the source is 表现 (behave/appear).
[/錶/g, "表"],
// 复用 (reuse) is 復用; 複 stays for 複雜 and 複製.
[/複用/g, "復用"],
// "and/also" is 並為; 合併為 (merged into) keeps 併.
[/(?<!合)併為/g, "並為"],
// 后 is a queen; the source is 后 (after), which is 後 in Traditional.
[/后/g, "後"],
];
function applyPostConversionCorrections(text) {
let corrected = text;
for (const [pattern, replacement] of POST_CONVERSION_CORRECTIONS) {
corrected = corrected.replace(pattern, replacement);
}
return corrected;
}
function toTraditionalTaiwan(text, convert) {
if (text.includes(PROCESS_MARK)) {
throw new Error("description already contains the 进程 placeholder");
@@ -48,7 +105,12 @@ function toTraditionalTaiwan(text, convert) {
if (converted.includes("进程") || (marked.includes(PROCESS_MARK) && !converted.includes(PROCESS_MARK))) {
throw new Error("OpenCC dropped the 进程 placeholder");
}
return converted.replaceAll(PROCESS_MARK, "行程");
let traditional = converted.replaceAll(PROCESS_MARK, "行程");
for (const [from, to] of TAIWAN_PHRASE_FIXES) {
traditional = traditional.replaceAll(from, to);
}
// Phrase fixes run first so 后綴→字尾 is not broken by the 后→後 rule.
return applyPostConversionCorrections(traditional);
}
const source = JSON.parse(fs.readFileSync(sourcePath, "utf8"));
@@ -85,6 +85,29 @@ const COVERED_COMMANDS = [
"ping",
"netstat",
"ss",
// Batch 4: small-gap core utilities and macOS/BSD compat tools.
"echo",
"which",
"pwd",
"clear",
"su",
"crontab",
"env",
"uname",
"base64",
"date",
"id",
"split",
"seq",
"join",
"dig",
"dd",
"htop",
"basename",
"dirname",
"readlink",
"more",
"paste",
];
function collectDescriptions(node, out, seen) {