@kaynooo/cli-check 0.23.1 → 0.24.1
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/README.md +5 -2
- package/dist/{chunk-rcsspcmv.js → chunk-1rrfsren.js} +1 -1
- package/dist/{chunk-8wyt4whk.js → chunk-898e3vv3.js} +2 -2
- package/dist/{chunk-11sws6xz.js → chunk-kbkmjjg6.js} +1 -1
- package/dist/cli.js +3 -3
- package/dist/errs-cli.js +1 -1
- package/dist/j-cli.js +2 -2
- package/package.json +2 -2
package/README.md
CHANGED
|
@@ -40,13 +40,14 @@ A folder with no step of its own but subfolders that have some (a root with `api
|
|
|
40
40
|
In a repo that runs its tools in a container, `check`, `check --fix` and `errs -- <command>` run a step inside the docker compose service that bind-mounts its folder, instead of on the host. The project is the nearest `compose.yaml`, `compose.yml`, `docker-compose.yaml` or `docker-compose.yml` from the step's folder up to the repository root (the folder holding `.git`), with its `compose.override.*` merged in. A service qualifies when one of its bind mounts (`.:/app`, `./api:/var/www/html`, the long `type: bind` syntax, `${VAR:-default}` interpolated with the environment and the project's `.env`) holds the folder, a mount of a parent folder included; named volumes are ignored. The step runs `docker compose exec -T -w <path of the folder in the container> <service> sh -c '<command>'` from the project's folder, with `NO_COLOR=1 FORCE_COLOR=0` set, and the container path is the mount's target plus the folder's path under its source.
|
|
41
41
|
|
|
42
42
|
- The stack is only read: `docker compose ps --services --status running` is asked once per project, and a service that is down is never started. The step fails, naming the service and where its project lives, and the other steps go on; start the stack yourself, or pass `--host`.
|
|
43
|
+
- `make`, `just`, `task` and `mise` run on the host, mount or not: their recipes start the stack and exec into it themselves (`make up`, `make patch`), so only `--in <service>` sends one into a container.
|
|
43
44
|
- Several services mounting the folder (php and a worker): the one whose name, image or build names the step's tool wins (`bun` and `node` look for `bun` or `node`, `composer`, `php`, `phpunit`, `phpstan` and `vendor/bin/*` for `php`). When none or several stand out the call fails listing them and asks for `--in <service>`.
|
|
44
45
|
- `--in <service>` runs in that service, failing when it does not exist or does not mount the folder. `--host` runs on the host. Both together are a usage error.
|
|
45
46
|
- `check --list` has a column saying where each step runs, `host` or the service; `--json` adds `in` with the service name to a step that runs in one (`--list --json` as well).
|
|
46
47
|
- `COMPOSE_FILE` (in the environment or the project's `.env`) replaces the search for `compose.yaml`: the files it names, separated by `:` (`COMPOSE_PATH_SEPARATOR` if set) and read relative to the project folder, are merged in order. A file it names that does not exist fails the call, as `docker compose` would.
|
|
47
48
|
- No `docker` on the PATH (a devcontainer, CI): there is no container to reach, so the step runs on the host and stderr says `host, docker not found` once per project; `--in <service>` fails instead.
|
|
48
49
|
- A compose file that does not parse fails the call naming the file and the parse error, and points at `--host`; it never falls back to the host silently, even without docker.
|
|
49
|
-
- The slot queue (the default when `slot` is installed
|
|
50
|
+
- The slot queue (the default when `slot` is installed; `--slot` warns on stderr and runs unqueued without it, while `--lock` refuses) holds the whole docker command. `--timeout` ends the `docker compose exec` client, which does not always end what it started inside the container.
|
|
50
51
|
- `check --changed` (`-c`) narrows `lint` to the changed source files (staged, unstaged and untracked, against HEAD) when its script is a bare `keslint`, `eslint` or `oxlint`, and `test` to the changed test files and the tests next to changed sources (same folder, `tests/`, `../tests/`) when its script is a bare `bun test`. Every other step runs in full and its line says so, a test step finding no test for the diff included. The typecheck is never narrowed.
|
|
51
52
|
- `check --fix` runs the project's scripts and `php-cs-fixer` in the service, and keeps its own formatters (`justfile`, `go`, `rust`, `python`, `makefile`) on the host. The recursion guard variable is passed into the container.
|
|
52
53
|
|
|
@@ -74,7 +75,7 @@ check --fix --in app # run the scripts in this compose service; --host force
|
|
|
74
75
|
check --fix --json # {fixers, changed}, a skipped fixer as {name, command, skipped}
|
|
75
76
|
```
|
|
76
77
|
|
|
77
|
-
The project's own `fix` script, recipe or target when it has one, else its `lint:fix
|
|
78
|
+
The project's own `fix` script, recipe or target when it has one, else its lint fixer (`lint:fix`, `lint-fix`, `fix:lint`, `eslint:fix`...) and formatter (`fmt`, `format`, `format:fix`, `prettier`, `biome`...), found in the same sources as `check`'s steps; a `package.json` with none of those names takes the scripts running `prettier --write`, `biome check --write` or `eslint --fix`. Then the formatters the folder's files call for:
|
|
78
79
|
|
|
79
80
|
| Fixer | When | Runs |
|
|
80
81
|
| --- | --- | --- |
|
|
@@ -134,4 +135,6 @@ It reads a `justfile`, a `Makefile` (a `## doc` comment above a target or after
|
|
|
134
135
|
|
|
135
136
|
A name several entries share opens the picker on those alone, unless it comes qualified by its runner (`just:check`, `bun:api/test`). A required parameter of a recipe not given after the name is asked for. Without a terminal, `j` lists what can run instead.
|
|
136
137
|
|
|
138
|
+
A script runs in the compose service that bind-mounts its folder, as a `check` step does (see above); a Justfile, Makefile, Taskfile or mise task runs on the host, its recipes being the ones that start the stack and exec into it. `--in <service>` and `--host` override either.
|
|
139
|
+
|
|
137
140
|
Hidden flags for the shell and the tmux integration: `--list` prints the rows term shows as JSON (`label`, `hint`, `typed`, `preview`, `editsTyped`), `--names` the names with a description for the completions (`name<TAB>description`, a qualified form on its own line for a name several runners share), `--show <kind> <dir> <name>` the preview of one, `--record <id> [args...]` notes a run, and `--emit [name] [args...]` prints what tmux_pick reads: `run`, the words typed back, the id to record, then one line per word of the command, `=fixed`, `+given` or `?name` for a parameter to ask.
|
|
@@ -1,5 +1,5 @@
|
|
|
1
1
|
// @bun
|
|
2
|
-
import{paint,role,stripAnsi,formatDuration}from"./chunk-ngcnmctk.js";import{runCommand,privateLogDirectory,sweepLogs,bunCheckFields,failureExcerpt,LOG_PATTERNS}from"./chunk-8wyt4whk.js";import{mkdir,readdir,stat,writeFile}from"fs/promises";import{basename,join}from"path";import process from"process";import{relative}from"path";var E2E_NOISE=[/^(?:Running \d+ tests? using|\(node:\d+\) Warning|\(Use `node|\[\d+\/\d+\] |\s+[-\u2713\u2718\u00B0\u00D7]\s+\d+|To open last HTML|Serving HTML report|\s*npx playwright show-report)/,/^[\u00B7F\u00D7\u00B0T\u00B1]+$/,/^(?: RUN {2}v|\s*[\u276F\u2713\u00D7\u2193] |\s+(?:Test Files|Tests|Start at|Duration|Errors) {2}|\u23AF)/],PLAYWRIGHT_HEADER=/^ {2}\d+\) (?:\[([^\]]+)\] \u203A )?(.+?):(\d+):(\d+) \u203A (.+?) \u2500+$/,PLAYWRIGHT_SUMMARY=/^ {2}\d+ (failed|flaky|passed|skipped|did not run|interrupted)\b/,PLAYWRIGHT_ENTRY=/^ {4}(?:\[([^\]]+)\] \u203A )?(.+?):(\d+):(\d+) \u203A (.+?) \u2500+$/,PLAYWRIGHT_RETRY=/^\s+Retry #\d+ \u2500+$/,FRAME=/^\s+at (?:.*? \()?(.+?):(\d+):(\d+)\)?$/,EXPECTED=/^\s+Expected: (.*)$/,RECEIVED=/^\s+Received: (.*)$/,VITEST_FAIL=/^ FAIL {2}(?:\|[^|]+\| )?(.+)$/,VITEST_SUITE=/^(.+?) \[ .+ \]$/,VITEST_FRAME=/^\s*\u276F (\S+):(\d+):(\d+)$/;function key(project,file,line,column,title){return`${project??""}|${file}:${line}:${column} \u203A ${title}`}function firstFrame(block){return block.map((line)=>FRAME.exec(line)).find((match)=>match!==null&&!match[1]?.includes("node_modules"))??void 0}var collectPlaywright=(lines,used)=>{let flaky=new Set,section="";for(let[index,line]of lines.entries()){let summary=PLAYWRIGHT_SUMMARY.exec(line),entry=PLAYWRIGHT_ENTRY.exec(line);if(summary!==null)section=summary[1]??"",used.add(index);else if(entry!==null&§ion!==""){if(section==="flaky")flaky.add(key(entry[1],entry[2],entry[3],entry[4],entry[5]));used.add(index)}}let errors=[];for(let index=0;index<lines.length;index++){let header=PLAYWRIGHT_HEADER.exec(lines[index]??"");if(header===null)continue;let end=index+1;while(end<lines.length&&!PLAYWRIGHT_HEADER.test(lines[end]??"")&&!PLAYWRIGHT_SUMMARY.test(lines[end]??""))end++;for(let at=index;at<end;at++)used.add(at);let[,project,file,line,column,title]=header,retry=lines.findIndex((text,at)=>at>index&&at<end&&PLAYWRIGHT_RETRY.test(text)),block=lines.slice(index+1,retry===-1?end:retry),frame=firstFrame(block),message=block.find((text)=>text.trim()!=="")?.trim()??"failed",expected=block.map((text)=>EXPECTED.exec(text)?.[1]?.trim()).find((text)=>text!==void 0),received=block.map((text)=>RECEIVED.exec(text)?.[1]?.trim()).find((text)=>text!==void 0),values=expected===void 0||received===void 0?"":` (expected ${expected}, received ${received})`;if(index=end-1,flaky.has(key(project,file,line,column,title)))continue;errors.push({tool:"playwright",file:frame?.[1]??file??"",line:Number(frame?.[2]??line),column:Number(frame?.[3]??column),severity:"error",message:`${message}${values}`,test:`${project===void 0?"":`[${project}] `}${title}`})}return errors},collectVitest=(lines,used)=>{let errors=[];for(let index=0;index<lines.length;index++){let header=VITEST_FAIL.exec(lines[index]??"")?.[1];if(header===void 0)continue;let end=index+1;while(end<lines.length&&!(lines[end]??"").startsWith("\u23AF")&&!VITEST_FAIL.test(lines[end]??""))end++;for(let at=index;at<end;at++)used.add(at);let block=lines.slice(index+1,end),frame=block.map((text)=>VITEST_FRAME.exec(text)).find((match)=>match!==null&&!match[1]?.includes("node_modules")),suite=VITEST_SUITE.exec(header)?.[1],[file="",...names]=(suite??header).split(" > ");errors.push({tool:"vitest",file:frame?.[1]??file,line:Number(frame?.[2]??0),column:Number(frame?.[3]??0),severity:"error",message:block.find((text)=>text.trim()!=="")?.trim()??"failed",...suite===void 0&&names.length>0?{test:names.join(" > ")}:{}}),index=end-1}return errors};var PHP_NOISE=[/^(?:PHPUnit \d|ParaTest v|Runtime: |Configuration: |Processes: |Random Seed: |Time: |Tests: |OK(?:,| \()|FAILURES!|ERRORS!|WARNINGS!|No tests executed|--$)/,/^[.FEWRISD]+\s+\d+ \/ \d+ \(\d+%\)$/,/^ -{3,}(?: -{3,})*\s*$/,/^\s*\d+\/\d+ \[[=>\-\u2593\u2591 ]*\]\s+\d+%/,/^(?:Note: Using configuration file|\s*\[(?:OK|ERROR)\] )/,/^(?:Loaded config|PHP runtime:|PHP CS Fixer \d|Running analysis|Parallel runner|Using cache file|Paths from configuration|Rules from configuration|Setting PHP_CS_FIXER|Unable to determine minimum|If you need help|Found \d+ of \d+ files|Checked all files|Fixed \d+ of \d+ files|Legend:)/];var PHPUNIT_HEADER=/^There (?:was|were) \d+ ([a-z ]+?)s?:$/i,PHPUNIT_TRIGGERED=/^\d+ tests? triggered \d+ [\w ]+?s?:$/,PHPUNIT_END=/^(?:--|FAILURES!|ERRORS!|WARNINGS!|OK\b.*|Tests: .*|No tests executed!)$/,PHPUNIT_ITEM=/^\d+\) (.*)$/,PHP_LOCATION=/^([\w./-]+\.php):(\d+)$/,PHPSTAN_FILE=/^ {2}Line {3}(\S.*)$/,PHPSTAN_GENERAL=/^ {2}Error\s*$/,PHPSTAN_MESSAGE=/^ {2}(\S.*)$/,PHPSTAN_ROW=/^ {2}(\d+|-) +(\S.*)$/,PHPSTAN_CONTINUATION=/^ {9}(\S.*)$/,PHPSTAN_IDENTIFIER=/^ {9}\uD83E\uDEAA\s+(\S+)\s*$/,PHPSTAN_TIP=/^ {9}\uD83D\uDCA1/,PHPSTAN_BORDER=/^ -{3,}(?: -{3,})*\s*$/,PHPSTAN_RAW=/^(\S.*?\.(?:php|phtml|twig|neon|inc)):(\d+):(\S.*)$/,PHPSTAN_JSON=/^\{.*"totals"/,CS_FIXER_FILE=/^\s+\d+\) (\S.*?\.php)(?: \((.+)\))?$/,CS_FIXER_DIFF_START=/^\s+-+ begin diff -+$/,CS_FIXER_DIFF_END=/^\s+-+ end diff -+$/;function isHeader(line){return PHPUNIT_HEADER.test(line)||PHPUNIT_TRIGGERED.test(line)}function diffSummary(message){let start=message.findIndex((line)=>line==="+++ Actual");if(start===-1)return"";let changed=message.slice(start+1).filter((line)=>line.startsWith("-")||line.startsWith("+")).map((line)=>`${line[0]} ${line.slice(1).trim()}`),shown=changed.slice(0,6).join(" | ");return changed.length===0?"":` (${shown}${changed.length>6?" | ...":""})`}function phpunitError(test,body){let at=body.findIndex((line)=>PHP_LOCATION.test(line)),location=PHP_LOCATION.exec(body[at]??""),message=body.slice(0,at===-1?body.length:at).map((line)=>line.trimEnd()),first=message.find((line)=>line.trim()!=="")??"failed";return{tool:"phpunit",file:location?.[1]??"",line:Number(location?.[2]??0),column:0,severity:"error",message:`${first}${diffSummary(message)}`,test}}var collectPhpunit=(lines,used)=>{let errors=[];for(let index=0;index<lines.length;index++){let line=lines[index]??"",kind=PHPUNIT_HEADER.exec(line)?.[1];if(kind===void 0&&!PHPUNIT_TRIGGERED.test(line))continue;let end=index+1;while(end<lines.length&&!PHPUNIT_END.test(lines[end]??"")&&!isHeader(lines[end]??""))end++;for(let at=index;at<end;at++)used.add(at);if(kind==="error"||kind==="failure"){let starts=Array.from({length:end-index-1},(_,at)=>index+1+at).filter((at)=>PHPUNIT_ITEM.test(lines[at]??""));for(let[position,start]of starts.entries())errors.push(phpunitError(PHPUNIT_ITEM.exec(lines[start]??"")?.[1]??"",lines.slice(start+1,starts[position+1]??end)))}index=end-1}return errors};function appendMessage(error,text){error.message=`${error.message} ${text}`}function phpstanJson(text){try{let report=JSON.parse(text);return[...Object.entries(report.files??{}).flatMap(([file,entry])=>entry.messages.map((message)=>({file,line:message.line??0,message:message.message,...message.identifier===void 0?{}:{rule:message.identifier}}))),...(report.errors??[]).map((message)=>({file:"",line:0,message}))]}catch{return}}var collectPhpstan=(lines,used)=>{let errors=[],file,current,rows=0,tip=!1,general=!1;for(let[index,text]of lines.entries()){let line=text.trimEnd();if(used.has(index))continue;if(PHPSTAN_JSON.test(line)){let parsed=phpstanJson(line);for(let entry of parsed??[])errors.push({tool:"phpstan",file:entry.file,line:entry.line,column:0,severity:"error",message:entry.message,...entry.rule===void 0?{}:{rule:entry.rule}});if(parsed!==void 0)used.add(index);continue}let raw=PHPSTAN_RAW.exec(line);if(raw!==null){errors.push({tool:"phpstan",file:raw[1]??"",line:Number(raw[2]),column:0,severity:"error",message:raw[3]??""}),used.add(index);continue}let header=PHPSTAN_FILE.exec(line);if(header!==null||PHPSTAN_GENERAL.test(line)){file=header?.[1]??"",general=header===null,current=void 0,rows=0,used.add(index);continue}if(file===void 0)continue;let message=PHPSTAN_MESSAGE.exec(line)?.[1];if(general&&message!==void 0&&!PHPSTAN_BORDER.test(line)){errors.push({tool:"phpstan",file:"",line:0,column:0,severity:"error",message}),rows++,used.add(index);continue}let row=PHPSTAN_ROW.exec(line),identifier=PHPSTAN_IDENTIFIER.exec(line)?.[1],continuation=PHPSTAN_CONTINUATION.exec(line)?.[1];if(PHPSTAN_BORDER.test(line)&&rows>0)file=void 0,general=!1,current=void 0;else if(row!==null)current={tool:"phpstan",file,line:row[1]==="-"?0:Number(row[1]),column:0,severity:"error",message:row[2]??""},errors.push(current),rows++,tip=!1,used.add(index);else if(identifier!==void 0&¤t!==void 0)current.rule=identifier,used.add(index);else if(PHPSTAN_TIP.test(line))tip=!0,used.add(index);else if(continuation!==void 0&¤t!==void 0){if(!tip)appendMessage(current,continuation);used.add(index)}}return errors},collectCsFixer=(lines,used)=>{let errors=[];for(let index=0;index<lines.length;index++){let match=CS_FIXER_FILE.exec(lines[index]??"");if(match===null)continue;if(errors.push({tool:"php-cs-fixer",file:match[1]??"",line:0,column:0,...match[2]===void 0?{}:{rule:match[2]},severity:"error",message:"style issues to fix"}),used.add(index),!CS_FIXER_DIFF_START.test(lines[index+1]??""))continue;let end=lines.findIndex((text,at)=>at>index&&CS_FIXER_DIFF_END.test(text));for(let at=index+1;at<=(end===-1?index+1:end);at++)used.add(at);index=end===-1?index+1:end}return errors};var{BASH_ECHO,DURATION,BOUNDARY,BUN_TEST_SUMMARY,BUN_CHECK_SUMMARY,TSC_CONTINUATION,TSC_FRAME,TSC_SUMMARY,ESLINT_PROBLEM,ESLINT_SUMMARY}=LOG_PATTERNS,TSC_PLAIN_ERROR=/^(.+?)\((\d+),(\d+)\): error (TS\d+): (.*)$/,TSC_PRETTY_ERROR=/^(.+?):(\d+):(\d+) - error (TS\d+): (.*)$/,TSC_SOURCE_LINE=/^\d+ /,ESLINT_FIELDS=/^ +(\d+):(\d+) +(error|warning) +(\S.*)$/,ESLINT_RULE=/ {2,}(\S+)$/,ESLINT_FILE=/^(?:\/|~\/|\.{1,2}[/\\]|[a-z]:\\)|^[^\s/\\]+[/\\]\S*$/i,BUN_TEST_EXPECTED=/^Expected: (.*)$/,BUN_TEST_RECEIVED=/^Received: (.*)$/,BUN_TEST_FRAME=/^\s+at (?:.*? \()?(.+?):(\d+):(\d+)\)?$/,BUN_TEST_FILE=/^\S+\.test\.[jt]sx?:$/,GO_ERROR=/^\s*(?:vet: )?(\S+\.go):(\d+):(?:(\d+):)? (.+)$/,GO_LINTER=/^(.*\S)\s+\(([a-z][\w-]*)\)$/,GO_NOISE=/^# \S+(?: \[\S+\])?$/,ARROW=/^\s*--> (.+?):(\d+):(\d+)$/,CARGO_HEADER=/^(error|warning)(?:\[([\w-]+)\])?: (.*)$/,LINE_BREAK=/\r?\n/,CONTINUATION=/^\s+\S/,MAX_CONTINUATION=20,KAY_SUMMARY=/^(?:\d+ errors?(?:, \d+ warnings?)?|\d+ warnings?)(?:, failing under --deny-warnings)?$|^checked with /,CARGO_NOISE=/^(?:\s+(?:Compiling|Finished|Checking|Fresh|Running|Blocking) |error: (?:aborting due to|could not compile)|warning: .* generated \d+ warnings?|Some errors have detailed explanations|For more information about (?:this|an) error|To learn more, run the command again)/,RUFF_CONCISE=/^(\S+\.pyi?):(\d+):(\d+): ([A-Z]+\d+) (?:\[\*\] )?(.*)$/,RUFF_HEADER=/^([A-Z]{1,5}\d{1,4}) (?:\[\*\] )?(.+)$/,RUFF_NOISE=/^(?:Found \d+ errors?\.|\[\*\] \d+ fixable|No fixes available|All checks passed|help: |\s*(?:\|\s*)?$)/,PYTEST_LOCATION=/^(\S+\.py):(\d+): (\S.*)$/,PYTEST_E_LINE=/^E {3}(.*)$/,PYTEST_BANNER=/^={3,} (.*?) ={3,}$/,PYTEST_FAILURES=new Set(["FAILURES","ERRORS"]),PYTEST_SUMMARY_LINE=/^(?:FAILED|ERROR) \S/,PYTEST_FRAME=/^in \S/,PYTEST_SECTION=/^_{3,} (.*) _{3,}$/,PYTEST_SUMMARY=/^(?:FAILED|ERROR) ([^\s:]+?\.py)(?:::(.*)| - (.*))?$/,PYTEST_ERROR_SECTION=/^ERROR (?:at (?:setup|teardown) of |collecting )/,PYTEST_EXCEPTION_END=/[\s:]/,PYTEST_NOISE=/^(?:platform |rootdir: |collected |plugins: |configfile: |cachedir: |\S+\.pyi? [.FEsxXR]+ +\[ *\d+%\]$|\S+\.py:\d+: $)/,GENERIC_LINE=/^(\S[^:]*):(\d+)(?::(\d+))?: (?:fatal )?(error|warning|note): (.*)$/,GENERIC_RULE=/\s(?:\[([\w-]+)\]|\(([a-z][\w-]*)\))$/,NOISE=/^(?:bun test v|Errors {2}Files$|Ran \d+ tests?|note: |\s*\d+ expect\(\) calls|\s+\d+\s+\S+:\d+$|\s*\d+ errors? and \d+ warnings? potentially fixable|error: script ".+" exited with code \d+$)/;function isNoise(line){return line.trim()===""||[NOISE,BUN_TEST_SUMMARY,BUN_CHECK_SUMMARY,TSC_SUMMARY,ESLINT_SUMMARY,BOUNDARY,BASH_ECHO,GO_NOISE,CARGO_NOISE,KAY_SUMMARY,RUFF_NOISE,PYTEST_NOISE,PYTEST_BANNER,...PHP_NOISE,...E2E_NOISE].some((pattern)=>pattern.test(line))}var collectBunCheck=(lines,used)=>{let errors=[];for(let index=0;index<lines.length;index++){if(!(lines[index]??"").startsWith("<error file="))continue;let end=lines.findIndex((line,at)=>at>=index&&line==="</error>");if(end===-1)break;let{file,line,column,code,message}=bunCheckFields(lines.slice(index,end+1).join(`
|
|
2
|
+
import{paint,role,stripAnsi,formatDuration}from"./chunk-ngcnmctk.js";import{runCommand,privateLogDirectory,sweepLogs,bunCheckFields,failureExcerpt,LOG_PATTERNS}from"./chunk-898e3vv3.js";import{mkdir,readdir,stat,writeFile}from"fs/promises";import{basename,join}from"path";import process from"process";import{relative}from"path";var E2E_NOISE=[/^(?:Running \d+ tests? using|\(node:\d+\) Warning|\(Use `node|\[\d+\/\d+\] |\s+[-\u2713\u2718\u00B0\u00D7]\s+\d+|To open last HTML|Serving HTML report|\s*npx playwright show-report)/,/^[\u00B7F\u00D7\u00B0T\u00B1]+$/,/^(?: RUN {2}v|\s*[\u276F\u2713\u00D7\u2193] |\s+(?:Test Files|Tests|Start at|Duration|Errors) {2}|\u23AF)/],PLAYWRIGHT_HEADER=/^ {2}\d+\) (?:\[([^\]]+)\] \u203A )?(.+?):(\d+):(\d+) \u203A (.+?) \u2500+$/,PLAYWRIGHT_SUMMARY=/^ {2}\d+ (failed|flaky|passed|skipped|did not run|interrupted)\b/,PLAYWRIGHT_ENTRY=/^ {4}(?:\[([^\]]+)\] \u203A )?(.+?):(\d+):(\d+) \u203A (.+?) \u2500+$/,PLAYWRIGHT_RETRY=/^\s+Retry #\d+ \u2500+$/,FRAME=/^\s+at (?:.*? \()?(.+?):(\d+):(\d+)\)?$/,EXPECTED=/^\s+Expected: (.*)$/,RECEIVED=/^\s+Received: (.*)$/,VITEST_FAIL=/^ FAIL {2}(?:\|[^|]+\| )?(.+)$/,VITEST_SUITE=/^(.+?) \[ .+ \]$/,VITEST_FRAME=/^\s*\u276F (\S+):(\d+):(\d+)$/;function key(project,file,line,column,title){return`${project??""}|${file}:${line}:${column} \u203A ${title}`}function firstFrame(block){return block.map((line)=>FRAME.exec(line)).find((match)=>match!==null&&!match[1]?.includes("node_modules"))??void 0}var collectPlaywright=(lines,used)=>{let flaky=new Set,section="";for(let[index,line]of lines.entries()){let summary=PLAYWRIGHT_SUMMARY.exec(line),entry=PLAYWRIGHT_ENTRY.exec(line);if(summary!==null)section=summary[1]??"",used.add(index);else if(entry!==null&§ion!==""){if(section==="flaky")flaky.add(key(entry[1],entry[2],entry[3],entry[4],entry[5]));used.add(index)}}let errors=[];for(let index=0;index<lines.length;index++){let header=PLAYWRIGHT_HEADER.exec(lines[index]??"");if(header===null)continue;let end=index+1;while(end<lines.length&&!PLAYWRIGHT_HEADER.test(lines[end]??"")&&!PLAYWRIGHT_SUMMARY.test(lines[end]??""))end++;for(let at=index;at<end;at++)used.add(at);let[,project,file,line,column,title]=header,retry=lines.findIndex((text,at)=>at>index&&at<end&&PLAYWRIGHT_RETRY.test(text)),block=lines.slice(index+1,retry===-1?end:retry),frame=firstFrame(block),message=block.find((text)=>text.trim()!=="")?.trim()??"failed",expected=block.map((text)=>EXPECTED.exec(text)?.[1]?.trim()).find((text)=>text!==void 0),received=block.map((text)=>RECEIVED.exec(text)?.[1]?.trim()).find((text)=>text!==void 0),values=expected===void 0||received===void 0?"":` (expected ${expected}, received ${received})`;if(index=end-1,flaky.has(key(project,file,line,column,title)))continue;errors.push({tool:"playwright",file:frame?.[1]??file??"",line:Number(frame?.[2]??line),column:Number(frame?.[3]??column),severity:"error",message:`${message}${values}`,test:`${project===void 0?"":`[${project}] `}${title}`})}return errors},collectVitest=(lines,used)=>{let errors=[];for(let index=0;index<lines.length;index++){let header=VITEST_FAIL.exec(lines[index]??"")?.[1];if(header===void 0)continue;let end=index+1;while(end<lines.length&&!(lines[end]??"").startsWith("\u23AF")&&!VITEST_FAIL.test(lines[end]??""))end++;for(let at=index;at<end;at++)used.add(at);let block=lines.slice(index+1,end),frame=block.map((text)=>VITEST_FRAME.exec(text)).find((match)=>match!==null&&!match[1]?.includes("node_modules")),suite=VITEST_SUITE.exec(header)?.[1],[file="",...names]=(suite??header).split(" > ");errors.push({tool:"vitest",file:frame?.[1]??file,line:Number(frame?.[2]??0),column:Number(frame?.[3]??0),severity:"error",message:block.find((text)=>text.trim()!=="")?.trim()??"failed",...suite===void 0&&names.length>0?{test:names.join(" > ")}:{}}),index=end-1}return errors};var PHP_NOISE=[/^(?:PHPUnit \d|ParaTest v|Runtime: |Configuration: |Processes: |Random Seed: |Time: |Tests: |OK(?:,| \()|FAILURES!|ERRORS!|WARNINGS!|No tests executed|--$)/,/^[.FEWRISD]+\s+\d+ \/ \d+ \(\d+%\)$/,/^ -{3,}(?: -{3,})*\s*$/,/^\s*\d+\/\d+ \[[=>\-\u2593\u2591 ]*\]\s+\d+%/,/^(?:Note: Using configuration file|\s*\[(?:OK|ERROR)\] )/,/^(?:Loaded config|PHP runtime:|PHP CS Fixer \d|Running analysis|Parallel runner|Using cache file|Paths from configuration|Rules from configuration|Setting PHP_CS_FIXER|Unable to determine minimum|If you need help|Found \d+ of \d+ files|Checked all files|Fixed \d+ of \d+ files|Legend:)/];var PHPUNIT_HEADER=/^There (?:was|were) \d+ ([a-z ]+?)s?:$/i,PHPUNIT_TRIGGERED=/^\d+ tests? triggered \d+ [\w ]+?s?:$/,PHPUNIT_END=/^(?:--|FAILURES!|ERRORS!|WARNINGS!|OK\b.*|Tests: .*|No tests executed!)$/,PHPUNIT_ITEM=/^\d+\) (.*)$/,PHP_LOCATION=/^([\w./-]+\.php):(\d+)$/,PHPSTAN_FILE=/^ {2}Line {3}(\S.*)$/,PHPSTAN_GENERAL=/^ {2}Error\s*$/,PHPSTAN_MESSAGE=/^ {2}(\S.*)$/,PHPSTAN_ROW=/^ {2}(\d+|-) +(\S.*)$/,PHPSTAN_CONTINUATION=/^ {9}(\S.*)$/,PHPSTAN_IDENTIFIER=/^ {9}\uD83E\uDEAA\s+(\S+)\s*$/,PHPSTAN_TIP=/^ {9}\uD83D\uDCA1/,PHPSTAN_BORDER=/^ -{3,}(?: -{3,})*\s*$/,PHPSTAN_RAW=/^(\S.*?\.(?:php|phtml|twig|neon|inc)):(\d+):(\S.*)$/,PHPSTAN_JSON=/^\{.*"totals"/,CS_FIXER_FILE=/^\s+\d+\) (\S.*?\.php)(?: \((.+)\))?$/,CS_FIXER_DIFF_START=/^\s+-+ begin diff -+$/,CS_FIXER_DIFF_END=/^\s+-+ end diff -+$/;function isHeader(line){return PHPUNIT_HEADER.test(line)||PHPUNIT_TRIGGERED.test(line)}function diffSummary(message){let start=message.findIndex((line)=>line==="+++ Actual");if(start===-1)return"";let changed=message.slice(start+1).filter((line)=>line.startsWith("-")||line.startsWith("+")).map((line)=>`${line[0]} ${line.slice(1).trim()}`),shown=changed.slice(0,6).join(" | ");return changed.length===0?"":` (${shown}${changed.length>6?" | ...":""})`}function phpunitError(test,body){let at=body.findIndex((line)=>PHP_LOCATION.test(line)),location=PHP_LOCATION.exec(body[at]??""),message=body.slice(0,at===-1?body.length:at).map((line)=>line.trimEnd()),first=message.find((line)=>line.trim()!=="")??"failed";return{tool:"phpunit",file:location?.[1]??"",line:Number(location?.[2]??0),column:0,severity:"error",message:`${first}${diffSummary(message)}`,test}}var collectPhpunit=(lines,used)=>{let errors=[];for(let index=0;index<lines.length;index++){let line=lines[index]??"",kind=PHPUNIT_HEADER.exec(line)?.[1];if(kind===void 0&&!PHPUNIT_TRIGGERED.test(line))continue;let end=index+1;while(end<lines.length&&!PHPUNIT_END.test(lines[end]??"")&&!isHeader(lines[end]??""))end++;for(let at=index;at<end;at++)used.add(at);if(kind==="error"||kind==="failure"){let starts=Array.from({length:end-index-1},(_,at)=>index+1+at).filter((at)=>PHPUNIT_ITEM.test(lines[at]??""));for(let[position,start]of starts.entries())errors.push(phpunitError(PHPUNIT_ITEM.exec(lines[start]??"")?.[1]??"",lines.slice(start+1,starts[position+1]??end)))}index=end-1}return errors};function appendMessage(error,text){error.message=`${error.message} ${text}`}function phpstanJson(text){try{let report=JSON.parse(text);return[...Object.entries(report.files??{}).flatMap(([file,entry])=>entry.messages.map((message)=>({file,line:message.line??0,message:message.message,...message.identifier===void 0?{}:{rule:message.identifier}}))),...(report.errors??[]).map((message)=>({file:"",line:0,message}))]}catch{return}}var collectPhpstan=(lines,used)=>{let errors=[],file,current,rows=0,tip=!1,general=!1;for(let[index,text]of lines.entries()){let line=text.trimEnd();if(used.has(index))continue;if(PHPSTAN_JSON.test(line)){let parsed=phpstanJson(line);for(let entry of parsed??[])errors.push({tool:"phpstan",file:entry.file,line:entry.line,column:0,severity:"error",message:entry.message,...entry.rule===void 0?{}:{rule:entry.rule}});if(parsed!==void 0)used.add(index);continue}let raw=PHPSTAN_RAW.exec(line);if(raw!==null){errors.push({tool:"phpstan",file:raw[1]??"",line:Number(raw[2]),column:0,severity:"error",message:raw[3]??""}),used.add(index);continue}let header=PHPSTAN_FILE.exec(line);if(header!==null||PHPSTAN_GENERAL.test(line)){file=header?.[1]??"",general=header===null,current=void 0,rows=0,used.add(index);continue}if(file===void 0)continue;let message=PHPSTAN_MESSAGE.exec(line)?.[1];if(general&&message!==void 0&&!PHPSTAN_BORDER.test(line)){errors.push({tool:"phpstan",file:"",line:0,column:0,severity:"error",message}),rows++,used.add(index);continue}let row=PHPSTAN_ROW.exec(line),identifier=PHPSTAN_IDENTIFIER.exec(line)?.[1],continuation=PHPSTAN_CONTINUATION.exec(line)?.[1];if(PHPSTAN_BORDER.test(line)&&rows>0)file=void 0,general=!1,current=void 0;else if(row!==null)current={tool:"phpstan",file,line:row[1]==="-"?0:Number(row[1]),column:0,severity:"error",message:row[2]??""},errors.push(current),rows++,tip=!1,used.add(index);else if(identifier!==void 0&¤t!==void 0)current.rule=identifier,used.add(index);else if(PHPSTAN_TIP.test(line))tip=!0,used.add(index);else if(continuation!==void 0&¤t!==void 0){if(!tip)appendMessage(current,continuation);used.add(index)}}return errors},collectCsFixer=(lines,used)=>{let errors=[];for(let index=0;index<lines.length;index++){let match=CS_FIXER_FILE.exec(lines[index]??"");if(match===null)continue;if(errors.push({tool:"php-cs-fixer",file:match[1]??"",line:0,column:0,...match[2]===void 0?{}:{rule:match[2]},severity:"error",message:"style issues to fix"}),used.add(index),!CS_FIXER_DIFF_START.test(lines[index+1]??""))continue;let end=lines.findIndex((text,at)=>at>index&&CS_FIXER_DIFF_END.test(text));for(let at=index+1;at<=(end===-1?index+1:end);at++)used.add(at);index=end===-1?index+1:end}return errors};var{BASH_ECHO,DURATION,BOUNDARY,BUN_TEST_SUMMARY,BUN_CHECK_SUMMARY,TSC_CONTINUATION,TSC_FRAME,TSC_SUMMARY,ESLINT_PROBLEM,ESLINT_SUMMARY}=LOG_PATTERNS,TSC_PLAIN_ERROR=/^(.+?)\((\d+),(\d+)\): error (TS\d+): (.*)$/,TSC_PRETTY_ERROR=/^(.+?):(\d+):(\d+) - error (TS\d+): (.*)$/,TSC_SOURCE_LINE=/^\d+ /,ESLINT_FIELDS=/^ +(\d+):(\d+) +(error|warning) +(\S.*)$/,ESLINT_RULE=/ {2,}(\S+)$/,ESLINT_FILE=/^(?:\/|~\/|\.{1,2}[/\\]|[a-z]:\\)|^[^\s/\\]+[/\\]\S*$/i,BUN_TEST_EXPECTED=/^Expected: (.*)$/,BUN_TEST_RECEIVED=/^Received: (.*)$/,BUN_TEST_FRAME=/^\s+at (?:.*? \()?(.+?):(\d+):(\d+)\)?$/,BUN_TEST_FILE=/^\S+\.test\.[jt]sx?:$/,GO_ERROR=/^\s*(?:vet: )?(\S+\.go):(\d+):(?:(\d+):)? (.+)$/,GO_LINTER=/^(.*\S)\s+\(([a-z][\w-]*)\)$/,GO_NOISE=/^# \S+(?: \[\S+\])?$/,ARROW=/^\s*--> (.+?):(\d+):(\d+)$/,CARGO_HEADER=/^(error|warning)(?:\[([\w-]+)\])?: (.*)$/,LINE_BREAK=/\r?\n/,CONTINUATION=/^\s+\S/,MAX_CONTINUATION=20,KAY_SUMMARY=/^(?:\d+ errors?(?:, \d+ warnings?)?|\d+ warnings?)(?:, failing under --deny-warnings)?$|^checked with /,CARGO_NOISE=/^(?:\s+(?:Compiling|Finished|Checking|Fresh|Running|Blocking) |error: (?:aborting due to|could not compile)|warning: .* generated \d+ warnings?|Some errors have detailed explanations|For more information about (?:this|an) error|To learn more, run the command again)/,RUFF_CONCISE=/^(\S+\.pyi?):(\d+):(\d+): ([A-Z]+\d+) (?:\[\*\] )?(.*)$/,RUFF_HEADER=/^([A-Z]{1,5}\d{1,4}) (?:\[\*\] )?(.+)$/,RUFF_NOISE=/^(?:Found \d+ errors?\.|\[\*\] \d+ fixable|No fixes available|All checks passed|help: |\s*(?:\|\s*)?$)/,PYTEST_LOCATION=/^(\S+\.py):(\d+): (\S.*)$/,PYTEST_E_LINE=/^E {3}(.*)$/,PYTEST_BANNER=/^={3,} (.*?) ={3,}$/,PYTEST_FAILURES=new Set(["FAILURES","ERRORS"]),PYTEST_SUMMARY_LINE=/^(?:FAILED|ERROR) \S/,PYTEST_FRAME=/^in \S/,PYTEST_SECTION=/^_{3,} (.*) _{3,}$/,PYTEST_SUMMARY=/^(?:FAILED|ERROR) ([^\s:]+?\.py)(?:::(.*)| - (.*))?$/,PYTEST_ERROR_SECTION=/^ERROR (?:at (?:setup|teardown) of |collecting )/,PYTEST_EXCEPTION_END=/[\s:]/,PYTEST_NOISE=/^(?:platform |rootdir: |collected |plugins: |configfile: |cachedir: |\S+\.pyi? [.FEsxXR]+ +\[ *\d+%\]$|\S+\.py:\d+: $)/,GENERIC_LINE=/^(\S[^:]*):(\d+)(?::(\d+))?: (?:fatal )?(error|warning|note): (.*)$/,GENERIC_RULE=/\s(?:\[([\w-]+)\]|\(([a-z][\w-]*)\))$/,NOISE=/^(?:bun test v|Errors {2}Files$|Ran \d+ tests?|note: |\s*\d+ expect\(\) calls|\s+\d+\s+\S+:\d+$|\s*\d+ errors? and \d+ warnings? potentially fixable|error: script ".+" exited with code \d+$)/;function isNoise(line){return line.trim()===""||[NOISE,BUN_TEST_SUMMARY,BUN_CHECK_SUMMARY,TSC_SUMMARY,ESLINT_SUMMARY,BOUNDARY,BASH_ECHO,GO_NOISE,CARGO_NOISE,KAY_SUMMARY,RUFF_NOISE,PYTEST_NOISE,PYTEST_BANNER,...PHP_NOISE,...E2E_NOISE].some((pattern)=>pattern.test(line))}var collectBunCheck=(lines,used)=>{let errors=[];for(let index=0;index<lines.length;index++){if(!(lines[index]??"").startsWith("<error file="))continue;let end=lines.findIndex((line,at)=>at>=index&&line==="</error>");if(end===-1)break;let{file,line,column,code,message}=bunCheckFields(lines.slice(index,end+1).join(`
|
|
3
3
|
`));errors.push({tool:"bun check",file,line:Number(line),column:Number(column),rule:code,severity:"error",message:message.replaceAll(/\s*\n\s*/g," ")});for(let at=index;at<=end;at++)used.add(at);index=end}return errors},collectBunTest=(lines,used)=>{let errors=[],seen=new Set,names=new Set;for(let[index,line]of lines.entries()){if(!line.startsWith("(fail) "))continue;used.add(index);let test=line.slice(7).replace(DURATION,""),start=lines.findLastIndex((text,at)=>at<index&&BOUNDARY.test(text))+1,block=lines.slice(start,index),failure=block.findIndex((text)=>text.startsWith("error:"));for(let at=start;at<index;at++)used.add(at);let frame=block.slice(Math.max(failure,0)).map((text)=>BUN_TEST_FRAME.exec(text)).find((match)=>match!==null),header=lines.slice(0,index).findLast((text)=>BUN_TEST_FILE.test(text)),key=`${header??""}\x00${test}`;if(seen.has(key)||failure===-1&&names.has(test))continue;seen.add(key),names.add(test);let expected=block.map((text)=>BUN_TEST_EXPECTED.exec(text)?.[1]).find((text)=>text!==void 0),received=block.map((text)=>BUN_TEST_RECEIVED.exec(text)?.[1]).find((text)=>text!==void 0),reason=failure===-1?"failed":(block[failure]??"").slice(6).trim(),values=expected===void 0||received===void 0?"":` (expected ${expected}, received ${received})`;errors.push({tool:"bun test",file:frame?.[1]??header?.replace(":","")??"",line:Number(frame?.[2]??0),column:Number(frame?.[3]??0),severity:"error",message:`${reason}${values}`,test})}return errors},collectTsc=(lines,used)=>{let errors=[],current,pretty=!1;for(let[index,line]of lines.entries()){if(used.has(index))continue;let plain=TSC_PLAIN_ERROR.exec(line),match=plain??TSC_PRETTY_ERROR.exec(line);if(match!==null)current={tool:"tsc",file:match[1]??"",line:Number(match[2]),column:Number(match[3]),rule:match[4],severity:"error",message:match[5]??""},pretty=plain===null,errors.push(current),used.add(index);else if(current!==void 0&&TSC_CONTINUATION.test(line)&&!TSC_FRAME.test(line))current.message+=` ${line.trim()}`,used.add(index);else if(current!==void 0&&pretty&&(TSC_FRAME.test(line)||TSC_SOURCE_LINE.test(line)))used.add(index);else if(!(pretty&&line.trim()===""))current=void 0}return errors},collectEslint=(lines,used)=>{let errors=[],file;for(let[index,line]of lines.entries()){if(used.has(index))continue;let match=ESLINT_PROBLEM.test(line)?ESLINT_FIELDS.exec(line):null;if(match!==null&&file!==void 0){let text=match[4]??"",rule=ESLINT_RULE.exec(text);errors.push({tool:"eslint",file:(lines[file]??"").trim(),line:Number(match[1]),column:Number(match[2]),rule:rule?.[1],severity:match[3]==="warning"?"warning":"error",message:rule===null?text:text.slice(0,rule.index)}),used.add(index),used.add(file)}else if(!isNoise(line)&&!line.includes(": ")&&ESLINT_FILE.test(line.trimEnd()))file=index}return errors},collectGo=(lines,used)=>{let errors=[];for(let[index,line]of lines.entries()){let match=used.has(index)?null:GO_ERROR.exec(line);if(match===null)continue;let linter=GO_LINTER.exec(match[4]??"");errors.push({tool:"go",file:match[1]??"",line:Number(match[2]),column:Number(match[3]??0),...linter===null?{}:{rule:linter[2]},severity:"error",message:linter===null?match[4]??"":linter[1]??""}),used.add(index)}return errors};function headerAbove(lines,arrow,used){let at=arrow-1;while(at>0&&arrow-at<=MAX_CONTINUATION&&!used.has(at)&&CONTINUATION.test(lines[at]??"")&&!ARROW.test(lines[at]??""))at--;return at}var collectArrowed=(lines,used)=>{let errors=[];for(let[index,line]of lines.entries()){let arrow=used.has(index)||index===0?null:ARROW.exec(line),at=arrow===null?-1:headerAbove(lines,index,used),header=at===-1?null:lines[at]??"",cargo=header===null?null:CARGO_HEADER.exec(header),ruff=header===null||cargo!==null?null:RUFF_HEADER.exec(header);if(arrow===null||cargo===null&&ruff===null||used.has(at))continue;let[,file="",row,column]=arrow,fields={file,line:Number(row),column:Number(column)};errors.push(cargo===null?{tool:"ruff",...fields,rule:ruff?.[1],severity:"error",message:ruff?.[2]??""}:{tool:file.endsWith(".rs")?"cargo":"kay check",...fields,rule:cargo[2],severity:cargo[1]==="warning"?"warning":"error",message:cargo[3]??""});for(let taken=at;taken<=index;taken++)used.add(taken);for(let frame=index+1;frame<lines.length&&(lines[frame]??"").trim()!=="";frame++){if(CARGO_HEADER.test(lines[frame]??"")||RUFF_HEADER.test(lines[frame]??""))break;used.add(frame)}}return errors},collectRuff=(lines,used)=>{let errors=[];for(let[index,line]of lines.entries()){let match=used.has(index)?null:RUFF_CONCISE.exec(line);if(match===null)continue;errors.push({tool:"ruff",file:match[1]??"",line:Number(match[2]),column:Number(match[3]),rule:match[4],severity:"error",message:match[5]??""}),used.add(index)}return errors},collectPytest=(lines,used)=>{let errors=[],silent=new Map,section,closeSection=()=>{if(section===void 0||errors.length!==section.errors)return;let key=section.title.replace(PYTEST_ERROR_SECTION,"");silent.set(key,(silent.get(key)??0)+1)},title=(line)=>PYTEST_BANNER.exec(line??"")?.[1],start=lines.findIndex((line)=>PYTEST_FAILURES.has(title(line)??""));if(start===-1)return errors;let end=lines.findIndex((line,index)=>index>start&&title(line)!==void 0&&!PYTEST_FAILURES.has(title(line)??"")),stop=end===-1?lines.length:end,message=[],frame;for(let index=start;index<stop;index++){let line=lines[index]??"",failure=PYTEST_E_LINE.exec(line);if(failure!==null)message.push((failure[1]??"").trim());else{if(frame!==void 0&&message.length>0)errors.push({tool:"pytest",...frame,column:0,severity:"error",message:message[0]??""}),frame=void 0;let location=PYTEST_LOCATION.exec(line);if(location!==null&&PYTEST_FRAME.test(location[3]??""))frame={file:location[1]??"",line:Number(location[2])};else if(location!==null){let[exception=""]=(location[3]??"").split(PYTEST_EXCEPTION_END),first=message[0]??"",text=first===""||first.startsWith(exception)?first||(location[3]??""):`${location[3]??""}: ${first}`;errors.push({tool:"pytest",file:location[1]??"",line:Number(location[2]),column:0,severity:"error",message:text})}let opened=PYTEST_SECTION.exec(line);if(opened!==null)frame=void 0,closeSection(),section={title:opened[1]??"",errors:errors.length};if(line.trim()!=="")message=[]}used.add(index)}if(frame!==void 0&&message.length>0)errors.push({tool:"pytest",...frame,column:0,severity:"error",message:message[0]??""});closeSection();for(let index=stop;index<lines.length;index++){if(!PYTEST_SUMMARY_LINE.test(lines[index]??""))continue;used.add(index);let[,file="",rest,fileReason]=PYTEST_SUMMARY.exec(lines[index]??"")??[],parts=summaryParts(file,rest,fileReason,silent);if(parts===void 0)continue;let{key,name,reason}=parts,left=silent.get(key)??0;silent.set(key,left-1),errors.push({tool:"pytest",file,line:0,column:0,severity:"error",message:reason??"failed",test:name===void 0?file:`${file}::${name}`})}return errors};function summaryParts(file,rest,fileReason,silent){let keyOf=(name)=>name===void 0?file:name.replaceAll("::","."),candidates=[];if(rest===void 0)candidates.push({name:void 0,reason:fileReason});else{for(let at=rest.indexOf(" - ");at!==-1;at=rest.indexOf(" - ",at+1))candidates.push({name:rest.slice(0,at),reason:rest.slice(at+3)});candidates.push({name:rest,reason:void 0})}let found=candidates.find((candidate)=>(silent.get(keyOf(candidate.name))??0)>0);return found===void 0?void 0:{key:keyOf(found.name),...found}}var collectGeneric=(lines,used)=>{let errors=[];for(let[index,line]of lines.entries()){let match=used.has(index)?null:GENERIC_LINE.exec(line);if(match===null)continue;if(used.add(index),match[4]==="note")continue;let text=match[5]??"",ruled=GENERIC_RULE.exec(text),rule=ruled?.[1]??ruled?.[2];errors.push({tool:"generic",file:match[1]??"",line:Number(match[2]),column:Number(match[3]??0),rule,severity:match[4]==="warning"?"warning":"error",message:ruled===null?text:text.slice(0,ruled.index).trimEnd()})}return errors},COLLECTORS=[collectBunCheck,collectBunTest,collectVitest,collectPlaywright,collectPhpunit,collectPhpstan,collectCsFixer,collectPytest,collectArrowed,collectRuff,collectGo,collectTsc,collectEslint,collectGeneric];function parseErrors(output){let lines=stripAnsi(output).split(LINE_BREAK);if(BASH_ECHO.test(lines[0]??""))lines.shift();let used=new Set,seen=new Set,errors=COLLECTORS.flatMap((collect)=>collect(lines,used)).filter((error)=>{let key=[error.file,error.line,error.column,error.message,error.test].join("\x00");if(seen.has(key))return!1;return seen.add(key),!0}),unrecognisedLines=lines.filter((line,index)=>!used.has(index)&&!isNoise(line));return{errors,unrecognised:unrecognisedLines.length,unrecognisedLines}}function formatError(error,cwd){let path=error.file.startsWith("/")?relative(cwd,error.file):error.file,where=`${path.startsWith("..")?error.file:path}:${error.line}:${error.column}`,label=error.test===void 0?"":`${error.test}: `,level=error.severity==="warning"?"warning: ":"",rule=error.rule===void 0?"":` (${error.rule})`;return`${where}: ${level}${label}${error.message}${rule}`}var LOG_MAX_AGE_MS=259200000,RESULTS_FILE="results.json",runPrefix=(cwd)=>`${basename(cwd)}-${Bun.hash(cwd).toString(36)}-`;async function logDirectory(cwd){let root=await privateLogDirectory("check");await sweepLogs(root,LOG_MAX_AGE_MS);let path=join(root,`${runPrefix(cwd)}${Date.now().toString(36)}-${process.pid}`);return await mkdir(path,{mode:448}),path}async function lastResults(cwd){let root=await privateLogDirectory("check"),prefix=runPrefix(cwd),latest;for(let name of await readdir(root)){if(!name.startsWith(prefix))continue;let file=join(root,name,RESULTS_FILE);try{let{mtimeMs}=await stat(file);if(latest===void 0||mtimeMs>latest.time)latest={time:mtimeMs,file}}catch{}}if(latest===void 0)return;return JSON.parse(await Bun.file(latest.file).text())}async function lastFailed(cwd){return(await lastResults(cwd))?.filter((result)=>!result.ok).map((result)=>result.name)}async function saveLog(output){let root=await privateLogDirectory("errs");await sweepLogs(root);let path=join(root,`${new Date().toISOString().replaceAll(/[:.]/g,"-")}-${process.pid}-${crypto.randomUUID().slice(0,8)}.log`);return await writeFile(path,output,{mode:384,flag:"wx"}),path}async function runStep(command,cwd,logFile,{env={},timeoutMs,held}={}){let started=Date.now(),{code,text,timedOut}=await runCommand(["sh","-c",`${command} 2>&1`],{cwd,env:{...process.env,NO_COLOR:"1",FORCE_COLOR:"0",...env},...timeoutMs===void 0?{}:{timeoutMs},...held===void 0?{}:{onStart:(child)=>held.forward(child)}}),output=stripAnsi(text);return await writeFile(logFile,output,{mode:384,flag:"wx"}),{ok:code===0,ms:Date.now()-started,output,...timedOut?{timedOut}:{}}}async function refusedStep(reason,logFile){return await writeFile(logFile,reason,{mode:384,flag:"wx"}),{ok:!1,ms:0,output:reason}}var MAX_INLINE_ERRORS=40;function formattedFailure(output,cwd=process.cwd()){let{errors,unrecognised}=parseErrors(output);if(errors.length===0)return{text:failureExcerpt(output),errors,unrecognised};let shown=errors.slice(0,MAX_INLINE_ERRORS).map((error)=>formatError(error,cwd)),more=errors.length>MAX_INLINE_ERRORS?[`... +${errors.length-MAX_INLINE_ERRORS} more errors`]:[],extra=unrecognised>0?[`(${unrecognised} unrecognised ${unrecognised===1?"line":"lines"} in full log)`]:[];return{text:[...shown,...more,...extra].join(`
|
|
4
4
|
`),errors,unrecognised}}function outcomeJson(name,command,logFile,outcome,service,cwd=process.cwd()){if(outcome.ok)return{name,command,...service===void 0?{}:{in:service},ok:!0,ms:outcome.ms,log:logFile};let{text,errors,unrecognised}=formattedFailure(outcome.output,cwd);return{name,command,...service===void 0?{}:{in:service},ok:!1,ms:outcome.ms,log:logFile,...outcome.timedOut===!0?{timedOut:!0}:{},failed:text,errors,unrecognised}}function printOutcome(name,width,command,logFile,outcome,cwd=process.cwd()){let colors=paint(process.stdout),path=role("path",process.stdout),took=colors.dim(formatDuration(outcome.ms));if(outcome.ok){console.log(`${colors.bold(colors.green("ok "))} ${name.padEnd(width)} ${took} ${path(logFile)}`);return}let label=outcome.timedOut===!0?colors.bold(colors.yellow("TIME ")):colors.bold(colors.red("FAIL "));if(console.log(`${label} ${name.padEnd(width)} ${took} ${colors.dim(command)} ${path(logFile)}`),outcome.timedOut===!0)console.log(colors.yellow(` timed out after ${formatDuration(outcome.ms)}, the step and what it started were ended`));console.log(formattedFailure(outcome.output,cwd).text.split(`
|
|
5
5
|
`).map((line)=>` ${line}`.trimEnd()).join(`
|
|
@@ -62,7 +62,7 @@ __kaynooo_cli_bins+=(${bins.join(" ")})
|
|
|
62
62
|
`,temp=`${path}.${process6.pid}.tmp`;writeFileSync(temp,kept,{mode:384}),renameSync(temp,path)}function recordUsage(entry,env=process6.env,maxBytes=MAX_USAGE_BYTES){if(!usageRecorded(env))return;try{let path=usagePath(env);mkdirSync(dirname(path),{recursive:!0,mode:448}),appendFileSync(path,`${JSON.stringify(entry)}
|
|
63
63
|
`,{mode:384}),trimUsage(path,maxBytes)}catch{}}var LEVEL_OPTIONS={...OUTPUT_OPTIONS,help:{type:"boolean",short:"h",description:"show this help"}},TOP_OPTIONS={...LEVEL_OPTIONS,version:{type:"boolean",short:"v",description:"print the version"},completions:{type:"string",choices:COMPLETION_SHELLS,description:"print the shell completion script"}};function printError(prefix,message,hint,cause){let colors=paint(process7.stderr),styled=takesControlCodes(process7.stderr),head=styled?`${colors.red.bold("error")} ${colors.dim(`${prefix}:`)}`:`error: ${prefix}:`,under=(label,text,tint)=>text===void 0?"":`
|
|
64
64
|
${styled?tint(label):`${label}:`} ${text}`;writeErr(`${head} ${message}${under("cause",cause,colors.dim)}${under("hint",hint,colors.yellow)}`)}function printJsonError(message,hint,cause,extra){writeErr(JSON.stringify({error:message,...extra?.code===void 0?{}:{code:extra.code},...extra?.command===void 0?{}:{command:extra.command},...hint===void 0?{}:{hint},...cause===void 0?{}:{cause}}))}function wantsJson(argv){let end=argv.indexOf("--");return(end===-1?argv:argv.slice(0,end)).includes("--json")}function reportThrown(prefix,error,redact=(text)=>text,json=!1){if(error instanceof HelpShown)return 0;let code=error instanceof Exit?error.code:1,helpHint=error instanceof UsageError?`run ${prefix} --help for its options`:void 0,named=error instanceof Error&&!(error instanceof Exit)&&error.name!=="Error"?`${error.name}: ${error.message}`:void 0,cause=error instanceof Error&&error.cause instanceof Error?redact(error.cause.message):void 0;if(error instanceof Exit&&error.code===2)noteUsageError(error.message);return(json?(message,hint,causeText)=>printJsonError(message,hint,causeText,{code,command:prefix}):(message,hint,causeText)=>printError(prefix,message,hint,causeText))(redact(named??(error instanceof Error?error.message:String(error))),error instanceof Exit?error.hint??helpHint:void 0,cause),code}function packageVersion(entry=Bun.main){let resolved=entry;try{resolved=realpathSync2(entry)}catch{}for(let dir=dirname2(resolved);;dir=dirname2(dir)){try{let{version}=JSON.parse(readFileSync4(join3(dir,"package.json"),"utf8"));if(typeof version==="string")return version}catch{}if(dirname2(dir)===dir)return"0.0.0"}}async function runMain({name,version,run,redact,usage},argv=scriptArgs()){let answered=await askpassClient(argv);if(answered!==void 0)return answered;if(argv[0]===COMPLETE)return printCandidates(leafCandidates(run,argv.slice(1)));if(argv[0]===COMPLETIONS||argv[0]?.startsWith(`${COMPLETIONS}=`)===!0)return printCompletionScript(name,flagValue(argv),printError);if(argv.length===1&&(argv[0]==="--version"||argv[0]==="-v"))return console.log(version??packageVersion()),0;let code,meta=!1,started=performance.now();heading.bin={name,version:()=>version??packageVersion()};try{code=await run(argv)}catch(error){meta=error instanceof HelpShown,code=reportThrown(name,error,redact,wantsJson(argv))}finally{heading.bin=void 0}if(notifyEnd(name,code,performance.now()-started),usage!==!1&&!meta)try{recordUsage(usageEntry(name,void 0,argv,code,{ms:performance.now()-started,mode:outputMode()}))}catch{}return code}import{existsSync,statSync as statSync2}from"fs";import{homedir as homedir3}from"os";import{basename,dirname as dirname3,join as join4,relative,resolve as resolve2}from"path";import process8 from"process";var SAFE_WORD=/^[\w@%+=:,./-]+$/;var SHELLS=new Set(["sh","bash","zsh","dash","ash","ksh","fish","csh","tcsh","nu","xonsh","elvish","pwsh","powershell"]),SCANNED_PROGRAMS=new Set(["su","runuser","flock"]),COMMAND_STRING_PROGRAMS=new Set([...SHELLS,...SCANNED_PROGRAMS]);function wrapper(short="",long=[],operands=0,runsString=!1){return{short,long,operands,runsString}}var RUNNER={...wrapper(),afterDashes:!0},WRAPPERS=new Map([["command",wrapper()],["builtin",wrapper()],["nohup",wrapper()],["setsid",wrapper()],["busybox",wrapper()],["exec",wrapper("a")],["time",wrapper("fo",["--format","--output"])],["env",wrapper("uCS",["--unset","--chdir","--split-string","--argv0"])],["sudo",wrapper("ughpCTrtUDR",["--user","--group","--host","--prompt","--close-from","--command-timeout","--role","--type","--other-user","--chdir","--chroot"])],["doas",wrapper("uC")],["timeout",wrapper("sk",["--signal","--kill-after"],1)],["nice",wrapper("n",["--adjustment"])],["ionice",wrapper("cnpPu",["--class","--classdata","--pid","--pgid","--uid"])],["stdbuf",wrapper("ioe",["--input","--output","--error"])],["chroot",wrapper("",["--userspec","--groups"],1)],["watch",wrapper("n",["--interval"],0,!0)],["flock",wrapper("wE",["--timeout","--conflict-exit-code"],1)],["parallel",wrapper("jnNSaIPlLdTsC",["--jobs","--max-args","--max-replace-args","--sshlogin","--arg-file","--delimiter","--colsep"],0,!0)],["unbuffer",wrapper()],["systemd-run",wrapper("puEMH",["--property","--unit","--description","--slice","--setenv","--machine","--host","--uid","--gid","--working-directory","--nice","--service-type"])],["xargs",wrapper("IndsEaPL",["--max-args","--max-procs","--max-chars","--delimiter","--arg-file","--eof","--max-lines","--process-slot-var"])],["strace",wrapper("abeEIoOpPsSuUX",["--trace","--output","--attach","--string-limit","--user","--env","--columns","--trace-path","--signal","--status","--summary-sort-by","--summary-columns","--const-print-style","--interruptible","--detach-on"])],["ltrace",wrapper("aeFlnopsuxX",["--output","--user","--library","--config","--align","--indent"])],["taskset",wrapper("",[],1)],["fakeroot",wrapper("lsib",["--lib","--faked"])],["sshpass",wrapper("pfdP")],["coproc",wrapper()],["proxychains",wrapper("f")],["proxychains4",wrapper("f")],["torsocks",wrapper("upaP",["--user","--pass","--address","--port"])],["chrt",wrapper("TPD",["--sched-runtime","--sched-period","--sched-deadline"],1)],["unshare",wrapper("SGRw",["--setuid","--setgid","--root","--wd","--map-user","--map-group","--map-users","--map-groups","--propagation","--setgroups"])],["nsenter",wrapper("tSG",["--target","--setuid","--setgid"])],["out",RUNNER],["slot",RUNNER],["waitfor",RUNNER],["base",RUNNER]]);function shellQuote(word){return SAFE_WORD.test(word)&&!word.startsWith("=")?word:`'${word.replaceAll("'","'\\''")}'`}var COMPOSE_FILES=["compose.yaml","compose.yml","docker-compose.yaml","docker-compose.yml"],OVERRIDE_FILES=["compose.override.yaml","compose.override.yml","docker-compose.override.yaml","docker-compose.override.yml"],PS_TIMEOUT_MS=20000;var VARIABLE=/\$\{(\w+)(?::?-([^${}]*))?\}|\$(\w+)/g,ENV_LINE=/^\s*(?:export\s+)?(\w+)=(.*)$/,QUOTED=/^(['"])(.*)\1$/,TOOL_WORDS={bun:["bun"],bunx:["bun"],node:["node","bun"],npm:["node","bun"],npx:["node","bun"],pnpm:["node","bun"],yarn:["node","bun"],composer:["php"],php:["php"],phpunit:["php"],phpstan:["php"],paratest:["php"],pest:["php"],symfony:["php"],python:["python"],python3:["python"],pytest:["python"],ruff:["python"],uv:["python"],go:["go","golang"],cargo:["rust"],deno:["deno"]};function toolWords(program){let name=basename(program);return TOOL_WORDS[name]??(program.includes("vendor/bin/")?["php"]:[])}async function readFiles(dir,names){for(let name of names){let handle=Bun.file(join4(dir,name));if(await handle.exists())return{name,text:await handle.text()}}return}async function variables(composeDir){let env={},text=(await readFiles(composeDir,[".env"]))?.text??"";for(let line of text.split(`
|
|
65
|
-
`)){let match=ENV_LINE.exec(line);if(match!==null&&!line.trimStart().startsWith("#"))env[match[1]??""]=(match[2]??"").trim().replace(QUOTED,"$2")}for(let[key,value]of Object.entries(process8.env))if(value!==void 0)env[key]=value;return env.PWD=composeDir,env}function interpolate(text,env){let current=text;for(let round=0;round<4&¤t.includes("$");round++)current=current.replaceAll(VARIABLE,(_,braced,fallback,bare)=>{let value=env[braced??bare??""];return value!==void 0&&value!==""?value:fallback??""});return current}function bindSource(source,composeDir,env){let path=interpolate(source,env);if(path.startsWith("~"))return join4(homedir3(),path.slice(1));if(path.startsWith("/"))return resolve2(path);return path.startsWith(".")?resolve2(composeDir,path):void 0}function mountsOf(volumes,composeDir,env){if(!Array.isArray(volumes))return[];let mounts=[];for(let volume of volumes){let source,target;if(typeof volume==="string")[source,target]=interpolate(volume,env).split(":");else if(typeof volume==="object"&&volume!==null){let object=volume;if(object.type==="bind"&&typeof object.source==="string"&&typeof object.target==="string")({source,target}=object)}let resolved=source===void 0?void 0:bindSource(source,composeDir,env);if(resolved!==void 0&&target?.startsWith("/")===!0)mounts.push({source:resolved,target})}return mounts}function buildText(build){if(typeof build==="string")return build;return typeof build==="object"&&build!==null?Object.values(build).filter((value)=>typeof value==="string").join(" "):""}function parseServices(text,composeDir,env){let services=new Map,parsed=Bun.YAML.parse(text);for(let[name,service]of Object.entries(parsed?.services??{}))if(service!==null&&typeof service==="object")services.set(name,{...service,mounts:mountsOf(service.volumes,composeDir,env)});return services}async function composeFiles(composeDir,env){let listed=env.COMPOSE_FILE;if(listed!==void 0&&listed!==""){let files=[],separator=env.COMPOSE_PATH_SEPARATOR;for(let name of listed.split(separator===void 0||separator===""?":":separator).filter((entry)=>entry!=="")){let file=Bun.file(resolve2(composeDir,name));if(!await file.exists())fail(`COMPOSE_FILE names ${join4(composeDir,name)}, which does not exist`,1,"fix COMPOSE_FILE, or run on the host with --host");files.push({name,text:await file.text()})}return files}let base=await readFiles(composeDir,COMPOSE_FILES);if(base===void 0)return[];let override=await readFiles(composeDir,OVERRIDE_FILES);return override===void 0?[base]:[base,override]}async function readServices(composeDir){let env=await variables(composeDir),files=await composeFiles(composeDir,env);if(files.length===0)return;let services=new Map;for(let file of files){let parsed;try{parsed=parseServices(file.text,composeDir,env)}catch(error){fail(`cannot read ${join4(composeDir,file.name)}: ${error instanceof Error?error.message:String(error)}`,1,"fix the file, or run on the host with --host")}for(let[name,extra]of parsed){let known=services.get(name);services.set(name,known===void 0?extra:{...known,...extra,mounts:[...known.mounts,...extra.mounts],image:extra.image??known.image,build:extra.build??known.build})}}return[...services].map(([name,service])=>({name,mounts:service.mounts,profile:`${name} ${typeof service.image==="string"?service.image:""} ${buildText(service.build)}`.toLowerCase()}))}function climb(dir){let folders=[dir],current=dir;while(!existsSync(join4(current,".git"))&&dirname3(current)!==current)current=dirname3(current),folders.push(current);return existsSync(join4(current,".git"))?folders:[dir]}function containerPath(service,dir){let deepest=service.mounts.filter((mount)=>{let inside=relative(mount.source,dir);return!inside.startsWith("..")&&!inside.startsWith("/")}).toSorted((a,b)=>b.source.length-a.source.length)[0];if(deepest===void 0)return;let inside=relative(deepest.source,dir);return inside===""?deepest.target:join4(deepest.target,inside)}var noticed=new Set;async function place(dir,program,{service,host}={}){if(host===!0)return;let found;for(let composeDir of climb(dir)){let services=await readServices(composeDir),mounting=(services??[]).filter((candidate)=>containerPath(candidate,dir)!==void 0);if(services!==void 0&&(mounting.length>0||services.some((candidate)=>candidate.name===service))){found={composeDir,services,mounting};break}}if(found===void 0){if(service!==void 0)fail(`--in ${service}: no compose project mounts ${dir}`);return}if(Bun.which("docker",{PATH:process8.env.PATH??""})===null){if(service!==void 0)fail(`--in ${service}: docker not found`);if(!noticed.has(found.composeDir))noticed.add(found.composeDir),warn(`host, docker not found: the compose project in ${found.composeDir} is not reached`);return}let chosen=choose(found.mounting,found.services,dir,program,service);return{service:chosen.name,composeDir:found.composeDir,workdir:containerPath(chosen,dir)??dir}}function choose(mounting,services,dir,program,service){if(service!==void 0){let named=mounting.find((candidate)=>candidate.name===service);if(named===void 0)fail(`--in ${service}: ${services.some((candidate)=>candidate.name===service)?`the service does not mount ${dir}`:`no such service, found ${services.map((candidate)=>candidate.name).join(", ")}`}`);return named}let[only]=mounting;if(mounting.length===1&&only!==void 0)return only;let words=toolWords(program),fitting=mounting.filter((candidate)=>words.some((word)=>candidate.profile.includes(word))),[fit]=fitting;if(fitting.length!==1||fit===void 0)fail(`${mounting.map((candidate)=>candidate.name).join(", ")} all mount ${dir} and none stands out for ${basename(program)}: pick one with --in <service>, or run on the host with --host`);return fit}function execArgv(placement,argv,env){let variables=Object.entries({NO_COLOR:"1",FORCE_COLOR:"0",...env}).flatMap(([name,value])=>["-e",`${name}=${value}`]);return["docker","compose","exec","-T","-w",placement.workdir,...variables,placement.service,...argv]}function shellIn(placement,command,env={}){return`cd ${shellQuote(placement.composeDir)} && ${execArgv(placement,["sh","-c",command],env).map((word)=>shellQuote(word)).join(" ")}`}function argvIn(placement,argv,env={}){return execArgv(placement,argv,env)}class Stack{answers=new Map;async ask(composeDir){let answer=this.answers.get(composeDir);if(answer===void 0)answer=Stack.running(composeDir),this.answers.set(composeDir,answer);return answer}static async running(composeDir){try{let ran=await runCommand(["docker","compose","ps","--services","--status","running"],{cwd:composeDir,env:process8.env,timeoutMs:PS_TIMEOUT_MS});if(ran.code!==0)return`docker compose ps failed in ${composeDir}: ${ran.text.trim().split(`
|
|
65
|
+
`)){let match=ENV_LINE.exec(line);if(match!==null&&!line.trimStart().startsWith("#"))env[match[1]??""]=(match[2]??"").trim().replace(QUOTED,"$2")}for(let[key,value]of Object.entries(process8.env))if(value!==void 0)env[key]=value;return env.PWD=composeDir,env}function interpolate(text,env){let current=text;for(let round=0;round<4&¤t.includes("$");round++)current=current.replaceAll(VARIABLE,(_,braced,fallback,bare)=>{let value=env[braced??bare??""];return value!==void 0&&value!==""?value:fallback??""});return current}function bindSource(source,composeDir,env){let path=interpolate(source,env);if(path.startsWith("~"))return join4(homedir3(),path.slice(1));if(path.startsWith("/"))return resolve2(path);return path.startsWith(".")?resolve2(composeDir,path):void 0}function mountsOf(volumes,composeDir,env){if(!Array.isArray(volumes))return[];let mounts=[];for(let volume of volumes){let source,target;if(typeof volume==="string")[source,target]=interpolate(volume,env).split(":");else if(typeof volume==="object"&&volume!==null){let object=volume;if(object.type==="bind"&&typeof object.source==="string"&&typeof object.target==="string")({source,target}=object)}let resolved=source===void 0?void 0:bindSource(source,composeDir,env);if(resolved!==void 0&&target?.startsWith("/")===!0)mounts.push({source:resolved,target})}return mounts}function buildText(build){if(typeof build==="string")return build;return typeof build==="object"&&build!==null?Object.values(build).filter((value)=>typeof value==="string").join(" "):""}function parseServices(text,composeDir,env){let services=new Map,parsed=Bun.YAML.parse(text);for(let[name,service]of Object.entries(parsed?.services??{}))if(service!==null&&typeof service==="object")services.set(name,{...service,mounts:mountsOf(service.volumes,composeDir,env)});return services}async function composeFiles(composeDir,env){let listed=env.COMPOSE_FILE;if(listed!==void 0&&listed!==""){let files=[],separator=env.COMPOSE_PATH_SEPARATOR;for(let name of listed.split(separator===void 0||separator===""?":":separator).filter((entry)=>entry!=="")){let file=Bun.file(resolve2(composeDir,name));if(!await file.exists())fail(`COMPOSE_FILE names ${join4(composeDir,name)}, which does not exist`,1,"fix COMPOSE_FILE, or run on the host with --host");files.push({name,text:await file.text()})}return files}let base=await readFiles(composeDir,COMPOSE_FILES);if(base===void 0)return[];let override=await readFiles(composeDir,OVERRIDE_FILES);return override===void 0?[base]:[base,override]}async function readServices(composeDir){let env=await variables(composeDir),files=await composeFiles(composeDir,env);if(files.length===0)return;let services=new Map;for(let file of files){let parsed;try{parsed=parseServices(file.text,composeDir,env)}catch(error){fail(`cannot read ${join4(composeDir,file.name)}: ${error instanceof Error?error.message:String(error)}`,1,"fix the file, or run on the host with --host")}for(let[name,extra]of parsed){let known=services.get(name);services.set(name,known===void 0?extra:{...known,...extra,mounts:[...known.mounts,...extra.mounts],image:extra.image??known.image,build:extra.build??known.build})}}return[...services].map(([name,service])=>({name,mounts:service.mounts,profile:`${name} ${typeof service.image==="string"?service.image:""} ${buildText(service.build)}`.toLowerCase()}))}function climb(dir){let folders=[dir],current=dir;while(!existsSync(join4(current,".git"))&&dirname3(current)!==current)current=dirname3(current),folders.push(current);return existsSync(join4(current,".git"))?folders:[dir]}function containerPath(service,dir){let deepest=service.mounts.filter((mount)=>{let inside=relative(mount.source,dir);return!inside.startsWith("..")&&!inside.startsWith("/")}).toSorted((a,b)=>b.source.length-a.source.length)[0];if(deepest===void 0)return;let inside=relative(deepest.source,dir);return inside===""?deepest.target:join4(deepest.target,inside)}var ORCHESTRATORS=new Set(["make","just","task","mise"]),noticed=new Set;async function place(dir,program,{service,host}={}){if(host===!0||service===void 0&&ORCHESTRATORS.has(basename(program)))return;let found;for(let composeDir of climb(dir)){let services=await readServices(composeDir),mounting=(services??[]).filter((candidate)=>containerPath(candidate,dir)!==void 0);if(services!==void 0&&(mounting.length>0||services.some((candidate)=>candidate.name===service))){found={composeDir,services,mounting};break}}if(found===void 0){if(service!==void 0)fail(`--in ${service}: no compose project mounts ${dir}`);return}if(Bun.which("docker",{PATH:process8.env.PATH??""})===null){if(service!==void 0)fail(`--in ${service}: docker not found`);if(!noticed.has(found.composeDir))noticed.add(found.composeDir),warn(`host, docker not found: the compose project in ${found.composeDir} is not reached`);return}let chosen=choose(found.mounting,found.services,dir,program,service);return{service:chosen.name,composeDir:found.composeDir,workdir:containerPath(chosen,dir)??dir}}function choose(mounting,services,dir,program,service){if(service!==void 0){let named=mounting.find((candidate)=>candidate.name===service);if(named===void 0)fail(`--in ${service}: ${services.some((candidate)=>candidate.name===service)?`the service does not mount ${dir}`:`no such service, found ${services.map((candidate)=>candidate.name).join(", ")}`}`);return named}let[only]=mounting;if(mounting.length===1&&only!==void 0)return only;let words=toolWords(program),fitting=mounting.filter((candidate)=>words.some((word)=>candidate.profile.includes(word))),[fit]=fitting;if(fitting.length!==1||fit===void 0)fail(`${mounting.map((candidate)=>candidate.name).join(", ")} all mount ${dir} and none stands out for ${basename(program)}: pick one with --in <service>, or run on the host with --host`);return fit}function execArgv(placement,argv,env){let variables=Object.entries({NO_COLOR:"1",FORCE_COLOR:"0",...env}).flatMap(([name,value])=>["-e",`${name}=${value}`]);return["docker","compose","exec","-T","-w",placement.workdir,...variables,placement.service,...argv]}function shellIn(placement,command,env={}){return`cd ${shellQuote(placement.composeDir)} && ${execArgv(placement,["sh","-c",command],env).map((word)=>shellQuote(word)).join(" ")}`}function argvIn(placement,argv,env={}){return execArgv(placement,argv,env)}class Stack{answers=new Map;async ask(composeDir){let answer=this.answers.get(composeDir);if(answer===void 0)answer=Stack.running(composeDir),this.answers.set(composeDir,answer);return answer}static async running(composeDir){try{let ran=await runCommand(["docker","compose","ps","--services","--status","running"],{cwd:composeDir,env:process8.env,timeoutMs:PS_TIMEOUT_MS});if(ran.code!==0)return`docker compose ps failed in ${composeDir}: ${ran.text.trim().split(`
|
|
66
66
|
`).at(-1)??`exit ${ran.code}`}`;return ran.text.split(`
|
|
67
67
|
`).map((line)=>line.trim()).filter((line)=>line!=="")}catch(error){return`cannot run docker compose in ${composeDir}: ${error instanceof Error?error.message:String(error)}`}}async problem(placement){let answer=await this.ask(placement.composeDir);if(typeof answer==="string")return answer;return answer.includes(placement.service)?void 0:`the ${placement.service} service is not running (compose project in ${placement.composeDir}): start it yourself, or run on the host with --host`}}function programOf(command){let end=command.indexOf(" ");return end===-1?command:command.slice(0,end)}async function composeServiceCandidates(){try{return(await readServices(process8.cwd()))?.map((service)=>service.name)??[]}catch{return[]}}var placeOptions={in:{type:"string",description:"run in this compose service instead of the one found mounting the folder",candidates:composeServiceCandidates},host:{type:"boolean",description:"run on the host even when a compose service mounts the folder"}};function placeSettings(values){if(values.in!==void 0&&values.host===!0)fail("--in and --host exclude each other");return{service:values.in,host:values.host}}var BASH_ECHO=/^\$ /,DURATION=/ \[[\d.]+m?s\]$/,BOUNDARY=/^(?:\((?:pass|fail|skip|todo)\) |\S+\.test\.[jt]sx?:$)/,BUN_TEST_SUMMARY=/^\s*\d+ (?:pass|fail|skip|todo)$|^Ran \d+ tests?/,BUN_CHECK_BLOCK=/<error file=[\s\S]*?<\/error>/g,BUN_CHECK_SOURCE=/<source>[\s\S]*?<\/source>\n?/g,BUN_CHECK_ATTRIBUTE=/(\w+)="([^"]*)"/g,BUN_CHECK_SUMMARY=/^Found \d+ errors?/,TSC_ERROR=/\berror TS\d+/,TSC_CONTINUATION=/^\s{2,}\S/,TSC_FRAME=/^\s*[~^|]/,TSC_SUMMARY=/^Found \d+ errors?/,ESLINT_PROBLEM=/^\s+\d+:\d+\s+(?:error|warning)\s/,ESLINT_SUMMARY=/^(?:\u2716 )?\d+ problems? \(/,PHPSTAN_TABLE=/^\s*-{3,} -{3,}/,PHPSTAN_NOISE=/^\s*\[OK\]/,PHP_FAILURES=/^(?:There w(?:as|ere) \d+ (?:failure|error|risky|warning)|\s+(?:FAIL|FAILED)\s+\S|In \S+\.php line \d+:$)/,VITEST_FAIL_LINE=/^ FAIL {2}\S/,PLAYWRIGHT_FAIL_LINE=/^ {2}1\) .+:\d+:\d+ \u203A .+ \u2500+$/,CS_FIXER_LINE=/^\s+\d+\) \S.*\.php(?: \(.+\))?$/,CS_FIXER_TOTAL=/^Found \d+ of \d+ files/,MAX_TESTS=10,MAX_LINES=100,TAIL=30,bunTest=(lines)=>{let seen=new Set,blocks=[];for(let[index,line]of lines.entries()){let name=line.replace(DURATION,"");if(!line.startsWith("(fail) ")||seen.has(name))continue;if(seen.add(name),blocks.length<MAX_TESTS)blocks.push(lines.slice(lines.findLastIndex((text,at)=>at<index&&BOUNDARY.test(text))+1,index+1).join(`
|
|
68
68
|
`).trim())}if(blocks.length===0)return;if(seen.size>MAX_TESTS)blocks.push(`and ${seen.size-MAX_TESTS} more failed tests`);return[...blocks.join(`
|
|
@@ -75,5 +75,5 @@ __kaynooo_cli_bins+=(${bins.join(" ")})
|
|
|
75
75
|
`).trim()}}var tsc=(lines)=>{let kept=[],inError=!1;for(let line of lines)if(TSC_ERROR.test(line))inError=!0,kept.push(line);else if(TSC_SUMMARY.test(line))inError=!1,kept.push(line);else if(inError&&TSC_CONTINUATION.test(line)&&!TSC_FRAME.test(line))kept.push(line);else inError=!1;return kept.some((line)=>TSC_ERROR.test(line))?kept:void 0},eslint=(lines)=>{let kept=[],file="",shown="";for(let line of lines)if(ESLINT_PROBLEM.test(line)){if(file!==shown)kept.push(file),shown=file;kept.push(line)}else if(ESLINT_SUMMARY.test(line))kept.push(line);else if(line.trim()!=="")file=line;return kept.some((line)=>ESLINT_PROBLEM.test(line))?kept:void 0},phpstan=(lines)=>{let start=lines.findIndex((line)=>PHPSTAN_TABLE.test(line));return start===-1?void 0:lines.slice(start).filter((line)=>!PHPSTAN_NOISE.test(line))},php=(lines)=>{let start=lines.findIndex((line)=>PHP_FAILURES.test(line));return start===-1?void 0:lines.slice(start)},vitest=(lines)=>{let start=lines.findIndex((line)=>VITEST_FAIL_LINE.test(line));return start===-1?void 0:lines.slice(start)},playwright=(lines)=>{let start=lines.findIndex((line)=>PLAYWRIGHT_FAIL_LINE.test(line));return start===-1?void 0:lines.slice(start)},phpCsFixer=(lines)=>{let files=lines.filter((line)=>CS_FIXER_LINE.test(line)||CS_FIXER_TOTAL.test(line));return files.some((line)=>CS_FIXER_LINE.test(line))?files:void 0},PARSERS=[bunTest,bunCheck,tsc,eslint,vitest,playwright,phpCsFixer,phpstan,php];function squeeze(lines){let out=[];for(let line of lines.map((text)=>text.trimEnd()))if(line!==""||out.at(-1)!=="")out.push(line);while(out.at(-1)==="")out.pop();return out}function cut(shown){return shown.length>MAX_LINES?[...shown.slice(0,MAX_LINES),`... ${shown.length-MAX_LINES} more lines`].join(`
|
|
76
76
|
`):shown.join(`
|
|
77
77
|
`)}function recognised(lines,parsers){return parsers.map((parser)=>parser(lines)).find((result)=>result!==void 0&&result.some((line)=>line.trim()!==""))}function failureExcerpt(output){let lines=stripAnsi(output).split(`
|
|
78
|
-
`);if(BASH_ECHO.test(lines[0]??""))lines.shift();return cut(squeeze(recognised(lines,PARSERS)??lines.slice(-TAIL)))}var LOG_PATTERNS={BASH_ECHO,DURATION,BOUNDARY,BUN_TEST_SUMMARY,BUN_CHECK_SUMMARY,TSC_CONTINUATION,TSC_FRAME,TSC_SUMMARY,ESLINT_PROBLEM,ESLINT_SUMMARY};var{Glob}=globalThis.Bun;var SESSION_FILES=new Glob("*.json"),ACCOUNT_DIRS=new Glob("*/sessions");import{basename as basename2,dirname as dirname4,join as join5,relative as relative2,sep}from"path";var PARENT=`..${sep}`;var version="0.
|
|
78
|
+
`);if(BASH_ECHO.test(lines[0]??""))lines.shift();return cut(squeeze(recognised(lines,PARSERS)??lines.slice(-TAIL)))}var LOG_PATTERNS={BASH_ECHO,DURATION,BOUNDARY,BUN_TEST_SUMMARY,BUN_CHECK_SUMMARY,TSC_CONTINUATION,TSC_FRAME,TSC_SUMMARY,ESLINT_PROBLEM,ESLINT_SUMMARY};var{Glob}=globalThis.Bun;var SESSION_FILES=new Glob("*.json"),ACCOUNT_DIRS=new Glob("*/sessions");import{basename as basename2,dirname as dirname4,join as join5,relative as relative2,sep}from"path";var PARENT=`..${sep}`;var version="0.24.1";
|
|
79
79
|
export{exitCodeOf,holdSignals,runCommand,privateLogDirectory,sweepLogs,runMain,shellQuote,place,shellIn,argvIn,Stack,programOf,placeOptions,placeSettings,bunCheckFields,failureExcerpt,LOG_PATTERNS,version};
|
|
@@ -1,5 +1,5 @@
|
|
|
1
1
|
// @bun
|
|
2
|
-
import{warn,fail,ignoredFolders}from"./chunk-ngcnmctk.js";import{runCommand}from"./chunk-8wyt4whk.js";import{existsSync as existsSync2,readdirSync,readFileSync as readFileSync2}from"fs";import{dirname,join as join2,resolve as resolvePath}from"path";import{existsSync,readFileSync}from"fs";import{readdir}from"fs/promises";import{basename,join,relative,resolve as resolve2}from"path";var STEP_NAMES=["check","typecheck","lint","fmt","test"],STEP_SOURCES={fmt:["fmt:check","format:check","fmt-check","format-check"]},TARGET=/^@?([\w-]+)(?:[ \t][^:=\n]*)?:(?!=)/gm,JUSTFILES=["justfile","Justfile",".justfile"],TASKFILES=["Taskfile.yml","taskfile.yml","Taskfile.yaml","taskfile.yaml","Taskfile.dist.yml","taskfile.dist.yml","Taskfile.dist.yaml","taskfile.dist.yaml"],DENO_FILES=["deno.json","deno.jsonc"],MISE_FILES=["mise.toml",".mise.toml",".config/mise.toml"],CHECKRC_FILES=[".checkrc.jsonc",".checkrc.json"],TASK_RUNNERS=new Set(["Justfile","Makefile","Taskfile","mise"]),MAKEFILES=["GNUmakefile","makefile","Makefile"],CS_FIXER_CONFIGS=[".php-cs-fixer.php",".php-cs-fixer.dist.php"],JUST_TIMEOUT_MS=1e4,PHPSTAN_CONFIGS=["phpstan.neon","phpstan.neon.dist","phpstan.dist.neon"],PHPUNIT_CONFIGS=["phpunit.xml","phpunit.xml.dist","phpunit.dist.xml"],RUFF_CONFIGS=["ruff.toml",".ruff.toml"],PYTEST_CONFIGS=["pytest.ini","conftest.py"],MYPY_CONFIGS=["mypy.ini",".mypy.ini"],RUFF_SECTION=/^\[tool\.ruff/m,PYTEST_SECTION=/^\[tool\.pytest/m,MYPY_SECTION=/^\[tool\.mypy/m;async function readFirst(dir,files){for(let file of files){let handle=Bun.file(join(dir,file));if(await handle.exists())return{file,text:await handle.text()}}return}async function read(dir,...files){for(let file of files){let handle=Bun.file(join(dir,file));if(await handle.exists())return handle.text()}return}async function loadCheckConfig(dir){let found=await readFirst(dir,CHECKRC_FILES);if(found===void 0)return;try{let parsed=Bun.JSONC.parse(found.text);if(parsed===null||typeof parsed!=="object"||Array.isArray(parsed))fail(`${found.file} must be a JSON object`);return parsed}catch(error){fail(`${found.file} is not valid JSONC: ${error instanceof Error?error.message:String(error)}`)}}function parseJsonManifest(file,text){try{let parsed=JSON.parse(text);return parsed!==null&&typeof parsed==="object"?parsed:{}}catch{fail(`${file} is not valid JSON`)}}function scriptsOf(manifest){let value=manifest.scripts;return value!==null&&typeof value==="object"?value:{}}function targets(text){return[...text.matchAll(TARGET)].map((match)=>match[1]??"")}async function recipes(dir,file,text){if(Bun.which("just")===null)return targets(text);try{let ran=await runCommand(["just","--justfile",file,"--dump","--dump-format","json"],{cwd:dir,timeoutMs:JUST_TIMEOUT_MS}),dump=JSON.parse(ran.text);if(ran.code!==0)return targets(text);return Object.entries(dump.recipes??{}).filter(([,recipe])=>recipe.private!==!0&&(recipe.parameters??[]).every((parameter)=>parameter.default!==null||parameter.kind==="star")).map(([name])=>name)}catch{return targets(text)}}async function miseTasks(dir){if(Bun.which("mise")===null||!MISE_FILES.some((name)=>existsSync(join(dir,name))))return[];try{let ran=await runCommand(["mise","tasks","ls","--json"],{cwd:dir,timeoutMs:JUST_TIMEOUT_MS});if(ran.code!==0)return[];let root=`${resolve2(dir)}/`;return JSON.parse(ran.text).filter((task)=>!task.hide&&!task.global&&task.source.startsWith(root)).map((task)=>task.name)}catch{return[]}}function callsSelf(value,bin){return typeof value==="string"&&(value===bin||value.startsWith(`${bin} `)||value.startsWith(`${bin} `))}async function candidates(dir,bin,includeNative=!1){let steps=[],packageJson=await read(dir,"package.json"),composerJson=await read(dir,"composer.json"),denoFile=await readFirst(dir,DENO_FILES),justfile=await readFirst(dir,JUSTFILES),makefile=await read(dir,...MAKEFILES),taskfile=await readFirst(dir,TASKFILES),pyprojectText=await read(dir,"pyproject.toml");if(packageJson!==void 0){let manifest=parseJsonManifest("package.json",packageJson),tool=manager(dir,manifest);for(let[name,value]of Object.entries(scriptsOf(manifest)))if(!callsSelf(value,bin))steps.push({name,command:`${tool} run ${name}`,source:"package.json"})}if(composerJson!==void 0){let manifest=parseJsonManifest("composer.json",composerJson);for(let name of Object.keys(scriptsOf(manifest)))steps.push({name,command:`composer run ${name}`,source:"composer.json"})}if(denoFile!==void 0)try{let parsed=Bun.JSONC.parse(denoFile.text);for(let name of Object.keys(parsed?.tasks??{}))steps.push({name,command:`deno task ${name}`,source:denoFile.file})}catch{}if(justfile!==void 0)for(let name of await recipes(dir,justfile.file,justfile.text))steps.push({name,command:`just ${name}`,source:"Justfile"});for(let name of targets(makefile??""))steps.push({name,command:`make ${name}`,source:"Makefile"});if(taskfile!==void 0)try{let parsed=Bun.YAML.parse(taskfile.text);for(let[name,task]of Object.entries(parsed?.tasks??{}))if(!(task!==null&&typeof task==="object"&&task.internal===!0))steps.push({name,command:`task ${name}`,source:"Taskfile"})}catch{}for(let name of await miseTasks(dir))steps.push({name,command:`mise run ${name}`,source:"mise"});if(pyprojectText!==void 0)try{let parsed=Bun.TOML.parse(pyprojectText),runner=existsSync(join(dir,"uv.lock"))?"uv run poe":"poe";for(let name of Object.keys(parsed.tool?.poe?.tasks??{}))if(!name.startsWith("_"))steps.push({name,command:`${runner} ${name}`,source:"pyproject.toml"})}catch{}if(steps.push(...await phpSteps(dir)),includeNative)steps.push(...await nativeSteps(dir,pyprojectText));return steps}async function firstFile(dir,names){for(let name of names)if(await Bun.file(join(dir,name)).exists())return name;return}async function phpSteps(dir){let steps=[],phpstan=await firstFile(dir,PHPSTAN_CONFIGS),csFixer=await firstFile(dir,CS_FIXER_CONFIGS),phpunit=await firstFile(dir,PHPUNIT_CONFIGS);if(phpstan!==void 0)steps.push({name:"typecheck",command:"vendor/bin/phpstan analyse --no-progress --memory-limit=1G",source:phpstan});if(csFixer!==void 0)steps.push({name:"lint",command:"vendor/bin/php-cs-fixer fix --dry-run -v",source:csFixer});if(phpunit!==void 0)steps.push({name:"test",command:"vendor/bin/phpunit",source:phpunit});return steps}async function nativeSteps(dir,pyprojectText){let steps=[];if(existsSync(join(dir,"go.mod")))steps.push({name:"lint",command:"go vet ./...",source:"go.mod"}),steps.push({name:"test",command:"go test ./...",source:"go.mod"});if(existsSync(join(dir,"Cargo.toml")))steps.push({name:"check",command:"cargo check",source:"Cargo.toml"}),steps.push({name:"lint",command:"cargo clippy",source:"Cargo.toml"}),steps.push({name:"fmt:check",command:"cargo fmt -- --check",source:"Cargo.toml"}),steps.push({name:"test",command:"cargo test",source:"Cargo.toml"});let pyPrefix=existsSync(join(dir,"uv.lock"))?"uv run ":"",ruffFile=await firstFile(dir,RUFF_CONFIGS),hasRuff=ruffFile!==void 0||pyprojectText!==void 0&&RUFF_SECTION.test(pyprojectText),hasMypy=await firstFile(dir,MYPY_CONFIGS)!==void 0||pyprojectText!==void 0&&MYPY_SECTION.test(pyprojectText),hasPytest=await firstFile(dir,PYTEST_CONFIGS)!==void 0||pyprojectText!==void 0&&PYTEST_SECTION.test(pyprojectText);if(hasMypy)steps.push({name:"typecheck",command:`${pyPrefix}mypy .`,source:"mypy"});if(hasRuff){let source=ruffFile??"pyproject.toml";steps.push({name:"lint",command:`${pyPrefix}ruff check .`,source}),steps.push({name:"fmt:check",command:`${pyPrefix}ruff format --check .`,source})}if(hasPytest)steps.push({name:"test",command:`${pyPrefix}pytest`,source:"pytest"});return steps}function packageNameOf(dir){let file=join(dir,"package.json");if(!existsSync(file))return;try{let parsed=JSON.parse(readFileSync(file,"utf8"));return typeof parsed.name==="string"?parsed.name:void 0}catch{return}}async function resolveTargets(dir,targets){let known=folders(dir),projects=[],seen=new Set;for(let target of targets){let direct=resolve2(dir,target),matchedDir;if(existsSync(direct))matchedDir=direct;else{let hit=known.find((sub)=>sub===target||basename(sub)===target||packageNameOf(join(dir,sub))===target);if(hit!==void 0)matchedDir=join(dir,hit)}if(matchedDir===void 0)fail(`no path or workspace matching ${target}`);if(seen.has(matchedDir))continue;seen.add(matchedDir);let steps=await discover(matchedDir);if(steps.length===0)fail(`no check steps found in ${target}`);let rel=relative(dir,matchedDir);projects.push({...rel===""?{}:{name:rel},dir:matchedDir,steps})}return projects}async function discoverProjects(dir,targets){if(targets!==void 0&&targets.length>0)return resolveTargets(dir,targets);let own=await discover(dir);if(own.length>0)return[{dir,steps:own}];let projects=[],entries=await readdir(dir,{withFileTypes:!0}),ignored=ignoredFolders(["var","tmp"]),direct=entries.filter((entry)=>entry.isDirectory()&&!entry.name.startsWith(".")&&!ignored.has(entry.name)).map((entry)=>entry.name),subdirs=[...new Set([...direct,...workspaces(dir)])].filter((name)=>name!==".").toSorted((a,b)=>a.localeCompare(b));for(let sub of subdirs){let steps=await discover(join(dir,sub));if(steps.length>0)projects.push({name:sub,dir:join(dir,sub),steps})}return projects}async function discover(dir){let found=await candidates(dir,"check",!0),overrides=(await loadCheckConfig(dir))?.steps??{},runnerCheck=found.find((candidate)=>candidate.name==="check"&&TASK_RUNNERS.has(candidate.source)),base=STEP_NAMES.flatMap((name)=>{if(name in overrides){let custom=overrides[name];return custom===null||custom===void 0?[]:[{name,command:custom,source:".checkrc.json"}]}let step=name==="check"&&runnerCheck!==void 0?runnerCheck:(STEP_SOURCES[name]??[name]).map((each)=>found.find((candidate)=>candidate.name===each)).find((each)=>each!==void 0);return step===void 0?[]:[{...step,name}]});for(let[name,command]of Object.entries(overrides))if(!STEP_NAMES.includes(name)&&typeof command==="string"&&command!=="")base.push({name,command,source:".checkrc.json"});return base}var JUSTFILE=/^\.?justfile$/i,TASKFILES2=["Taskfile.yml","taskfile.yml","Taskfile.yaml","taskfile.yaml","Taskfile.dist.yml","taskfile.dist.yml","Taskfile.dist.yaml","taskfile.dist.yaml"],MISE_FILES2=["mise.toml",".mise.toml","mise.local.toml",".mise.local.toml","mise",".mise","mise-tasks",".mise-tasks",".config/mise.toml",".config/mise"],LOCKFILES=[["bun.lock","bun"],["bun.lockb","bun"],["pnpm-lock.yaml","pnpm"],["yarn.lock","yarn"],["package-lock.json","npm"]],QUALIFIED=/^([a-z]+):(?!:)(.+)$/,BLANKS=/\s+/,TRAILING_SLASHES=/\/+$/,VERSION_SUFFIX=/@.*/,LEADING_HASHES=/^#*/,INCLUDE=/^(?:-|s)?include[ \t]+([^#]+)/,GLOB_CHARS=/[*?[]/,installed=new Map;function has(tool){if(!installed.has(tool))installed.set(tool,Bun.which(tool)!==null);return installed.get(tool)}function list(dir){try{return readdirSync(dir)}catch{return[]}}function locate(dir,here,names){for(let current=dir;;current=join2(current,"..")){let found=names.find((name)=>existsSync2(join2(current,name)));if(found!==void 0)return join2(current,found);let absolute=resolvePath(current);if(!here||existsSync2(join2(current,".git"))||dirname(absolute)===absolute)return}}function children(dir="."){let ignored=ignoredFolders();return readdirSync(dir,{withFileTypes:!0}).filter((child)=>child.isDirectory()&&!child.name.startsWith(".")&&!ignored.has(child.name)).map((child)=>child.name).toSorted()}function build(base,items){return items.map((item)=>({...base,doc:null,parameters:[],...item}))}function text(value){if(typeof value==="string")return value;if(Array.isArray(value)&&value.every((line)=>typeof line==="string"))return value.join(`
|
|
2
|
+
import{warn,fail,ignoredFolders}from"./chunk-ngcnmctk.js";import{runCommand}from"./chunk-898e3vv3.js";import{existsSync as existsSync2,readdirSync,readFileSync as readFileSync2}from"fs";import{dirname,join as join2,resolve as resolvePath}from"path";import{existsSync,readFileSync}from"fs";import{readdir}from"fs/promises";import{basename,join,relative,resolve as resolve2}from"path";var STEP_NAMES=["check","typecheck","lint","fmt","test"],STEP_SOURCES={fmt:["fmt:check","format:check","fmt-check","format-check"]},TARGET=/^@?([\w-]+)(?:[ \t][^:=\n]*)?:(?!=)/gm,JUSTFILES=["justfile","Justfile",".justfile"],TASKFILES=["Taskfile.yml","taskfile.yml","Taskfile.yaml","taskfile.yaml","Taskfile.dist.yml","taskfile.dist.yml","Taskfile.dist.yaml","taskfile.dist.yaml"],DENO_FILES=["deno.json","deno.jsonc"],MISE_FILES=["mise.toml",".mise.toml",".config/mise.toml"],CHECKRC_FILES=[".checkrc.jsonc",".checkrc.json"],TASK_RUNNERS=new Set(["Justfile","Makefile","Taskfile","mise"]),MAKEFILES=["GNUmakefile","makefile","Makefile"],CS_FIXER_CONFIGS=[".php-cs-fixer.php",".php-cs-fixer.dist.php"],JUST_TIMEOUT_MS=1e4,PHPSTAN_CONFIGS=["phpstan.neon","phpstan.neon.dist","phpstan.dist.neon"],PHPUNIT_CONFIGS=["phpunit.xml","phpunit.xml.dist","phpunit.dist.xml"],RUFF_CONFIGS=["ruff.toml",".ruff.toml"],PYTEST_CONFIGS=["pytest.ini","conftest.py"],MYPY_CONFIGS=["mypy.ini",".mypy.ini"],RUFF_SECTION=/^\[tool\.ruff/m,PYTEST_SECTION=/^\[tool\.pytest/m,MYPY_SECTION=/^\[tool\.mypy/m;async function readFirst(dir,files){for(let file of files){let handle=Bun.file(join(dir,file));if(await handle.exists())return{file,text:await handle.text()}}return}async function read(dir,...files){for(let file of files){let handle=Bun.file(join(dir,file));if(await handle.exists())return handle.text()}return}async function loadCheckConfig(dir){let found=await readFirst(dir,CHECKRC_FILES);if(found===void 0)return;try{let parsed=Bun.JSONC.parse(found.text);if(parsed===null||typeof parsed!=="object"||Array.isArray(parsed))fail(`${found.file} must be a JSON object`);return parsed}catch(error){fail(`${found.file} is not valid JSONC: ${error instanceof Error?error.message:String(error)}`)}}function parseJsonManifest(file,text){try{let parsed=JSON.parse(text);return parsed!==null&&typeof parsed==="object"?parsed:{}}catch{fail(`${file} is not valid JSON`)}}function scriptsOf(manifest){let value=manifest.scripts;return value!==null&&typeof value==="object"?value:{}}function targets(text){return[...text.matchAll(TARGET)].map((match)=>match[1]??"")}async function recipes(dir,file,text){if(Bun.which("just")===null)return targets(text);try{let ran=await runCommand(["just","--justfile",file,"--dump","--dump-format","json"],{cwd:dir,timeoutMs:JUST_TIMEOUT_MS}),dump=JSON.parse(ran.text);if(ran.code!==0)return targets(text);return Object.entries(dump.recipes??{}).filter(([,recipe])=>recipe.private!==!0&&(recipe.parameters??[]).every((parameter)=>parameter.default!==null||parameter.kind==="star")).map(([name])=>name)}catch{return targets(text)}}async function miseTasks(dir){if(Bun.which("mise")===null||!MISE_FILES.some((name)=>existsSync(join(dir,name))))return[];try{let ran=await runCommand(["mise","tasks","ls","--json"],{cwd:dir,timeoutMs:JUST_TIMEOUT_MS});if(ran.code!==0)return[];let root=`${resolve2(dir)}/`;return JSON.parse(ran.text).filter((task)=>!task.hide&&!task.global&&task.source.startsWith(root)).map((task)=>task.name)}catch{return[]}}function callsSelf(value,bin){return typeof value==="string"&&(value===bin||value.startsWith(`${bin} `)||value.startsWith(`${bin} `))}async function candidates(dir,bin,includeNative=!1){let steps=[],packageJson=await read(dir,"package.json"),composerJson=await read(dir,"composer.json"),denoFile=await readFirst(dir,DENO_FILES),justfile=await readFirst(dir,JUSTFILES),makefile=await read(dir,...MAKEFILES),taskfile=await readFirst(dir,TASKFILES),pyprojectText=await read(dir,"pyproject.toml");if(packageJson!==void 0){let manifest=parseJsonManifest("package.json",packageJson),tool=manager(dir,manifest);for(let[name,value]of Object.entries(scriptsOf(manifest)))if(!callsSelf(value,bin))steps.push({name,command:`${tool} run ${name}`,source:"package.json"})}if(composerJson!==void 0){let manifest=parseJsonManifest("composer.json",composerJson);for(let name of Object.keys(scriptsOf(manifest)))steps.push({name,command:`composer run ${name}`,source:"composer.json"})}if(denoFile!==void 0)try{let parsed=Bun.JSONC.parse(denoFile.text);for(let name of Object.keys(parsed?.tasks??{}))steps.push({name,command:`deno task ${name}`,source:denoFile.file})}catch{}if(justfile!==void 0)for(let name of await recipes(dir,justfile.file,justfile.text))steps.push({name,command:`just ${name}`,source:"Justfile"});for(let name of targets(makefile??""))steps.push({name,command:`make ${name}`,source:"Makefile"});if(taskfile!==void 0)try{let parsed=Bun.YAML.parse(taskfile.text);for(let[name,task]of Object.entries(parsed?.tasks??{}))if(!(task!==null&&typeof task==="object"&&task.internal===!0))steps.push({name,command:`task ${name}`,source:"Taskfile"})}catch{}for(let name of await miseTasks(dir))steps.push({name,command:`mise run ${name}`,source:"mise"});if(pyprojectText!==void 0)try{let parsed=Bun.TOML.parse(pyprojectText),runner=existsSync(join(dir,"uv.lock"))?"uv run poe":"poe";for(let name of Object.keys(parsed.tool?.poe?.tasks??{}))if(!name.startsWith("_"))steps.push({name,command:`${runner} ${name}`,source:"pyproject.toml"})}catch{}if(steps.push(...await phpSteps(dir)),includeNative)steps.push(...await nativeSteps(dir,pyprojectText));return steps}async function firstFile(dir,names){for(let name of names)if(await Bun.file(join(dir,name)).exists())return name;return}async function phpSteps(dir){let steps=[],phpstan=await firstFile(dir,PHPSTAN_CONFIGS),csFixer=await firstFile(dir,CS_FIXER_CONFIGS),phpunit=await firstFile(dir,PHPUNIT_CONFIGS);if(phpstan!==void 0)steps.push({name:"typecheck",command:"vendor/bin/phpstan analyse --no-progress --memory-limit=1G",source:phpstan});if(csFixer!==void 0)steps.push({name:"lint",command:"vendor/bin/php-cs-fixer fix --dry-run -v",source:csFixer});if(phpunit!==void 0)steps.push({name:"test",command:"vendor/bin/phpunit",source:phpunit});return steps}async function nativeSteps(dir,pyprojectText){let steps=[];if(existsSync(join(dir,"go.mod")))steps.push({name:"lint",command:"go vet ./...",source:"go.mod"}),steps.push({name:"test",command:"go test ./...",source:"go.mod"});if(existsSync(join(dir,"Cargo.toml")))steps.push({name:"check",command:"cargo check",source:"Cargo.toml"}),steps.push({name:"lint",command:"cargo clippy",source:"Cargo.toml"}),steps.push({name:"fmt:check",command:"cargo fmt -- --check",source:"Cargo.toml"}),steps.push({name:"test",command:"cargo test",source:"Cargo.toml"});let pyPrefix=existsSync(join(dir,"uv.lock"))?"uv run ":"",ruffFile=await firstFile(dir,RUFF_CONFIGS),hasRuff=ruffFile!==void 0||pyprojectText!==void 0&&RUFF_SECTION.test(pyprojectText),hasMypy=await firstFile(dir,MYPY_CONFIGS)!==void 0||pyprojectText!==void 0&&MYPY_SECTION.test(pyprojectText),hasPytest=await firstFile(dir,PYTEST_CONFIGS)!==void 0||pyprojectText!==void 0&&PYTEST_SECTION.test(pyprojectText);if(hasMypy)steps.push({name:"typecheck",command:`${pyPrefix}mypy .`,source:"mypy"});if(hasRuff){let source=ruffFile??"pyproject.toml";steps.push({name:"lint",command:`${pyPrefix}ruff check .`,source}),steps.push({name:"fmt:check",command:`${pyPrefix}ruff format --check .`,source})}if(hasPytest)steps.push({name:"test",command:`${pyPrefix}pytest`,source:"pytest"});return steps}function packageNameOf(dir){let file=join(dir,"package.json");if(!existsSync(file))return;try{let parsed=JSON.parse(readFileSync(file,"utf8"));return typeof parsed.name==="string"?parsed.name:void 0}catch{return}}async function resolveTargets(dir,targets){let known=folders(dir),projects=[],seen=new Set;for(let target of targets){let direct=resolve2(dir,target),matchedDir;if(existsSync(direct))matchedDir=direct;else{let hit=known.find((sub)=>sub===target||basename(sub)===target||packageNameOf(join(dir,sub))===target);if(hit!==void 0)matchedDir=join(dir,hit)}if(matchedDir===void 0)fail(`no path or workspace matching ${target}`);if(seen.has(matchedDir))continue;seen.add(matchedDir);let steps=await discover(matchedDir);if(steps.length===0)fail(`no check steps found in ${target}`);let rel=relative(dir,matchedDir);projects.push({...rel===""?{}:{name:rel},dir:matchedDir,steps})}return projects}async function discoverProjects(dir,targets){if(targets!==void 0&&targets.length>0)return resolveTargets(dir,targets);let own=await discover(dir);if(own.length>0)return[{dir,steps:own}];let projects=[],entries=await readdir(dir,{withFileTypes:!0}),ignored=ignoredFolders(["var","tmp"]),direct=entries.filter((entry)=>entry.isDirectory()&&!entry.name.startsWith(".")&&!ignored.has(entry.name)).map((entry)=>entry.name),subdirs=[...new Set([...direct,...workspaces(dir)])].filter((name)=>name!==".").toSorted((a,b)=>a.localeCompare(b));for(let sub of subdirs){let steps=await discover(join(dir,sub));if(steps.length>0)projects.push({name:sub,dir:join(dir,sub),steps})}return projects}async function discover(dir){let found=await candidates(dir,"check",!0),overrides=(await loadCheckConfig(dir))?.steps??{},runnerCheck=found.find((candidate)=>candidate.name==="check"&&TASK_RUNNERS.has(candidate.source)),base=STEP_NAMES.flatMap((name)=>{if(name in overrides){let custom=overrides[name];return custom===null||custom===void 0?[]:[{name,command:custom,source:".checkrc.json"}]}let step=name==="check"&&runnerCheck!==void 0?runnerCheck:(STEP_SOURCES[name]??[name]).map((each)=>found.find((candidate)=>candidate.name===each)).find((each)=>each!==void 0);return step===void 0?[]:[{...step,name}]});for(let[name,command]of Object.entries(overrides))if(!STEP_NAMES.includes(name)&&typeof command==="string"&&command!=="")base.push({name,command,source:".checkrc.json"});return base}var JUSTFILE=/^\.?justfile$/i,TASKFILES2=["Taskfile.yml","taskfile.yml","Taskfile.yaml","taskfile.yaml","Taskfile.dist.yml","taskfile.dist.yml","Taskfile.dist.yaml","taskfile.dist.yaml"],MISE_FILES2=["mise.toml",".mise.toml","mise.local.toml",".mise.local.toml","mise",".mise","mise-tasks",".mise-tasks",".config/mise.toml",".config/mise"],LOCKFILES=[["bun.lock","bun"],["bun.lockb","bun"],["pnpm-lock.yaml","pnpm"],["yarn.lock","yarn"],["package-lock.json","npm"]],QUALIFIED=/^([a-z]+):(?!:)(.+)$/,BLANKS=/\s+/,TRAILING_SLASHES=/\/+$/,VERSION_SUFFIX=/@.*/,LEADING_HASHES=/^#*/,INCLUDE=/^(?:-|s)?include[ \t]+([^#]+)/,GLOB_CHARS=/[*?[]/,installed=new Map;function has(tool){if(!installed.has(tool))installed.set(tool,Bun.which(tool)!==null);return installed.get(tool)}function list(dir){try{return readdirSync(dir)}catch{return[]}}function locate(dir,here,names){for(let current=dir;;current=join2(current,"..")){let found=names.find((name)=>existsSync2(join2(current,name)));if(found!==void 0)return join2(current,found);let absolute=resolvePath(current);if(!here||existsSync2(join2(current,".git"))||dirname(absolute)===absolute)return}}function children(dir="."){let ignored=ignoredFolders();return readdirSync(dir,{withFileTypes:!0}).filter((child)=>child.isDirectory()&&!child.name.startsWith(".")&&!ignored.has(child.name)).map((child)=>child.name).toSorted()}function build(base,items){return items.map((item)=>({...base,doc:null,parameters:[],...item}))}function text(value){if(typeof value==="string")return value;if(Array.isArray(value)&&value.every((line)=>typeof line==="string"))return value.join(`
|
|
3
3
|
`);return Bun.YAML.stringify(value,null,2)??""}function field(value,key){let found=value!==null&&typeof value==="object"?value[key]:void 0;return typeof found==="string"?found:null}function recipes2(tree){return[...Object.values(tree.recipes).filter((recipe)=>!recipe.private),...Object.values(tree.modules).flatMap((module)=>recipes2(module))]}function justFlags(dir,here){if(here)return[];let file=list(dir).find((name)=>JUSTFILE.test(name));return file===void 0?void 0:["--justfile",join2(dir,file)]}function just(dir,here){let flags=justFlags(dir,here);if(flags===void 0||!has("just"))return[];let proc=Bun.spawnSync(["just",...flags,"--dump","--dump-format","json"],{stderr:"pipe"});if(!proc.success)return[];let items=recipes2(JSON.parse(proc.stdout.toString())).map((recipe)=>({name:recipe.namepath,doc:recipe.doc,parameters:recipe.parameters}));return build({kind:"just",tag:"just",runner:["just"],separated:!1,dir},items)}function targets2(source){let found=new Map,pending=null;for(let line of source.split(`
|
|
4
4
|
`)){if(line.startsWith("\t"))continue;let[rule="",...rest]=line.split("#"),comment=rest.join("#").replace(LEADING_HASHES,"").trim()||null;if(rule.trim()===""){pending=line.startsWith("##")?comment:null;continue}let colon=rule.indexOf(":"),assignment=rule[colon+1]==="="||rule.slice(colon+1).startsWith(":=")||rule.slice(0,colon).includes("=");if(colon===-1||assignment){pending=null;continue}let doc=comment??pending;for(let name of rule.slice(0,colon).trim().split(BLANKS)){if(name.startsWith(".")||name.includes("%")||name.includes("$"))continue;if(!found.has(name))found.set(name,doc)}pending=null}return[...found].map(([name,doc])=>({name,doc}))}function show(source,target){let lines=source.split(`
|
|
5
5
|
`),start=lines.findIndex((line)=>{let hash=line.indexOf("#"),rule=hash===-1?line:line.slice(0,hash),colon=rule.indexOf(":");return colon!==-1&&rule[colon+1]!=="="&&!rule.slice(0,colon).includes("=")&&rule.slice(0,colon).trim().split(BLANKS).includes(target)});if(start===-1)return target;let end=start+1;while(end<lines.length&&(lines[end].startsWith("\t")||lines[end].trim()===""))end++;return lines.slice(start,end).join(`
|
package/dist/cli.js
CHANGED
|
@@ -1,14 +1,14 @@
|
|
|
1
1
|
#!/bin/sh
|
|
2
2
|
// @bun 2>/dev/null; exec bun --no-env-file --config=/dev/null "$0" "$@"
|
|
3
|
-
import{paint,header,formatDuration,table,printJson,wholeNumber,duration,jsonOption,fail,parse,ignoredFolders}from"./chunk-ngcnmctk.js";import{exitCodeOf,holdSignals,runMain,shellQuote,place,shellIn,Stack,programOf,placeOptions,placeSettings,version}from"./chunk-
|
|
3
|
+
import{paint,header,formatDuration,table,printJson,wholeNumber,duration,jsonOption,fail,parse,ignoredFolders}from"./chunk-ngcnmctk.js";import{exitCodeOf,holdSignals,runMain,shellQuote,place,shellIn,Stack,programOf,placeOptions,placeSettings,version}from"./chunk-898e3vv3.js";import{RESULTS_FILE,logDirectory,lastResults,lastFailed,runStep,refusedStep,outcomeJson,printOutcome}from"./chunk-1rrfsren.js";import{STEP_NAMES,MAKEFILES,CS_FIXER_CONFIGS,read,loadCheckConfig,candidates,firstFile,discoverProjects}from"./chunk-kbkmjjg6.js";import process3 from"process";import{watch}from"fs";import{writeFile as writeFile2}from"fs/promises";import{basename as basename2,join as join4}from"path";import process2 from"process";import{existsSync as existsSync2,statSync}from"fs";import{rename,writeFile}from"fs/promises";import{extname as extname2,join as join3}from"path";import process from"process";import{stat}from"fs/promises";import{join}from"path";var{$}=globalThis.Bun;async function dirtyFiles(dir){let listed=await $`git ls-files -z --modified --others --exclude-standard`.cwd(dir).quiet().nothrow();if(listed.exitCode!==0)return;let files=new Map;for(let path of listed.stdout.toString().split("\x00").filter(Boolean))try{let{size,mtimeMs}=await stat(join(dir,path));files.set(path,`${size}:${mtimeMs}`)}catch{files.set(path,"")}return files}function changedFiles(before,after){return[...after].filter(([path,hash])=>before.get(path)!==hash).map(([path])=>path)}var TARGET=/^([\w-]+(?:[ \t]+[\w-]+)*)[ \t]*::?(?!:?=)(.*)$/gm,PHONY_LINE=/^\.PHONY:((?:.*\\\n)*.*)$/gm,DEFINE_BLOCK=/^define\b.*\n(?:.*\n)*?endef\b.*$/gm,BLANKS=/\s+/,CONTINUATION=/\\\n/g,EXTRA_BLANK_LINES=/\n\s*\n\s*\n/g,LEADING_BLANK_LINES=/^\s*\n/,TRAILING_WHITESPACE=/\s+$/,FILE_LIKE=/[./]/;function declarePhony(content,exists=()=>!1){let declared=Array.from(content.matchAll(PHONY_LINE),(match)=>match[1].replace(CONTINUATION," ").split(BLANKS)).flat().filter((name)=>name!==""),found=Array.from(content.replace(DEFINE_BLOCK,"").matchAll(TARGET),(match)=>({names:match[1].split(BLANKS),deps:match[2]})).filter(({deps})=>!FILE_LIKE.test(deps)).flatMap(({names})=>names).filter((name)=>!exists(name)),targets=[...new Set([...declared,...found])].sort((a,b)=>a.localeCompare(b)),isFirst=!0,body=content.replace(PHONY_LINE,()=>{let kept=isFirst?"\x00phony\x00":"";return isFirst=!1,kept}).replace(EXTRA_BLANK_LINES,`
|
|
4
4
|
|
|
5
5
|
`).replace(LEADING_BLANK_LINES,""),line=targets.length===0?"":`.PHONY: ${targets.join(" ")}`;return{content:(body.includes("\x00phony\x00")||line===""?body.replace("\x00phony\x00",()=>line):`${line}
|
|
6
6
|
|
|
7
7
|
${body}`).replace(LEADING_BLANK_LINES,"").replace(TRAILING_WHITESPACE,`
|
|
8
|
-
`),targets}}import{existsSync,readFileSync}from"fs";import{basename,dirname,extname,join as join2,resolve}from"path";var{$:$2}=globalThis.Bun;var WRAPPER_PREFIX=/^(?:(?:bunx|npx|pnpm\s+exec|yarn|uv\s+run)\s+)+/,LINTERS=/^(?:keslint|eslint|oxlint|biome\s+check|biome\s+lint)\b/,LINTABLE=new Set([".ts",".tsx",".js",".jsx",".mjs",".cjs",".mts",".cts",".vue",".svelte"]),PYTHON_EXT=new Set([".py",".pyi"]),TEST_RUNNER=/^(?:bun test|\$npm_execpath test)\b/,VITEST_RUNNER=/^vitest(?:\s+run)?\b/,PYTEST_RUNNER=/^pytest\b/,RUFF_CHECK=/^ruff\s+check\b/,RUFF_FORMAT=/^ruff\s+format\b/,GO_TEST=/^go\s+test\s+\.\.\.\/?$|^go\s+test\s+\.\/\.\.\./,TRAILING_DOT=/\s+\.\/?$/,TEST_FILE=/\.(?:test|spec)\.[jt]sx?$/,PY_TEST_FILE=/(?:^|\/)(?:test_[^/]+|[^/]+_test)\.py$/,IMPORT_SPEC=/(?:from|import)\s+['"]([^'"]+)['"]|require\(\s*['"]([^'"]+)['"]\s*\)/g,WHITESPACE=/\s+/;async function changedPaths(dir,base="HEAD"){let tracked=await $2`git diff --name-only --relative -z ${base}`.cwd(dir).quiet().nothrow(),untracked=await $2`git ls-files -z --others --exclude-standard`.cwd(dir).quiet().nothrow();if(tracked.exitCode!==0||untracked.exitCode!==0)return;return[...new Set([...tracked.stdout.toString().split("\x00"),...untracked.stdout.toString().split("\x00")])].filter((path)=>path!==""&&existsSync(join2(dir,path)))}function siblingTests(path,exists){let extension=extname(path),name=basename(path,extension),dir=dirname(path),folders=[dir,join2(dir,"tests"),join2(dir,"..","tests"),join2(dir,"__tests__")],found=new Set;for(let folder of folders)for(let kind of["test","spec"])for(let candidate of[`${name}.${kind}${extension}`,`${name}.${kind}.ts`].map((file)=>join2(folder,file)))if(exists(candidate))found.add(candidate);return[...found]}function siblingPyTests(path,exists){let extension=extname(path),name=basename(path,extension),dir=dirname(path),folders=[dir,join2(dir,"tests"),join2(dir,"..","tests"),"tests"],found=new Set;for(let folder of folders)for(let candidate of[`test_${name}.py`,`${name}_test.py`].map((file)=>join2(folder,file)))if(exists(candidate))found.add(candidate);return[...found]}function reverseImportTests(dir,changedSources){if(changedSources.length===0)return[];let targets=new Set(changedSources.map((file)=>{let abs=resolve(dir,file),ext=extname(abs);return ext===""?abs:abs.slice(0,-ext.length)})),found=new Set,glob=new Bun.Glob("**/*.{test,spec}.{ts,tsx,js,jsx}");for(let testFile of glob.scanSync({cwd:dir})){if(testFile.split("/").includes("node_modules")||testFile.startsWith(".git/"))continue;let text;try{text=readFileSync(join2(dir,testFile),"utf8")}catch{continue}let testDir=dirname(resolve(dir,testFile));for(let match of text.matchAll(IMPORT_SPEC)){let specifier=match[1]??match[2]??"";if(!specifier.startsWith("."))continue;let imported=resolve(testDir,specifier),ext=extname(imported),stem=ext===""?imported:imported.slice(0,-ext.length);if(targets.has(stem)||targets.has(join2(stem,"index"))){found.add(testFile);break}}}return[...found]}function isBare(script,tool,allowDot=!1){let unwrapped=script.trim().replace(WRAPPER_PREFIX,"");if(!tool.test(unwrapped))return!1;let rest=unwrapped.replace(tool,"").trim();if(rest==="")return!0;return rest.split(WHITESPACE).every((word)=>word===""||word.startsWith("-")||allowDot&&(word==="."||word==="./"))}function stripTrailingDot(command){return command.replace(TRAILING_DOT,"")}function jsTestFiles(dir,changed){let tests=new Set,nonTests=[];for(let path of changed)if(TEST_FILE.test(path))tests.add(path);else{if(LINTABLE.has(extname(path)))nonTests.push(path);for(let test of siblingTests(path,(candidate)=>existsSync(join2(dir,candidate))))tests.add(test)}for(let imported of reverseImportTests(dir,nonTests))tests.add(imported);return[...tests]}async function narrow(step,dir,changed){let script=step.source==="package.json"?(await scriptText(dir,step.name))?.trim():void 0,effective=script??step.command.trim(),full=(why)=>({command:step.command,note:`in full, ${why}`});if(script!==void 0&&step.name==="lint"&&isBare(script,LINTERS,!0)){let files=changed.filter((path)=>LINTABLE.has(extname(path)));if(files.length===0)return{command:"true",note:"nothing changed to lint"};return{command:TRAILING_DOT.test(script)?`${stripTrailingDot(script)} ${files.map(quote).join(" ")}`:`${step.command} -- ${files.map(quote).join(" ")}`,note:`${files.length} changed file${files.length===1?"":"s"}`}}if(step.name==="lint"&&isBare(effective,RUFF_CHECK,!0)||step.name==="fmt"&&isBare(effective,RUFF_FORMAT,!0)){let files=changed.filter((path)=>PYTHON_EXT.has(extname(path)));if(files.length===0)return{command:"true",note:`nothing changed to ${step.name}`};return{command:`${stripTrailingDot(effective)} ${files.map(quote).join(" ")}`,note:`${files.length} changed file${files.length===1?"":"s"}`}}if(step.name==="test"&&isBare(effective,VITEST_RUNNER)){let files=changed.filter((path)=>LINTABLE.has(extname(path)));if(files.length===0)return full("no JS/TS file changed");return{command:`${step.command} -- --related ${files.map(quote).join(" ")}`,note:`${files.length} related file${files.length===1?"":"s"}`}}if(script!==void 0&&step.name==="test"&&isBare(script,TEST_RUNNER)){let tests=jsTestFiles(dir,changed);if(tests.length===0)return full("no test sits next to the changed files");return{command:`${step.command} -- ${tests.map((test)=>quote(`./${test}`)).join(" ")}`,note:`${tests.length} test file${tests.length===1?"":"s"}`}}if(step.name==="test"&&isBare(effective,PYTEST_RUNNER,!0)){let tests=new Set;for(let path of changed)if(PY_TEST_FILE.test(path))tests.add(path);else if(PYTHON_EXT.has(extname(path)))for(let test of siblingPyTests(path,(candidate)=>existsSync(join2(dir,candidate))))tests.add(test);if(tests.size===0)return full("no test sits next to the changed files");return{command:`${stripTrailingDot(effective)} ${[...tests].map(quote).join(" ")}`,note:`${tests.size} test file${tests.size===1?"":"s"}`}}if(step.name==="test"&&GO_TEST.test(effective)){let pkgs=[...new Set(changed.filter((path)=>extname(path)===".go").map((path)=>{let folder=dirname(path);return folder==="."?".":`./${folder}`}))];if(pkgs.length===0)return{command:"true",note:"no Go files changed"};return{command:`go test ${pkgs.map(quote).join(" ")}`,note:`${pkgs.length} Go package${pkgs.length===1?"":"s"}`}}return full(`${step.name} cannot be narrowed`)}function quote(path){return`'${path.replaceAll("'","'\\''")}'`}async function scriptText(dir,name){let text=await read(dir,"package.json");if(text===void 0)return;try{let value=JSON.parse(text).scripts?.[name];return typeof value==="string"?value:void 0}catch{return}}var options={list:{type:"boolean",short:"l",description:"print the steps (or, with --fix, the fixers) found, the commands that run them and where (host or service), without running them"},only:{type:"string",short:"o",description:`comma separated steps to run, among ${STEP_NAMES.join(", ")}; with --fix the fixers to run, by the names --list prints`,candidates:()=>[...STEP_NAMES]},timeout:{type:"string",short:"t",description:"longest a step or fixer may run before it is ended (30s, 5m, 1h), none by default"},...placeOptions,json:jsonOption("[{name, command, in?, ok, ms, log, failed?, errors?}], with --list [{name, command, source, in?}], with --fix {fixers, changed}"),fix:{type:"boolean",short:"f",description:"run the folder's fixers and formatters instead of the steps"},quiet:{type:"boolean",short:"q",description:"print nothing for a passing step, and nothing at all when every step passes"},failed:{type:"boolean",description:"run only the steps that failed in the last run of this folder, read from the run folder"},changed:{type:"boolean",short:"c",description:"narrow lint, fmt, fix, and test to files changed against --base (default HEAD), with 1-hop reverse-import test selection"},base:{type:"string",description:"git ref to diff against with --changed (default HEAD)"},"fail-fast":{type:"boolean",short:"x",description:"stop after the first failing step"},retry:{type:"string",description:"retry a failing step up to N times before reporting failure"},lock:{type:"string",description:"named slot lock to hold alongside the slot (visible in slot ls)"},watch:{type:"boolean",short:"w",description:"watch project files and re-run on changes"},slot:{type:"boolean",description:"run each step through slot, queued behind the machine-wide slots of the other sessions, as it does by default when the slot bin is installed; fails without the bin"},"no-slot":{type:"boolean",description:"run the steps at once, without queueing behind the other sessions' slots"},parallel:{type:"boolean",description:"run the steps at the same time, printing each one's output in step order"}},COMMA=/\s*,\s*/;function pick(steps,only,noun="step"){if(only===void 0)return steps;let names=only.split(COMMA).filter((name)=>name!=="");if(names.length===0)fail(`--only names no ${noun}, found ${steps.map((step)=>step.label??step.name).join(", ")}`);let matches=(step,wanted)=>step.name===wanted||step.label===wanted,unknown=names.filter((name)=>!steps.some((step)=>matches(step,name)));if(unknown.length>0)fail(`no ${unknown.join(", ")} ${noun} here, found ${[...new Set(steps.map((step)=>step.label??step.name))].join(", ")}`);return steps.filter((step)=>names.some((wanted)=>matches(step,wanted)))}var RUNNING="KAYNOOO_CLI_FIX",JUSTFILES=["justfile","Justfile",".justfile"],RUFF_CONFIGS=["ruff.toml",".ruff.toml"],RUFF_SECTION=/^\[tool\.ruff/m,MAX_CHANGED=30,JS_EXTS=new Set([".ts",".tsx",".js",".jsx",".mjs",".cjs",".mts",".cts",".vue",".svelte"]),PY_EXTS=new Set([".py",".pyi"]),PHP_EXTS=new Set([".php"]),GO_EXTS=new Set([".go"]),RS_EXTS=new Set([".rs"]),JS_FIXER=/^(?:(?:bunx|npx|pnpm\s+exec|yarn)\s+)?(?:keslint|eslint|oxlint|prettier|biome)\b/,TRAILING_DOT2=/\s+\.\/?$/,quotePath=(path)=>`'${path.replaceAll("'","'\\''")}'`;async function narrowFixers(found,cwd,base){let paths=await changedPaths(cwd,base);if(paths===void 0)fail("--changed needs a git repository");let result=[],pkgText=await read(cwd,"package.json"),scripts=pkgText===void 0?{}:JSON.parse(pkgText).scripts??{};for(let fixer of found){if(fixer.name==="python"){let files=paths.filter((path)=>PY_EXTS.has(extname2(path)));if(files.length>0)result.push({...fixer,command:`ruff check --fix ${files.map(quotePath).join(" ")} && ruff format ${files.map(quotePath).join(" ")}`});continue}if(fixer.name==="php-cs-fixer"){let files=paths.filter((path)=>PHP_EXTS.has(extname2(path)));if(files.length>0)result.push({...fixer,command:`vendor/bin/php-cs-fixer fix ${files.map(quotePath).join(" ")}`});continue}if(fixer.name==="go"){if(paths.some((path)=>GO_EXTS.has(extname2(path))||path==="go.mod"))result.push(fixer);continue}if(fixer.name==="rust"){if(paths.some((path)=>RS_EXTS.has(extname2(path))||path==="Cargo.toml"))result.push(fixer);continue}if(fixer.name==="makefile"||fixer.name==="justfile"){if(paths.includes(fixer.source))result.push(fixer);continue}if(fixer.source==="package.json"){let script=scripts[fixer.name]?.trim()??"",files=paths.filter((path)=>JS_EXTS.has(extname2(path)));if(JS_FIXER.test(script)){if(files.length>0){let stripped=script.replace(TRAILING_DOT2,"");result.push({...fixer,command:TRAILING_DOT2.test(script)?`${stripped} ${files.map(quotePath).join(" ")}`:`${fixer.command} -- ${files.map(quotePath).join(" ")}`})}continue}}result.push(fixer)}return result}async function replaceFile(path,content){let temporary=`${path}.${process.pid}.tmp`;await writeFile(temporary,content,{mode:statSync(path).mode&511}),await rename(temporary,path)}async function projectFixers(dir){let found=await candidates(dir,"check"),named=(name)=>found.find((step)=>step.name===name),all=named("fix");if(all!==void 0)return[all];return[named("lint:fix")??named("lint-fix"),named("fmt")??named("format")].filter((step)=>step!==void 0)}async function toolFixers(dir){let fixers=[],makefile=await firstFile(dir,MAKEFILES),justfile=await firstFile(dir,JUSTFILES),ruff=await firstFile(dir,RUFF_CONFIGS)!==void 0||RUFF_SECTION.test(await read(dir,"pyproject.toml")??"");if(makefile!==void 0)fixers.push({name:"makefile",command:"declare every target .PHONY",source:makefile,write:async(cwd)=>{let path=join3(cwd,makefile),current=await Bun.file(path).text(),{content,targets}=declarePhony(current,(name)=>existsSync2(join3(cwd,name)));if(content!==current)await replaceFile(path,content);return`.PHONY: ${targets.join(" ")}`}});if(justfile!==void 0)fixers.push({name:"justfile",command:`just --justfile ${justfile} --fmt`,source:justfile,requires:"just"});if(await Bun.file(join3(dir,"go.mod")).exists())fixers.push({name:"go",command:"go fmt ./... && go mod tidy",source:"go.mod",requires:"go"});if(await Bun.file(join3(dir,"Cargo.toml")).exists())fixers.push({name:"rust",command:"cargo fmt",source:"Cargo.toml",requires:"cargo"});if(ruff)fixers.push({name:"python",command:"ruff check --fix . && ruff format .",source:"ruff",requires:"ruff"});return fixers}async function fixers(dir){let project=await projectFixers(dir),csFixer=await firstFile(dir,CS_FIXER_CONFIGS),php=csFixer===void 0||project.some((fixer)=>fixer.source==="composer.json")?[]:[{name:"php-cs-fixer",command:"vendor/bin/php-cs-fixer fix",source:csFixer}];return[...project,...php,...await toolFixers(dir)]}function runsInService(fixer){return fixer.write===void 0&&fixer.requires===void 0}async function runFixer(fixer,placement,cwd,logFile,settings){if(fixer.write===void 0&&placement!==void 0)return runStep(shellIn(placement,fixer.command,{[RUNNING]:"1"}),cwd,logFile,{...settings,env:{[RUNNING]:"1"}});if(fixer.write===void 0)return runStep(fixer.command,cwd,logFile,{...settings,env:{[RUNNING]:"1"}});let started=Date.now(),outcome;try{outcome={ok:!0,ms:0,output:await fixer.write(cwd)}}catch(error){outcome={ok:!1,ms:0,output:error instanceof Error?error.message:String(error)}}return await writeFile(logFile,outcome.output,{mode:384,flag:"wx"}),{...outcome,ms:Date.now()-started}}function printChanged(changed){if(changed.length===0){console.log("nothing changed");return}console.log(`changed ${changed.length} file${changed.length===1?"":"s"}:`);for(let path of changed.slice(0,MAX_CHANGED))console.log(` ${path}`);if(changed.length>MAX_CHANGED)console.log(` and ${changed.length-MAX_CHANGED} more`)}async function runFixers(values,cwd){let parsed={values},settings=placeSettings(values);if(process.env[RUNNING]!==void 0)fail("a fixer called check --fix again, which would recurse: give its script another command");let found=await fixers(cwd);if(found.length===0)fail("nothing to fix here: no fix, lint:fix, fmt or format script, php-cs-fixer config, Makefile, Justfile, go.mod, Cargo.toml nor ruff config");let pickedAll=pick(found,parsed.values.only,"fixer"),picked=parsed.values.changed===!0?await narrowFixers(pickedAll,cwd,parsed.values.base):pickedAll;if(picked.length===0){if(parsed.values.json===!0)printJson(parsed.values.list===!0?[]:{fixers:[],changed:[]});else console.log("nothing changed to fix");return 0}let placements=new Map;for(let fixer of picked)placements.set(fixer,runsInService(fixer)?await place(cwd,programOf(fixer.command),settings):void 0);let json=parsed.values.json===!0,missing=(fixer)=>fixer.requires!==void 0&&Bun.which(fixer.requires)===null;if(parsed.values.list===!0){if(json)printJson(picked.map((fixer)=>({name:fixer.name,command:fixer.command,source:fixer.source,...placements.get(fixer)===void 0?{}:{in:placements.get(fixer)?.service},...missing(fixer)?{needs:fixer.requires}:{}})));else console.log(table(picked.map((fixer)=>[fixer.name,fixer.command,missing(fixer)?`${fixer.source}, needs ${fixer.requires}`:fixer.source,placements.get(fixer)?.service??"host"])));return 0}let timeoutMs=parsed.values.timeout===void 0?void 0:duration(parsed.values.timeout,"timeout",0),directory=await logDirectory(cwd),held=holdSignals(),runSettings={...timeoutMs===void 0?{}:{timeoutMs},held},stack=new Stack,width=Math.max(...picked.map((fixer)=>fixer.name.length)),before=await dirtyFiles(cwd),ran=[],failed=0,timedOut=!1;try{for(let fixer of picked){if(held.signal!==void 0)break;if(missing(fixer)){if(!json)console.log(`${paint(process.stdout).yellow("skip ")} ${fixer.name.padEnd(width)} ${fixer.requires} is not installed`);ran.push({name:fixer.name,command:fixer.command,skipped:`${fixer.requires} is not installed`});continue}let logFile=join3(directory,`fix-${fixer.name.replaceAll(":","-")}.log`),placement=placements.get(fixer),down=placement===void 0?void 0:await stack.problem(placement),outcome=down===void 0?await runFixer(fixer,placement,cwd,logFile,runSettings):await refusedStep(down,logFile);if(!json)printOutcome(fixer.name,width,placement===void 0?fixer.command:`${fixer.command} (in ${placement.service})`,logFile,outcome);if(ran.push(outcomeJson(fixer.name,fixer.command,logFile,outcome,placement?.service)),outcome.timedOut===!0)timedOut=!0;if(!outcome.ok)failed++}}finally{held.release()}let after=before&&await dirtyFiles(cwd),changed=before!==void 0&&after!==void 0?changedFiles(before,after):null;if(json)printJson({fixers:ran,changed});else if(changed!==null)printChanged(changed);if(held.signal!==void 0)return exitCodeOf(null,held.signal);if(timedOut)return 2;return failed===0?0:1}var usage=`check [path|workspace...] [--only <steps>] [--changed [--base <ref>]] [--failed] [--fail-fast] [--retry <n>] [--watch] [--quiet] [--timeout <duration>] [--slot | --no-slot] [--lock <name>] [--parallel] [--in <service> | --host] [--list]
|
|
8
|
+
`),targets}}import{existsSync,readFileSync}from"fs";import{basename,dirname,extname,join as join2,resolve}from"path";var{$:$2}=globalThis.Bun;var WRAPPER_PREFIX=/^(?:(?:bunx|npx|pnpm\s+exec|yarn|uv\s+run)\s+)+/,LINTERS=/^(?:keslint|eslint|oxlint|biome\s+check|biome\s+lint)\b/,LINTABLE=new Set([".ts",".tsx",".js",".jsx",".mjs",".cjs",".mts",".cts",".vue",".svelte"]),PYTHON_EXT=new Set([".py",".pyi"]),TEST_RUNNER=/^(?:bun test|\$npm_execpath test)\b/,VITEST_RUNNER=/^vitest(?:\s+run)?\b/,PYTEST_RUNNER=/^pytest\b/,RUFF_CHECK=/^ruff\s+check\b/,RUFF_FORMAT=/^ruff\s+format\b/,GO_TEST=/^go\s+test\s+\.\.\.\/?$|^go\s+test\s+\.\/\.\.\./,TRAILING_DOT=/\s+\.\/?$/,TEST_FILE=/\.(?:test|spec)\.[jt]sx?$/,PY_TEST_FILE=/(?:^|\/)(?:test_[^/]+|[^/]+_test)\.py$/,IMPORT_SPEC=/(?:from|import)\s+['"]([^'"]+)['"]|require\(\s*['"]([^'"]+)['"]\s*\)/g,WHITESPACE=/\s+/;async function changedPaths(dir,base="HEAD"){let tracked=await $2`git diff --name-only --relative -z ${base}`.cwd(dir).quiet().nothrow(),untracked=await $2`git ls-files -z --others --exclude-standard`.cwd(dir).quiet().nothrow();if(tracked.exitCode!==0||untracked.exitCode!==0)return;return[...new Set([...tracked.stdout.toString().split("\x00"),...untracked.stdout.toString().split("\x00")])].filter((path)=>path!==""&&existsSync(join2(dir,path)))}function siblingTests(path,exists){let extension=extname(path),name=basename(path,extension),dir=dirname(path),folders=[dir,join2(dir,"tests"),join2(dir,"..","tests"),join2(dir,"__tests__")],found=new Set;for(let folder of folders)for(let kind of["test","spec"])for(let candidate of[`${name}.${kind}${extension}`,`${name}.${kind}.ts`].map((file)=>join2(folder,file)))if(exists(candidate))found.add(candidate);return[...found]}function siblingPyTests(path,exists){let extension=extname(path),name=basename(path,extension),dir=dirname(path),folders=[dir,join2(dir,"tests"),join2(dir,"..","tests"),"tests"],found=new Set;for(let folder of folders)for(let candidate of[`test_${name}.py`,`${name}_test.py`].map((file)=>join2(folder,file)))if(exists(candidate))found.add(candidate);return[...found]}function reverseImportTests(dir,changedSources){if(changedSources.length===0)return[];let targets=new Set(changedSources.map((file)=>{let abs=resolve(dir,file),ext=extname(abs);return ext===""?abs:abs.slice(0,-ext.length)})),found=new Set,glob=new Bun.Glob("**/*.{test,spec}.{ts,tsx,js,jsx}");for(let testFile of glob.scanSync({cwd:dir})){if(testFile.split("/").includes("node_modules")||testFile.startsWith(".git/"))continue;let text;try{text=readFileSync(join2(dir,testFile),"utf8")}catch{continue}let testDir=dirname(resolve(dir,testFile));for(let match of text.matchAll(IMPORT_SPEC)){let specifier=match[1]??match[2]??"";if(!specifier.startsWith("."))continue;let imported=resolve(testDir,specifier),ext=extname(imported),stem=ext===""?imported:imported.slice(0,-ext.length);if(targets.has(stem)||targets.has(join2(stem,"index"))){found.add(testFile);break}}}return[...found]}function isBare(script,tool,allowDot=!1){let unwrapped=script.trim().replace(WRAPPER_PREFIX,"");if(!tool.test(unwrapped))return!1;let rest=unwrapped.replace(tool,"").trim();if(rest==="")return!0;return rest.split(WHITESPACE).every((word)=>word===""||word.startsWith("-")||allowDot&&(word==="."||word==="./"))}function stripTrailingDot(command){return command.replace(TRAILING_DOT,"")}function jsTestFiles(dir,changed){let tests=new Set,nonTests=[];for(let path of changed)if(TEST_FILE.test(path))tests.add(path);else{if(LINTABLE.has(extname(path)))nonTests.push(path);for(let test of siblingTests(path,(candidate)=>existsSync(join2(dir,candidate))))tests.add(test)}for(let imported of reverseImportTests(dir,nonTests))tests.add(imported);return[...tests]}async function narrow(step,dir,changed){let script=step.source==="package.json"?(await scriptText(dir,step.name))?.trim():void 0,effective=script??step.command.trim(),full=(why)=>({command:step.command,note:`in full, ${why}`});if(script!==void 0&&step.name==="lint"&&isBare(script,LINTERS,!0)){let files=changed.filter((path)=>LINTABLE.has(extname(path)));if(files.length===0)return{command:"true",note:"nothing changed to lint"};return{command:TRAILING_DOT.test(script)?`${stripTrailingDot(script)} ${files.map(quote).join(" ")}`:`${step.command} -- ${files.map(quote).join(" ")}`,note:`${files.length} changed file${files.length===1?"":"s"}`}}if(step.name==="lint"&&isBare(effective,RUFF_CHECK,!0)||step.name==="fmt"&&isBare(effective,RUFF_FORMAT,!0)){let files=changed.filter((path)=>PYTHON_EXT.has(extname(path)));if(files.length===0)return{command:"true",note:`nothing changed to ${step.name}`};return{command:`${stripTrailingDot(effective)} ${files.map(quote).join(" ")}`,note:`${files.length} changed file${files.length===1?"":"s"}`}}if(step.name==="test"&&isBare(effective,VITEST_RUNNER)){let files=changed.filter((path)=>LINTABLE.has(extname(path)));if(files.length===0)return full("no JS/TS file changed");return{command:`${step.command} -- --related ${files.map(quote).join(" ")}`,note:`${files.length} related file${files.length===1?"":"s"}`}}if(script!==void 0&&step.name==="test"&&isBare(script,TEST_RUNNER)){let tests=jsTestFiles(dir,changed);if(tests.length===0)return full("no test sits next to the changed files");return{command:`${step.command} -- ${tests.map((test)=>quote(`./${test}`)).join(" ")}`,note:`${tests.length} test file${tests.length===1?"":"s"}`}}if(step.name==="test"&&isBare(effective,PYTEST_RUNNER,!0)){let tests=new Set;for(let path of changed)if(PY_TEST_FILE.test(path))tests.add(path);else if(PYTHON_EXT.has(extname(path)))for(let test of siblingPyTests(path,(candidate)=>existsSync(join2(dir,candidate))))tests.add(test);if(tests.size===0)return full("no test sits next to the changed files");return{command:`${stripTrailingDot(effective)} ${[...tests].map(quote).join(" ")}`,note:`${tests.size} test file${tests.size===1?"":"s"}`}}if(step.name==="test"&&GO_TEST.test(effective)){let pkgs=[...new Set(changed.filter((path)=>extname(path)===".go").map((path)=>{let folder=dirname(path);return folder==="."?".":`./${folder}`}))];if(pkgs.length===0)return{command:"true",note:"no Go files changed"};return{command:`go test ${pkgs.map(quote).join(" ")}`,note:`${pkgs.length} Go package${pkgs.length===1?"":"s"}`}}return full(`${step.name} cannot be narrowed`)}function quote(path){return`'${path.replaceAll("'","'\\''")}'`}async function scriptText(dir,name){let text=await read(dir,"package.json");if(text===void 0)return;try{let value=JSON.parse(text).scripts?.[name];return typeof value==="string"?value:void 0}catch{return}}var options={list:{type:"boolean",short:"l",description:"print the steps (or, with --fix, the fixers) found, the commands that run them and where (host or service), without running them"},only:{type:"string",short:"o",description:`comma separated steps to run, among ${STEP_NAMES.join(", ")}; with --fix the fixers to run, by the names --list prints`,candidates:()=>[...STEP_NAMES]},timeout:{type:"string",short:"t",description:"longest a step or fixer may run before it is ended (30s, 5m, 1h), none by default"},...placeOptions,json:jsonOption("[{name, command, in?, ok, ms, log, failed?, errors?}], with --list [{name, command, source, in?}], with --fix {fixers, changed}"),fix:{type:"boolean",short:"f",description:"run the folder's fixers and formatters instead of the steps"},quiet:{type:"boolean",short:"q",description:"print nothing for a passing step, and nothing at all when every step passes"},failed:{type:"boolean",description:"run only the steps that failed in the last run of this folder, read from the run folder"},changed:{type:"boolean",short:"c",description:"narrow lint, fmt, fix, and test to files changed against --base (default HEAD), with 1-hop reverse-import test selection"},base:{type:"string",description:"git ref to diff against with --changed (default HEAD)"},"fail-fast":{type:"boolean",short:"x",description:"stop after the first failing step"},retry:{type:"string",description:"retry a failing step up to N times before reporting failure"},lock:{type:"string",description:"named slot lock to hold alongside the slot (visible in slot ls); refused without the slot bin"},watch:{type:"boolean",short:"w",description:"watch project files and re-run on changes"},slot:{type:"boolean",description:"run each step through slot, queued behind the machine-wide slots of the other sessions, as it does by default when the slot bin is installed; without the bin it warns and runs unqueued"},"no-slot":{type:"boolean",description:"run the steps at once, without queueing behind the other sessions' slots"},parallel:{type:"boolean",description:"run the steps at the same time, printing each one's output in step order"}},COMMA=/\s*,\s*/;function pick(steps,only,noun="step"){if(only===void 0)return steps;let names=only.split(COMMA).filter((name)=>name!=="");if(names.length===0)fail(`--only names no ${noun}, found ${steps.map((step)=>step.label??step.name).join(", ")}`);let matches=(step,wanted)=>step.name===wanted||step.label===wanted,unknown=names.filter((name)=>!steps.some((step)=>matches(step,name)));if(unknown.length>0)fail(`no ${unknown.join(", ")} ${noun} here, found ${[...new Set(steps.map((step)=>step.label??step.name))].join(", ")}`);return steps.filter((step)=>names.some((wanted)=>matches(step,wanted)))}var RUNNING="KAYNOOO_CLI_FIX",JUSTFILES=["justfile","Justfile",".justfile"],RUFF_CONFIGS=["ruff.toml",".ruff.toml"],RUFF_SECTION=/^\[tool\.ruff/m,MAX_CHANGED=30,JS_EXTS=new Set([".ts",".tsx",".js",".jsx",".mjs",".cjs",".mts",".cts",".vue",".svelte"]),PY_EXTS=new Set([".py",".pyi"]),PHP_EXTS=new Set([".php"]),GO_EXTS=new Set([".go"]),RS_EXTS=new Set([".rs"]),JS_FIXER=/^(?:(?:bunx|npx|pnpm\s+exec|yarn)\s+)?(?:keslint|eslint|oxlint|prettier|biome)\b/,TRAILING_DOT2=/\s+\.\/?$/,quotePath=(path)=>`'${path.replaceAll("'","'\\''")}'`;async function narrowFixers(found,cwd,base){let paths=await changedPaths(cwd,base);if(paths===void 0)fail("--changed needs a git repository");let result=[],pkgText=await read(cwd,"package.json"),scripts=pkgText===void 0?{}:JSON.parse(pkgText).scripts??{};for(let fixer of found){if(fixer.name==="python"){let files=paths.filter((path)=>PY_EXTS.has(extname2(path)));if(files.length>0)result.push({...fixer,command:`ruff check --fix ${files.map(quotePath).join(" ")} && ruff format ${files.map(quotePath).join(" ")}`});continue}if(fixer.name==="php-cs-fixer"){let files=paths.filter((path)=>PHP_EXTS.has(extname2(path)));if(files.length>0)result.push({...fixer,command:`vendor/bin/php-cs-fixer fix ${files.map(quotePath).join(" ")}`});continue}if(fixer.name==="go"){if(paths.some((path)=>GO_EXTS.has(extname2(path))||path==="go.mod"))result.push(fixer);continue}if(fixer.name==="rust"){if(paths.some((path)=>RS_EXTS.has(extname2(path))||path==="Cargo.toml"))result.push(fixer);continue}if(fixer.name==="makefile"||fixer.name==="justfile"){if(paths.includes(fixer.source))result.push(fixer);continue}if(fixer.source==="package.json"){let script=scripts[fixer.name]?.trim()??"",files=paths.filter((path)=>JS_EXTS.has(extname2(path)));if(JS_FIXER.test(script)){if(files.length>0){let stripped=script.replace(TRAILING_DOT2,"");result.push({...fixer,command:TRAILING_DOT2.test(script)?`${stripped} ${files.map(quotePath).join(" ")}`:`${fixer.command} -- ${files.map(quotePath).join(" ")}`})}continue}}result.push(fixer)}return result}async function replaceFile(path,content){let temporary=`${path}.${process.pid}.tmp`;await writeFile(temporary,content,{mode:statSync(path).mode&511}),await rename(temporary,path)}var LINT_FIXERS=["lint:fix","lint-fix","fix:lint","fix-lint","eslint:fix","eslint-fix","biome:fix","oxlint:fix"],FORMAT_FIXERS=["fmt","format","format:fix","format-fix","fmt:fix","fmt-fix","fix:format","fix:fmt","prettier","biome"],WRITING_FIXER=/^(?:(?:bunx|npx|pnpm\s+exec|yarn)\s+)?(?:(?:keslint|eslint|oxlint)\b.*\s--fix\b|prettier\b.*\s--write\b|biome\s+(?:check|format|lint)\b.*\s--(?:write|apply)\b)/;async function projectFixers(dir){let found=await candidates(dir,"check"),named=(names)=>names.map((name)=>found.find((step)=>step.name===name)).find((step)=>step!==void 0),all=named(["fix"]);if(all!==void 0)return[all];let byName=[named(LINT_FIXERS),named(FORMAT_FIXERS)].filter((step)=>step!==void 0);if(byName.length>0)return byName;let text=await read(dir,"package.json"),scripts=text===void 0?{}:JSON.parse(text).scripts??{};return found.filter((step)=>step.source==="package.json"&&typeof scripts[step.name]==="string"&&WRITING_FIXER.test(scripts[step.name]))}async function toolFixers(dir){let fixers=[],makefile=await firstFile(dir,MAKEFILES),justfile=await firstFile(dir,JUSTFILES),ruff=await firstFile(dir,RUFF_CONFIGS)!==void 0||RUFF_SECTION.test(await read(dir,"pyproject.toml")??"");if(makefile!==void 0)fixers.push({name:"makefile",command:"declare every target .PHONY",source:makefile,write:async(cwd)=>{let path=join3(cwd,makefile),current=await Bun.file(path).text(),{content,targets}=declarePhony(current,(name)=>existsSync2(join3(cwd,name)));if(content!==current)await replaceFile(path,content);return`.PHONY: ${targets.join(" ")}`}});if(justfile!==void 0)fixers.push({name:"justfile",command:`just --justfile ${justfile} --fmt`,source:justfile,requires:"just"});if(await Bun.file(join3(dir,"go.mod")).exists())fixers.push({name:"go",command:"go fmt ./... && go mod tidy",source:"go.mod",requires:"go"});if(await Bun.file(join3(dir,"Cargo.toml")).exists())fixers.push({name:"rust",command:"cargo fmt",source:"Cargo.toml",requires:"cargo"});if(ruff)fixers.push({name:"python",command:"ruff check --fix . && ruff format .",source:"ruff",requires:"ruff"});return fixers}async function fixers(dir){let project=await projectFixers(dir),csFixer=await firstFile(dir,CS_FIXER_CONFIGS),php=csFixer===void 0||project.some((fixer)=>fixer.source==="composer.json")?[]:[{name:"php-cs-fixer",command:"vendor/bin/php-cs-fixer fix",source:csFixer}];return[...project,...php,...await toolFixers(dir)]}function runsInService(fixer){return fixer.write===void 0&&fixer.requires===void 0}async function runFixer(fixer,placement,cwd,logFile,settings){if(fixer.write===void 0&&placement!==void 0)return runStep(shellIn(placement,fixer.command,{[RUNNING]:"1"}),cwd,logFile,{...settings,env:{[RUNNING]:"1"}});if(fixer.write===void 0)return runStep(fixer.command,cwd,logFile,{...settings,env:{[RUNNING]:"1"}});let started=Date.now(),outcome;try{outcome={ok:!0,ms:0,output:await fixer.write(cwd)}}catch(error){outcome={ok:!1,ms:0,output:error instanceof Error?error.message:String(error)}}return await writeFile(logFile,outcome.output,{mode:384,flag:"wx"}),{...outcome,ms:Date.now()-started}}function printChanged(changed){if(changed.length===0){console.log("nothing changed");return}console.log(`changed ${changed.length} file${changed.length===1?"":"s"}:`);for(let path of changed.slice(0,MAX_CHANGED))console.log(` ${path}`);if(changed.length>MAX_CHANGED)console.log(` and ${changed.length-MAX_CHANGED} more`)}async function runFixers(values,cwd){let parsed={values},settings=placeSettings(values);if(process.env[RUNNING]!==void 0)fail("a fixer called check --fix again, which would recurse: give its script another command");let found=await fixers(cwd);if(found.length===0)fail("nothing to fix here: no fix, lint:fix, fmt or format script (nor one running prettier --write, biome --write or eslint --fix), php-cs-fixer config, Makefile, Justfile, go.mod, Cargo.toml nor ruff config");let pickedAll=pick(found,parsed.values.only,"fixer"),picked=parsed.values.changed===!0?await narrowFixers(pickedAll,cwd,parsed.values.base):pickedAll;if(picked.length===0){if(parsed.values.json===!0)printJson(parsed.values.list===!0?[]:{fixers:[],changed:[]});else console.log("nothing changed to fix");return 0}let placements=new Map;for(let fixer of picked)placements.set(fixer,runsInService(fixer)?await place(cwd,programOf(fixer.command),settings):void 0);let json=parsed.values.json===!0,missing=(fixer)=>fixer.requires!==void 0&&Bun.which(fixer.requires)===null;if(parsed.values.list===!0){if(json)printJson(picked.map((fixer)=>({name:fixer.name,command:fixer.command,source:fixer.source,...placements.get(fixer)===void 0?{}:{in:placements.get(fixer)?.service},...missing(fixer)?{needs:fixer.requires}:{}})));else console.log(table(picked.map((fixer)=>[fixer.name,fixer.command,missing(fixer)?`${fixer.source}, needs ${fixer.requires}`:fixer.source,placements.get(fixer)?.service??"host"])));return 0}let timeoutMs=parsed.values.timeout===void 0?void 0:duration(parsed.values.timeout,"timeout",0),directory=await logDirectory(cwd),held=holdSignals(),runSettings={...timeoutMs===void 0?{}:{timeoutMs},held},stack=new Stack,width=Math.max(...picked.map((fixer)=>fixer.name.length)),before=await dirtyFiles(cwd),ran=[],failed=0,timedOut=!1;try{for(let fixer of picked){if(held.signal!==void 0)break;if(missing(fixer)){if(!json)console.log(`${paint(process.stdout).yellow("skip ")} ${fixer.name.padEnd(width)} ${fixer.requires} is not installed`);ran.push({name:fixer.name,command:fixer.command,skipped:`${fixer.requires} is not installed`});continue}let logFile=join3(directory,`fix-${fixer.name.replaceAll(":","-")}.log`),placement=placements.get(fixer),down=placement===void 0?void 0:await stack.problem(placement),outcome=down===void 0?await runFixer(fixer,placement,cwd,logFile,runSettings):await refusedStep(down,logFile);if(!json)printOutcome(fixer.name,width,placement===void 0?fixer.command:`${fixer.command} (in ${placement.service})`,logFile,outcome);if(ran.push(outcomeJson(fixer.name,fixer.command,logFile,outcome,placement?.service)),outcome.timedOut===!0)timedOut=!0;if(!outcome.ok)failed++}}finally{held.release()}let after=before&&await dirtyFiles(cwd),changed=before!==void 0&&after!==void 0?changedFiles(before,after):null;if(json)printJson({fixers:ran,changed});else if(changed!==null)printChanged(changed);if(held.signal!==void 0)return exitCodeOf(null,held.signal);if(timedOut)return 2;return failed===0?0:1}var usage=`check [path|workspace...] [--only <steps>] [--changed [--base <ref>]] [--failed] [--fail-fast] [--retry <n>] [--watch] [--quiet] [--timeout <duration>] [--slot | --no-slot] [--lock <name>] [--parallel] [--in <service> | --host] [--list]
|
|
9
9
|
check --fix [--only <fixers>] [--changed [--base <ref>]] [--timeout <duration>] [--in <service> | --host] [--list]
|
|
10
10
|
|
|
11
11
|
Runs the repo's typecheck, lint, fmt and test steps (\`check --fix\` to auto-fix and format) across package.json, composer.json, deno.json, Justfile, Makefile, Taskfile, mise, pyproject.toml, Go, Rust, Python, PHP or .checkrc.json; a folder with no steps runs its subfolders and workspaces.
|
|
12
12
|
A step runs inside the running compose service that mounts its folder and never starts one, and queues for a machine-wide slot when \`slot\` is installed.
|
|
13
13
|
A passing step prints one line, a failing one structured errors, and each step's full log is saved to the file its line ends with.
|
|
14
|
-
With --fix, the project's fix, lint:fix and fmt or format scripts run instead, then the formatters its files call for (php-cs-fixer, \`just --fmt\`, go fmt, cargo fmt, ruff), and the files they changed are listed.`,EXITS=[[0,"every step passed"],[1,"one failed"],[2,"bad usage, no step is found or a step timed out"]],WATCH_DEBOUNCE_MS=200;function slotted(command,lock){return`slot ${lock===void 0?"":`--lock ${shellQuote(lock)} `}-- sh -c ${shellQuote(command)}`}async function plan(steps,settings){let planned=[];for(let{project,...step}of steps)planned.push({...step,dir:project.dir,label:project.name===void 0?step.name:`${project.name}/${step.name}`,placement:await place(project.dir,programOf(step.command),settings)});return planned}async function narrowed(steps,base){let cache=new Map,result=[];for(let step of steps){if(!cache.has(step.dir)){let paths=await changedPaths(step.dir,base);if(paths===void 0)fail("--changed needs a git repository");cache.set(step.dir,paths)}let{command,note}=await narrow(step,step.dir,cache.get(step.dir)??[]);result.push({...step,command,note})}return result}function launch(step){return step.placement===void 0?step.command:shellIn(step.placement,step.command)}function summaryLine(outcomes){let colors=paint(process2.stdout),failed=outcomes.filter((outcome)=>!outcome.ok).length,passed=outcomes.length-failed;return[colors.green(`${passed} passed`),...failed===0?[]:[colors.red(`${failed} failed`)],colors.dim(formatDuration(outcomes.reduce((sum,outcome)=>sum+outcome.ms,0)))].join(colors.dim(" \xB7 "))}async function runOnce(config,held){let{cwd,steps,slotting,lock,timeoutMs,parallel,failFast,retries,json,quiet}=config,directory=await logDirectory(cwd),stack=new Stack,width=Math.max(...steps.map((step)=>step.label.length)),outcomes=[],heading=json||quiet?"":header("check",`${basename2(cwd)} \xB7 ${steps.length} ${steps.length===1?"step":"steps"}`,process2.stdout);if(heading!=="")console.log(heading);let execute=async(step,signals)=>{let down=step.placement===void 0?void 0:await stack.problem(step.placement),command=slotting?slotted(launch(step),lock):launch(step),logFile=join4(directory,`${step.label.replaceAll("/","-")}.log`),outcome,attempts=0;for(;;)if(attempts+=1,logFile=attempts===1?join4(directory,`${step.label.replaceAll("/","-")}.log`):join4(directory,`${step.label.replaceAll("/","-")}-try${attempts}.log`),outcome=down===void 0?await runStep(command,step.dir,logFile,{...timeoutMs===void 0?{}:{timeoutMs},held:signals}):await refusedStep(down,logFile),outcome.ok||down!==void 0||outcome.timedOut===!0||signals.signal!==void 0||attempts>retries)break;return{step,logFile,outcome,attempts}},report=({step,logFile,outcome,attempts})=>{let retryNote=attempts>1?`attempt ${attempts}/${retries+1}`:void 0,notes=[step.note,retryNote,step.placement===void 0?void 0:`in ${step.placement.service}`].filter((each)=>each!==void 0),described=notes.length===0?step.command:`${step.command} (${notes.join(", ")})`;if(!json&&!(quiet&&outcome.ok))printOutcome(step.label,width,described,logFile,outcome,step.dir);outcomes.push(outcomeJson(step.label,step.command,logFile,outcome,step.placement?.service,step.dir))};if(parallel){let children=new Set,shared={get signal(){return held.signal},forward:(child)=>children.add(child),release:held.release};held.forward({kill:(signal)=>{for(let child of children)child.kill(signal)}});let aborted=!1,runs=steps.map(async(step)=>{let result=await execute(step,shared);if(failFast&&!result.outcome.ok&&!aborted){aborted=!0;for(let child of children)child.kill("SIGTERM")}return result});for(let run of runs)report(await run)}else for(let step of steps){let result=await execute(step,held);if(report(result),held.signal!==void 0||failFast&&!result.outcome.ok)break}let ran=outcomes.map(({name,ok})=>({name,ok})),kept=(await lastResults(cwd)??[]).filter(({name})=>!ran.some((each)=>each.name===name));if(await writeFile2(join4(directory,RESULTS_FILE),JSON.stringify([...kept,...ran]),{mode:384}),json)printJson(outcomes);else if(heading!==""||quiet&&!outcomes.every((outcome)=>outcome.ok))console.log(summaryLine(outcomes));if(held.signal!==void 0)return exitCodeOf(null,held.signal);if(outcomes.some((outcome)=>outcome.timedOut===!0))return 2;return outcomes.every((outcome)=>outcome.ok)?0:1}function shouldIgnoreWatchPath(filename){if(filename===null)return!1;let ignored=ignoredFolders([".git","var","tmp"]);return filename.split("/").some((part)=>part.startsWith(".git")||ignored.has(part))}async function watchAndRun(config,dirs){let held=holdSignals(),watchers=[],timer,running=!1,pending=!1,trigger=async()=>{if(running){pending=!0;return}running=!0;try{await runOnce(config,held)}finally{running=!1}if(pending&&held.signal===void 0)pending=!1,trigger()};try{if(await trigger(),held.signal!==void 0)return exitCodeOf(null,held.signal);console.log(paint(process2.stdout).dim("watching for changes (Ctrl-C to stop)...")),await new Promise((resolveDone)=>{let done=()=>{if(timer!==void 0)clearTimeout(timer);resolveDone()};held.forward({kill:()=>done()});for(let dir of new Set(dirs))watchers.push(watch(dir,{recursive:!0},(_event,filename)=>{if(held.signal!==void 0||shouldIgnoreWatchPath(filename))return;if(timer!==void 0)clearTimeout(timer);timer=setTimeout(()=>{if(held.signal===void 0)trigger()},WATCH_DEBOUNCE_MS)}))})}finally{for(let watcher of watchers)watcher.close();held.release()}return held.signal===void 0?0:exitCodeOf(null,held.signal)}async function check(args,cwd=process2.cwd()){let parsed=parse(args,usage,options,{exits:EXITS,positionals:["[path...]"],replaces:"chaining docker compose exec <service> bun run check | tail, lint and test by hand, or bun run check && bun run lint && bun run test read through tail, and with --fix each fixer and formatter run by hand",examples:["check",["check packages/kit --only lint,test","one workspace, two steps"],["check --changed --base main -x","narrowed to branch diff, fail fast"],["check --in app","every step inside the app service"],["check --fix --changed","fixers on changed files only"]]}),settings=placeSettings(parsed.values),rc=await loadCheckConfig(cwd);if(parsed.values.fix===!0){for(let flag of["failed","slot","no-slot","parallel","fail-fast","watch"])if(parsed.values[flag]===!0)fail(`--${flag} does not apply to --fix`);if(parsed.values.retry!==void 0||parsed.values.lock!==void 0)fail("--retry and --lock do not apply to --fix");return runFixers(parsed.values,cwd)}let timeoutRaw=parsed.values.timeout??rc?.timeout,timeoutMs=timeoutRaw===void 0?void 0:duration(timeoutRaw,"timeout",0),retries=parsed.values.retry===void 0?0:wholeNumber(parsed.values.retry,"--retry",0,0),lock=parsed.values.lock??rc?.lock;if(parsed.values.slot===!0&&parsed.values["no-slot"]===!0)fail("--slot and --no-slot exclude each other");let hasSlot=Bun.which("slot",{PATH:process2.env.PATH??""})!==null;if(
|
|
14
|
+
With --fix, the project's fix, lint:fix and fmt or format scripts run instead, then the formatters its files call for (php-cs-fixer, \`just --fmt\`, go fmt, cargo fmt, ruff), and the files they changed are listed.`,EXITS=[[0,"every step passed"],[1,"one failed"],[2,"bad usage, no step is found or a step timed out"]],WATCH_DEBOUNCE_MS=200;function slotted(command,lock){return`slot ${lock===void 0?"":`--lock ${shellQuote(lock)} `}-- sh -c ${shellQuote(command)}`}async function plan(steps,settings){let planned=[];for(let{project,...step}of steps)planned.push({...step,dir:project.dir,label:project.name===void 0?step.name:`${project.name}/${step.name}`,placement:await place(project.dir,programOf(step.command),settings)});return planned}async function narrowed(steps,base){let cache=new Map,result=[];for(let step of steps){if(!cache.has(step.dir)){let paths=await changedPaths(step.dir,base);if(paths===void 0)fail("--changed needs a git repository");cache.set(step.dir,paths)}let{command,note}=await narrow(step,step.dir,cache.get(step.dir)??[]);result.push({...step,command,note})}return result}function launch(step){return step.placement===void 0?step.command:shellIn(step.placement,step.command)}function summaryLine(outcomes){let colors=paint(process2.stdout),failed=outcomes.filter((outcome)=>!outcome.ok).length,passed=outcomes.length-failed;return[colors.green(`${passed} passed`),...failed===0?[]:[colors.red(`${failed} failed`)],colors.dim(formatDuration(outcomes.reduce((sum,outcome)=>sum+outcome.ms,0)))].join(colors.dim(" \xB7 "))}async function runOnce(config,held){let{cwd,steps,slotting,lock,timeoutMs,parallel,failFast,retries,json,quiet}=config,directory=await logDirectory(cwd),stack=new Stack,width=Math.max(...steps.map((step)=>step.label.length)),outcomes=[],heading=json||quiet?"":header("check",`${basename2(cwd)} \xB7 ${steps.length} ${steps.length===1?"step":"steps"}`,process2.stdout);if(heading!=="")console.log(heading);let execute=async(step,signals)=>{let down=step.placement===void 0?void 0:await stack.problem(step.placement),command=slotting?slotted(launch(step),lock):launch(step),logFile=join4(directory,`${step.label.replaceAll("/","-")}.log`),outcome,attempts=0;for(;;)if(attempts+=1,logFile=attempts===1?join4(directory,`${step.label.replaceAll("/","-")}.log`):join4(directory,`${step.label.replaceAll("/","-")}-try${attempts}.log`),outcome=down===void 0?await runStep(command,step.dir,logFile,{...timeoutMs===void 0?{}:{timeoutMs},held:signals}):await refusedStep(down,logFile),outcome.ok||down!==void 0||outcome.timedOut===!0||signals.signal!==void 0||attempts>retries)break;return{step,logFile,outcome,attempts}},report=({step,logFile,outcome,attempts})=>{let retryNote=attempts>1?`attempt ${attempts}/${retries+1}`:void 0,notes=[step.note,retryNote,step.placement===void 0?void 0:`in ${step.placement.service}`].filter((each)=>each!==void 0),described=notes.length===0?step.command:`${step.command} (${notes.join(", ")})`;if(!json&&!(quiet&&outcome.ok))printOutcome(step.label,width,described,logFile,outcome,step.dir);outcomes.push(outcomeJson(step.label,step.command,logFile,outcome,step.placement?.service,step.dir))};if(parallel){let children=new Set,shared={get signal(){return held.signal},forward:(child)=>children.add(child),release:held.release};held.forward({kill:(signal)=>{for(let child of children)child.kill(signal)}});let aborted=!1,runs=steps.map(async(step)=>{let result=await execute(step,shared);if(failFast&&!result.outcome.ok&&!aborted){aborted=!0;for(let child of children)child.kill("SIGTERM")}return result});for(let run of runs)report(await run)}else for(let step of steps){let result=await execute(step,held);if(report(result),held.signal!==void 0||failFast&&!result.outcome.ok)break}let ran=outcomes.map(({name,ok})=>({name,ok})),kept=(await lastResults(cwd)??[]).filter(({name})=>!ran.some((each)=>each.name===name));if(await writeFile2(join4(directory,RESULTS_FILE),JSON.stringify([...kept,...ran]),{mode:384}),json)printJson(outcomes);else if(heading!==""||quiet&&!outcomes.every((outcome)=>outcome.ok))console.log(summaryLine(outcomes));if(held.signal!==void 0)return exitCodeOf(null,held.signal);if(outcomes.some((outcome)=>outcome.timedOut===!0))return 2;return outcomes.every((outcome)=>outcome.ok)?0:1}function shouldIgnoreWatchPath(filename){if(filename===null)return!1;let ignored=ignoredFolders([".git","var","tmp"]);return filename.split("/").some((part)=>part.startsWith(".git")||ignored.has(part))}async function watchAndRun(config,dirs){let held=holdSignals(),watchers=[],timer,running=!1,pending=!1,trigger=async()=>{if(running){pending=!0;return}running=!0;try{await runOnce(config,held)}finally{running=!1}if(pending&&held.signal===void 0)pending=!1,trigger()};try{if(await trigger(),held.signal!==void 0)return exitCodeOf(null,held.signal);console.log(paint(process2.stdout).dim("watching for changes (Ctrl-C to stop)...")),await new Promise((resolveDone)=>{let done=()=>{if(timer!==void 0)clearTimeout(timer);resolveDone()};held.forward({kill:()=>done()});for(let dir of new Set(dirs))watchers.push(watch(dir,{recursive:!0},(_event,filename)=>{if(held.signal!==void 0||shouldIgnoreWatchPath(filename))return;if(timer!==void 0)clearTimeout(timer);timer=setTimeout(()=>{if(held.signal===void 0)trigger()},WATCH_DEBOUNCE_MS)}))})}finally{for(let watcher of watchers)watcher.close();held.release()}return held.signal===void 0?0:exitCodeOf(null,held.signal)}async function check(args,cwd=process2.cwd()){let parsed=parse(args,usage,options,{exits:EXITS,positionals:["[path...]"],replaces:"chaining docker compose exec <service> bun run check | tail, lint and test by hand, or bun run check && bun run lint && bun run test read through tail, and with --fix each fixer and formatter run by hand",examples:["check",["check packages/kit --only lint,test","one workspace, two steps"],["check --changed --base main -x","narrowed to branch diff, fail fast"],["check --in app","every step inside the app service"],["check --fix --changed","fixers on changed files only"]]}),settings=placeSettings(parsed.values),rc=await loadCheckConfig(cwd);if(parsed.values.fix===!0){for(let flag of["failed","slot","no-slot","parallel","fail-fast","watch"])if(parsed.values[flag]===!0)fail(`--${flag} does not apply to --fix`);if(parsed.values.retry!==void 0||parsed.values.lock!==void 0)fail("--retry and --lock do not apply to --fix");return runFixers(parsed.values,cwd)}let timeoutRaw=parsed.values.timeout??rc?.timeout,timeoutMs=timeoutRaw===void 0?void 0:duration(timeoutRaw,"timeout",0),retries=parsed.values.retry===void 0?0:wholeNumber(parsed.values.retry,"--retry",0,0),lock=parsed.values.lock??rc?.lock;if(parsed.values.slot===!0&&parsed.values["no-slot"]===!0)fail("--slot and --no-slot exclude each other");let hasSlot=Bun.which("slot",{PATH:process2.env.PATH??""})!==null;if(lock!==void 0&&!hasSlot)fail("--lock needs the slot bin: bun install -g @kaynooo/cli-wait");if(parsed.values.slot===!0&&!hasSlot)console.error("slot bin not found, running unqueued: bun install -g @kaynooo/cli-wait");let slotting=parsed.values["no-slot"]!==!0&&hasSlot,targets=parsed.positionals,projects=await discoverProjects(cwd,targets),found=projects.flatMap((project)=>project.steps.map((step)=>({...step,project,label:project.name===void 0?step.name:`${project.name}/${step.name}`})));if(found.length===0)fail(`no ${STEP_NAMES.join(", ")} step in package.json, composer.json, deno.json, Justfile, Makefile, Taskfile, mise, pyproject.toml, Go, Rust, Python or PHP configs, nor in a subfolder`);let only=parsed.values.only??(rc?.only!==void 0&&rc.only.length>0?rc.only.join(","):void 0),wanted=pick(found,only);if(parsed.values.failed===!0){let failed=await lastFailed(cwd);if(failed===void 0||failed.length===0)fail("no failed step in the last run of this folder");if(wanted=wanted.filter((step)=>failed.includes(step.label)),wanted.length===0)fail(`none of the steps picked failed in the last run, which failed ${failed.join(", ")}`)}let planned=await plan(wanted,settings),base=parsed.values.base??rc?.base,steps=parsed.values.changed===!0?await narrowed(planned,base):planned,json=parsed.values.json===!0;if(parsed.values.list===!0){if(json)printJson(steps.map(({label,command,source,placement})=>({name:label,command,source,...placement===void 0?{}:{in:placement.service}})));else console.log(table(steps.map((step)=>[step.label,step.command,step.source,step.placement?.service??"host"])));return 0}let config={cwd,steps,slotting,lock,timeoutMs,parallel:parsed.values.parallel===!0||rc?.parallel===!0,failFast:parsed.values["fail-fast"]===!0||rc?.failFast===!0,retries,json,quiet:parsed.values.quiet===!0};if(parsed.values.watch===!0)return watchAndRun(config,projects.map((project)=>project.dir));let held=holdSignals();try{return await runOnce(config,held)}finally{held.release()}}process3.exitCode=await runMain({name:"check",version,run:async(args)=>check(args)});
|
package/dist/errs-cli.js
CHANGED
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
#!/bin/sh
|
|
2
2
|
// @bun 2>/dev/null; exec bun --no-env-file --config=/dev/null "$0" "$@"
|
|
3
|
-
import{paint,warn,role,stripAnsi,printJson,readInput,jsonOption,fail,parse}from"./chunk-ngcnmctk.js";import{holdSignals,runCommand,runMain,place,argvIn,Stack,placeOptions,placeSettings,version}from"./chunk-
|
|
3
|
+
import{paint,warn,role,stripAnsi,printJson,readInput,jsonOption,fail,parse}from"./chunk-ngcnmctk.js";import{holdSignals,runCommand,runMain,place,argvIn,Stack,placeOptions,placeSettings,version}from"./chunk-898e3vv3.js";import{parseErrors,formatError,saveLog}from"./chunk-1rrfsren.js";import process2 from"process";import{relative}from"path";import process from"process";var usage=`errs [options] [log]
|
|
4
4
|
errs [options] -- <command> [args...]
|
|
5
5
|
errs --in <service> | --host -- <command> [args...]
|
|
6
6
|
|
package/dist/j-cli.js
CHANGED
|
@@ -1,11 +1,11 @@
|
|
|
1
1
|
#!/bin/sh
|
|
2
2
|
// @bun 2>/dev/null; exec bun --no-env-file --config=/dev/null "$0" "$@"
|
|
3
|
-
import{isInteractive,paint,role,closest,table,printJson,jsonOption,fail,parse,cacheFolder}from"./chunk-ngcnmctk.js";import{runMain,shellQuote,place,argvIn,Stack,placeOptions,placeSettings,version}from"./chunk-
|
|
3
|
+
import{isInteractive,paint,role,closest,table,printJson,jsonOption,fail,parse,cacheFolder}from"./chunk-ngcnmctk.js";import{runMain,shellQuote,place,argvIn,Stack,placeOptions,placeSettings,version}from"./chunk-898e3vv3.js";import{stopJob,visible,CTRL_KEY,styled,parseKeys,createState,withRows,appendRows,highlighted,press,chosen,SYNC_START,SYNC_END,overwrite,input2}from"./chunk-eg6m1ry1.js";import{justFlags,everything,readKind,key,id,resolve,shortest,signature}from"./chunk-kbkmjjg6.js";import process6 from"process";import{resolve as resolvePath}from"path";import process5 from"process";import{existsSync,mkdirSync,readFileSync,writeFileSync}from"fs";import{dirname,join}from"path";import process3 from"process";import{openSync}from"fs";import process2 from"process";import tty from"tty";import process from"process";var PREVIEW_BYTES=65536,PREVIEW_LINES=200,PREVIEW_TIMEOUT_MS=3000,PLACEHOLDER=/\{([1-9]\d*)?\}/g;function previewCommand(template,line,hidden=[]){return template.replace(PLACEHOLDER,(_,field)=>shellQuote(field===void 0?line:hidden[Number(field)-1]??""))}function previewLines(output){let lines=output.split(`
|
|
4
4
|
`);if(lines.at(-1)==="")lines.pop();return lines.slice(0,PREVIEW_LINES)}async function runPreview(template,line,signal,hidden=[]){let proc=Bun.spawn(["sh","-c",`exec 2>&1
|
|
5
5
|
${previewCommand(template,line,hidden)}`],{stdin:"ignore",stdout:"pipe",stderr:"ignore",detached:!0}),stop=()=>{try{process.kill(-proc.pid,"SIGKILL")}catch{proc.kill()}},timer=setTimeout(stop,PREVIEW_TIMEOUT_MS),chunks=[],size=0;signal.addEventListener("abort",stop);try{for await(let chunk of proc.stdout)if(chunks.push(chunk),size+=chunk.length,size>=PREVIEW_BYTES){stop();break}}finally{clearTimeout(timer),signal.removeEventListener("abort",stop)}return signal.aborted?[]:previewLines(Buffer.concat(chunks).subarray(0,PREVIEW_BYTES).toString())}var MIN_HEIGHT=4,PREVIEW_MIN_COLUMNS=80,PREVIEW_MIN_ROWS=10,PREVIEW_SHARE=0.4,PREVIEW_RIGHT_SHARE=0.5,RESET="\x1B[0m",SEPARATOR=" \u2502 ",HEIGHT=/^(\d+)(%?)$/;function parseHeight(text){let found=HEIGHT.exec(text);if(found===null||Number(found[1])<1)return;return found[2]==="%"?{percent:Math.min(100,Number(found[1]))}:{lines:Number(found[1])}}function layoutFor(size,height,previewing,position="right",share){let wanted="lines"in height?height.lines:Math.round(size.rows*height.percent/100),rows=Math.min(size.rows,Math.max(MIN_HEIGHT,wanted));if(!previewing||position==="hidden")return{height:rows,listHeight:rows,listWidth:size.columns,previewWidth:0,previewHeight:0};if(position==="down"){let previewHeight=rows>=PREVIEW_MIN_ROWS?Math.round(rows*(share??PREVIEW_SHARE)):0;return{height:rows,listHeight:rows-previewHeight,listWidth:size.columns,previewWidth:0,previewHeight}}let split=size.columns>=PREVIEW_MIN_COLUMNS,rightShare=share??PREVIEW_RIGHT_SHARE,listWidth=split?Math.max(10,Math.floor(size.columns*(1-rightShare))):size.columns;return{height:rows,listHeight:rows,listWidth,previewWidth:split?Math.max(0,size.columns-listWidth-SEPARATOR.length):0,previewHeight:0}}function fit(text,width,plain,mark=plain,marked=new Set,styles){let room=Bun.stringWidth(text)>width?width-1:width,out="",used=0,at=0;for(let char of text){let size=Bun.stringWidth(char);if(used+size>room)break;let style=marked.has(at)?"":styles?.[at]??"";out+=style===""?(marked.has(at)?mark:plain)(char):`${style}${char}${RESET}`,used+=size,at+=char.length}if(room<width)out+=plain("\u2026"),used+=1;return{text:out,width:used}}var identity=(text)=>text;function fitStyled(line,width,plain=identity){let{text,styles}=styled(line);return fit(text,width,plain,plain,new Set,styles)}function queryShown(state,layout){return visible({text:state.query,caret:state.caret},Math.max(1,layout.listWidth-Bun.stringWidth(state.prompt)))}function caretCell(state,layout){let shown=queryShown(state,layout);return{column:Math.min(layout.listWidth,Bun.stringWidth(state.prompt)+shown.column+1),char:shown.at??" "}}function helpLines(state,layout,theme){let lines=["type to filter, up, down, ctrl-p, ctrl-n, pgup, pgdn, home, end, the wheel move","left, right, ctrl-a, ctrl-e move in the query, ctrl or alt with left or right by a word","ctrl-w or ctrl-backspace erase a word, ctrl-u back to the start, ctrl-k to the end, del ahead","ctrl-y puts back what they erased, ctrl-z suspends to the shell",`enter picks${state.multi?", tab marks":""}, esc or ctrl-c cancels`,...state.expect.length>0?[`${state.expect.join(", ")} end the pick as this command asks`]:[]],title="keys, any key closes this help";return[{text:theme.accent("keys, any key closes this help"),width:30},...lines.map((line)=>fit(` ${line}`,layout.listWidth,theme.label))]}function listLines(state,layout,theme){if(state.help)return helpLines(state,layout,theme);let header=state.header===""?[]:state.header.split(`
|
|
6
6
|
`).map((line)=>fitStyled(line,layout.listWidth,theme.label)),rows=Math.max(1,layout.listHeight-2-header.length),prefixWidth=state.multi?4:2,top=Math.max(0,Math.min(state.cursor-Math.floor(rows/2),state.matches.length-rows)),marks=(state.marked.size>0?` (${state.marked.size} marked)`:"")+(state.status===""?"":` ${state.status}`),promptWidth=Bun.stringWidth(state.prompt),shown=queryShown(state,layout),text=`${shown.before}${shown.at??""}${shown.after}`,query={text,width:Bun.stringWidth(text)},place=state.matches.length>rows?` (${state.cursor+1} of ${state.matches.length})`:"",count=fit(` ${state.matches.length}/${state.items.length}${place}${marks} ctrl-/ keys`,layout.listWidth,theme.label),lines=[{text:theme.accent(state.prompt)+query.text,width:promptWidth+query.width},count,...header];if(state.matches.length===0)lines.push(fit(" no match",layout.listWidth,theme.label));for(let[offset,match]of state.matches.slice(top,top+rows).entries()){let current=top+offset===state.cursor,pointer=current?theme.accent("\u276F"):" ",mark=state.multi?`${state.marked.has(match.index)?theme.id("\u25CF"):" "} `:"",text=fit(state.items[match.index],layout.listWidth-prefixWidth,current?theme.value:identity,theme.match??theme.accent,new Set(match.positions),state.styles[match.index]);lines.push({text:`${pointer} ${mark}${text.text}`,width:prefixWidth+text.width})}return lines}function render(state,layout,theme,preview=[]){let left=listLines(state,layout,theme);return Array.from({length:layout.height},(_,row)=>{if(row>=layout.listHeight)return row===layout.listHeight?theme.label("\u2500".repeat(layout.listWidth)):fitStyled(preview[row-layout.listHeight-1]??"",layout.listWidth).text;let list=left[row]??{text:"",width:0};if(layout.previewWidth===0)return list.text;return`${list.text}${" ".repeat(Math.max(0,layout.listWidth-list.width))}${theme.label(SEPARATOR)}${fitStyled(preview[row]??"",layout.previewWidth).text}`})}var PREVIEW_DELAY_MS=120,ESCAPE_WAIT_MS=30,OPEN={ctrl:"open"},HIDE_CURSOR="\x1B[?25l",SHOW_CURSOR="\x1B[?25h",REVERSE="\x1B[7m",REVERSE_END="\x1B[27m",PASTE_ON="\x1B[?2004h",PASTE_OFF="\x1B[?2004l",MOUSE_ON="\x1B[?1000h\x1B[?1006h",MOUSE_OFF="\x1B[?1006l\x1B[?1000l",CLEAR_BELOW="\r\x1B[J",SIGNALS=["SIGINT","SIGTERM","SIGHUP"];function up(lines){return lines>0?`\x1B[${lines}A`:""}function openTerminal(){let mode;try{mode=new tty.ReadStream(openSync("/dev/tty","r"))}catch{return fail("no terminal to read keys from (/dev/tty)")}let keys=Bun.file("/dev/tty").stream().getReader(),out=process2.stderr,resize;async function read(onChunk){let decoder=new TextDecoder;try{for(let chunk=await keys.read();!chunk.done;chunk=await keys.read())onChunk(decoder.decode(chunk.value,{stream:!0}))}catch{onChunk("\x03")}}return{get columns(){return out.columns||80},get rows(){return out.rows||24},theme:{accent:role("accent",out),label:role("label",out),value:role("value",out),id:role("id",out),match:(text)=>paint(out).underline(role("accent",out)(text))},write:(text)=>void out.write(text),listen(onChunk,onResize){resize=onResize,mode.setRawMode(!0),out.on("resize",onResize),read(onChunk)},suspend(){mode.setRawMode(!1),stopJob(),mode.setRawMode(!0)},close(){if(resize!==void 0)out.off("resize",resize);try{mode.setRawMode(!1)}finally{mode.destroy(),keys.cancel()}}}}async function select(rows,settings,terminal=openTerminal()){let{theme}=terminal,state=createState(rows,settings),preview=[],reserved=0,previewTimer,previewing=new AbortController,shownLine,finish,restored=!1,escape,showPreview=settings.preview!==void 0&&settings.previewPosition!=="hidden";function draw(clear=!1){if(restored)return;let layout=layoutFor({columns:terminal.columns,rows:terminal.rows},settings.height,showPreview,settings.previewPosition,settings.previewShare),frame=SYNC_START+HIDE_CURSOR;if(reserved!==layout.height||clear)frame+=CLEAR_BELOW+`
|
|
7
7
|
`.repeat(layout.height-1)+up(layout.height-1),reserved=layout.height;let caret=caretCell(state,layout);frame+=`\r${overwrite(render(state,layout,theme,preview),terminal.columns)}${up(layout.height-1)}\r\x1B[${caret.column}G${REVERSE}${caret.char}${REVERSE_END}\r${SYNC_END}`,terminal.write(frame)}function pageSize(){let headerLines=state.header===""?0:state.header.split(`
|
|
8
8
|
`).length;return Math.max(1,layoutFor({columns:terminal.columns,rows:terminal.rows},settings.height,showPreview,settings.previewPosition,settings.previewShare).listHeight-2-headerLines)}function refreshPreview(){let at=highlighted(state);if(!showPreview||settings.preview===void 0||at===shownLine)return;if(shownLine=at,clearTimeout(previewTimer),previewing.abort(),previewing=new AbortController,at===void 0){preview=[];return}let{signal}=previewing,template=settings.preview,row=state.rows[at];async function show(){let shown=typeof template==="string"?await runPreview(template,row.cells.join(" "),signal,row.hidden):await previewOf(template,row.hidden,signal);if(!signal.aborted)preview=shown,draw()}previewTimer=setTimeout(()=>void show(),PREVIEW_DELAY_MS)}function restore(){if(restored)return;restored=!0,clearTimeout(previewTimer),clearTimeout(escape),previewing.abort(),terminal.write(`${CLEAR_BELOW}${MOUSE_OFF}${PASTE_OFF}${SHOW_CURSOR}`),terminal.close()}function suspend(){if(terminal.suspend===void 0)return;terminal.write(`${CLEAR_BELOW}${MOUSE_OFF}${PASTE_OFF}${SHOW_CURSOR}`),terminal.suspend(),terminal.write(`${PASTE_ON}${MOUSE_ON}`),draw(!0)}let stop=()=>{state={...state,done:"cancel"},finish?.()},paste={active:!1},{reload}=settings,pending=[],busy=!1,draining=!1;async function reloadRows(){if(reload===void 0)return;busy=!0,state={...state,status:"reloading"},draw();try{let next=await reload.run();state={...withRows(state,next.rows,next.header),status:""},shownLine=void 0}catch(error){state={...state,status:`reload failed: ${error instanceof Error?error.message:String(error)}`}}finally{busy=!1}}async function drain(){if(draining)return;draining=!0;try{for(let key=pending.shift();key!==void 0&&state.done===void 0;key=pending.shift())if(key===OPEN||typeof key==="object"&&"ctrl"in key&&key.ctrl===reload?.key)await reloadRows();else if(key==="suspend")suspend();else state=press({...state,page:pageSize()},key)}finally{draining=!1}if(state.done!==void 0){finish?.();return}refreshPreview(),draw()}function onChunk(chunk){if(escape!==void 0)clearTimeout(escape),escape=void 0,chunk=`\x1B${chunk}`;else if(chunk==="\x1B"){escape=setTimeout(()=>{escape=void 0,takeKeys("\x1B")},ESCAPE_WAIT_MS);return}takeKeys(chunk)}function takeKeys(chunk){let keys=parseKeys(chunk,paste,[...settings.expect??[],...reload?.key===void 0?[]:[reload.key]]);if(busy&&keys.includes("cancel")){stop();return}pending.push(...keys),drain()}let ended=new Promise((resolve)=>{finish=resolve});process2.once("exit",restore);for(let signal of SIGNALS)process2.once(signal,stop);async function consumeStream(source){state={...state,status:"loading"},draw();try{for await(let batch of source){if(restored||state.done!==void 0)return;if(batch.length===0)continue;state=appendRows(state,batch),refreshPreview(),draw()}}finally{if(!restored&&state.done===void 0)state={...state,status:""},draw()}}try{if(terminal.write(`${PASTE_ON}${MOUSE_ON}`),terminal.listen(onChunk,()=>draw(!0)),refreshPreview(),draw(!0),settings.stream!==void 0)consumeStream(settings.stream);if(reload?.onOpen===!0)pending.push(OPEN),drain();await ended}finally{for(let signal of SIGNALS)process2.off(signal,stop);process2.off("exit",restore),restore()}return state.done==="accept"?{rows:chosen(state),key:state.key,query:state.query}:void 0}async function previewOf(preview,hidden,signal){try{return previewLines(await preview(hidden,signal))}catch(error){return[error instanceof Error?error.message:String(error)]}}var REMEMBERED=20;async function pick(rows,options){let height=parseHeight(options.height??"100%"),keys=[...options.expect??[],...options.reload?.key===void 0?[]:[options.reload.key]];if(height===void 0)throw Error(`pick: the height is lines or a percentage, not ${options.height}`);for(let key of keys)if(!CTRL_KEY.test(key))throw Error(`pick: ${key} is not a key it can report, one of ctrl-a to ctrl-z but ctrl-c, h, i, j and m`);let found=await select(rows,{multi:!1,prompt:options.prompt,query:"",height,preview:options.preview,previewPosition:"down",header:options.header,expect:options.expect,searched:options.searched,reload:options.reload});return found===void 0?void 0:{key:found.key,hidden:found.rows[0]?.hidden??[],query:found.query}}function heightFor(count){return String(Math.max(15,Math.ceil((count+4)/0.6)))}function historyFile(name){return join(cacheFolder(),name,"history.json")}function history(name){try{let file=historyFile(name);return existsSync(file)?JSON.parse(readFileSync(file,"utf-8")):{}}catch{return{}}}function runs(name){return history(name)[process3.cwd()]??[]}function record(name,run){let all=history(name),file=historyFile(name);all[process3.cwd()]=[run,...(all[process3.cwd()]??[]).filter((earlier)=>earlier.id!==run.id)].slice(0,REMEMBERED),mkdirSync(dirname(file),{recursive:!0}),writeFileSync(file,JSON.stringify(all))}function byRecency(items,previous,idOf){let rankMap=new Map(previous.map((run,index)=>[run.id,index]));return[...items.filter((item)=>rankMap.has(idOf(item))).sort((a,b)=>rankMap.get(idOf(a))-rankMap.get(idOf(b))),...items.filter((item)=>!rankMap.has(idOf(item)))]}function word(arg){if(typeof arg==="string")return`=${arg}`;return"given"in arg?`+${arg.given}`:`?${arg.ask}`}function emit(mode,typed,recorded,command){let words=command.map(word);console.log([mode,typed,recorded,...words].join(`
|
|
9
|
-
`))}function list(rows){console.log(JSON.stringify(rows))}import process4 from"process";var TINTS={just:"yellow",make:"blue",package:"magenta",composer:"cyan",deno:"green",task:"cyan",mise:"red",poe:"green",uv:"green"};function labelled(entries){return new Set(entries.map((entry)=>entry.tag)).size>1}function row(entry,labels,signed){let colors=paint(process4.stderr),keyed=entry.dir==="."?entry.name:`${colors.dim(`${entry.dir}/`)}${entry.name}`;return{hidden:[entry.kind,entry.dir,entry.name,id(entry)],cells:[...labels?[colors[TINTS[entry.kind]](entry.tag)]:[],keyed,...signed?[colors.cyan(signature(entry))]:[],colors.dim(entry.doc??"")]}}async function pickJob(entries,narrowed=!1){let labels=labelled(entries),signed=entries.some((entry)=>signature(entry)!==""),picked=await pick(entries.map((entry)=>row(entry,labels,signed)),{prompt:`${[...new Set(entries.map((entry)=>entry.tag))].join("/")}> `,searched:labels?2:1,...narrowed?{height:heightFor(entries.length)}:{},preview:`${process4.execPath} ${process4.argv[1]} --show {1} {2} {3}`});return entries.find((candidate)=>id(candidate)===picked?.hidden[3])}var usage="j [name] [args...] [--in <service> | --host]\nj -\n\nWithout a name, picks a recipe, script or task of this folder, its parents and its child folders and runs it, the ones run last first; without a terminal it lists them instead.\n`j -` runs the last one again with the same arguments, `j <name> [args...]` runs without the picker, the words after the name filling the parameters in order.\nThe sources are a Justfile, a Makefile, package.json and composer.json scripts, deno tasks, a Taskfile, mise tasks and a pyproject; a name several share offers them, unless qualified by its runner (`just:check`).",EXITS=[["its own","the code of the command it ran"],[1,"there is nothing to run here or nothing by that name"]],options={...placeOptions,json:jsonOption("[{ id, key, runner, dir, name, doc, parameters }]")};function preview(kind,dir,name){let entry=readKind(kind,dir).find((candidate)=>candidate.name===name);if(entry===void 0)return;let colors=paint(process5.stdout);if(console.log(`${colors.dim(`$ ${dir==="."?"":`env -C ${dir} `}`)}${colors.bold([...entry.runner,entry.name].join(" "))}
|
|
9
|
+
`))}function list(rows){console.log(JSON.stringify(rows))}import process4 from"process";var TINTS={just:"yellow",make:"blue",package:"magenta",composer:"cyan",deno:"green",task:"cyan",mise:"red",poe:"green",uv:"green"};function labelled(entries){return new Set(entries.map((entry)=>entry.tag)).size>1}function row(entry,labels,signed){let colors=paint(process4.stderr),keyed=entry.dir==="."?entry.name:`${colors.dim(`${entry.dir}/`)}${entry.name}`;return{hidden:[entry.kind,entry.dir,entry.name,id(entry)],cells:[...labels?[colors[TINTS[entry.kind]](entry.tag)]:[],keyed,...signed?[colors.cyan(signature(entry))]:[],colors.dim(entry.doc??"")]}}async function pickJob(entries,narrowed=!1){let labels=labelled(entries),signed=entries.some((entry)=>signature(entry)!==""),picked=await pick(entries.map((entry)=>row(entry,labels,signed)),{prompt:`${[...new Set(entries.map((entry)=>entry.tag))].join("/")}> `,searched:labels?2:1,...narrowed?{height:heightFor(entries.length)}:{},preview:`${process4.execPath} ${process4.argv[1]} --show {1} {2} {3}`});return entries.find((candidate)=>id(candidate)===picked?.hidden[3])}var usage="j [name] [args...] [--in <service> | --host]\nj -\n\nWithout a name, picks a recipe, script or task of this folder, its parents and its child folders and runs it, the ones run last first; without a terminal it lists them instead.\n`j -` runs the last one again with the same arguments, `j <name> [args...]` runs without the picker, the words after the name filling the parameters in order.\nThe sources are a Justfile, a Makefile, package.json and composer.json scripts, deno tasks, a Taskfile, mise tasks and a pyproject; a name several share offers them, unless qualified by its runner (`just:check`).\nA script runs in the compose service that bind-mounts its folder, a Justfile, Makefile, Taskfile or mise task on the host, as its recipes drive the stack; `--in` and `--host` override either.",EXITS=[["its own","the code of the command it ran"],[1,"there is nothing to run here or nothing by that name"]],options={...placeOptions,json:jsonOption("[{ id, key, runner, dir, name, doc, parameters }]")};function preview(kind,dir,name){let entry=readKind(kind,dir).find((candidate)=>candidate.name===name);if(entry===void 0)return;let colors=paint(process5.stdout);if(console.log(`${colors.dim(`$ ${dir==="."?"":`env -C ${dir} `}`)}${colors.bold([...entry.runner,entry.name].join(" "))}
|
|
10
10
|
`),entry.body!==void 0)console.log(entry.body);else Bun.spawnSync(["just",...justFlags(dir,dir===".")??[],"--show",name],{stdout:"inherit",stderr:"inherit"})}function names(found){let described=(entry)=>entry.doc===null||entry.doc===""?entry.tag:entry.doc;return[...new Set(found.map(key))].flatMap((name)=>{let same=resolve(found,name);return same.length===1?[[name,described(same[0])]]:[[name,same.map((entry)=>entry.tag).join(", ")],...same.map((entry)=>[id(entry),described(entry)])]})}function completions(){try{return[...names(everything()),["-","the last one again, with its arguments"]]}catch{return[]}}function listed(found){let labels=labelled(found);return byRecency(found,runs("j"),id).map((entry)=>({label:[labels?entry.tag:"",key(entry),signature(entry)].filter(Boolean).join(" "),hint:entry.doc??"",typed:shortest(found,entry),preview:["--show",entry.kind,entry.dir,entry.name],editsTyped:!0}))}function listing(found){let colors=paint(process5.stdout),labels=labelled(found);return table(found.map((entry)=>[...labels?[entry.tag]:[],key(entry),signature(entry),colors.dim(entry.doc??"")]))}function missing(entry,given){return entry.parameters.slice(given.length).filter((parameter)=>parameter.default===null&¶meter.kind==="singular").map((parameter)=>parameter.name)}function commandOf(entry,args){let separated=entry.separated&&args.length>0?["--"]:[];return[...entry.dir==="."?[]:["env","-C",entry.dir],...entry.runner,entry.name,...separated,...args]}async function j(argv){let[flag=""]=argv;if(flag==="--show"){let[kind="just",dir=".",name=""]=argv.slice(1);return preview(kind,dir,name),0}if(flag==="--record")return record("j",{id:argv[1]??"",args:argv.slice(2)}),0;if(flag==="--list"||flag==="--names"){let found=everything();if(found.length===0)fail("nothing to run here: no recipe, target, script or task",1);if(flag==="--list")list(listed(found));else console.log(names(found).map(([name,description])=>`${name} ${description}`).join(`
|
|
11
11
|
`));return 0}let emitting=flag==="--emit",args=emitting?argv.slice(1):argv,parsed=args[0]==="-"?{values:{},positionals:["-"],rest:args.slice(1)}:parse(args,usage,options,{exits:EXITS,positionals:["[name]"],candidates:{"[name]":completions},trailing:!0,replaces:"reading the Justfile, Makefile, package.json scripts or composer scripts to find what to run, then retyping it",examples:["j",["j test","run the test recipe, script or task"],["j --in app test","run inside the app compose service"],["j api/test --watch","a child folder's, with an argument"],["j just:check","the one of a runner, when several share the name"],["j -","the last one again"]]}),settings=placeSettings(parsed.values),[named]=parsed.positionals,given=parsed.rest??[],found=everything();if(found.length===0)fail("nothing to run here: no recipe, target, script or task",1);let previous=runs("j"),interactive=isInteractive()&&parsed.values.json!==!0,entry,words=given;if(named==="-"){let earlier=previous[0];if(entry=earlier&&found.find((candidate)=>id(candidate)===earlier.id),entry===void 0)fail(earlier?`${earlier.id} is gone`:"nothing run here yet",1);words=[...earlier.args,...given]}else if(named===void 0){if(!interactive){if(emitting)fail("the picker needs a terminal",1);if(parsed.values.json===!0)printJson(found.map((each)=>({id:id(each),key:key(each),runner:each.tag,dir:each.dir,name:each.name,doc:each.doc,parameters:each.parameters})));else console.log(listing(found));return 0}entry=await pickJob(byRecency(found,previous,id))}else{let matching=resolve(found,named);if(matching.length===0){let nearest=closest(named,found.map(key));fail(`nothing named ${named}${nearest===void 0?"":`, did you mean ${nearest}?`}`,1)}if(matching.length>1&&!interactive)fail(`${named} is several: ${matching.map(id).join(", ")}`,1,"qualify it with its runner");entry=matching.length===1?matching[0]:await pickJob(matching,!0)}if(entry===void 0)return 1;let typed=shortest(found,entry),asks=missing(entry,words);if(emitting)return emit("run",typed,id(entry),commandOf(entry,[...words.map((word)=>({given:word})),...asks.map((ask)=>({ask}))])),0;let answers=[];for(let ask of asks){let answer=await input2(ask,{history:`j ${id(entry)} ${ask}`,hint:`pass ${ask} as an argument after \`j ${typed}\``});if(answer===void 0)return 1;answers.push(answer)}let all=[...words,...answers];record("j",{id:id(entry),args:all});let entryDir=resolvePath(entry.dir),placement=await place(entryDir,entry.runner[0]??"",settings);if(placement!==void 0){let down=await new Stack().problem(placement);if(down!==void 0)fail(down,1);let separated=entry.separated&&all.length>0?["--"]:[],inner=[...entry.runner,entry.name,...separated,...all];return Bun.spawn(argvIn(placement,inner),{cwd:placement.composeDir,stdio:["inherit","inherit","inherit"]}).exited}return Bun.spawn(commandOf(entry,all),{stdio:["inherit","inherit","inherit"]}).exited}process6.exitCode=await runMain({name:"j",version,run:j});
|
package/package.json
CHANGED
|
@@ -1,7 +1,7 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "@kaynooo/cli-check",
|
|
3
3
|
"type": "module",
|
|
4
|
-
"version": "0.
|
|
4
|
+
"version": "0.24.1",
|
|
5
5
|
"description": "check and errs: run a repo's check, typecheck, lint, format check and test steps or, with --fix, its fixers, inside its docker compose service when one mounts the folder, showing only what failed with each full output saved to a file, and turn tsc, eslint, bun test, vitest, playwright, phpunit, phpstan and php-cs-fixer logs into file:line:col errors.",
|
|
6
6
|
"author": "Kaynooo <contact@kaynooo.fr>",
|
|
7
7
|
"license": "MIT",
|
|
@@ -39,6 +39,6 @@
|
|
|
39
39
|
"j": "$npm_execpath src/j-cli.ts"
|
|
40
40
|
},
|
|
41
41
|
"devDependencies": {
|
|
42
|
-
"@kaynooo/cli-kit": "0.52.
|
|
42
|
+
"@kaynooo/cli-kit": "0.52.1"
|
|
43
43
|
}
|
|
44
44
|
}
|