Compare commits
| Author | SHA1 | Date | |
|---|---|---|---|
|
|
f2c1a60884 | ||
|
|
32128d28a5 | ||
|
|
0aeb8ca052 | ||
|
|
6dc76788e2 | ||
|
|
f9d561ae57 | ||
|
|
546a0dd8d3 | ||
|
|
1b9f407264 | ||
|
|
bde2b69b11 | ||
|
|
49e4f8a756 | ||
|
|
e0a016c6ae | ||
|
|
f5d03ffe54 | ||
|
|
2bdf3ecc9e | ||
|
|
5f0b2d75d6 | ||
|
|
7395313229 | ||
|
|
9c9229cf8e | ||
|
|
b9b50c8cf6 | ||
|
|
bbb7247e25 | ||
|
|
65e30d4e84 | ||
|
|
14556d6260 | ||
|
|
4d53834f54 | ||
|
|
eaf0a48146 | ||
|
|
a08364ffa5 | ||
|
|
a3beb56d50 | ||
|
|
ff24094656 | ||
|
|
c14068f7be | ||
|
|
2a43d41974 | ||
|
|
3bd2ba4a86 | ||
|
|
7e7bb30aa2 | ||
|
|
f5432cea1d | ||
|
|
0c1aacf166 | ||
|
|
4f7e704516 | ||
|
|
170b827db6 | ||
|
|
c771a852f5 | ||
|
|
cb02c5e47f | ||
|
|
0fd1759760 | ||
|
|
3b69ccbe9b | ||
|
|
246655c279 | ||
|
|
b9e843c607 | ||
|
|
2279e803d7 | ||
|
|
ab051e7351 | ||
|
|
50d780d32a | ||
|
|
3a1891e8b8 | ||
|
|
bafd131b8b | ||
|
|
8e3aa43282 | ||
|
|
f87a9ff637 | ||
|
|
74b9f487ee | ||
|
|
2b682c2eac | ||
|
|
9ae81dc7db | ||
|
|
54383ccc70 | ||
|
|
0ee640b601 | ||
|
|
39a8b3019f | ||
|
|
299651c8c9 | ||
|
|
901f2e48d9 | ||
|
|
34d613f336 | ||
|
|
1688b3501b | ||
|
|
8566df62c7 | ||
|
|
78cb4ad96d | ||
|
|
ceb7424680 | ||
|
|
709f51b2fa | ||
|
|
6eeac03dea | ||
|
|
9900ca8eb6 | ||
|
|
7573caad0f | ||
|
|
91bfd6de4d | ||
|
|
0a166135aa | ||
|
|
9f3108376e | ||
|
|
2d4a9006ce | ||
|
|
bfed7311b9 | ||
|
|
b735f37952 | ||
|
|
9d981f1e0d | ||
|
|
a1e787dde4 | ||
|
|
bf1265a9ca | ||
|
|
07cff80588 | ||
|
|
9551d30b3d | ||
|
|
7e2649bfd2 | ||
|
|
07dad250ed | ||
|
|
eb5a52f148 | ||
|
|
d40360c9b7 | ||
|
|
2927fb468f | ||
|
|
9872c4b1a9 | ||
|
|
6968a1a63c | ||
|
|
f737cbcb93 | ||
|
|
52cc91c3d5 | ||
|
|
632bbe6150 | ||
|
|
e7c5ce5b54 | ||
|
|
de5db5d3c0 | ||
|
|
860c566b86 | ||
|
|
5b52c745dd | ||
|
|
1d278369a6 | ||
|
|
795f12252c | ||
|
|
741b128664 | ||
|
|
d4ae64314f | ||
|
|
77c04e9c98 | ||
|
|
756f60f350 | ||
|
|
3861597c02 | ||
|
|
39b2a1e5e8 | ||
|
|
c96a713317 | ||
|
|
1b8c014fd4 | ||
|
|
2622813bfe | ||
|
|
55031de03e | ||
|
|
354cf423eb | ||
|
|
a704864e5d | ||
|
|
08ccd6e962 | ||
|
|
8d08c0bbd4 | ||
|
|
8a000fe3ee | ||
|
|
2a29742b89 | ||
|
|
4c5125b528 | ||
|
|
8ad7e91b57 | ||
|
|
2ba4501201 | ||
|
|
7083681752 | ||
|
|
0f55d18146 | ||
|
|
8b95b9561e | ||
|
|
2c126825c5 | ||
|
|
2f3b937b3b | ||
|
|
ac965de730 | ||
|
|
04c930e027 | ||
|
|
28d36379b2 | ||
|
|
11a7c187f8 | ||
|
|
6b8ff8d31e | ||
|
|
5c4610d763 | ||
|
|
aba25afc1c | ||
|
|
c1d24d0197 | ||
|
|
dfaead471b | ||
|
|
2b8f5dc997 | ||
|
|
e4d390214d | ||
|
|
968c36577d | ||
|
|
2ee9ccc0eb | ||
|
|
bf1c132bb7 | ||
|
|
af11cb23b0 | ||
|
|
133053e63a | ||
|
|
2c51343bab | ||
|
|
c6d6c45727 | ||
|
|
21c5cdde54 | ||
|
|
d64bf7fd84 | ||
|
|
831a559256 | ||
|
|
2654dc541a | ||
|
|
6d619e37de | ||
|
|
eab18ef1f0 | ||
|
|
28feb5924b | ||
|
|
64773edfd4 | ||
|
|
9eba684da9 | ||
|
|
d3974255f9 | ||
|
|
dbfcf06fa6 | ||
|
|
ec7ec3cb09 | ||
|
|
f20a76f723 | ||
|
|
f67f2efb5c | ||
|
|
f10465e54a | ||
|
|
767b6d6430 | ||
|
|
0f47303091 | ||
|
|
e23808417f | ||
|
|
33eb969778 | ||
|
|
8b8fa70ce4 | ||
|
|
4d0b91ed94 | ||
|
|
12e0612b48 | ||
|
|
98e05f4998 | ||
|
|
2fa99ec3a2 | ||
|
|
8dd212fc71 | ||
|
|
a4bbaf9f27 | ||
|
|
419a8118fc | ||
|
|
da5b621cb6 | ||
|
|
1df0263a42 | ||
|
|
74394cbde9 | ||
|
|
f1ea0f9156 | ||
|
|
fff8869aff | ||
|
|
a0c5a5f18c | ||
|
|
b309e3e6f0 | ||
|
|
09cdc91761 | ||
|
|
a18573c9f8 | ||
|
|
eacc92ce4b | ||
|
|
3bcc958dda | ||
|
|
11f0bbee53 | ||
|
|
c145ad0900 | ||
|
|
e02c1f018f | ||
|
|
07fea6238f | ||
|
|
5f1fdfa6c1 | ||
|
|
4fb25d0463 | ||
|
|
bf23894188 | ||
|
|
aec0f9f171 | ||
|
|
83fed68432 | ||
|
|
4311533445 | ||
|
|
ce28b948d0 | ||
|
|
efc602e0ba | ||
|
|
917063db0c | ||
|
|
3e552428a5 | ||
|
|
50455c491d | ||
|
|
12ec399b09 | ||
|
|
5a49998c2c | ||
|
|
590f19603e | ||
|
|
ee8c4b9aa5 | ||
|
|
e8d6613ac8 | ||
|
|
91ad9006fa | ||
|
|
60ba3ad417 | ||
|
|
b74e4724d4 | ||
|
|
30246fd626 | ||
|
|
06aed7b27a | ||
|
|
b001dfe667 | ||
|
|
d905ad027a | ||
|
|
3f6a03aee8 | ||
|
|
302e874710 | ||
|
|
9d9820072a | ||
|
|
53d14345b9 | ||
|
|
67c3346f2f | ||
|
|
346afdd143 | ||
|
|
48729cdfa4 | ||
|
|
b9574f0106 | ||
|
|
635ca463c0 | ||
|
|
2459988ff0 | ||
|
|
6ab08fe97f | ||
|
|
2dafe4a981 | ||
|
|
ec24e0713d | ||
|
|
969ccae25c | ||
|
|
5b46ff0efd | ||
|
|
d234616406 | ||
|
|
af3e55e518 | ||
|
|
13b48229ac | ||
|
|
670f6ed7a0 | ||
|
|
bbc7c50fae | ||
|
|
779d1e0a0e | ||
|
|
54581f0216 | ||
|
|
3d01822e77 | ||
|
|
4e0ca92c77 | ||
|
|
388e54b3e3 | ||
|
|
6f2e76221a | ||
|
|
e0d3b938e3 | ||
|
|
491a030bf8 | ||
|
|
bff7cc2a27 | ||
|
|
ff30b00e71 | ||
|
|
e1eb5eeaa6 | ||
|
|
2a2e11d8e0 | ||
|
|
6eb4f31127 | ||
|
|
4b58e00c26 | ||
|
|
8ffd8af13c | ||
|
|
67861d4455 | ||
|
|
299e6d8bfe | ||
|
|
388822e90a | ||
|
|
91993b4548 | ||
|
|
bb69558aaa | ||
|
|
052c670627 | ||
|
|
67fd215d0e | ||
|
|
9ecbbff6fa | ||
|
|
774ac0f0ca | ||
|
|
b785d24a08 | ||
|
|
22f991e72e | ||
|
|
5518b27663 | ||
|
|
0b899dea2c | ||
|
|
3424fea8ad | ||
|
|
ddc1d83d58 | ||
|
|
4b0a85411d | ||
|
|
46e871b626 | ||
|
|
258dcc88e7 | ||
|
|
75bf449bed | ||
|
|
58586395fb | ||
|
|
c5a68af5e6 | ||
|
|
b4c0284734 | ||
|
|
c5d1dad8de |
No files matched your search
@@ -1,2 +1,4 @@
|
||||
*.exe
|
||||
.qodo
|
||||
*.sqlite
|
||||
.cursor/rules
|
||||
@@ -0,0 +1,7 @@
|
||||
*
|
||||
!configs
|
||||
!configs/**
|
||||
!hooks
|
||||
!hooks/**
|
||||
!qlty.toml
|
||||
!.gitignore
|
||||
@@ -0,0 +1 @@
|
||||
source-path=SCRIPTDIR
|
||||
@@ -0,0 +1,81 @@
|
||||
# This file was automatically generated by `qlty init`.
|
||||
# You can modify it to suit your needs.
|
||||
# We recommend you to commit this file to your repository.
|
||||
#
|
||||
# This configuration is used by both Qlty CLI and Qlty Cloud.
|
||||
#
|
||||
# Qlty CLI -- Code quality toolkit for developers
|
||||
# Qlty Cloud -- Fully automated Code Health Platform
|
||||
#
|
||||
# Try Qlty Cloud: https://qlty.sh
|
||||
#
|
||||
# For a guide to configuration, visit https://qlty.sh/d/config
|
||||
# Or for a full reference, visit https://qlty.sh/d/qlty-toml
|
||||
config_version = "0"
|
||||
|
||||
exclude_patterns = [
|
||||
"*_min.*",
|
||||
"*-min.*",
|
||||
"*.min.*",
|
||||
"**/.yarn/**",
|
||||
"**/*.d.ts",
|
||||
"**/assets/**",
|
||||
"**/bower_components/**",
|
||||
"**/build/**",
|
||||
"**/cache/**",
|
||||
"**/config/**",
|
||||
"**/db/**",
|
||||
"**/deps/**",
|
||||
"**/dist/**",
|
||||
"**/extern/**",
|
||||
"**/external/**",
|
||||
"**/generated/**",
|
||||
"**/Godeps/**",
|
||||
"**/gradlew/**",
|
||||
"**/mvnw/**",
|
||||
"**/node_modules/**",
|
||||
"**/protos/**",
|
||||
"**/seed/**",
|
||||
"**/target/**",
|
||||
"**/templates/**",
|
||||
"**/testdata/**",
|
||||
"**/vendor/**",
|
||||
"cmd/rj.go",
|
||||
"cmd/xj.go",
|
||||
]
|
||||
|
||||
test_patterns = [
|
||||
"**/test/**",
|
||||
"**/spec/**",
|
||||
"**/*.test.*",
|
||||
"**/*.spec.*",
|
||||
"**/*_test.*",
|
||||
"**/*_spec.*",
|
||||
"**/test_*.*",
|
||||
"**/spec_*.*",
|
||||
]
|
||||
|
||||
[smells]
|
||||
mode = "comment"
|
||||
|
||||
[runtimes.enabled]
|
||||
go = "1.26.0"
|
||||
|
||||
[[source]]
|
||||
name = "default"
|
||||
default = true
|
||||
|
||||
|
||||
[[plugin]]
|
||||
name = "gofmt"
|
||||
|
||||
[[plugin]]
|
||||
name = "golangci-lint"
|
||||
|
||||
[[plugin]]
|
||||
name = "radarlint-go"
|
||||
|
||||
[[triage]]
|
||||
match.plugins = ["golangci-lint"]
|
||||
match.rules = ["golangci-lint:gosec"]
|
||||
set.ignored = true
|
||||
Vendored
+67
-3
@@ -11,10 +11,20 @@
|
||||
"mode": "auto",
|
||||
"program": "${workspaceFolder}",
|
||||
"cwd": "C:/Users/Administrator/Seafile/Games-Barotrauma",
|
||||
"args": [
|
||||
"*.toml",
|
||||
]
|
||||
},
|
||||
{
|
||||
"name": "Launch Package (Payday 2)",
|
||||
"type": "go",
|
||||
"request": "launch",
|
||||
"mode": "auto",
|
||||
"program": "${workspaceFolder}",
|
||||
"cwd": "C:/Users/Administrator/Seafile/Games-Payday2",
|
||||
"args": [
|
||||
"-loglevel",
|
||||
"trace",
|
||||
"-cook",
|
||||
"*.yml",
|
||||
]
|
||||
},
|
||||
@@ -32,17 +42,71 @@
|
||||
"cookassistant.yml",
|
||||
]
|
||||
},
|
||||
{
|
||||
"name": "Launch Package (Quasimorph cookfile)",
|
||||
"type": "go",
|
||||
"request": "launch",
|
||||
"mode": "auto",
|
||||
"program": "${workspaceFolder}",
|
||||
"cwd": "C:/Users/Administrator/Seafile/Games-Quasimorph",
|
||||
"args": [
|
||||
"cook.yml",
|
||||
]
|
||||
},
|
||||
{
|
||||
"name": "Launch Package (Rimworld cookfile)",
|
||||
"type": "go",
|
||||
"request": "launch",
|
||||
"mode": "auto",
|
||||
"program": "${workspaceFolder}",
|
||||
"cwd": "C:/Users/Administrator/Seafile/Games-Rimworld/294100",
|
||||
"args": [
|
||||
"cookVehicles.yml",
|
||||
]
|
||||
},
|
||||
{
|
||||
"name": "Launch Package (Workspace)",
|
||||
"type": "go",
|
||||
"request": "launch",
|
||||
"mode": "auto",
|
||||
"program": "${workspaceFolder}",
|
||||
"args": [
|
||||
"tester.yml",
|
||||
]
|
||||
},
|
||||
{
|
||||
"name": "Launch Package (Avorion)",
|
||||
"type": "go",
|
||||
"request": "launch",
|
||||
"mode": "auto",
|
||||
"program": "${workspaceFolder}",
|
||||
"cwd": "C:/Users/Administrator/Seafile/Games-Avorion/Avorion",
|
||||
"args": [
|
||||
"*.yml",
|
||||
]
|
||||
},
|
||||
{
|
||||
"name": "Launch Package (Minecraft)",
|
||||
"type": "go",
|
||||
"request": "launch",
|
||||
"mode": "auto",
|
||||
"program": "${workspaceFolder}",
|
||||
"cwd": "C:/Users/Administrator/Seafile/Games-Minecraft",
|
||||
"args": [
|
||||
"cook_tacz.yml",
|
||||
]
|
||||
},
|
||||
{
|
||||
"name": "Launch Package (ICARUS)",
|
||||
"type": "go",
|
||||
"request": "launch",
|
||||
"mode": "auto",
|
||||
"program": "${workspaceFolder}",
|
||||
"cwd": "C:/Users/Administrator/Seafile/Games-ICARUS/Icarus/Saved/IME3/Mods",
|
||||
"args": [
|
||||
"-loglevel",
|
||||
"trace",
|
||||
"-cook",
|
||||
"cookscoop.yml",
|
||||
"cook_processorrecipes.yml",
|
||||
]
|
||||
}
|
||||
]
|
||||
|
||||
@@ -1,116 +1,302 @@
|
||||
# Big Chef
|
||||
# Chef
|
||||
|
||||
A Go-based tool for modifying XML, JSON, and text documents using XPath/JSONPath/Regex expressions and Lua transformations.
|
||||
`chef` is a Go CLI for batch file transformations using regex, JSON, or XML mode with Lua scripts.
|
||||
It runs commands from cook files (`.toml` or `.yml/.yaml`), supports glob-based file selection, and keeps file snapshots so changes can be reset.
|
||||
|
||||
## Features
|
||||
## What it does
|
||||
|
||||
- **Multi-Format Processing**:
|
||||
- XML (XPath)
|
||||
- JSON (JSONPath)
|
||||
- Text (Regex)
|
||||
- **Node Value Modification**: Update text values in XML elements, JSON properties or text matches
|
||||
- **Attribute Manipulation**: Modify XML attributes, JSON object keys or regex capture groups
|
||||
- **Conditional Logic**: Apply transformations based on document content
|
||||
- **Complex Operations**:
|
||||
- Mathematical calculations
|
||||
- String manipulations
|
||||
- Date conversions
|
||||
- Structural changes
|
||||
- Whole ass Lua environment
|
||||
- **Error Handling**: Comprehensive error detection for:
|
||||
- Invalid XML/JSON
|
||||
- Malformed XPath/JSONPath
|
||||
- Lua syntax errors
|
||||
|
||||
## Usage Examples
|
||||
|
||||
### 1. Basic field modification
|
||||
```xml
|
||||
<!-- Input -->
|
||||
<price>44.95</price>
|
||||
|
||||
<!-- Command -->
|
||||
chef -xml "//price" "v=v*2" input.xml
|
||||
|
||||
<!-- Output -->
|
||||
<price>89.9</price>
|
||||
```
|
||||
|
||||
### 2. Supports glob patterns
|
||||
```xml
|
||||
chef -xml "//price" "v=v*2" data/**.xml
|
||||
```
|
||||
|
||||
### 3. Attribute Update
|
||||
```xml
|
||||
<!-- Input -->
|
||||
<item price="10.50"/>
|
||||
|
||||
<!-- Command -->
|
||||
chef -xml "//item/@price" "v=v*2" input.xml
|
||||
|
||||
<!-- Output -->
|
||||
<item price="21"/>
|
||||
```
|
||||
|
||||
### 3. JSONPath Transformation
|
||||
```json
|
||||
// Input
|
||||
{
|
||||
"products": [
|
||||
{"name": "Widget", "price": 19.99},
|
||||
{"name": "Gadget", "price": 29.99}
|
||||
]
|
||||
}
|
||||
|
||||
// Command
|
||||
chef -json "$.products[*].price" "v=v*0.75" input.json
|
||||
|
||||
// Output
|
||||
{
|
||||
"products": [
|
||||
{"name": "Widget", "price": 14.99},
|
||||
{"name": "Gadget", "price": 22.49}
|
||||
]
|
||||
}
|
||||
```
|
||||
|
||||
### 4. Regex Text Replacement
|
||||
Regex works slightly differently, up to 12 match groups are provided as v1..v12 and s1..s12 for numbers and strings respectively.
|
||||
A special shorthand "!num" is also provided that simply expands to `(\d*\.?\d+)`.
|
||||
```xml
|
||||
<!-- Input -->
|
||||
<description>Price: $15.00 Special Offer</description>
|
||||
|
||||
<!-- Command -->
|
||||
chef "Price: $!num Special Offer" "v1 = v1 * 0.92" input.xml
|
||||
|
||||
<!-- Output -->
|
||||
<description>Price: $13.80 Special Offer</description>
|
||||
```
|
||||
|
||||
### 5. Conditional Transformation
|
||||
```xml
|
||||
<!-- Input -->
|
||||
<item stock="5" price="10.00"/>
|
||||
|
||||
<!-- Command -->
|
||||
chef -xml "//item" "if tonumber(v.stock) > 0 then v.price = v.price * 0.8 end" input.xml
|
||||
|
||||
<!-- Output -->
|
||||
<item stock="5" price="8.00"/>
|
||||
```
|
||||
- Applies regex-based edits using Lua on capture groups (`v1`, `s1`, named groups, etc.).
|
||||
- Applies JSON edits by exposing parsed JSON as `data` in Lua (`json = true` command mode).
|
||||
- Applies XML edits by exposing parsed XML nodes as `data` in Lua (`xml = true` command mode).
|
||||
- Every command gets a `ctx` table with `source_file`, `target_file`, `command_name`, and (in regex mode) `capture` entries.
|
||||
- Supports multi-command pipelines, command filtering, per-command log levels, isolate passes, and reset behavior.
|
||||
- Saves original file snapshots in `data.sqlite` so you can restore files later.
|
||||
|
||||
## Installation
|
||||
|
||||
```bash
|
||||
go build -o chef main.go
|
||||
go build -o chef .
|
||||
```
|
||||
|
||||
## Quick start
|
||||
|
||||
1) Generate an example config:
|
||||
|
||||
```bash
|
||||
# Process XML file
|
||||
./chef -xml "//price" "v=v*1.2" input.xml
|
||||
|
||||
# Process JSON file
|
||||
./chef -json "$.prices[*]" "v=v*0.9" input.json
|
||||
chef --example
|
||||
```
|
||||
|
||||
This writes `example_cook.toml` in the current directory.
|
||||
|
||||
2) Run it:
|
||||
|
||||
```bash
|
||||
chef example_cook.toml
|
||||
```
|
||||
|
||||
3) Run only selected commands:
|
||||
|
||||
```bash
|
||||
chef -f "UpdateAmounts,Prefix" example_cook.toml
|
||||
```
|
||||
|
||||
4) Restore files from snapshots:
|
||||
|
||||
```bash
|
||||
chef reset
|
||||
```
|
||||
|
||||
5) Clear all saved snapshots:
|
||||
|
||||
```bash
|
||||
chef dump
|
||||
```
|
||||
|
||||
6) Open the interactive TUI:
|
||||
|
||||
```bash
|
||||
chef tui example_cook.toml
|
||||
```
|
||||
|
||||
## CLI flags
|
||||
|
||||
- `-P, --parallel` number of files to process concurrently (default `100`).
|
||||
- `-f, --filter` comma-separated command name filters.
|
||||
- `-c, --conv` convert YAML cook files to TOML (skips output if target `.toml` already exists).
|
||||
- `-e, --example` generate `example_cook.toml` and exit.
|
||||
- `-m, --meta` generate `meta.lua` (LuaLS autocomplete helper) and exit.
|
||||
- `-l, --loglevel` global log level (`ERROR`, `WARNING`, `INFO`, `DEBUG`, `TRACE`).
|
||||
|
||||
## TUI mode
|
||||
|
||||
Launch with:
|
||||
|
||||
```bash
|
||||
chef tui <cook-files...>
|
||||
```
|
||||
|
||||
Behavior:
|
||||
|
||||
- Displays files as top-level rows and commands indented under each file.
|
||||
- Toggle a command row to select that command for next run.
|
||||
- Toggle a file row to select/deselect all commands under that file.
|
||||
- Shows per-command status lines after runs:
|
||||
- green (modified, no errors)
|
||||
- yellow (no modifications, no errors)
|
||||
- red (errors)
|
||||
- Watched commands are marked with a blue watch indicator.
|
||||
|
||||
Hotkeys:
|
||||
|
||||
- `j` / `k` or arrow keys: move cursor
|
||||
- `Space`: toggle focused row
|
||||
- `a`: select all commands
|
||||
- `c`: clear all selections
|
||||
- `s`: run selected
|
||||
- `S`: run all
|
||||
- `w`: toggle watch on focused command
|
||||
- `W`: toggle watch for all commands under focused file
|
||||
- `e`: escape clipboard text (regex quote)
|
||||
- `E`: escape clipboard text with whitespace minimization
|
||||
- `q`: quit
|
||||
|
||||
Watch mode details:
|
||||
|
||||
- Watch source: **cook/config files only**.
|
||||
- Trigger engine: **fsnotify only**.
|
||||
- Debounce: `500ms`.
|
||||
- On cook file change, TUI reloads commands and reruns only watched commands whose definitions changed.
|
||||
|
||||
## Cook file format
|
||||
|
||||
`chef` executes commands from cook files. Prefer TOML (shown below), YAML is also supported.
|
||||
|
||||
```toml
|
||||
[[commands]]
|
||||
name = "MultiplyValues"
|
||||
regex = "value = !num"
|
||||
lua = "v1 = v1 * 1.5"
|
||||
files = ["data/**/*.txt"]
|
||||
loglevel = "INFO"
|
||||
|
||||
[[commands]]
|
||||
name = "JSONUpdate"
|
||||
json = true
|
||||
lua = "data.version = '2.0.0'; modified = true"
|
||||
files = ["config/**/*.json"]
|
||||
|
||||
[[commands]]
|
||||
name = "XMLUpdate"
|
||||
xml = true
|
||||
lua = "data.attr.version = '2'; modified = true"
|
||||
files = ["config/**/*.xml"]
|
||||
```
|
||||
|
||||
### Command fields
|
||||
|
||||
- `name`: display/log/filter name.
|
||||
- `regex`: single regex pattern (regex mode).
|
||||
- `regexes`: multiple regex patterns for one command.
|
||||
- `regex_pred`: optional prefilter regex; command runs only when file content matches.
|
||||
- `regex_preds`: optional list of prefilter regex patterns (OR semantics).
|
||||
- `lua`: Lua snippet or external file reference via `@path/to/script.lua`.
|
||||
- `files`: glob patterns to match target files.
|
||||
- `json`: command-level JSON mode.
|
||||
- `xml`: command-level XML mode.
|
||||
- `noreset`: skip reset for target files before this run (`false` by default, so files are reset unless `true`).
|
||||
- `isolate`: run command in an isolated pass before regular commands.
|
||||
- `nodedup`: disable overlap deduplication for capture groups.
|
||||
- `disable`: skip command.
|
||||
- `raw`: when used alone (no regex/json/xml), passes entire file content as the `data` string in Lua — equivalent to `regex = '(?s).*'` without regex. Has no effect when combined with json/xml (values are already plain).
|
||||
- `loglevel`: per-command log level override.
|
||||
|
||||
## Processing modes
|
||||
|
||||
### Regex mode (default)
|
||||
|
||||
- Use `regex` or `regexes` in a command.
|
||||
- Pattern helpers:
|
||||
- `!num` -> numeric capture pattern (`(-?\d*\.?\d+)`)
|
||||
- `!any` -> non-greedy wildcard (`.*?`)
|
||||
- `!rep(pattern, n)` -> repeats `pattern` `n` times
|
||||
- Unnamed capture groups are available as `s1..sN` (string) and `v1..vN` (number when parseable).
|
||||
- Named capture groups are available as Lua variables by name.
|
||||
- Set `replacement` in Lua to replace the full match; otherwise updates are applied to changed captures.
|
||||
|
||||
### JSON mode
|
||||
|
||||
- Enable per-command with `json = true`.
|
||||
- Parsed JSON is exposed as `data` in Lua.
|
||||
- Values are plain Lua values: numbers, strings, booleans, and null. Use `N(x)` (an alias for `tonumber`) to convert a string to a number.
|
||||
- JSONPath helper is available: `json.jpath(node, expr)` (use `data` for root).
|
||||
- JSONPath remover is available: `json.jpathrm(node, expr)` (returns removed count).
|
||||
- Set `modified = true` (or return truthy/nil) to apply changes.
|
||||
- Changes are applied surgically where possible to preserve unrelated formatting.
|
||||
|
||||
### XML mode
|
||||
|
||||
- Enable per-command with `xml = true`.
|
||||
- Parsed XML is exposed as `data` in Lua.
|
||||
- XML nodes expose:
|
||||
- `data.tag`: element name
|
||||
- `data.text`: plain string text
|
||||
- `data.attr`: attribute table of plain string values
|
||||
- `data.children`: child node array
|
||||
- `data.name.local`: local name
|
||||
- `data.name.uri`: namespace URI
|
||||
- `data.name.prefix`: namespace prefix
|
||||
- XPath helper is available: `xml.xpath(node, expr)` (use `data` for root).
|
||||
- XPath remover is available: `xml.xpathrm(node, expr)` (returns removed count).
|
||||
- Add/remove child nodes by mutating `data.children` with normal Lua table operations.
|
||||
- Set `modified = true` (or return truthy/nil) to apply changes.
|
||||
- Existing XML is edited surgically where possible; newly added nodes are serialized from the Lua node table.
|
||||
|
||||
## Lua runtime reference
|
||||
|
||||
### Variables available in Lua
|
||||
|
||||
- `@script.lua` in `lua` loads an external script relative to the cook file directory.
|
||||
- `file`: current file path being processed.
|
||||
- `modified`: boolean gate for applying changes.
|
||||
- Defaults to `false` before script execution.
|
||||
- Set to `true` when your script returns `nil` or truthy.
|
||||
- Set `modified = false` (or `return false`) to skip writing changes.
|
||||
- `ctx`: table with contextual metadata about the current command execution:
|
||||
- `ctx.source_file`: path to the cook file where this command is defined.
|
||||
- `ctx.target_file`: the file being processed in this iteration (same as `file`).
|
||||
- `ctx.command_name`: the command's name (same as `command_name` global).
|
||||
- `ctx.capture`: in regex mode, a table mirroring all capture group variables (`s1`, `v1`, named groups, etc.) as fields.
|
||||
|
||||
Regex mode adds:
|
||||
|
||||
- `s1..sN`: string value for unnamed capture groups.
|
||||
- `v1..vN`: numeric value for unnamed capture groups when parseable as number.
|
||||
- Named captures as variables, for example `(?P<amount>!num)` -> `amount`.
|
||||
- `replacement`: optional full-match replacement string.
|
||||
|
||||
Notes:
|
||||
|
||||
- If you prefer fixed positions, treat captures as `s1..s9` and `v1..v9` (and beyond when needed).
|
||||
- `vX` only exists when capture `sX` parses as a number.
|
||||
|
||||
JSON mode adds:
|
||||
|
||||
- `data`: parsed JSON document as a mutable Lua table.
|
||||
- `json.jpath(node, expr)`: evaluate JSONPath relative to `node`.
|
||||
- `json.jpathrm(node, expr)`: remove JSON nodes matched by JSONPath.
|
||||
|
||||
XML mode adds:
|
||||
|
||||
- `data`: parsed XML node tree as a mutable Lua table.
|
||||
- Node shape:
|
||||
- `tag`
|
||||
- `text`
|
||||
- `attr`
|
||||
- `children`
|
||||
- `name.local`
|
||||
- `name.uri`
|
||||
- `name.prefix`
|
||||
- `xml.xpath(node, expr)`: evaluate XPath relative to `node`.
|
||||
- `xml.xpathrm(node, expr)`: remove XML nodes matched by XPath.
|
||||
|
||||
Example:
|
||||
|
||||
```lua
|
||||
for _, item in ipairs(xml.xpath(data, "//Item")) do
|
||||
if item.attr.Weight then
|
||||
item.attr.Weight = N(item.attr.Weight) * 2
|
||||
end
|
||||
end
|
||||
|
||||
for _, group in ipairs(xml.xpath(data, "//Group")) do
|
||||
for _, entry in ipairs(xml.xpath(group, ".//Entry")) do
|
||||
entry.attr.Enabled = "true"
|
||||
end
|
||||
end
|
||||
|
||||
modified = true
|
||||
```
|
||||
|
||||
### CSV helpers
|
||||
|
||||
- `csv.read(text, options)` parses CSV/TSV into rows.
|
||||
- `csv.write(rows, options)` converts rows back into CSV/TSV text.
|
||||
|
||||
Supported options keys:
|
||||
|
||||
- `delimiter` (default `","`)
|
||||
- `hasheader` (default `false`)
|
||||
- `hascomments` (default `false`, skips lines starting with `#`)
|
||||
|
||||
Example:
|
||||
|
||||
```lua
|
||||
local rows = csv.read(csvText, {
|
||||
delimiter = "\t",
|
||||
hasheader = true,
|
||||
hascomments = true,
|
||||
})
|
||||
|
||||
rows[1].Price = util.num(rows[1].Price) * 1.1
|
||||
replacement = csv.write(rows, { delimiter = "\t", hasheader = true })
|
||||
modified = true
|
||||
```
|
||||
|
||||
## Useful Lua helpers
|
||||
|
||||
Built-in helpers:
|
||||
|
||||
- CSV: `csv.read(text, opts)`, `csv.write(rows, opts)`
|
||||
- JSON: `json.read(path)`, `json.visit(data, cb)`, `json.find(data, pred)`, `json.modifyNumbers(data, pred, mod)`, `json.jpath(node, expr)`, `json.jpathrm(node, expr)`
|
||||
- XML: `xml.read(path)`, `xml.find(root, tag)`, `xml.visit(root, cb)`, `xml.filter(root, pred)`, `xml.getAttr`/`xml.setAttr`/`xml.hasAttr`, `xml.getNumAttr`/`xml.setNumAttr`/`xml.modifyNumAttr`, `xml.getText`/`xml.setText`, `xml.findFirst`, `xml.addChild`/`xml.removeChildren`/`xml.getChildren`/`xml.countChildren`, `xml.xpath(node, expr)`, `xml.xpathrm(node, expr)`
|
||||
- Math: `math.round(x, n)`
|
||||
- Strings: `string.trim(s)`, `string.split(s, sep)`
|
||||
- Util: `util.printf(fmt, ...)`, `util.num(str)`, `util.str(n)`, `util.isNumber(s)`, `util.isArray(t)`, `util.dump(t)`
|
||||
- HTTP: `fetch(url, options)` returns `{status, statusText, ok, body, headers}`
|
||||
- Regex: `re(pattern, input)` returns match table (`[1]` full match, `[2+]` groups)
|
||||
|
||||
Run `chef --help` for the full generated helper reference, and `chef --meta` to generate `meta.lua` for editor autocomplete.
|
||||
|
||||
## Notes about `example_cook.toml`
|
||||
|
||||
`example_cook.toml` is intentionally broad and demonstrates many patterns (`regexes`, `isolate`, `nodedup`, JSON commands, multiline regex, external systems). Treat it as a feature showcase and copy only the parts you need into your own cook files.
|
||||
+139
@@ -0,0 +1,139 @@
|
||||
# TUI V2 Plan (Two-Pane, Lazygit-Style)
|
||||
|
||||
## Objective
|
||||
|
||||
Build a practical TUI that gives immediate feedback:
|
||||
|
||||
- Left pane: expandable tree of cook files and commands
|
||||
- Right pane: live command/watch logs
|
||||
|
||||
This is intentionally a two-pane UI (not multi-window like lazygit).
|
||||
|
||||
## Ground Rules
|
||||
|
||||
- Keep TUI logic isolated in `/tui` and thin adapter in `tui_cmd.go`.
|
||||
- Do not print runtime logs to stdout while TUI is active.
|
||||
- In TUI mode, logger handling order is:
|
||||
1. set level to `ERROR` first
|
||||
2. if debug mode enabled, create fresh `logger.Default` and redirect output to file (`chef.log`) using the new output-redirection method.
|
||||
|
||||
## UX Target
|
||||
|
||||
### Left Pane (Tree)
|
||||
|
||||
- Top-level nodes: cook files (config source files)
|
||||
- Child nodes: commands from each cook file
|
||||
- Expand/collapse per cook file (lazygit-like tree interaction)
|
||||
- Multi-select support for commands
|
||||
- Watched marker on watched commands
|
||||
|
||||
### Right Pane (Logs)
|
||||
|
||||
- Large scrollable log buffer
|
||||
- Show timeline entries with timestamp + event source
|
||||
- Show:
|
||||
- run start/end
|
||||
- per-command start/end and summary
|
||||
- watch tick detection and rerun decisions
|
||||
- errors with full message
|
||||
|
||||
### Footer
|
||||
|
||||
- Current mode + focused pane
|
||||
- Last action summary
|
||||
- Watch state summary (on/off, last tick time)
|
||||
|
||||
## Interaction Model
|
||||
|
||||
- `j/k`, arrows: move
|
||||
- `Enter` or `l`: expand/collapse file row
|
||||
- `Space`: select/deselect focused command
|
||||
- `a`: select all commands
|
||||
- `c`: clear selection
|
||||
- `s`: run selected
|
||||
- `S`: run all
|
||||
- `w`: toggle watch on selected commands
|
||||
- `Tab`: switch focus between left/right panes
|
||||
- `g/G` (right pane): top/bottom log
|
||||
- `q`: quit
|
||||
|
||||
## Logging and Feedback Pipeline
|
||||
|
||||
### Core idea
|
||||
|
||||
Treat the right pane as the primary feedback channel.
|
||||
|
||||
### Implementation
|
||||
|
||||
1. Introduce a TUI log sink (`io.Writer`) that appends lines to in-memory ring buffers.
|
||||
2. Attach sink to logger output in TUI mode (via the new logger redirection method).
|
||||
3. Emit structured lifecycle events in adapter code (`tui_cmd.go`) in addition to normal logs:
|
||||
- `watch_tick_detected`
|
||||
- `watch_reload_done`
|
||||
- `run_started`
|
||||
- `command_started`
|
||||
- `command_finished`
|
||||
- `run_finished`
|
||||
4. Render the active log buffer in right pane with autoscroll (while still allowing manual scroll).
|
||||
|
||||
## Watch Behavior (Pragmatic)
|
||||
|
||||
- Poll cook files at fixed interval (current 500ms is fine to start).
|
||||
- On detected cook-file content change:
|
||||
- reload commands
|
||||
- compare watched command snapshots (string compare on serialized command payload)
|
||||
- rerun watched commands that changed
|
||||
- log all decisions in right pane
|
||||
|
||||
If no watched command changed, log that explicitly.
|
||||
|
||||
## Architecture
|
||||
|
||||
### `/tui`
|
||||
|
||||
- `layout.go`: pane split calculations
|
||||
- `tree.go`: left pane model + expand/collapse + selection
|
||||
- `logs.go`: ring buffer + right pane scroll model
|
||||
- `render.go`: draw both panes + footer
|
||||
- `events.go`: app event types (run/watch/log)
|
||||
- `watch.go`: polling source of watch ticks
|
||||
|
||||
### `tui_cmd.go`
|
||||
|
||||
- load cook files + commands
|
||||
- run selected/all
|
||||
- watch reload + diff + rerun
|
||||
- publish events/log lines to TUI app
|
||||
|
||||
## Borrowed Patterns
|
||||
|
||||
### From `mprocs`
|
||||
|
||||
- Single layout function computes pane rectangles (`AppLayout` style)
|
||||
- Left list + right terminal pane separation
|
||||
- Active pane border/focus clarity
|
||||
|
||||
### From `lazygit`
|
||||
|
||||
- Keep command/action logs in dedicated panel
|
||||
- Keep layout and rendering responsibilities separate
|
||||
- Stream long-running output incrementally to UI pane
|
||||
|
||||
## Delivery Steps
|
||||
|
||||
1. Add two-pane layout skeleton (`left tree`, `right logs`).
|
||||
2. Move existing list/status rendering into left pane.
|
||||
3. Add right-pane ring-buffer log viewer.
|
||||
4. Wire run and watch lifecycle events into logs pane.
|
||||
5. Wire logger output redirection (with new method) for TUI mode.
|
||||
6. Add pane focus + log scrolling keybinds.
|
||||
7. Add explicit watch diagnostics lines to logs pane.
|
||||
8. Verify run/watch feedback is always visible without stdout.
|
||||
|
||||
## Acceptance Criteria
|
||||
|
||||
- User can always tell whether a command was run and what happened.
|
||||
- Editing watched cook file produces visible watch tick + rerun events in right pane.
|
||||
- Left pane supports expandable cook-file tree with command selection.
|
||||
- TUI does not rely on stdout for feedback.
|
||||
- TUI remains isolated from core logic except through adapter callbacks.
|
||||
@@ -0,0 +1,20 @@
|
||||
#!/bin/bash
|
||||
|
||||
set -euo pipefail
|
||||
|
||||
TAG="${1:-}"
|
||||
if [ -z "$TAG" ]; then
|
||||
TAG=$(git describe --tags --always --dirty)
|
||||
fi
|
||||
|
||||
COMMIT=$(git rev-parse --short HEAD)
|
||||
BUILD_DATE=$(date -u +"%Y-%m-%dT%H:%M:%SZ")
|
||||
LD_FLAGS="-s -w -X cook/internal/chef.Version=$TAG -X cook/internal/chef.Commit=$COMMIT -X cook/internal/chef.BuildDate=$BUILD_DATE"
|
||||
|
||||
echo "Building chef.exe"
|
||||
echo "Version: $TAG"
|
||||
echo "Commit: $COMMIT"
|
||||
echo "Date: $BUILD_DATE"
|
||||
|
||||
go build -ldflags "$LD_FLAGS" -o chef.exe .
|
||||
go install -ldflags "$LD_FLAGS" .
|
||||
@@ -0,0 +1,16 @@
|
||||
package cmd
|
||||
|
||||
import (
|
||||
"cook/internal/chef"
|
||||
|
||||
"github.com/spf13/cobra"
|
||||
)
|
||||
|
||||
func newClearCmd() *cobra.Command {
|
||||
return newRunCommand(
|
||||
"clear",
|
||||
"Clear the glob pattern -> file cache",
|
||||
cobra.NoArgs,
|
||||
chef.RunClearGlobCache,
|
||||
)
|
||||
}
|
||||
@@ -0,0 +1,71 @@
|
||||
//go:build e2e
|
||||
|
||||
package cmd
|
||||
|
||||
import (
|
||||
"bytes"
|
||||
"os"
|
||||
"testing"
|
||||
|
||||
"cook/utils"
|
||||
|
||||
"github.com/stretchr/testify/assert"
|
||||
"github.com/stretchr/testify/require"
|
||||
)
|
||||
|
||||
func TestClearCommand(t *testing.T) {
|
||||
t.Run("empty_cache/clears_without_error", func(t *testing.T) {
|
||||
tmp := t.TempDir()
|
||||
wd, err := os.Getwd()
|
||||
require.NoError(t, err)
|
||||
require.NoError(t, os.Chdir(tmp))
|
||||
t.Cleanup(func() {
|
||||
if err := os.Chdir(wd); err != nil {
|
||||
return
|
||||
}
|
||||
})
|
||||
|
||||
var stdout bytes.Buffer
|
||||
var stderr bytes.Buffer
|
||||
root := resetRootCmdForE2E(t)
|
||||
root.SetOut(&stdout)
|
||||
root.SetErr(&stderr)
|
||||
root.SetArgs([]string{"clear"})
|
||||
|
||||
err = root.Execute()
|
||||
require.NoError(t, err)
|
||||
})
|
||||
|
||||
t.Run("populated_cache/clears_all_entries", func(t *testing.T) {
|
||||
tmp := t.TempDir()
|
||||
wd, err := os.Getwd()
|
||||
require.NoError(t, err)
|
||||
require.NoError(t, os.Chdir(tmp))
|
||||
t.Cleanup(func() {
|
||||
if err := os.Chdir(wd); err != nil {
|
||||
return
|
||||
}
|
||||
})
|
||||
|
||||
db, err := utils.GetDB()
|
||||
require.NoError(t, err)
|
||||
require.NoError(t, db.SaveGlobCache("*.txt", []string{"a.txt", "b.txt"}))
|
||||
require.NoError(t, db.Close())
|
||||
|
||||
root := resetRootCmdForE2E(t)
|
||||
root.SetArgs([]string{"clear"})
|
||||
|
||||
err = root.Execute()
|
||||
require.NoError(t, err)
|
||||
|
||||
db2, err := utils.GetDB()
|
||||
require.NoError(t, err)
|
||||
t.Cleanup(func() {
|
||||
if err := db2.Close(); err != nil {
|
||||
return
|
||||
}
|
||||
})
|
||||
_, err = db2.GetGlobCache("*.txt")
|
||||
assert.Error(t, err)
|
||||
})
|
||||
}
|
||||
@@ -0,0 +1,30 @@
|
||||
package cmd
|
||||
|
||||
import (
|
||||
"github.com/spf13/cobra"
|
||||
)
|
||||
|
||||
// newRunCommand builds a simple subcommand that invokes a fixed function.
|
||||
func newRunCommand(use, short string, args cobra.PositionalArgs, run func() error) *cobra.Command {
|
||||
return &cobra.Command{
|
||||
Use: use,
|
||||
Short: short,
|
||||
Args: args,
|
||||
RunE: func(cmd *cobra.Command, _ []string) error {
|
||||
return run()
|
||||
},
|
||||
}
|
||||
}
|
||||
|
||||
// newArgsCommand builds a simple subcommand that invokes a function with the
|
||||
// positional arguments.
|
||||
func newArgsCommand(use, short string, run func([]string) error) *cobra.Command {
|
||||
return &cobra.Command{
|
||||
Use: use,
|
||||
Short: short,
|
||||
Args: cobra.MinimumNArgs(1),
|
||||
RunE: func(cmd *cobra.Command, args []string) error {
|
||||
return run(args)
|
||||
},
|
||||
}
|
||||
}
|
||||
+15
@@ -0,0 +1,15 @@
|
||||
package cmd
|
||||
|
||||
import (
|
||||
"cook/internal/chef"
|
||||
|
||||
"github.com/spf13/cobra"
|
||||
)
|
||||
|
||||
func newConvCmd() *cobra.Command {
|
||||
return newArgsCommand(
|
||||
"conv <yaml-file-pattern> [more yaml-file-pattern...]",
|
||||
"Convert YAML cook files to TOML",
|
||||
chef.ConvYAMLPatterns,
|
||||
)
|
||||
}
|
||||
@@ -0,0 +1,118 @@
|
||||
//go:build e2e
|
||||
|
||||
package cmd
|
||||
|
||||
import (
|
||||
"os"
|
||||
"path/filepath"
|
||||
"testing"
|
||||
|
||||
"github.com/stretchr/testify/assert"
|
||||
"github.com/stretchr/testify/require"
|
||||
)
|
||||
|
||||
const yamlGlob = "*.yaml"
|
||||
|
||||
func TestConvCommand(t *testing.T) {
|
||||
t.Run("single_yaml_file/converts_to_toml", func(t *testing.T) {
|
||||
tmp := t.TempDir()
|
||||
wd, err := os.Getwd()
|
||||
require.NoError(t, err)
|
||||
require.NoError(t, os.Chdir(tmp))
|
||||
t.Cleanup(func() {
|
||||
if err := os.Chdir(wd); err != nil {
|
||||
return
|
||||
}
|
||||
})
|
||||
|
||||
yamlContent := `commands:
|
||||
- name: replace
|
||||
regex: "foo"
|
||||
lua: "s1 = 'bar'"
|
||||
files: ["*.txt"]
|
||||
`
|
||||
require.NoError(t, os.WriteFile("input.yaml", []byte(yamlContent), 0644))
|
||||
|
||||
root := resetRootCmdForE2E(t)
|
||||
root.SetArgs([]string{"conv", yamlGlob})
|
||||
|
||||
err = root.Execute()
|
||||
require.NoError(t, err)
|
||||
|
||||
tomlPath := filepath.Join(tmp, "input.toml")
|
||||
b, readErr := os.ReadFile(tomlPath)
|
||||
require.NoError(t, readErr)
|
||||
assert.Contains(t, string(b), "[[commands]]")
|
||||
assert.Contains(t, string(b), `name = "replace"`)
|
||||
})
|
||||
|
||||
t.Run("yaml_file_with_existing_toml/skips_conversion", func(t *testing.T) {
|
||||
tmp := t.TempDir()
|
||||
wd, err := os.Getwd()
|
||||
require.NoError(t, err)
|
||||
require.NoError(t, os.Chdir(tmp))
|
||||
t.Cleanup(func() {
|
||||
if err := os.Chdir(wd); err != nil {
|
||||
return
|
||||
}
|
||||
})
|
||||
|
||||
yamlContent := `commands:
|
||||
- name: test
|
||||
regex: "x"
|
||||
files: ["*.txt"]
|
||||
`
|
||||
require.NoError(t, os.WriteFile("input.yaml", []byte(yamlContent), 0644))
|
||||
require.NoError(t, os.WriteFile("input.toml", []byte("existing"), 0644))
|
||||
|
||||
root := resetRootCmdForE2E(t)
|
||||
root.SetArgs([]string{"conv", yamlGlob})
|
||||
|
||||
err = root.Execute()
|
||||
require.NoError(t, err)
|
||||
})
|
||||
|
||||
t.Run("no_matching_files/succeeds_silently", func(t *testing.T) {
|
||||
tmp := t.TempDir()
|
||||
wd, err := os.Getwd()
|
||||
require.NoError(t, err)
|
||||
require.NoError(t, os.Chdir(tmp))
|
||||
t.Cleanup(func() {
|
||||
if err := os.Chdir(wd); err != nil {
|
||||
return
|
||||
}
|
||||
})
|
||||
|
||||
root := resetRootCmdForE2E(t)
|
||||
root.SetArgs([]string{"conv", yamlGlob})
|
||||
|
||||
err = root.Execute()
|
||||
require.NoError(t, err)
|
||||
})
|
||||
|
||||
t.Run("multiple_patterns/converts_all", func(t *testing.T) {
|
||||
tmp := t.TempDir()
|
||||
wd, err := os.Getwd()
|
||||
require.NoError(t, err)
|
||||
require.NoError(t, os.Chdir(tmp))
|
||||
t.Cleanup(func() {
|
||||
if err := os.Chdir(wd); err != nil {
|
||||
return
|
||||
}
|
||||
})
|
||||
|
||||
require.NoError(t, os.WriteFile("a.yaml", []byte("commands:\n - name: a\n regex: x\n files: ['*.txt']\n"), 0644))
|
||||
require.NoError(t, os.WriteFile("b.yaml", []byte("commands:\n - name: b\n regex: y\n files: ['*.txt']\n"), 0644))
|
||||
|
||||
root := resetRootCmdForE2E(t)
|
||||
root.SetArgs([]string{"conv", yamlGlob})
|
||||
|
||||
err = root.Execute()
|
||||
require.NoError(t, err)
|
||||
|
||||
_, aErr := os.ReadFile("a.toml")
|
||||
_, bErr := os.ReadFile("b.toml")
|
||||
require.NoError(t, aErr)
|
||||
require.NoError(t, bErr)
|
||||
})
|
||||
}
|
||||
@@ -0,0 +1,31 @@
|
||||
package cmd
|
||||
|
||||
import (
|
||||
"os"
|
||||
"path/filepath"
|
||||
"testing"
|
||||
|
||||
"github.com/stretchr/testify/assert"
|
||||
"github.com/stretchr/testify/require"
|
||||
)
|
||||
|
||||
func TestConvCommandRunE(t *testing.T) {
|
||||
tmpDir := t.TempDir()
|
||||
yamlContent := "commands:\n - name: test\n regex: value\n lua: s1\n files: [\"a.txt\"]\n"
|
||||
require.NoError(t, os.WriteFile(filepath.Join(tmpDir, "c.yml"), []byte(yamlContent), 0644))
|
||||
|
||||
origDir, err := os.Getwd()
|
||||
require.NoError(t, err)
|
||||
defer func() {
|
||||
if err := os.Chdir(origDir); err != nil {
|
||||
t.Logf("failed to restore working directory: %v", err)
|
||||
}
|
||||
}()
|
||||
require.NoError(t, os.Chdir(tmpDir))
|
||||
|
||||
c := newConvCmd()
|
||||
require.NoError(t, c.RunE(c, []string{"c.yml"}))
|
||||
|
||||
_, err = os.Stat(filepath.Join(tmpDir, "c.toml"))
|
||||
assert.NoError(t, err)
|
||||
}
|
||||
+16
@@ -0,0 +1,16 @@
|
||||
package cmd
|
||||
|
||||
import (
|
||||
"cook/internal/chef"
|
||||
|
||||
"github.com/spf13/cobra"
|
||||
)
|
||||
|
||||
func newDumpCmd() *cobra.Command {
|
||||
return newRunCommand(
|
||||
"dump",
|
||||
"Clear all stored file snapshots",
|
||||
cobra.NoArgs,
|
||||
chef.RunDumpSnapshots,
|
||||
)
|
||||
}
|
||||
@@ -0,0 +1,51 @@
|
||||
//go:build e2e
|
||||
|
||||
package cmd
|
||||
|
||||
import (
|
||||
"bytes"
|
||||
"os"
|
||||
"testing"
|
||||
|
||||
"cook/utils"
|
||||
|
||||
"github.com/stretchr/testify/assert"
|
||||
"github.com/stretchr/testify/require"
|
||||
)
|
||||
|
||||
func TestDumpCommand(t *testing.T) {
|
||||
t.Run("preseeded_snapshots/dump_deletes_all_rows", func(t *testing.T) {
|
||||
dir := t.TempDir()
|
||||
wd, err := os.Getwd()
|
||||
require.NoError(t, err)
|
||||
require.NoError(t, os.Chdir(dir))
|
||||
t.Cleanup(func() {
|
||||
if err := os.Chdir(wd); err != nil {
|
||||
return
|
||||
}
|
||||
})
|
||||
|
||||
db, err := utils.GetDB()
|
||||
require.NoError(t, err)
|
||||
require.NoError(t, db.SaveFile("a.txt", []byte("before")))
|
||||
require.NoError(t, db.Close())
|
||||
|
||||
var out bytes.Buffer
|
||||
var er bytes.Buffer
|
||||
root := resetRootCmdForE2E(t)
|
||||
root.SetOut(&out)
|
||||
root.SetErr(&er)
|
||||
root.SetArgs([]string{"dump"})
|
||||
|
||||
execOut, execErr := captureOutput(t, func() error { return root.Execute() })
|
||||
require.NoError(t, execErr, execOut+out.String()+er.String())
|
||||
|
||||
db2, err := utils.GetDB()
|
||||
require.NoError(t, err)
|
||||
var count int64
|
||||
require.NoError(t, db2.DB().Model(&utils.FileSnapshot{}).Count(&count).Error)
|
||||
require.NoError(t, db2.Close())
|
||||
|
||||
assert.Equal(t, int64(0), count)
|
||||
})
|
||||
}
|
||||
@@ -0,0 +1,50 @@
|
||||
package cmd
|
||||
|
||||
import (
|
||||
"os"
|
||||
"path/filepath"
|
||||
"testing"
|
||||
|
||||
"cook/utils"
|
||||
|
||||
"github.com/stretchr/testify/assert"
|
||||
"github.com/stretchr/testify/require"
|
||||
)
|
||||
|
||||
func TestDumpCommandRunE(t *testing.T) {
|
||||
tmpDir, err := os.MkdirTemp("", "dump-cmd-*")
|
||||
require.NoError(t, err)
|
||||
origDir, err := os.Getwd()
|
||||
require.NoError(t, err)
|
||||
defer func() {
|
||||
if err := os.Chdir(origDir); err != nil {
|
||||
t.Logf("failed to restore working directory: %v", err)
|
||||
}
|
||||
}()
|
||||
require.NoError(t, os.Chdir(tmpDir))
|
||||
|
||||
db, err := utils.GetDB()
|
||||
require.NoError(t, err)
|
||||
defer func() {
|
||||
if err := db.Close(); err != nil {
|
||||
return
|
||||
}
|
||||
}()
|
||||
require.NoError(t, db.SaveFile(filepath.Join(tmpDir, "b.txt"), []byte("x")))
|
||||
|
||||
c := newDumpCmd()
|
||||
err = c.RunE(c, nil)
|
||||
require.NoError(t, err)
|
||||
|
||||
db2, err := utils.GetDB()
|
||||
require.NoError(t, err)
|
||||
defer func() {
|
||||
if err := db2.Close(); err != nil {
|
||||
return
|
||||
}
|
||||
}()
|
||||
|
||||
after, err := db2.GetAllFiles()
|
||||
require.NoError(t, err)
|
||||
assert.Len(t, after, 0)
|
||||
}
|
||||
@@ -0,0 +1,21 @@
|
||||
package cmd
|
||||
|
||||
import (
|
||||
"cook/internal/chef"
|
||||
|
||||
"github.com/spf13/cobra"
|
||||
)
|
||||
|
||||
func newEscapeCmd() *cobra.Command {
|
||||
var minimize bool
|
||||
cmd := &cobra.Command{
|
||||
Use: "escape",
|
||||
Short: "Regexp-escape clipboard text; write result back to clipboard",
|
||||
Args: cobra.NoArgs,
|
||||
RunE: func(cmd *cobra.Command, args []string) error {
|
||||
return chef.RunEscapeClipboard(minimize)
|
||||
},
|
||||
}
|
||||
cmd.Flags().BoolVarP(&minimize, "minimize", "m", false, "minimize: replace whitespace runs with \\s*")
|
||||
return cmd
|
||||
}
|
||||
@@ -0,0 +1,59 @@
|
||||
//go:build e2e
|
||||
|
||||
package cmd
|
||||
|
||||
import (
|
||||
"bytes"
|
||||
"fmt"
|
||||
"testing"
|
||||
|
||||
"github.com/stretchr/testify/assert"
|
||||
"github.com/stretchr/testify/require"
|
||||
clip "golang.design/x/clipboard"
|
||||
)
|
||||
|
||||
func TestEscapeCommand(t *testing.T) {
|
||||
t.Run("plain_text/escapes_and_writes_back", func(t *testing.T) {
|
||||
if err := clip.Init(); err != nil {
|
||||
t.Fatalf("clipboard is required but init failed: %v", err)
|
||||
}
|
||||
if clip.Write(clip.FmtText, []byte(`a+b?`)) == nil {
|
||||
t.Fatalf("clipboard write is required but failed")
|
||||
}
|
||||
|
||||
var out bytes.Buffer
|
||||
var er bytes.Buffer
|
||||
root := resetRootCmdForE2E(t)
|
||||
root.SetOut(&out)
|
||||
root.SetErr(&er)
|
||||
root.SetArgs([]string{"escape"})
|
||||
|
||||
execOut, execErr := captureOutput(t, func() error { return root.Execute() })
|
||||
require.NoError(t, execErr, execOut+out.String()+er.String())
|
||||
|
||||
got := string(clip.Read(clip.FmtText))
|
||||
assert.Equal(t, `a\+b\?`, got, fmt.Sprintf("stdout=%q stderr=%q", out.String(), er.String()))
|
||||
})
|
||||
|
||||
t.Run("minimize_flag/replaces_whitespace_runs_with_regex", func(t *testing.T) {
|
||||
if err := clip.Init(); err != nil {
|
||||
t.Fatalf("clipboard is required but init failed: %v", err)
|
||||
}
|
||||
if clip.Write(clip.FmtText, []byte("a \t b")) == nil {
|
||||
t.Fatalf("clipboard write is required but failed")
|
||||
}
|
||||
|
||||
var out bytes.Buffer
|
||||
var er bytes.Buffer
|
||||
root := resetRootCmdForE2E(t)
|
||||
root.SetOut(&out)
|
||||
root.SetErr(&er)
|
||||
root.SetArgs([]string{"escape", "--minimize"})
|
||||
|
||||
execOut, execErr := captureOutput(t, func() error { return root.Execute() })
|
||||
require.NoError(t, execErr, execOut+out.String()+er.String())
|
||||
|
||||
got := string(clip.Read(clip.FmtText))
|
||||
assert.Equal(t, `a\s*b`, got)
|
||||
})
|
||||
}
|
||||
+15
@@ -0,0 +1,15 @@
|
||||
package cmd
|
||||
|
||||
import (
|
||||
"cook/internal/chef"
|
||||
|
||||
"github.com/spf13/cobra"
|
||||
)
|
||||
|
||||
func newFmtCmd() *cobra.Command {
|
||||
return newArgsCommand(
|
||||
"fmt <toml-file> [more toml-file...]",
|
||||
"Format multiline lua = '''...''' blocks via stylua",
|
||||
chef.FormatTomlPaths,
|
||||
)
|
||||
}
|
||||
@@ -0,0 +1,64 @@
|
||||
//go:build e2e
|
||||
|
||||
package cmd
|
||||
|
||||
import (
|
||||
"bytes"
|
||||
"os"
|
||||
"path/filepath"
|
||||
"strings"
|
||||
"testing"
|
||||
|
||||
"github.com/stretchr/testify/assert"
|
||||
"github.com/stretchr/testify/require"
|
||||
)
|
||||
|
||||
func TestFmtCommand(t *testing.T) {
|
||||
t.Run("valid_toml_with_lua_block/formats_via_stylua", func(t *testing.T) {
|
||||
tmp := t.TempDir()
|
||||
wd, err := os.Getwd()
|
||||
require.NoError(t, err)
|
||||
require.NoError(t, os.Chdir(tmp))
|
||||
t.Cleanup(func() {
|
||||
if err := os.Chdir(wd); err != nil {
|
||||
return
|
||||
}
|
||||
})
|
||||
|
||||
inPath := filepath.Join(tmp, "cook.toml")
|
||||
require.NoError(t, os.WriteFile(inPath, []byte(strings.Join([]string{
|
||||
`[[commands]]`,
|
||||
`name = "X"`,
|
||||
`files = ["*.txt"]`,
|
||||
`search = "a"`,
|
||||
`replace = "b"`,
|
||||
`lua = '''`,
|
||||
`local x=1`,
|
||||
`return x`,
|
||||
`'''`,
|
||||
``,
|
||||
}, "\n")), 0644))
|
||||
|
||||
var stdout bytes.Buffer
|
||||
var stderr bytes.Buffer
|
||||
|
||||
out, execErr := captureOutput(t, func() error {
|
||||
root := resetRootCmdForE2E(t)
|
||||
root.SetOut(&stdout)
|
||||
root.SetErr(&stderr)
|
||||
root.SetArgs([]string{"fmt", inPath})
|
||||
return root.Execute()
|
||||
})
|
||||
if execErr != nil {
|
||||
msg := execErr.Error()
|
||||
if strings.Contains(msg, "executable file not found") || strings.Contains(msg, "CreateProcess") || (strings.Contains(msg, "stylua") && strings.Contains(msg, "not found")) {
|
||||
t.Fatalf("stylua is required but not available in PATH: %v", execErr)
|
||||
}
|
||||
}
|
||||
require.NoError(t, execErr, out+stdout.String()+stderr.String())
|
||||
|
||||
b, readErr := os.ReadFile(inPath)
|
||||
require.NoError(t, readErr)
|
||||
assert.Contains(t, string(b), "local x = 1")
|
||||
})
|
||||
}
|
||||
@@ -0,0 +1,31 @@
|
||||
package cmd
|
||||
|
||||
import (
|
||||
"os"
|
||||
"os/exec"
|
||||
"path/filepath"
|
||||
"testing"
|
||||
|
||||
"github.com/stretchr/testify/assert"
|
||||
"github.com/stretchr/testify/require"
|
||||
)
|
||||
|
||||
func TestNewFmtCmd(t *testing.T) {
|
||||
t.Run("integration/stylua_formats_multiline_lua_block", func(t *testing.T) {
|
||||
if _, err := exec.LookPath("stylua"); err != nil {
|
||||
t.Fatalf("stylua must be installed and on PATH: %v", err)
|
||||
}
|
||||
tmp := t.TempDir()
|
||||
path := filepath.Join(tmp, "test.toml")
|
||||
content := "[[commands]]\nname = 'x'\nlua = '''\nlocal z=2\nprint( z )\n'''\n"
|
||||
require.NoError(t, os.WriteFile(path, []byte(content), 0644))
|
||||
|
||||
c := newFmtCmd()
|
||||
err := c.RunE(c, []string{path})
|
||||
require.NoError(t, err)
|
||||
|
||||
out, err := os.ReadFile(path)
|
||||
require.NoError(t, err)
|
||||
assert.Contains(t, string(out), "local z = 2")
|
||||
})
|
||||
}
|
||||
+18
@@ -0,0 +1,18 @@
|
||||
package cmd
|
||||
|
||||
import (
|
||||
"cook/internal/chef"
|
||||
|
||||
"github.com/spf13/cobra"
|
||||
)
|
||||
|
||||
func newGenCmd() *cobra.Command {
|
||||
return &cobra.Command{
|
||||
Use: "gen [name]",
|
||||
Short: "Generate TOML commands from clipboard diff",
|
||||
Args: cobra.MaximumNArgs(1),
|
||||
RunE: func(cmd *cobra.Command, args []string) error {
|
||||
return chef.Gen(cmd.OutOrStdout(), cmd.ErrOrStderr(), args)
|
||||
},
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,107 @@
|
||||
//go:build e2e
|
||||
|
||||
package cmd
|
||||
|
||||
import (
|
||||
"bytes"
|
||||
"os"
|
||||
"strings"
|
||||
"testing"
|
||||
|
||||
"github.com/atotto/clipboard"
|
||||
"github.com/stretchr/testify/assert"
|
||||
"github.com/stretchr/testify/require"
|
||||
)
|
||||
|
||||
func TestGenCommand(t *testing.T) {
|
||||
t.Run("clipboard_has_diff/prints_generated_toml", func(t *testing.T) {
|
||||
chdirTempForE2E(t)
|
||||
|
||||
diff := strings.Join([]string{
|
||||
"diff --git a/a.txt b/a.txt",
|
||||
"index 0000000..1111111 100644",
|
||||
"--- a/a.txt",
|
||||
"+++ b/a.txt",
|
||||
"@@ -1 +1 @@",
|
||||
"-old",
|
||||
"+new",
|
||||
"",
|
||||
}, "\n")
|
||||
require.NoError(t, clipboard.WriteAll(diff))
|
||||
|
||||
var out bytes.Buffer
|
||||
var er bytes.Buffer
|
||||
root := resetRootCmdForE2E(t)
|
||||
root.SetOut(&out)
|
||||
root.SetErr(&er)
|
||||
root.SetArgs([]string{"gen"})
|
||||
|
||||
execOut, execErr := captureOutput(t, func() error { return root.Execute() })
|
||||
require.NoError(t, execErr, execOut+out.String()+er.String())
|
||||
|
||||
got := execOut + out.String()
|
||||
assert.Contains(t, got, "[[commands]]")
|
||||
assert.Contains(t, got, "name = 'a.txt gen'")
|
||||
assert.Contains(t, got, "regex =")
|
||||
assert.Contains(t, got, "lua =")
|
||||
assert.Contains(t, got, "files = ['a.txt']")
|
||||
})
|
||||
|
||||
t.Run("clipboard_has_diff/name_arg_names_commands", func(t *testing.T) {
|
||||
chdirTempForE2E(t)
|
||||
|
||||
diff := strings.Join([]string{
|
||||
"diff --git a/a.txt b/a.txt",
|
||||
"index 0000000..1111111 100644",
|
||||
"--- a/a.txt",
|
||||
"+++ b/a.txt",
|
||||
"@@ -1 +1 @@",
|
||||
"-old",
|
||||
"+new",
|
||||
"",
|
||||
}, "\n")
|
||||
require.NoError(t, clipboard.WriteAll(diff))
|
||||
|
||||
var out bytes.Buffer
|
||||
var er bytes.Buffer
|
||||
root := resetRootCmdForE2E(t)
|
||||
root.SetOut(&out)
|
||||
root.SetErr(&er)
|
||||
root.SetArgs([]string{"gen", "my-patch"})
|
||||
|
||||
execOut, execErr := captureOutput(t, func() error { return root.Execute() })
|
||||
require.NoError(t, execErr, execOut+out.String()+er.String())
|
||||
|
||||
got := execOut + out.String()
|
||||
assert.Contains(t, got, "name = 'my-patch a.txt gen'")
|
||||
})
|
||||
|
||||
t.Run("clipboard_empty/fails_loudly", func(t *testing.T) {
|
||||
chdirTempForE2E(t)
|
||||
|
||||
require.NoError(t, clipboard.WriteAll(""))
|
||||
|
||||
var out bytes.Buffer
|
||||
var er bytes.Buffer
|
||||
root := resetRootCmdForE2E(t)
|
||||
root.SetOut(&out)
|
||||
root.SetErr(&er)
|
||||
root.SetArgs([]string{"gen"})
|
||||
|
||||
_, execErr := captureOutput(t, func() error { return root.Execute() })
|
||||
require.Error(t, execErr)
|
||||
})
|
||||
}
|
||||
|
||||
func chdirTempForE2E(t *testing.T) {
|
||||
t.Helper()
|
||||
dir := t.TempDir()
|
||||
wd, err := os.Getwd()
|
||||
require.NoError(t, err)
|
||||
require.NoError(t, os.Chdir(dir))
|
||||
t.Cleanup(func() {
|
||||
if err := os.Chdir(wd); err != nil {
|
||||
return
|
||||
}
|
||||
})
|
||||
}
|
||||
@@ -1,27 +0,0 @@
|
||||
package main
|
||||
|
||||
import (
|
||||
"modify/logger"
|
||||
"time"
|
||||
)
|
||||
|
||||
func main() {
|
||||
// Initialize logger with DEBUG level
|
||||
logger.Init(logger.LevelDebug)
|
||||
|
||||
// Test different log levels
|
||||
logger.Info("This is an info message")
|
||||
logger.Debug("This is a debug message")
|
||||
logger.Warning("This is a warning message")
|
||||
logger.Error("This is an error message")
|
||||
logger.Trace("This is a trace message (not visible at DEBUG level)")
|
||||
|
||||
// Test with a goroutine
|
||||
logger.SafeGo(func() {
|
||||
time.Sleep(10 * time.Millisecond)
|
||||
logger.Info("Message from goroutine")
|
||||
})
|
||||
|
||||
// Wait for goroutine to complete
|
||||
time.Sleep(20 * time.Millisecond)
|
||||
}
|
||||
@@ -0,0 +1,32 @@
|
||||
package cmd
|
||||
|
||||
import (
|
||||
"cook/internal/chef"
|
||||
|
||||
"github.com/spf13/cobra"
|
||||
)
|
||||
|
||||
func NewLuaCmd() *cobra.Command {
|
||||
cmd := &cobra.Command{
|
||||
Use: "lua <file.lua>...",
|
||||
Short: "Run Lua files with the chef helper library preloaded",
|
||||
Long: `Run one or more Lua files inside the same engine used by cook commands.
|
||||
|
||||
Files run in the order given and share a single Lua state, so earlier
|
||||
files stay loaded in the engine and later files can use what they
|
||||
define. The full chef Lua helper library is available: csv, json, xml,
|
||||
util, math.round, string.trim, string.split, clone, fetch, re, json.read
|
||||
and xml.read. Lua print() writes through chef's logger. The "file"
|
||||
global is set to each script's path so relative json.read/xml.read
|
||||
resolve from that script's directory.
|
||||
|
||||
Use "chef lua watch <file.lua>..." to keep running and re-run all files
|
||||
whenever any of them changes on disk.`,
|
||||
Args: cobra.MinimumNArgs(1),
|
||||
RunE: func(cmd *cobra.Command, args []string) error {
|
||||
return chef.RunLuaFile(args)
|
||||
},
|
||||
}
|
||||
cmd.AddCommand(newWatchCmd())
|
||||
return cmd
|
||||
}
|
||||
@@ -0,0 +1,21 @@
|
||||
package cmd
|
||||
|
||||
import (
|
||||
"cook/internal/chef"
|
||||
|
||||
"github.com/spf13/cobra"
|
||||
)
|
||||
|
||||
func newWatchCmd() *cobra.Command {
|
||||
return &cobra.Command{
|
||||
Use: "watch <file.lua>...",
|
||||
Short: "Run Lua files and re-run them whenever any changes on disk",
|
||||
Long: `Run one or more Lua files inside the same engine used by cook commands,
|
||||
then keep watching them and re-run all files in order whenever any of
|
||||
them changes on disk. The command keeps running until interrupted.`,
|
||||
Args: cobra.MinimumNArgs(1),
|
||||
RunE: func(cmd *cobra.Command, args []string) error {
|
||||
return chef.RunLuaFileWatch(args)
|
||||
},
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,16 @@
|
||||
package cmd
|
||||
|
||||
import (
|
||||
"cook/internal/chef"
|
||||
|
||||
"github.com/spf13/cobra"
|
||||
)
|
||||
|
||||
func newResetCmd() *cobra.Command {
|
||||
return newRunCommand(
|
||||
"reset",
|
||||
"Restore all snapshotted files to original state",
|
||||
cobra.NoArgs,
|
||||
chef.RunResetSnapshots,
|
||||
)
|
||||
}
|
||||
@@ -0,0 +1,54 @@
|
||||
//go:build e2e
|
||||
|
||||
package cmd
|
||||
|
||||
import (
|
||||
"bytes"
|
||||
"os"
|
||||
"path/filepath"
|
||||
"testing"
|
||||
|
||||
"cook/utils"
|
||||
|
||||
"github.com/stretchr/testify/assert"
|
||||
"github.com/stretchr/testify/require"
|
||||
)
|
||||
|
||||
func TestResetCommand(t *testing.T) {
|
||||
t.Run("snapshot_exists/reset_restores_file_bytes", func(t *testing.T) {
|
||||
dir := t.TempDir()
|
||||
wd, err := os.Getwd()
|
||||
require.NoError(t, err)
|
||||
require.NoError(t, os.Chdir(dir))
|
||||
t.Cleanup(func() {
|
||||
if err := os.Chdir(wd); err != nil {
|
||||
return
|
||||
}
|
||||
})
|
||||
|
||||
orig := []byte("value=1\n")
|
||||
cur := []byte("value=999\n")
|
||||
|
||||
p := filepath.Join(dir, "a.txt")
|
||||
require.NoError(t, os.WriteFile(p, cur, 0644))
|
||||
|
||||
db, err := utils.GetDB()
|
||||
require.NoError(t, err)
|
||||
require.NoError(t, db.SaveFile(p, orig))
|
||||
require.NoError(t, db.Close())
|
||||
|
||||
var out bytes.Buffer
|
||||
var er bytes.Buffer
|
||||
root := resetRootCmdForE2E(t)
|
||||
root.SetOut(&out)
|
||||
root.SetErr(&er)
|
||||
root.SetArgs([]string{"reset"})
|
||||
|
||||
execOut, execErr := captureOutput(t, func() error { return root.Execute() })
|
||||
require.NoError(t, execErr, execOut+out.String()+er.String())
|
||||
|
||||
b, readErr := os.ReadFile(p)
|
||||
require.NoError(t, readErr)
|
||||
assert.Equal(t, orig, b)
|
||||
})
|
||||
}
|
||||
@@ -0,0 +1,46 @@
|
||||
package cmd
|
||||
|
||||
import (
|
||||
"os"
|
||||
"path/filepath"
|
||||
"testing"
|
||||
|
||||
"cook/utils"
|
||||
|
||||
"github.com/stretchr/testify/assert"
|
||||
"github.com/stretchr/testify/require"
|
||||
)
|
||||
|
||||
func TestResetCommandRunE(t *testing.T) {
|
||||
tmpDir, err := os.MkdirTemp("", "reset-cmd-*")
|
||||
require.NoError(t, err)
|
||||
origDir, err := os.Getwd()
|
||||
require.NoError(t, err)
|
||||
defer func() {
|
||||
if err := os.Chdir(origDir); err != nil {
|
||||
t.Logf("failed to restore working directory: %v", err)
|
||||
}
|
||||
}()
|
||||
require.NoError(t, os.Chdir(tmpDir))
|
||||
|
||||
file := filepath.Join(tmpDir, "file.txt")
|
||||
require.NoError(t, os.WriteFile(file, []byte("original"), 0644))
|
||||
|
||||
db, err := utils.GetDB()
|
||||
require.NoError(t, err)
|
||||
defer func() {
|
||||
if err := db.Close(); err != nil {
|
||||
return
|
||||
}
|
||||
}()
|
||||
require.NoError(t, db.SaveFile(file, []byte("original")))
|
||||
require.NoError(t, db.Close())
|
||||
require.NoError(t, os.WriteFile(file, []byte("modified"), 0644))
|
||||
|
||||
c := newResetCmd()
|
||||
require.NoError(t, c.RunE(c, nil))
|
||||
|
||||
data, err := os.ReadFile(file)
|
||||
require.NoError(t, err)
|
||||
assert.Equal(t, "original", string(data))
|
||||
}
|
||||
@@ -0,0 +1,27 @@
|
||||
package cmd
|
||||
|
||||
import (
|
||||
"cook/internal/chef"
|
||||
|
||||
"github.com/spf13/cobra"
|
||||
)
|
||||
|
||||
func newRJPathCmd() *cobra.Command {
|
||||
return &cobra.Command{
|
||||
Use: "rj <jsonpath> [files...]",
|
||||
Short: "Search JSON files with a JSONPath expression",
|
||||
Long: `Search JSON files with a JSONPath expression, printing every line that
|
||||
contains a match, ripgrep style. With no file arguments, searches the
|
||||
current directory recursively for *.json files.
|
||||
|
||||
Examples:
|
||||
chef rj '$..ammo' mods/**/*.json
|
||||
chef rj '$..ammo' mods
|
||||
chef rj '$.items[?(@.price < 10)]' shop.json
|
||||
chef rj '$..*[?(@.ammo_restriction.battery > 1)]' mods`,
|
||||
Args: cobra.MinimumNArgs(1),
|
||||
RunE: func(cmd *cobra.Command, args []string) error {
|
||||
return chef.RunJSONSearch(args, cmd.OutOrStdout(), cmd.ErrOrStderr())
|
||||
},
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,74 @@
|
||||
//go:build e2e
|
||||
|
||||
package cmd
|
||||
|
||||
import (
|
||||
"bytes"
|
||||
"os"
|
||||
"path/filepath"
|
||||
"testing"
|
||||
|
||||
"github.com/stretchr/testify/assert"
|
||||
"github.com/stretchr/testify/require"
|
||||
)
|
||||
|
||||
func TestRJPathCmdE2E(t *testing.T) {
|
||||
dir := t.TempDir()
|
||||
wd, err := os.Getwd()
|
||||
require.NoError(t, err)
|
||||
require.NoError(t, os.Chdir(dir))
|
||||
t.Cleanup(func() {
|
||||
if err := os.Chdir(wd); err != nil {
|
||||
return
|
||||
}
|
||||
})
|
||||
|
||||
write := func(name, content string) string {
|
||||
p := filepath.Join(dir, name)
|
||||
require.NoError(t, os.WriteFile(p, []byte(content), 0644))
|
||||
return p
|
||||
}
|
||||
fileA := write("a.json", "{\n \"ammo\": [ \"arrow\" ],\n \"x\": 1\n}\n")
|
||||
write("b.json", "{\n \"y\": 2\n}\n")
|
||||
|
||||
t.Run("e2e/rj/multi_file_grep_style", func(t *testing.T) {
|
||||
var stdout bytes.Buffer
|
||||
var stderr bytes.Buffer
|
||||
root := resetRootCmdForE2E(t)
|
||||
root.SetOut(&stdout)
|
||||
root.SetErr(&stderr)
|
||||
root.SetArgs([]string{"rj", "$..ammo", fileA, filepath.Join(dir, "b.json")})
|
||||
require.NoError(t, root.Execute())
|
||||
|
||||
got := stdout.String()
|
||||
assert.Contains(t, got, fileA+"\n")
|
||||
assert.Contains(t, got, "2: \"ammo\": [ \"arrow\" ],")
|
||||
assert.NotContains(t, got, "b.json\n")
|
||||
})
|
||||
|
||||
t.Run("e2e/rj/glob_pattern", func(t *testing.T) {
|
||||
var stdout bytes.Buffer
|
||||
var stderr bytes.Buffer
|
||||
root := resetRootCmdForE2E(t)
|
||||
root.SetOut(&stdout)
|
||||
root.SetErr(&stderr)
|
||||
root.SetArgs([]string{"rj", "$..ammo", filepath.Join(dir, "*.json")})
|
||||
require.NoError(t, root.Execute())
|
||||
|
||||
got := stdout.String()
|
||||
assert.Contains(t, got, fileA+"\n")
|
||||
assert.Contains(t, got, "2: \"ammo\": [ \"arrow\" ],")
|
||||
})
|
||||
|
||||
t.Run("e2e/rj/invalid_expression_errors", func(t *testing.T) {
|
||||
var stdout bytes.Buffer
|
||||
var stderr bytes.Buffer
|
||||
root := resetRootCmdForE2E(t)
|
||||
root.SetOut(&stdout)
|
||||
root.SetErr(&stderr)
|
||||
root.SetArgs([]string{"rj", "$$$bad", fileA})
|
||||
err := root.Execute()
|
||||
require.Error(t, err)
|
||||
assert.Contains(t, err.Error(), "invalid jsonpath")
|
||||
})
|
||||
}
|
||||
+241
@@ -0,0 +1,241 @@
|
||||
package cmd
|
||||
|
||||
import (
|
||||
"errors"
|
||||
|
||||
luacmd "cook/cmd/lua"
|
||||
"cook/internal/chef"
|
||||
"cook/processor"
|
||||
|
||||
"github.com/spf13/cobra"
|
||||
)
|
||||
|
||||
func Execute() error {
|
||||
return NewRootCmd().Execute()
|
||||
}
|
||||
|
||||
func NewRootCmd() *cobra.Command {
|
||||
root := &cobra.Command{
|
||||
Use: "chef [flags] <cook_files...>",
|
||||
Short: "Batch file transformations with regex, JSON, XML + Lua",
|
||||
Args: cobra.ArbitraryArgs,
|
||||
TraverseChildren: true,
|
||||
Long: rootLongHelp,
|
||||
PersistentPreRun: persistentPreRun,
|
||||
RunE: runRoot,
|
||||
}
|
||||
|
||||
addRootFlags(root)
|
||||
root.SetUsageTemplate(rootUsageTemplate)
|
||||
root.Example = rootExampleHelp()
|
||||
addRootSubcommands(root)
|
||||
return root
|
||||
}
|
||||
|
||||
func persistentPreRun(cmd *cobra.Command, args []string) {
|
||||
noColor, _ := cmd.Flags().GetBool("no-color")
|
||||
logLevelStr, _ := cmd.Flags().GetString("loglevel")
|
||||
versionFlag, _ := cmd.Flags().GetBool("version")
|
||||
chef.PersistentPreRun(chef.PersistentPreRunInput{
|
||||
SubcommandName: cmd.Name(),
|
||||
LogLevel: logLevelStr,
|
||||
Version: versionFlag,
|
||||
NoColor: noColor,
|
||||
})
|
||||
}
|
||||
|
||||
func runRoot(cmd *cobra.Command, args []string) error {
|
||||
cfg, err := rootRunConfig(cmd, args)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
err = chef.RunRoot(cfg)
|
||||
if errors.Is(err, chef.ErrShowUsage) {
|
||||
if usageErr := cmd.Usage(); usageErr != nil {
|
||||
return usageErr
|
||||
}
|
||||
return nil
|
||||
}
|
||||
return err
|
||||
}
|
||||
|
||||
func addRootFlags(root *cobra.Command) {
|
||||
root.Flags().IntP("parallel", "P", 100, "Number of files to process in parallel")
|
||||
root.Flags().StringP("filter", "f", "", "Filter commands before running them")
|
||||
root.Flags().String("hooks", "cook_hooks.toml", "Path to global before_each/after_each hooks file")
|
||||
root.Flags().BoolP("version", "v", false, "Print version and exit")
|
||||
root.Flags().BoolP("example", "e", false, "Generate example_cook.toml and exit")
|
||||
root.Flags().BoolP("meta", "m", false, "Generate meta.lua file for LuaLS autocomplete and exit")
|
||||
|
||||
root.PersistentFlags().String("loglevel", "info", "log level")
|
||||
root.PersistentFlags().Bool("no-color", false, "disable colors")
|
||||
}
|
||||
|
||||
func addRootSubcommands(root *cobra.Command) {
|
||||
root.AddCommand(newFmtCmd())
|
||||
root.AddCommand(newGenCmd())
|
||||
root.AddCommand(newConvCmd())
|
||||
root.AddCommand(newResetCmd())
|
||||
root.AddCommand(newDumpCmd())
|
||||
root.AddCommand(newClearCmd())
|
||||
root.AddCommand(newWatchCmd())
|
||||
root.AddCommand(newTUICmd())
|
||||
root.AddCommand(newEscapeCmd())
|
||||
root.AddCommand(newRJPathCmd())
|
||||
root.AddCommand(newXJPathCmd())
|
||||
root.AddCommand(luacmd.NewLuaCmd())
|
||||
}
|
||||
|
||||
func rootExampleHelp() string {
|
||||
return rootExampleBase + processor.GetLuaFunctionsHelp()
|
||||
}
|
||||
|
||||
const rootLongHelp = `chef processes files using commands loaded from cook files (TOML or YAML).
|
||||
|
||||
Core functionality:
|
||||
- Regex mode (default): capture groups are exposed to Lua as s1..sN / v1..vN plus named captures
|
||||
- JSON mode: set per-command with json=true, with parsed data exposed as Lua global "data" and json.jpath(node, expr)
|
||||
- XML mode: set per-command with xml=true, with parsed XML tree exposed as Lua global "data" (fields: data.tag, data.text, data.attr, data.children, data.name.local, data.name.uri, data.name.prefix) and xml.xpath(node, expr)
|
||||
- Glob expansion: files fields support doublestar patterns (**/*.json, etc.)
|
||||
- Safe resets: original file snapshots are stored in data.sqlite and can be restored with "chef reset"
|
||||
|
||||
Utility commands:
|
||||
- chef watch : run cook files and re-run whenever any of them changes on disk
|
||||
- chef reset : restore all snapshotted files to original state
|
||||
- chef dump : clear all stored file snapshots
|
||||
- chef clear : clear the glob pattern -> file cache
|
||||
- chef fmt : format multiline lua blocks in TOML via stylua
|
||||
- chef gen : generate TOML commands from clipboard diff (chef gen [name])
|
||||
- chef conv : convert YAML cook files to TOML
|
||||
- chef escape: regexp-escape clipboard text, write back to clipboard
|
||||
- chef lua : run one or more Lua files with the full helper library preloaded
|
||||
|
||||
Search commands (ripgrep-style, print matching lines):
|
||||
- chef rj <jsonpath> [files...] : search JSON files with a JSONPath expression
|
||||
- chef xj <xmlpath> [files...] : search XML files with an XPath expression
|
||||
|
||||
Extra helpers:
|
||||
- --example generates example_cook.toml
|
||||
- --meta generates meta.lua for LuaLS autocomplete
|
||||
`
|
||||
|
||||
const rootUsageTemplate = `Usage:{{if .Runnable}}
|
||||
{{.UseLine}}{{end}}{{if .HasAvailableSubCommands}}
|
||||
{{.CommandPath}} [command]{{end}} {{if gt (len .Aliases) 0}}
|
||||
|
||||
Aliases:
|
||||
{{.NameAndAliases}}{{end}}{{if .HasExample}}
|
||||
|
||||
Examples:
|
||||
{{.Example}}{{end}}{{if .HasAvailableSubCommands}}
|
||||
|
||||
Available Commands:{{range .Commands}}{{if (or .IsAvailableCommand (eq .Name "help"))}}
|
||||
{{rpad .Name .NamePadding }} {{.Short}}{{end}}{{end}}{{end}}{{if .HasAvailableLocalFlags}}
|
||||
|
||||
Flags:
|
||||
{{.LocalFlags.FlagUsages | trimTrailingWhitespaces}}{{end}}{{if .HasAvailableInheritedFlags}}
|
||||
|
||||
Global Flags:
|
||||
{{.InheritedFlags.FlagUsages | trimTrailingWhitespaces}}{{end}}{{if .HasHelpSubCommands}}
|
||||
|
||||
Additional help topics:{{range .Commands}}{{if .IsAdditionalHelpTopicCommand}}
|
||||
{{rpad .CommandPath .CommandPathPadding}} {{.Short}}{{end}}{{end}}{{end}}{{if .HasAvailableSubCommands}}
|
||||
|
||||
Use "{{.CommandPath}} [command] --help" for more information about a command.{{end}}
|
||||
`
|
||||
|
||||
const rootExampleBase = `Run a TOML cook file:
|
||||
chef example_cook.toml
|
||||
|
||||
Run every TOML cook file in the current directory (default when no files given):
|
||||
chef
|
||||
|
||||
Run multiple cook files:
|
||||
chef base.toml overrides.yaml
|
||||
|
||||
Filter by command names:
|
||||
chef -f "Balance,Prefix" example_cook.toml
|
||||
|
||||
Re-run whenever a cook file changes:
|
||||
chef watch example_cook.toml
|
||||
chef watch -f "Balance" base.toml
|
||||
|
||||
Format lua blocks in TOML files:
|
||||
chef fmt example_cook.toml
|
||||
chef fmt **/*.toml
|
||||
|
||||
Convert YAML cook files to TOML:
|
||||
chef conv *.yml
|
||||
chef conv **/*.yaml
|
||||
|
||||
Generate helpers:
|
||||
chef --example
|
||||
chef --meta
|
||||
chef gen > generated.toml
|
||||
chef gen my-fix > generated.toml
|
||||
|
||||
Restore or clear snapshots / glob cache:
|
||||
chef reset
|
||||
chef dump
|
||||
chef clear
|
||||
|
||||
Search JSON / XML in ripgrep style:
|
||||
chef rj '$..ammo' mods/**/*.json
|
||||
chef xj '//item[@id="1"]' mods/**/*.xml
|
||||
|
||||
Run Lua files with helpers preloaded:
|
||||
chef lua script.lua
|
||||
chef lua lib.lua main.lua
|
||||
chef lua watch script.lua
|
||||
|
||||
Notes:
|
||||
Regex placeholders: !num, !any, !rep(pattern, n)
|
||||
Capture variables: s1..sN (string), v1..vN (number when parseable), plus named captures
|
||||
Full-match override: set Lua global "replacement"
|
||||
Apply gate: set "modified" false or return false to skip writes
|
||||
External Lua: set lua = "@script.lua" in cook file (resolved relative to cook file)
|
||||
ctx table: available in every Lua script — ctx.source_file, ctx.target_file, ctx.command_name, ctx.capture (regex)
|
||||
|
||||
`
|
||||
|
||||
func rootRunConfig(cmd *cobra.Command, args []string) (chef.RootRunConfig, error) {
|
||||
var cfg chef.RootRunConfig
|
||||
cfg.Stdout = cmd.OutOrStdout()
|
||||
cfg.CookArgs = args
|
||||
|
||||
boolSpecs := []struct {
|
||||
name string
|
||||
dst *bool
|
||||
}{
|
||||
{name: "version", dst: &cfg.Version},
|
||||
{name: "example", dst: &cfg.Example},
|
||||
{name: "meta", dst: &cfg.Meta},
|
||||
}
|
||||
for _, spec := range boolSpecs {
|
||||
val, err := cmd.Flags().GetBool(spec.name)
|
||||
if err != nil {
|
||||
return chef.RootRunConfig{}, err
|
||||
}
|
||||
*spec.dst = val
|
||||
}
|
||||
|
||||
parallel, err := cmd.Flags().GetInt("parallel")
|
||||
if err != nil {
|
||||
return chef.RootRunConfig{}, err
|
||||
}
|
||||
cfg.Parallel = parallel
|
||||
|
||||
filter, err := cmd.Flags().GetString("filter")
|
||||
if err != nil {
|
||||
return chef.RootRunConfig{}, err
|
||||
}
|
||||
cfg.Filter = filter
|
||||
|
||||
hooks, err := cmd.Flags().GetString("hooks")
|
||||
if err != nil {
|
||||
return chef.RootRunConfig{}, err
|
||||
}
|
||||
cfg.GlobalHooksPath = hooks
|
||||
|
||||
return cfg, nil
|
||||
}
|
||||
@@ -0,0 +1,804 @@
|
||||
//go:build e2e
|
||||
|
||||
package cmd
|
||||
|
||||
import (
|
||||
"bytes"
|
||||
"io"
|
||||
"os"
|
||||
"path/filepath"
|
||||
"testing"
|
||||
|
||||
"github.com/spf13/cobra"
|
||||
"github.com/stretchr/testify/assert"
|
||||
"github.com/stretchr/testify/require"
|
||||
)
|
||||
|
||||
const (
|
||||
dataTxtPath = "data.txt"
|
||||
cookTomlPath = "cook.toml"
|
||||
dataJSONPath = "data.json"
|
||||
dataXMLPath = "data.xml"
|
||||
)
|
||||
|
||||
func captureOutput(t *testing.T, run func() error) (string, error) {
|
||||
t.Helper()
|
||||
origOut := os.Stdout
|
||||
origErr := os.Stderr
|
||||
rOut, wOut, err := os.Pipe()
|
||||
require.NoError(t, err)
|
||||
rErr, wErr, err := os.Pipe()
|
||||
require.NoError(t, err)
|
||||
os.Stdout = wOut
|
||||
os.Stderr = wErr
|
||||
t.Cleanup(func() {
|
||||
os.Stdout = origOut
|
||||
os.Stderr = origErr
|
||||
})
|
||||
runErr := run()
|
||||
if err := wOut.Close(); err != nil {
|
||||
return "", err
|
||||
}
|
||||
if err := wErr.Close(); err != nil {
|
||||
return "", err
|
||||
}
|
||||
os.Stdout = origOut
|
||||
os.Stderr = origErr
|
||||
outBytes, _ := io.ReadAll(rOut)
|
||||
errBytes, _ := io.ReadAll(rErr)
|
||||
if err := rOut.Close(); err != nil {
|
||||
return "", err
|
||||
}
|
||||
if err := rErr.Close(); err != nil {
|
||||
return "", err
|
||||
}
|
||||
return string(outBytes) + string(errBytes), runErr
|
||||
}
|
||||
|
||||
func resetRootCmdForE2E(t *testing.T) *cobra.Command {
|
||||
t.Helper()
|
||||
root := NewRootCmd()
|
||||
require.NoError(t, root.PersistentFlags().Set("loglevel", "INFO"))
|
||||
require.NoError(t, root.Flags().Set("parallel", "100"))
|
||||
require.NoError(t, root.Flags().Set("filter", ""))
|
||||
require.NoError(t, root.Flags().Set("version", "false"))
|
||||
require.NoError(t, root.Flags().Set("example", "false"))
|
||||
require.NoError(t, root.Flags().Set("meta", "false"))
|
||||
return root
|
||||
}
|
||||
|
||||
func TestNewRootCmd(t *testing.T) {
|
||||
|
||||
t.Run("e2e/root/version_flag/prints_version_and_exits_zero", func(t *testing.T) {
|
||||
tmp := t.TempDir()
|
||||
wd, err := os.Getwd()
|
||||
require.NoError(t, err)
|
||||
require.NoError(t, os.Chdir(tmp))
|
||||
t.Cleanup(func() {
|
||||
if err := os.Chdir(wd); err != nil {
|
||||
return
|
||||
}
|
||||
})
|
||||
|
||||
var stdout bytes.Buffer
|
||||
var stderr bytes.Buffer
|
||||
|
||||
out, err := captureOutput(t, func() error {
|
||||
root := resetRootCmdForE2E(t)
|
||||
root.SetOut(&stdout)
|
||||
root.SetErr(&stderr)
|
||||
root.SetArgs([]string{"--version"})
|
||||
return root.Execute()
|
||||
})
|
||||
require.NoError(t, err)
|
||||
|
||||
assert.NotEmpty(t, out+stdout.String()+stderr.String())
|
||||
})
|
||||
|
||||
t.Run("e2e/root/example_flag/writes_example_cook_toml", func(t *testing.T) {
|
||||
tmp := t.TempDir()
|
||||
wd, err := os.Getwd()
|
||||
require.NoError(t, err)
|
||||
require.NoError(t, os.Chdir(tmp))
|
||||
t.Cleanup(func() {
|
||||
if err := os.Chdir(wd); err != nil {
|
||||
return
|
||||
}
|
||||
})
|
||||
|
||||
var stdout bytes.Buffer
|
||||
var stderr bytes.Buffer
|
||||
|
||||
_, err = captureOutput(t, func() error {
|
||||
root := resetRootCmdForE2E(t)
|
||||
root.SetOut(&stdout)
|
||||
root.SetErr(&stderr)
|
||||
root.SetArgs([]string{"--example"})
|
||||
return root.Execute()
|
||||
})
|
||||
require.NoError(t, err)
|
||||
|
||||
p := filepath.Join(tmp, "example_cook.toml")
|
||||
b, readErr := os.ReadFile(p)
|
||||
require.NoError(t, readErr)
|
||||
assert.NotEmpty(t, b)
|
||||
})
|
||||
|
||||
t.Run("e2e/root/no_args/prints_usage_and_exits_zero", func(t *testing.T) {
|
||||
tmp := t.TempDir()
|
||||
wd, err := os.Getwd()
|
||||
require.NoError(t, err)
|
||||
require.NoError(t, os.Chdir(tmp))
|
||||
t.Cleanup(func() {
|
||||
if err := os.Chdir(wd); err != nil {
|
||||
return
|
||||
}
|
||||
})
|
||||
|
||||
var stdout bytes.Buffer
|
||||
var stderr bytes.Buffer
|
||||
|
||||
out, err := captureOutput(t, func() error {
|
||||
root := resetRootCmdForE2E(t)
|
||||
root.SetOut(&stdout)
|
||||
root.SetErr(&stderr)
|
||||
root.SetArgs([]string{})
|
||||
return root.Execute()
|
||||
})
|
||||
require.NoError(t, err)
|
||||
|
||||
assert.Contains(t, out+stdout.String()+stderr.String(), "Usage:")
|
||||
})
|
||||
|
||||
t.Run("e2e/main/no_args/prints_usage", func(t *testing.T) {
|
||||
tmp := t.TempDir()
|
||||
wd, err := os.Getwd()
|
||||
require.NoError(t, err)
|
||||
require.NoError(t, os.Chdir(tmp))
|
||||
t.Cleanup(func() {
|
||||
if err := os.Chdir(wd); err != nil {
|
||||
return
|
||||
}
|
||||
})
|
||||
|
||||
var stdout bytes.Buffer
|
||||
var stderr bytes.Buffer
|
||||
root := resetRootCmdForE2E(t)
|
||||
root.SetOut(&stdout)
|
||||
root.SetErr(&stderr)
|
||||
root.SetArgs([]string{})
|
||||
|
||||
err = root.Execute()
|
||||
assert.Contains(t, stdout.String()+stderr.String(), "chef")
|
||||
})
|
||||
|
||||
t.Run("e2e/main/meta_flag/generates_meta_lua", func(t *testing.T) {
|
||||
tmp := t.TempDir()
|
||||
wd, err := os.Getwd()
|
||||
require.NoError(t, err)
|
||||
require.NoError(t, os.Chdir(tmp))
|
||||
t.Cleanup(func() {
|
||||
if err := os.Chdir(wd); err != nil {
|
||||
return
|
||||
}
|
||||
})
|
||||
|
||||
var stdout bytes.Buffer
|
||||
var stderr bytes.Buffer
|
||||
root := resetRootCmdForE2E(t)
|
||||
root.SetOut(&stdout)
|
||||
root.SetErr(&stderr)
|
||||
root.SetArgs([]string{"--meta"})
|
||||
|
||||
err = root.Execute()
|
||||
require.NoError(t, err)
|
||||
|
||||
metaPath := filepath.Join(tmp, "meta.lua")
|
||||
b, readErr := os.ReadFile(metaPath)
|
||||
require.NoError(t, readErr)
|
||||
assert.Contains(t, string(b), "---@meta")
|
||||
})
|
||||
|
||||
t.Run("e2e/cook_run/regex/placeholder_num_matches", func(t *testing.T) {
|
||||
dir := t.TempDir()
|
||||
wd, wderr := os.Getwd()
|
||||
require.NoError(t, wderr)
|
||||
require.NoError(t, os.Chdir(dir))
|
||||
t.Cleanup(func() { os.Chdir(wd) })
|
||||
|
||||
os.WriteFile(dataTxtPath, []byte("value=100"), 0644)
|
||||
os.WriteFile(cookTomlPath, []byte(`[[commands]]
|
||||
regex = "value=!num"
|
||||
lua = "v1 = v1 * 2"
|
||||
files = ["data.txt"]
|
||||
`), 0644)
|
||||
|
||||
root := resetRootCmdForE2E(t)
|
||||
root.SetArgs([]string{cookTomlPath})
|
||||
require.NoError(t, root.Execute())
|
||||
b, rerr := os.ReadFile(dataTxtPath)
|
||||
require.NoError(t, rerr)
|
||||
assert.Contains(t, string(b), "200")
|
||||
})
|
||||
|
||||
t.Run("e2e/cook_run/regex/placeholder_any_matches", func(t *testing.T) {
|
||||
dir := t.TempDir()
|
||||
wd, wderr := os.Getwd()
|
||||
require.NoError(t, wderr)
|
||||
require.NoError(t, os.Chdir(dir))
|
||||
t.Cleanup(func() { os.Chdir(wd) })
|
||||
|
||||
os.WriteFile(dataTxtPath, []byte("startMIDDLEend"), 0644)
|
||||
os.WriteFile(cookTomlPath, []byte(`[[commands]]
|
||||
regex = "start!anyend"
|
||||
lua = "replacement = 'REPLACED'"
|
||||
files = ["data.txt"]
|
||||
`), 0644)
|
||||
|
||||
root := resetRootCmdForE2E(t)
|
||||
root.SetArgs([]string{cookTomlPath})
|
||||
require.NoError(t, root.Execute())
|
||||
b, rerr := os.ReadFile(dataTxtPath)
|
||||
require.NoError(t, rerr)
|
||||
assert.Equal(t, "REPLACED", string(b))
|
||||
})
|
||||
|
||||
t.Run("e2e/cook_run/regex/multiple_capture_groups_v1_v2", func(t *testing.T) {
|
||||
dir := t.TempDir()
|
||||
wd, wderr := os.Getwd()
|
||||
require.NoError(t, wderr)
|
||||
require.NoError(t, os.Chdir(dir))
|
||||
t.Cleanup(func() { os.Chdir(wd) })
|
||||
|
||||
os.WriteFile(dataTxtPath, []byte("count=5,limit=10"), 0644)
|
||||
os.WriteFile(cookTomlPath, []byte(`[[commands]]
|
||||
regex = "(\\w+)=(\\d+)"
|
||||
lua = "v2 = v2 * 2"
|
||||
files = ["data.txt"]
|
||||
`), 0644)
|
||||
|
||||
root := resetRootCmdForE2E(t)
|
||||
root.SetArgs([]string{cookTomlPath})
|
||||
require.NoError(t, root.Execute())
|
||||
b, rerr := os.ReadFile(dataTxtPath)
|
||||
require.NoError(t, rerr)
|
||||
assert.Contains(t, string(b), "limit=20")
|
||||
assert.Contains(t, string(b), "count=10")
|
||||
})
|
||||
|
||||
t.Run("e2e/cook_run/regex/named_capture_group", func(t *testing.T) {
|
||||
dir := t.TempDir()
|
||||
wd, wderr := os.Getwd()
|
||||
require.NoError(t, wderr)
|
||||
require.NoError(t, os.Chdir(dir))
|
||||
t.Cleanup(func() { os.Chdir(wd) })
|
||||
|
||||
os.WriteFile(dataTxtPath, []byte("amount=50"), 0644)
|
||||
os.WriteFile(cookTomlPath, []byte(`[[commands]]
|
||||
regex = "(?P<key>\\w+)=(?P<val>\\d+)"
|
||||
lua = "val = val * 3"
|
||||
files = ["data.txt"]
|
||||
`), 0644)
|
||||
|
||||
root := resetRootCmdForE2E(t)
|
||||
root.SetArgs([]string{cookTomlPath})
|
||||
require.NoError(t, root.Execute())
|
||||
b, rerr := os.ReadFile(dataTxtPath)
|
||||
require.NoError(t, rerr)
|
||||
assert.Contains(t, string(b), "amount=150")
|
||||
})
|
||||
|
||||
t.Run("e2e/cook_run/regex/alternation_matches", func(t *testing.T) {
|
||||
dir := t.TempDir()
|
||||
wd, wderr := os.Getwd()
|
||||
require.NoError(t, wderr)
|
||||
require.NoError(t, os.Chdir(dir))
|
||||
t.Cleanup(func() { os.Chdir(wd) })
|
||||
|
||||
os.WriteFile(dataTxtPath, []byte("dog and cat"), 0644)
|
||||
os.WriteFile(cookTomlPath, []byte(`[[commands]]
|
||||
regex = "(cat|dog|bird)"
|
||||
lua = "replacement = 'PET'"
|
||||
files = ["data.txt"]
|
||||
`), 0644)
|
||||
|
||||
root := resetRootCmdForE2E(t)
|
||||
root.SetArgs([]string{cookTomlPath})
|
||||
require.NoError(t, root.Execute())
|
||||
b, rerr := os.ReadFile(dataTxtPath)
|
||||
require.NoError(t, rerr)
|
||||
assert.Equal(t, "PET and PET", string(b))
|
||||
})
|
||||
|
||||
t.Run("e2e/cook_run/regex/character_class", func(t *testing.T) {
|
||||
dir := t.TempDir()
|
||||
wd, wderr := os.Getwd()
|
||||
require.NoError(t, wderr)
|
||||
require.NoError(t, os.Chdir(dir))
|
||||
t.Cleanup(func() { os.Chdir(wd) })
|
||||
|
||||
os.WriteFile(dataTxtPath, []byte("abc123xyz"), 0644)
|
||||
os.WriteFile(cookTomlPath, []byte(`[[commands]]
|
||||
regex = "([a-z]+)"
|
||||
lua = "replacement = 'LOWER'"
|
||||
files = ["data.txt"]
|
||||
`), 0644)
|
||||
|
||||
root := resetRootCmdForE2E(t)
|
||||
root.SetArgs([]string{cookTomlPath})
|
||||
require.NoError(t, root.Execute())
|
||||
b, rerr := os.ReadFile(dataTxtPath)
|
||||
require.NoError(t, rerr)
|
||||
assert.Equal(t, "LOWER123LOWER", string(b))
|
||||
})
|
||||
|
||||
t.Run("e2e/cook_run/regex/digit_quantifier", func(t *testing.T) {
|
||||
dir := t.TempDir()
|
||||
wd, wderr := os.Getwd()
|
||||
require.NoError(t, wderr)
|
||||
require.NoError(t, os.Chdir(dir))
|
||||
t.Cleanup(func() { os.Chdir(wd) })
|
||||
|
||||
os.WriteFile(dataTxtPath, []byte("code: 12345"), 0644)
|
||||
os.WriteFile(cookTomlPath, []byte(`[[commands]]
|
||||
regex = "(\\d{3})"
|
||||
lua = "replacement = 'XXX'"
|
||||
files = ["data.txt"]
|
||||
`), 0644)
|
||||
|
||||
root := resetRootCmdForE2E(t)
|
||||
root.SetArgs([]string{cookTomlPath})
|
||||
require.NoError(t, root.Execute())
|
||||
b, rerr := os.ReadFile(dataTxtPath)
|
||||
require.NoError(t, rerr)
|
||||
assert.Contains(t, string(b), "XXX")
|
||||
})
|
||||
|
||||
t.Run("e2e/cook_run/regex/multi_digit_groups", func(t *testing.T) {
|
||||
dir := t.TempDir()
|
||||
wd, wderr := os.Getwd()
|
||||
require.NoError(t, wderr)
|
||||
require.NoError(t, os.Chdir(dir))
|
||||
t.Cleanup(func() { os.Chdir(wd) })
|
||||
|
||||
os.WriteFile(dataTxtPath, []byte("a=1 b=22 c=333"), 0644)
|
||||
os.WriteFile(cookTomlPath, []byte(`[[commands]]
|
||||
regex = "(\\d+)"
|
||||
lua = "v1 = v1 + 100"
|
||||
files = ["data.txt"]
|
||||
`), 0644)
|
||||
|
||||
root := resetRootCmdForE2E(t)
|
||||
root.SetArgs([]string{cookTomlPath})
|
||||
require.NoError(t, root.Execute())
|
||||
b, rerr := os.ReadFile(dataTxtPath)
|
||||
require.NoError(t, rerr)
|
||||
assert.Contains(t, string(b), "a=101")
|
||||
assert.Contains(t, string(b), "b=122")
|
||||
assert.Contains(t, string(b), "c=433")
|
||||
})
|
||||
|
||||
t.Run("e2e/cook_run/regex/uses_numeric_capture_val", func(t *testing.T) {
|
||||
dir := t.TempDir()
|
||||
wd, wderr := os.Getwd()
|
||||
require.NoError(t, wderr)
|
||||
require.NoError(t, os.Chdir(dir))
|
||||
t.Cleanup(func() { os.Chdir(wd) })
|
||||
|
||||
os.WriteFile(dataTxtPath, []byte("value=100"), 0644)
|
||||
os.WriteFile(cookTomlPath, []byte(`[[commands]]
|
||||
regex = "(\\d+)"
|
||||
lua = "v1 = v1 * 2"
|
||||
files = ["data.txt"]
|
||||
`), 0644)
|
||||
|
||||
root := resetRootCmdForE2E(t)
|
||||
root.SetArgs([]string{cookTomlPath})
|
||||
require.NoError(t, root.Execute())
|
||||
b, rerr := os.ReadFile(dataTxtPath)
|
||||
require.NoError(t, rerr)
|
||||
assert.Contains(t, string(b), "200")
|
||||
})
|
||||
|
||||
t.Run("e2e/cook_run/regex/uses_string_capture_raw", func(t *testing.T) {
|
||||
dir := t.TempDir()
|
||||
wd, wderr := os.Getwd()
|
||||
require.NoError(t, wderr)
|
||||
require.NoError(t, os.Chdir(dir))
|
||||
t.Cleanup(func() { os.Chdir(wd) })
|
||||
|
||||
os.WriteFile(dataTxtPath, []byte("hello"), 0644)
|
||||
os.WriteFile(cookTomlPath, []byte(`[[commands]]
|
||||
regex = "(.+)"
|
||||
lua = "replacement = string.upper(s1)"
|
||||
files = ["data.txt"]
|
||||
`), 0644)
|
||||
|
||||
root := resetRootCmdForE2E(t)
|
||||
root.SetArgs([]string{cookTomlPath})
|
||||
require.NoError(t, root.Execute())
|
||||
b, rerr := os.ReadFile(dataTxtPath)
|
||||
require.NoError(t, rerr)
|
||||
assert.Equal(t, "HELLO", string(b))
|
||||
})
|
||||
|
||||
t.Run("e2e/cook_run/regex/uses_replacement_variable", func(t *testing.T) {
|
||||
dir := t.TempDir()
|
||||
wd, wderr := os.Getwd()
|
||||
require.NoError(t, wderr)
|
||||
require.NoError(t, os.Chdir(dir))
|
||||
t.Cleanup(func() { os.Chdir(wd) })
|
||||
|
||||
os.WriteFile(dataTxtPath, []byte("hello world"), 0644)
|
||||
os.WriteFile(cookTomlPath, []byte(`[[commands]]
|
||||
regex = "(hello)"
|
||||
lua = "replacement = 'goodbye'"
|
||||
files = ["data.txt"]
|
||||
`), 0644)
|
||||
|
||||
root := resetRootCmdForE2E(t)
|
||||
root.SetArgs([]string{cookTomlPath})
|
||||
require.NoError(t, root.Execute())
|
||||
b, rerr := os.ReadFile(dataTxtPath)
|
||||
require.NoError(t, rerr)
|
||||
assert.Equal(t, "goodbye world", string(b))
|
||||
})
|
||||
|
||||
t.Run("e2e/cook_run/regex/conditional_modification", func(t *testing.T) {
|
||||
dir := t.TempDir()
|
||||
wd, wderr := os.Getwd()
|
||||
require.NoError(t, wderr)
|
||||
require.NoError(t, os.Chdir(dir))
|
||||
t.Cleanup(func() { os.Chdir(wd) })
|
||||
|
||||
os.WriteFile(dataTxtPath, []byte("num=5"), 0644)
|
||||
os.WriteFile(cookTomlPath, []byte(`[[commands]]
|
||||
regex = "num=(\\d+)"
|
||||
lua = "if tonumber(v1) > 3 then replacement = 'num=big' else replacement = 'num=small' end"
|
||||
files = ["data.txt"]
|
||||
`), 0644)
|
||||
|
||||
root := resetRootCmdForE2E(t)
|
||||
root.SetArgs([]string{cookTomlPath})
|
||||
require.NoError(t, root.Execute())
|
||||
b, rerr := os.ReadFile(dataTxtPath)
|
||||
require.NoError(t, rerr)
|
||||
assert.Equal(t, "num=big", string(b))
|
||||
})
|
||||
|
||||
t.Run("e2e/cook_run/json/modifies_field", func(t *testing.T) {
|
||||
dir := t.TempDir()
|
||||
wd, wderr := os.Getwd()
|
||||
require.NoError(t, wderr)
|
||||
require.NoError(t, os.Chdir(dir))
|
||||
t.Cleanup(func() { os.Chdir(wd) })
|
||||
|
||||
os.WriteFile(dataJSONPath, []byte(`{"count":5}`), 0644)
|
||||
os.WriteFile(cookTomlPath, []byte(`[[commands]]
|
||||
json = true
|
||||
lua = "data.count = data.count + 10"
|
||||
files = ["data.json"]
|
||||
`), 0644)
|
||||
|
||||
root := resetRootCmdForE2E(t)
|
||||
root.SetArgs([]string{cookTomlPath})
|
||||
require.NoError(t, root.Execute())
|
||||
b, rerr := os.ReadFile(dataJSONPath)
|
||||
require.NoError(t, rerr)
|
||||
assert.Contains(t, string(b), "15")
|
||||
})
|
||||
|
||||
t.Run("e2e/cook_run/json/adds_field", func(t *testing.T) {
|
||||
dir := t.TempDir()
|
||||
wd, wderr := os.Getwd()
|
||||
require.NoError(t, wderr)
|
||||
require.NoError(t, os.Chdir(dir))
|
||||
t.Cleanup(func() { os.Chdir(wd) })
|
||||
|
||||
os.WriteFile(dataJSONPath, []byte(`{}`), 0644)
|
||||
os.WriteFile(cookTomlPath, []byte(`[[commands]]
|
||||
json = true
|
||||
lua = "data.name = 'test'"
|
||||
files = ["data.json"]
|
||||
`), 0644)
|
||||
|
||||
root := resetRootCmdForE2E(t)
|
||||
root.SetArgs([]string{cookTomlPath})
|
||||
require.NoError(t, root.Execute())
|
||||
b, rerr := os.ReadFile(dataJSONPath)
|
||||
require.NoError(t, rerr)
|
||||
assert.Contains(t, string(b), "name")
|
||||
})
|
||||
|
||||
t.Run("e2e/cook_run/json/removes_field_with_nil", func(t *testing.T) {
|
||||
dir := t.TempDir()
|
||||
wd, wderr := os.Getwd()
|
||||
require.NoError(t, wderr)
|
||||
require.NoError(t, os.Chdir(dir))
|
||||
t.Cleanup(func() { os.Chdir(wd) })
|
||||
|
||||
os.WriteFile(dataJSONPath, []byte(`{"keep":"yes","remove":"no"}`), 0644)
|
||||
os.WriteFile(cookTomlPath, []byte(`[[commands]]
|
||||
json = true
|
||||
lua = "data.remove = nil"
|
||||
files = ["data.json"]
|
||||
`), 0644)
|
||||
|
||||
root := resetRootCmdForE2E(t)
|
||||
root.SetArgs([]string{cookTomlPath})
|
||||
require.NoError(t, root.Execute())
|
||||
b, rerr := os.ReadFile(dataJSONPath)
|
||||
require.NoError(t, rerr)
|
||||
assert.NotContains(t, string(b), "remove")
|
||||
assert.Contains(t, string(b), "keep")
|
||||
})
|
||||
|
||||
t.Run("e2e/cook_run/json/removes_with_jpathrm", func(t *testing.T) {
|
||||
dir := t.TempDir()
|
||||
wd, wderr := os.Getwd()
|
||||
require.NoError(t, wderr)
|
||||
require.NoError(t, os.Chdir(dir))
|
||||
t.Cleanup(func() { os.Chdir(wd) })
|
||||
|
||||
os.WriteFile(dataJSONPath, []byte(`{"a":1,"b":2}`), 0644)
|
||||
os.WriteFile(cookTomlPath, []byte(`[[commands]]
|
||||
json = true
|
||||
lua = "json.jpathrm(data, '$.a')"
|
||||
files = ["data.json"]
|
||||
`), 0644)
|
||||
|
||||
root := resetRootCmdForE2E(t)
|
||||
root.SetArgs([]string{cookTomlPath})
|
||||
require.NoError(t, root.Execute())
|
||||
b, rerr := os.ReadFile(dataJSONPath)
|
||||
require.NoError(t, rerr)
|
||||
assert.NotContains(t, string(b), `"a"`)
|
||||
assert.Contains(t, string(b), `"b"`)
|
||||
})
|
||||
|
||||
t.Run("e2e/cook_run/json/moves_array_elements", func(t *testing.T) {
|
||||
dir := t.TempDir()
|
||||
wd, wderr := os.Getwd()
|
||||
require.NoError(t, wderr)
|
||||
require.NoError(t, os.Chdir(dir))
|
||||
t.Cleanup(func() { os.Chdir(wd) })
|
||||
|
||||
os.WriteFile(dataJSONPath, []byte(`{"items":["a","b","c"]}`), 0644)
|
||||
os.WriteFile(cookTomlPath, []byte(`[[commands]]
|
||||
json = true
|
||||
lua = "local t = data.items[2]; table.remove(data.items, 2); table.insert(data.items, 1, t)"
|
||||
files = ["data.json"]
|
||||
`), 0644)
|
||||
|
||||
root := resetRootCmdForE2E(t)
|
||||
root.SetArgs([]string{cookTomlPath})
|
||||
require.NoError(t, root.Execute())
|
||||
b, rerr := os.ReadFile(dataJSONPath)
|
||||
require.NoError(t, rerr)
|
||||
assert.Contains(t, string(b), "b")
|
||||
assert.Contains(t, string(b), "a")
|
||||
})
|
||||
|
||||
t.Run("e2e/cook_run/json/nested_access", func(t *testing.T) {
|
||||
dir := t.TempDir()
|
||||
wd, wderr := os.Getwd()
|
||||
require.NoError(t, wderr)
|
||||
require.NoError(t, os.Chdir(dir))
|
||||
t.Cleanup(func() { os.Chdir(wd) })
|
||||
|
||||
os.WriteFile(dataJSONPath, []byte(`{"outer":{"inner":1}}`), 0644)
|
||||
os.WriteFile(cookTomlPath, []byte(`[[commands]]
|
||||
json = true
|
||||
lua = "data.outer.inner = 999"
|
||||
files = ["data.json"]
|
||||
`), 0644)
|
||||
|
||||
root := resetRootCmdForE2E(t)
|
||||
root.SetArgs([]string{cookTomlPath})
|
||||
require.NoError(t, root.Execute())
|
||||
b, rerr := os.ReadFile(dataJSONPath)
|
||||
require.NoError(t, rerr)
|
||||
assert.Contains(t, string(b), "999")
|
||||
})
|
||||
|
||||
t.Run("e2e/cook_run/xml/adds_attribute", func(t *testing.T) {
|
||||
dir := t.TempDir()
|
||||
wd, wderr := os.Getwd()
|
||||
require.NoError(t, wderr)
|
||||
require.NoError(t, os.Chdir(dir))
|
||||
t.Cleanup(func() { os.Chdir(wd) })
|
||||
|
||||
os.WriteFile(dataXMLPath, []byte(`<root><item/></root>`), 0644)
|
||||
os.WriteFile(cookTomlPath, []byte(`[[commands]]
|
||||
xml = true
|
||||
xpath = "//item"
|
||||
lua = "xml.setAttr(data, 'id', '1')"
|
||||
files = ["data.xml"]
|
||||
`), 0644)
|
||||
|
||||
root := resetRootCmdForE2E(t)
|
||||
root.SetArgs([]string{cookTomlPath})
|
||||
require.NoError(t, root.Execute())
|
||||
b, rerr := os.ReadFile(dataXMLPath)
|
||||
require.NoError(t, rerr)
|
||||
assert.Contains(t, string(b), `id="1"`)
|
||||
})
|
||||
|
||||
t.Run("e2e/cook_run/xml/removes_with_xpathrm", func(t *testing.T) {
|
||||
dir := t.TempDir()
|
||||
wd, wderr := os.Getwd()
|
||||
require.NoError(t, wderr)
|
||||
require.NoError(t, os.Chdir(dir))
|
||||
t.Cleanup(func() { os.Chdir(wd) })
|
||||
|
||||
os.WriteFile(dataXMLPath, []byte(`<root><item id="1"/><item id="2"/></root>`), 0644)
|
||||
os.WriteFile(cookTomlPath, []byte(`[[commands]]
|
||||
xml = true
|
||||
lua = "xml.xpathrm(data, '//item[@id=\"1\"]')"
|
||||
files = ["data.xml"]
|
||||
`), 0644)
|
||||
|
||||
root := resetRootCmdForE2E(t)
|
||||
root.SetArgs([]string{cookTomlPath})
|
||||
require.NoError(t, root.Execute())
|
||||
b, rerr := os.ReadFile(dataXMLPath)
|
||||
require.NoError(t, rerr)
|
||||
assert.NotContains(t, string(b), `id="1"`)
|
||||
assert.Contains(t, string(b), `id="2"`)
|
||||
})
|
||||
|
||||
t.Run("e2e/cook_run/xml/modifies_text", func(t *testing.T) {
|
||||
dir := t.TempDir()
|
||||
wd, wderr := os.Getwd()
|
||||
require.NoError(t, wderr)
|
||||
require.NoError(t, os.Chdir(dir))
|
||||
t.Cleanup(func() { os.Chdir(wd) })
|
||||
|
||||
os.WriteFile(dataXMLPath, []byte(`<root><item>old</item></root>`), 0644)
|
||||
os.WriteFile(cookTomlPath, []byte(`[[commands]]
|
||||
xml = true
|
||||
xpath = "//item"
|
||||
lua = "xml.setText(data, 'new')"
|
||||
files = ["data.xml"]
|
||||
`), 0644)
|
||||
|
||||
root := resetRootCmdForE2E(t)
|
||||
root.SetArgs([]string{cookTomlPath})
|
||||
require.NoError(t, root.Execute())
|
||||
b, rerr := os.ReadFile(dataXMLPath)
|
||||
require.NoError(t, rerr)
|
||||
assert.Contains(t, string(b), "new")
|
||||
})
|
||||
|
||||
t.Run("e2e/cook_run/xml/adds_child", func(t *testing.T) {
|
||||
dir := t.TempDir()
|
||||
wd, wderr := os.Getwd()
|
||||
require.NoError(t, wderr)
|
||||
require.NoError(t, os.Chdir(dir))
|
||||
t.Cleanup(func() { os.Chdir(wd) })
|
||||
|
||||
os.WriteFile(dataXMLPath, []byte(`<root><parent/></root>`), 0644)
|
||||
os.WriteFile(cookTomlPath, []byte(`[[commands]]
|
||||
xml = true
|
||||
xpath = "//parent"
|
||||
lua = "local child = {tag='child', text='hello'}; xml.addChild(data, child)"
|
||||
files = ["data.xml"]
|
||||
`), 0644)
|
||||
|
||||
root := resetRootCmdForE2E(t)
|
||||
root.SetArgs([]string{cookTomlPath})
|
||||
require.NoError(t, root.Execute())
|
||||
b, rerr := os.ReadFile(dataXMLPath)
|
||||
require.NoError(t, rerr)
|
||||
assert.Contains(t, string(b), "<child>hello</child>")
|
||||
})
|
||||
|
||||
t.Run("e2e/cook_run/xml/adds_new_element", func(t *testing.T) {
|
||||
dir := t.TempDir()
|
||||
wd, wderr := os.Getwd()
|
||||
require.NoError(t, wderr)
|
||||
require.NoError(t, os.Chdir(dir))
|
||||
t.Cleanup(func() { os.Chdir(wd) })
|
||||
|
||||
os.WriteFile(dataXMLPath, []byte(`<root/>`), 0644)
|
||||
os.WriteFile(cookTomlPath, []byte(`[[commands]]
|
||||
xml = true
|
||||
lua = "local el = {tag='item', attr={id='1'}}; xml.addChild(data, el)"
|
||||
files = ["data.xml"]
|
||||
`), 0644)
|
||||
|
||||
root := resetRootCmdForE2E(t)
|
||||
root.SetArgs([]string{cookTomlPath})
|
||||
require.NoError(t, root.Execute())
|
||||
b, rerr := os.ReadFile(dataXMLPath)
|
||||
require.NoError(t, rerr)
|
||||
assert.Contains(t, string(b), `id="1"`)
|
||||
})
|
||||
|
||||
t.Run("e2e/cook_run/xml/finds_with_predicate", func(t *testing.T) {
|
||||
dir := t.TempDir()
|
||||
wd, wderr := os.Getwd()
|
||||
require.NoError(t, wderr)
|
||||
require.NoError(t, os.Chdir(dir))
|
||||
t.Cleanup(func() { os.Chdir(wd) })
|
||||
|
||||
os.WriteFile(dataXMLPath, []byte(`<root><item v="10"/><item v="20"/></root>`), 0644)
|
||||
os.WriteFile(cookTomlPath, []byte(`[[commands]]
|
||||
xml = true
|
||||
lua = "for _, el in ipairs(xml.xpath(data, '//item[@v>15]')) do xml.setAttr(el, 'v', '99') end"
|
||||
files = ["data.xml"]
|
||||
`), 0644)
|
||||
|
||||
root := resetRootCmdForE2E(t)
|
||||
root.SetArgs([]string{cookTomlPath})
|
||||
require.NoError(t, root.Execute())
|
||||
b, rerr := os.ReadFile(dataXMLPath)
|
||||
require.NoError(t, rerr)
|
||||
assert.Contains(t, string(b), `v="10"`)
|
||||
assert.Contains(t, string(b), `v="99"`)
|
||||
})
|
||||
|
||||
t.Run("e2e/cook_run/json/preserves_whitespace", func(t *testing.T) {
|
||||
dir := t.TempDir()
|
||||
wd, wderr := os.Getwd()
|
||||
require.NoError(t, wderr)
|
||||
require.NoError(t, os.Chdir(dir))
|
||||
t.Cleanup(func() { os.Chdir(wd) })
|
||||
|
||||
os.WriteFile(dataJSONPath, []byte("{\n \"a\": 1\n}\n"), 0644)
|
||||
os.WriteFile(cookTomlPath, []byte(`[[commands]]
|
||||
json = true
|
||||
lua = "data.a = 2"
|
||||
files = ["data.json"]
|
||||
`), 0644)
|
||||
|
||||
root := resetRootCmdForE2E(t)
|
||||
root.SetArgs([]string{cookTomlPath})
|
||||
require.NoError(t, root.Execute())
|
||||
b, rerr := os.ReadFile(dataJSONPath)
|
||||
require.NoError(t, rerr)
|
||||
assert.Contains(t, string(b), `"a": 2`)
|
||||
})
|
||||
|
||||
t.Run("e2e/cook_run/xml/preserves_whitespace", func(t *testing.T) {
|
||||
dir := t.TempDir()
|
||||
wd, wderr := os.Getwd()
|
||||
require.NoError(t, wderr)
|
||||
require.NoError(t, os.Chdir(dir))
|
||||
t.Cleanup(func() { os.Chdir(wd) })
|
||||
|
||||
os.WriteFile(dataXMLPath, []byte("<root>\n <item/>\n</root>\n"), 0644)
|
||||
os.WriteFile(cookTomlPath, []byte(`[[commands]]
|
||||
xml = true
|
||||
xpath = "//item"
|
||||
lua = "xml.setAttr(data, 'x', 'y')"
|
||||
files = ["data.xml"]
|
||||
`), 0644)
|
||||
|
||||
root := resetRootCmdForE2E(t)
|
||||
root.SetArgs([]string{cookTomlPath})
|
||||
require.NoError(t, root.Execute())
|
||||
b, rerr := os.ReadFile(dataXMLPath)
|
||||
require.NoError(t, rerr)
|
||||
assert.Contains(t, string(b), `x="y"`)
|
||||
})
|
||||
}
|
||||
|
||||
func TestExecute(t *testing.T) {
|
||||
t.Run("e2e/execute/version_flag", func(t *testing.T) {
|
||||
tmp := t.TempDir()
|
||||
wd, err := os.Getwd()
|
||||
require.NoError(t, err)
|
||||
require.NoError(t, os.Chdir(tmp))
|
||||
t.Cleanup(func() {
|
||||
if err := os.Chdir(wd); err != nil {
|
||||
return
|
||||
}
|
||||
})
|
||||
old := os.Args
|
||||
t.Cleanup(func() { os.Args = old })
|
||||
os.Args = []string{"chef", "--version"}
|
||||
err = Execute()
|
||||
require.NoError(t, err)
|
||||
})
|
||||
}
|
||||
@@ -0,0 +1,13 @@
|
||||
package cmd
|
||||
|
||||
import (
|
||||
"os"
|
||||
"testing"
|
||||
|
||||
logger "git.site.quack-lab.dev/dave/cylogger/v3"
|
||||
)
|
||||
|
||||
func TestMain(m *testing.M) {
|
||||
logger.Init(logger.LevelInfo, false)
|
||||
os.Exit(m.Run())
|
||||
}
|
||||
+35
@@ -0,0 +1,35 @@
|
||||
package cmd
|
||||
|
||||
import (
|
||||
"cook/internal/chef"
|
||||
|
||||
"github.com/spf13/cobra"
|
||||
)
|
||||
|
||||
func newTUICmd() *cobra.Command {
|
||||
var parallel int
|
||||
var filter string
|
||||
var debugLog bool
|
||||
cmd := &cobra.Command{
|
||||
Use: "tui <cook_files...>",
|
||||
Short: "Open interactive TUI for selecting and running commands",
|
||||
Args: cobra.MinimumNArgs(1),
|
||||
RunE: func(cmd *cobra.Command, args []string) error {
|
||||
logLevelStr, err := cmd.Flags().GetString("loglevel")
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
return chef.RunTUI(chef.TUIConfig{
|
||||
Args: args,
|
||||
Parallel: parallel,
|
||||
Filter: filter,
|
||||
DebugLog: debugLog,
|
||||
LogLevel: logLevelStr,
|
||||
})
|
||||
},
|
||||
}
|
||||
cmd.Flags().IntVarP(¶llel, "parallel", "P", 100, "Number of files to process in parallel")
|
||||
cmd.Flags().StringVarP(&filter, "filter", "f", "", "Filter commands before loading")
|
||||
cmd.Flags().BoolVarP(&debugLog, "debug-log", "d", false, "Tee logs to chef.log for debugging")
|
||||
return cmd
|
||||
}
|
||||
@@ -0,0 +1,40 @@
|
||||
package cmd
|
||||
|
||||
import (
|
||||
"errors"
|
||||
|
||||
"cook/internal/chef"
|
||||
|
||||
"github.com/spf13/cobra"
|
||||
)
|
||||
|
||||
func newWatchCmd() *cobra.Command {
|
||||
cmd := &cobra.Command{
|
||||
Use: "watch <cook_files...>",
|
||||
Short: "Run cook files and re-run them whenever any of them changes on disk",
|
||||
Long: `Run the cook files exactly like the default command, then keep watching
|
||||
them and re-run all of them whenever any cook file changes on disk. The
|
||||
command keeps running until interrupted.
|
||||
|
||||
Supports the same flags and cook files as the default command.`,
|
||||
Args: cobra.ArbitraryArgs,
|
||||
RunE: runWatch,
|
||||
}
|
||||
addRootFlags(cmd)
|
||||
return cmd
|
||||
}
|
||||
|
||||
func runWatch(cmd *cobra.Command, args []string) error {
|
||||
cfg, err := rootRunConfig(cmd, args)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
err = chef.RunRootWatch(cfg)
|
||||
if errors.Is(err, chef.ErrShowUsage) {
|
||||
if usageErr := cmd.Usage(); usageErr != nil {
|
||||
return usageErr
|
||||
}
|
||||
return nil
|
||||
}
|
||||
return err
|
||||
}
|
||||
@@ -0,0 +1,25 @@
|
||||
package cmd
|
||||
|
||||
import (
|
||||
"cook/internal/chef"
|
||||
|
||||
"github.com/spf13/cobra"
|
||||
)
|
||||
|
||||
func newXJPathCmd() *cobra.Command {
|
||||
return &cobra.Command{
|
||||
Use: "xj <xmlpath> [files...]",
|
||||
Short: "Search XML files with an XPath expression",
|
||||
Long: `Search XML files with an XPath expression, printing every line that
|
||||
contains a match, ripgrep style. With no file arguments, searches the
|
||||
current directory recursively for *.xml files.
|
||||
|
||||
Examples:
|
||||
chef xj '//item[@id="1"]' mods/**/*.xml
|
||||
chef xj '//ammo' mods`,
|
||||
Args: cobra.MinimumNArgs(1),
|
||||
RunE: func(cmd *cobra.Command, args []string) error {
|
||||
return chef.RunXMLSearch(args, cmd.OutOrStdout(), cmd.ErrOrStderr())
|
||||
},
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,73 @@
|
||||
//go:build e2e
|
||||
|
||||
package cmd
|
||||
|
||||
import (
|
||||
"bytes"
|
||||
"os"
|
||||
"path/filepath"
|
||||
"testing"
|
||||
|
||||
"github.com/stretchr/testify/assert"
|
||||
"github.com/stretchr/testify/require"
|
||||
)
|
||||
|
||||
func TestXJPathCmdE2E(t *testing.T) {
|
||||
dir := t.TempDir()
|
||||
wd, err := os.Getwd()
|
||||
require.NoError(t, err)
|
||||
require.NoError(t, os.Chdir(dir))
|
||||
t.Cleanup(func() {
|
||||
if err := os.Chdir(wd); err != nil {
|
||||
return
|
||||
}
|
||||
})
|
||||
|
||||
write := func(name, content string) string {
|
||||
p := filepath.Join(dir, name)
|
||||
require.NoError(t, os.WriteFile(p, []byte(content), 0644))
|
||||
return p
|
||||
}
|
||||
fileA := write("a.xml", "<root>\n <ammo>arrow</ammo>\n</root>\n")
|
||||
write("b.xml", "<root>\n <other/>\n</root>\n")
|
||||
|
||||
t.Run("e2e/xj/multi_file_grep_style", func(t *testing.T) {
|
||||
var stdout bytes.Buffer
|
||||
var stderr bytes.Buffer
|
||||
root := resetRootCmdForE2E(t)
|
||||
root.SetOut(&stdout)
|
||||
root.SetErr(&stderr)
|
||||
root.SetArgs([]string{"xj", "//ammo", fileA, filepath.Join(dir, "b.xml")})
|
||||
require.NoError(t, root.Execute())
|
||||
|
||||
got := stdout.String()
|
||||
assert.Contains(t, got, fileA+"\n")
|
||||
assert.Contains(t, got, "2: <ammo>arrow</ammo>")
|
||||
assert.NotContains(t, got, "b.xml\n")
|
||||
})
|
||||
|
||||
t.Run("e2e/xj/attribute_predicate", func(t *testing.T) {
|
||||
var stdout bytes.Buffer
|
||||
var stderr bytes.Buffer
|
||||
root := resetRootCmdForE2E(t)
|
||||
root.SetOut(&stdout)
|
||||
root.SetErr(&stderr)
|
||||
root.SetArgs([]string{"xj", `//ammo[text()="arrow"]`, fileA})
|
||||
require.NoError(t, root.Execute())
|
||||
|
||||
got := stdout.String()
|
||||
assert.Contains(t, got, "2: <ammo>arrow</ammo>")
|
||||
})
|
||||
|
||||
t.Run("e2e/xj/invalid_expression_errors", func(t *testing.T) {
|
||||
var stdout bytes.Buffer
|
||||
var stderr bytes.Buffer
|
||||
root := resetRootCmdForE2E(t)
|
||||
root.SetOut(&stdout)
|
||||
root.SetErr(&stderr)
|
||||
root.SetArgs([]string{"xj", "//[", fileA})
|
||||
err := root.Execute()
|
||||
require.Error(t, err)
|
||||
assert.Contains(t, err.Error(), "invalid xpath")
|
||||
})
|
||||
}
|
||||
@@ -1,95 +0,0 @@
|
||||
package main
|
||||
|
||||
import (
|
||||
"modify/utils"
|
||||
"os"
|
||||
"path/filepath"
|
||||
"testing"
|
||||
)
|
||||
|
||||
func TestGlobExpansion(t *testing.T) {
|
||||
// Create a temporary directory structure for testing
|
||||
tmpDir, err := os.MkdirTemp("", "glob-test")
|
||||
if err != nil {
|
||||
t.Fatalf("Failed to create temp dir: %v", err)
|
||||
}
|
||||
defer os.RemoveAll(tmpDir)
|
||||
|
||||
// Create some test files
|
||||
testFiles := []string{
|
||||
filepath.Join(tmpDir, "file1.xml"),
|
||||
filepath.Join(tmpDir, "file2.xml"),
|
||||
filepath.Join(tmpDir, "test.txt"),
|
||||
filepath.Join(tmpDir, "subdir", "file3.xml"),
|
||||
filepath.Join(tmpDir, "subdir", "file4.txt"),
|
||||
filepath.Join(tmpDir, "subdir", "nested", "file5.xml"),
|
||||
}
|
||||
|
||||
// Create the directory structure
|
||||
err = os.MkdirAll(filepath.Join(tmpDir, "subdir", "nested"), 0755)
|
||||
if err != nil {
|
||||
t.Fatalf("Failed to create subdirectories: %v", err)
|
||||
}
|
||||
|
||||
// Create the files
|
||||
for _, file := range testFiles {
|
||||
dir := filepath.Dir(file)
|
||||
if err := os.MkdirAll(dir, 0755); err != nil {
|
||||
t.Fatalf("Failed to create directory %s: %v", dir, err)
|
||||
}
|
||||
if err := os.WriteFile(file, []byte("test content"), 0644); err != nil {
|
||||
t.Fatalf("Failed to create file %s: %v", file, err)
|
||||
}
|
||||
}
|
||||
|
||||
// Change to the temporary directory to use relative paths
|
||||
origDir, _ := os.Getwd()
|
||||
os.Chdir(tmpDir)
|
||||
defer os.Chdir(origDir)
|
||||
|
||||
// Test cases
|
||||
tests := []struct {
|
||||
name string
|
||||
patterns []string
|
||||
expected int
|
||||
}{
|
||||
{
|
||||
name: "Simple pattern",
|
||||
patterns: []string{"*.xml"},
|
||||
expected: 2, // file1.xml, file2.xml
|
||||
},
|
||||
{
|
||||
name: "Multiple patterns",
|
||||
patterns: []string{"*.xml", "*.txt"},
|
||||
expected: 3, // file1.xml, file2.xml, test.txt
|
||||
},
|
||||
{
|
||||
name: "Directory globbing",
|
||||
patterns: []string{"subdir/*.xml"},
|
||||
expected: 1, // subdir/file3.xml
|
||||
},
|
||||
{
|
||||
name: "Doublestar pattern",
|
||||
patterns: []string{"**/*.xml"},
|
||||
expected: 4, // All XML files in all directories
|
||||
},
|
||||
}
|
||||
|
||||
for _, tc := range tests {
|
||||
t.Run(tc.name, func(t *testing.T) {
|
||||
// Convert string patterns to map[string]struct{} for ExpandGLobs
|
||||
patternMap := make(map[string]struct{})
|
||||
for _, pattern := range tc.patterns {
|
||||
patternMap[pattern] = struct{}{}
|
||||
}
|
||||
files, err := utils.ExpandGLobs(patternMap)
|
||||
if err != nil {
|
||||
t.Fatalf("ExpandGLobs failed: %v", err)
|
||||
}
|
||||
|
||||
if len(files) != tc.expected {
|
||||
t.Errorf("Expected %d files, got %d: %v", tc.expected, len(files), files)
|
||||
}
|
||||
})
|
||||
}
|
||||
}
|
||||
@@ -1,38 +1,63 @@
|
||||
module modify
|
||||
module cook
|
||||
|
||||
go 1.24.1
|
||||
go 1.26
|
||||
|
||||
require (
|
||||
github.com/bmatcuk/doublestar/v4 v4.8.1
|
||||
github.com/stretchr/testify v1.10.0
|
||||
github.com/stretchr/testify v1.11.1
|
||||
github.com/yuin/gopher-lua v1.1.1
|
||||
gopkg.in/yaml.v3 v3.0.1
|
||||
gorm.io/gorm v1.30.0
|
||||
)
|
||||
|
||||
require (
|
||||
dario.cat/mergo v1.0.0 // indirect
|
||||
github.com/Microsoft/go-winio v0.6.2 // indirect
|
||||
github.com/ProtonMail/go-crypto v1.1.5 // indirect
|
||||
github.com/cloudflare/circl v1.6.0 // indirect
|
||||
github.com/cyphar/filepath-securejoin v0.4.1 // indirect
|
||||
github.com/bits-and-blooms/bitset v1.24.2 // indirect
|
||||
github.com/bits-and-blooms/bloom/v3 v3.7.1 // indirect
|
||||
github.com/davecgh/go-spew v1.1.1 // indirect
|
||||
github.com/emirpasic/gods v1.18.1 // indirect
|
||||
github.com/go-git/gcfg v1.5.1-0.20230307220236-3a3c6141e376 // indirect
|
||||
github.com/go-git/go-billy/v5 v5.6.2 // indirect
|
||||
github.com/jbenet/go-context v0.0.0-20150711004518-d14ea06fba99 // indirect
|
||||
github.com/kevinburke/ssh_config v1.2.0 // indirect
|
||||
github.com/pjbgf/sha1cd v0.3.2 // indirect
|
||||
github.com/gdamore/encoding v1.0.1 // indirect
|
||||
github.com/grafana/regexp v0.0.0-20250905101755-5eb4f3acbf71 // indirect
|
||||
github.com/hexops/valast v1.5.0 // indirect
|
||||
github.com/inconshreveable/mousetrap v1.1.0 // indirect
|
||||
github.com/jinzhu/inflection v1.0.0 // indirect
|
||||
github.com/jinzhu/now v1.1.5 // indirect
|
||||
github.com/kr/pretty v0.3.1 // indirect
|
||||
github.com/lucasb-eyer/go-colorful v1.3.0 // indirect
|
||||
github.com/mattn/go-runewidth v0.0.16 // indirect
|
||||
github.com/mattn/go-sqlite3 v1.14.22 // indirect
|
||||
github.com/pmezard/go-difflib v1.0.0 // indirect
|
||||
github.com/sergi/go-diff v1.3.2-0.20230802210424-5b0b94c5c0d3 // indirect
|
||||
github.com/skeema/knownhosts v1.3.1 // indirect
|
||||
github.com/xanzy/ssh-agent v0.3.3 // indirect
|
||||
golang.org/x/crypto v0.35.0 // indirect
|
||||
golang.org/x/sys v0.30.0 // indirect
|
||||
gopkg.in/warnings.v0 v0.1.2 // indirect
|
||||
github.com/rivo/uniseg v0.4.7 // indirect
|
||||
github.com/rogpeppe/go-internal v1.14.1 // indirect
|
||||
github.com/spf13/pflag v1.0.9 // indirect
|
||||
github.com/tidwall/match v1.1.1 // indirect
|
||||
github.com/tidwall/pretty v1.2.0 // indirect
|
||||
golang.org/x/exp/shiny v0.0.0-20250606033433-dcc06ee1d476 // indirect
|
||||
golang.org/x/image v0.28.0 // indirect
|
||||
golang.org/x/mobile v0.0.0-20250606033058-a2a15c67f36f // indirect
|
||||
golang.org/x/mod v0.29.0 // indirect
|
||||
golang.org/x/sync v0.18.0 // indirect
|
||||
golang.org/x/sys v0.38.0 // indirect
|
||||
golang.org/x/term v0.37.0 // indirect
|
||||
golang.org/x/text v0.31.0 // indirect
|
||||
golang.org/x/time v0.12.0 // indirect
|
||||
golang.org/x/tools v0.38.0 // indirect
|
||||
mvdan.cc/gofumpt v0.4.0 // indirect
|
||||
)
|
||||
|
||||
require (
|
||||
github.com/go-git/go-git/v5 v5.14.0
|
||||
github.com/golang/groupcache v0.0.0-20241129210726-2c02b8208cf8 // indirect
|
||||
golang.org/x/net v0.35.0 // indirect
|
||||
git.site.quack-lab.dev/dave/cylogger/v3 v3.1.3
|
||||
git.site.quack-lab.dev/dave/cyutils v1.7.0
|
||||
git.site.quack-lab.dev/dave/gripgrep v0.17.3
|
||||
github.com/BurntSushi/toml v1.5.0
|
||||
github.com/antchfx/xpath v1.3.6
|
||||
github.com/atotto/clipboard v0.1.4
|
||||
github.com/bluekeyes/go-gitdiff v0.8.1
|
||||
github.com/fsnotify/fsnotify v1.10.1
|
||||
github.com/gdamore/tcell/v2 v2.8.1
|
||||
github.com/google/go-cmp v0.6.0
|
||||
github.com/jedib0t/go-pretty/v6 v6.7.8
|
||||
github.com/spf13/cobra v1.10.1
|
||||
github.com/theory/jsonpath v0.11.0
|
||||
github.com/tidwall/gjson v1.18.0
|
||||
golang.design/x/clipboard v0.7.1
|
||||
gorm.io/driver/sqlite v1.6.0
|
||||
)
|
||||
@@ -1,106 +1,185 @@
|
||||
dario.cat/mergo v1.0.0 h1:AGCNq9Evsj31mOgNPcLyXc+4PNABt905YmuqPYYpBWk=
|
||||
dario.cat/mergo v1.0.0/go.mod h1:uNxQE+84aUszobStD9th8a29P2fMDhsBdgRYvZOxGmk=
|
||||
github.com/Microsoft/go-winio v0.5.2/go.mod h1:WpS1mjBmmwHBEWmogvA2mj8546UReBk4v8QkMxJ6pZY=
|
||||
github.com/Microsoft/go-winio v0.6.2 h1:F2VQgta7ecxGYO8k3ZZz3RS8fVIXVxONVUPlNERoyfY=
|
||||
github.com/Microsoft/go-winio v0.6.2/go.mod h1:yd8OoFMLzJbo9gZq8j5qaps8bJ9aShtEA8Ipt1oGCvU=
|
||||
github.com/ProtonMail/go-crypto v1.1.5 h1:eoAQfK2dwL+tFSFpr7TbOaPNUbPiJj4fLYwwGE1FQO4=
|
||||
github.com/ProtonMail/go-crypto v1.1.5/go.mod h1:rA3QumHc/FZ8pAHreoekgiAbzpNsfQAosU5td4SnOrE=
|
||||
github.com/anmitsu/go-shlex v0.0.0-20200514113438-38f4b401e2be h1:9AeTilPcZAjCFIImctFaOjnTIavg87rW78vTPkQqLI8=
|
||||
github.com/anmitsu/go-shlex v0.0.0-20200514113438-38f4b401e2be/go.mod h1:ySMOLuWl6zY27l47sB3qLNK6tF2fkHG55UZxx8oIVo4=
|
||||
github.com/armon/go-socks5 v0.0.0-20160902184237-e75332964ef5 h1:0CwZNZbxp69SHPdPJAN/hZIm0C4OItdklCFmMRWYpio=
|
||||
github.com/armon/go-socks5 v0.0.0-20160902184237-e75332964ef5/go.mod h1:wHh0iHkYZB8zMSxRWpUBQtwG5a7fFgvEO+odwuTv2gs=
|
||||
git.site.quack-lab.dev/dave/cylogger/v3 v3.1.3 h1:0QAxa9T6/3sF13Uriihn7535cD8K2H2E9F+hYMMpBOs=
|
||||
git.site.quack-lab.dev/dave/cylogger/v3 v3.1.3/go.mod h1:u+l522/uUogR/Sf5CbE0umZQBey754Oi+9sf9ZJoa3Y=
|
||||
git.site.quack-lab.dev/dave/cyutils v1.7.0 h1:+b2mrJ8hVF0jF4amIw9QE6gEHHwTvnu3dKztyttPvzk=
|
||||
git.site.quack-lab.dev/dave/cyutils v1.7.0/go.mod h1:2tH6NnD3fy29GKc3xFMigoeMuJ1eTYqIkGZumczMNxM=
|
||||
git.site.quack-lab.dev/dave/gripgrep v0.17.3 h1:NBMMWVFs7KIbpytV7mw/ETWFxUIaeCcnM51bD4VjPzk=
|
||||
git.site.quack-lab.dev/dave/gripgrep v0.17.3/go.mod h1:ysH7FCT6w8CbWj8Em4DyWJdVAiEgFf9opsEaNqzZduk=
|
||||
github.com/BurntSushi/toml v1.5.0 h1:W5quZX/G/csjUnuI8SUYlsHs9M38FC7znL0lIO+DvMg=
|
||||
github.com/BurntSushi/toml v1.5.0/go.mod h1:ukJfTF/6rtPPRCnwkur4qwRxa8vTRFBF0uk2lLoLwho=
|
||||
github.com/antchfx/xpath v1.3.6 h1:s0y+ElRRtTQdfHP609qFu0+c6bglDv20pqOViQjjdPI=
|
||||
github.com/antchfx/xpath v1.3.6/go.mod h1:i54GszH55fYfBmoZXapTHN8T8tkcHfRgLyVwwqzXNcs=
|
||||
github.com/atotto/clipboard v0.1.4 h1:EH0zSVneZPSuFR11BlR9YppQTVDbh5+16AmcJi4g1z4=
|
||||
github.com/atotto/clipboard v0.1.4/go.mod h1:ZY9tmq7sm5xIbd9bOK4onWV4S6X0u6GY7Vn0Yu86PYI=
|
||||
github.com/bits-and-blooms/bitset v1.24.2 h1:M7/NzVbsytmtfHbumG+K2bremQPMJuqv1JD3vOaFxp0=
|
||||
github.com/bits-and-blooms/bitset v1.24.2/go.mod h1:7hO7Gc7Pp1vODcmWvKMRA9BNmbv6a/7QIWpPxHddWR8=
|
||||
github.com/bits-and-blooms/bloom/v3 v3.7.1 h1:WXovk4TRKZttAMJfoQx6K2DM0zNIt8w+c67UqO+etV0=
|
||||
github.com/bits-and-blooms/bloom/v3 v3.7.1/go.mod h1:rZzYLLje2dfzXfAkJNxQQHsKurAyK55KUnL43Euk0hU=
|
||||
github.com/bluekeyes/go-gitdiff v0.8.1 h1:lL1GofKMywO17c0lgQmJYcKek5+s8X6tXVNOLxy4smI=
|
||||
github.com/bluekeyes/go-gitdiff v0.8.1/go.mod h1:WWAk1Mc6EgWarCrPFO+xeYlujPu98VuLW3Tu+B/85AE=
|
||||
github.com/bmatcuk/doublestar/v4 v4.8.1 h1:54Bopc5c2cAvhLRAzqOGCYHYyhcDHsFF4wWIR5wKP38=
|
||||
github.com/bmatcuk/doublestar/v4 v4.8.1/go.mod h1:xBQ8jztBU6kakFMg+8WGxn0c6z1fTSPVIjEY1Wr7jzc=
|
||||
github.com/cloudflare/circl v1.6.0 h1:cr5JKic4HI+LkINy2lg3W2jF8sHCVTBncJr5gIIq7qk=
|
||||
github.com/cloudflare/circl v1.6.0/go.mod h1:uddAzsPgqdMAYatqJ0lsjX1oECcQLIlRpzZh3pJrofs=
|
||||
github.com/cyphar/filepath-securejoin v0.4.1 h1:JyxxyPEaktOD+GAnqIqTf9A8tHyAG22rowi7HkoSU1s=
|
||||
github.com/cyphar/filepath-securejoin v0.4.1/go.mod h1:Sdj7gXlvMcPZsbhwhQ33GguGLDGQL7h7bg04C/+u9jI=
|
||||
github.com/davecgh/go-spew v1.1.0/go.mod h1:J7Y8YcW2NihsgmVo/mv3lAwl/skON4iLHjSsI+c5H38=
|
||||
github.com/cpuguy83/go-md2man/v2 v2.0.6/go.mod h1:oOW0eioCTA6cOiMLiUPZOpcVxMig6NIQQ7OS05n1F4g=
|
||||
github.com/creack/pty v1.1.9/go.mod h1:oKZEueFk5CKHvIhNR5MUki03XCEU+Q6VDXinZuGJ33E=
|
||||
github.com/davecgh/go-spew v1.1.1 h1:vj9j/u1bqnvCEfJOwUhtlOARqs3+rkHYY13jYWTU97c=
|
||||
github.com/davecgh/go-spew v1.1.1/go.mod h1:J7Y8YcW2NihsgmVo/mv3lAwl/skON4iLHjSsI+c5H38=
|
||||
github.com/elazarl/goproxy v1.7.2 h1:Y2o6urb7Eule09PjlhQRGNsqRfPmYI3KKQLFpCAV3+o=
|
||||
github.com/elazarl/goproxy v1.7.2/go.mod h1:82vkLNir0ALaW14Rc399OTTjyNREgmdL2cVoIbS6XaE=
|
||||
github.com/emirpasic/gods v1.18.1 h1:FXtiHYKDGKCW2KzwZKx0iC0PQmdlorYgdFG9jPXJ1Bc=
|
||||
github.com/emirpasic/gods v1.18.1/go.mod h1:8tpGGwCnJ5H4r6BWwaV6OrWmMoPhUl5jm/FMNAnJvWQ=
|
||||
github.com/gliderlabs/ssh v0.3.8 h1:a4YXD1V7xMF9g5nTkdfnja3Sxy1PVDCj1Zg4Wb8vY6c=
|
||||
github.com/gliderlabs/ssh v0.3.8/go.mod h1:xYoytBv1sV0aL3CavoDuJIQNURXkkfPA/wxQ1pL1fAU=
|
||||
github.com/go-git/gcfg v1.5.1-0.20230307220236-3a3c6141e376 h1:+zs/tPmkDkHx3U66DAb0lQFJrpS6731Oaa12ikc+DiI=
|
||||
github.com/go-git/gcfg v1.5.1-0.20230307220236-3a3c6141e376/go.mod h1:an3vInlBmSxCcxctByoQdvwPiA7DTK7jaaFDBTtu0ic=
|
||||
github.com/go-git/go-billy/v5 v5.6.2 h1:6Q86EsPXMa7c3YZ3aLAQsMA0VlWmy43r6FHqa/UNbRM=
|
||||
github.com/go-git/go-billy/v5 v5.6.2/go.mod h1:rcFC2rAsp/erv7CMz9GczHcuD0D32fWzH+MJAU+jaUU=
|
||||
github.com/go-git/go-git-fixtures/v4 v4.3.2-0.20231010084843-55a94097c399 h1:eMje31YglSBqCdIqdhKBW8lokaMrL3uTkpGYlE2OOT4=
|
||||
github.com/go-git/go-git-fixtures/v4 v4.3.2-0.20231010084843-55a94097c399/go.mod h1:1OCfN199q1Jm3HZlxleg+Dw/mwps2Wbk9frAWm+4FII=
|
||||
github.com/go-git/go-git/v5 v5.14.0 h1:/MD3lCrGjCen5WfEAzKg00MJJffKhC8gzS80ycmCi60=
|
||||
github.com/go-git/go-git/v5 v5.14.0/go.mod h1:Z5Xhoia5PcWA3NF8vRLURn9E5FRhSl7dGj9ItW3Wk5k=
|
||||
github.com/golang/groupcache v0.0.0-20241129210726-2c02b8208cf8 h1:f+oWsMOmNPc8JmEHVZIycC7hBoQxHH9pNKQORJNozsQ=
|
||||
github.com/golang/groupcache v0.0.0-20241129210726-2c02b8208cf8/go.mod h1:wcDNUvekVysuuOpQKo3191zZyTpiI6se1N1ULghS0sw=
|
||||
github.com/google/go-cmp v0.7.0 h1:wk8382ETsv4JYUZwIsn6YpYiWiBsYLSJiTsyBybVuN8=
|
||||
github.com/google/go-cmp v0.7.0/go.mod h1:pXiqmnSA92OHEEa9HXL2W4E7lf9JzCmGVUdgjX3N/iU=
|
||||
github.com/jbenet/go-context v0.0.0-20150711004518-d14ea06fba99 h1:BQSFePA1RWJOlocH6Fxy8MmwDt+yVQYULKfN0RoTN8A=
|
||||
github.com/jbenet/go-context v0.0.0-20150711004518-d14ea06fba99/go.mod h1:1lJo3i6rXxKeerYnT8Nvf0QmHCRC1n8sfWVwXF2Frvo=
|
||||
github.com/kevinburke/ssh_config v1.2.0 h1:x584FjTGwHzMwvHx18PXxbBVzfnxogHaAReU4gf13a4=
|
||||
github.com/kevinburke/ssh_config v1.2.0/go.mod h1:CT57kijsi8u/K/BOFA39wgDQJ9CxiF4nAY/ojJ6r6mM=
|
||||
github.com/kr/pretty v0.1.0/go.mod h1:dAy3ld7l9f0ibDNOQOHHMYYIIbhfbHSm3C4ZsoJORNo=
|
||||
github.com/frankban/quicktest v1.14.3 h1:FJKSZTDHjyhriyC81FLQ0LY93eSai0ZyR/ZIkd3ZUKE=
|
||||
github.com/frankban/quicktest v1.14.3/go.mod h1:mgiwOwqx65TmIk1wJ6Q7wvnVMocbUorkibMOrVTHZps=
|
||||
github.com/fsnotify/fsnotify v1.10.1 h1:b0/UzAf9yR5rhf3RPm9gf3ehBPpf0oZKIjtpKrx59Ho=
|
||||
github.com/fsnotify/fsnotify v1.10.1/go.mod h1:TLheqan6HD6GBK6PrDWyDPBaEV8LspOxvPSjC+bVfgo=
|
||||
github.com/gdamore/encoding v1.0.1 h1:YzKZckdBL6jVt2Gc+5p82qhrGiqMdG/eNs6Wy0u3Uhw=
|
||||
github.com/gdamore/encoding v1.0.1/go.mod h1:0Z0cMFinngz9kS1QfMjCP8TY7em3bZYeeklsSDPivEo=
|
||||
github.com/gdamore/tcell/v2 v2.8.1 h1:KPNxyqclpWpWQlPLx6Xui1pMk8S+7+R37h3g07997NU=
|
||||
github.com/gdamore/tcell/v2 v2.8.1/go.mod h1:bj8ori1BG3OYMjmb3IklZVWfZUJ1UBQt9JXrOCOhGWw=
|
||||
github.com/google/go-cmp v0.6.0 h1:ofyhxvXcZhMsU5ulbFiLKl/XBFqE1GSq7atu8tAmTRI=
|
||||
github.com/google/go-cmp v0.6.0/go.mod h1:17dUlkBOakJ0+DkrSSNjCkIjxS6bF9zb3elmeNGIjoY=
|
||||
github.com/grafana/regexp v0.0.0-20250905101755-5eb4f3acbf71 h1:A4D22zZV7+EeQk9TeATDDY/PG2wnzdqKcj4IZq+PcwA=
|
||||
github.com/grafana/regexp v0.0.0-20250905101755-5eb4f3acbf71/go.mod h1:+JKpmjMGhpgPL+rXZ5nsZieVzvarn86asRlBg4uNGnk=
|
||||
github.com/hexops/autogold v0.8.1 h1:wvyd/bAJ+Dy+DcE09BoLk6r4Fa5R5W+O+GUzmR985WM=
|
||||
github.com/hexops/autogold v0.8.1/go.mod h1:97HLDXyG23akzAoRYJh/2OBs3kd80eHyKPvZw0S5ZBY=
|
||||
github.com/hexops/gotextdiff v1.0.3 h1:gitA9+qJrrTCsiCl7+kh75nPqQt1cx4ZkudSTLoUqJM=
|
||||
github.com/hexops/gotextdiff v1.0.3/go.mod h1:pSWU5MAI3yDq+fZBTazCSJysOMbxWL1BSow5/V2vxeg=
|
||||
github.com/hexops/valast v1.5.0 h1:FBTuvVi0wjTngtXJRZXMbkN/Dn6DgsUsBwch2DUJU8Y=
|
||||
github.com/hexops/valast v1.5.0/go.mod h1:Jcy1pNH7LNraVaAZDLyv21hHg2WBv9Nf9FL6fGxU7o4=
|
||||
github.com/inconshreveable/mousetrap v1.1.0 h1:wN+x4NVGpMsO7ErUn/mUI3vEoE6Jt13X2s0bqwp9tc8=
|
||||
github.com/inconshreveable/mousetrap v1.1.0/go.mod h1:vpF70FUmC8bwa3OWnCshd2FqLfsEA9PFc4w1p2J65bw=
|
||||
github.com/jedib0t/go-pretty/v6 v6.7.8 h1:BVYrDy5DPBA3Qn9ICT+PokP9cvCv1KaHv2i+Hc8sr5o=
|
||||
github.com/jedib0t/go-pretty/v6 v6.7.8/go.mod h1:YwC5CE4fJ1HFUDeivSV1r//AmANFHyqczZk+U6BDALU=
|
||||
github.com/jinzhu/inflection v1.0.0 h1:K317FqzuhWc8YvSVlFMCCUb36O/S9MCKRDI7QkRKD/E=
|
||||
github.com/jinzhu/inflection v1.0.0/go.mod h1:h+uFLlag+Qp1Va5pdKtLDYj+kHp5pxUVkryuEj+Srlc=
|
||||
github.com/jinzhu/now v1.1.5 h1:/o9tlHleP7gOFmsnYNz3RGnqzefHA47wQpKrrdTIwXQ=
|
||||
github.com/jinzhu/now v1.1.5/go.mod h1:d3SSVoowX0Lcu0IBviAWJpolVfI5UJVZZ7cO71lE/z8=
|
||||
github.com/kr/pretty v0.3.1 h1:flRD4NNwYAUpkphVc1HcthR4KEIFJ65n8Mw5qdRn3LE=
|
||||
github.com/kr/pretty v0.3.1/go.mod h1:hoEshYVHaxMs3cyo3Yncou5ZscifuDolrwPKZanG3xk=
|
||||
github.com/kr/pty v1.1.1/go.mod h1:pFQYn66WHrOpPYNljwOMqo10TkYh1fy3cYio2l3bCsQ=
|
||||
github.com/kr/text v0.1.0/go.mod h1:4Jbv+DJW3UT/LiOwJeYQe1efqtUx/iVham/4vfdArNI=
|
||||
github.com/kr/text v0.2.0 h1:5Nx0Ya0ZqY2ygV366QzturHI13Jq95ApcVaJBhpS+AY=
|
||||
github.com/kr/text v0.2.0/go.mod h1:eLer722TekiGuMkidMxC/pM04lWEeraHUUmBw8l2grE=
|
||||
github.com/onsi/gomega v1.34.1 h1:EUMJIKUjM8sKjYbtxQI9A4z2o+rruxnzNvpknOXie6k=
|
||||
github.com/onsi/gomega v1.34.1/go.mod h1:kU1QgUvBDLXBJq618Xvm2LUX6rSAfRaFRTcdOeDLwwY=
|
||||
github.com/pjbgf/sha1cd v0.3.2 h1:a9wb0bp1oC2TGwStyn0Umc/IGKQnEgF0vVaZ8QF8eo4=
|
||||
github.com/pjbgf/sha1cd v0.3.2/go.mod h1:zQWigSxVmsHEZow5qaLtPYxpcKMMQpa09ixqBxuCS6A=
|
||||
github.com/pkg/errors v0.9.1 h1:FEBLx1zS214owpjy7qsBeixbURkuhQAwrK5UwLGTwt4=
|
||||
github.com/pkg/errors v0.9.1/go.mod h1:bwawxfHBFNV+L2hUp1rHADufV3IMtnDRdf1r5NINEl0=
|
||||
github.com/lucasb-eyer/go-colorful v1.2.0/go.mod h1:R4dSotOR9KMtayYi1e77YzuveK+i7ruzyGqttikkLy0=
|
||||
github.com/lucasb-eyer/go-colorful v1.3.0 h1:2/yBRLdWBZKrf7gB40FoiKfAWYQ0lqNcbuQwVHXptag=
|
||||
github.com/lucasb-eyer/go-colorful v1.3.0/go.mod h1:R4dSotOR9KMtayYi1e77YzuveK+i7ruzyGqttikkLy0=
|
||||
github.com/mattn/go-runewidth v0.0.16 h1:E5ScNMtiwvlvB5paMFdw9p4kSQzbXFikJ5SQO6TULQc=
|
||||
github.com/mattn/go-runewidth v0.0.16/go.mod h1:Jdepj2loyihRzMpdS35Xk/zdY8IAYHsh153qUoGf23w=
|
||||
github.com/mattn/go-sqlite3 v1.14.22 h1:2gZY6PC6kBnID23Tichd1K+Z0oS6nE/XwU+Vz/5o4kU=
|
||||
github.com/mattn/go-sqlite3 v1.14.22/go.mod h1:Uh1q+B4BYcTPb+yiD3kU8Ct7aC0hY9fxUwlHK0RXw+Y=
|
||||
github.com/pkg/diff v0.0.0-20210226163009-20ebb0f2a09e/go.mod h1:pJLUxLENpZxwdsKMEsNbx1VGcRFpLqf3715MtcvvzbA=
|
||||
github.com/pmezard/go-difflib v1.0.0 h1:4DBwDE0NGyQoBHbLQYPwSUPoCMWR5BEzIk/f1lZbAQM=
|
||||
github.com/pmezard/go-difflib v1.0.0/go.mod h1:iKH77koFhYxTK1pcRnkKkqfTogsbg7gZNVY4sRDYZ/4=
|
||||
github.com/rivo/uniseg v0.2.0/go.mod h1:J6wj4VEh+S6ZtnVlnTBMWIodfgj8LQOQFoIToxlJtxc=
|
||||
github.com/rivo/uniseg v0.4.3/go.mod h1:FN3SvrM+Zdj16jyLfmOkMNblXMcoc8DfTHruCPUcx88=
|
||||
github.com/rivo/uniseg v0.4.7 h1:WUdvkW8uEhrYfLC4ZzdpI2ztxP1I582+49Oc5Mq64VQ=
|
||||
github.com/rivo/uniseg v0.4.7/go.mod h1:FN3SvrM+Zdj16jyLfmOkMNblXMcoc8DfTHruCPUcx88=
|
||||
github.com/rogpeppe/go-internal v1.9.0/go.mod h1:WtVeX8xhTBvf0smdhujwtBcq4Qrzq/fJaraNFVN+nFs=
|
||||
github.com/rogpeppe/go-internal v1.14.1 h1:UQB4HGPB6osV0SQTLymcB4TgvyWu6ZyliaW0tI/otEQ=
|
||||
github.com/rogpeppe/go-internal v1.14.1/go.mod h1:MaRKkUm5W0goXpeCfT7UZI6fk/L7L7so1lCWt35ZSgc=
|
||||
github.com/sergi/go-diff v1.3.2-0.20230802210424-5b0b94c5c0d3 h1:n661drycOFuPLCN3Uc8sB6B/s6Z4t2xvBgU1htSHuq8=
|
||||
github.com/sergi/go-diff v1.3.2-0.20230802210424-5b0b94c5c0d3/go.mod h1:A0bzQcvG0E7Rwjx0REVgAGH58e96+X0MeOfepqsbeW4=
|
||||
github.com/sirupsen/logrus v1.7.0/go.mod h1:yWOB1SBYBC5VeMP7gHvWumXLIWorT60ONWic61uBYv0=
|
||||
github.com/skeema/knownhosts v1.3.1 h1:X2osQ+RAjK76shCbvhHHHVl3ZlgDm8apHEHFqRjnBY8=
|
||||
github.com/skeema/knownhosts v1.3.1/go.mod h1:r7KTdC8l4uxWRyK2TpQZ/1o5HaSzh06ePQNxPwTcfiY=
|
||||
github.com/stretchr/objx v0.1.0/go.mod h1:HFkY916IF+rwdDfMAkV7OtwuqBVzrE8GR6GFx+wExME=
|
||||
github.com/stretchr/testify v1.2.2/go.mod h1:a8OnRcib4nhh0OaRAV+Yts87kKdq0PP7pXfy6kDkUVs=
|
||||
github.com/stretchr/testify v1.4.0/go.mod h1:j7eGeouHqKxXV5pUuKE4zz7dFj8WfuZ+81PSLYec5m4=
|
||||
github.com/stretchr/testify v1.10.0 h1:Xv5erBjTwe/5IxqUQTdXv5kgmIvbHo3QQyRwhJsOfJA=
|
||||
github.com/stretchr/testify v1.10.0/go.mod h1:r2ic/lqez/lEtzL7wO/rwa5dbSLXVDPFyf8C91i36aY=
|
||||
github.com/xanzy/ssh-agent v0.3.3 h1:+/15pJfg/RsTxqYcX6fHqOXZwwMP+2VyYWJeWM2qQFM=
|
||||
github.com/xanzy/ssh-agent v0.3.3/go.mod h1:6dzNDKs0J9rVPHPhaGCukekBHKqfl+L3KghI1Bc68Uw=
|
||||
github.com/russross/blackfriday/v2 v2.1.0/go.mod h1:+Rmxgy9KzJVeS9/2gXHxylqXiyQDYRxCVz55jmeOWTM=
|
||||
github.com/spf13/cobra v1.10.1 h1:lJeBwCfmrnXthfAupyUTzJ/J4Nc1RsHC/mSRU2dll/s=
|
||||
github.com/spf13/cobra v1.10.1/go.mod h1:7SmJGaTHFVBY0jW4NXGluQoLvhqFQM+6XSKD+P4XaB0=
|
||||
github.com/spf13/pflag v1.0.9 h1:9exaQaMOCwffKiiiYk6/BndUBv+iRViNW+4lEMi0PvY=
|
||||
github.com/spf13/pflag v1.0.9/go.mod h1:McXfInJRrz4CZXVZOBLb0bTZqETkiAhM9Iw0y3An2Bg=
|
||||
github.com/stretchr/testify v1.11.1 h1:7s2iGBzp5EwR7/aIZr8ao5+dra3wiQyKjjFuvgVKu7U=
|
||||
github.com/stretchr/testify v1.11.1/go.mod h1:wZwfW3scLgRK+23gO65QZefKpKQRnfz6sD981Nm4B6U=
|
||||
github.com/theory/jsonpath v0.11.0 h1:IlzhI/Ui8nFu50SVpnyYHzZVvI0+etEoZLR5LsZJOVc=
|
||||
github.com/theory/jsonpath v0.11.0/go.mod h1:vl8nfJyq9MKMbcAiKv+7N9W3jDCH8qPr0mZoZj8wRk8=
|
||||
github.com/tidwall/gjson v1.18.0 h1:FIDeeyB800efLX89e5a8Y0BNH+LOngJyGrIWxG2FKQY=
|
||||
github.com/tidwall/gjson v1.18.0/go.mod h1:/wbyibRr2FHMks5tjHJ5F8dMZh3AcwJEMf5vlfC0lxk=
|
||||
github.com/tidwall/match v1.1.1 h1:+Ho715JplO36QYgwN9PGYNhgZvoUSc9X2c80KVTi+GA=
|
||||
github.com/tidwall/match v1.1.1/go.mod h1:eRSPERbgtNPcGhD8UCthc6PmLEQXEWd3PRB5JTxsfmM=
|
||||
github.com/tidwall/pretty v1.2.0 h1:RWIZEg2iJ8/g6fDDYzMpobmaoGh5OLl4AXtGUGPcqCs=
|
||||
github.com/tidwall/pretty v1.2.0/go.mod h1:ITEVvHYasfjBbM0u2Pg8T2nJnzm8xPwvNhhsoaGGjNU=
|
||||
github.com/twmb/murmur3 v1.1.8 h1:8Yt9taO/WN3l08xErzjeschgZU2QSrwm1kclYq+0aRg=
|
||||
github.com/twmb/murmur3 v1.1.8/go.mod h1:Qq/R7NUyOfr65zD+6Q5IHKsJLwP7exErjN6lyyq3OSQ=
|
||||
github.com/yuin/goldmark v1.4.13/go.mod h1:6yULJ656Px+3vBD8DxQVa3kxgyrAnzto9xy5taEt/CY=
|
||||
github.com/yuin/gopher-lua v1.1.1 h1:kYKnWBjvbNP4XLT3+bPEwAXJx262OhaHDWDVOPjL46M=
|
||||
github.com/yuin/gopher-lua v1.1.1/go.mod h1:GBR0iDaNXjAgGg9zfCvksxSRnQx76gclCIb7kdAd1Pw=
|
||||
golang.org/x/crypto v0.0.0-20220622213112-05595931fe9d/go.mod h1:IxCIyHEi3zRg3s0A5j5BB6A9Jmi73HwBIUl50j+osU4=
|
||||
golang.org/x/crypto v0.35.0 h1:b15kiHdrGCHrP6LvwaQ3c03kgNhhiMgvlhxHQhmg2Xs=
|
||||
golang.org/x/crypto v0.35.0/go.mod h1:dy7dXNW32cAb/6/PRuTNsix8T+vJAqvuIy5Bli/x0YQ=
|
||||
golang.org/x/exp v0.0.0-20240719175910-8a7402abbf56 h1:2dVuKD2vS7b0QIHQbpyTISPd0LeHDbnYEryqj5Q1ug8=
|
||||
golang.org/x/exp v0.0.0-20240719175910-8a7402abbf56/go.mod h1:M4RDyNAINzryxdtnbRXRL/OHtkFuWGRjvuhBJpk2IlY=
|
||||
golang.org/x/net v0.0.0-20211112202133-69e39bad7dc2/go.mod h1:9nx3DQGgdP8bBQD5qxJ1jj9UTztislL4KSBs9R2vV5Y=
|
||||
golang.org/x/net v0.35.0 h1:T5GQRQb2y08kTAByq9L4/bz8cipCdA8FbRTXewonqY8=
|
||||
golang.org/x/net v0.35.0/go.mod h1:EglIi67kWsHKlRzzVMUD93VMSWGFOMSZgxFjparz1Qk=
|
||||
golang.org/x/sys v0.0.0-20191026070338-33540a1f6037/go.mod h1:h1NjWce9XRLGQEsW7wpKNCjG9DtNlClVuFLEZdDNbEs=
|
||||
golang.design/x/clipboard v0.7.1 h1:OEG3CmcYRBNnRwpDp7+uWLiZi3hrMRJpE9JkkkYtz2c=
|
||||
golang.design/x/clipboard v0.7.1/go.mod h1:i5SiIqj0wLFw9P/1D7vfILFK0KHMk7ydE72HRrUIgkg=
|
||||
golang.org/x/crypto v0.0.0-20190308221718-c2843e01d9a2/go.mod h1:djNgcEr1/C05ACkg1iLfiJU5Ep61QUkGW8qpdssI0+w=
|
||||
golang.org/x/crypto v0.0.0-20210921155107-089bfa567519/go.mod h1:GvvjBRRGRdwPK5ydBHafDWAxML/pGHZbMvKqRZ5+Abc=
|
||||
golang.org/x/crypto v0.13.0/go.mod h1:y6Z2r+Rw4iayiXXAIxJIDAJ1zMW4yaTpebo8fPOliYc=
|
||||
golang.org/x/crypto v0.19.0/go.mod h1:Iy9bg/ha4yyC70EfRS8jz+B6ybOBKMaSxLj6P6oBDfU=
|
||||
golang.org/x/crypto v0.23.0/go.mod h1:CKFgDieR+mRhux2Lsu27y0fO304Db0wZe70UKqHu0v8=
|
||||
golang.org/x/exp/shiny v0.0.0-20250606033433-dcc06ee1d476 h1:Wdx0vgH5Wgsw+lF//LJKmWOJBLWX6nprsMqnf99rYDE=
|
||||
golang.org/x/exp/shiny v0.0.0-20250606033433-dcc06ee1d476/go.mod h1:ygj7T6vSGhhm/9yTpOQQNvuAUFziTH7RUiH74EoE2C8=
|
||||
golang.org/x/image v0.28.0 h1:gdem5JW1OLS4FbkWgLO+7ZeFzYtL3xClb97GaUzYMFE=
|
||||
golang.org/x/image v0.28.0/go.mod h1:GUJYXtnGKEUgggyzh+Vxt+AviiCcyiwpsl8iQ8MvwGY=
|
||||
golang.org/x/mobile v0.0.0-20250606033058-a2a15c67f36f h1:/n+PL2HlfqeSiDCuhdBbRNlGS/g2fM4OHufalHaTVG8=
|
||||
golang.org/x/mobile v0.0.0-20250606033058-a2a15c67f36f/go.mod h1:ESkJ836Z6LpG6mTVAhA48LpfW/8fNR0ifStlH2axyfg=
|
||||
golang.org/x/mod v0.6.0-dev.0.20220419223038-86c51ed26bb4/go.mod h1:jJ57K6gSWd91VN4djpZkiMVwK6gcyfeH4XE8wZrZaV4=
|
||||
golang.org/x/mod v0.8.0/go.mod h1:iBbtSCu2XBx23ZKBPSOrRkjjQPZFPuis4dIYUhu/chs=
|
||||
golang.org/x/mod v0.12.0/go.mod h1:iBbtSCu2XBx23ZKBPSOrRkjjQPZFPuis4dIYUhu/chs=
|
||||
golang.org/x/mod v0.15.0/go.mod h1:hTbmBsO62+eylJbnUtE2MGJUyE7QWk4xUqPFrRgJ+7c=
|
||||
golang.org/x/mod v0.17.0/go.mod h1:hTbmBsO62+eylJbnUtE2MGJUyE7QWk4xUqPFrRgJ+7c=
|
||||
golang.org/x/mod v0.29.0 h1:HV8lRxZC4l2cr3Zq1LvtOsi/ThTgWnUk/y64QSs8GwA=
|
||||
golang.org/x/mod v0.29.0/go.mod h1:NyhrlYXJ2H4eJiRy/WDBO6HMqZQ6q9nk4JzS3NuCK+w=
|
||||
golang.org/x/net v0.0.0-20190620200207-3b0461eec859/go.mod h1:z5CRVTTTmAJ677TzLLGU+0bjPO0LkuOLi4/5GtJWs/s=
|
||||
golang.org/x/net v0.0.0-20210226172049-e18ecbb05110/go.mod h1:m0MpNAwzfU5UDzcl9v0D8zg8gWTRqZa9RBIspLL5mdg=
|
||||
golang.org/x/net v0.0.0-20220722155237-a158d28d115b/go.mod h1:XRhObCWvk6IyKnWLug+ECip1KBveYUHfp+8e9klMJ9c=
|
||||
golang.org/x/net v0.6.0/go.mod h1:2Tu9+aMcznHK/AK1HMvgo6xiTLG5rD5rZLDS+rp2Bjs=
|
||||
golang.org/x/net v0.10.0/go.mod h1:0qNGK6F8kojg2nk9dLZ2mShWaEBan6FAoqfSigmmuDg=
|
||||
golang.org/x/net v0.15.0/go.mod h1:idbUs1IY1+zTqbi8yxTbhexhEEk5ur9LInksu6HrEpk=
|
||||
golang.org/x/net v0.21.0/go.mod h1:bIjVDfnllIU7BJ2DNgfnXvpSvtn8VRwhlsaeUTyUS44=
|
||||
golang.org/x/net v0.25.0/go.mod h1:JkAGAh7GEvH74S6FOH42FLoXpXbE/aqXSrIQjXgsiwM=
|
||||
golang.org/x/sync v0.0.0-20190423024810-112230192c58/go.mod h1:RxMgew5VJxzue5/jJTE5uejpjVlOe/izrB70Jof72aM=
|
||||
golang.org/x/sync v0.0.0-20220722155255-886fb9371eb4/go.mod h1:RxMgew5VJxzue5/jJTE5uejpjVlOe/izrB70Jof72aM=
|
||||
golang.org/x/sync v0.1.0/go.mod h1:RxMgew5VJxzue5/jJTE5uejpjVlOe/izrB70Jof72aM=
|
||||
golang.org/x/sync v0.3.0/go.mod h1:FU7BRWz2tNW+3quACPkgCx/L+uEAv1htQ0V83Z9Rj+Y=
|
||||
golang.org/x/sync v0.6.0/go.mod h1:Czt+wKu1gCyEFDUtn0jG5QVvpJ6rzVqr5aXyt9drQfk=
|
||||
golang.org/x/sync v0.7.0/go.mod h1:Czt+wKu1gCyEFDUtn0jG5QVvpJ6rzVqr5aXyt9drQfk=
|
||||
golang.org/x/sync v0.10.0/go.mod h1:Czt+wKu1gCyEFDUtn0jG5QVvpJ6rzVqr5aXyt9drQfk=
|
||||
golang.org/x/sync v0.18.0 h1:kr88TuHDroi+UVf+0hZnirlk8o8T+4MrK6mr60WkH/I=
|
||||
golang.org/x/sync v0.18.0/go.mod h1:9KTHXmSnoGruLpwFjVSX0lNNA75CykiMECbovNTZqGI=
|
||||
golang.org/x/sys v0.0.0-20190215142949-d0b11bdaac8a/go.mod h1:STP8DvDyc/dI5b8T5hshtkjS+E42TnysNCUPdjciGhY=
|
||||
golang.org/x/sys v0.0.0-20201119102817-f84b799fce68/go.mod h1:h1NjWce9XRLGQEsW7wpKNCjG9DtNlClVuFLEZdDNbEs=
|
||||
golang.org/x/sys v0.0.0-20210124154548-22da62e12c0c/go.mod h1:h1NjWce9XRLGQEsW7wpKNCjG9DtNlClVuFLEZdDNbEs=
|
||||
golang.org/x/sys v0.0.0-20210423082822-04245dca01da/go.mod h1:h1NjWce9XRLGQEsW7wpKNCjG9DtNlClVuFLEZdDNbEs=
|
||||
golang.org/x/sys v0.0.0-20210615035016-665e8c7367d1/go.mod h1:oPkhp1MJrh7nUepCBck5+mAzfO9JrbApNNgaTdGDITg=
|
||||
golang.org/x/sys v0.0.0-20220715151400-c0bba94af5f8/go.mod h1:oPkhp1MJrh7nUepCBck5+mAzfO9JrbApNNgaTdGDITg=
|
||||
golang.org/x/sys v0.30.0 h1:QjkSwP/36a20jFYWkSue1YwXzLmsV5Gfq7Eiy72C1uc=
|
||||
golang.org/x/sys v0.30.0/go.mod h1:/VUhepiaJMQUp4+oa/7Zr1D23ma6VTLIYjOOTFZPUcA=
|
||||
golang.org/x/sys v0.0.0-20220520151302-bc2c85ada10a/go.mod h1:oPkhp1MJrh7nUepCBck5+mAzfO9JrbApNNgaTdGDITg=
|
||||
golang.org/x/sys v0.0.0-20220722155257-8c9f86f7a55f/go.mod h1:oPkhp1MJrh7nUepCBck5+mAzfO9JrbApNNgaTdGDITg=
|
||||
golang.org/x/sys v0.5.0/go.mod h1:oPkhp1MJrh7nUepCBck5+mAzfO9JrbApNNgaTdGDITg=
|
||||
golang.org/x/sys v0.8.0/go.mod h1:oPkhp1MJrh7nUepCBck5+mAzfO9JrbApNNgaTdGDITg=
|
||||
golang.org/x/sys v0.12.0/go.mod h1:oPkhp1MJrh7nUepCBck5+mAzfO9JrbApNNgaTdGDITg=
|
||||
golang.org/x/sys v0.17.0/go.mod h1:/VUhepiaJMQUp4+oa/7Zr1D23ma6VTLIYjOOTFZPUcA=
|
||||
golang.org/x/sys v0.20.0/go.mod h1:/VUhepiaJMQUp4+oa/7Zr1D23ma6VTLIYjOOTFZPUcA=
|
||||
golang.org/x/sys v0.29.0/go.mod h1:/VUhepiaJMQUp4+oa/7Zr1D23ma6VTLIYjOOTFZPUcA=
|
||||
golang.org/x/sys v0.38.0 h1:3yZWxaJjBmCWXqhN1qh02AkOnCQ1poK6oF+a7xWL6Gc=
|
||||
golang.org/x/sys v0.38.0/go.mod h1:OgkHotnGiDImocRcuBABYBEXf8A9a87e/uXjp9XT3ks=
|
||||
golang.org/x/telemetry v0.0.0-20240228155512-f48c80bd79b2/go.mod h1:TeRTkGYfJXctD9OcfyVLyj2J3IxLnKwHJR8f4D8a3YE=
|
||||
golang.org/x/term v0.0.0-20201126162022-7de9c90e9dd1/go.mod h1:bj7SfCRtBDWHUb9snDiAeCFNEtKQo2Wmx5Cou7ajbmo=
|
||||
golang.org/x/term v0.29.0 h1:L6pJp37ocefwRRtYPKSWOWzOtWSxVajvz2ldH/xi3iU=
|
||||
golang.org/x/term v0.29.0/go.mod h1:6bl4lRlvVuDgSf3179VpIxBF0o10JUpXWOnI7nErv7s=
|
||||
golang.org/x/text v0.3.6/go.mod h1:5Zoc/QRtKVWzQhOtBMvqHzDpF6irO9z98xDceosuGiQ=
|
||||
golang.org/x/text v0.22.0 h1:bofq7m3/HAFvbF51jz3Q9wLg3jkvSPuiZu/pD1XwgtM=
|
||||
golang.org/x/text v0.22.0/go.mod h1:YRoo4H8PVmsu+E3Ou7cqLVH8oXWIHVoX0jqUWALQhfY=
|
||||
golang.org/x/term v0.0.0-20210927222741-03fcf44c2211/go.mod h1:jbD1KX2456YbFQfuXm/mYQcufACuNUgVhRMnK/tPxf8=
|
||||
golang.org/x/term v0.5.0/go.mod h1:jMB1sMXY+tzblOD4FWmEbocvup2/aLOaQEp7JmGp78k=
|
||||
golang.org/x/term v0.8.0/go.mod h1:xPskH00ivmX89bAKVGSKKtLOWNx2+17Eiy94tnKShWo=
|
||||
golang.org/x/term v0.12.0/go.mod h1:owVbMEjm3cBLCHdkQu9b1opXd4ETQWc3BhuQGKgXgvU=
|
||||
golang.org/x/term v0.17.0/go.mod h1:lLRBjIVuehSbZlaOtGMbcMncT+aqLLLmKrsjNrUguwk=
|
||||
golang.org/x/term v0.20.0/go.mod h1:8UkIAJTvZgivsXaD6/pH6U9ecQzZ45awqEOzuCvwpFY=
|
||||
golang.org/x/term v0.28.0/go.mod h1:Sw/lC2IAUZ92udQNf3WodGtn4k/XoLyZoh8v/8uiwek=
|
||||
golang.org/x/term v0.37.0 h1:8EGAD0qCmHYZg6J17DvsMy9/wJ7/D/4pV/wfnld5lTU=
|
||||
golang.org/x/term v0.37.0/go.mod h1:5pB4lxRNYYVZuTLmy8oR2BH8dflOR+IbTYFD8fi3254=
|
||||
golang.org/x/text v0.3.0/go.mod h1:NqM8EUOU14njkJ3fqMW+pc6Ldnwhi/IjpwHt7yyuwOQ=
|
||||
golang.org/x/text v0.3.3/go.mod h1:5Zoc/QRtKVWzQhOtBMvqHzDpF6irO9z98xDceosuGiQ=
|
||||
golang.org/x/text v0.3.7/go.mod h1:u+2+/6zg+i71rQMx5EYifcz6MCKuco9NR6JIITiCfzQ=
|
||||
golang.org/x/text v0.7.0/go.mod h1:mrYo+phRRbMaCq/xk9113O4dZlRixOauAjOtrjsXDZ8=
|
||||
golang.org/x/text v0.9.0/go.mod h1:e1OnstbJyHTd6l/uOt8jFFHp6TRDWZR/bV3emEE/zU8=
|
||||
golang.org/x/text v0.13.0/go.mod h1:TvPlkZtksWOMsz7fbANvkp4WM8x/WCo/om8BMLbz+aE=
|
||||
golang.org/x/text v0.14.0/go.mod h1:18ZOQIKpY8NJVqYksKHtTdi31H5itFRjB5/qKTNYzSU=
|
||||
golang.org/x/text v0.15.0/go.mod h1:18ZOQIKpY8NJVqYksKHtTdi31H5itFRjB5/qKTNYzSU=
|
||||
golang.org/x/text v0.21.0/go.mod h1:4IBbMaMmOPCJ8SecivzSH54+73PCFmPWxNTLm+vZkEQ=
|
||||
golang.org/x/text v0.31.0 h1:aC8ghyu4JhP8VojJ2lEHBnochRno1sgL6nEi9WGFGMM=
|
||||
golang.org/x/text v0.31.0/go.mod h1:tKRAlv61yKIjGGHX/4tP1LTbc13YSec1pxVEWXzfoeM=
|
||||
golang.org/x/time v0.12.0 h1:ScB/8o8olJvc+CQPWrK3fPZNfh7qgwCrY0zJmoEQLSE=
|
||||
golang.org/x/time v0.12.0/go.mod h1:CDIdPxbZBQxdj6cxyCIdrNogrJKMJ7pr37NYpMcMDSg=
|
||||
golang.org/x/tools v0.0.0-20180917221912-90fa682c2a6e/go.mod h1:n7NCudcB/nEzxVGmLbDWY5pfWTLqBcC2KZ6jyYvM4mQ=
|
||||
golang.org/x/tools v0.0.0-20191119224855-298f0cb1881e/go.mod h1:b+2E5dAYhXwXZwtnZ6UAqBI28+e2cm9otk0dWdXHAEo=
|
||||
golang.org/x/tools v0.1.12/go.mod h1:hNGJHUnrk76NpqgfD5Aqm5Crs+Hm0VOH/i9J2+nxYbc=
|
||||
golang.org/x/tools v0.6.0/go.mod h1:Xwgl3UAJ/d3gWutnCtw505GrjyAbvKui8lOU390QaIU=
|
||||
golang.org/x/tools v0.13.0/go.mod h1:HvlwmtVNQAhOuCjW7xxvovg8wbNq7LwfXh/k7wXUl58=
|
||||
golang.org/x/tools v0.21.1-0.20240508182429-e35e4ccd0d2d/go.mod h1:aiJjzUbINMkxbQROHiO6hDPo2LHcIPhhQsa9DLh0yGk=
|
||||
golang.org/x/tools v0.38.0 h1:Hx2Xv8hISq8Lm16jvBZ2VQf+RLmbd7wVUsALibYI/IQ=
|
||||
golang.org/x/tools v0.38.0/go.mod h1:yEsQ/d/YK8cjh0L6rZlY8tgtlKiBNTL14pGDJPJpYQs=
|
||||
golang.org/x/xerrors v0.0.0-20190717185122-a985d3407aa7/go.mod h1:I/5z698sn9Ka8TeJc9MKroUUfqBBauWjQqLJ2OPfmY0=
|
||||
gopkg.in/check.v1 v0.0.0-20161208181325-20d25e280405/go.mod h1:Co6ibVJAznAaIkqp8huTwlJQCZ016jof/cbN4VW5Yz0=
|
||||
gopkg.in/check.v1 v1.0.0-20190902080502-41f04d3bba15/go.mod h1:Co6ibVJAznAaIkqp8huTwlJQCZ016jof/cbN4VW5Yz0=
|
||||
gopkg.in/check.v1 v1.0.0-20201130134442-10cb98267c6c h1:Hei/4ADfdWqJk1ZMxUNpqntNwaWcugrBjAiHlqqRiVk=
|
||||
gopkg.in/check.v1 v1.0.0-20201130134442-10cb98267c6c/go.mod h1:JHkPIbrfpd72SG/EVd6muEfDQjcINNoR0C8j2r3qZ4Q=
|
||||
gopkg.in/warnings.v0 v0.1.2 h1:wFXVbFY8DY5/xOe1ECiWdKCzZlxgshcYVNkBHstARME=
|
||||
gopkg.in/warnings.v0 v0.1.2/go.mod h1:jksf8JmL6Qr/oQM2OXTHunEvvTAsrWBLb6OOjuVWRNI=
|
||||
gopkg.in/yaml.v2 v2.2.2/go.mod h1:hI93XBmqTisBFMUTm0b8Fm+jr3Dg1NNxqwp+5A1VGuI=
|
||||
gopkg.in/yaml.v2 v2.4.0/go.mod h1:RDklbk79AGWmwhnvt/jBztapEOGDOx6ZbXqjP6csGnQ=
|
||||
gopkg.in/yaml.v3 v3.0.1 h1:fxVm/GzAzEWqLHuvctI91KS9hhNmmWOoWu0XTYJS7CA=
|
||||
gopkg.in/yaml.v3 v3.0.1/go.mod h1:K4uyk7z7BCEPqu6E+C64Yfv1cQ7kz7rIZviUmN+EgEM=
|
||||
gorm.io/driver/sqlite v1.6.0 h1:WHRRrIiulaPiPFmDcod6prc4l2VGVWHz80KspNsxSfQ=
|
||||
gorm.io/driver/sqlite v1.6.0/go.mod h1:AO9V1qIQddBESngQUKWL9yoH93HIeA1X6V633rBwyT8=
|
||||
gorm.io/gorm v1.30.0 h1:qbT5aPv1UH8gI99OsRlvDToLxW5zR7FzS9acZDOZcgs=
|
||||
gorm.io/gorm v1.30.0/go.mod h1:8Z33v652h4//uMA76KjeDH8mJXPm1QNCYrMeatR0DOE=
|
||||
mvdan.cc/gofumpt v0.4.0 h1:JVf4NN1mIpHogBj7ABpgOyZc65/UUOkKQFkoURsz4MM=
|
||||
mvdan.cc/gofumpt v0.4.0/go.mod h1:PljLOHDeZqgS8opHRKLzp2It2VBuSdteAgqUfzMTxlQ=
|
||||
@@ -0,0 +1,20 @@
|
||||
package chef
|
||||
|
||||
import (
|
||||
"fmt"
|
||||
|
||||
"cook/utils"
|
||||
|
||||
logger "git.site.quack-lab.dev/dave/cylogger/v3"
|
||||
)
|
||||
|
||||
func RunClearGlobCache() error {
|
||||
log := logger.With("cmd", "clear")
|
||||
log.Info("Clearing glob cache")
|
||||
err := withSnapshotDB(func(db utils.DB) error { return db.ClearGlobCache() })
|
||||
if err != nil {
|
||||
return fmt.Errorf("failed to clear glob cache: %w", err)
|
||||
}
|
||||
log.Info("Cleared glob cache")
|
||||
return nil
|
||||
}
|
||||
@@ -0,0 +1,117 @@
|
||||
package chef
|
||||
|
||||
import (
|
||||
"log/slog"
|
||||
"sync/atomic"
|
||||
|
||||
"cook/utils"
|
||||
|
||||
logger "git.site.quack-lab.dev/dave/cylogger/v3"
|
||||
)
|
||||
|
||||
func loggerForCommand(commandName string, commandLoggers map[string]*slog.Logger) *slog.Logger {
|
||||
cmdLogger := slog.Default()
|
||||
if cmdLog, ok := commandLoggers[commandName]; ok {
|
||||
cmdLogger = cmdLog
|
||||
}
|
||||
return cmdLogger
|
||||
}
|
||||
|
||||
func addCommandModificationCount(commandName string, delta int) {
|
||||
if delta <= 0 {
|
||||
return
|
||||
}
|
||||
count, ok := stats.ModificationsPerCommand.Load(commandName)
|
||||
if !ok {
|
||||
count = 0
|
||||
}
|
||||
stats.ModificationsPerCommand.Store(commandName, count.(int)+delta)
|
||||
}
|
||||
|
||||
func commandSeenPredicateGate(command utils.ModifyCommand, commandName string, fileDataStr string, log *slog.Logger, isolate bool) bool {
|
||||
incrementCommandCounter(commandName, func(cs *CommandStats) {
|
||||
atomic.AddInt64(&cs.FilesSeen, 1)
|
||||
})
|
||||
matches, predErr := commandPredicateMatches(command, fileDataStr)
|
||||
if predErr != nil {
|
||||
if isolate {
|
||||
log.Error("Predicate error for isolate command", "err", predErr)
|
||||
} else {
|
||||
log.Error("Predicate error for command", "cmd", command.Name, "err", predErr)
|
||||
}
|
||||
incrementCommandError(commandName, predErr)
|
||||
return false
|
||||
}
|
||||
if !matches {
|
||||
incrementCommandCounter(commandName, func(cs *CommandStats) {
|
||||
atomic.AddInt64(&cs.FilesPredicateSkipped, 1)
|
||||
})
|
||||
return false
|
||||
}
|
||||
return true
|
||||
}
|
||||
|
||||
type otherCommandRunner struct {
|
||||
file string
|
||||
fileDataStr string
|
||||
commandLoggers map[string]*slog.Logger
|
||||
log *slog.Logger
|
||||
jsonData interface{}
|
||||
jsonParsed bool
|
||||
structuredModified bool
|
||||
xmlCommands []utils.ModifyCommand
|
||||
xmlCommandNames []string
|
||||
regexCommands []utils.ModifyCommand
|
||||
commands []utils.ReplaceCommand
|
||||
numCommandsConsidered int
|
||||
regexLogNames []string
|
||||
regexLogSeen map[string]struct{}
|
||||
}
|
||||
|
||||
func RunOtherCommands(file string, fileDataStr string, association utils.FileCommandAssociation, commandLoggers map[string]*slog.Logger) (string, error) {
|
||||
log := logger.With("func", "RunOtherCommands", "target", file)
|
||||
log.Debug("Running other commands for file")
|
||||
|
||||
r := &otherCommandRunner{
|
||||
file: file,
|
||||
fileDataStr: fileDataStr,
|
||||
commandLoggers: commandLoggers,
|
||||
log: log,
|
||||
regexLogSeen: make(map[string]struct{}),
|
||||
}
|
||||
r.runStructuredCommands(association.Commands)
|
||||
r.runXMLQueued()
|
||||
r.runRegexCommands(r.regexCommands)
|
||||
|
||||
log.Debug("Aggregated modifications", "count", len(r.commands), "runs", r.numCommandsConsidered)
|
||||
|
||||
if len(r.commands) == 0 {
|
||||
if r.structuredModified {
|
||||
return r.fileDataStr, nil
|
||||
}
|
||||
log.Debug("No modifications produced by any command for file", "commands_considered", r.numCommandsConsidered)
|
||||
return r.fileDataStr, ErrNothingToDo
|
||||
}
|
||||
log.Debug("Executing modifications for file", "count", len(r.commands))
|
||||
|
||||
var count int
|
||||
r.fileDataStr, count = utils.ExecuteModificationsForFile(file, r.regexLogNames, r.commands, r.fileDataStr)
|
||||
|
||||
atomic.AddInt64(&stats.TotalModifications, int64(count))
|
||||
|
||||
log.Info("Executed modifications for file", "count", count)
|
||||
return r.fileDataStr, nil
|
||||
}
|
||||
|
||||
func uniqueCommandNames(commands []utils.ModifyCommand) []string {
|
||||
names := make([]string, 0, len(commands))
|
||||
seen := make(map[string]struct{}, len(commands))
|
||||
for _, c := range commands {
|
||||
n := commandNameForStats(c)
|
||||
if _, dup := seen[n]; !dup {
|
||||
seen[n] = struct{}{}
|
||||
names = append(names, n)
|
||||
}
|
||||
}
|
||||
return names
|
||||
}
|
||||
@@ -0,0 +1,156 @@
|
||||
package chef
|
||||
|
||||
import (
|
||||
"log/slog"
|
||||
"sync/atomic"
|
||||
|
||||
"cook/processor"
|
||||
"cook/utils"
|
||||
|
||||
logger "git.site.quack-lab.dev/dave/cylogger/v3"
|
||||
)
|
||||
|
||||
type isolateCommandRunner struct {
|
||||
file string
|
||||
fileDataStr string
|
||||
log *slog.Logger
|
||||
anythingDone bool
|
||||
}
|
||||
|
||||
func RunIsolateCommands(association utils.FileCommandAssociation, file string, fileDataStr string) (string, error) {
|
||||
log := logger.With("func", "RunIsolateCommands", "target", file)
|
||||
log.Debug("Running isolate commands for file")
|
||||
|
||||
runner := &isolateCommandRunner{
|
||||
file: file,
|
||||
fileDataStr: fileDataStr,
|
||||
log: log,
|
||||
}
|
||||
|
||||
for _, isolateCommand := range association.IsolateCommands {
|
||||
cmdLog := log.With("cmd", isolateCommand.Name, "src", isolateCommand.SourceFile)
|
||||
commandName := commandNameForStats(isolateCommand)
|
||||
if !commandSeenPredicateGate(isolateCommand, commandName, runner.fileDataStr, cmdLog, true) {
|
||||
continue
|
||||
}
|
||||
runner.runIsolate(isolateCommand, commandName, cmdLog)
|
||||
}
|
||||
if !runner.anythingDone {
|
||||
log.Debug("No isolate commands produced modifications for file")
|
||||
return fileDataStr, ErrNothingToDo
|
||||
}
|
||||
return runner.fileDataStr, nil
|
||||
}
|
||||
|
||||
func (r *isolateCommandRunner) runIsolate(command utils.ModifyCommand, commandName string, cmdLog *slog.Logger) {
|
||||
switch {
|
||||
case command.XML:
|
||||
r.runIsolateXML(command, commandName, cmdLog)
|
||||
case command.Raw:
|
||||
r.runIsolateRaw(command, commandName)
|
||||
case command.JSON:
|
||||
r.runIsolateJSON(command, commandName, cmdLog)
|
||||
default:
|
||||
r.runIsolateRegex(command, commandName, cmdLog)
|
||||
}
|
||||
}
|
||||
|
||||
func (r *isolateCommandRunner) runIsolateXML(command utils.ModifyCommand, commandName string, cmdLog *slog.Logger) {
|
||||
r.runIsolateStructured(command, commandName, cmdLog, "XML", processor.ProcessXML)
|
||||
}
|
||||
|
||||
func (r *isolateCommandRunner) runIsolateJSON(command utils.ModifyCommand, commandName string, cmdLog *slog.Logger) {
|
||||
r.runIsolateStructured(command, commandName, cmdLog, "JSON", processor.ProcessJSON)
|
||||
}
|
||||
|
||||
func (r *isolateCommandRunner) runIsolateRaw(command utils.ModifyCommand, commandName string) {
|
||||
modifications, err := processor.ProcessRaw(r.fileDataStr, command, r.file)
|
||||
if err != nil {
|
||||
incrementCommandError(commandName, err)
|
||||
return
|
||||
}
|
||||
if len(modifications) > 0 {
|
||||
r.fileDataStr, _ = utils.ExecuteModificationsForFile(r.file, []string{commandName}, modifications, r.fileDataStr)
|
||||
r.anythingDone = true
|
||||
}
|
||||
}
|
||||
|
||||
func (r *isolateCommandRunner) runIsolateStructured(command utils.ModifyCommand, commandName string, cmdLog *slog.Logger, kind string, process func(string, utils.ModifyCommand, string) ([]utils.ReplaceCommand, error)) {
|
||||
cmdLog.Debug("Begin processing file with " + kind + " isolate command")
|
||||
modifications, err := process(r.fileDataStr, command, r.file)
|
||||
if err != nil {
|
||||
cmdLog.Error("Failed to process file with "+kind+" isolate command", "err", err)
|
||||
incrementCommandError(commandName, err)
|
||||
return
|
||||
}
|
||||
|
||||
if len(modifications) == 0 {
|
||||
cmdLog.Warn(kind+" isolate command produced no modifications", "file", r.file)
|
||||
incrementCommandCounter(commandName, func(cs *CommandStats) {
|
||||
atomic.AddInt64(&cs.FilesNoMatch, 1)
|
||||
})
|
||||
return
|
||||
}
|
||||
incrementCommandCounter(commandName, func(cs *CommandStats) {
|
||||
atomic.AddInt64(&cs.FilesModified, 1)
|
||||
atomic.AddInt64(&cs.ModificationsTotal, int64(len(modifications)))
|
||||
})
|
||||
r.anythingDone = true
|
||||
|
||||
cmdLog.Debug("Executing "+kind+" isolate modifications", "count", len(modifications))
|
||||
var count int
|
||||
r.fileDataStr, count = utils.ExecuteModificationsForFile(r.file, []string{commandName}, modifications, r.fileDataStr)
|
||||
|
||||
atomic.AddInt64(&stats.TotalModifications, int64(count))
|
||||
addCommandModificationCount(command.Name, len(modifications))
|
||||
|
||||
cmdLog.Info("Executed "+kind+" isolate modifications", "count", count)
|
||||
}
|
||||
|
||||
func (r *isolateCommandRunner) runIsolateRegex(command utils.ModifyCommand, commandName string, cmdLog *slog.Logger) {
|
||||
patterns := command.Regexes
|
||||
if len(patterns) == 0 {
|
||||
patterns = []string{command.Regex}
|
||||
}
|
||||
totalModsForCommand := 0
|
||||
hadError := false
|
||||
for idx, pattern := range patterns {
|
||||
tmpCmd := command
|
||||
tmpCmd.Regex = pattern
|
||||
cmdLog := r.log.With("cmd", command.Name, "patternIdx", idx+1, "patternTotal", len(patterns))
|
||||
cmdLog.Debug("Begin processing file with isolate command")
|
||||
modifications, err := processor.ProcessRegex(r.fileDataStr, tmpCmd, r.file)
|
||||
if err != nil {
|
||||
r.log.Error("Failed to process file with isolate command", "cmd", command.Name, "err", err)
|
||||
incrementCommandError(commandName, err)
|
||||
hadError = true
|
||||
continue
|
||||
}
|
||||
|
||||
if len(modifications) == 0 {
|
||||
cmdLog.Warn("Regex isolate command produced no modifications", "regex", pattern, "file", r.file)
|
||||
continue
|
||||
}
|
||||
totalModsForCommand += len(modifications)
|
||||
r.anythingDone = true
|
||||
|
||||
cmdLog.Debug("Executing isolate modifications", "count", len(modifications))
|
||||
var count int
|
||||
r.fileDataStr, count = utils.ExecuteModificationsForFile(r.file, []string{commandName}, modifications, r.fileDataStr)
|
||||
|
||||
atomic.AddInt64(&stats.TotalModifications, int64(count))
|
||||
addCommandModificationCount(command.Name, len(modifications))
|
||||
|
||||
cmdLog.Info("Executed isolate modifications", "count", count)
|
||||
}
|
||||
if totalModsForCommand > 0 {
|
||||
incrementCommandCounter(commandName, func(cs *CommandStats) {
|
||||
atomic.AddInt64(&cs.FilesModified, 1)
|
||||
atomic.AddInt64(&cs.ModificationsTotal, int64(totalModsForCommand))
|
||||
})
|
||||
} else if !hadError {
|
||||
incrementCommandCounter(commandName, func(cs *CommandStats) {
|
||||
atomic.AddInt64(&cs.FilesNoMatch, 1)
|
||||
})
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,70 @@
|
||||
package chef
|
||||
|
||||
import (
|
||||
"log/slog"
|
||||
"sync/atomic"
|
||||
|
||||
"cook/processor"
|
||||
"cook/utils"
|
||||
)
|
||||
|
||||
func (r *otherCommandRunner) runRegexCommands(commands []utils.ModifyCommand) {
|
||||
for _, command := range commands {
|
||||
commandName := commandNameForStats(command)
|
||||
if !commandSeenPredicateGate(command, commandName, r.fileDataStr, r.log, false) {
|
||||
continue
|
||||
}
|
||||
|
||||
cmdLogger := loggerForCommand(command.Name, r.commandLoggers)
|
||||
|
||||
totalModsForCommand, hadError := r.runCommandPatterns(command, commandName, cmdLogger)
|
||||
if totalModsForCommand > 0 {
|
||||
incrementCommandCounter(commandName, func(cs *CommandStats) {
|
||||
atomic.AddInt64(&cs.FilesModified, 1)
|
||||
atomic.AddInt64(&cs.ModificationsTotal, int64(totalModsForCommand))
|
||||
})
|
||||
} else if !hadError {
|
||||
incrementCommandCounter(commandName, func(cs *CommandStats) {
|
||||
atomic.AddInt64(&cs.FilesNoMatch, 1)
|
||||
})
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
func (r *otherCommandRunner) runCommandPatterns(command utils.ModifyCommand, commandName string, cmdLogger *slog.Logger) (int, bool) {
|
||||
patterns := command.Regexes
|
||||
if len(patterns) == 0 {
|
||||
patterns = []string{command.Regex}
|
||||
}
|
||||
totalModsForCommand := 0
|
||||
hadError := false
|
||||
for idx, pattern := range patterns {
|
||||
tmpCmd := command
|
||||
tmpCmd.Regex = pattern
|
||||
cmdLog := cmdLogger.With("cmd", command.Name, "patternIdx", idx+1, "patternTotal", len(patterns))
|
||||
cmdLog.Debug("Begin processing file with command")
|
||||
r.numCommandsConsidered++
|
||||
newModifications, err := processor.ProcessRegex(r.fileDataStr, tmpCmd, r.file)
|
||||
if err != nil {
|
||||
r.log.Error("Failed to process file with command", "cmd", command.Name, "err", err)
|
||||
incrementCommandError(commandName, err)
|
||||
hadError = true
|
||||
continue
|
||||
}
|
||||
r.commands = append(r.commands, newModifications...)
|
||||
totalModsForCommand += len(newModifications)
|
||||
addCommandModificationCount(command.Name, len(newModifications))
|
||||
if len(newModifications) > 0 {
|
||||
if _, dup := r.regexLogSeen[commandName]; !dup {
|
||||
r.regexLogSeen[commandName] = struct{}{}
|
||||
r.regexLogNames = append(r.regexLogNames, commandName)
|
||||
}
|
||||
}
|
||||
|
||||
cmdLog.Debug("Generated modifications", "count", len(newModifications))
|
||||
if len(newModifications) == 0 {
|
||||
cmdLog.Warn("Regex produced no modifications", "regex", pattern, "file", r.file)
|
||||
}
|
||||
}
|
||||
return totalModsForCommand, hadError
|
||||
}
|
||||
@@ -0,0 +1,131 @@
|
||||
package chef
|
||||
|
||||
import (
|
||||
"fmt"
|
||||
"log/slog"
|
||||
"sync/atomic"
|
||||
|
||||
"cook/processor"
|
||||
"cook/utils"
|
||||
)
|
||||
|
||||
func (r *otherCommandRunner) runStructuredCommands(commands []utils.ModifyCommand) {
|
||||
for _, command := range commands {
|
||||
commandName := commandNameForStats(command)
|
||||
if !commandSeenPredicateGate(command, commandName, r.fileDataStr, r.log, false) {
|
||||
continue
|
||||
}
|
||||
|
||||
cmdLogger := loggerForCommand(command.Name, r.commandLoggers)
|
||||
|
||||
switch {
|
||||
case command.Raw:
|
||||
r.runRawCommand(command, commandName)
|
||||
case command.JSON:
|
||||
r.runJSONCommand(command, commandName, cmdLogger)
|
||||
case command.XML:
|
||||
cmdLog := cmdLogger.With("cmd", command.Name)
|
||||
cmdLog.Debug("Queued file for XML mode")
|
||||
r.xmlCommands = append(r.xmlCommands, command)
|
||||
r.xmlCommandNames = append(r.xmlCommandNames, commandName)
|
||||
default:
|
||||
r.regexCommands = append(r.regexCommands, command)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
func (r *otherCommandRunner) runRawCommand(command utils.ModifyCommand, commandName string) {
|
||||
modifications, err := processor.ProcessRaw(r.fileDataStr, command, r.file)
|
||||
if err != nil {
|
||||
incrementCommandError(commandName, err)
|
||||
return
|
||||
}
|
||||
if len(modifications) > 0 {
|
||||
r.fileDataStr, _ = utils.ExecuteModificationsForFile(r.file, []string{commandName}, modifications, r.fileDataStr)
|
||||
r.structuredModified = true
|
||||
}
|
||||
}
|
||||
|
||||
func (r *otherCommandRunner) runJSONCommand(command utils.ModifyCommand, commandName string, cmdLogger *slog.Logger) {
|
||||
cmdLog := cmdLogger.With("cmd", command.Name)
|
||||
cmdLog.Debug("Processing file with JSON mode")
|
||||
if !r.jsonParsed {
|
||||
if err := processor.JSONUnmarshal([]byte(r.fileDataStr), &r.jsonData); err != nil {
|
||||
r.log.Error("Failed to parse JSON for command", "cmd", command.Name, "err", err)
|
||||
incrementCommandError(commandName, fmt.Errorf("failed to parse JSON: %v", err))
|
||||
return
|
||||
}
|
||||
r.jsonParsed = true
|
||||
}
|
||||
newData, newModifications, modified, err := processor.ProcessJSONParsed(r.fileDataStr, r.jsonData, command, r.file)
|
||||
if err != nil {
|
||||
r.log.Error("Failed to process file with JSON command", "cmd", command.Name, "err", err)
|
||||
incrementCommandError(commandName, err)
|
||||
return
|
||||
}
|
||||
|
||||
if modified {
|
||||
var count int
|
||||
r.fileDataStr, count = utils.ExecuteModificationsForFile(r.file, []string{commandName}, newModifications, r.fileDataStr)
|
||||
atomic.AddInt64(&stats.TotalModifications, int64(count))
|
||||
cmdLog.Debug("Applied JSON modifications", "count", count)
|
||||
r.structuredModified = true
|
||||
r.jsonData = newData
|
||||
incrementCommandCounter(commandName, func(cs *CommandStats) {
|
||||
atomic.AddInt64(&cs.FilesModified, 1)
|
||||
atomic.AddInt64(&cs.ModificationsTotal, int64(len(newModifications)))
|
||||
})
|
||||
} else {
|
||||
incrementCommandCounter(commandName, func(cs *CommandStats) {
|
||||
atomic.AddInt64(&cs.FilesNoMatch, 1)
|
||||
})
|
||||
}
|
||||
|
||||
addCommandModificationCount(command.Name, len(newModifications))
|
||||
}
|
||||
|
||||
func (r *otherCommandRunner) runXMLQueued() {
|
||||
if len(r.xmlCommands) == 0 {
|
||||
return
|
||||
}
|
||||
newModifications, counts, err := processor.ProcessXMLCommands(r.fileDataStr, r.xmlCommands, r.file)
|
||||
if err != nil {
|
||||
r.recordXMLProcessError(err)
|
||||
return
|
||||
}
|
||||
r.recordXMLCommandCounts(counts)
|
||||
if len(newModifications) > 0 {
|
||||
var count int
|
||||
r.fileDataStr, count = utils.ExecuteModificationsForFile(r.file, uniqueCommandNames(r.xmlCommands), newModifications, r.fileDataStr)
|
||||
atomic.AddInt64(&stats.TotalModifications, int64(count))
|
||||
r.structuredModified = true
|
||||
}
|
||||
}
|
||||
|
||||
func (r *otherCommandRunner) recordXMLProcessError(err error) {
|
||||
r.log.Error("Failed to process file with XML commands", "err", err)
|
||||
if ce, ok := err.(processor.XMLCommandError); ok {
|
||||
incrementCommandError(ce.CommandName, ce.Err)
|
||||
return
|
||||
}
|
||||
for _, name := range r.xmlCommandNames {
|
||||
incrementCommandError(name, err)
|
||||
}
|
||||
}
|
||||
|
||||
func (r *otherCommandRunner) recordXMLCommandCounts(counts []int) {
|
||||
for i, c := range r.xmlCommands {
|
||||
count := counts[i]
|
||||
if count > 0 {
|
||||
incrementCommandCounter(r.xmlCommandNames[i], func(cs *CommandStats) {
|
||||
atomic.AddInt64(&cs.FilesModified, 1)
|
||||
atomic.AddInt64(&cs.ModificationsTotal, int64(count))
|
||||
})
|
||||
addCommandModificationCount(c.Name, count)
|
||||
} else {
|
||||
incrementCommandCounter(r.xmlCommandNames[i], func(cs *CommandStats) {
|
||||
atomic.AddInt64(&cs.FilesNoMatch, 1)
|
||||
})
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,310 @@
|
||||
package chef
|
||||
|
||||
import (
|
||||
"bytes"
|
||||
"encoding/json"
|
||||
"log/slog"
|
||||
"os"
|
||||
"path/filepath"
|
||||
"strings"
|
||||
"sync/atomic"
|
||||
"testing"
|
||||
|
||||
"cook/processor"
|
||||
"cook/utils"
|
||||
|
||||
logger "git.site.quack-lab.dev/dave/cylogger/v3"
|
||||
"github.com/stretchr/testify/assert"
|
||||
"github.com/stretchr/testify/require"
|
||||
)
|
||||
|
||||
const (
|
||||
testJSONPath = "test.json"
|
||||
testXMLPath = "test.xml"
|
||||
)
|
||||
|
||||
func TestRunOtherCommands(t *testing.T) {
|
||||
t.Run("regression/json/parse_once/two_regular_commands_same_file/parses_once", func(t *testing.T) {
|
||||
var parses int32
|
||||
orig := processor.JSONUnmarshal
|
||||
t.Cleanup(func() { processor.JSONUnmarshal = orig })
|
||||
processor.JSONUnmarshal = func(data []byte, v interface{}) error {
|
||||
atomic.AddInt32(&parses, 1)
|
||||
return json.Unmarshal(data, v)
|
||||
}
|
||||
|
||||
file := testJSONPath
|
||||
input := `{"a":1,"b":2,"nested":{"x":3}}`
|
||||
association := utils.FileCommandAssociation{
|
||||
File: file,
|
||||
Commands: []utils.ModifyCommand{
|
||||
{
|
||||
Name: "cmd1_add_to_a",
|
||||
JSON: true,
|
||||
Lua: `data.a = data.a + 10; modified = true`,
|
||||
Files: []string{file},
|
||||
},
|
||||
{
|
||||
Name: "cmd2_set_nested_x_from_updated_a",
|
||||
JSON: true,
|
||||
Lua: `data.nested.x = data.a + data.b; modified = true`,
|
||||
Files: []string{file},
|
||||
},
|
||||
},
|
||||
}
|
||||
|
||||
got, err := RunOtherCommands(file, input, association, map[string]*slog.Logger{})
|
||||
require.NoError(t, err)
|
||||
assert.Equal(t, `{"a":11,"b":2,"nested":{"x":13}}`, got)
|
||||
assert.Equal(t, int32(1), atomic.LoadInt32(&parses))
|
||||
})
|
||||
|
||||
t.Run("regression/xml/parse_once/two_regular_commands_same_file/parses_once", func(t *testing.T) {
|
||||
var parses int32
|
||||
orig := processor.ParseXMLWithPositions
|
||||
t.Cleanup(func() { processor.ParseXMLWithPositions = orig })
|
||||
processor.ParseXMLWithPositions = func(content string) (*processor.XMLElement, error) {
|
||||
atomic.AddInt32(&parses, 1)
|
||||
return orig(content)
|
||||
}
|
||||
|
||||
file := testXMLPath
|
||||
input := `<root version="1"><item price="10" /></root>`
|
||||
association := utils.FileCommandAssociation{
|
||||
File: file,
|
||||
Commands: []utils.ModifyCommand{
|
||||
{
|
||||
Name: "cmd1_set_version",
|
||||
XML: true,
|
||||
Lua: `data.attr.version = "2"; modified = true`,
|
||||
Files: []string{file},
|
||||
},
|
||||
{
|
||||
Name: "cmd2_add_to_price",
|
||||
XML: true,
|
||||
Lua: `data.children[1].attr.price = N(data.children[1].attr.price) + 7; modified = true`,
|
||||
Files: []string{file},
|
||||
},
|
||||
},
|
||||
}
|
||||
|
||||
got, err := RunOtherCommands(file, input, association, map[string]*slog.Logger{})
|
||||
require.NoError(t, err)
|
||||
assert.Equal(t, `<root version="2"><item price="17" /></root>`, got)
|
||||
assert.Equal(t, int32(1), atomic.LoadInt32(&parses))
|
||||
})
|
||||
|
||||
t.Run("regression/json/two_regular_commands_on_same_file/preserve_sequential_semantics", func(t *testing.T) {
|
||||
file := testJSONPath
|
||||
input := `{"a":1,"b":2,"nested":{"x":3}}`
|
||||
|
||||
association := utils.FileCommandAssociation{
|
||||
File: file,
|
||||
Commands: []utils.ModifyCommand{
|
||||
{
|
||||
Name: "cmd1_add_to_a",
|
||||
JSON: true,
|
||||
Lua: `data.a = data.a + 10; modified = true`,
|
||||
Files: []string{file},
|
||||
},
|
||||
{
|
||||
Name: "cmd2_set_nested_x_from_updated_a",
|
||||
JSON: true,
|
||||
Lua: `data.nested.x = data.a + data.b; modified = true`,
|
||||
Files: []string{file},
|
||||
},
|
||||
},
|
||||
}
|
||||
|
||||
got, err := RunOtherCommands(file, input, association, map[string]*slog.Logger{})
|
||||
require.NoError(t, err)
|
||||
assert.Equal(t, `{"a":11,"b":2,"nested":{"x":13}}`, got)
|
||||
})
|
||||
|
||||
t.Run("regression/xml/two_regular_commands_on_same_file/preserve_sequential_semantics", func(t *testing.T) {
|
||||
file := testXMLPath
|
||||
input := `<root version="1"><item price="10" /></root>`
|
||||
|
||||
association := utils.FileCommandAssociation{
|
||||
File: file,
|
||||
Commands: []utils.ModifyCommand{
|
||||
{
|
||||
Name: "cmd1_set_version",
|
||||
XML: true,
|
||||
Lua: `data.attr.version = "2"; modified = true`,
|
||||
Files: []string{file},
|
||||
},
|
||||
{
|
||||
Name: "cmd2_add_to_price",
|
||||
XML: true,
|
||||
Lua: `data.children[1].attr.price = N(data.children[1].attr.price) + 7; modified = true`,
|
||||
Files: []string{file},
|
||||
},
|
||||
},
|
||||
}
|
||||
|
||||
got, err := RunOtherCommands(file, input, association, map[string]*slog.Logger{})
|
||||
require.NoError(t, err)
|
||||
assert.Equal(t, `<root version="2"><item price="17" /></root>`, got)
|
||||
})
|
||||
|
||||
t.Run("integration/mixed_regular_commands/json_then_regex/regex_sees_structured_output", func(t *testing.T) {
|
||||
file := testJSONPath
|
||||
input := `{"marker":"X"}`
|
||||
|
||||
association := utils.FileCommandAssociation{
|
||||
File: file,
|
||||
Commands: []utils.ModifyCommand{
|
||||
{
|
||||
Name: "cmd1_json_update_marker",
|
||||
JSON: true,
|
||||
Lua: `data.marker = "Y"; modified = true`,
|
||||
Files: []string{file},
|
||||
},
|
||||
{
|
||||
Name: "cmd2_regex_update_marker",
|
||||
Regex: `"marker":"(?P<val>[^"]+)"`,
|
||||
Lua: `val = "Z"; modified = true`,
|
||||
Files: []string{file},
|
||||
},
|
||||
},
|
||||
}
|
||||
|
||||
got, err := RunOtherCommands(file, input, association, map[string]*slog.Logger{})
|
||||
require.NoError(t, err)
|
||||
assert.Equal(t, `{"marker":"Z"}`, got)
|
||||
assert.NotContains(t, got, `"marker":"X"`)
|
||||
assert.NotContains(t, got, `"marker":"Y"`)
|
||||
})
|
||||
|
||||
t.Run("regression/game-balance-parse-error/no_log_line_ever_contains_newline_token", func(t *testing.T) {
|
||||
var buf bytes.Buffer
|
||||
logger.ToWritersD(&buf)
|
||||
logger.NoStdoutD()
|
||||
t.Cleanup(func() {
|
||||
logger.Init(logger.LevelInfo, false)
|
||||
})
|
||||
|
||||
dir := filepath.FromSlash("../../processor/testdata/regression/game-balance-parse-error")
|
||||
tomlBytes, err := os.ReadFile(filepath.Join(dir, "game_balance.toml"))
|
||||
require.NoError(t, err)
|
||||
inputBytes, err := os.ReadFile(filepath.Join(dir, "game_balance.json"))
|
||||
require.NoError(t, err)
|
||||
|
||||
commands, err := utils.LoadCommandsFromTomlFile(tomlBytes)
|
||||
require.NoError(t, err)
|
||||
|
||||
var cmd utils.ModifyCommand
|
||||
for _, c := range commands {
|
||||
if c.Name == "NPC_HEALING_RATE" {
|
||||
cmd = c
|
||||
break
|
||||
}
|
||||
}
|
||||
require.NotEmpty(t, cmd.Name, "NPC_HEALING_RATE command not found in fixture")
|
||||
cmd.SourceFile = filepath.Join(dir, "game_balance.toml")
|
||||
|
||||
globalBefore, globalAfter, err := utils.LoadGlobalHooks(filepath.Join(dir, "cook_hooks.toml"))
|
||||
require.NoError(t, err)
|
||||
cmd.BeforeEach = globalBefore + "\n" + cmd.BeforeEach
|
||||
cmd.AfterEach = cmd.AfterEach + "\n" + globalAfter
|
||||
|
||||
file := "game_balance.json"
|
||||
association := utils.FileCommandAssociation{
|
||||
File: file,
|
||||
Commands: []utils.ModifyCommand{cmd},
|
||||
}
|
||||
|
||||
_, err = RunOtherCommands(file, string(inputBytes), association, map[string]*slog.Logger{})
|
||||
require.Error(t, err)
|
||||
|
||||
captured := buf.String()
|
||||
require.Contains(t, captured, "Failed to process file with JSON command",
|
||||
"expected the JSON command failure to be logged, got: %s", captured)
|
||||
assert.Contains(t, captured, "game_balance.toml line:55",
|
||||
"the logged err must reference the same source line as the formatted stderr output, got: %s", captured)
|
||||
assert.NotContains(t, captured, "line:102",
|
||||
"the logged err must not reference the raw chunk line 102, got: %s", captured)
|
||||
|
||||
for _, line := range strings.Split(captured, "\n") {
|
||||
assert.NotContains(t, line, `\n`,
|
||||
"a log line must never contain a literal \\n token inside a message: %q", line)
|
||||
}
|
||||
})
|
||||
}
|
||||
|
||||
func TestRunIsolateCommands(t *testing.T) {
|
||||
t.Run("regression/json/isolate_exempt/two_isolate_commands_same_file/parses_per_command", func(t *testing.T) {
|
||||
var parses int32
|
||||
orig := processor.JSONUnmarshal
|
||||
t.Cleanup(func() { processor.JSONUnmarshal = orig })
|
||||
processor.JSONUnmarshal = func(data []byte, v interface{}) error {
|
||||
atomic.AddInt32(&parses, 1)
|
||||
return json.Unmarshal(data, v)
|
||||
}
|
||||
|
||||
file := testJSONPath
|
||||
input := `{"a":1,"b":2,"nested":{"x":3}}`
|
||||
association := utils.FileCommandAssociation{
|
||||
File: file,
|
||||
IsolateCommands: []utils.ModifyCommand{
|
||||
{
|
||||
Name: "cmd1_add_to_a",
|
||||
JSON: true,
|
||||
Lua: `data.a = data.a + 10; modified = true`,
|
||||
Files: []string{file},
|
||||
Isolate: true,
|
||||
},
|
||||
{
|
||||
Name: "cmd2_set_nested_x_from_updated_a",
|
||||
JSON: true,
|
||||
Lua: `data.nested.x = data.a + data.b; modified = true`,
|
||||
Files: []string{file},
|
||||
Isolate: true,
|
||||
},
|
||||
},
|
||||
}
|
||||
|
||||
got, err := RunIsolateCommands(association, file, input)
|
||||
require.NoError(t, err)
|
||||
assert.Equal(t, `{"a":11,"b":2,"nested":{"x":13}}`, got)
|
||||
assert.Equal(t, int32(2), atomic.LoadInt32(&parses))
|
||||
})
|
||||
|
||||
t.Run("regression/xml/isolate_exempt/two_isolate_commands_same_file/parses_per_command", func(t *testing.T) {
|
||||
var parses int32
|
||||
orig := processor.ParseXMLWithPositions
|
||||
t.Cleanup(func() { processor.ParseXMLWithPositions = orig })
|
||||
processor.ParseXMLWithPositions = func(content string) (*processor.XMLElement, error) {
|
||||
atomic.AddInt32(&parses, 1)
|
||||
return orig(content)
|
||||
}
|
||||
|
||||
file := testXMLPath
|
||||
input := `<root version="1"><item price="10" /></root>`
|
||||
association := utils.FileCommandAssociation{
|
||||
File: file,
|
||||
IsolateCommands: []utils.ModifyCommand{
|
||||
{
|
||||
Name: "cmd1_set_version",
|
||||
XML: true,
|
||||
Lua: `data.attr.version = "2"; modified = true`,
|
||||
Files: []string{file},
|
||||
Isolate: true,
|
||||
},
|
||||
{
|
||||
Name: "cmd2_add_to_price",
|
||||
XML: true,
|
||||
Lua: `data.children[1].attr.price = N(data.children[1].attr.price) + 7; modified = true`,
|
||||
Files: []string{file},
|
||||
Isolate: true,
|
||||
},
|
||||
},
|
||||
}
|
||||
|
||||
got, err := RunIsolateCommands(association, file, input)
|
||||
require.NoError(t, err)
|
||||
assert.Equal(t, `<root version="2"><item price="17" /></root>`, got)
|
||||
assert.Equal(t, int32(2), atomic.LoadInt32(&parses))
|
||||
})
|
||||
}
|
||||
@@ -0,0 +1,125 @@
|
||||
package chef
|
||||
|
||||
import (
|
||||
"fmt"
|
||||
"os"
|
||||
"regexp"
|
||||
"strings"
|
||||
"sync/atomic"
|
||||
|
||||
"cook/utils"
|
||||
)
|
||||
|
||||
type CommandStats struct {
|
||||
FilesSeen int64
|
||||
FilesPredicateSkipped int64
|
||||
FilesModified int64
|
||||
FilesNoMatch int64
|
||||
LuaErrors int64
|
||||
ParseErrors int64
|
||||
OtherErrors int64
|
||||
ModificationsTotal int64
|
||||
}
|
||||
|
||||
func commandNameForStats(command utils.ModifyCommand) string {
|
||||
if command.Name != "" {
|
||||
return command.Name
|
||||
}
|
||||
if command.Regex != "" {
|
||||
return command.Regex
|
||||
}
|
||||
if command.XML {
|
||||
return "<xml-command>"
|
||||
}
|
||||
if command.JSON {
|
||||
return "<json-command>"
|
||||
}
|
||||
return "<unnamed-command>"
|
||||
}
|
||||
|
||||
func getOrCreateCommandStats(commandName string) *CommandStats {
|
||||
if existing, ok := stats.CommandStats.Load(commandName); ok {
|
||||
return existing.(*CommandStats)
|
||||
}
|
||||
created := &CommandStats{}
|
||||
actual, _ := stats.CommandStats.LoadOrStore(commandName, created)
|
||||
return actual.(*CommandStats)
|
||||
}
|
||||
|
||||
func incrementCommandCounter(commandName string, fn func(*CommandStats)) {
|
||||
cs := getOrCreateCommandStats(commandName)
|
||||
fn(cs)
|
||||
}
|
||||
|
||||
func incrementCommandError(commandName string, err error) {
|
||||
cs := getOrCreateCommandStats(commandName)
|
||||
msg := strings.ToLower(err.Error())
|
||||
switch {
|
||||
case strings.Contains(msg, "lua script execution failed"):
|
||||
atomic.AddInt64(&cs.LuaErrors, 1)
|
||||
case strings.Contains(msg, "failed to parse json") || strings.Contains(msg, "failed to parse xml"):
|
||||
atomic.AddInt64(&cs.ParseErrors, 1)
|
||||
default:
|
||||
atomic.AddInt64(&cs.OtherErrors, 1)
|
||||
}
|
||||
}
|
||||
|
||||
func commandPredicateMatches(command utils.ModifyCommand, content string) (bool, error) {
|
||||
preds := make([]string, 0, len(command.RegexPreds)+1)
|
||||
if command.RegexPred != "" {
|
||||
preds = append(preds, command.RegexPred)
|
||||
}
|
||||
preds = append(preds, command.RegexPreds...)
|
||||
if len(preds) == 0 {
|
||||
return true, nil
|
||||
}
|
||||
for _, pred := range preds {
|
||||
matched, err := regexp.MatchString(pred, content)
|
||||
if err != nil {
|
||||
return false, fmt.Errorf("invalid regex_pred %q for command %q: %w", pred, command.Name, err)
|
||||
}
|
||||
if matched {
|
||||
return true, nil
|
||||
}
|
||||
}
|
||||
return false, nil
|
||||
}
|
||||
|
||||
func printCommandSummaryTable() {
|
||||
rows := commandSummaryRows()
|
||||
utils.RenderCommandSummaryTable(os.Stdout, rows)
|
||||
}
|
||||
|
||||
func commandSummaryRows() []utils.CommandSummaryRow {
|
||||
rows := make([]utils.CommandSummaryRow, 0)
|
||||
stats.CommandStats.Range(func(key, value interface{}) bool {
|
||||
name := key.(string)
|
||||
cs := value.(*CommandStats)
|
||||
|
||||
seen := atomic.LoadInt64(&cs.FilesSeen)
|
||||
predSkip := atomic.LoadInt64(&cs.FilesPredicateSkipped)
|
||||
filesModified := atomic.LoadInt64(&cs.FilesModified)
|
||||
filesNoMatch := atomic.LoadInt64(&cs.FilesNoMatch)
|
||||
luaErr := atomic.LoadInt64(&cs.LuaErrors)
|
||||
parseErr := atomic.LoadInt64(&cs.ParseErrors)
|
||||
otherErr := atomic.LoadInt64(&cs.OtherErrors)
|
||||
edits := atomic.LoadInt64(&cs.ModificationsTotal)
|
||||
errorsTotal := luaErr + parseErr + otherErr
|
||||
filesUnchanged := filesNoMatch + errorsTotal
|
||||
|
||||
rows = append(rows, utils.CommandSummaryRow{
|
||||
Name: name,
|
||||
Seen: seen,
|
||||
PredSkip: predSkip,
|
||||
FilesModified: filesModified,
|
||||
FilesUnchanged: filesUnchanged,
|
||||
LuaErr: luaErr,
|
||||
ParseErr: parseErr,
|
||||
OtherErr: otherErr,
|
||||
Edits: edits,
|
||||
HasErrors: errorsTotal > 0,
|
||||
})
|
||||
return true
|
||||
})
|
||||
return rows
|
||||
}
|
||||
@@ -0,0 +1,69 @@
|
||||
package chef
|
||||
|
||||
import (
|
||||
"os"
|
||||
"path/filepath"
|
||||
"testing"
|
||||
|
||||
"cook/utils"
|
||||
|
||||
"github.com/stretchr/testify/assert"
|
||||
"github.com/stretchr/testify/require"
|
||||
)
|
||||
|
||||
const cookFilename = "activity_actor.toml"
|
||||
|
||||
func copyFixtureFile(t *testing.T, src, dst string) {
|
||||
t.Helper()
|
||||
data, err := os.ReadFile(src)
|
||||
require.NoError(t, err)
|
||||
require.NoError(t, os.WriteFile(dst, data, 0644))
|
||||
}
|
||||
|
||||
func TestCommandStats(t *testing.T) {
|
||||
t.Run("regression/activity-actor-1-missing-summary/every_loaded_command_appears_in_summary", func(t *testing.T) {
|
||||
ResetGlobalStatsForTest()
|
||||
|
||||
base := t.TempDir()
|
||||
cookDir := filepath.Join(base, "chef_recipes_simple")
|
||||
srcDir := filepath.Join(base, "src")
|
||||
require.NoError(t, os.MkdirAll(cookDir, 0755))
|
||||
require.NoError(t, os.MkdirAll(srcDir, 0755))
|
||||
|
||||
fixtureDir := filepath.Join("testdata", "regression", "activity-actor-1-missing-summary")
|
||||
copyFixtureFile(t, filepath.Join(fixtureDir, cookFilename), filepath.Join(cookDir, cookFilename))
|
||||
copyFixtureFile(t, filepath.Join(fixtureDir, "activity_actor.cpp"), filepath.Join(srcDir, "activity_actor.cpp"))
|
||||
|
||||
setWorkingDir(t, cookDir)
|
||||
|
||||
commands, err := utils.LoadCommands([]string{cookFilename})
|
||||
require.NoError(t, err)
|
||||
require.NotEmpty(t, commands)
|
||||
|
||||
expectedNames := make(map[string]struct{}, len(commands))
|
||||
for _, cmd := range commands {
|
||||
expectedNames[commandNameForStats(cmd)] = struct{}{}
|
||||
}
|
||||
require.Contains(t, expectedNames, "gen_activity_actor_1",
|
||||
"fixture must still contain the command that was reported missing from the summary")
|
||||
|
||||
require.NoError(t, RunCookfiles(RunCookfilesConfig{
|
||||
CookPaths: []string{cookFilename},
|
||||
Parallel: 1,
|
||||
}))
|
||||
|
||||
rows := commandSummaryRows()
|
||||
rowNames := make(map[string]struct{}, len(rows))
|
||||
for _, row := range rows {
|
||||
rowNames[row.Name] = struct{}{}
|
||||
}
|
||||
|
||||
assert.Contains(t, rowNames, "Reduce hand crank charge time",
|
||||
"the pipeline must have actually processed the file and produced summary rows")
|
||||
|
||||
for name := range expectedNames {
|
||||
assert.Contains(t, rowNames, name,
|
||||
"command %q was loaded from the cook file but is absent from the summary table", name)
|
||||
}
|
||||
})
|
||||
}
|
||||
@@ -0,0 +1,134 @@
|
||||
package chef
|
||||
|
||||
import (
|
||||
"fmt"
|
||||
"log/slog"
|
||||
"os"
|
||||
"path/filepath"
|
||||
"strings"
|
||||
|
||||
"cook/utils"
|
||||
|
||||
logger "git.site.quack-lab.dev/dave/cylogger/v3"
|
||||
"github.com/BurntSushi/toml"
|
||||
)
|
||||
|
||||
func ConvYAMLPatterns(patterns []string) error {
|
||||
log := logger.With("cmd", "conv")
|
||||
log.Info("Converting patterns", "count", len(patterns))
|
||||
for i := 0; i < len(patterns); i++ {
|
||||
pattern := patterns[i]
|
||||
log.Debug("Processing pattern", "idx", i+1, "total", len(patterns), "pattern", pattern)
|
||||
if err := ConvertYAMLToTOML(pattern); err != nil {
|
||||
return fmt.Errorf("failed to convert YAML files for pattern %s: %w", pattern, err)
|
||||
}
|
||||
}
|
||||
return nil
|
||||
}
|
||||
|
||||
func ConvertYAMLToTOML(yamlPattern string) error {
|
||||
log := logger.With("func", "ConvertYAMLToTOML", "pattern", yamlPattern)
|
||||
log.Debug("Starting YAML to TOML conversion")
|
||||
|
||||
static, pattern := utils.SplitPattern(yamlPattern)
|
||||
yamlFiles, err := utils.GlobFiles(static, pattern)
|
||||
if err != nil {
|
||||
log.Error("Failed to glob YAML files", "err", err)
|
||||
return fmt.Errorf("failed to glob YAML files: %w", err)
|
||||
}
|
||||
|
||||
log.Debug("Found YAML files to convert", "count", len(yamlFiles))
|
||||
|
||||
if len(yamlFiles) == 0 {
|
||||
log.Info("No YAML files found for pattern")
|
||||
return nil
|
||||
}
|
||||
|
||||
conversionCount, skippedCount := convertYAMLFiles(log, static, yamlFiles)
|
||||
|
||||
log.Info("Conversion completed", "converted", conversionCount, "skipped", skippedCount)
|
||||
return nil
|
||||
}
|
||||
|
||||
func convertYAMLFiles(log *slog.Logger, static string, yamlFiles []string) (converted, skipped int) {
|
||||
for _, yamlFile := range yamlFiles {
|
||||
yamlFilePath := utils.ResolvePath(filepath.Join(static, yamlFile))
|
||||
flog := log.With("src", yamlFilePath, "target", tomlPathFor(yamlFilePath))
|
||||
flog.Debug("Processing YAML file")
|
||||
|
||||
ok, skip := convertYAMLFile(flog, yamlFilePath)
|
||||
if skip {
|
||||
skipped++
|
||||
} else if ok {
|
||||
converted++
|
||||
}
|
||||
}
|
||||
return converted, skipped
|
||||
}
|
||||
|
||||
func convertYAMLFile(flog *slog.Logger, yamlFilePath string) (converted, skipped bool) {
|
||||
tomlFilePath := tomlPathFor(yamlFilePath)
|
||||
|
||||
if _, err := os.Stat(filepath.FromSlash(tomlFilePath)); err == nil {
|
||||
flog.Info("Skipping conversion - TOML file already exists")
|
||||
return false, true
|
||||
}
|
||||
|
||||
if err := convertYAMLContent(flog, yamlFilePath, tomlFilePath); err != nil {
|
||||
return false, false
|
||||
}
|
||||
|
||||
flog.Info("Successfully converted file")
|
||||
return true, false
|
||||
}
|
||||
|
||||
// convertYAMLContent reads, parses and writes the converted TOML file.
|
||||
func convertYAMLContent(flog *slog.Logger, yamlFilePath, tomlFilePath string) error {
|
||||
yamlData, err := os.ReadFile(filepath.FromSlash(yamlFilePath))
|
||||
if err != nil {
|
||||
flog.Error("Failed to read YAML file", "err", err)
|
||||
return err
|
||||
}
|
||||
|
||||
fileCommands, err := utils.LoadCommandsFromCookFile(yamlData)
|
||||
if err != nil {
|
||||
flog.Error("Failed to parse YAML file", "err", err)
|
||||
return err
|
||||
}
|
||||
|
||||
tomlData, err := convertCommandsToTOML(fileCommands)
|
||||
if err != nil {
|
||||
flog.Error("Failed to convert commands to TOML", "err", err)
|
||||
return err
|
||||
}
|
||||
|
||||
if err := os.WriteFile(filepath.FromSlash(tomlFilePath), tomlData, 0644); err != nil {
|
||||
flog.Error("Failed to write TOML file", "err", err)
|
||||
return err
|
||||
}
|
||||
return nil
|
||||
}
|
||||
|
||||
func tomlPathFor(yamlFilePath string) string {
|
||||
return strings.TrimSuffix(yamlFilePath, filepath.Ext(yamlFilePath)) + ".toml"
|
||||
}
|
||||
|
||||
func convertCommandsToTOML(commands []utils.ModifyCommand) ([]byte, error) {
|
||||
log := logger.With("func", "convertCommandsToTOML")
|
||||
log.Debug("Converting commands to TOML format", "count", len(commands))
|
||||
|
||||
tomlData := struct {
|
||||
Commands []utils.ModifyCommand `toml:"commands"`
|
||||
}{
|
||||
Commands: commands,
|
||||
}
|
||||
|
||||
tomlBytes, err := toml.Marshal(tomlData)
|
||||
if err != nil {
|
||||
log.Error("Failed to marshal commands to TOML", "err", err)
|
||||
return nil, fmt.Errorf("failed to marshal commands to TOML: %w", err)
|
||||
}
|
||||
|
||||
log.Debug("Successfully converted commands to TOML", "commands", len(commands), "bytes", len(tomlBytes))
|
||||
return tomlBytes, nil
|
||||
}
|
||||
@@ -0,0 +1,141 @@
|
||||
package chef
|
||||
|
||||
import (
|
||||
"os"
|
||||
"path/filepath"
|
||||
"testing"
|
||||
|
||||
"cook/utils"
|
||||
|
||||
"github.com/stretchr/testify/assert"
|
||||
"github.com/stretchr/testify/require"
|
||||
)
|
||||
|
||||
const (
|
||||
testYmlPath = "test.yml"
|
||||
testTomlPath = "test.toml"
|
||||
)
|
||||
|
||||
func TestConvertYAMLToTOML(t *testing.T) {
|
||||
t.Run("unit/read_error/unreadable_yaml_returns_without_crash", func(t *testing.T) {
|
||||
tmpDir := t.TempDir()
|
||||
yamlFile := filepath.Join(tmpDir, testYmlPath)
|
||||
require.NoError(t, os.WriteFile(yamlFile, []byte("commands:\n - name: test\n"), 0000))
|
||||
origDir, err := os.Getwd()
|
||||
require.NoError(t, err)
|
||||
require.NoError(t, os.Chdir(tmpDir))
|
||||
t.Cleanup(func() { require.NoError(t, os.Chdir(origDir)) })
|
||||
require.NoError(t, ConvertYAMLToTOML(testYmlPath))
|
||||
require.NoError(t, os.Chmod(yamlFile, 0644))
|
||||
})
|
||||
|
||||
t.Run("unit/parse_error/does_not_write_toml", func(t *testing.T) {
|
||||
tmpDir := t.TempDir()
|
||||
yamlFile := filepath.Join(tmpDir, "invalid.yml")
|
||||
require.NoError(t, os.WriteFile(yamlFile, []byte("commands:\n - [this is not valid yaml}}"), 0644))
|
||||
origDir, err := os.Getwd()
|
||||
require.NoError(t, err)
|
||||
require.NoError(t, os.Chdir(tmpDir))
|
||||
t.Cleanup(func() { require.NoError(t, os.Chdir(origDir)) })
|
||||
require.NoError(t, ConvertYAMLToTOML("invalid.yml"))
|
||||
_, statErr := os.Stat(filepath.Join(tmpDir, "invalid.toml"))
|
||||
assert.True(t, os.IsNotExist(statErr))
|
||||
})
|
||||
|
||||
t.Run("unit/write_error/readonly_output_dir", func(t *testing.T) {
|
||||
tmpDir := t.TempDir()
|
||||
yamlFile := filepath.Join(tmpDir, testYmlPath)
|
||||
require.NoError(t, os.WriteFile(yamlFile, []byte("commands:\n - name: test\n regex: test\n lua: v1\n files: [test.txt]\n"), 0644))
|
||||
outputDir := filepath.Join(tmpDir, "readonly")
|
||||
require.NoError(t, os.Mkdir(outputDir, 0555))
|
||||
t.Cleanup(func() { require.NoError(t, os.Chmod(outputDir, 0755)) })
|
||||
origDir, err := os.Getwd()
|
||||
require.NoError(t, err)
|
||||
require.NoError(t, os.Chdir(tmpDir))
|
||||
t.Cleanup(func() { require.NoError(t, os.Chdir(origDir)) })
|
||||
newYamlFile := filepath.Join(outputDir, testYmlPath)
|
||||
require.NoError(t, os.Rename(yamlFile, newYamlFile))
|
||||
require.NoError(t, os.Chdir(outputDir))
|
||||
require.NoError(t, ConvertYAMLToTOML(testYmlPath))
|
||||
})
|
||||
|
||||
t.Run("unit/skip_existing/toml_left_unchanged", func(t *testing.T) {
|
||||
tmpDir := t.TempDir()
|
||||
yamlContent := `
|
||||
commands:
|
||||
- name: "test"
|
||||
regex: "value"
|
||||
lua: "v1 * 2"
|
||||
files: ["*.txt"]
|
||||
`
|
||||
yamlFile := filepath.Join(tmpDir, testYmlPath)
|
||||
require.NoError(t, os.WriteFile(yamlFile, []byte(yamlContent), 0644))
|
||||
tomlFile := filepath.Join(tmpDir, testTomlPath)
|
||||
require.NoError(t, os.WriteFile(tomlFile, []byte("# existing"), 0644))
|
||||
origDir, err := os.Getwd()
|
||||
require.NoError(t, err)
|
||||
require.NoError(t, os.Chdir(tmpDir))
|
||||
t.Cleanup(func() { require.NoError(t, os.Chdir(origDir)) })
|
||||
require.NoError(t, ConvertYAMLToTOML(testYmlPath))
|
||||
content, err := os.ReadFile(tomlFile)
|
||||
require.NoError(t, err)
|
||||
assert.Equal(t, "# existing", string(content))
|
||||
})
|
||||
|
||||
t.Run("integration/full_yaml/writes_loadable_toml_and_idempotent_rerun", func(t *testing.T) {
|
||||
tmpDir := t.TempDir()
|
||||
origDir, err := os.Getwd()
|
||||
require.NoError(t, err)
|
||||
require.NoError(t, os.Chdir(tmpDir))
|
||||
t.Cleanup(func() { require.NoError(t, os.Chdir(origDir)) })
|
||||
|
||||
yamlContent := `commands:
|
||||
- name: "ConversionTest"
|
||||
regex: "value = !num"
|
||||
lua: "v1 * 3"
|
||||
files: ["test.txt"]
|
||||
loglevel: DEBUG
|
||||
- name: "AnotherTest"
|
||||
regex: "enabled = (true|false)"
|
||||
lua: "= false"
|
||||
files: ["*.conf"]
|
||||
`
|
||||
require.NoError(t, os.WriteFile(filepath.Join(tmpDir, testYmlPath), []byte(yamlContent), 0644))
|
||||
require.NoError(t, ConvertYAMLToTOML(testYmlPath))
|
||||
|
||||
tomlFile := filepath.Join(tmpDir, testTomlPath)
|
||||
_, err = os.Stat(tomlFile)
|
||||
require.NoError(t, err)
|
||||
tomlData, err := os.ReadFile(tomlFile)
|
||||
require.NoError(t, err)
|
||||
tomlContent := string(tomlData)
|
||||
assert.Contains(t, tomlContent, `name = "ConversionTest"`)
|
||||
assert.Contains(t, tomlContent, `name = "AnotherTest"`)
|
||||
|
||||
commands, err := utils.LoadCommandsFromTomlFiles(testTomlPath)
|
||||
require.NoError(t, err)
|
||||
assert.Len(t, commands, 2)
|
||||
|
||||
require.NoError(t, ConvertYAMLToTOML(testYmlPath))
|
||||
originalTomlData, err := os.ReadFile(tomlFile)
|
||||
require.NoError(t, err)
|
||||
assert.Equal(t, tomlData, originalTomlData)
|
||||
})
|
||||
|
||||
t.Run("unit/minimal_yaml/writes_expected_toml_fragments", func(t *testing.T) {
|
||||
tmpDir := t.TempDir()
|
||||
yamlContent := "commands:\n - name: test\n regex: value\n lua: s1\n files: [\"a.txt\"]\n"
|
||||
yamlFile := filepath.Join(tmpDir, "ok.yml")
|
||||
require.NoError(t, os.WriteFile(yamlFile, []byte(yamlContent), 0644))
|
||||
origDir, err := os.Getwd()
|
||||
require.NoError(t, err)
|
||||
require.NoError(t, os.Chdir(tmpDir))
|
||||
t.Cleanup(func() { require.NoError(t, os.Chdir(origDir)) })
|
||||
require.NoError(t, ConvertYAMLToTOML("ok.yml"))
|
||||
tomlBytes, err := os.ReadFile(filepath.Join(tmpDir, "ok.toml"))
|
||||
require.NoError(t, err)
|
||||
assert.Contains(t, string(tomlBytes), "[[commands]]")
|
||||
assert.Contains(t, string(tomlBytes), "name = \"test\"")
|
||||
})
|
||||
|
||||
}
|
||||
@@ -0,0 +1,24 @@
|
||||
package chef
|
||||
|
||||
import (
|
||||
"fmt"
|
||||
|
||||
"cook/utils"
|
||||
|
||||
logger "git.site.quack-lab.dev/dave/cylogger/v3"
|
||||
)
|
||||
|
||||
// withSnapshotDB opens the database and invokes fn with it, closing the
|
||||
// connection afterwards.
|
||||
func withSnapshotDB(fn func(utils.DB) error) error {
|
||||
db, err := utils.GetDB()
|
||||
if err != nil {
|
||||
return fmt.Errorf("failed to get database: %w", err)
|
||||
}
|
||||
defer func() {
|
||||
if err := db.Close(); err != nil {
|
||||
logger.Warn("failed to close database", "err", err)
|
||||
}
|
||||
}()
|
||||
return fn(db)
|
||||
}
|
||||
@@ -0,0 +1,31 @@
|
||||
package chef
|
||||
|
||||
import (
|
||||
"fmt"
|
||||
|
||||
"cook/utils"
|
||||
|
||||
logger "git.site.quack-lab.dev/dave/cylogger/v3"
|
||||
)
|
||||
|
||||
func RunDumpSnapshots() error {
|
||||
log := logger.With("cmd", "dump")
|
||||
log.Info("Dumping all files from database (clearing snapshots)")
|
||||
if err := withSnapshotDB(removeAllFiles); err != nil {
|
||||
return fmt.Errorf("failed to remove all files from database: %w", err)
|
||||
}
|
||||
log.Info("Successfully cleared all file snapshots from database")
|
||||
return nil
|
||||
}
|
||||
|
||||
func removeAllFiles(db utils.DB) error {
|
||||
log := logger.With("func", "removeAllFiles")
|
||||
log.Debug("Removing all files from database")
|
||||
err := db.DB().Exec("DELETE FROM file_snapshots").Error
|
||||
if err != nil {
|
||||
log.Error("Failed to remove all files from database", "err", err)
|
||||
} else {
|
||||
log.Debug("All files removed from database")
|
||||
}
|
||||
return err
|
||||
}
|
||||
@@ -0,0 +1,49 @@
|
||||
package chef
|
||||
|
||||
import (
|
||||
"os"
|
||||
"path/filepath"
|
||||
"testing"
|
||||
|
||||
"cook/utils"
|
||||
|
||||
"github.com/stretchr/testify/assert"
|
||||
"github.com/stretchr/testify/require"
|
||||
)
|
||||
|
||||
func closeTestDB(t *testing.T, db utils.DB) {
|
||||
t.Helper()
|
||||
if err := db.Close(); err != nil {
|
||||
return
|
||||
}
|
||||
}
|
||||
|
||||
func TestRemoveAllFilesClearsSnapshots(t *testing.T) {
|
||||
tmpDir, err := os.MkdirTemp("", "dump-clear-*")
|
||||
require.NoError(t, err)
|
||||
origDir, err := os.Getwd()
|
||||
require.NoError(t, err)
|
||||
defer func() {
|
||||
if err := os.Chdir(origDir); err != nil {
|
||||
t.Logf("failed to restore working directory: %v", err)
|
||||
}
|
||||
}()
|
||||
require.NoError(t, os.Chdir(tmpDir))
|
||||
|
||||
db, err := utils.GetDB()
|
||||
require.NoError(t, err)
|
||||
defer closeTestDB(t, db)
|
||||
|
||||
file := filepath.Join(tmpDir, "a.txt")
|
||||
require.NoError(t, db.SaveFile(file, []byte("original")))
|
||||
|
||||
before, err := db.GetAllFiles()
|
||||
require.NoError(t, err)
|
||||
require.NotEmpty(t, before)
|
||||
|
||||
require.NoError(t, removeAllFiles(db))
|
||||
|
||||
after, err := db.GetAllFiles()
|
||||
require.NoError(t, err)
|
||||
assert.Len(t, after, 0)
|
||||
}
|
||||
@@ -0,0 +1,7 @@
|
||||
package chef
|
||||
|
||||
import "errors"
|
||||
|
||||
var ErrNothingToDo = errors.New("nothing to do")
|
||||
|
||||
var ErrShowUsage = errors.New("show usage")
|
||||
@@ -0,0 +1,55 @@
|
||||
package chef
|
||||
|
||||
import (
|
||||
"fmt"
|
||||
"regexp"
|
||||
|
||||
logger "git.site.quack-lab.dev/dave/cylogger/v3"
|
||||
clip "golang.design/x/clipboard"
|
||||
)
|
||||
|
||||
func RunEscapeClipboard(minimize bool) error {
|
||||
log := logger.With("cmd", "escape")
|
||||
log.Info("Initializing clipboard...")
|
||||
if err := clip.Init(); err != nil {
|
||||
return fmt.Errorf("initialize clipboard: %w", err)
|
||||
}
|
||||
|
||||
log.Info("Reading text from clipboard...")
|
||||
clipboardContent := clip.Read(clip.FmtText)
|
||||
inputText := string(clipboardContent)
|
||||
log.Info("Read characters from clipboard", "count", len(inputText))
|
||||
log.Debug("Original text", "text", inputText)
|
||||
|
||||
escapedText := escapeText(inputText, minimize)
|
||||
|
||||
log.Info("Escaping regex special characters...")
|
||||
log.Info("Escaped characters", "count", len(escapedText))
|
||||
log.Debug("Escaped text", "text", escapedText)
|
||||
|
||||
log.Info("Writing escaped text back to clipboard...")
|
||||
if clip.Write(clip.FmtText, []byte(escapedText)) == nil {
|
||||
return fmt.Errorf("clipboard write failed for %d bytes: clipboard backend returned nil channel", len(escapedText))
|
||||
}
|
||||
log.Info("Successfully wrote escaped text to clipboard")
|
||||
return nil
|
||||
}
|
||||
|
||||
func escapeText(inputText string, minimize bool) string {
|
||||
var escapedText string
|
||||
if minimize {
|
||||
re := regexp.MustCompile(`([ \t]+)|([^ \t]+)`)
|
||||
var out []byte
|
||||
for _, m := range re.FindAllStringSubmatch(inputText, -1) {
|
||||
if m[1] != "" {
|
||||
out = append(out, `\s*`...)
|
||||
} else {
|
||||
out = append(out, regexp.QuoteMeta(m[2])...)
|
||||
}
|
||||
}
|
||||
escapedText = string(out)
|
||||
} else {
|
||||
escapedText = regexp.QuoteMeta(inputText)
|
||||
}
|
||||
return escapedText
|
||||
}
|
||||
@@ -0,0 +1,607 @@
|
||||
# File-level before_each / after_each run around every command that does not
|
||||
# set its own, in the command's Lua state. cook_hooks.toml (via --hooks) wraps
|
||||
# all commands across cook files the same way.
|
||||
before_each = '''
|
||||
local function clamp(val, lo, hi)
|
||||
if val < lo then return lo end
|
||||
if val > hi then return hi end
|
||||
return val
|
||||
end
|
||||
'''
|
||||
|
||||
after_each = '''
|
||||
print("finished command: " .. tostring(command_name))
|
||||
'''
|
||||
|
||||
# File-level `files` applies to every command that omits its own.
|
||||
files = ['defaults/*.cfg']
|
||||
|
||||
|
||||
# --- regex mode (default) ---
|
||||
|
||||
[[commands]]
|
||||
name = 'Bump default port'
|
||||
regex = 'port = !num'
|
||||
lua = 'v1 = v1 + 1'
|
||||
|
||||
# !num expands to a numeric capture; v1..vN are the unnamed groups as numbers.
|
||||
[[commands]]
|
||||
name = 'Double crafting time'
|
||||
regex = 'craftTime = !num'
|
||||
lua = 'v1 = v1 * 2'
|
||||
files = ['Data\Config\recipes.xml']
|
||||
|
||||
[[commands]]
|
||||
name = 'Swap min/max health'
|
||||
regex = '''
|
||||
minHealth = !num
|
||||
maxHealth = !num
|
||||
'''
|
||||
lua = 'v1, v2 = v2, v1'
|
||||
files = ['Data\Config\items.xml']
|
||||
|
||||
# (?P<name>...) groups become Lua variables; only changed groups are rewritten.
|
||||
[[commands]]
|
||||
name = 'Bump patch version'
|
||||
regex = 'version = (?P<major>!num)\\.(?P<minor>!num)\\.(?P<patch>!num)'
|
||||
lua = 'patch = patch + 1'
|
||||
files = ['config/version.txt']
|
||||
|
||||
[[commands]]
|
||||
name = 'Fill local YAML placeholders'
|
||||
regex = '''
|
||||
datasource:
|
||||
username: (DEV_USER)
|
||||
password: (DEV_PASS)
|
||||
'''
|
||||
lua = '''
|
||||
s1 = "localuser"
|
||||
s2 = "localpass"
|
||||
'''
|
||||
files = ['config/application-local.yaml']
|
||||
|
||||
# Empty capture () marks an insertion point; s1 = [[...]] for multiline text.
|
||||
[[commands]]
|
||||
name = 'gen_compose_add_bind_mount_1'
|
||||
regex = '''
|
||||
services:
|
||||
app:
|
||||
volumes:
|
||||
- \./src:/app/src
|
||||
() - app_logs:/var/log/app
|
||||
'''
|
||||
lua = '''
|
||||
s1 = [[ - ./local-data:/app/data
|
||||
]]
|
||||
'''
|
||||
files = ['deploy/docker-compose.yaml']
|
||||
noreset = false
|
||||
|
||||
[[commands]]
|
||||
name = 'gen_dockerfile_inject_copy_1'
|
||||
regex = '''
|
||||
WORKDIR /app
|
||||
()RUN apt-get update
|
||||
'''
|
||||
lua = '''
|
||||
s1 = [[COPY local-data/ /app/local-data/
|
||||
]]
|
||||
'''
|
||||
files = ['deploy/Dockerfile']
|
||||
noreset = false
|
||||
|
||||
# (?-s) keeps `.` from spanning newlines inside one long line.
|
||||
[[commands]]
|
||||
name = 'gen_env_replace_secret_1'
|
||||
regex = '(?-s)API_TOKEN=.+?"(REPLACE_ME)"'
|
||||
lua = 's1 = "dev-token-value"'
|
||||
files = ['.env']
|
||||
noreset = false
|
||||
|
||||
[[commands]]
|
||||
name = 'gen_add_import_1'
|
||||
regex = '''
|
||||
import com\.example\.common\.Alpha;
|
||||
()import com\.example\.common\.Beta;
|
||||
'''
|
||||
lua = '''
|
||||
s1 = [[import com.example.config.Profile;
|
||||
]]
|
||||
'''
|
||||
files = ['src/main/java/com/example/app/Bootstrap.java']
|
||||
noreset = false
|
||||
|
||||
# Ordered gen_* steps on one file; the follow-up keeps noreset = false.
|
||||
[[commands]]
|
||||
name = 'gen_lua_spell_guard_1'
|
||||
regex = '()-- spell gate'
|
||||
lua = '''
|
||||
s1 = [[local seen = {}
|
||||
local function mark(id) seen[id] = true end
|
||||
|
||||
]]
|
||||
'''
|
||||
files = ['game/scripts/spell_gate.lua']
|
||||
|
||||
[[commands]]
|
||||
name = 'gen_lua_spell_guard_2'
|
||||
regex = '''
|
||||
if banned\[id\] then return false end
|
||||
() if not allowed\[id\] then
|
||||
'''
|
||||
lua = '''
|
||||
s1 = [[ if seen[id] then return false end
|
||||
]]
|
||||
'''
|
||||
files = ['game/scripts/spell_gate.lua']
|
||||
noreset = false
|
||||
|
||||
# regexes: several patterns share one Lua transform. '*' is shorthand for
|
||||
# v1 = v1 * 2. loglevel overrides the command's log verbosity.
|
||||
[[commands]]
|
||||
name = 'Scale numeric tuning keys'
|
||||
regexes = [
|
||||
'powerPerTick = !num',
|
||||
'drainPerSecond = !num',
|
||||
]
|
||||
lua = '* 2'
|
||||
files = ['mods/**/balance.toml']
|
||||
loglevel = 'DEBUG'
|
||||
|
||||
# isolate runs the command in its own pass before regular commands.
|
||||
[[commands]]
|
||||
name = 'Uppercase marked region'
|
||||
regex = '''MARK_START
|
||||
(?P<chunk>!any)
|
||||
MARK_END'''
|
||||
lua = 'chunk = string.upper(chunk); return true'
|
||||
files = ['notes/*.txt']
|
||||
isolate = true
|
||||
|
||||
# replacement replaces the whole match instead of individual captures.
|
||||
[[commands]]
|
||||
name = 'Advance copyright year'
|
||||
regex = 'Copyright (?P<year>\d{4})'
|
||||
lua = 'replacement = "Copyright " .. (year + 1)'
|
||||
files = ['src/**/*.{js,py}']
|
||||
|
||||
# !rep(pattern, n) repeats a sub-pattern; the outer capture takes the result.
|
||||
[[commands]]
|
||||
name = 'Uppercase MAC addresses'
|
||||
regex = '(!rep([0-9a-f]{2}, 6))'
|
||||
lua = 's1 = string.upper(s1)'
|
||||
files = ['config/network.txt']
|
||||
|
||||
# nodedup keeps nested capture groups that overlap an outer one.
|
||||
[[commands]]
|
||||
name = 'Tighten nested match'
|
||||
regex = '((?P<name>\\w+) = (?P<amount>!num))'
|
||||
lua = 'name = string.upper(name); amount = amount * 2'
|
||||
files = ['config/tuning.txt']
|
||||
nodedup = true
|
||||
|
||||
# regex_pred: the command only runs when the file content matches the pattern.
|
||||
[[commands]]
|
||||
name = 'Pin staging-only image tag'
|
||||
regex = 'image = "registry.example/app:(!any)"'
|
||||
regex_pred = 'STAGING_ONLY'
|
||||
lua = 's1 = "latest"'
|
||||
files = ['deploy/staging/*.yaml']
|
||||
|
||||
# regex_preds: OR semantics, runs when any pattern matches.
|
||||
[[commands]]
|
||||
name = 'Append debug endpoint'
|
||||
regex = 'endpoint = "(!any)"'
|
||||
regex_preds = ['ENABLE_DEBUG', 'DEBUG_MODE']
|
||||
lua = 's1 = s1 .. "/debug"'
|
||||
files = ['config/*.json']
|
||||
|
||||
# return false skips this match (the wrapper sets `modified` from the return).
|
||||
[[commands]]
|
||||
name = 'Scale only small values'
|
||||
regex = 'capacity = !num'
|
||||
lua = '''
|
||||
if v1 > 100 then
|
||||
return false
|
||||
end
|
||||
v1 = v1 * 2
|
||||
'''
|
||||
files = ['Data\Config\items.xml']
|
||||
|
||||
# lua = '@path' loads an external script relative to the cook file.
|
||||
[[commands]]
|
||||
name = 'Bump version via external script'
|
||||
regex = 'version = "!any"'
|
||||
lua = '@scripts/bump_version.lua'
|
||||
files = ['src/version.txt']
|
||||
|
||||
# disable skips the command at load time.
|
||||
[[commands]]
|
||||
name = 'Disabled experiment'
|
||||
regex = 'experiment = !num'
|
||||
lua = 'v1 = v1 * 100'
|
||||
files = ['notes/*.txt']
|
||||
disable = true
|
||||
|
||||
|
||||
# --- json mode (json = true) ---
|
||||
|
||||
[[commands]]
|
||||
name = 'Force feature on in JSON'
|
||||
json = true
|
||||
lua = '''
|
||||
if data.features then
|
||||
data.features.core = true
|
||||
modified = true
|
||||
end
|
||||
'''
|
||||
files = ['config/**/*.json']
|
||||
|
||||
# Values are plain Lua values; setting a key to nil removes it.
|
||||
[[commands]]
|
||||
name = 'Retune and prune JSON'
|
||||
json = true
|
||||
lua = '''
|
||||
data.retries = data.retries + 1
|
||||
data.enabled = true
|
||||
data.deprecated = nil
|
||||
modified = true
|
||||
'''
|
||||
files = ['config/app.json']
|
||||
|
||||
[[commands]]
|
||||
name = 'Double all item quantities'
|
||||
json = true
|
||||
lua = '''
|
||||
for _, item in ipairs(json.jpath(data, "$.items[*]")) do
|
||||
item.qty = item.qty * 2
|
||||
end
|
||||
modified = true
|
||||
'''
|
||||
files = ['config/**/*.json']
|
||||
|
||||
# json.jpathrm removes matched nodes and returns how many were removed.
|
||||
[[commands]]
|
||||
name = 'Drop obsolete keys'
|
||||
json = true
|
||||
lua = '''
|
||||
local removed = json.jpathrm(data, "$.obsolete")
|
||||
print("removed " .. tostring(removed) .. " obsolete key")
|
||||
modified = true
|
||||
'''
|
||||
files = ['config/app.json']
|
||||
|
||||
[[commands]]
|
||||
name = 'Migrate and bump JSON'
|
||||
json = true
|
||||
lua = '''
|
||||
json.modifyNumbers(data, function(v, key, parent)
|
||||
return key == "price"
|
||||
end, function(v)
|
||||
return math.round(v * 1.1, 2)
|
||||
end)
|
||||
for _, v in ipairs(json.find(data, function(value, key, parent)
|
||||
return key == "oldField"
|
||||
end)) do
|
||||
v = "migrated"
|
||||
end
|
||||
json.visit(data, function(value, key, parent)
|
||||
if type(value) == "table" and key and next(value) == nil then
|
||||
print("empty container: " .. tostring(key))
|
||||
end
|
||||
end)
|
||||
modified = true
|
||||
'''
|
||||
files = ['config/app.json']
|
||||
|
||||
# json.read parses a sibling file, resolved relative to the file being edited.
|
||||
[[commands]]
|
||||
name = 'Stamp imported source'
|
||||
json = true
|
||||
lua = '''
|
||||
local other = json.read("config/source.json")
|
||||
if other then
|
||||
data.importedFrom = other.source
|
||||
modified = true
|
||||
end
|
||||
'''
|
||||
files = ['config/app.json']
|
||||
|
||||
# raw = true alongside json = true keeps every value as a literal string
|
||||
# with no automatic number coercion; N() converts explicitly.
|
||||
[[commands]]
|
||||
name = 'Double port raw'
|
||||
json = true
|
||||
raw = true
|
||||
lua = '''
|
||||
data.port = data.port * 2
|
||||
modified = true
|
||||
'''
|
||||
files = ['config/raw.json']
|
||||
|
||||
|
||||
# --- xml mode (xml = true) ---
|
||||
|
||||
[[commands]]
|
||||
name = 'Faster crafting'
|
||||
xml = true
|
||||
lua = '''
|
||||
local craftTimeDivisor = 2
|
||||
local recipesWithTime = xml.xpath(data, "//recipe[@craft_time]")
|
||||
for _, recipeNode in pairs(recipesWithTime) do
|
||||
recipeNode.attr.craft_time = N(recipeNode.attr.craft_time) / craftTimeDivisor
|
||||
end
|
||||
'''
|
||||
files = ['Data\Config\recipes.xml']
|
||||
|
||||
[[commands]]
|
||||
name = 'More max bleed counter'
|
||||
xml = true
|
||||
lua = '''
|
||||
local maxBleedCounterMultiplier = 3
|
||||
local maxBleedSets =
|
||||
xml.xpath(data, "//triggered_effect[@action='ModifyCVar' and @cvar='$maxBleedCounter' and @operation='set' and @value]")
|
||||
for _, triggeredEffectNode in pairs(maxBleedSets) do
|
||||
triggeredEffectNode.attr.value = triggeredEffectNode.attr.value * maxBleedCounterMultiplier
|
||||
end
|
||||
'''
|
||||
files = ['Data\Config\buffs.xml']
|
||||
|
||||
[[commands]]
|
||||
name = 'More kill xp'
|
||||
xml = true
|
||||
lua = '''
|
||||
local zombieXpProperties = xml.xpath(data, "//replace_properties/property[starts-with(@name,'xp') and @value]")
|
||||
for _, xpPropertyNode in pairs(zombieXpProperties) do
|
||||
xpPropertyNode.attr.value = N(xpPropertyNode.attr.value) * 4
|
||||
end
|
||||
'''
|
||||
files = ['Data\Config\entityclasses.xml']
|
||||
|
||||
# Attributes are plain string values; N() converts them for arithmetic.
|
||||
[[commands]]
|
||||
name = 'More container loot'
|
||||
xml = true
|
||||
lua = '''
|
||||
local lootMultiplier = 2
|
||||
|
||||
local function multiplyCountAttribute(node, attributeName, multiplier)
|
||||
local attribute = node.attr[attributeName]
|
||||
if attribute == nil then
|
||||
return
|
||||
end
|
||||
|
||||
local countValue = attribute
|
||||
local countParts = string.split(tostring(countValue), ",")
|
||||
if countParts ~= nil and #countParts == 2 then
|
||||
local minCountText = string.trim(countParts[1])
|
||||
local maxCountText = string.trim(countParts[2])
|
||||
attribute = tostring(N(minCountText) * multiplier)
|
||||
.. ","
|
||||
.. tostring(N(maxCountText) * multiplier)
|
||||
return
|
||||
end
|
||||
|
||||
local countNumber = N(countValue)
|
||||
if countNumber ~= nil then
|
||||
attribute = countNumber * multiplier
|
||||
end
|
||||
end
|
||||
|
||||
local lootContainersWithCount = xml.xpath(data, "//lootcontainer[@count]")
|
||||
for _, lootContainerNode in pairs(lootContainersWithCount) do
|
||||
multiplyCountAttribute(lootContainerNode, "count", lootMultiplier)
|
||||
end
|
||||
|
||||
local lootItemsWithCount = xml.xpath(data, "//lootgroup/item[@count]")
|
||||
for _, lootItemNode in pairs(lootItemsWithCount) do
|
||||
multiplyCountAttribute(lootItemNode, "count", lootMultiplier)
|
||||
end
|
||||
'''
|
||||
files = ['Data\Config\loot.xml']
|
||||
|
||||
[[commands]]
|
||||
name = 'Strip debug elements'
|
||||
xml = true
|
||||
lua = '''
|
||||
local removed = xml.xpathrm(data, "//debug")
|
||||
print("removed " .. tostring(removed) .. " debug nodes")
|
||||
modified = true
|
||||
'''
|
||||
files = ['Data\Config\buffs.xml']
|
||||
|
||||
# Attributes and text are plain values in every XML command.
|
||||
[[commands]]
|
||||
name = 'Normalize XML with helper API'
|
||||
xml = true
|
||||
lua = '''
|
||||
xml.visit(data, function(node, depth, path)
|
||||
if xml.hasAttr(node, "price") then
|
||||
xml.modifyNumAttr(node, "price", function(v) return math.round(v * 1.1, 2) end)
|
||||
end
|
||||
end)
|
||||
for _, item in ipairs(xml.filter(data, function(node)
|
||||
return xml.getAttr(node, "class") == "rework"
|
||||
end)) do
|
||||
xml.setAttr(item, "class", "reworked")
|
||||
xml.setNumAttr(item, "revision", (xml.getNumAttr(item, "revision") or 0) + 1)
|
||||
end
|
||||
print("items: " .. #xml.find(data, "item"))
|
||||
local firstEntry = xml.findFirst(data, "entry")
|
||||
if firstEntry and xml.getText(firstEntry) == "old" then
|
||||
xml.setText(firstEntry, "new")
|
||||
end
|
||||
print("entries: " .. #xml.getChildren(data, "entry") .. " / count: " .. xml.countChildren(data, "entry"))
|
||||
print("removed " .. xml.removeChildren(data, "obsolete") .. " obsolete nodes")
|
||||
xml.addChild(data, { tag = "footer", attr = { version = "2" }, text = "generated" })
|
||||
modified = true
|
||||
'''
|
||||
files = ['Data\Config\buffs.xml']
|
||||
|
||||
# Mutating data.children adds/removes/renames elements; new nodes are
|
||||
# serialized from the Lua table. Namespace info lives in name.local/uri/prefix.
|
||||
[[commands]]
|
||||
name = 'Reorganize XML children'
|
||||
xml = true
|
||||
lua = '''
|
||||
local root = data
|
||||
print("root: " .. tostring(root.tag) .. " ns=" .. tostring(root.name.uri))
|
||||
for i = #root.children, 1, -1 do
|
||||
if root.children[i].tag == "obsolete" then
|
||||
table.remove(root.children, i)
|
||||
end
|
||||
end
|
||||
for _, node in pairs(xml.xpath(root, ".//renameme")) do
|
||||
node.name.local = "renamed"
|
||||
end
|
||||
table.insert(root.children, {
|
||||
tag = "footer",
|
||||
attr = { version = "2" },
|
||||
text = "appended",
|
||||
})
|
||||
modified = true
|
||||
'''
|
||||
files = ['Data\Config\blocks.xml']
|
||||
|
||||
[[commands]]
|
||||
name = 'Copy banner from template'
|
||||
xml = true
|
||||
lua = '''
|
||||
local other = xml.read("templates/banner.xml")
|
||||
if other then
|
||||
local banner = xml.findFirst(other, "banner")
|
||||
if banner then
|
||||
table.insert(data.children, banner)
|
||||
modified = true
|
||||
end
|
||||
end
|
||||
'''
|
||||
files = ['docs/*.xml']
|
||||
|
||||
|
||||
# --- raw mode (raw = true alone): whole file is the `data` string ---
|
||||
|
||||
[[commands]]
|
||||
name = 'Prepend license header'
|
||||
raw = true
|
||||
lua = [[
|
||||
data = "# Copyright 2025 Acme Corp\n# License: MIT\n" .. data
|
||||
modified = true
|
||||
]]
|
||||
files = ['src/**/*.py']
|
||||
|
||||
[[commands]]
|
||||
name = 'Mark up prices in CSV'
|
||||
raw = true
|
||||
lua = '''
|
||||
local rows = csv.read(data, { hasheader = true })
|
||||
for _, row in ipairs(rows) do
|
||||
row.Price = math.round(util.num(row.Price) * 1.1, 2)
|
||||
end
|
||||
data = csv.write(rows, { hasheader = true })
|
||||
modified = true
|
||||
'''
|
||||
files = ['data/*.csv']
|
||||
|
||||
|
||||
# --- lua runtime ---
|
||||
|
||||
# ctx (ctx.source_file / ctx.target_file / ctx.command_name / ctx.capture),
|
||||
# file, and command_name are available in every command.
|
||||
[[commands]]
|
||||
name = 'Report file metadata'
|
||||
raw = true
|
||||
lua = '''
|
||||
print("source_file: " .. tostring(ctx.source_file))
|
||||
print("target_file: " .. tostring(ctx.target_file) .. " (also: " .. tostring(file) .. ")")
|
||||
print("command: " .. tostring(ctx.command_name) .. " (also: " .. tostring(command_name) .. ")")
|
||||
return false
|
||||
'''
|
||||
files = ['notes/**/*.txt']
|
||||
|
||||
# ctx.capture mirrors the regex capture globals as table fields.
|
||||
[[commands]]
|
||||
name = 'Halve weight via ctx.capture'
|
||||
regex = 'weight = !num'
|
||||
lua = 'v1 = ctx.capture.v1 * 0.5'
|
||||
files = ['config/*.txt']
|
||||
|
||||
# clone(node) deep-copies a node; edits to the copy do not affect the source.
|
||||
[[commands]]
|
||||
name = 'Deep-copy config block'
|
||||
json = true
|
||||
lua = '''
|
||||
local draft = clone(data)
|
||||
draft.items[#draft.items + 1] = { name = "extra", qty = 1 }
|
||||
data = draft
|
||||
modified = true
|
||||
'''
|
||||
files = ['config/app.json']
|
||||
|
||||
[[commands]]
|
||||
name = 'Stamp upstream health'
|
||||
raw = true
|
||||
lua = '''
|
||||
local resp = fetch("https://example.com/api/health")
|
||||
if resp and resp.ok then
|
||||
data = data .. "\n# upstream: " .. tostring(resp.status)
|
||||
modified = true
|
||||
end
|
||||
'''
|
||||
files = ['notes/health.txt']
|
||||
|
||||
# re(pattern, input) runs a Go regex from Lua; no chef placeholders inside.
|
||||
[[commands]]
|
||||
name = 'Bump version via re'
|
||||
raw = true
|
||||
lua = '''
|
||||
local m = re("(version = )([0-9]+)", data)
|
||||
if m then
|
||||
data = string.gsub(data, m[1], m[2] .. tostring(N(m[3]) + 1), 1)
|
||||
modified = true
|
||||
end
|
||||
'''
|
||||
files = ['src/version.txt']
|
||||
|
||||
[[commands]]
|
||||
name = 'Debug JSON with util.dump'
|
||||
json = true
|
||||
lua = '''
|
||||
util.printf("items is array: %s", tostring(util.isArray(data.items)))
|
||||
util.printf("isNumber('42') = %s, str(3.14) = %s", tostring(util.isNumber("42")), util.str(3.14))
|
||||
util.dump(data)
|
||||
return false
|
||||
'''
|
||||
files = ['config/app.json']
|
||||
|
||||
|
||||
# --- hooks ---
|
||||
|
||||
# The clamp helper below comes from the file-level before_each above.
|
||||
[[commands]]
|
||||
name = 'Clamp crafting time'
|
||||
xml = true
|
||||
lua = '''
|
||||
local recipes = xml.xpath(data, "//recipe[@craft_time]")
|
||||
for _, r in pairs(recipes) do
|
||||
r.attr.craft_time = clamp(N(r.attr.craft_time), 1, 60)
|
||||
end
|
||||
'''
|
||||
files = ['Data\Config\recipes.xml']
|
||||
|
||||
[[commands]]
|
||||
name = 'Clamp stack size'
|
||||
regex = '<stacksize>(\d+)</stacksize>'
|
||||
lua = 'v1 = clamp(v1, 1, 999)'
|
||||
files = ['Data\Config\items.xml']
|
||||
|
||||
# A command with its own before_each/after_each overrides the file-level ones.
|
||||
[[commands]]
|
||||
name = 'Clamp respawn time (per-command hook)'
|
||||
regex = 'respawnTime = !num'
|
||||
before_each = '''
|
||||
local function clampTo(v, hi) if v > hi then return hi end return v end
|
||||
'''
|
||||
after_each = 'print("respawn clamp done")'
|
||||
lua = 'v1 = clampTo(v1, 60)'
|
||||
files = ['Data\Config\gamestages.xml']
|
||||
@@ -0,0 +1,105 @@
|
||||
package chef
|
||||
|
||||
import (
|
||||
"bytes"
|
||||
"fmt"
|
||||
"log/slog"
|
||||
"os"
|
||||
"os/exec"
|
||||
"regexp"
|
||||
"strings"
|
||||
|
||||
logger "git.site.quack-lab.dev/dave/cylogger/v3"
|
||||
)
|
||||
|
||||
var luaMultilineBlock = regexp.MustCompile("(?s)lua = '''\r?\n(.*?)\r?\n'''")
|
||||
|
||||
func FormatTomlPaths(paths []string) error {
|
||||
log := logger.With("cmd", "fmt")
|
||||
log.Info("Formatting files", "count", len(paths))
|
||||
for i := 0; i < len(paths); i++ {
|
||||
path := paths[i]
|
||||
flog := log.With("target", path)
|
||||
flog.Debug("Formatting", "idx", i+1, "total", len(paths))
|
||||
if err := formatLuaBlocksInTOML(path, flog); err != nil {
|
||||
return err
|
||||
}
|
||||
}
|
||||
return nil
|
||||
}
|
||||
|
||||
func formatLuaBlocksInTOML(path string, flog *slog.Logger) error {
|
||||
contentBytes, err := os.ReadFile(path)
|
||||
if err != nil {
|
||||
return fmt.Errorf("failed to read %s: %w", path, err)
|
||||
}
|
||||
content := string(contentBytes)
|
||||
|
||||
newContent, matchCount, err := formatLuaMatches(content)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
|
||||
if newContent == content {
|
||||
flog.Debug("No changes needed")
|
||||
return nil
|
||||
}
|
||||
|
||||
if err := os.WriteFile(path, []byte(newContent), 0644); err != nil {
|
||||
return fmt.Errorf("failed to write %s: %w", path, err)
|
||||
}
|
||||
flog.Info("Formatted Lua blocks", "count", matchCount)
|
||||
return nil
|
||||
}
|
||||
|
||||
// formatLuaMatches rewrites every Lua block in the TOML content and returns
|
||||
// the result plus how many blocks were found.
|
||||
func formatLuaMatches(content string) (string, int, error) {
|
||||
matches := luaMultilineBlock.FindAllStringSubmatchIndex(content, -1)
|
||||
if len(matches) == 0 {
|
||||
return content, 0, nil
|
||||
}
|
||||
|
||||
var out strings.Builder
|
||||
out.Grow(len(content) + 128)
|
||||
|
||||
lastEnd := 0
|
||||
for i := 0; i < len(matches); i++ {
|
||||
m := matches[i]
|
||||
if len(m) < 4 {
|
||||
return "", 0, fmt.Errorf("internal error: unexpected regex match shape")
|
||||
}
|
||||
|
||||
codeStart, codeEnd := m[2], m[3]
|
||||
if codeStart < 0 || codeEnd < 0 {
|
||||
return "", 0, fmt.Errorf("internal error: missing capture ranges")
|
||||
}
|
||||
|
||||
code := content[codeStart:codeEnd]
|
||||
formatted, err := styluaFormat(code)
|
||||
if err != nil {
|
||||
return "", 0, err
|
||||
}
|
||||
formatted = strings.TrimRight(formatted, "\r\n")
|
||||
|
||||
out.WriteString(content[lastEnd:codeStart])
|
||||
out.WriteString(formatted)
|
||||
lastEnd = codeEnd
|
||||
}
|
||||
out.WriteString(content[lastEnd:])
|
||||
|
||||
return out.String(), len(matches), nil
|
||||
}
|
||||
|
||||
func styluaFormat(code string) (string, error) {
|
||||
cmd := exec.Command("stylua", "-")
|
||||
cmd.Stdin = strings.NewReader(code)
|
||||
var stdout bytes.Buffer
|
||||
var stderr bytes.Buffer
|
||||
cmd.Stdout = &stdout
|
||||
cmd.Stderr = &stderr
|
||||
if err := cmd.Run(); err != nil {
|
||||
return "", fmt.Errorf("stylua error:\n%s", strings.TrimRight(stderr.String(), "\n"))
|
||||
}
|
||||
return stdout.String(), nil
|
||||
}
|
||||
@@ -0,0 +1,60 @@
|
||||
package chef
|
||||
|
||||
import (
|
||||
"os"
|
||||
"os/exec"
|
||||
"path/filepath"
|
||||
"strings"
|
||||
"testing"
|
||||
|
||||
logger "git.site.quack-lab.dev/dave/cylogger/v3"
|
||||
"github.com/stretchr/testify/assert"
|
||||
"github.com/stretchr/testify/require"
|
||||
)
|
||||
|
||||
func TestMain(m *testing.M) {
|
||||
logger.Init(logger.LevelInfo, false)
|
||||
os.Exit(m.Run())
|
||||
}
|
||||
|
||||
func TestFormatTomlPaths(t *testing.T) {
|
||||
t.Run("unit/no_multiline_lua_blocks/file_unchanged", func(t *testing.T) {
|
||||
tmp := t.TempDir()
|
||||
path := filepath.Join(tmp, "test.toml")
|
||||
original := "[[commands]]\nname = 'x'\nlua = 'print(1)'\n"
|
||||
require.NoError(t, os.WriteFile(path, []byte(original), 0644))
|
||||
require.NoError(t, FormatTomlPaths([]string{path}))
|
||||
out, err := os.ReadFile(path)
|
||||
require.NoError(t, err)
|
||||
assert.Equal(t, original, string(out))
|
||||
})
|
||||
|
||||
t.Run("unit/multiline_lua_blocks/stylua_reformats", func(t *testing.T) {
|
||||
if _, err := exec.LookPath("stylua"); err != nil {
|
||||
t.Fatalf("stylua must be installed and on PATH: %v", err)
|
||||
}
|
||||
tmp := t.TempDir()
|
||||
path := filepath.Join(tmp, "test.toml")
|
||||
content := "[[commands]]\nname = 'x'\nlua = '''\nlocal x=1\nif x>0 then\nprint( x )\nend\n'''\n"
|
||||
require.NoError(t, os.WriteFile(path, []byte(content), 0644))
|
||||
require.NoError(t, FormatTomlPaths([]string{path}))
|
||||
out, err := os.ReadFile(path)
|
||||
require.NoError(t, err)
|
||||
text := string(out)
|
||||
assert.Contains(t, text, "local x = 1")
|
||||
assert.Contains(t, text, "if x > 0 then")
|
||||
assert.Contains(t, text, "print(x)")
|
||||
})
|
||||
|
||||
t.Run("unit/stylua_not_on_path/format_returns_error", func(t *testing.T) {
|
||||
origPath := os.Getenv("PATH")
|
||||
t.Setenv("PATH", "")
|
||||
if strings.Contains(strings.ToLower(os.Getenv("pathext")), ".exe") {
|
||||
t.Setenv("PATHEXT", ".EXE")
|
||||
}
|
||||
_, err := styluaFormat("local x = 1")
|
||||
require.Error(t, err)
|
||||
assert.Contains(t, err.Error(), "stylua error")
|
||||
t.Setenv("PATH", origPath)
|
||||
})
|
||||
}
|
||||
@@ -0,0 +1,202 @@
|
||||
package chef
|
||||
|
||||
import (
|
||||
"fmt"
|
||||
"io"
|
||||
"os"
|
||||
"path/filepath"
|
||||
"strconv"
|
||||
"strings"
|
||||
|
||||
"cook/utils"
|
||||
|
||||
logger "git.site.quack-lab.dev/dave/cylogger/v3"
|
||||
"github.com/atotto/clipboard"
|
||||
"github.com/bluekeyes/go-gitdiff/gitdiff"
|
||||
)
|
||||
|
||||
func GenerateCommandsTOMLFromClipboard(givenName string) (string, int, error) {
|
||||
diffText, err := clipboard.ReadAll()
|
||||
if err != nil {
|
||||
return "", 0, fmt.Errorf("failed to read clipboard: %w", err)
|
||||
}
|
||||
|
||||
commands, skipped, err := GenerateCommandsFromUnifiedDiffNamed(diffText, givenName)
|
||||
if err != nil {
|
||||
return "", skipped, err
|
||||
}
|
||||
|
||||
if len(commands) == 0 {
|
||||
return "", skipped, fmt.Errorf("no replaceable diff blocks found in clipboard")
|
||||
}
|
||||
|
||||
out, err := renderGeneratedCommandsTOML(commands)
|
||||
if err != nil {
|
||||
return "", skipped, err
|
||||
}
|
||||
|
||||
return out, skipped, nil
|
||||
}
|
||||
|
||||
func Gen(stdout, stderr io.Writer, args []string) error {
|
||||
givenName := ""
|
||||
if len(args) > 0 {
|
||||
givenName = strings.TrimSpace(args[0])
|
||||
}
|
||||
output, skipped, err := GenerateCommandsTOMLFromClipboard(givenName)
|
||||
if err != nil {
|
||||
return fmt.Errorf("failed to generate commands from clipboard diff: %w", err)
|
||||
}
|
||||
log := logger.With("cmd", "gen")
|
||||
log.Info("Generated commands from clipboard diff")
|
||||
if _, err := fmt.Fprint(stdout, output); err != nil {
|
||||
return err
|
||||
}
|
||||
if skipped > 0 {
|
||||
if _, err := fmt.Fprintf(stderr, "skipped %d insertion-only diff block(s)\n", skipped); err != nil {
|
||||
return err
|
||||
}
|
||||
}
|
||||
return nil
|
||||
}
|
||||
|
||||
func GenerateCommandsFromUnifiedDiff(diffText string) ([]utils.ModifyCommand, int, error) {
|
||||
return GenerateCommandsFromUnifiedDiffNamed(diffText, "")
|
||||
}
|
||||
|
||||
// GenerateCommandsFromUnifiedDiffNamed converts a unified diff into ModifyCommands.
|
||||
// givenName, when non-empty, is prepended to each generated command name.
|
||||
// Target file content is loaded from the snapshot database when a snapshot
|
||||
// exists (the pristine source we patch against), falling back to disk.
|
||||
func GenerateCommandsFromUnifiedDiffNamed(diffText, givenName string) ([]utils.ModifyCommand, int, error) {
|
||||
return generateCommandsFromUnifiedDiff(diffText, givenName, loadPristineFileContent)
|
||||
}
|
||||
|
||||
// generateCommandsFromUnifiedDiff is the pure transform. loadContent returns
|
||||
// the pristine source bytes for a target file (nil when unavailable), which is
|
||||
// used to trim regex context to the shortest still-unique pattern.
|
||||
func generateCommandsFromUnifiedDiff(diffText, givenName string, loadContent func(string) []byte) ([]utils.ModifyCommand, int, error) {
|
||||
files, _, err := gitdiff.Parse(strings.NewReader(normalizeNewlines(diffText)))
|
||||
if err != nil {
|
||||
return nil, 0, fmt.Errorf("failed to parse unified diff: %w", err)
|
||||
}
|
||||
|
||||
commands := make([]utils.ModifyCommand, 0)
|
||||
skippedInsertionOnly := 0
|
||||
perFileCounter := make(map[string]int)
|
||||
|
||||
for _, fileDiff := range files {
|
||||
filePath := diffFilePath(fileDiff)
|
||||
if filePath == "" {
|
||||
continue
|
||||
}
|
||||
content := loadContent(filePath)
|
||||
for _, fragment := range fileDiff.TextFragments {
|
||||
chunks, skipped := extractDiffChunksFromFragment(fragment)
|
||||
skippedInsertionOnly += skipped
|
||||
for _, chunk := range chunks {
|
||||
commands = append(commands, buildGeneratedCommand(filePath, chunk, perFileCounter, content, givenName))
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
return commands, skippedInsertionOnly, nil
|
||||
}
|
||||
|
||||
// buildGeneratedCommand converts one diff chunk into a ModifyCommand.
|
||||
func buildGeneratedCommand(filePath string, chunk diffChunk, perFileCounter map[string]int, content []byte, givenName string) utils.ModifyCommand {
|
||||
oldBlock, newBlock := buildBlocks(chunk, content)
|
||||
perFileCounter[filePath]++
|
||||
return utils.ModifyCommand{
|
||||
Name: generateCommandName(filePath, perFileCounter[filePath], givenName),
|
||||
Regex: oldBlock,
|
||||
Lua: "s1 = [[" + newBlock + "]]",
|
||||
Files: []string{filePath},
|
||||
NoReset: false,
|
||||
}
|
||||
}
|
||||
|
||||
// loadPristineFileContent returns the pristine source of a target file: the
|
||||
// stored snapshot in the database when one exists, otherwise the file on disk.
|
||||
func loadPristineFileContent(filePath string) []byte {
|
||||
if content, ok := snapshotContent(filePath); ok {
|
||||
return content
|
||||
}
|
||||
content, _ := os.ReadFile(filePath)
|
||||
return content
|
||||
}
|
||||
|
||||
// snapshotContent looks up the stored file snapshot in the database.
|
||||
func snapshotContent(filePath string) ([]byte, bool) {
|
||||
var content []byte
|
||||
var found bool
|
||||
err := withSnapshotDB(func(db utils.DB) error {
|
||||
stored, err := db.GetFile(filePath)
|
||||
if err != nil {
|
||||
return nil
|
||||
}
|
||||
content = stored
|
||||
found = true
|
||||
return nil
|
||||
})
|
||||
if err != nil {
|
||||
return nil, false
|
||||
}
|
||||
return content, found
|
||||
}
|
||||
|
||||
// diffFilePath resolves the target path for a file diff, falling back to the
|
||||
// old name when the new name is empty.
|
||||
func diffFilePath(fileDiff *gitdiff.File) string {
|
||||
filePath := normalizeDiffPath(fileDiff.NewName)
|
||||
if filePath == "" {
|
||||
filePath = normalizeDiffPath(fileDiff.OldName)
|
||||
}
|
||||
return filePath
|
||||
}
|
||||
|
||||
func normalizeDiffPath(name string) string {
|
||||
trimmed := strings.TrimSpace(name)
|
||||
if isNullDiffPath(trimmed) {
|
||||
return ""
|
||||
}
|
||||
trimmed = strings.TrimPrefix(trimmed, "b/")
|
||||
trimmed = strings.TrimPrefix(trimmed, "a/")
|
||||
return filepath.ToSlash(trimmed)
|
||||
}
|
||||
|
||||
func isNullDiffPath(name string) bool {
|
||||
_, ok := nullDiffPaths[name]
|
||||
return ok
|
||||
}
|
||||
|
||||
var nullDiffPaths = map[string]struct{}{
|
||||
"": {},
|
||||
"/dev/null": {},
|
||||
"a/dev/null": {},
|
||||
"b/dev/null": {},
|
||||
}
|
||||
|
||||
func generateCommandName(path string, idx int, givenName string) string {
|
||||
name := filepath.Base(path)
|
||||
if givenName != "" {
|
||||
name = givenName + " " + name
|
||||
}
|
||||
name += " gen"
|
||||
if idx > 1 {
|
||||
name += " " + strconv.Itoa(idx)
|
||||
}
|
||||
return name
|
||||
}
|
||||
|
||||
func normalizeNewlines(s string) string {
|
||||
s = strings.ReplaceAll(s, "\r\n", "\n")
|
||||
s = strings.ReplaceAll(s, "\r", "\n")
|
||||
return s
|
||||
}
|
||||
|
||||
func normalizeDiffLine(s string) string {
|
||||
s = strings.TrimSuffix(s, "\n")
|
||||
s = strings.TrimSuffix(s, "\r")
|
||||
return s
|
||||
}
|
||||
@@ -0,0 +1,100 @@
|
||||
package chef
|
||||
|
||||
import "github.com/bluekeyes/go-gitdiff/gitdiff"
|
||||
|
||||
// diffChunk is one contiguous replace/insert block of a diff fragment,
|
||||
// together with the context lines that anchor it.
|
||||
type diffChunk struct {
|
||||
oldLines []string
|
||||
newLines []string
|
||||
preLines []string
|
||||
postLines []string
|
||||
mode chunkMode
|
||||
}
|
||||
|
||||
type chunkMode int
|
||||
|
||||
const (
|
||||
chunkReplaceOrDelete chunkMode = iota
|
||||
chunkInsertWithContext
|
||||
)
|
||||
|
||||
// extractDiffChunksFromFragment splits a diff fragment into anchored chunks,
|
||||
// skipping insertion-only blocks that have no context to anchor them. The
|
||||
// returned count is how many such blocks were skipped.
|
||||
func extractDiffChunksFromFragment(fragment *gitdiff.TextFragment) ([]diffChunk, int) {
|
||||
chunks := make([]diffChunk, 0)
|
||||
skippedInsertionOnly := 0
|
||||
for i := 0; i < len(fragment.Lines); i++ {
|
||||
if fragment.Lines[i].Op == gitdiff.OpContext {
|
||||
continue
|
||||
}
|
||||
|
||||
end := chunkEndIndex(fragment.Lines, i)
|
||||
chunk := collectChunkLines(fragment.Lines, i, end)
|
||||
chunk.preLines = collectPreLines(fragment.Lines, i)
|
||||
chunk.postLines = collectPostLines(fragment.Lines, end)
|
||||
|
||||
if setChunkMode(&chunk) {
|
||||
skippedInsertionOnly++
|
||||
continue
|
||||
}
|
||||
|
||||
chunks = append(chunks, chunk)
|
||||
i = end
|
||||
}
|
||||
|
||||
return chunks, skippedInsertionOnly
|
||||
}
|
||||
|
||||
func chunkEndIndex(lines []gitdiff.Line, start int) int {
|
||||
end := start
|
||||
for end+1 < len(lines) && lines[end+1].Op != gitdiff.OpContext {
|
||||
end++
|
||||
}
|
||||
return end
|
||||
}
|
||||
|
||||
func collectChunkLines(lines []gitdiff.Line, start, end int) diffChunk {
|
||||
chunk := diffChunk{}
|
||||
for j := start; j <= end; j++ {
|
||||
switch lines[j].Op {
|
||||
case gitdiff.OpDelete:
|
||||
chunk.oldLines = append(chunk.oldLines, normalizeDiffLine(lines[j].Line))
|
||||
case gitdiff.OpAdd:
|
||||
chunk.newLines = append(chunk.newLines, normalizeDiffLine(lines[j].Line))
|
||||
}
|
||||
}
|
||||
return chunk
|
||||
}
|
||||
|
||||
func collectPreLines(lines []gitdiff.Line, start int) []string {
|
||||
preLines := make([]string, 0)
|
||||
for j := start - 1; j >= 0 && lines[j].Op == gitdiff.OpContext; j-- {
|
||||
preLines = append([]string{normalizeDiffLine(lines[j].Line)}, preLines...)
|
||||
}
|
||||
return preLines
|
||||
}
|
||||
|
||||
func collectPostLines(lines []gitdiff.Line, end int) []string {
|
||||
postLines := make([]string, 0)
|
||||
for j := end + 1; j < len(lines) && lines[j].Op == gitdiff.OpContext; j++ {
|
||||
postLines = append(postLines, normalizeDiffLine(lines[j].Line))
|
||||
}
|
||||
return postLines
|
||||
}
|
||||
|
||||
// setChunkMode classifies a chunk: replacement/deletion when it has old lines,
|
||||
// insertion anchored by context otherwise. A chunk with no old lines and no
|
||||
// context at all is unanchored; setChunkMode reports that it must be skipped.
|
||||
func setChunkMode(chunk *diffChunk) bool {
|
||||
if len(chunk.oldLines) == 0 {
|
||||
if len(chunk.preLines) == 0 && len(chunk.postLines) == 0 {
|
||||
return true
|
||||
}
|
||||
chunk.mode = chunkInsertWithContext
|
||||
} else {
|
||||
chunk.mode = chunkReplaceOrDelete
|
||||
}
|
||||
return false
|
||||
}
|
||||
@@ -0,0 +1,125 @@
|
||||
package chef
|
||||
|
||||
import (
|
||||
"regexp"
|
||||
"strings"
|
||||
)
|
||||
|
||||
// buildBlocks builds the (regex, replacement) pair for one diff chunk.
|
||||
func buildBlocks(chunk diffChunk, content []byte) (string, string) {
|
||||
switch chunk.mode {
|
||||
case chunkInsertWithContext:
|
||||
regex := buildMinimalPattern(chunk.preLines, "", chunk.postLines, true, content)
|
||||
replacement := strings.Join(chunk.newLines, "\n")
|
||||
if len(chunk.postLines) > 0 {
|
||||
replacement += "\n"
|
||||
}
|
||||
return regex, replacement
|
||||
default:
|
||||
regex := buildMinimalPattern(chunk.preLines, strings.Join(chunk.oldLines, "\n"), chunk.postLines, false, content)
|
||||
return regex, strings.Join(chunk.newLines, "\n")
|
||||
}
|
||||
}
|
||||
|
||||
// buildMinimalPattern builds the regex that uniquely matches the target block,
|
||||
// trimming top/bottom context lines to the shortest still-unique pattern.
|
||||
//
|
||||
// The floor keeps at least one line of context on each side (when available),
|
||||
// so a zero-context / single-anchor-line regex is never produced even when it
|
||||
// would uniquely match today. Every (top_trim, bottom_trim) combination up to
|
||||
// the available context is brute-forced; only patterns that match the target
|
||||
// file exactly once, at the target location, are accepted. The full-context
|
||||
// pattern is the fallback when the file is unreadable or nothing smaller is
|
||||
// unique.
|
||||
func buildMinimalPattern(preLines []string, captureText string, postLines []string, emptyCapture bool, content []byte) string {
|
||||
full := buildPatternWithContext(preLines, captureText, postLines, emptyCapture)
|
||||
target, ok := uniqueTargetSpan(full, content)
|
||||
if !ok {
|
||||
return full
|
||||
}
|
||||
targetStart, targetEnd := target[0], target[1]
|
||||
|
||||
best := full
|
||||
maxTrimTop := max(0, len(preLines)-1)
|
||||
maxTrimBottom := max(0, len(postLines)-1)
|
||||
for top := 0; top <= maxTrimTop; top++ {
|
||||
for bottom := 0; bottom <= maxTrimBottom; bottom++ {
|
||||
candidate := buildPatternWithContext(preLines[top:], captureText, postLines[:len(postLines)-bottom], emptyCapture)
|
||||
if len(candidate) < len(best) && candidateUnique(candidate, content, targetStart, targetEnd) {
|
||||
best = candidate
|
||||
}
|
||||
}
|
||||
}
|
||||
return best
|
||||
}
|
||||
|
||||
// uniqueTargetSpan returns the single match span of pattern in content, or
|
||||
// ok=false when content is empty, the pattern is invalid, or the pattern
|
||||
// matches zero or multiple times.
|
||||
func uniqueTargetSpan(pattern string, content []byte) (span [2]int, ok bool) {
|
||||
if len(content) == 0 {
|
||||
return [2]int{}, false
|
||||
}
|
||||
re, err := regexp.Compile(pattern)
|
||||
if err != nil {
|
||||
return [2]int{}, false
|
||||
}
|
||||
matches := re.FindAllIndex(content, -1)
|
||||
if len(matches) != 1 {
|
||||
return [2]int{}, false
|
||||
}
|
||||
return [2]int{matches[0][0], matches[0][1]}, true
|
||||
}
|
||||
|
||||
// candidateUnique reports whether candidate matches content exactly once,
|
||||
// inside the target block's span, so a trimmed pattern stays unique.
|
||||
func candidateUnique(candidate string, content []byte, targetStart, targetEnd int) bool {
|
||||
re, err := regexp.Compile(candidate)
|
||||
if err != nil {
|
||||
return false
|
||||
}
|
||||
matches := re.FindAllIndex(content, -1)
|
||||
return len(matches) == 1 && matches[0][0] >= targetStart && matches[0][1] <= targetEnd
|
||||
}
|
||||
|
||||
func buildPatternWithContext(preLines []string, captureText string, postLines []string, emptyCapture bool) string {
|
||||
if emptyCapture {
|
||||
return buildEmptyCapturePattern(preLines, postLines)
|
||||
}
|
||||
return buildCapturePattern(preLines, captureText, postLines)
|
||||
}
|
||||
|
||||
func buildEmptyCapturePattern(preLines, postLines []string) string {
|
||||
var b strings.Builder
|
||||
pre := strings.Join(preLines, "\n")
|
||||
post := strings.Join(postLines, "\n")
|
||||
if pre != "" {
|
||||
b.WriteString(regexp.QuoteMeta(pre))
|
||||
b.WriteString("\n")
|
||||
}
|
||||
b.WriteString("()")
|
||||
if post != "" {
|
||||
b.WriteString(regexp.QuoteMeta(post))
|
||||
}
|
||||
return b.String()
|
||||
}
|
||||
|
||||
func buildCapturePattern(preLines []string, captureText string, postLines []string) string {
|
||||
var b strings.Builder
|
||||
pre := strings.Join(preLines, "\n")
|
||||
post := strings.Join(postLines, "\n")
|
||||
if pre != "" {
|
||||
b.WriteString(regexp.QuoteMeta(pre))
|
||||
}
|
||||
if pre != "" && captureText != "" {
|
||||
b.WriteString("\n")
|
||||
}
|
||||
b.WriteString("(")
|
||||
b.WriteString(regexp.QuoteMeta(captureText))
|
||||
b.WriteString(")")
|
||||
if post != "" {
|
||||
b.WriteString("\n")
|
||||
b.WriteString(regexp.QuoteMeta(post))
|
||||
}
|
||||
return b.String()
|
||||
}
|
||||
@@ -0,0 +1,73 @@
|
||||
package chef
|
||||
|
||||
import (
|
||||
"fmt"
|
||||
"strconv"
|
||||
"strings"
|
||||
|
||||
"cook/utils"
|
||||
|
||||
"github.com/BurntSushi/toml"
|
||||
)
|
||||
|
||||
func renderGeneratedCommandsTOML(commands []utils.ModifyCommand) (string, error) {
|
||||
var b strings.Builder
|
||||
|
||||
for i, cmd := range commands {
|
||||
if i > 0 {
|
||||
b.WriteString("\n")
|
||||
}
|
||||
b.WriteString("[[commands]]\n")
|
||||
b.WriteString("name = '")
|
||||
b.WriteString(strings.ReplaceAll(cmd.Name, "'", "_"))
|
||||
b.WriteString("'\n")
|
||||
|
||||
b.WriteString("regex = ")
|
||||
b.WriteString(formatTomlRegexLiteral(stripUnsafeControlChars(cmd.Regex)))
|
||||
b.WriteString("\n")
|
||||
|
||||
b.WriteString("lua = '''\n")
|
||||
b.WriteString(stripUnsafeControlChars(cmd.Lua))
|
||||
b.WriteString("\n'''\n")
|
||||
|
||||
b.WriteString("files = [")
|
||||
for j, f := range cmd.Files {
|
||||
if j > 0 {
|
||||
b.WriteString(", ")
|
||||
}
|
||||
b.WriteString("'")
|
||||
b.WriteString(strings.ReplaceAll(f, "'", "_"))
|
||||
b.WriteString("'")
|
||||
}
|
||||
b.WriteString("]\n")
|
||||
b.WriteString("noreset = false\n")
|
||||
}
|
||||
|
||||
out := b.String()
|
||||
var validate struct {
|
||||
Commands []utils.ModifyCommand `toml:"commands"`
|
||||
}
|
||||
if _, err := toml.Decode(out, &validate); err != nil {
|
||||
return "", fmt.Errorf("generated TOML is invalid: %w", err)
|
||||
}
|
||||
|
||||
return out, nil
|
||||
}
|
||||
|
||||
func stripUnsafeControlChars(s string) string {
|
||||
var b strings.Builder
|
||||
b.Grow(len(s))
|
||||
for _, r := range s {
|
||||
if r == '\n' || r == '\t' || r >= 0x20 {
|
||||
b.WriteRune(r)
|
||||
}
|
||||
}
|
||||
return b.String()
|
||||
}
|
||||
|
||||
func formatTomlRegexLiteral(s string) string {
|
||||
if strings.Contains(s, "'''") {
|
||||
return strconv.Quote(s)
|
||||
}
|
||||
return "'''\n" + s + "\n'''"
|
||||
}
|
||||
@@ -0,0 +1,349 @@
|
||||
package chef
|
||||
|
||||
import (
|
||||
"regexp"
|
||||
"testing"
|
||||
|
||||
"cook/utils"
|
||||
|
||||
"github.com/stretchr/testify/assert"
|
||||
"github.com/stretchr/testify/require"
|
||||
)
|
||||
|
||||
const propertyGroupCloseCRLF = " </PropertyGroup>\r\n"
|
||||
|
||||
const minimalContextContent = "line1\nline2\nold3\nline4\nline5\n"
|
||||
|
||||
var minimalContextRegex = "line2\n(" + regexp.QuoteMeta("old3") + ")\nline4"
|
||||
|
||||
func TestGenerateCommandsFromUnifiedDiffBasicReplacement(t *testing.T) {
|
||||
setWorkingDir(t, t.TempDir())
|
||||
|
||||
diffText := `diff --git a/src/activity_actor.cpp b/src/activity_actor.cpp
|
||||
index 1234567..89abcde 100644
|
||||
--- a/src/activity_actor.cpp
|
||||
+++ b/src/activity_actor.cpp
|
||||
@@ -2840 +2840 @@
|
||||
- if( it != nullptr && it->has_flag( flag_SINGLE_USE ) ) {
|
||||
+ if( it != nullptr && it->has_flag( flag_SINGLE_USE ) && !it->count_by_charges() ) {
|
||||
`
|
||||
|
||||
commands, skipped, err := GenerateCommandsFromUnifiedDiff(diffText)
|
||||
require.NoError(t, err)
|
||||
require.Equal(t, 0, skipped)
|
||||
require.Len(t, commands, 1)
|
||||
|
||||
cmd := commands[0]
|
||||
assert.Equal(t, false, cmd.NoReset)
|
||||
assert.Equal(t, []string{"src/activity_actor.cpp"}, cmd.Files)
|
||||
oldLine := " if( it != nullptr && it->has_flag( flag_SINGLE_USE ) ) {"
|
||||
assert.Equal(t, "("+regexp.QuoteMeta(oldLine)+")", cmd.Regex)
|
||||
assert.Equal(t, `s1 = [[ if( it != nullptr && it->has_flag( flag_SINGLE_USE ) && !it->count_by_charges() ) {]]`, cmd.Lua)
|
||||
assert.Equal(t, "activity_actor.cpp gen", cmd.Name)
|
||||
}
|
||||
|
||||
func TestGenerateCommandsFromUnifiedDiffInsertionOnlyAnchoredByContext(t *testing.T) {
|
||||
setWorkingDir(t, t.TempDir())
|
||||
|
||||
diffText := `diff --git a/src/ranged.cpp b/src/ranged.cpp
|
||||
index 1234567..89abcde 100644
|
||||
--- a/src/ranged.cpp
|
||||
+++ b/src/ranged.cpp
|
||||
@@ -100,1 +101,3 @@
|
||||
line_before
|
||||
+
|
||||
+ dispersion.add_multiplier(0.25);
|
||||
`
|
||||
|
||||
commands, skipped, err := GenerateCommandsFromUnifiedDiff(diffText)
|
||||
require.NoError(t, err)
|
||||
assert.Equal(t, 0, skipped)
|
||||
require.Len(t, commands, 1)
|
||||
cmd := commands[0]
|
||||
assert.Equal(t, regexp.QuoteMeta("line_before")+"\n()", cmd.Regex)
|
||||
assert.Equal(t, "s1 = [[\n dispersion.add_multiplier(0.25);]]", cmd.Lua)
|
||||
}
|
||||
|
||||
func TestGenerateCommandsFromUnifiedDiffDeleteOnly(t *testing.T) {
|
||||
setWorkingDir(t, t.TempDir())
|
||||
|
||||
diffText := `diff --git a/src/ranged.cpp b/src/ranged.cpp
|
||||
index 1234567..89abcde 100644
|
||||
--- a/src/ranged.cpp
|
||||
+++ b/src/ranged.cpp
|
||||
@@ -200,2 +200,0 @@
|
||||
-old line one
|
||||
-old line two
|
||||
`
|
||||
|
||||
commands, skipped, err := GenerateCommandsFromUnifiedDiff(diffText)
|
||||
require.NoError(t, err)
|
||||
assert.Equal(t, 0, skipped)
|
||||
require.Len(t, commands, 1)
|
||||
|
||||
cmd := commands[0]
|
||||
oldBlock := "old line one\nold line two"
|
||||
assert.Equal(t, "("+regexp.QuoteMeta(oldBlock)+")", cmd.Regex)
|
||||
assert.Equal(t, `s1 = [[]]`, cmd.Lua)
|
||||
assert.Equal(t, false, cmd.NoReset)
|
||||
}
|
||||
|
||||
func TestRenderGeneratedCommandsTOMLUsesLiteralNewlinesWithoutLogLevel(t *testing.T) {
|
||||
commands := []struct {
|
||||
Name string
|
||||
Regex string
|
||||
Lua string
|
||||
Files []string
|
||||
NoReset bool
|
||||
}{
|
||||
{
|
||||
Name: "gen_advanced_inv_1",
|
||||
Regex: `( const int input_amount = by_charges \? it\.charges : action == "MOVE_SINGLE_ITEM" \? 1 : sitem\.stacks;)`,
|
||||
Lua: "s1 = [[ const int input_amount = std::max( 1, by_charges ? it.charges :\n action == \"MOVE_SINGLE_ITEM\" ? 1 : sitem.stacks );]]",
|
||||
Files: []string{"src/advanced_inv.cpp"},
|
||||
NoReset: false,
|
||||
},
|
||||
}
|
||||
|
||||
actual := make([]utils.ModifyCommand, 0, len(commands))
|
||||
for _, cmd := range commands {
|
||||
actual = append(actual, utils.ModifyCommand{
|
||||
Name: cmd.Name,
|
||||
Regex: cmd.Regex,
|
||||
Lua: cmd.Lua,
|
||||
Files: cmd.Files,
|
||||
NoReset: cmd.NoReset,
|
||||
})
|
||||
}
|
||||
|
||||
out, err := renderGeneratedCommandsTOML(actual)
|
||||
require.NoError(t, err)
|
||||
|
||||
assert.NotContains(t, out, `loglevel`)
|
||||
assert.NotContains(t, out, `\n`)
|
||||
assert.Contains(t, out, "lua = '''\n")
|
||||
assert.Contains(t, out, "regex = '''\n")
|
||||
assert.Contains(t, out, "files = ['src/advanced_inv.cpp']")
|
||||
}
|
||||
|
||||
func TestGenerateCommandsFromUnifiedDiffHandlesCRLFPropsDiff(t *testing.T) {
|
||||
setWorkingDir(t, t.TempDir())
|
||||
|
||||
diffText := "diff --git a/msvc-full-features/Cataclysm-common.props b/msvc-full-features/Cataclysm-common.props\r\n" +
|
||||
"--- a/msvc-full-features/Cataclysm-common.props\r\n" +
|
||||
"+++ b/msvc-full-features/Cataclysm-common.props\r\n" +
|
||||
"@@ -26,6 +26,11 @@\r\n" +
|
||||
" <PropertyGroup Label=\"Vcpkg\">\r\n" +
|
||||
" <VcpkgAdditionalInstallOptions>--clean-after-build</VcpkgAdditionalInstallOptions>\r\n" +
|
||||
propertyGroupCloseCRLF +
|
||||
"+ <PropertyGroup>\r\n" +
|
||||
"+ <!-- debug versions of libs often (but not always) use `d` suffix, as a convention. E.g. \"SDL2-staticd.lib\" -->\r\n" +
|
||||
"+ <VcpkgLibSuffix></VcpkgLibSuffix>\r\n" +
|
||||
"+ <VcpkgLibSuffix Condition='\"'\"'$(Configuration)'\"'\"'=='\"'\"'Debug'\"'\"''>d</VcpkgLibSuffix>\r\n" +
|
||||
"+ </PropertyGroup>\r\n" +
|
||||
" <PropertyGroup Condition=\"$(_CDDA_USE_CCACHE)\">\r\n" +
|
||||
" <ClToolPath>$(CDDA_CCACHE_PATH)</ClToolPath>\r\n" +
|
||||
propertyGroupCloseCRLF +
|
||||
"@@ -39,8 +44,6 @@\r\n" +
|
||||
" <!-- vcpkg passes dependecy libs via a glob pattern which lld-link doesn't accept. We have to manually enumerate the deps now. -->\r\n" +
|
||||
" <VcpkgAutoLink>false</VcpkgAutoLink>\r\n" +
|
||||
" <!-- debug versions of libs often (but not always) use `d` suffix, as a convention. E.g. \"SDL2-staticd.lib\" -->\r\n" +
|
||||
"- <VcpkgLibSuffix></VcpkgLibSuffix>\r\n" +
|
||||
"- <VcpkgLibSuffix Condition=\"$(Configuration.StartsWith(Debug))\">d</VcpkgLibSuffix>\r\n" +
|
||||
propertyGroupCloseCRLF +
|
||||
" <ItemDefinitionGroup>\r\n" +
|
||||
" <ClCompile>\r\n"
|
||||
|
||||
commands, skipped, err := GenerateCommandsFromUnifiedDiff(diffText)
|
||||
require.NoError(t, err)
|
||||
assert.Equal(t, 0, skipped)
|
||||
assert.GreaterOrEqual(t, len(commands), 2)
|
||||
|
||||
out, err := renderGeneratedCommandsTOML(commands)
|
||||
require.NoError(t, err)
|
||||
assert.NotContains(t, out, "\r")
|
||||
assert.NotContains(t, out, `\n`)
|
||||
assert.Contains(t, out, "files = ['msvc-full-features/Cataclysm-common.props']")
|
||||
|
||||
first := commands[0]
|
||||
assert.Contains(t, first.Regex, regexp.QuoteMeta(" <PropertyGroup Label=\"Vcpkg\">"))
|
||||
assert.Contains(t, first.Regex, regexp.QuoteMeta(" <PropertyGroup Condition=\"$(_CDDA_USE_CCACHE)\">"))
|
||||
assert.Contains(t, first.Regex, "()")
|
||||
|
||||
second := commands[1]
|
||||
assert.Contains(t, second.Regex, regexp.QuoteMeta(" <!-- debug versions of libs often (but not always) use `d` suffix, as a convention. E.g. \"SDL2-staticd.lib\" -->"))
|
||||
assert.Contains(t, second.Regex, regexp.QuoteMeta(" </PropertyGroup>"))
|
||||
}
|
||||
|
||||
func TestGenerateCommandsFromUnifiedDiffDeletionUsesContextOutsideCapture(t *testing.T) {
|
||||
setWorkingDir(t, t.TempDir())
|
||||
|
||||
diffText := `diff --git a/src/test.txt b/src/test.txt
|
||||
--- a/src/test.txt
|
||||
+++ b/src/test.txt
|
||||
@@ -1,4 +1,2 @@
|
||||
keep-before
|
||||
-delete-one
|
||||
-delete-two
|
||||
keep-after
|
||||
`
|
||||
|
||||
commands, skipped, err := GenerateCommandsFromUnifiedDiff(diffText)
|
||||
require.NoError(t, err)
|
||||
assert.Equal(t, 0, skipped)
|
||||
require.Len(t, commands, 1)
|
||||
|
||||
cmd := commands[0]
|
||||
assert.Contains(t, cmd.Regex, regexp.QuoteMeta("keep-before"))
|
||||
assert.Contains(t, cmd.Regex, regexp.QuoteMeta("keep-after"))
|
||||
assert.Contains(t, cmd.Regex, "("+regexp.QuoteMeta("delete-one\ndelete-two")+")")
|
||||
}
|
||||
|
||||
func TestGenerateCommandsFromUnifiedDiffMinimalContext(t *testing.T) {
|
||||
dir := t.TempDir()
|
||||
setWorkingDir(t, dir)
|
||||
writeTestFile(t, "a.txt", minimalContextContent)
|
||||
|
||||
diffText := `diff --git a/a.txt b/a.txt
|
||||
--- a/a.txt
|
||||
+++ b/a.txt
|
||||
@@ -1,5 +1,5 @@
|
||||
line1
|
||||
line2
|
||||
-old3
|
||||
+new3
|
||||
line4
|
||||
line5
|
||||
`
|
||||
|
||||
commands, _, err := GenerateCommandsFromUnifiedDiff(diffText)
|
||||
require.NoError(t, err)
|
||||
require.Len(t, commands, 1)
|
||||
|
||||
// Full context is line1..line5; the shortest still-unique pattern keeps the
|
||||
// floor of one context line on each side.
|
||||
assert.Equal(t, minimalContextRegex, commands[0].Regex)
|
||||
}
|
||||
|
||||
func TestGenerateCommandsFromUnifiedDiffMinimalContextRejectsAmbiguousTrim(t *testing.T) {
|
||||
dir := t.TempDir()
|
||||
setWorkingDir(t, dir)
|
||||
content := "very-long-prefix-line-1\nshort2\nold3\nsuffix-A\nsuffix-BB-very-long\n" +
|
||||
"other\nshort2\nold3\nsuffix-A\nother\n"
|
||||
writeTestFile(t, "a.txt", content)
|
||||
|
||||
diffText := `diff --git a/a.txt b/a.txt
|
||||
--- a/a.txt
|
||||
+++ b/a.txt
|
||||
@@ -1,5 +1,5 @@
|
||||
very-long-prefix-line-1
|
||||
short2
|
||||
-old3
|
||||
+new3
|
||||
suffix-A
|
||||
suffix-BB-very-long
|
||||
`
|
||||
|
||||
commands, _, err := GenerateCommandsFromUnifiedDiff(diffText)
|
||||
require.NoError(t, err)
|
||||
require.Len(t, commands, 1)
|
||||
|
||||
// Trimming to short2..suffix-A would match the second block too, so the
|
||||
// minimal valid pattern must keep enough context to stay unique.
|
||||
assert.Equal(t, "short2\n("+regexp.QuoteMeta("old3")+")\nsuffix-A\nsuffix-BB-very-long", commands[0].Regex)
|
||||
}
|
||||
|
||||
func TestGenerateCommandsFromUnifiedDiffMinimalContextInsertion(t *testing.T) {
|
||||
dir := t.TempDir()
|
||||
setWorkingDir(t, dir)
|
||||
writeTestFile(t, "a.txt", "alpha\nbeta\ngamma\ndelta\nomega\n")
|
||||
|
||||
diffText := `diff --git a/a.txt b/a.txt
|
||||
--- a/a.txt
|
||||
+++ b/a.txt
|
||||
@@ -1,4 +1,5 @@
|
||||
alpha
|
||||
beta
|
||||
+NEW
|
||||
gamma
|
||||
delta
|
||||
`
|
||||
|
||||
commands, _, err := GenerateCommandsFromUnifiedDiff(diffText)
|
||||
require.NoError(t, err)
|
||||
require.Len(t, commands, 1)
|
||||
|
||||
assert.Equal(t, "beta\n()gamma", commands[0].Regex)
|
||||
assert.Equal(t, "s1 = [[NEW\n]]", commands[0].Lua)
|
||||
}
|
||||
|
||||
func TestGenerateCommandsFromUnifiedDiffNamed(t *testing.T) {
|
||||
setWorkingDir(t, t.TempDir())
|
||||
|
||||
diffText := `diff --git a/src/activity_actor.cpp b/src/activity_actor.cpp
|
||||
--- a/src/activity_actor.cpp
|
||||
+++ b/src/activity_actor.cpp
|
||||
@@ -2840 +2840 @@
|
||||
-old line
|
||||
+new line
|
||||
`
|
||||
|
||||
commands, skipped, err := GenerateCommandsFromUnifiedDiffNamed(diffText, "fix chargers")
|
||||
require.NoError(t, err)
|
||||
require.Equal(t, 0, skipped)
|
||||
require.Len(t, commands, 1)
|
||||
assert.Equal(t, "fix chargers activity_actor.cpp gen", commands[0].Name)
|
||||
}
|
||||
|
||||
func TestGenerateCommandsFromUnifiedDiffNameDisambiguatesDuplicates(t *testing.T) {
|
||||
setWorkingDir(t, t.TempDir())
|
||||
|
||||
diffText := `diff --git a/x.txt b/x.txt
|
||||
--- a/x.txt
|
||||
+++ b/x.txt
|
||||
@@ -1 +1 @@
|
||||
-old1
|
||||
+new1
|
||||
@@ -10 +10 @@
|
||||
-old10
|
||||
+new10
|
||||
`
|
||||
|
||||
commands, skipped, err := GenerateCommandsFromUnifiedDiffNamed(diffText, "props")
|
||||
require.NoError(t, err)
|
||||
require.Equal(t, 0, skipped)
|
||||
require.Len(t, commands, 2)
|
||||
assert.Equal(t, "props x.txt gen", commands[0].Name)
|
||||
assert.Equal(t, "props x.txt gen 2", commands[1].Name)
|
||||
}
|
||||
|
||||
func TestGenerateCommandsFromUnifiedDiffMinimalContextUsesSnapshotNotDisk(t *testing.T) {
|
||||
dir := t.TempDir()
|
||||
setWorkingDir(t, dir)
|
||||
// The file on disk has diverged from the pristine source.
|
||||
writeTestFile(t, "a.txt", "disk-line-1\nold3\ndisk-line-4\ndisk-line-5\n")
|
||||
|
||||
db, err := utils.GetDB()
|
||||
require.NoError(t, err)
|
||||
defer closeTestDB(t, db)
|
||||
require.NoError(t, db.SaveFile("a.txt", []byte(minimalContextContent)))
|
||||
|
||||
diffText := `diff --git a/a.txt b/a.txt
|
||||
--- a/a.txt
|
||||
+++ b/a.txt
|
||||
@@ -1,5 +1,5 @@
|
||||
line1
|
||||
line2
|
||||
-old3
|
||||
+new3
|
||||
line4
|
||||
line5
|
||||
`
|
||||
|
||||
commands, _, err := GenerateCommandsFromUnifiedDiff(diffText)
|
||||
require.NoError(t, err)
|
||||
require.Len(t, commands, 1)
|
||||
|
||||
// Context trimming ran against the snapshot, not the on-disk content.
|
||||
assert.Equal(t, minimalContextRegex, commands[0].Regex)
|
||||
}
|
||||
@@ -0,0 +1,385 @@
|
||||
package chef
|
||||
|
||||
import (
|
||||
"log/slog"
|
||||
"os"
|
||||
"path/filepath"
|
||||
"testing"
|
||||
|
||||
"cook/utils"
|
||||
|
||||
"github.com/stretchr/testify/assert"
|
||||
"github.com/stretchr/testify/require"
|
||||
)
|
||||
|
||||
const (
|
||||
testTxtPath = "test.txt"
|
||||
jsonTestFile = "test.json"
|
||||
xmlTestFile = "test.xml"
|
||||
ironsSpellbooksServerToml = "irons_spellbooks-server.toml"
|
||||
)
|
||||
|
||||
func setWorkingDir(t *testing.T, dir string) {
|
||||
t.Helper()
|
||||
|
||||
origDir, err := os.Getwd()
|
||||
require.NoError(t, err)
|
||||
require.NoError(t, os.Chdir(dir))
|
||||
|
||||
t.Cleanup(func() {
|
||||
require.NoError(t, os.Chdir(origDir))
|
||||
})
|
||||
}
|
||||
|
||||
func writeTestFile(t *testing.T, path, content string) {
|
||||
t.Helper()
|
||||
require.NoError(t, os.WriteFile(path, []byte(content), 0644))
|
||||
}
|
||||
|
||||
func TestIsolateCommandsSequentialExecution(t *testing.T) {
|
||||
tmpDir := t.TempDir()
|
||||
|
||||
// Create test file content
|
||||
testContent := `BEGIN
|
||||
block1 content with value 42
|
||||
END
|
||||
Some other content
|
||||
BEGIN
|
||||
block2 content with value 100
|
||||
END
|
||||
More content
|
||||
BEGIN
|
||||
block3 content with value 200
|
||||
END`
|
||||
|
||||
testFile := filepath.Join(tmpDir, testTxtPath)
|
||||
writeTestFile(t, testFile, testContent)
|
||||
setWorkingDir(t, tmpDir)
|
||||
|
||||
// Create isolate commands that work sequentially on the same block
|
||||
// First command: 42 -> 84
|
||||
// Second command: 84 -> 168 (works on result of first command)
|
||||
// Third command: 168 -> 336 (works on result of second command)
|
||||
commands := []utils.ModifyCommand{
|
||||
{
|
||||
Name: "MultiplyFirst",
|
||||
Regex: `BEGIN\n(?P<block>.*?value 42.*?)\nEND`,
|
||||
Lua: `replacement = "BEGIN\n" .. string.gsub(block, "42", "84") .. "\nEND"; return true`,
|
||||
Files: []string{testTxtPath},
|
||||
Isolate: true,
|
||||
},
|
||||
{
|
||||
Name: "MultiplySecond",
|
||||
Regex: `BEGIN\nblock1 content with value (?P<value>!num)\nEND`,
|
||||
Lua: `value = "168"; return true`,
|
||||
Files: []string{testTxtPath},
|
||||
Isolate: true,
|
||||
},
|
||||
{
|
||||
Name: "MultiplyThird",
|
||||
Regex: `BEGIN\nblock1 content with value (?P<value>!num)\nEND`,
|
||||
Lua: `value = "336"; return true`,
|
||||
Files: []string{testTxtPath},
|
||||
Isolate: true,
|
||||
},
|
||||
}
|
||||
|
||||
// Associate files with commands
|
||||
files := []string{testTxtPath}
|
||||
associations, err := utils.AssociateFilesWithCommands(files, commands)
|
||||
require.NoError(t, err)
|
||||
|
||||
// Verify that all three isolate commands are associated
|
||||
association := associations[testTxtPath]
|
||||
assert.Len(t, association.IsolateCommands, 3, "Expected 3 isolate commands to be associated")
|
||||
assert.Len(t, association.Commands, 0, "Expected 0 regular commands")
|
||||
|
||||
// Run the isolate commands
|
||||
result, err := RunIsolateCommands(association, testTxtPath, testContent)
|
||||
assert.NoError(t, err)
|
||||
|
||||
// Verify that all isolate commands were applied sequentially
|
||||
// First command: 42 -> 84
|
||||
// Second command: 84 -> 168 (works on result of first)
|
||||
// Third command: 168 -> 336 (works on result of second)
|
||||
assert.Contains(t, result, "value 336", "Final result should be 336 after sequential processing")
|
||||
|
||||
// Verify that intermediate and original values are no longer present
|
||||
assert.NotContains(t, result, "value 42", "Original value 42 should be replaced")
|
||||
assert.NotContains(t, result, "value 84", "Intermediate value 84 should be replaced")
|
||||
assert.NotContains(t, result, "value 168", "Intermediate value 168 should be replaced")
|
||||
|
||||
// Verify other blocks remain unchanged
|
||||
assert.Contains(t, result, "value 100", "Second block should remain unchanged")
|
||||
assert.Contains(t, result, "value 200", "Third block should remain unchanged")
|
||||
|
||||
}
|
||||
|
||||
func TestIsolateCommandsWithDifferentPatterns(t *testing.T) {
|
||||
tmpDir := t.TempDir()
|
||||
|
||||
// Create test file content with distinct patterns
|
||||
testContent := `SECTION1
|
||||
value = 10
|
||||
END_SECTION1
|
||||
|
||||
SECTION2
|
||||
value = 20
|
||||
END_SECTION2`
|
||||
|
||||
testFile := filepath.Join(tmpDir, testTxtPath)
|
||||
writeTestFile(t, testFile, testContent)
|
||||
setWorkingDir(t, tmpDir)
|
||||
|
||||
// Create isolate commands with different patterns on the same content
|
||||
commands := []utils.ModifyCommand{
|
||||
{
|
||||
Name: "UpdateSection1",
|
||||
Regex: `SECTION1.*?value = (?P<value>!num).*?END_SECTION1`,
|
||||
Lua: `value = "100"; return true`,
|
||||
Files: []string{testTxtPath},
|
||||
Isolate: true,
|
||||
},
|
||||
{
|
||||
Name: "UpdateSection2",
|
||||
Regex: `SECTION2.*?value = (?P<value>!num).*?END_SECTION2`,
|
||||
Lua: `value = "200"; return true`,
|
||||
Files: []string{testTxtPath},
|
||||
Isolate: true,
|
||||
},
|
||||
}
|
||||
|
||||
// Associate files with commands
|
||||
files := []string{testTxtPath}
|
||||
associations, err := utils.AssociateFilesWithCommands(files, commands)
|
||||
require.NoError(t, err)
|
||||
|
||||
// Run the isolate commands
|
||||
result, err := RunIsolateCommands(associations[testTxtPath], testTxtPath, testContent)
|
||||
assert.NoError(t, err)
|
||||
|
||||
// Verify that both isolate commands were applied
|
||||
assert.Contains(t, result, "value = 100", "Section1 should be updated")
|
||||
assert.Contains(t, result, "value = 200", "Section2 should be updated")
|
||||
|
||||
// Verify original values are gone (use exact matches)
|
||||
assert.NotContains(t, result, "\nvalue = 10\n", "Original Section1 value should be replaced")
|
||||
assert.NotContains(t, result, "\nvalue = 20\n", "Original Section2 value should be replaced")
|
||||
|
||||
}
|
||||
|
||||
func TestIsolateCommandsWithJSONMode(t *testing.T) {
|
||||
tmpDir := t.TempDir()
|
||||
|
||||
// Create test JSON content
|
||||
testContent := `{
|
||||
"section1": {
|
||||
"value": 42
|
||||
},
|
||||
"section2": {
|
||||
"value": 100
|
||||
}
|
||||
}`
|
||||
|
||||
testFile := filepath.Join(tmpDir, jsonTestFile)
|
||||
writeTestFile(t, testFile, testContent)
|
||||
setWorkingDir(t, tmpDir)
|
||||
|
||||
// Create isolate commands with JSON mode
|
||||
commands := []utils.ModifyCommand{
|
||||
{
|
||||
Name: "UpdateJSONFirst",
|
||||
JSON: true,
|
||||
Lua: `data.section1.value = data.section1.value * 2; return true`,
|
||||
Files: []string{jsonTestFile},
|
||||
Isolate: true,
|
||||
},
|
||||
{
|
||||
Name: "UpdateJSONSecond",
|
||||
JSON: true,
|
||||
Lua: `data.section2.value = data.section2.value * 3; return true`,
|
||||
Files: []string{jsonTestFile},
|
||||
Isolate: true,
|
||||
},
|
||||
}
|
||||
|
||||
// Associate files with commands
|
||||
files := []string{jsonTestFile}
|
||||
associations, err := utils.AssociateFilesWithCommands(files, commands)
|
||||
require.NoError(t, err)
|
||||
|
||||
// Run the isolate commands
|
||||
result, err := RunIsolateCommands(associations[jsonTestFile], jsonTestFile, testContent)
|
||||
assert.NoError(t, err)
|
||||
|
||||
// Verify that both JSON isolate commands were applied
|
||||
assert.Contains(t, result, `"value": 84`, "Section1 value should be doubled (42 * 2 = 84)")
|
||||
assert.Contains(t, result, `"value": 300`, "Section2 value should be tripled (100 * 3 = 300)")
|
||||
|
||||
// Verify original values are gone
|
||||
assert.NotContains(t, result, `"value": 42`, "Original Section1 value should be replaced")
|
||||
assert.NotContains(t, result, `"value": 100`, "Original Section2 value should be replaced")
|
||||
|
||||
}
|
||||
|
||||
func TestRunOtherCommandsWithXMLMode(t *testing.T) {
|
||||
testContent := `<root version="1"><item price="10" /></root>`
|
||||
association := utils.FileCommandAssociation{
|
||||
File: xmlTestFile,
|
||||
Commands: []utils.ModifyCommand{
|
||||
{
|
||||
Name: "UpdateXML",
|
||||
XML: true,
|
||||
Lua: `data.attr.version = "2"; data.children[1].attr.price = N(data.children[1].attr.price) * 3; return true`,
|
||||
Files: []string{xmlTestFile},
|
||||
},
|
||||
},
|
||||
}
|
||||
|
||||
result, err := RunOtherCommands(xmlTestFile, testContent, association, map[string]*slog.Logger{})
|
||||
if err != nil {
|
||||
t.Fatalf("Failed to run XML commands: %v", err)
|
||||
}
|
||||
|
||||
assert.Equal(t, `<root version="2"><item price="30" /></root>`, result)
|
||||
}
|
||||
|
||||
func TestRunOtherCommandsRegexPredSkipsStructuredParsing(t *testing.T) {
|
||||
testContent := `<root><item value="1"/></root>`
|
||||
association := utils.FileCommandAssociation{
|
||||
File: xmlTestFile,
|
||||
Commands: []utils.ModifyCommand{
|
||||
{
|
||||
Name: "SkipByPred",
|
||||
XML: true,
|
||||
RegexPred: `DefinitelyNotInFile`,
|
||||
Lua: `error("should not execute")`,
|
||||
Files: []string{xmlTestFile},
|
||||
},
|
||||
},
|
||||
}
|
||||
|
||||
_, err := RunOtherCommands(xmlTestFile, testContent, association, map[string]*slog.Logger{})
|
||||
assert.Equal(t, ErrNothingToDo, err)
|
||||
}
|
||||
|
||||
func TestIsolateVsRegularCommands(t *testing.T) {
|
||||
tmpDir := t.TempDir()
|
||||
|
||||
// Create test file with distinct sections
|
||||
testContent := `ISOLATE_SECTION
|
||||
value = 5
|
||||
END_ISOLATE
|
||||
|
||||
REGULAR_SECTION
|
||||
value = 10
|
||||
END_REGULAR`
|
||||
|
||||
testFile := filepath.Join(tmpDir, testTxtPath)
|
||||
writeTestFile(t, testFile, testContent)
|
||||
setWorkingDir(t, tmpDir)
|
||||
|
||||
// Create both isolate and regular commands
|
||||
commands := []utils.ModifyCommand{
|
||||
{
|
||||
Name: "IsolateMultiply",
|
||||
Regex: `ISOLATE_SECTION.*?value = (?P<value>!num).*?END_ISOLATE`,
|
||||
Lua: `value = tostring(util.num(value) * 10); return true`,
|
||||
Files: []string{testTxtPath},
|
||||
Isolate: true,
|
||||
},
|
||||
{
|
||||
Name: "RegularMultiply",
|
||||
Regex: `value = (?P<value>!num)`,
|
||||
Lua: `value = tostring(util.num(value) + 100); return true`,
|
||||
Files: []string{testTxtPath},
|
||||
},
|
||||
}
|
||||
|
||||
// Associate files with commands
|
||||
files := []string{testTxtPath}
|
||||
associations, err := utils.AssociateFilesWithCommands(files, commands)
|
||||
require.NoError(t, err)
|
||||
|
||||
// Verify the association
|
||||
association := associations[testTxtPath]
|
||||
assert.Len(t, association.IsolateCommands, 1, "Expected 1 isolate command")
|
||||
assert.Len(t, association.Commands, 1, "Expected 1 regular command")
|
||||
|
||||
// First run isolate commands
|
||||
isolateResult, err := RunIsolateCommands(association, testTxtPath, testContent)
|
||||
assert.NoError(t, err)
|
||||
|
||||
// Verify isolate command result
|
||||
assert.Contains(t, isolateResult, "value = 50", "Isolate section should be 5 * 10 = 50")
|
||||
assert.Contains(t, isolateResult, "value = 10", "Regular section should be unchanged by isolate commands")
|
||||
|
||||
// Then run regular commands
|
||||
commandLoggers := make(map[string]*slog.Logger)
|
||||
finalResult, err := RunOtherCommands(testTxtPath, isolateResult, association, commandLoggers)
|
||||
assert.NoError(t, err)
|
||||
|
||||
// Verify final results - regular commands should affect ALL values
|
||||
assert.Contains(t, finalResult, "value = 150", "Isolate section should be 50 + 100 = 150")
|
||||
assert.Contains(t, finalResult, "value = 110", "Regular section should be 10 + 100 = 110")
|
||||
|
||||
}
|
||||
|
||||
func TestMultipleIsolateModifiersOnSameValue(t *testing.T) {
|
||||
tmpDir := t.TempDir()
|
||||
|
||||
// Create test file content that matches the scenario in the issue
|
||||
testContent := `irons_spellbooks:chain_creeper
|
||||
SpellPowerMultiplier = 1
|
||||
irons_spellbooks:chain_lightning
|
||||
SpellPowerMultiplier = 1`
|
||||
|
||||
testFile := filepath.Join(tmpDir, ironsSpellbooksServerToml)
|
||||
writeTestFile(t, testFile, testContent)
|
||||
setWorkingDir(t, tmpDir)
|
||||
|
||||
// Create isolate commands that match the issue scenario
|
||||
// First command: targets chain_creeper and chain_lightning with multiplier *4
|
||||
// Second command: targets all SpellPowerMultiplier with multiplier *4
|
||||
commands := []utils.ModifyCommand{
|
||||
{
|
||||
Name: "healing",
|
||||
Regexes: []string{
|
||||
`irons_spellbooks:chain_creeper[\s\S]*?SpellPowerMultiplier = !num`,
|
||||
`irons_spellbooks:chain_lightning[\s\S]*?SpellPowerMultiplier = !num`,
|
||||
},
|
||||
Lua: `v1 * 4`, // This should multiply by 4
|
||||
Files: []string{ironsSpellbooksServerToml},
|
||||
NoReset: false,
|
||||
Isolate: true,
|
||||
},
|
||||
{
|
||||
Name: "spellpower",
|
||||
Regex: `SpellPowerMultiplier = !num`,
|
||||
Lua: `v1 * 4`, // This should multiply by 4 again
|
||||
Files: []string{ironsSpellbooksServerToml},
|
||||
NoReset: false,
|
||||
Isolate: true,
|
||||
},
|
||||
}
|
||||
|
||||
// Associate files with commands
|
||||
files := []string{ironsSpellbooksServerToml}
|
||||
associations, err := utils.AssociateFilesWithCommands(files, commands)
|
||||
require.NoError(t, err)
|
||||
|
||||
// Verify that both isolate commands are associated
|
||||
association := associations[ironsSpellbooksServerToml]
|
||||
assert.Len(t, association.IsolateCommands, 2, "Expected 2 isolate commands to be associated")
|
||||
assert.Len(t, association.Commands, 0, "Expected 0 regular commands")
|
||||
|
||||
// Run the isolate commands
|
||||
result, err := RunIsolateCommands(association, ironsSpellbooksServerToml, testContent)
|
||||
assert.NoError(t, err)
|
||||
|
||||
// Verify that both isolate commands were applied sequentially
|
||||
// Expected: 1 -> 4 (first command) -> 16 (second command)
|
||||
assert.Contains(t, result, "SpellPowerMultiplier = 16", "Final result should be 16 after sequential processing (1 * 4 * 4)")
|
||||
|
||||
assert.Contains(t, result, "SpellPowerMultiplier = 16", "The system correctly applies both isolate modifiers sequentially")
|
||||
}
|
||||
@@ -0,0 +1,149 @@
|
||||
package chef
|
||||
|
||||
import (
|
||||
"strconv"
|
||||
"strings"
|
||||
)
|
||||
|
||||
// resolveJSONPointerRange maps an RFC 6902 JSON pointer to the byte range of
|
||||
// the value it references within content. The empty pointer refers to the
|
||||
// root value.
|
||||
func resolveJSONPointerRange(content, pointer string) (int, int, bool) {
|
||||
start := skipJSONSpace(content, 0)
|
||||
if start >= len(content) {
|
||||
return 0, 0, false
|
||||
}
|
||||
curStart, curEnd := valueJSONRange(content, start)
|
||||
if curStart < 0 {
|
||||
return 0, 0, false
|
||||
}
|
||||
if pointer == "" {
|
||||
return curStart, curEnd, true
|
||||
}
|
||||
for _, tok := range strings.Split(pointer, "/")[1:] {
|
||||
nextStart, nextEnd, ok := stepJSONPointer(content, curStart, curEnd, tok)
|
||||
if !ok {
|
||||
return 0, 0, false
|
||||
}
|
||||
curStart, curEnd = nextStart, nextEnd
|
||||
}
|
||||
return curStart, curEnd, true
|
||||
}
|
||||
|
||||
func stepJSONPointer(content string, curStart, curEnd int, token string) (int, int, bool) {
|
||||
token = unescapeJSONPointerToken(token)
|
||||
if curStart >= curEnd {
|
||||
return 0, 0, false
|
||||
}
|
||||
switch content[curStart] {
|
||||
case '{':
|
||||
vs, ve := locateJSONObjectMember(content, curStart, curEnd, token)
|
||||
return vs, ve, vs >= 0
|
||||
case '[':
|
||||
idx, ok := jsonPointerIndex(token)
|
||||
if !ok {
|
||||
return 0, 0, false
|
||||
}
|
||||
vs, ve := locateJSONArrayElement(content, curStart, curEnd, idx)
|
||||
return vs, ve, vs >= 0
|
||||
default:
|
||||
return 0, 0, false
|
||||
}
|
||||
}
|
||||
|
||||
func jsonPointerIndex(token string) (int, bool) {
|
||||
idx, err := strconv.Atoi(token)
|
||||
if err != nil {
|
||||
return 0, false
|
||||
}
|
||||
if idx < 0 {
|
||||
return 0, false
|
||||
}
|
||||
return idx, true
|
||||
}
|
||||
|
||||
func locateJSONObjectMember(s string, objStart, objEnd int, key string) (int, int) {
|
||||
i := skipJSONSpace(s, objStart+1)
|
||||
for i < objEnd {
|
||||
i = skipJSONSpace(s, i)
|
||||
k, vStart, vEnd, next, ok := nextJSONObjectMember(s, i, objEnd)
|
||||
if !ok {
|
||||
return -1, -1
|
||||
}
|
||||
if k == key {
|
||||
return vStart, vEnd
|
||||
}
|
||||
i = next
|
||||
}
|
||||
return -1, -1
|
||||
}
|
||||
|
||||
func nextJSONObjectMember(s string, i, objEnd int) (string, int, int, int, bool) {
|
||||
decoded, colonPos, ok := readJSONObjectKey(s, i, objEnd)
|
||||
if !ok {
|
||||
return "", 0, 0, i, false
|
||||
}
|
||||
vStart, vEnd, next, ok := readJSONMemberValue(s, colonPos, objEnd)
|
||||
if !ok {
|
||||
return "", 0, 0, i, false
|
||||
}
|
||||
return decoded, vStart, vEnd, next, true
|
||||
}
|
||||
|
||||
func readJSONObjectKey(s string, i, objEnd int) (string, int, bool) {
|
||||
if i >= objEnd || s[i] != '"' {
|
||||
return "", 0, false
|
||||
}
|
||||
keyEnd := jsonStringEnd(s, i)
|
||||
if keyEnd < 0 {
|
||||
return "", 0, false
|
||||
}
|
||||
decoded := decodeJSONString(s, i, keyEnd)
|
||||
j := skipJSONSpace(s, keyEnd)
|
||||
if j >= objEnd || s[j] != ':' {
|
||||
return "", 0, false
|
||||
}
|
||||
return decoded, j, true
|
||||
}
|
||||
|
||||
func readJSONMemberValue(s string, colonPos, objEnd int) (int, int, int, bool) {
|
||||
vStart, vEnd := valueJSONRange(s, colonPos+1)
|
||||
if vStart < 0 {
|
||||
return 0, 0, colonPos, false
|
||||
}
|
||||
next := skipJSONSpace(s, vEnd)
|
||||
if next < objEnd {
|
||||
if s[next] == ',' {
|
||||
next++
|
||||
}
|
||||
}
|
||||
return vStart, vEnd, next, true
|
||||
}
|
||||
|
||||
func locateJSONArrayElement(s string, arrStart, arrEnd, idx int) (int, int) {
|
||||
i := skipJSONSpace(s, arrStart+1)
|
||||
current := 0
|
||||
for i < arrEnd {
|
||||
vStart, vEnd := valueJSONRange(s, i)
|
||||
if vStart < 0 {
|
||||
return -1, -1
|
||||
}
|
||||
if current == idx {
|
||||
return vStart, vEnd
|
||||
}
|
||||
current++
|
||||
i = skipJSONSpace(s, vEnd)
|
||||
if i < arrEnd {
|
||||
if s[i] == ',' {
|
||||
i++
|
||||
}
|
||||
}
|
||||
}
|
||||
return -1, -1
|
||||
}
|
||||
|
||||
func unescapeJSONPointerToken(tok string) string {
|
||||
tok = strings.ReplaceAll(tok, "~1", "/")
|
||||
tok = strings.ReplaceAll(tok, "~0", "~")
|
||||
return tok
|
||||
}
|
||||
@@ -0,0 +1,128 @@
|
||||
package chef
|
||||
|
||||
import "strconv"
|
||||
|
||||
func skipJSONSpace(s string, i int) int {
|
||||
for i < len(s) {
|
||||
switch s[i] {
|
||||
case ' ', '\t', '\n', '\r':
|
||||
i++
|
||||
default:
|
||||
return i
|
||||
}
|
||||
}
|
||||
return i
|
||||
}
|
||||
|
||||
func isJSONValueEnd(c byte) bool {
|
||||
switch c {
|
||||
case ',', '}', ']', ' ', '\t', '\n', '\r':
|
||||
return true
|
||||
}
|
||||
return false
|
||||
}
|
||||
|
||||
func valueJSONRange(s string, i int) (int, int) {
|
||||
i = skipJSONSpace(s, i)
|
||||
if i < 0 || i >= len(s) {
|
||||
return -1, -1
|
||||
}
|
||||
switch s[i] {
|
||||
case '{', '[':
|
||||
return jsonCompositeRange(s, i)
|
||||
case '"':
|
||||
return jsonStringRange(s, i)
|
||||
default:
|
||||
return jsonScalarRange(s, i)
|
||||
}
|
||||
}
|
||||
|
||||
func jsonStringRange(s string, i int) (int, int) {
|
||||
end := jsonStringEnd(s, i)
|
||||
if end < 0 {
|
||||
return -1, -1
|
||||
}
|
||||
return i, end
|
||||
}
|
||||
|
||||
func jsonScalarRange(s string, i int) (int, int) {
|
||||
j := i
|
||||
for j < len(s) && !isJSONValueEnd(s[j]) {
|
||||
j++
|
||||
}
|
||||
return i, j
|
||||
}
|
||||
|
||||
func jsonCompositeRange(s string, start int) (int, int) {
|
||||
open := s[start]
|
||||
closeCh := closingJSONChar(open)
|
||||
depth := 0
|
||||
for i := start; i < len(s); i++ {
|
||||
nextI, done, matched := advanceJSONComposite(s, i, open, closeCh, &depth)
|
||||
if done {
|
||||
if matched {
|
||||
return start, i + 1
|
||||
}
|
||||
return -1, -1
|
||||
}
|
||||
i = nextI
|
||||
}
|
||||
return -1, -1
|
||||
}
|
||||
|
||||
func closingJSONChar(open byte) byte {
|
||||
if open == '[' {
|
||||
return ']'
|
||||
}
|
||||
return '}'
|
||||
}
|
||||
|
||||
func advanceJSONComposite(s string, i int, open byte, closeCh byte, depth *int) (nextI int, done bool, matched bool) {
|
||||
switch s[i] {
|
||||
case '"':
|
||||
end := jsonStringEnd(s, i)
|
||||
if end < 0 {
|
||||
return 0, true, false
|
||||
}
|
||||
return end - 1, false, false
|
||||
case open:
|
||||
*depth++
|
||||
case closeCh:
|
||||
*depth--
|
||||
if *depth == 0 {
|
||||
return 0, true, true
|
||||
}
|
||||
}
|
||||
return i, false, false
|
||||
}
|
||||
|
||||
func jsonStringEnd(s string, start int) int {
|
||||
if start < 0 {
|
||||
return -1
|
||||
}
|
||||
if start >= len(s) {
|
||||
return -1
|
||||
}
|
||||
if s[start] != '"' {
|
||||
return -1
|
||||
}
|
||||
for i := start + 1; i < len(s); i++ {
|
||||
if s[i] == '\\' {
|
||||
i++
|
||||
continue
|
||||
}
|
||||
if s[i] == '"' {
|
||||
return i + 1
|
||||
}
|
||||
}
|
||||
return -1
|
||||
}
|
||||
|
||||
func decodeJSONString(s string, start, end int) string {
|
||||
raw := s[start:end]
|
||||
decoded := raw[1 : len(raw)-1]
|
||||
if u, err := strconv.Unquote(raw); err == nil {
|
||||
decoded = u
|
||||
}
|
||||
return decoded
|
||||
}
|
||||
@@ -0,0 +1,15 @@
|
||||
package chef
|
||||
|
||||
import (
|
||||
"log/slog"
|
||||
"strings"
|
||||
|
||||
logger "git.site.quack-lab.dev/dave/cylogger/v3"
|
||||
)
|
||||
|
||||
func ConfigureLogger(logLevel string, noColor bool) {
|
||||
logger.Init(logger.ParseLevel(strings.TrimSpace(logLevel)), !noColor)
|
||||
logger.WithFieldColorD("target", []string{logger.Purple})
|
||||
logger.WithFieldColorD("cmd", []string{logger.Blue})
|
||||
logger.WithLevelLineColorD(slog.Level(logger.LevelInfo+1).String(), []string{logger.Purple})
|
||||
}
|
||||
@@ -0,0 +1,87 @@
|
||||
package chef
|
||||
|
||||
import (
|
||||
"fmt"
|
||||
"os"
|
||||
"time"
|
||||
|
||||
"cook/processor"
|
||||
"cook/tui"
|
||||
"cook/utils"
|
||||
|
||||
logger "git.site.quack-lab.dev/dave/cylogger/v3"
|
||||
)
|
||||
|
||||
const luaWatchInterval = 500 * time.Millisecond
|
||||
|
||||
// RunLuaFile runs one or more standalone Lua files with the full context a
|
||||
// cook command would have. Files run in order inside a single Lua state, so
|
||||
// earlier files stay loaded in the engine and later files can use what they
|
||||
// define.
|
||||
func RunLuaFile(args []string) error {
|
||||
return runLua(args, false)
|
||||
}
|
||||
|
||||
// RunLuaFileWatch runs Lua files like RunLuaFile, then keeps watching them and
|
||||
// re-runs all files in order whenever any of them changes on disk until
|
||||
// interrupted.
|
||||
func RunLuaFileWatch(args []string) error {
|
||||
return runLua(args, true)
|
||||
}
|
||||
|
||||
func runLua(args []string, watch bool) error {
|
||||
paths, err := resolveLuaFiles(args)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
if err := processor.RunLuaFiles(paths); err != nil {
|
||||
if !watch {
|
||||
return err
|
||||
}
|
||||
logger.Error("Lua run failed")
|
||||
fmt.Fprintln(os.Stderr, err)
|
||||
}
|
||||
if !watch {
|
||||
return nil
|
||||
}
|
||||
return watchLuaFiles(paths)
|
||||
}
|
||||
|
||||
func resolveLuaFiles(args []string) ([]string, error) {
|
||||
if len(args) == 0 {
|
||||
return nil, fmt.Errorf("missing lua file path")
|
||||
}
|
||||
paths := make([]string, 0, len(args))
|
||||
for _, arg := range args {
|
||||
resolved := utils.ResolvePath(arg)
|
||||
if _, err := os.Stat(resolved); err != nil {
|
||||
return nil, fmt.Errorf("lua file %q: %w", arg, err)
|
||||
}
|
||||
paths = append(paths, resolved)
|
||||
}
|
||||
return paths, nil
|
||||
}
|
||||
|
||||
func watchLuaFiles(paths []string) error {
|
||||
logger.Info("Watching for changes", "paths", paths)
|
||||
events, errs, stop, err := tui.StartCookWatcher(paths, luaWatchInterval)
|
||||
if err != nil {
|
||||
return fmt.Errorf("failed to start watcher: %w", err)
|
||||
}
|
||||
defer stop()
|
||||
|
||||
for {
|
||||
select {
|
||||
case <-events:
|
||||
logger.Info("File changed, re-running", "paths", paths)
|
||||
if err := processor.RunLuaFiles(paths); err != nil {
|
||||
logger.Error("Lua run failed")
|
||||
fmt.Fprintln(os.Stderr, err)
|
||||
}
|
||||
case err := <-errs:
|
||||
if err != nil {
|
||||
logger.Error("Watch error", "err", err)
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,121 @@
|
||||
package chef
|
||||
|
||||
import (
|
||||
"path/filepath"
|
||||
"strings"
|
||||
"testing"
|
||||
"time"
|
||||
|
||||
logger "git.site.quack-lab.dev/dave/cylogger/v3"
|
||||
"github.com/stretchr/testify/assert"
|
||||
"github.com/stretchr/testify/require"
|
||||
)
|
||||
|
||||
const luaTestScript = "script.lua"
|
||||
|
||||
func TestRunLuaFile(t *testing.T) {
|
||||
logger.Init(logger.LevelInfo, false)
|
||||
|
||||
t.Run("unit/runs_script_with_helpers", func(t *testing.T) {
|
||||
dir := t.TempDir()
|
||||
path := filepath.Join(dir, luaTestScript)
|
||||
script := `
|
||||
local rows = csv.read("a,b\n1,2", { hasheader = true })
|
||||
assert(rows[1].a == "1")
|
||||
assert(math.round(2.567, 2) == 2.57)
|
||||
assert(string.trim(" x ") == "x")
|
||||
assert(util.num("42") == 42)
|
||||
`
|
||||
writeTestFile(t, path, script)
|
||||
require.NoError(t, RunLuaFile([]string{path}))
|
||||
})
|
||||
|
||||
t.Run("unit/script_has_full_command_context", func(t *testing.T) {
|
||||
dir := t.TempDir()
|
||||
setWorkingDir(t, dir)
|
||||
writeTestFile(t, luaTestScript, `
|
||||
assert(type(csv.read) == "function")
|
||||
assert(type(json.read) == "function")
|
||||
assert(type(xml.read) == "function")
|
||||
assert(type(fetch) == "function")
|
||||
assert(type(re) == "function")
|
||||
assert(type(print) == "function")
|
||||
assert(type(ctx) == "table")
|
||||
assert(ctx.source_file ~= nil)
|
||||
assert(ctx.target_file ~= nil)
|
||||
assert(type(ctx.capture) == "table")
|
||||
assert(command_name ~= nil)
|
||||
assert(type(file) == "string")
|
||||
assert(modified == false)
|
||||
`)
|
||||
require.NoError(t, RunLuaFile([]string{luaTestScript}))
|
||||
})
|
||||
|
||||
t.Run("unit/files_run_in_order_in_shared_state", func(t *testing.T) {
|
||||
dir := t.TempDir()
|
||||
lib := filepath.Join(dir, "lib.lua")
|
||||
main := filepath.Join(dir, "main.lua")
|
||||
writeTestFile(t, lib, "function double(x) return x * 2 end\n")
|
||||
writeTestFile(t, main, "assert(double(21) == 42)\n")
|
||||
require.NoError(t, RunLuaFile([]string{lib, main}))
|
||||
})
|
||||
|
||||
t.Run("unit/runtime_error_returns_error", func(t *testing.T) {
|
||||
dir := t.TempDir()
|
||||
path := filepath.Join(dir, "bad.lua")
|
||||
writeTestFile(t, path, "error('boom')\n")
|
||||
err := RunLuaFile([]string{path})
|
||||
require.Error(t, err)
|
||||
assert.Contains(t, err.Error(), "boom")
|
||||
})
|
||||
|
||||
t.Run("unit/runtime_error_stacktrace_is_readable_multiline", func(t *testing.T) {
|
||||
dir := t.TempDir()
|
||||
path := filepath.Join(dir, "bad.lua")
|
||||
writeTestFile(t, path, "local t = nil\nutil.dump(t)\n")
|
||||
err := RunLuaFile([]string{path})
|
||||
require.Error(t, err)
|
||||
msg := err.Error()
|
||||
assert.Contains(t, msg, "\n", "error must keep real line breaks in stack trace")
|
||||
assert.Contains(t, msg, "stack traceback")
|
||||
assert.NotContains(t, msg, "\\n", "error must not contain literal \\n escape tokens")
|
||||
assert.NotContains(t, msg, "\t", "error must not contain tabs")
|
||||
assert.False(t, strings.HasSuffix(msg, "\n"), "error must not end in a newline")
|
||||
})
|
||||
|
||||
t.Run("unit/missing_args_errors", func(t *testing.T) {
|
||||
err := RunLuaFile(nil)
|
||||
require.Error(t, err)
|
||||
assert.Contains(t, err.Error(), "missing lua file path")
|
||||
})
|
||||
|
||||
t.Run("unit/missing_file_errors", func(t *testing.T) {
|
||||
dir := t.TempDir()
|
||||
setWorkingDir(t, dir)
|
||||
err := RunLuaFile([]string{"nope.lua"})
|
||||
require.Error(t, err)
|
||||
})
|
||||
|
||||
t.Run("unit/run_resolves_json_read_relative_to_script", func(t *testing.T) {
|
||||
dir := t.TempDir()
|
||||
setWorkingDir(t, dir)
|
||||
writeTestFile(t, "data.json", `{"x":1}`)
|
||||
writeTestFile(t, luaTestScript, "local v = json.read('data.json')\nassert(v.x == 1)\n")
|
||||
require.NoError(t, RunLuaFile([]string{luaTestScript}))
|
||||
})
|
||||
|
||||
t.Run("unit/second_argument_watch_mode_stays_alive", func(t *testing.T) {
|
||||
dir := t.TempDir()
|
||||
setWorkingDir(t, dir)
|
||||
writeTestFile(t, luaTestScript, "local x = 1\n")
|
||||
done := make(chan error, 1)
|
||||
go func() {
|
||||
done <- RunLuaFileWatch([]string{luaTestScript})
|
||||
}()
|
||||
select {
|
||||
case err := <-done:
|
||||
t.Fatalf("watch mode returned early: %v", err)
|
||||
case <-time.After(700 * time.Millisecond):
|
||||
}
|
||||
})
|
||||
}
|
||||
@@ -0,0 +1,44 @@
|
||||
package chef
|
||||
|
||||
import (
|
||||
"fmt"
|
||||
"os"
|
||||
|
||||
"cook/utils"
|
||||
|
||||
logger "git.site.quack-lab.dev/dave/cylogger/v3"
|
||||
)
|
||||
|
||||
func RunResetSnapshots() error {
|
||||
log := logger.With("cmd", "reset")
|
||||
log.Info("Resetting all files to their original state from database")
|
||||
if err := withSnapshotDB(resetAllFiles); err != nil {
|
||||
return fmt.Errorf("failed to reset all files: %w", err)
|
||||
}
|
||||
log.Info("Successfully reset all files to original state")
|
||||
return nil
|
||||
}
|
||||
|
||||
func resetAllFiles(db utils.DB) error {
|
||||
log := logger.With("func", "resetAllFiles")
|
||||
log.Debug("Starting reset all files operation")
|
||||
fileSnapshots, err := db.GetAllFiles()
|
||||
if err != nil {
|
||||
log.Error("Failed to get all file snapshots from database", "err", err)
|
||||
return err
|
||||
}
|
||||
log.Debug("Found files in database to reset", "count", len(fileSnapshots))
|
||||
|
||||
for _, fileSnapshot := range fileSnapshots {
|
||||
flog := log.With("target", fileSnapshot.FilePath)
|
||||
flog.Debug("Resetting file")
|
||||
err = os.WriteFile(fileSnapshot.FilePath, fileSnapshot.FileData, 0644)
|
||||
if err != nil {
|
||||
flog.Warn("Failed to write file to disk", "err", err)
|
||||
continue
|
||||
}
|
||||
flog.Debug("File written to disk successfully")
|
||||
}
|
||||
log.Debug("Finished reset all files operation")
|
||||
return nil
|
||||
}
|
||||
@@ -0,0 +1,105 @@
|
||||
package chef
|
||||
|
||||
import (
|
||||
"os"
|
||||
"path/filepath"
|
||||
"testing"
|
||||
|
||||
"cook/utils"
|
||||
|
||||
"github.com/stretchr/testify/assert"
|
||||
"github.com/stretchr/testify/require"
|
||||
"gorm.io/gorm"
|
||||
)
|
||||
|
||||
type fakeResetDB struct {
|
||||
files []utils.FileSnapshot
|
||||
err error
|
||||
}
|
||||
|
||||
func (f fakeResetDB) DB() *gorm.DB { return nil }
|
||||
func (f fakeResetDB) Raw(sql string, args ...any) *gorm.DB { return &gorm.DB{} }
|
||||
func (f fakeResetDB) SaveFile(filePath string, fileData []byte) error { return nil }
|
||||
func (f fakeResetDB) GetFile(filePath string) ([]byte, error) { return nil, f.err }
|
||||
func (f fakeResetDB) GetAllFiles() ([]utils.FileSnapshot, error) { return f.files, f.err }
|
||||
func (f fakeResetDB) GetGlobCache(key string) ([]string, error) { return nil, gorm.ErrRecordNotFound }
|
||||
func (f fakeResetDB) SaveGlobCache(key string, files []string) error { return nil }
|
||||
func (f fakeResetDB) ClearGlobCache() error { return nil }
|
||||
func (f fakeResetDB) Close() error { return nil }
|
||||
|
||||
func TestResetAllFiles(t *testing.T) {
|
||||
tmpDir, err := os.MkdirTemp("", "reset-all-test-*")
|
||||
assert.NoError(t, err)
|
||||
defer func() {
|
||||
if err := os.RemoveAll(tmpDir); err != nil {
|
||||
t.Logf("failed to remove temp dir: %v", err)
|
||||
}
|
||||
}()
|
||||
origDir, err := os.Getwd()
|
||||
require.NoError(t, err)
|
||||
defer func() {
|
||||
if err := os.Chdir(origDir); err != nil {
|
||||
t.Logf("failed to restore working directory: %v", err)
|
||||
}
|
||||
}()
|
||||
require.NoError(t, os.Chdir(tmpDir))
|
||||
|
||||
file1 := filepath.Join(tmpDir, "file1.txt")
|
||||
file2 := filepath.Join(tmpDir, "file2.txt")
|
||||
|
||||
err = os.WriteFile(file1, []byte("original1"), 0644)
|
||||
assert.NoError(t, err)
|
||||
err = os.WriteFile(file2, []byte("original2"), 0644)
|
||||
assert.NoError(t, err)
|
||||
|
||||
db, err := utils.GetDB()
|
||||
assert.NoError(t, err)
|
||||
defer closeTestDB(t, db)
|
||||
err = db.SaveFile(file1, []byte("original1"))
|
||||
assert.NoError(t, err)
|
||||
err = db.SaveFile(file2, []byte("original2"))
|
||||
assert.NoError(t, err)
|
||||
|
||||
err = os.WriteFile(file1, []byte("modified1"), 0644)
|
||||
assert.NoError(t, err)
|
||||
err = os.WriteFile(file2, []byte("modified2"), 0644)
|
||||
assert.NoError(t, err)
|
||||
|
||||
data, err := os.ReadFile(file1)
|
||||
assert.NoError(t, err)
|
||||
assert.Equal(t, "modified1", string(data))
|
||||
|
||||
err = resetAllFiles(db)
|
||||
assert.NoError(t, err)
|
||||
|
||||
data, err = os.ReadFile(file1)
|
||||
assert.NoError(t, err)
|
||||
assert.Equal(t, "original1", string(data))
|
||||
|
||||
data, err = os.ReadFile(file2)
|
||||
assert.NoError(t, err)
|
||||
assert.Equal(t, "original2", string(data))
|
||||
}
|
||||
|
||||
func TestResetAllFilesGetAllFilesError(t *testing.T) {
|
||||
err := resetAllFiles(fakeResetDB{err: assert.AnError})
|
||||
assert.ErrorIs(t, err, assert.AnError)
|
||||
}
|
||||
|
||||
func TestResetAllFilesContinuesOnWriteError(t *testing.T) {
|
||||
tmpDir := t.TempDir()
|
||||
goodFile := filepath.Join(tmpDir, "good.txt")
|
||||
badFile := filepath.Join(tmpDir, "missing", "bad.txt")
|
||||
require.NoError(t, os.WriteFile(goodFile, []byte("stale"), 0644))
|
||||
|
||||
db := fakeResetDB{files: []utils.FileSnapshot{
|
||||
{FilePath: badFile, FileData: []byte("x")},
|
||||
{FilePath: goodFile, FileData: []byte("fresh")},
|
||||
}}
|
||||
|
||||
require.NoError(t, resetAllFiles(db))
|
||||
|
||||
data, err := os.ReadFile(goodFile)
|
||||
require.NoError(t, err)
|
||||
assert.Equal(t, "fresh", string(data))
|
||||
}
|
||||
@@ -0,0 +1,97 @@
|
||||
package chef
|
||||
|
||||
import (
|
||||
"encoding/json"
|
||||
"fmt"
|
||||
"io"
|
||||
"os"
|
||||
"sort"
|
||||
"strings"
|
||||
|
||||
jsonpath "github.com/theory/jsonpath"
|
||||
)
|
||||
|
||||
type JSONSearchConfig struct {
|
||||
Expr string
|
||||
Files []string
|
||||
Stdout io.Writer
|
||||
Stderr io.Writer
|
||||
}
|
||||
|
||||
// RunJSONSearch evaluates a JSONPath expression against each file and prints
|
||||
// every line containing a match, ripgrep style. args[0] is the expression;
|
||||
// remaining args are files, or the current directory is searched recursively
|
||||
// for *.json files. Nothing is printed when no file matches.
|
||||
func RunJSONSearch(args []string, stdout, stderr io.Writer) error {
|
||||
if len(args) == 0 {
|
||||
return fmt.Errorf("missing jsonpath expression")
|
||||
}
|
||||
cfg := JSONSearchConfig{
|
||||
Expr: args[0],
|
||||
Files: args[1:],
|
||||
Stdout: stdout,
|
||||
Stderr: stderr,
|
||||
}
|
||||
return runJSONSearch(cfg)
|
||||
}
|
||||
|
||||
func runJSONSearch(cfg JSONSearchConfig) error {
|
||||
path, err := jsonpath.Parse(cfg.Expr)
|
||||
if err != nil {
|
||||
return fmt.Errorf("invalid jsonpath expression %q: %w", cfg.Expr, err)
|
||||
}
|
||||
cfg.Stdout, cfg.Stderr = defaultWriters(cfg.Stdout, cfg.Stderr)
|
||||
|
||||
files, err := searchFileArgs(cfg.Files, ".json")
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
return searchJSONFiles(path, files, cfg)
|
||||
}
|
||||
|
||||
func searchJSONFiles(path *jsonpath.Path, files []string, cfg JSONSearchConfig) error {
|
||||
return runSearchOverFiles(searchIO{stdout: cfg.Stdout, stderr: cfg.Stderr, prefix: "rj"}, files, func(file string) ([]int, string, error) {
|
||||
data, err := os.ReadFile(file)
|
||||
if err != nil {
|
||||
return nil, "", err
|
||||
}
|
||||
return searchJSONContent(path, data)
|
||||
})
|
||||
}
|
||||
|
||||
// searchJSONContent evaluates path against data and returns the matched line
|
||||
// numbers together with the normalized content they refer to.
|
||||
func searchJSONContent(path *jsonpath.Path, data []byte) ([]int, string, error) {
|
||||
content := strings.TrimPrefix(string(data), "\xEF\xBB\xBF")
|
||||
var root interface{}
|
||||
if err := json.Unmarshal([]byte(content), &root); err != nil {
|
||||
return nil, "", fmt.Errorf("parse JSON: %w", err)
|
||||
}
|
||||
lines, err := jsonPathMatchLines(path, content, root)
|
||||
if err != nil {
|
||||
return nil, "", err
|
||||
}
|
||||
return lines, content, nil
|
||||
}
|
||||
|
||||
func jsonPathMatchLines(path *jsonpath.Path, content string, root interface{}) ([]int, error) {
|
||||
located := path.SelectLocated(root)
|
||||
seen := make(map[int]bool)
|
||||
var lines []int
|
||||
for _, node := range located {
|
||||
start, end, ok := resolveJSONPointerRange(content, node.Path.Pointer())
|
||||
if !ok {
|
||||
continue
|
||||
}
|
||||
startLine := searchLineOf(content, start)
|
||||
endLine := searchLineOf(content, end)
|
||||
for l := startLine; l <= endLine; l++ {
|
||||
if !seen[l] {
|
||||
seen[l] = true
|
||||
lines = append(lines, l)
|
||||
}
|
||||
}
|
||||
}
|
||||
sort.Ints(lines)
|
||||
return lines, nil
|
||||
}
|
||||
@@ -0,0 +1,222 @@
|
||||
package chef
|
||||
|
||||
import (
|
||||
"bytes"
|
||||
"encoding/json"
|
||||
"io"
|
||||
"os"
|
||||
"path/filepath"
|
||||
"testing"
|
||||
|
||||
"github.com/stretchr/testify/assert"
|
||||
"github.com/stretchr/testify/require"
|
||||
jsonpath "github.com/theory/jsonpath"
|
||||
)
|
||||
|
||||
const testAmmoPath = "$..ammo"
|
||||
|
||||
func runRJSearch(expr string, files []string, stdout, stderr io.Writer) error {
|
||||
return RunJSONSearch(append([]string{expr}, files...), stdout, stderr)
|
||||
}
|
||||
|
||||
func TestResolveJSONPointerRange(t *testing.T) {
|
||||
content := `{
|
||||
"items": [
|
||||
{ "id": "a", "ammo": [ "arrow" ] },
|
||||
{ "id": "b", "ammo": [ "bolt" ] }
|
||||
]
|
||||
}`
|
||||
|
||||
t.Run("unit/pointer/root_value", func(t *testing.T) {
|
||||
start, end, ok := resolveJSONPointerRange(content, "")
|
||||
require.True(t, ok)
|
||||
assert.Equal(t, 0, start)
|
||||
assert.Equal(t, len(content), end)
|
||||
})
|
||||
|
||||
t.Run("unit/pointer/object_member", func(t *testing.T) {
|
||||
start, end, ok := resolveJSONPointerRange(content, "/items")
|
||||
require.True(t, ok)
|
||||
assert.Equal(t, `[`, string(content[start]))
|
||||
assert.Equal(t, `]`, string(content[end-1]))
|
||||
})
|
||||
|
||||
t.Run("unit/pointer/array_element", func(t *testing.T) {
|
||||
start, end, ok := resolveJSONPointerRange(content, "/items/0/id")
|
||||
require.True(t, ok)
|
||||
assert.Equal(t, `"a"`, content[start:end])
|
||||
})
|
||||
|
||||
t.Run("unit/pointer/nested_ammo", func(t *testing.T) {
|
||||
start, end, ok := resolveJSONPointerRange(content, "/items/1/ammo")
|
||||
require.True(t, ok)
|
||||
assert.Equal(t, `[ "bolt" ]`, content[start:end])
|
||||
})
|
||||
|
||||
t.Run("unit/pointer/missing_member", func(t *testing.T) {
|
||||
_, _, ok := resolveJSONPointerRange(content, "/items/0/missing")
|
||||
assert.False(t, ok)
|
||||
})
|
||||
|
||||
t.Run("unit/pointer/escaped_tokens", func(t *testing.T) {
|
||||
escaped := `{"a/b":{"c~d":42}}`
|
||||
start, end, ok := resolveJSONPointerRange(escaped, "/a~1b/c~0d")
|
||||
require.True(t, ok)
|
||||
assert.Equal(t, "42", escaped[start:end])
|
||||
})
|
||||
}
|
||||
|
||||
func TestJSONPathMatchLines(t *testing.T) {
|
||||
content := "{\n \"ammo\": [ \"arrow\" ],\n \"other\": 1\n}\n"
|
||||
|
||||
t.Run("unit/rj/recursive_descent_ammo", func(t *testing.T) {
|
||||
path, err := jsonpath.Parse(testAmmoPath)
|
||||
require.NoError(t, err)
|
||||
var root interface{}
|
||||
require.NoError(t, json.Unmarshal([]byte(content), &root))
|
||||
lines, err := jsonPathMatchLines(path, content, root)
|
||||
require.NoError(t, err)
|
||||
assert.Equal(t, []int{2}, lines)
|
||||
})
|
||||
|
||||
t.Run("unit/rj/filter_predicate", func(t *testing.T) {
|
||||
doc := "{\n \"items\": [\n { \"price\": 5 },\n { \"price\": 15 }\n ]\n}\n"
|
||||
path, err := jsonpath.Parse("$.items[?(@.price > 10)]")
|
||||
require.NoError(t, err)
|
||||
var root interface{}
|
||||
require.NoError(t, json.Unmarshal([]byte(doc), &root))
|
||||
lines, err := jsonPathMatchLines(path, doc, root)
|
||||
require.NoError(t, err)
|
||||
assert.Equal(t, []int{4}, lines)
|
||||
})
|
||||
}
|
||||
|
||||
func TestRunJSONSearch(t *testing.T) {
|
||||
dir := t.TempDir()
|
||||
write := func(name, content string) string {
|
||||
p := filepath.Join(dir, name)
|
||||
require.NoError(t, os.WriteFile(p, []byte(content), 0644))
|
||||
return p
|
||||
}
|
||||
fileA := write("a.json", "{\n \"ammo\": [ \"arrow\" ],\n \"x\": 1\n}\n")
|
||||
fileB := write("b.json", "{\n \"y\": 2\n}\n")
|
||||
fileC := write("c.json", "{\n \"z\": 0,\n \"ammo\": [ \"bolt\" ]\n}\n")
|
||||
|
||||
t.Run("unit/rj/multi_file_heading_no_trailing_blank", func(t *testing.T) {
|
||||
var out bytes.Buffer
|
||||
var errOut bytes.Buffer
|
||||
err := runRJSearch(testAmmoPath, []string{fileA, fileB}, &out, &errOut)
|
||||
require.NoError(t, err)
|
||||
assert.Equal(t, fileA+"\n2: \"ammo\": [ \"arrow\" ],\n", out.String())
|
||||
})
|
||||
|
||||
t.Run("unit/rj/blank_separator_between_file_blocks", func(t *testing.T) {
|
||||
var out bytes.Buffer
|
||||
var errOut bytes.Buffer
|
||||
err := runRJSearch(testAmmoPath, []string{fileA, fileC}, &out, &errOut)
|
||||
require.NoError(t, err)
|
||||
assert.Equal(t,
|
||||
fileA+"\n2: \"ammo\": [ \"arrow\" ],\n"+
|
||||
"\n"+
|
||||
fileC+"\n3: \"ammo\": [ \"bolt\" ]\n",
|
||||
out.String())
|
||||
})
|
||||
|
||||
t.Run("unit/rj/single_file_no_heading", func(t *testing.T) {
|
||||
var out bytes.Buffer
|
||||
var errOut bytes.Buffer
|
||||
err := runRJSearch(testAmmoPath, []string{fileA}, &out, &errOut)
|
||||
require.NoError(t, err)
|
||||
assert.Equal(t, "2: \"ammo\": [ \"arrow\" ],\n", out.String())
|
||||
})
|
||||
|
||||
t.Run("unit/rj/ammo_scoped_battery_filter", func(t *testing.T) {
|
||||
doc := "{\n" +
|
||||
" \"pocket_data\": [\n" +
|
||||
" { \"pocket_type\": \"MAGAZINE\", \"ammo_restriction\": { \"battery\": 15, \"arrow\": 1 } },\n" +
|
||||
" { \"pocket_type\": \"MAGAZINE\", \"ammo_restriction\": { \"battery\": 1 } }\n" +
|
||||
" ],\n" +
|
||||
" \"unrelated\": { \"battery\": 99 }\n" +
|
||||
"}\n"
|
||||
file := write("ammo.json", doc)
|
||||
var out bytes.Buffer
|
||||
var errOut bytes.Buffer
|
||||
err := runRJSearch("$..*[?(@.ammo_restriction.battery > 1)]", []string{file}, &out, &errOut)
|
||||
require.NoError(t, err)
|
||||
assert.Equal(t, "3: { \"pocket_type\": \"MAGAZINE\", \"ammo_restriction\": { \"battery\": 15, \"arrow\": 1 } },\n", out.String())
|
||||
})
|
||||
|
||||
t.Run("unit/rj/ammo_filter_on_object_member_matches_nothing", func(t *testing.T) {
|
||||
doc := "{\n" +
|
||||
" \"pocket_data\": [\n" +
|
||||
" { \"pocket_type\": \"MAGAZINE\", \"ammo_restriction\": { \"battery\": 15 } }\n" +
|
||||
" ]\n" +
|
||||
"}\n"
|
||||
file := write("ammo2.json", doc)
|
||||
var out bytes.Buffer
|
||||
var errOut bytes.Buffer
|
||||
err := runRJSearch("$..ammo_restriction[?(@.battery > 1)]", []string{file}, &out, &errOut)
|
||||
require.NoError(t, err)
|
||||
assert.Equal(t, "", out.String())
|
||||
})
|
||||
|
||||
t.Run("unit/rj/no_matches_prints_nothing", func(t *testing.T) {
|
||||
var out bytes.Buffer
|
||||
var errOut bytes.Buffer
|
||||
err := runRJSearch("$..nothing", []string{fileB}, &out, &errOut)
|
||||
require.NoError(t, err)
|
||||
assert.Equal(t, "", out.String())
|
||||
})
|
||||
|
||||
t.Run("unit/rj/invalid_expression", func(t *testing.T) {
|
||||
var out bytes.Buffer
|
||||
var errOut bytes.Buffer
|
||||
err := runRJSearch("$$$not a path", []string{fileA}, &out, &errOut)
|
||||
require.Error(t, err)
|
||||
assert.Contains(t, err.Error(), "invalid jsonpath")
|
||||
})
|
||||
|
||||
t.Run("unit/rj/unparseable_file_reports_to_stderr", func(t *testing.T) {
|
||||
bad := write("bad.json", "{ not json")
|
||||
var out bytes.Buffer
|
||||
var errOut bytes.Buffer
|
||||
err := runRJSearch(testAmmoPath, []string{bad}, &out, &errOut)
|
||||
require.NoError(t, err)
|
||||
assert.Equal(t, "", out.String())
|
||||
assert.Contains(t, errOut.String(), "parse JSON")
|
||||
})
|
||||
|
||||
t.Run("unit/rj/glob_expansion", func(t *testing.T) {
|
||||
var out bytes.Buffer
|
||||
var errOut bytes.Buffer
|
||||
pattern := filepath.Join(dir, "*.json")
|
||||
err := runRJSearch(testAmmoPath, []string{pattern}, &out, &errOut)
|
||||
require.NoError(t, err)
|
||||
assert.Contains(t, out.String(), fileA+"\n")
|
||||
assert.Contains(t, out.String(), "2: \"ammo\": [ \"arrow\" ],")
|
||||
})
|
||||
|
||||
t.Run("unit/rj/glob_no_match_errors", func(t *testing.T) {
|
||||
var out bytes.Buffer
|
||||
var errOut bytes.Buffer
|
||||
err := runRJSearch(testAmmoPath, []string{filepath.Join(dir, "nope*.json")}, &out, &errOut)
|
||||
require.Error(t, err)
|
||||
assert.Contains(t, err.Error(), "no files matched")
|
||||
})
|
||||
}
|
||||
|
||||
func TestSearchLineHelpers(t *testing.T) {
|
||||
content := "line one\nline two\r\nline three"
|
||||
|
||||
t.Run("unit/search/line_of", func(t *testing.T) {
|
||||
assert.Equal(t, 1, searchLineOf(content, 0))
|
||||
assert.Equal(t, 2, searchLineOf(content, 9))
|
||||
assert.Equal(t, 3, searchLineOf(content, len(content)))
|
||||
})
|
||||
|
||||
t.Run("unit/search/line_at_strips_cr", func(t *testing.T) {
|
||||
assert.Equal(t, "line one", searchLineAt(content, 1))
|
||||
assert.Equal(t, "line two", searchLineAt(content, 2))
|
||||
assert.Equal(t, "line three", searchLineAt(content, 3))
|
||||
})
|
||||
}
|
||||
@@ -0,0 +1,119 @@
|
||||
package chef
|
||||
|
||||
import (
|
||||
_ "embed"
|
||||
"fmt"
|
||||
"io"
|
||||
"os"
|
||||
"path/filepath"
|
||||
|
||||
"cook/processor"
|
||||
|
||||
logger "git.site.quack-lab.dev/dave/cylogger/v3"
|
||||
)
|
||||
|
||||
//go:embed example_cook.toml
|
||||
var exampleCookToml string
|
||||
|
||||
const exampleCookTomlPath = "example_cook.toml"
|
||||
|
||||
func ExampleCookTomlContent() string {
|
||||
return exampleCookToml
|
||||
}
|
||||
|
||||
func WriteExampleCookToml() error {
|
||||
log := logger.With("func", "WriteExampleCookToml")
|
||||
log.Debug("Creating example configuration file")
|
||||
log.Debug("Writing example_cook.toml", "target", exampleCookTomlPath)
|
||||
err := os.WriteFile(exampleCookTomlPath, []byte(exampleCookToml), 0644)
|
||||
if err != nil {
|
||||
log.Error("Failed to write example_cook.toml", "err", err, "target", exampleCookTomlPath)
|
||||
return err
|
||||
}
|
||||
log.Info("Wrote example_cook.toml", "target", exampleCookTomlPath)
|
||||
return nil
|
||||
}
|
||||
|
||||
func GenerateMetaLua() error {
|
||||
cwd, err := os.Getwd()
|
||||
if err != nil {
|
||||
logger.Error("Failed to get current directory", "err", err)
|
||||
return err
|
||||
}
|
||||
metaPath := filepath.Join(cwd, "meta.lua")
|
||||
return processor.GenerateMetaFile(metaPath)
|
||||
}
|
||||
|
||||
type RootRunConfig struct {
|
||||
Stdout io.Writer
|
||||
CookArgs []string
|
||||
Version bool
|
||||
Example bool
|
||||
Meta bool
|
||||
Parallel int
|
||||
Filter string
|
||||
GlobalHooksPath string
|
||||
}
|
||||
|
||||
func RunRoot(cfg RootRunConfig) error {
|
||||
switch {
|
||||
case cfg.Version:
|
||||
return runVersion(cfg)
|
||||
case cfg.Example:
|
||||
return WriteExampleCookToml()
|
||||
case cfg.Meta:
|
||||
return GenerateMetaLua()
|
||||
default:
|
||||
return RunCookfiles(RunCookfilesConfig{
|
||||
CookPaths: defaultCookArgs(cfg.CookArgs),
|
||||
Parallel: cfg.Parallel,
|
||||
Filter: cfg.Filter,
|
||||
GlobalHooksPath: cfg.GlobalHooksPath,
|
||||
})
|
||||
}
|
||||
}
|
||||
|
||||
// defaultCookArgs returns *.toml when no cook files are given, so running with
|
||||
// no arguments behaves like "chef *.toml".
|
||||
func defaultCookArgs(args []string) []string {
|
||||
if len(args) > 0 {
|
||||
return args
|
||||
}
|
||||
return []string{"*.toml"}
|
||||
}
|
||||
|
||||
func runVersion(cfg RootRunConfig) error {
|
||||
if _, err := fmt.Fprintln(cfg.Stdout, VersionString()); err != nil {
|
||||
return err
|
||||
}
|
||||
return nil
|
||||
}
|
||||
|
||||
type PersistentPreRunInput struct {
|
||||
SubcommandName string
|
||||
LogLevel string
|
||||
Version bool
|
||||
NoColor bool
|
||||
}
|
||||
|
||||
func PersistentPreRun(in PersistentPreRunInput) {
|
||||
if in.SubcommandName == "tui" {
|
||||
ConfigureLogger(in.LogLevel, in.NoColor)
|
||||
return
|
||||
}
|
||||
if in.SubcommandName == "gen" {
|
||||
logger.Init(logger.ParseLevel("WARNING"), !in.NoColor)
|
||||
return
|
||||
}
|
||||
if in.SubcommandName == "rj" || in.SubcommandName == "xj" {
|
||||
ConfigureLogger(in.LogLevel, in.NoColor)
|
||||
return
|
||||
}
|
||||
if in.Version {
|
||||
return
|
||||
}
|
||||
ConfigureLogger(in.LogLevel, in.NoColor)
|
||||
log := logger.With("cmd", in.SubcommandName)
|
||||
log.Info("chef", "version", VersionString())
|
||||
log.Info("Initializing with log level", "level", in.LogLevel)
|
||||
}
|
||||
@@ -0,0 +1,57 @@
|
||||
package chef
|
||||
|
||||
import (
|
||||
"os"
|
||||
"testing"
|
||||
|
||||
logger "git.site.quack-lab.dev/dave/cylogger/v3"
|
||||
"github.com/stretchr/testify/assert"
|
||||
"github.com/stretchr/testify/require"
|
||||
)
|
||||
|
||||
const (
|
||||
defaultDataTxt = "data.txt"
|
||||
defaultDataOne = "value=1\n"
|
||||
defaultDataTwo = "value=2\n"
|
||||
)
|
||||
|
||||
func TestRunRootDefaultsToToml(t *testing.T) {
|
||||
logger.Init(logger.LevelInfo, false)
|
||||
setWorkingDir(t, t.TempDir())
|
||||
ResetGlobalStatsForTest()
|
||||
|
||||
require.NoError(t, os.WriteFile(defaultDataTxt, []byte(defaultDataOne), 0644))
|
||||
require.NoError(t, os.WriteFile("cook.toml", []byte(`[[commands]]
|
||||
name = "bump"
|
||||
regex = "(1)"
|
||||
lua = "v1 = v1 + 1"
|
||||
files = ["data.txt"]
|
||||
`), 0644))
|
||||
|
||||
require.NoError(t, RunRoot(RootRunConfig{Parallel: 100}))
|
||||
|
||||
b, err := os.ReadFile(defaultDataTxt)
|
||||
require.NoError(t, err)
|
||||
assert.Equal(t, defaultDataTwo, string(b))
|
||||
}
|
||||
|
||||
func TestRunRootDefaultsToTomlSkipsYaml(t *testing.T) {
|
||||
logger.Init(logger.LevelInfo, false)
|
||||
setWorkingDir(t, t.TempDir())
|
||||
ResetGlobalStatsForTest()
|
||||
|
||||
require.NoError(t, os.WriteFile(defaultDataTxt, []byte(defaultDataOne), 0644))
|
||||
require.NoError(t, os.WriteFile("cook.yaml", []byte(`commands:
|
||||
- name: bump
|
||||
regex: "(1)"
|
||||
lua: "v1 = v1 + 1"
|
||||
files: ["data.txt"]
|
||||
`), 0644))
|
||||
|
||||
err := RunRoot(RootRunConfig{Parallel: 100})
|
||||
require.Error(t, err)
|
||||
|
||||
b, readErr := os.ReadFile(defaultDataTxt)
|
||||
require.NoError(t, readErr)
|
||||
assert.Equal(t, defaultDataOne, string(b))
|
||||
}
|
||||
@@ -0,0 +1,34 @@
|
||||
package chef
|
||||
|
||||
import (
|
||||
"os"
|
||||
"path/filepath"
|
||||
"testing"
|
||||
|
||||
"github.com/stretchr/testify/assert"
|
||||
"github.com/stretchr/testify/require"
|
||||
)
|
||||
|
||||
func TestExampleCookTomlContent(t *testing.T) {
|
||||
t.Run("unit/returns_non_empty_embedded_example", func(t *testing.T) {
|
||||
s := ExampleCookTomlContent()
|
||||
assert.NotEmpty(t, s)
|
||||
assert.Contains(t, s, "[[commands]]")
|
||||
})
|
||||
}
|
||||
|
||||
func TestWriteExampleCookToml(t *testing.T) {
|
||||
t.Run("unit/writes_file_matching_example_content", func(t *testing.T) {
|
||||
tmp := t.TempDir()
|
||||
origDir, err := os.Getwd()
|
||||
require.NoError(t, err)
|
||||
require.NoError(t, os.Chdir(tmp))
|
||||
t.Cleanup(func() { require.NoError(t, os.Chdir(origDir)) })
|
||||
|
||||
require.NoError(t, WriteExampleCookToml())
|
||||
|
||||
b, err := os.ReadFile(filepath.Join(tmp, "example_cook.toml"))
|
||||
require.NoError(t, err)
|
||||
assert.Equal(t, ExampleCookTomlContent(), string(b))
|
||||
})
|
||||
}
|
||||
@@ -0,0 +1,90 @@
|
||||
package chef
|
||||
|
||||
import (
|
||||
"fmt"
|
||||
"os"
|
||||
"time"
|
||||
|
||||
"cook/tui"
|
||||
"cook/utils"
|
||||
|
||||
logger "git.site.quack-lab.dev/dave/cylogger/v3"
|
||||
)
|
||||
|
||||
const cookWatchInterval = 500 * time.Millisecond
|
||||
|
||||
// RunRootWatch runs cook files exactly like RunRoot, then keeps watching them
|
||||
// and re-runs all cook files whenever any of them changes on disk until
|
||||
// interrupted.
|
||||
func RunRootWatch(cfg RootRunConfig) error {
|
||||
if done, err := runRootOneShot(cfg); done {
|
||||
return err
|
||||
}
|
||||
|
||||
cfg.CookArgs = defaultCookArgs(cfg.CookArgs)
|
||||
watchFiles, err := collectCookFilesFromArgs(cfg.CookArgs)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
if len(watchFiles) == 0 {
|
||||
return ErrShowUsage
|
||||
}
|
||||
watchFiles = appendCookWatchHooks(watchFiles, cfg.GlobalHooksPath)
|
||||
|
||||
runCookOnce := func() {
|
||||
resetRuntimeStats()
|
||||
if err := RunRoot(cfg); err != nil {
|
||||
logger.Error("Cook run failed")
|
||||
fmt.Fprintln(os.Stderr, err)
|
||||
}
|
||||
}
|
||||
|
||||
runCookOnce()
|
||||
return watchCookFiles(watchFiles, runCookOnce)
|
||||
}
|
||||
|
||||
// runRootOneShot handles the one-shot root operations (version, example, meta)
|
||||
// and reports whether they were handled.
|
||||
func runRootOneShot(cfg RootRunConfig) (bool, error) {
|
||||
switch {
|
||||
case cfg.Version:
|
||||
return true, runVersion(cfg)
|
||||
case cfg.Example:
|
||||
return true, WriteExampleCookToml()
|
||||
case cfg.Meta:
|
||||
return true, GenerateMetaLua()
|
||||
}
|
||||
return false, nil
|
||||
}
|
||||
|
||||
func appendCookWatchHooks(watchFiles []string, hooksPath string) []string {
|
||||
if hooksPath == "" {
|
||||
return watchFiles
|
||||
}
|
||||
hooks := utils.ResolvePath(hooksPath)
|
||||
if _, statErr := os.Stat(hooks); statErr != nil {
|
||||
return watchFiles
|
||||
}
|
||||
return append(watchFiles, hooks)
|
||||
}
|
||||
|
||||
func watchCookFiles(watchFiles []string, runCookOnce func()) error {
|
||||
logger.Info("Watching for changes", "paths", watchFiles)
|
||||
events, errs, stop, err := tui.StartCookWatcher(watchFiles, cookWatchInterval)
|
||||
if err != nil {
|
||||
return fmt.Errorf("failed to start watcher: %w", err)
|
||||
}
|
||||
defer stop()
|
||||
|
||||
for {
|
||||
select {
|
||||
case <-events:
|
||||
logger.Info("File changed, re-running", "paths", watchFiles)
|
||||
runCookOnce()
|
||||
case err := <-errs:
|
||||
if err != nil {
|
||||
logger.Error("Watch error", "err", err)
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,88 @@
|
||||
package chef
|
||||
|
||||
import (
|
||||
"os"
|
||||
"path/filepath"
|
||||
"testing"
|
||||
"time"
|
||||
|
||||
logger "git.site.quack-lab.dev/dave/cylogger/v3"
|
||||
"github.com/stretchr/testify/assert"
|
||||
"github.com/stretchr/testify/require"
|
||||
)
|
||||
|
||||
const watchDataTxt = "data.txt"
|
||||
const watchCookToml = "cook.toml"
|
||||
|
||||
func TestRunRootWatch(t *testing.T) {
|
||||
logger.Init(logger.LevelInfo, false)
|
||||
|
||||
t.Run("unit/watch_mode_stays_alive", func(t *testing.T) {
|
||||
dir := t.TempDir()
|
||||
setWorkingDir(t, dir)
|
||||
ResetGlobalStatsForTest()
|
||||
|
||||
require.NoError(t, os.WriteFile(watchDataTxt, []byte("value=1\n"), 0644))
|
||||
cook := `[[commands]]
|
||||
name = "bump"
|
||||
regex = "(1)"
|
||||
lua = "v1 = v1 + 1"
|
||||
files = ["data.txt"]
|
||||
`
|
||||
cookPath := filepath.Join(dir, watchCookToml)
|
||||
require.NoError(t, os.WriteFile(cookPath, []byte(cook), 0644))
|
||||
|
||||
done := make(chan error, 1)
|
||||
go func() {
|
||||
done <- RunRootWatch(RootRunConfig{
|
||||
CookArgs: []string{watchCookToml},
|
||||
Parallel: 100,
|
||||
})
|
||||
}()
|
||||
|
||||
select {
|
||||
case err := <-done:
|
||||
t.Fatalf("watch mode returned early: %v", err)
|
||||
case <-time.After(700 * time.Millisecond):
|
||||
}
|
||||
})
|
||||
|
||||
t.Run("unit/initial_run_applies_commands", func(t *testing.T) {
|
||||
dir := t.TempDir()
|
||||
setWorkingDir(t, dir)
|
||||
ResetGlobalStatsForTest()
|
||||
|
||||
require.NoError(t, os.WriteFile(watchDataTxt, []byte("value=1\n"), 0644))
|
||||
require.NoError(t, os.WriteFile(watchCookToml, []byte(`[[commands]]
|
||||
name = "bump"
|
||||
regex = "(1)"
|
||||
lua = "v1 = v1 + 1"
|
||||
files = ["data.txt"]
|
||||
`), 0644))
|
||||
|
||||
done := make(chan error, 1)
|
||||
go func() {
|
||||
done <- RunRootWatch(RootRunConfig{
|
||||
CookArgs: []string{watchCookToml},
|
||||
Parallel: 100,
|
||||
})
|
||||
}()
|
||||
defer func() {
|
||||
select {
|
||||
case <-done:
|
||||
case <-time.After(1 * time.Second):
|
||||
}
|
||||
}()
|
||||
|
||||
deadline := time.Now().Add(3 * time.Second)
|
||||
for time.Now().Before(deadline) {
|
||||
b, err := os.ReadFile(watchDataTxt)
|
||||
require.NoError(t, err)
|
||||
if string(b) == "value=2\n" {
|
||||
return
|
||||
}
|
||||
time.Sleep(50 * time.Millisecond)
|
||||
}
|
||||
assert.Fail(t, "initial watch run did not apply commands")
|
||||
})
|
||||
}
|
||||
@@ -0,0 +1,292 @@
|
||||
package chef
|
||||
|
||||
import (
|
||||
"errors"
|
||||
"fmt"
|
||||
"log/slog"
|
||||
"os"
|
||||
"path/filepath"
|
||||
"sync/atomic"
|
||||
"time"
|
||||
|
||||
"cook/utils"
|
||||
|
||||
logger "git.site.quack-lab.dev/dave/cylogger/v3"
|
||||
cyutils "git.site.quack-lab.dev/dave/cyutils"
|
||||
)
|
||||
|
||||
type RunCookfilesConfig struct {
|
||||
CookPaths []string
|
||||
Parallel int
|
||||
Filter string
|
||||
GlobalHooksPath string
|
||||
}
|
||||
|
||||
func RunCookfiles(cfg RunCookfilesConfig) error {
|
||||
log := logger.With("func", "RunCookfiles")
|
||||
db, commands, err := loadRunInputs(cfg.CookPaths, cfg.Filter, cfg.GlobalHooksPath)
|
||||
if err != nil {
|
||||
log.Error("Failed to load run inputs", "cook_paths", cfg.CookPaths, "filter", cfg.Filter, "err", err)
|
||||
if errors.Is(err, ErrShowUsage) {
|
||||
return err
|
||||
}
|
||||
return nil
|
||||
}
|
||||
defer func() {
|
||||
if cerr := db.Close(); cerr != nil {
|
||||
log.Warn("Failed to close database", "err", cerr)
|
||||
}
|
||||
}()
|
||||
|
||||
for _, cmd := range commands {
|
||||
getOrCreateCommandStats(commandNameForStats(cmd))
|
||||
}
|
||||
|
||||
associations, err := prepareAssociations(commands, db)
|
||||
if err != nil {
|
||||
log.Error("Failed to prepare associations", "command_count", len(commands), "err", err)
|
||||
return nil
|
||||
}
|
||||
|
||||
commandLoggers := buildCommandLoggers(commands)
|
||||
|
||||
startTime := time.Now()
|
||||
processAssociations(cfg.Parallel, associations, db, commandLoggers)
|
||||
processingTime := time.Since(startTime)
|
||||
|
||||
logRunSummary(processingTime)
|
||||
printCommandSummaryTable()
|
||||
return nil
|
||||
}
|
||||
|
||||
func loadRunInputs(args []string, filterFlag string, globalHooksPath string) (utils.DB, []utils.ModifyCommand, error) {
|
||||
log := logger.With("func", "loadRunInputs")
|
||||
log.Debug("Getting database connection")
|
||||
db, err := utils.GetDB()
|
||||
if err != nil {
|
||||
log.Error("Failed to get database", "err", err)
|
||||
return nil, nil, err
|
||||
}
|
||||
log.Debug("Database connection established")
|
||||
|
||||
commands, err := loadRunCommands(args, log)
|
||||
if err != nil {
|
||||
if cerr := db.Close(); cerr != nil {
|
||||
log.Warn("Failed to close database", "err", cerr)
|
||||
}
|
||||
return nil, nil, err
|
||||
}
|
||||
|
||||
commands, err = applyGlobalHooks(commands, globalHooksPath, log)
|
||||
if err != nil {
|
||||
return nil, nil, err
|
||||
}
|
||||
commands = applyCommandFilter(commands, filterFlag, log)
|
||||
|
||||
return db, commands, nil
|
||||
}
|
||||
|
||||
func loadRunCommands(args []string, log *slog.Logger) ([]utils.ModifyCommand, error) {
|
||||
log.Debug("Loading commands from arguments")
|
||||
commands, err := utils.LoadCommands(args)
|
||||
if err != nil || len(commands) == 0 {
|
||||
log.Error("Failed to load commands", "err", err)
|
||||
if err == nil {
|
||||
err = ErrNothingToDo
|
||||
}
|
||||
return nil, fmt.Errorf("%w: %w", ErrShowUsage, err)
|
||||
}
|
||||
log.Info("Loaded commands", "count", len(commands))
|
||||
return commands, nil
|
||||
}
|
||||
|
||||
func applyGlobalHooks(commands []utils.ModifyCommand, globalHooksPath string, log *slog.Logger) ([]utils.ModifyCommand, error) {
|
||||
if globalHooksPath == "" {
|
||||
return commands, nil
|
||||
}
|
||||
globalBefore, globalAfter, err := utils.LoadGlobalHooks(globalHooksPath)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
for i := range commands {
|
||||
commands[i].BeforeEach = globalBefore + "\n" + commands[i].BeforeEach
|
||||
commands[i].AfterEach = commands[i].AfterEach + "\n" + globalAfter
|
||||
}
|
||||
return commands, nil
|
||||
}
|
||||
|
||||
func applyCommandFilter(commands []utils.ModifyCommand, filterFlag string, log *slog.Logger) []utils.ModifyCommand {
|
||||
if filterFlag == "" {
|
||||
return commands
|
||||
}
|
||||
log.Info("Filtering commands by name", "filter", filterFlag)
|
||||
commands = utils.FilterCommands(commands, filterFlag)
|
||||
log.Info("Filtered commands", "count", len(commands))
|
||||
return commands
|
||||
}
|
||||
|
||||
func prepareAssociations(commands []utils.ModifyCommand, db utils.DB) (map[string]utils.FileCommandAssociation, error) {
|
||||
log := logger.With("func", "prepareAssociations")
|
||||
log.Debug("Aggregating globs and deduplicating")
|
||||
globs := utils.AggregateGlobs(commands)
|
||||
log.Debug("Aggregated globs before deduplication", "count", utils.CountGlobsBeforeDedup(commands))
|
||||
|
||||
log.Info("Found unique file patterns", "count", len(globs))
|
||||
log.Debug("Expanding glob patterns to files")
|
||||
files, err := utils.ExpandGlobs(globs, db)
|
||||
if err != nil {
|
||||
log.Error("Failed to expand file patterns", "glob_count", len(globs), "err", err)
|
||||
return nil, err
|
||||
}
|
||||
log.Info("Found files to process", "count", len(files))
|
||||
|
||||
log.Debug("Associating files with commands")
|
||||
associations, err := utils.AssociateFilesWithCommands(files, commands)
|
||||
if err != nil {
|
||||
log.Error("Failed to associate files with commands", "file_count", len(files), "command_count", len(commands), "err", err)
|
||||
return nil, err
|
||||
}
|
||||
log.Debug("Files associated with commands")
|
||||
|
||||
for file, assoc := range associations {
|
||||
log.Debug("File associated with commands", "target", file, "regular", len(assoc.Commands), "isolate", len(assoc.IsolateCommands))
|
||||
}
|
||||
|
||||
log.Debug("Resetting files where necessary")
|
||||
err = utils.ResetWhereNecessary(associations, db)
|
||||
if err != nil {
|
||||
log.Error("Failed to reset files where necessary", "assoc_count", len(associations), "err", err)
|
||||
return nil, err
|
||||
}
|
||||
log.Debug("Files reset where necessary")
|
||||
|
||||
return associations, nil
|
||||
}
|
||||
|
||||
func buildCommandLoggers(commands []utils.ModifyCommand) map[string]*slog.Logger {
|
||||
log := logger.With("func", "buildCommandLoggers")
|
||||
commandLoggers := make(map[string]*slog.Logger)
|
||||
for _, command := range commands {
|
||||
cmdName := command.Name
|
||||
if cmdName == "" {
|
||||
if len(command.Regex) > 20 {
|
||||
cmdName = command.Regex[:17] + "..."
|
||||
} else {
|
||||
cmdName = command.Regex
|
||||
}
|
||||
}
|
||||
|
||||
commandLoggers[command.Name] = logger.With("cmd", cmdName, "src", command.SourceFile, "level", command.LogLevel)
|
||||
|
||||
log.Debug("Created logger for command", "cmd", cmdName, "src", command.SourceFile)
|
||||
}
|
||||
return commandLoggers
|
||||
}
|
||||
|
||||
func processAssociations(parallelFlag int, associations map[string]utils.FileCommandAssociation, db utils.DB, commandLoggers map[string]*slog.Logger) {
|
||||
log := logger.With("func", "processAssociations", "parallel", parallelFlag)
|
||||
log.Debug("Starting file processing")
|
||||
|
||||
cyutils.WithWorkers(parallelFlag, associations, func(worker int, file string, association utils.FileCommandAssociation) {
|
||||
processFile(worker, file, association, db, commandLoggers)
|
||||
})
|
||||
}
|
||||
|
||||
func processFile(worker int, file string, association utils.FileCommandAssociation, db utils.DB, commandLoggers map[string]*slog.Logger) {
|
||||
fileStartTime := time.Now()
|
||||
log := logger.With("func", "processFile", "worker", worker, "target", file)
|
||||
|
||||
log.Debug("Reading file")
|
||||
fileData, err := os.ReadFile(filepath.FromSlash(file))
|
||||
if err != nil {
|
||||
log.Error("Failed to read file", "err", err)
|
||||
atomic.AddInt64(&stats.FailedFiles, 1)
|
||||
return
|
||||
}
|
||||
|
||||
fileDataStr, isChanged, err := runFileCommands(file, string(fileData), association, commandLoggers)
|
||||
if err != nil {
|
||||
atomic.AddInt64(&stats.FailedFiles, 1)
|
||||
return
|
||||
}
|
||||
|
||||
if isChanged {
|
||||
log.Debug("Saving file snapshot to database")
|
||||
if err := db.SaveFile(file, fileData); err != nil {
|
||||
log.Error("Failed to save file snapshot to database", "err", err)
|
||||
atomic.AddInt64(&stats.FailedFiles, 1)
|
||||
return
|
||||
}
|
||||
log.Debug("File snapshot saved to database")
|
||||
}
|
||||
|
||||
log.Debug("Writing file")
|
||||
if err := os.WriteFile(filepath.FromSlash(file), []byte(fileDataStr), 0644); err != nil {
|
||||
log.Error("Failed to write file", "err", err)
|
||||
atomic.AddInt64(&stats.FailedFiles, 1)
|
||||
return
|
||||
}
|
||||
log.Debug("File written")
|
||||
|
||||
atomic.AddInt64(&stats.ProcessedFiles, 1)
|
||||
log.Debug("File processed", "elapsed", time.Since(fileStartTime))
|
||||
}
|
||||
|
||||
func runFileCommands(file string, fileDataStr string, association utils.FileCommandAssociation, commandLoggers map[string]*slog.Logger) (string, bool, error) {
|
||||
log := logger.With("func", "processFile", "target", file)
|
||||
|
||||
log.Debug("Running isolate commands")
|
||||
fileDataStr, err := RunIsolateCommands(association, file, fileDataStr)
|
||||
if err != nil && err != ErrNothingToDo {
|
||||
log.Error("Failed to run isolate commands", "err", err)
|
||||
return fileDataStr, false, err
|
||||
}
|
||||
changed := err != ErrNothingToDo
|
||||
|
||||
log.Debug("Running other commands")
|
||||
fileDataStr, err = RunOtherCommands(file, fileDataStr, association, commandLoggers)
|
||||
if err != nil && err != ErrNothingToDo {
|
||||
log.Error("Failed to run other commands", "err", err)
|
||||
return fileDataStr, false, err
|
||||
}
|
||||
if err != ErrNothingToDo {
|
||||
changed = true
|
||||
}
|
||||
|
||||
return fileDataStr, changed, nil
|
||||
}
|
||||
|
||||
func logRunSummary(processingTime time.Duration) {
|
||||
log := logger.With("func", "logRunSummary")
|
||||
log.Info("Processing completed", "elapsed", processingTime)
|
||||
processedFiles := atomic.LoadInt64(&stats.ProcessedFiles)
|
||||
if processedFiles > 0 {
|
||||
log.Info("Average time per file", "avg", processingTime/time.Duration(processedFiles))
|
||||
}
|
||||
|
||||
totalModifications := atomic.LoadInt64(&stats.TotalModifications)
|
||||
if totalModifications == 0 {
|
||||
log.Warn("No modifications were made in any files")
|
||||
stats.CommandStats.Range(func(key, value interface{}) bool {
|
||||
name := key.(string)
|
||||
cs := value.(*CommandStats)
|
||||
log.Warn("Command produced no modifications",
|
||||
"cmd", name,
|
||||
"files_seen", atomic.LoadInt64(&cs.FilesSeen),
|
||||
"files_predskip", atomic.LoadInt64(&cs.FilesPredicateSkipped),
|
||||
"files_no_match", atomic.LoadInt64(&cs.FilesNoMatch),
|
||||
"lua_errors", atomic.LoadInt64(&cs.LuaErrors),
|
||||
"parse_errors", atomic.LoadInt64(&cs.ParseErrors),
|
||||
"other_errors", atomic.LoadInt64(&cs.OtherErrors),
|
||||
)
|
||||
return true
|
||||
})
|
||||
} else {
|
||||
failedFiles := atomic.LoadInt64(&stats.FailedFiles)
|
||||
log.Info("Operation complete",
|
||||
"modified", totalModifications,
|
||||
"processed", processedFiles,
|
||||
"total", processedFiles+failedFiles,
|
||||
)
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,46 @@
|
||||
package chef
|
||||
|
||||
import (
|
||||
"os"
|
||||
"path/filepath"
|
||||
"testing"
|
||||
|
||||
"github.com/stretchr/testify/require"
|
||||
)
|
||||
|
||||
func TestRunChefEndToEnd(t *testing.T) {
|
||||
tmp, err := os.MkdirTemp("", "runchef-e2e-*")
|
||||
require.NoError(t, err)
|
||||
origDir, err := os.Getwd()
|
||||
require.NoError(t, err)
|
||||
defer func() {
|
||||
if err := os.Chdir(origDir); err != nil {
|
||||
t.Logf("failed to restore working directory: %v", err)
|
||||
}
|
||||
}()
|
||||
require.NoError(t, os.Chdir(tmp))
|
||||
|
||||
ResetGlobalStatsForTest()
|
||||
|
||||
contentPath := filepath.Join(tmp, "sample.txt")
|
||||
require.NoError(t, os.WriteFile(contentPath, []byte("value=1\n"), 0644))
|
||||
|
||||
cookPath := filepath.Join(tmp, "cook.toml")
|
||||
cook := `[[commands]]
|
||||
name = "bump"
|
||||
regex = "(1)"
|
||||
lua = "v1 = v1 + 1"
|
||||
files = ["sample.txt"]
|
||||
`
|
||||
require.NoError(t, os.WriteFile(cookPath, []byte(cook), 0644))
|
||||
|
||||
require.NoError(t, RunCookfiles(RunCookfilesConfig{
|
||||
CookPaths: []string{"cook.toml"},
|
||||
Parallel: 100,
|
||||
Filter: "",
|
||||
}))
|
||||
|
||||
out, err := os.ReadFile(contentPath)
|
||||
require.NoError(t, err)
|
||||
require.Equal(t, "value=2\n", string(out))
|
||||
}
|
||||
@@ -0,0 +1,180 @@
|
||||
package chef
|
||||
|
||||
import (
|
||||
"fmt"
|
||||
"io"
|
||||
"os"
|
||||
"path/filepath"
|
||||
"sort"
|
||||
"strings"
|
||||
|
||||
"cook/utils"
|
||||
)
|
||||
|
||||
// resolveSearchFiles expands file arguments into a sorted, deduplicated list.
|
||||
// Arguments containing glob metacharacters are expanded with doublestar;
|
||||
// plain paths must exist on disk.
|
||||
func resolveSearchFiles(args []string) ([]string, error) {
|
||||
var files []string
|
||||
seen := make(map[string]bool)
|
||||
for _, arg := range args {
|
||||
matches, err := expandSearchPattern(arg)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
for _, m := range matches {
|
||||
norm := filepath.Clean(m)
|
||||
if !seen[norm] {
|
||||
seen[norm] = true
|
||||
files = append(files, norm)
|
||||
}
|
||||
}
|
||||
}
|
||||
sort.Strings(files)
|
||||
return files, nil
|
||||
}
|
||||
|
||||
// expandSearchPattern expands a single file argument: plain paths must exist
|
||||
// on disk, glob patterns are resolved with doublestar.
|
||||
func expandSearchPattern(arg string) ([]string, error) {
|
||||
if !strings.ContainsAny(arg, "*?[") {
|
||||
if _, err := os.Stat(arg); err != nil {
|
||||
return nil, fmt.Errorf("no such file %q", arg)
|
||||
}
|
||||
return []string{arg}, nil
|
||||
}
|
||||
matches, err := utils.GlobFullPaths(arg)
|
||||
if err != nil {
|
||||
return nil, fmt.Errorf("invalid file pattern %q: %w", arg, err)
|
||||
}
|
||||
if len(matches) == 0 {
|
||||
return nil, fmt.Errorf("no files matched pattern %q", arg)
|
||||
}
|
||||
return matches, nil
|
||||
}
|
||||
|
||||
// searchFileArgs resolves the files to search. Explicit arguments are
|
||||
// expanded exactly like ripgrep paths; with none, the current directory is
|
||||
// searched recursively for files with the given extension.
|
||||
func searchFileArgs(args []string, ext string) ([]string, error) {
|
||||
if len(args) > 0 {
|
||||
return resolveSearchFiles(args)
|
||||
}
|
||||
pattern := "**/*" + ext
|
||||
matches, err := utils.GlobFullPaths(pattern)
|
||||
if err != nil {
|
||||
return nil, fmt.Errorf("glob %q in current directory: %w", pattern, err)
|
||||
}
|
||||
if len(matches) == 0 {
|
||||
return nil, fmt.Errorf("no files matched %q in current directory", pattern)
|
||||
}
|
||||
sort.Strings(matches)
|
||||
return matches, nil
|
||||
}
|
||||
|
||||
// printSearchLines writes one file's matching lines to w in ripgrep style:
|
||||
// "line:content" per match, with the file path as a heading when showHeading
|
||||
// is set. Separators between file blocks are the caller's responsibility.
|
||||
func printSearchLines(w io.Writer, name, content string, lines []int, showHeading bool) error {
|
||||
if showHeading {
|
||||
if _, err := fmt.Fprintln(w, name); err != nil {
|
||||
return err
|
||||
}
|
||||
}
|
||||
for _, l := range lines {
|
||||
if _, err := fmt.Fprintf(w, "%d:%s\n", l, searchLineAt(content, l)); err != nil {
|
||||
return err
|
||||
}
|
||||
}
|
||||
return nil
|
||||
}
|
||||
|
||||
// searchIO carries the output writers and diagnostic prefix for a search run.
|
||||
type searchIO struct {
|
||||
stdout io.Writer
|
||||
stderr io.Writer
|
||||
prefix string
|
||||
}
|
||||
|
||||
// runSearchOverFiles evaluates searchOne for each file and prints its matching
|
||||
// lines in ripgrep style. A blank line separates file blocks; files without
|
||||
// matches print nothing.
|
||||
func runSearchOverFiles(ioCfg searchIO, files []string, searchOne func(file string) ([]int, string, error)) error {
|
||||
multiFile := len(files) > 1
|
||||
wroteBlock := false
|
||||
for _, file := range files {
|
||||
lines, content, err := searchOne(file)
|
||||
if err != nil {
|
||||
if werr := reportSearchError(ioCfg.stderr, ioCfg.prefix, file, err); werr != nil {
|
||||
return werr
|
||||
}
|
||||
continue
|
||||
}
|
||||
if len(lines) == 0 {
|
||||
continue
|
||||
}
|
||||
wroteBlock, err = writeSearchBlock(ioCfg, file, content, lines, multiFile, wroteBlock)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
}
|
||||
return nil
|
||||
}
|
||||
|
||||
func writeSearchBlock(ioCfg searchIO, file, content string, lines []int, showHeading, separator bool) (bool, error) {
|
||||
if separator {
|
||||
if _, err := fmt.Fprintln(ioCfg.stdout); err != nil {
|
||||
return true, err
|
||||
}
|
||||
}
|
||||
if err := printSearchLines(ioCfg.stdout, file, content, lines, showHeading); err != nil {
|
||||
return true, fmt.Errorf("write search results for %s: %w", file, err)
|
||||
}
|
||||
return true, nil
|
||||
}
|
||||
|
||||
// defaultWriters replaces nil writers with os.Stdout/os.Stderr.
|
||||
func defaultWriters(stdout, stderr io.Writer) (io.Writer, io.Writer) {
|
||||
if stdout == nil {
|
||||
stdout = os.Stdout
|
||||
}
|
||||
if stderr == nil {
|
||||
stderr = os.Stderr
|
||||
}
|
||||
return stdout, stderr
|
||||
}
|
||||
|
||||
// reportSearchError writes a per-file diagnostic to stderr. A non-nil return
|
||||
// means the diagnostic itself could not be written.
|
||||
func reportSearchError(w io.Writer, prefix, file string, err error) error {
|
||||
if _, werr := fmt.Fprintf(w, "%s: %s: %v\n", prefix, file, err); werr != nil {
|
||||
return werr
|
||||
}
|
||||
return nil
|
||||
}
|
||||
|
||||
func searchLineOf(content string, pos int) int {
|
||||
if pos < 0 {
|
||||
pos = 0
|
||||
}
|
||||
if pos > len(content) {
|
||||
pos = len(content)
|
||||
}
|
||||
return strings.Count(content[:pos], "\n") + 1
|
||||
}
|
||||
|
||||
func searchLineAt(content string, line int) string {
|
||||
i := 0
|
||||
for n := 1; n < line; n++ {
|
||||
j := strings.IndexByte(content[i:], '\n')
|
||||
if j < 0 {
|
||||
return content[i:]
|
||||
}
|
||||
i += j + 1
|
||||
}
|
||||
j := strings.IndexByte(content[i:], '\n')
|
||||
if j < 0 {
|
||||
return strings.TrimSuffix(content[i:], "\r")
|
||||
}
|
||||
return strings.TrimSuffix(content[i:i+j], "\r")
|
||||
}
|
||||
@@ -0,0 +1,63 @@
|
||||
package chef
|
||||
|
||||
import (
|
||||
"os"
|
||||
"path/filepath"
|
||||
"testing"
|
||||
|
||||
"github.com/stretchr/testify/assert"
|
||||
"github.com/stretchr/testify/require"
|
||||
)
|
||||
|
||||
const testSearchJSONName = "a.json"
|
||||
|
||||
func TestSearchFileArgs(t *testing.T) {
|
||||
t.Run("unit/search/explicit_args_resolved", func(t *testing.T) {
|
||||
dir := t.TempDir()
|
||||
a := filepath.Join(dir, testSearchJSONName)
|
||||
require.NoError(t, os.WriteFile(a, []byte("{}"), 0644))
|
||||
files, err := searchFileArgs([]string{a}, ".json")
|
||||
require.NoError(t, err)
|
||||
assert.Equal(t, []string{a}, files)
|
||||
})
|
||||
|
||||
t.Run("unit/search/no_args_recursive_by_extension", func(t *testing.T) {
|
||||
dir := t.TempDir()
|
||||
require.NoError(t, os.MkdirAll(filepath.Join(dir, "sub"), 0755))
|
||||
require.NoError(t, os.WriteFile(filepath.Join(dir, testSearchJSONName), []byte("{}"), 0644))
|
||||
require.NoError(t, os.WriteFile(filepath.Join(dir, "sub", "b.json"), []byte("{}"), 0644))
|
||||
require.NoError(t, os.WriteFile(filepath.Join(dir, "sub", "c.xml"), []byte("<a/>"), 0644))
|
||||
wd, err := os.Getwd()
|
||||
require.NoError(t, err)
|
||||
require.NoError(t, os.Chdir(dir))
|
||||
t.Cleanup(func() {
|
||||
if err := os.Chdir(wd); err != nil {
|
||||
return
|
||||
}
|
||||
})
|
||||
|
||||
files, err := searchFileArgs(nil, ".json")
|
||||
require.NoError(t, err)
|
||||
got := make([]string, 0, len(files))
|
||||
for _, f := range files {
|
||||
got = append(got, filepath.Clean(f))
|
||||
}
|
||||
assert.ElementsMatch(t, []string{testSearchJSONName, filepath.Join("sub", "b.json")}, got)
|
||||
})
|
||||
|
||||
t.Run("unit/search/no_args_no_matches_errors", func(t *testing.T) {
|
||||
dir := t.TempDir()
|
||||
wd, err := os.Getwd()
|
||||
require.NoError(t, err)
|
||||
require.NoError(t, os.Chdir(dir))
|
||||
t.Cleanup(func() {
|
||||
if err := os.Chdir(wd); err != nil {
|
||||
return
|
||||
}
|
||||
})
|
||||
|
||||
_, err = searchFileArgs(nil, ".json")
|
||||
require.Error(t, err)
|
||||
assert.Contains(t, err.Error(), "no files matched")
|
||||
})
|
||||
}
|
||||
@@ -0,0 +1,23 @@
|
||||
package chef
|
||||
|
||||
import "sync"
|
||||
|
||||
type GlobalStats struct {
|
||||
TotalMatches int64
|
||||
TotalModifications int64
|
||||
ProcessedFiles int64
|
||||
FailedFiles int64
|
||||
ModificationsPerCommand sync.Map
|
||||
CommandStats sync.Map
|
||||
}
|
||||
|
||||
var stats = GlobalStats{
|
||||
ModificationsPerCommand: sync.Map{},
|
||||
}
|
||||
|
||||
func ResetGlobalStatsForTest() {
|
||||
stats = GlobalStats{
|
||||
ModificationsPerCommand: sync.Map{},
|
||||
CommandStats: sync.Map{},
|
||||
}
|
||||
}
|
||||
+15062
File diff suppressed because it is too large.
Load diff
+184
@@ -0,0 +1,184 @@
|
||||
files = ['../src/activity_actor.cpp']
|
||||
|
||||
[[commands]]
|
||||
name = 'Reduce hand crank charge time'
|
||||
regex = 'to_seconds<int>\( !num_seconds \)'
|
||||
lua = '1'
|
||||
|
||||
[[commands]]
|
||||
name = 'Auto-unload battery on full charge'
|
||||
regex = '''
|
||||
() add_msg\( m_info, _\( "You've charged the battery completely\." \) \);
|
||||
'''
|
||||
lua = '''
|
||||
s1 = [[
|
||||
item_location iloc = item_location(who, &hand_crank_item);
|
||||
who.unload(iloc, false);
|
||||
]]
|
||||
'''
|
||||
|
||||
[[commands]]
|
||||
name = 'Increase fishing catch chance'
|
||||
regex = 'x_in_y\( fish_chance, !num \)'
|
||||
lua = '/100'
|
||||
|
||||
[[commands]]
|
||||
name = 'Boost tree chop yields'
|
||||
regexes = [
|
||||
'log_quan = rng\( 2, !num \)',
|
||||
'stick_quan = rng\( 0, !num \)',
|
||||
'log_quan = rng\( 0, !num \)',
|
||||
'splint_quan = rng\( 5, !num \)',
|
||||
]
|
||||
lua = '* 5'
|
||||
|
||||
[[commands]]
|
||||
name = 'Fix single-use stackable consumption'
|
||||
regex = '''
|
||||
if\( used_tool->has_flag\( flag_SINGLE_USE \) \) \{
|
||||
(it\.remove_item\(\);)
|
||||
'''
|
||||
lua = '''
|
||||
s1 = [[
|
||||
if( !it->count_by_charges() ||
|
||||
it->use_charges( it->typeId(), charges_consumed, used, it.pos_bub( here ) ) ) {
|
||||
it.remove_item();
|
||||
}]]
|
||||
'''
|
||||
|
||||
[[commands]]
|
||||
name = 'Zero activity consumed moves'
|
||||
regex = '(std::max\( who\.item_handling_cost\( \*loc, true, 0, it->count\(\), true \), 1 \))'
|
||||
lua = '0'
|
||||
|
||||
[[commands]]
|
||||
name = 'Zero activity item move cost'
|
||||
regex = '(std::max\( who\.item_handling_cost\( \*item, true, 0, -1, true \), 1 \))'
|
||||
lua = '0'
|
||||
[[commands]]
|
||||
name = 'gen_activity_actor_1'
|
||||
regex = '''
|
||||
continue;
|
||||
\}
|
||||
|
||||
( bool is_adjacent_or_closer = square_dist\( you\.pos_bub\(\), src_bub \) <= 1;
|
||||
if\( !is_adjacent_or_closer \) \{
|
||||
add_msg_debug\( debugmode::DF_ACTIVITY,
|
||||
"zone_sort THINK: routing to source \(%d,%d,%d\) from \(%d,%d\)",
|
||||
src\.x\(\), src\.y\(\), src\.z\(\),
|
||||
you\.pos_bub\(\)\.x\(\), you\.pos_bub\(\)\.y\(\) \);
|
||||
// Route to source\. Can't skip: post-cutoff fallback tiles weren't pre-evaluated by route_length\.
|
||||
if\( !zone_sorting::route_to_destination\( you, act, src_bub, stage \) \) \{
|
||||
add_msg_debug\( debugmode::DF_ACTIVITY,
|
||||
"zone_sort THINK: route to source FAILED, trying next" \);
|
||||
continue;
|
||||
\}
|
||||
return false;
|
||||
\})
|
||||
add_msg_debug\( debugmode::DF_ACTIVITY,
|
||||
'''
|
||||
lua = '''
|
||||
s1 = [[]]
|
||||
'''
|
||||
files = ['src/activity_actor.cpp']
|
||||
noreset = false
|
||||
|
||||
[[commands]]
|
||||
name = 'gen_activity_actor_2'
|
||||
regex = '''
|
||||
add_msg_debug\( debugmode::DF_ACTIVITY,
|
||||
( "zone_sort THINK: adjacent to source \(%d,%d,%d\), entering DO",)
|
||||
src\.x\(\), src\.y\(\), src\.z\(\) \);
|
||||
stage = DO;
|
||||
break;
|
||||
'''
|
||||
lua = '''
|
||||
s1 = [[ "zone_sort THINK: source (%d,%d,%d), entering DO",]]
|
||||
'''
|
||||
|
||||
[[commands]]
|
||||
name = 'gen_activity_actor_3'
|
||||
regex = '''
|
||||
num_processed = 0;
|
||||
\}
|
||||
|
||||
( bool is_adjacent_or_closer = square_dist\( you\.pos_bub\(\), src_bub \) <= 1;
|
||||
// before we move any item, check if player is at or
|
||||
// adjacent to the loot source tile
|
||||
if\( !is_adjacent_or_closer \) \{
|
||||
add_msg_debug\( debugmode::DF_ACTIVITY,
|
||||
"zone_sort DO: NOT adjacent to src \(dist=%d\), back to THINK",
|
||||
square_dist\( you\.pos_bub\(\), src_bub \) \);
|
||||
stage = THINK;
|
||||
you\.mod_moves\( -1 \);
|
||||
return;
|
||||
\}
|
||||
)
|
||||
zone_sorting::zone_items items = zone_sorting::populate_items\( src_bub \);
|
||||
|
||||
zone_sorting::unload_sort_options zone_unload_options = zone_sorting::set_unload_options\( you, src,
|
||||
'''
|
||||
lua = '''
|
||||
s1 = [[]]
|
||||
'''
|
||||
|
||||
[[commands]]
|
||||
name = 'gen_activity_actor_4'
|
||||
regex = '''
|
||||
if\( dest == src \) \{
|
||||
continue;
|
||||
\}
|
||||
( if\( square_dist\( abspos, dest \) > 1 \) \{
|
||||
continue;
|
||||
\})
|
||||
const tripoint_bub_ms dest_bub = here\.get_bub\( dest \);
|
||||
if\( !here\.inbounds\( dest_bub \) \|\| here\.is_open_air\( dest_bub \) \) \{
|
||||
continue;
|
||||
'''
|
||||
lua = '''
|
||||
s1 = [[]]
|
||||
'''
|
||||
|
||||
[[commands]]
|
||||
name = 'gen_activity_actor_5'
|
||||
regex = '''
|
||||
\}
|
||||
continue;
|
||||
\}
|
||||
() \}
|
||||
|
||||
// Picking up
|
||||
'''
|
||||
lua = '''
|
||||
s1 = [[ continue;
|
||||
]]
|
||||
'''
|
||||
[[commands]]
|
||||
name = 'gen_activity_actor_1'
|
||||
regex = '''
|
||||
continue;
|
||||
\}
|
||||
|
||||
( bool is_adjacent_or_closer = square_dist\( you\.pos_bub\(\), src_bub \) <= 1;
|
||||
if\( !is_adjacent_or_closer \) \{
|
||||
add_msg_debug\( debugmode::DF_ACTIVITY,
|
||||
"zone_sort THINK: routing to source \(%d,%d,%d\) from \(%d,%d\)",
|
||||
src\.x\(\), src\.y\(\), src\.z\(\),
|
||||
you\.pos_bub\(\)\.x\(\), you\.pos_bub\(\)\.y\(\) \);
|
||||
// Route to source\. Can't skip: post-cutoff fallback tiles weren't pre-evaluated by route_length\.
|
||||
if\( !zone_sorting::route_to_destination\( you, act, src_bub, stage \) \) \{
|
||||
add_msg_debug\( debugmode::DF_ACTIVITY,
|
||||
"zone_sort THINK: route to source FAILED, trying next" \);
|
||||
continue;
|
||||
\}
|
||||
return false;
|
||||
\})
|
||||
add_msg_debug\( debugmode::DF_ACTIVITY,
|
||||
"zone_sort THINK: adjacent to source \(%d,%d,%d\), entering DO",
|
||||
src\.x\(\), src\.y\(\), src\.z\(\) \);
|
||||
'''
|
||||
lua = '''
|
||||
s1 = [[]]
|
||||
'''
|
||||
files = ['src/activity_actor.cpp']
|
||||
noreset = false
|
||||
@@ -0,0 +1,238 @@
|
||||
package chef
|
||||
|
||||
import (
|
||||
"bufio"
|
||||
"fmt"
|
||||
"io"
|
||||
"log/slog"
|
||||
"os"
|
||||
"regexp"
|
||||
"time"
|
||||
|
||||
"cook/tui"
|
||||
"cook/utils"
|
||||
|
||||
logger "git.site.quack-lab.dev/dave/cylogger/v3"
|
||||
)
|
||||
|
||||
type tuiEntry struct {
|
||||
ID string
|
||||
File string
|
||||
Command utils.ModifyCommand
|
||||
IsIsolate bool
|
||||
}
|
||||
|
||||
type tuiAdapter struct {
|
||||
args []string
|
||||
parallel int
|
||||
filter string
|
||||
db utils.DB
|
||||
logEvents chan<- tui.LogEvent
|
||||
rows []tui.Row
|
||||
entries map[string]tuiEntry
|
||||
fingerprints map[string]string
|
||||
watched map[string]bool
|
||||
cookFiles []string
|
||||
captureLevel logger.LogLevel
|
||||
}
|
||||
|
||||
var ansiEscape = regexp.MustCompile(`\x1b\[[0-9;?]*[ -/]*[@-~]`)
|
||||
var commandField = regexp.MustCompile(`\bcommand=("[^"]+"|'[^']+'|[^\s]+)`)
|
||||
var commandFieldAlt = regexp.MustCompile(`\bcommand:("[^"]+"|'[^']+'|[^\s]+)`)
|
||||
|
||||
type TUIConfig struct {
|
||||
Args []string
|
||||
Parallel int
|
||||
Filter string
|
||||
DebugLog bool
|
||||
LogLevel string
|
||||
}
|
||||
|
||||
func RunTUI(cfg TUIConfig) error {
|
||||
logEvents := make(chan tui.LogEvent, 4096)
|
||||
logReader, logWriter := io.Pipe()
|
||||
defer closeLogWriter(logWriter)
|
||||
go pipeLogLines(logReader, func(raw string) {
|
||||
emitLog(logEvents, raw)
|
||||
})
|
||||
|
||||
// Route os.Stderr (ReportLuaError writes multi-line traces there) into the
|
||||
// same log pipe so the TUI renders them instead of splashing raw text over
|
||||
// the screen.
|
||||
stopStderr, err := captureStderr(func(raw string) {
|
||||
emitLog(logEvents, raw)
|
||||
})
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
defer stopStderr()
|
||||
|
||||
captureLvl := logger.ParseLevel(cfg.LogLevel)
|
||||
|
||||
stopLogger, err := configureLogging(captureLvl, cfg.DebugLog, logWriter)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
defer stopLogger()
|
||||
|
||||
adapter, err := newTUIAdapter(cfg, logEvents, captureLvl)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
|
||||
watchEvents, watchErrors, stopWatch, watchEnabled, initialMessage := startTUIWatcher(adapter)
|
||||
if stopWatch != nil {
|
||||
defer stopWatch()
|
||||
}
|
||||
|
||||
app := buildTUIApp(adapter, tuiRunInputs{
|
||||
logEvents: logEvents,
|
||||
watchEvents: watchEvents,
|
||||
watchErrors: watchErrors,
|
||||
watchEnabled: watchEnabled,
|
||||
initialMessage: initialMessage,
|
||||
})
|
||||
return runApp(app)
|
||||
}
|
||||
|
||||
func closeLogWriter(w io.Closer) {
|
||||
if err := w.Close(); err != nil {
|
||||
logger.Warn("failed to close log writer", "err", err)
|
||||
}
|
||||
}
|
||||
|
||||
func newTUIAdapter(cfg TUIConfig, logEvents chan tui.LogEvent, captureLvl logger.LogLevel) (*tuiAdapter, error) {
|
||||
db, err := utils.GetDB()
|
||||
if err != nil {
|
||||
return nil, fmt.Errorf("failed to get database: %w", err)
|
||||
}
|
||||
|
||||
adapter := &tuiAdapter{
|
||||
args: cfg.Args,
|
||||
parallel: cfg.Parallel,
|
||||
filter: cfg.Filter,
|
||||
db: db,
|
||||
logEvents: logEvents,
|
||||
entries: make(map[string]tuiEntry),
|
||||
fingerprints: make(map[string]string),
|
||||
watched: make(map[string]bool),
|
||||
captureLevel: captureLvl,
|
||||
}
|
||||
|
||||
if err := adapter.reloadRows(false); err != nil {
|
||||
return nil, err
|
||||
}
|
||||
return adapter, nil
|
||||
}
|
||||
|
||||
func startTUIWatcher(adapter *tuiAdapter) (<-chan struct{}, <-chan error, func(), bool, string) {
|
||||
watchEvents, watchErrors, stopWatch, err := tui.StartCookWatcher(adapter.cookFiles, 500*time.Millisecond)
|
||||
if err != nil {
|
||||
return nil, nil, nil, false, "Watcher disabled: " + err.Error()
|
||||
}
|
||||
message := fmt.Sprintf("Loaded %d entries from %d cook file(s)", len(adapter.entries), len(adapter.cookFiles))
|
||||
return watchEvents, watchErrors, stopWatch, true, message
|
||||
}
|
||||
|
||||
// tuiRunInputs bundles the runtime inputs handed to the TUI app.
|
||||
type tuiRunInputs struct {
|
||||
logEvents chan tui.LogEvent
|
||||
watchEvents <-chan struct{}
|
||||
watchErrors <-chan error
|
||||
watchEnabled bool
|
||||
initialMessage string
|
||||
}
|
||||
|
||||
func buildTUIApp(adapter *tuiAdapter, in tuiRunInputs) *tui.App {
|
||||
return tui.New(tui.Inputs{
|
||||
Rows: adapter.rows,
|
||||
CookFiles: adapter.cookFiles,
|
||||
Version: VersionString(),
|
||||
WatchEvents: in.watchEvents,
|
||||
WatchErrors: in.watchErrors,
|
||||
LogEvents: in.logEvents,
|
||||
WatchEnabled: in.watchEnabled,
|
||||
InitialMessage: in.initialMessage,
|
||||
}, tui.Callbacks{
|
||||
RunSelected: adapter.runSelected,
|
||||
RunAll: adapter.runAll,
|
||||
FormatFile: adapter.runFmt,
|
||||
ResetAll: adapter.runResetAll,
|
||||
DumpAll: adapter.runDumpAll,
|
||||
Escape: adapter.runEscape,
|
||||
OnWatchSync: adapter.syncWatched,
|
||||
OnWatchTick: adapter.onWatchTick,
|
||||
})
|
||||
}
|
||||
|
||||
func runApp(app *tui.App) error {
|
||||
if err := app.Run(); err != nil {
|
||||
return fmt.Errorf("tui run failed: %w", err)
|
||||
}
|
||||
return nil
|
||||
}
|
||||
|
||||
// pipeLogLines scans reader line by line and hands each to emit.
|
||||
func pipeLogLines(reader io.Reader, emit func(string)) {
|
||||
scanner := bufio.NewScanner(reader)
|
||||
for scanner.Scan() {
|
||||
emit(scanner.Text())
|
||||
}
|
||||
}
|
||||
|
||||
// emitLog splits a raw log line into display lines and pushes each into the
|
||||
// TUI log event channel without blocking.
|
||||
func emitLog(logEvents chan<- tui.LogEvent, raw string) {
|
||||
lines := logDisplayLines(raw)
|
||||
if len(lines) == 0 {
|
||||
return
|
||||
}
|
||||
commandID := parseCommandID(lines[0])
|
||||
for _, line := range lines {
|
||||
select {
|
||||
case logEvents <- tui.LogEvent{Line: line, CommandID: commandID}:
|
||||
default:
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
// configureLogging initializes the logger and routes output to logWriter,
|
||||
// optionally also to chef.log when debugLog is set. The returned stop func
|
||||
// closes the debug log file, if any.
|
||||
func configureLogging(captureLvl logger.LogLevel, debugLog bool, logWriter io.Writer) (func(), error) {
|
||||
logger.Init(captureLvl, true)
|
||||
if !debugLog {
|
||||
logger.ToWritersD(logWriter)
|
||||
logger.WithLevelLineColorD(slog.Level(logger.LevelInfo+1).String(), []string{logger.Purple})
|
||||
return func() {
|
||||
/* no-op cleanup: logging is already bound to the pipe */
|
||||
}, nil
|
||||
}
|
||||
file, err := os.Create("chef.log")
|
||||
if err != nil {
|
||||
return nil, fmt.Errorf("open chef.log: %w", err)
|
||||
}
|
||||
logger.ToWritersD(io.MultiWriter(logWriter, file))
|
||||
logger.WithLevelLineColorD(slog.Level(logger.LevelInfo+1).String(), []string{logger.Purple})
|
||||
return func() {
|
||||
if err := file.Close(); err != nil {
|
||||
logger.Warn("failed to close chef.log", "err", err)
|
||||
}
|
||||
}, nil
|
||||
}
|
||||
|
||||
// captureStderr redirects os.Stderr into a pipe whose lines are handed to
|
||||
// emit, so direct stderr writes (ReportLuaError traces) reach the TUI log
|
||||
// pane instead of corrupting the screen. The returned stop func restores the
|
||||
// original stderr.
|
||||
func captureStderr(emit func(string)) (func(), error) {
|
||||
origStderr := os.Stderr
|
||||
errReader, errWriter, err := os.Pipe()
|
||||
if err != nil {
|
||||
return nil, fmt.Errorf("create stderr pipe: %w", err)
|
||||
}
|
||||
os.Stderr = errWriter
|
||||
go pipeLogLines(errReader, emit)
|
||||
stop := func() { os.Stderr = origStderr }
|
||||
return stop, nil
|
||||
}
|
||||
@@ -0,0 +1,186 @@
|
||||
package chef
|
||||
|
||||
import (
|
||||
"fmt"
|
||||
"sort"
|
||||
"strings"
|
||||
|
||||
"cook/tui"
|
||||
|
||||
logger "git.site.quack-lab.dev/dave/cylogger/v3"
|
||||
)
|
||||
|
||||
func (a *tuiAdapter) runEscape(minimize bool) (string, error) {
|
||||
err := RunEscapeClipboard(minimize)
|
||||
if err != nil {
|
||||
return "", err
|
||||
}
|
||||
return fmt.Sprintf("Escape done (min=%t)", minimize), nil
|
||||
}
|
||||
|
||||
func (a *tuiAdapter) runFmt(path string) (string, error) {
|
||||
flog := logger.With("func", "runFmt", "target", path)
|
||||
if err := formatLuaBlocksInTOML(path, flog); err != nil {
|
||||
return "", err
|
||||
}
|
||||
return "Formatted " + path, nil
|
||||
}
|
||||
|
||||
func (a *tuiAdapter) runResetAll() (string, error) {
|
||||
if err := resetAllFiles(a.db); err != nil {
|
||||
return "", err
|
||||
}
|
||||
return "Reset all files from snapshots", nil
|
||||
}
|
||||
|
||||
func (a *tuiAdapter) runDumpAll() (string, error) {
|
||||
if err := removeAllFiles(a.db); err != nil {
|
||||
return "", err
|
||||
}
|
||||
return "Cleared all snapshots", nil
|
||||
}
|
||||
|
||||
func (a *tuiAdapter) syncWatched(ids []string) error {
|
||||
a.watched = make(map[string]bool, len(ids))
|
||||
for _, id := range ids {
|
||||
a.watched[id] = true
|
||||
}
|
||||
return nil
|
||||
}
|
||||
|
||||
func (a *tuiAdapter) emit(line string, commandID string) {
|
||||
if a.logEvents == nil {
|
||||
return
|
||||
}
|
||||
for _, display := range logDisplayLines(line) {
|
||||
select {
|
||||
case a.logEvents <- tui.LogEvent{Line: display, CommandID: commandID}:
|
||||
default:
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
func sanitizeLogLine(line string) string {
|
||||
line = ansiEscape.ReplaceAllString(line, "")
|
||||
return strings.TrimRight(line, "\r")
|
||||
}
|
||||
|
||||
// logDisplayLines splits a raw log line into readable display lines. The
|
||||
// structured logger escapes multi-line values (like stack traces) into single
|
||||
// physical lines with literal "\n" and "\t" sequences; those must be turned
|
||||
// back into real line breaks and spaces so a stack trace renders as separate
|
||||
// lines instead of one giant wrapped wall. The first line keeps the log
|
||||
// record prefix; the caller is responsible for command attribution.
|
||||
func logDisplayLines(line string) []string {
|
||||
line = sanitizeLogLine(line)
|
||||
line = strings.ReplaceAll(line, `\t`, " ")
|
||||
parts := strings.Split(line, `\n`)
|
||||
out := make([]string, 0, len(parts))
|
||||
for _, p := range parts {
|
||||
if p != "" {
|
||||
out = append(out, p)
|
||||
}
|
||||
}
|
||||
if len(out) == 0 {
|
||||
return nil
|
||||
}
|
||||
return out
|
||||
}
|
||||
|
||||
func parseCommandID(line string) string {
|
||||
clean := ansiEscape.ReplaceAllString(line, "")
|
||||
m := commandField.FindStringSubmatch(clean)
|
||||
if len(m) < 2 {
|
||||
m = commandFieldAlt.FindStringSubmatch(clean)
|
||||
}
|
||||
if len(m) < 2 {
|
||||
return ""
|
||||
}
|
||||
return strings.Trim(m[1], `"'`)
|
||||
}
|
||||
|
||||
func (a *tuiAdapter) onWatchTick() (tui.WatchReloadResult, error) {
|
||||
old := copyFingerprints(a.fingerprints)
|
||||
|
||||
if err := a.reloadRows(true); err != nil {
|
||||
return tui.WatchReloadResult{}, err
|
||||
}
|
||||
|
||||
watchedIDs := changedWatchedIDs(a.watched, old, a.fingerprints)
|
||||
if len(watchedIDs) == 0 {
|
||||
return tui.WatchReloadResult{
|
||||
Rows: a.rows,
|
||||
Message: "Watch tick: no watched command changed",
|
||||
}, nil
|
||||
}
|
||||
|
||||
sort.Strings(watchedIDs)
|
||||
report, err := a.runByIDs(watchedIDs)
|
||||
if err != nil {
|
||||
return tui.WatchReloadResult{}, err
|
||||
}
|
||||
markWatchedAndRunning(report.Summaries, a.watched, watchedIDs)
|
||||
return tui.WatchReloadResult{
|
||||
Rows: a.rows,
|
||||
Report: report,
|
||||
TriggeredRuns: len(watchedIDs),
|
||||
Message: fmt.Sprintf("Watch event: reran %d watched command(s)", len(watchedIDs)),
|
||||
}, nil
|
||||
}
|
||||
|
||||
func copyFingerprints(fingerprints map[string]string) map[string]string {
|
||||
old := make(map[string]string, len(fingerprints))
|
||||
for k, v := range fingerprints {
|
||||
old[k] = v
|
||||
}
|
||||
return old
|
||||
}
|
||||
|
||||
func changedWatchedIDs(watched map[string]bool, old map[string]string, fingerprints map[string]string) []string {
|
||||
ids := make([]string, 0)
|
||||
for id := range watched {
|
||||
newDump, ok := fingerprints[id]
|
||||
if !ok {
|
||||
continue
|
||||
}
|
||||
oldDump, hadOld := old[id]
|
||||
if !hadOld || oldDump != newDump {
|
||||
ids = append(ids, id)
|
||||
}
|
||||
}
|
||||
return ids
|
||||
}
|
||||
|
||||
func (a *tuiAdapter) runSelected(ids []string) (tui.RunReport, error) {
|
||||
report, err := a.runByIDs(ids)
|
||||
if err != nil {
|
||||
return tui.RunReport{}, err
|
||||
}
|
||||
markWatchedAndRunning(report.Summaries, a.watched, nil)
|
||||
return report, nil
|
||||
}
|
||||
|
||||
func (a *tuiAdapter) runAll() (tui.RunReport, error) {
|
||||
ids := make([]string, 0, len(a.entries))
|
||||
for id := range a.entries {
|
||||
ids = append(ids, id)
|
||||
}
|
||||
sort.Strings(ids)
|
||||
report, err := a.runByIDs(ids)
|
||||
if err != nil {
|
||||
return tui.RunReport{}, err
|
||||
}
|
||||
markWatchedAndRunning(report.Summaries, a.watched, nil)
|
||||
return report, nil
|
||||
}
|
||||
|
||||
func markWatchedAndRunning(summaries []tui.CommandSummary, watched map[string]bool, running []string) {
|
||||
runningByID := make(map[string]bool)
|
||||
for _, id := range running {
|
||||
runningByID[id] = true
|
||||
}
|
||||
for i := range summaries {
|
||||
summaries[i].Watched = watched[summaries[i].Name]
|
||||
summaries[i].Running = runningByID[summaries[i].Name]
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,130 @@
|
||||
package chef
|
||||
|
||||
import (
|
||||
"fmt"
|
||||
"path/filepath"
|
||||
"sort"
|
||||
"sync"
|
||||
|
||||
"cook/tui"
|
||||
"cook/utils"
|
||||
|
||||
"gopkg.in/yaml.v3"
|
||||
)
|
||||
|
||||
func buildRowsAndEntriesFromCommands(commands []utils.ModifyCommand, cookFiles []string) ([]tui.Row, map[string]tuiEntry, map[string]string) {
|
||||
commandsBySource := groupCommandsBySource(commands)
|
||||
order := sourceOrder(cookFiles, commandsBySource)
|
||||
labelBySource := sourceLabels(order)
|
||||
|
||||
rows := make([]tui.Row, 0)
|
||||
entries := make(map[string]tuiEntry)
|
||||
fps := make(map[string]string)
|
||||
|
||||
for _, source := range order {
|
||||
cmds := commandsBySource[source]
|
||||
if len(cmds) == 0 {
|
||||
continue
|
||||
}
|
||||
rows = append(rows, tui.Row{ID: "file::" + source, Kind: tui.RowFile, File: source, Label: labelBySource[source]})
|
||||
appendCommandRows(cmds, source, &rows, entries, fps)
|
||||
}
|
||||
|
||||
return rows, entries, fps
|
||||
}
|
||||
|
||||
func groupCommandsBySource(commands []utils.ModifyCommand) map[string][]utils.ModifyCommand {
|
||||
commandsBySource := make(map[string][]utils.ModifyCommand)
|
||||
for _, cmd := range commands {
|
||||
source := cmd.SourceFile
|
||||
if source == "" {
|
||||
source = cmd.SourceDir
|
||||
}
|
||||
commandsBySource[source] = append(commandsBySource[source], cmd)
|
||||
}
|
||||
return commandsBySource
|
||||
}
|
||||
|
||||
func sourceOrder(cookFiles []string, commandsBySource map[string][]utils.ModifyCommand) []string {
|
||||
order := append([]string(nil), cookFiles...)
|
||||
if len(order) == 0 {
|
||||
for source := range commandsBySource {
|
||||
order = append(order, source)
|
||||
}
|
||||
sort.Strings(order)
|
||||
}
|
||||
return order
|
||||
}
|
||||
|
||||
func appendCommandRows(cmds []utils.ModifyCommand, source string, rows *[]tui.Row, entries map[string]tuiEntry, fps map[string]string) {
|
||||
counts := make(map[string]int)
|
||||
for _, cmd := range cmds {
|
||||
counts[cmd.Name]++
|
||||
rowID := fmt.Sprintf("%s::%s#%d", source, cmd.Name, counts[cmd.Name])
|
||||
*rows = append(*rows, tui.Row{ID: rowID, Kind: tui.RowCommand, File: source, Command: cmd.Name, Label: commandRowLabel(cmd)})
|
||||
entries[rowID] = tuiEntry{ID: rowID, File: source, Command: cmd, IsIsolate: cmd.Isolate}
|
||||
fps[rowID] = commandFingerprint(cmd)
|
||||
}
|
||||
}
|
||||
|
||||
func commandRowLabel(cmd utils.ModifyCommand) string {
|
||||
label := cmd.Name
|
||||
if label == "" {
|
||||
label = "<unnamed>"
|
||||
}
|
||||
if cmd.Isolate {
|
||||
label += " [isolate]"
|
||||
}
|
||||
return label
|
||||
}
|
||||
|
||||
func sourceLabels(files []string) map[string]string {
|
||||
labels := make(map[string]string, len(files))
|
||||
baseCount := make(map[string]int)
|
||||
for _, f := range files {
|
||||
baseCount[filepath.Base(f)]++
|
||||
}
|
||||
for _, f := range files {
|
||||
base := filepath.Base(f)
|
||||
if baseCount[base] == 1 {
|
||||
labels[f] = base
|
||||
continue
|
||||
}
|
||||
labels[f] = f
|
||||
}
|
||||
return labels
|
||||
}
|
||||
|
||||
func commandFingerprint(cmd utils.ModifyCommand) string {
|
||||
b, err := yaml.Marshal(cmd)
|
||||
if err != nil {
|
||||
return fmt.Sprintf("marshal-error:%s:%s:%s", cmd.Name, cmd.Regex, cmd.Lua)
|
||||
}
|
||||
return string(b)
|
||||
}
|
||||
|
||||
func resetRuntimeStats() {
|
||||
stats = GlobalStats{ModificationsPerCommand: sync.Map{}, CommandStats: sync.Map{}}
|
||||
}
|
||||
|
||||
func collectCookFilesFromArgs(args []string) ([]string, error) {
|
||||
out := make([]string, 0)
|
||||
seen := make(map[string]struct{})
|
||||
for _, arg := range args {
|
||||
static, pattern := utils.SplitPattern(arg)
|
||||
matches, err := utils.GlobFiles(static, pattern)
|
||||
if err != nil {
|
||||
return nil, fmt.Errorf("failed to resolve cook arg %q: %w", arg, err)
|
||||
}
|
||||
for _, m := range matches {
|
||||
p := utils.ResolvePath(filepath.Join(static, m))
|
||||
if _, exists := seen[p]; exists {
|
||||
continue
|
||||
}
|
||||
seen[p] = struct{}{}
|
||||
out = append(out, p)
|
||||
}
|
||||
}
|
||||
sort.Strings(out)
|
||||
return out, nil
|
||||
}
|
||||
@@ -0,0 +1,41 @@
|
||||
package chef
|
||||
|
||||
import (
|
||||
"testing"
|
||||
|
||||
"github.com/stretchr/testify/assert"
|
||||
"github.com/stretchr/testify/require"
|
||||
)
|
||||
|
||||
func TestLogDisplayLines(t *testing.T) {
|
||||
t.Run("unit/single_line_stays_single", func(t *testing.T) {
|
||||
lines := logDisplayLines("time=1 level=INFO msg=hello")
|
||||
require.Len(t, lines, 1)
|
||||
assert.Equal(t, "time=1 level=INFO msg=hello", lines[0])
|
||||
})
|
||||
|
||||
t.Run("unit/escaped_newline_becomes_separate_lines", func(t *testing.T) {
|
||||
line := "err=\"attempt to index nil\\nstack traceback:\\n <string>:9: in function 'run'\""
|
||||
lines := logDisplayLines(line)
|
||||
require.Len(t, lines, 3)
|
||||
assert.Equal(t, "err=\"attempt to index nil", lines[0])
|
||||
assert.Equal(t, "stack traceback:", lines[1])
|
||||
assert.Equal(t, " <string>:9: in function 'run'\"", lines[2])
|
||||
})
|
||||
|
||||
t.Run("unit/escaped_tab_becomes_spaces", func(t *testing.T) {
|
||||
lines := logDisplayLines("trace:\\t[G]: in function 'pairs'")
|
||||
require.Len(t, lines, 1)
|
||||
assert.Equal(t, "trace: [G]: in function 'pairs'", lines[0])
|
||||
})
|
||||
|
||||
t.Run("unit/ansi_codes_stripped", func(t *testing.T) {
|
||||
lines := logDisplayLines("\x1b[1;32mINFO\x1b[0m msg=ok")
|
||||
require.Len(t, lines, 1)
|
||||
assert.Equal(t, "INFO msg=ok", lines[0])
|
||||
})
|
||||
|
||||
t.Run("unit/empty_line_yields_nothing", func(t *testing.T) {
|
||||
assert.Nil(t, logDisplayLines(""))
|
||||
})
|
||||
}
|
||||
@@ -0,0 +1,161 @@
|
||||
package chef
|
||||
|
||||
import (
|
||||
"fmt"
|
||||
|
||||
"cook/tui"
|
||||
"cook/utils"
|
||||
)
|
||||
|
||||
type commandRowState struct {
|
||||
selected bool
|
||||
watched bool
|
||||
status tui.StatusLight
|
||||
hasStats bool
|
||||
seen int64
|
||||
predSkip int64
|
||||
filesMod int64
|
||||
unchanged int64
|
||||
luaErr int64
|
||||
parseErr int64
|
||||
otherErr int64
|
||||
edits int64
|
||||
}
|
||||
|
||||
func (a *tuiAdapter) reloadRows(preserveSelection bool) error {
|
||||
oldByID, oldByKey := captureRowStates(a.rows, preserveSelection)
|
||||
|
||||
commands, err := utils.LoadCommands(a.args)
|
||||
if err != nil {
|
||||
return fmt.Errorf("failed to load commands: %w", err)
|
||||
}
|
||||
if a.filter != "" {
|
||||
commands = utils.FilterCommands(commands, a.filter)
|
||||
}
|
||||
|
||||
cookFiles, err := collectCookFilesFromArgs(a.args)
|
||||
if err != nil {
|
||||
return fmt.Errorf("failed to resolve cook files: %w", err)
|
||||
}
|
||||
|
||||
rows, entries, fps := buildRowsAndEntriesFromCommands(commands, cookFiles)
|
||||
if preserveSelection {
|
||||
replayRowStates(rows, oldByID, oldByKey)
|
||||
}
|
||||
|
||||
newWatched := computeNewWatched(a.watched, rows, entries, preserveSelection)
|
||||
|
||||
a.rows = rows
|
||||
a.entries = entries
|
||||
a.fingerprints = fps
|
||||
a.watched = newWatched
|
||||
|
||||
a.cookFiles = cookFiles
|
||||
return nil
|
||||
}
|
||||
|
||||
func captureRowStates(rows []tui.Row, preserveSelection bool) (map[string]commandRowState, map[string][]commandRowState) {
|
||||
oldByID := make(map[string]commandRowState)
|
||||
oldByKey := make(map[string][]commandRowState)
|
||||
if !preserveSelection {
|
||||
return oldByID, oldByKey
|
||||
}
|
||||
for i := range rows {
|
||||
if rows[i].Kind != tui.RowCommand {
|
||||
continue
|
||||
}
|
||||
state := commandRowState{
|
||||
selected: rows[i].Selected,
|
||||
watched: rows[i].Watched,
|
||||
status: rows[i].Status,
|
||||
hasStats: rows[i].HasStats,
|
||||
seen: rows[i].Seen,
|
||||
predSkip: rows[i].PredSkip,
|
||||
filesMod: rows[i].FilesMod,
|
||||
unchanged: rows[i].Unchanged,
|
||||
luaErr: rows[i].LuaErr,
|
||||
parseErr: rows[i].ParseErr,
|
||||
otherErr: rows[i].OtherErr,
|
||||
edits: rows[i].Edits,
|
||||
}
|
||||
oldByID[rows[i].ID] = state
|
||||
k := rowStateKey(rows[i].File, rows[i].Command)
|
||||
oldByKey[k] = append(oldByKey[k], state)
|
||||
}
|
||||
return oldByID, oldByKey
|
||||
}
|
||||
|
||||
func replayRowStates(rows []tui.Row, oldByID map[string]commandRowState, oldByKey map[string][]commandRowState) {
|
||||
replayByKeyIndex := make(map[string]int)
|
||||
for i := range rows {
|
||||
if rows[i].Kind != tui.RowCommand {
|
||||
continue
|
||||
}
|
||||
state, ok := oldByID[rows[i].ID]
|
||||
if !ok {
|
||||
k := rowStateKey(rows[i].File, rows[i].Command)
|
||||
idx := replayByKeyIndex[k]
|
||||
if list := oldByKey[k]; idx < len(list) {
|
||||
state = list[idx]
|
||||
replayByKeyIndex[k] = idx + 1
|
||||
ok = true
|
||||
}
|
||||
}
|
||||
if !ok {
|
||||
continue
|
||||
}
|
||||
rows[i].Selected = state.selected
|
||||
rows[i].Watched = state.watched
|
||||
rows[i].Status = state.status
|
||||
rows[i].HasStats = state.hasStats
|
||||
rows[i].Seen = state.seen
|
||||
rows[i].PredSkip = state.predSkip
|
||||
rows[i].FilesMod = state.filesMod
|
||||
rows[i].Unchanged = state.unchanged
|
||||
rows[i].LuaErr = state.luaErr
|
||||
rows[i].ParseErr = state.parseErr
|
||||
rows[i].OtherErr = state.otherErr
|
||||
rows[i].Edits = state.edits
|
||||
}
|
||||
}
|
||||
|
||||
func computeNewWatched(watched map[string]bool, rows []tui.Row, entries map[string]tuiEntry, preserveSelection bool) map[string]bool {
|
||||
if preserveSelection {
|
||||
return watchedRowsBySelection(rows)
|
||||
}
|
||||
newWatched := watchedRowsByEntry(watched, entries)
|
||||
applyWatchedToRows(rows, newWatched)
|
||||
return newWatched
|
||||
}
|
||||
|
||||
func watchedRowsBySelection(rows []tui.Row) map[string]bool {
|
||||
newWatched := make(map[string]bool)
|
||||
for i := range rows {
|
||||
if rows[i].Kind == tui.RowCommand && rows[i].Watched {
|
||||
newWatched[rows[i].ID] = true
|
||||
}
|
||||
}
|
||||
return newWatched
|
||||
}
|
||||
|
||||
func watchedRowsByEntry(watched map[string]bool, entries map[string]tuiEntry) map[string]bool {
|
||||
newWatched := make(map[string]bool)
|
||||
for id := range watched {
|
||||
if _, ok := entries[id]; ok {
|
||||
newWatched[id] = true
|
||||
}
|
||||
}
|
||||
return newWatched
|
||||
}
|
||||
|
||||
func applyWatchedToRows(rows []tui.Row, newWatched map[string]bool) {
|
||||
for i := range rows {
|
||||
if rows[i].Kind == tui.RowCommand {
|
||||
rows[i].Watched = newWatched[rows[i].ID]
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
func rowStateKey(file string, command string) string {
|
||||
return file + "\x1f" + command
|
||||
}
|
||||
@@ -0,0 +1,186 @@
|
||||
package chef
|
||||
|
||||
import (
|
||||
"bytes"
|
||||
"fmt"
|
||||
"log/slog"
|
||||
"sort"
|
||||
"strings"
|
||||
"sync/atomic"
|
||||
"time"
|
||||
|
||||
"cook/tui"
|
||||
"cook/utils"
|
||||
|
||||
logger "git.site.quack-lab.dev/dave/cylogger/v3"
|
||||
)
|
||||
|
||||
func (a *tuiAdapter) runByIDs(ids []string) (tui.RunReport, error) {
|
||||
uniqueIDs := a.uniqueEntryIDs(ids)
|
||||
if len(uniqueIDs) == 0 {
|
||||
return tui.RunReport{}, nil
|
||||
}
|
||||
|
||||
originalLogger := slog.Default()
|
||||
defer slog.SetDefault(originalLogger)
|
||||
|
||||
start := time.Now()
|
||||
commands, runtimeNameToRowID, runtimeNameToDisplay := buildRuntimeCommands(a.entries, uniqueIDs)
|
||||
|
||||
buffer := bytes.NewBuffer(nil)
|
||||
logger.Init(a.captureLevel, false)
|
||||
logger.ToWritersD(buffer)
|
||||
|
||||
resetRuntimeStats()
|
||||
associations, err := a.runAssociations(commands)
|
||||
if err != nil {
|
||||
return tui.RunReport{}, err
|
||||
}
|
||||
|
||||
commandLoggers := buildCommandLoggers(commands)
|
||||
processAssociations(a.parallel, associations, a.db, commandLoggers)
|
||||
logRunSummary(time.Since(start))
|
||||
|
||||
rows := commandSummaryRows()
|
||||
commandSummaries := remapSummaryNames(rows, runtimeNameToRowID)
|
||||
displayRows := displaySummaryRows(rows, runtimeNameToDisplay)
|
||||
utils.RenderCommandSummaryTable(buffer, displayRows)
|
||||
|
||||
processed := atomic.LoadInt64(&stats.ProcessedFiles)
|
||||
failed := atomic.LoadInt64(&stats.FailedFiles)
|
||||
modified := atomic.LoadInt64(&stats.TotalModifications)
|
||||
|
||||
a.emitBufferedLines(buffer, uniqueIDs, runtimeNameToRowID)
|
||||
|
||||
return tui.RunReport{
|
||||
Processed: processed,
|
||||
Failed: failed,
|
||||
Modified: modified,
|
||||
ElapsedMs: time.Since(start).Milliseconds(),
|
||||
Summaries: commandSummaries,
|
||||
}, nil
|
||||
}
|
||||
|
||||
func (a *tuiAdapter) runAssociations(commands []utils.ModifyCommand) (map[string]utils.FileCommandAssociation, error) {
|
||||
globs := utils.AggregateGlobs(commands)
|
||||
files, err := utils.ExpandGlobs(globs, a.db)
|
||||
if err != nil {
|
||||
return nil, fmt.Errorf("failed to expand globs: %w", err)
|
||||
}
|
||||
associations, err := utils.AssociateFilesWithCommands(files, commands)
|
||||
if err != nil {
|
||||
return nil, fmt.Errorf("failed to associate files with commands: %w", err)
|
||||
}
|
||||
if err := utils.ResetWhereNecessary(associations, a.db); err != nil {
|
||||
return nil, fmt.Errorf("failed pre-run reset: %w", err)
|
||||
}
|
||||
return associations, nil
|
||||
}
|
||||
|
||||
func displaySummaryRows(rows []utils.CommandSummaryRow, runtimeNameToDisplay map[string]string) []utils.CommandSummaryRow {
|
||||
displayRows := make([]utils.CommandSummaryRow, len(rows))
|
||||
copy(displayRows, rows)
|
||||
for i := range displayRows {
|
||||
if displayName, ok := runtimeNameToDisplay[displayRows[i].Name]; ok {
|
||||
displayRows[i].Name = displayName
|
||||
}
|
||||
}
|
||||
return displayRows
|
||||
}
|
||||
|
||||
func (a *tuiAdapter) uniqueEntryIDs(ids []string) []string {
|
||||
uniqueIDs := make([]string, 0, len(ids))
|
||||
seen := make(map[string]struct{}, len(ids))
|
||||
for _, id := range ids {
|
||||
if _, ok := seen[id]; ok {
|
||||
continue
|
||||
}
|
||||
seen[id] = struct{}{}
|
||||
if _, ok := a.entries[id]; ok {
|
||||
uniqueIDs = append(uniqueIDs, id)
|
||||
}
|
||||
}
|
||||
return uniqueIDs
|
||||
}
|
||||
|
||||
func buildRuntimeCommands(entries map[string]tuiEntry, uniqueIDs []string) ([]utils.ModifyCommand, map[string]string, map[string]string) {
|
||||
commands := make([]utils.ModifyCommand, 0, len(uniqueIDs))
|
||||
runtimeNameToRowID := make(map[string]string, len(uniqueIDs))
|
||||
runtimeNameToDisplay := make(map[string]string, len(uniqueIDs))
|
||||
for i, id := range uniqueIDs {
|
||||
entry := entries[id]
|
||||
cmd := entry.Command
|
||||
runtimeName := fmt.Sprintf("__tui_%d", i+1)
|
||||
cmd.Name = runtimeName
|
||||
commands = append(commands, cmd)
|
||||
runtimeNameToRowID[runtimeName] = id
|
||||
displayName := entry.Command.Name
|
||||
if displayName == "" {
|
||||
displayName = "<unnamed>"
|
||||
}
|
||||
runtimeNameToDisplay[runtimeName] = displayName
|
||||
}
|
||||
return commands, runtimeNameToRowID, runtimeNameToDisplay
|
||||
}
|
||||
|
||||
func remapSummaryNames(rows []utils.CommandSummaryRow, runtimeNameToRowID map[string]string) []tui.CommandSummary {
|
||||
commandSummaries := toTUISummaries(rows)
|
||||
for i := range commandSummaries {
|
||||
if rowID, ok := runtimeNameToRowID[commandSummaries[i].Name]; ok {
|
||||
commandSummaries[i].Name = rowID
|
||||
}
|
||||
}
|
||||
return commandSummaries
|
||||
}
|
||||
|
||||
func (a *tuiAdapter) emitBufferedLines(buffer *bytes.Buffer, uniqueIDs []string, runtimeNameToRowID map[string]string) {
|
||||
lastCommandID := ""
|
||||
for _, line := range strings.Split(buffer.String(), "\n") {
|
||||
line = strings.TrimSpace(line)
|
||||
if line == "" {
|
||||
continue
|
||||
}
|
||||
runtimeName := parseCommandID(line)
|
||||
commandID := runtimeNameToRowID[runtimeName]
|
||||
if commandID != "" {
|
||||
lastCommandID = commandID
|
||||
} else if lastCommandID != "" {
|
||||
commandID = lastCommandID
|
||||
} else if len(uniqueIDs) == 1 {
|
||||
commandID = uniqueIDs[0]
|
||||
} else {
|
||||
for _, id := range uniqueIDs {
|
||||
a.emit(line, id)
|
||||
}
|
||||
continue
|
||||
}
|
||||
a.emit(line, commandID)
|
||||
}
|
||||
}
|
||||
|
||||
func toTUISummaries(rows []utils.CommandSummaryRow) []tui.CommandSummary {
|
||||
out := make([]tui.CommandSummary, 0, len(rows))
|
||||
for _, r := range rows {
|
||||
light := tui.StatusYellow
|
||||
hasErrors := (r.LuaErr + r.ParseErr + r.OtherErr) > 0
|
||||
if hasErrors {
|
||||
light = tui.StatusRed
|
||||
} else if r.FilesModified > 0 {
|
||||
light = tui.StatusGreen
|
||||
}
|
||||
out = append(out, tui.CommandSummary{
|
||||
Name: r.Name,
|
||||
Seen: r.Seen,
|
||||
PredSkip: r.PredSkip,
|
||||
FilesMod: r.FilesModified,
|
||||
Unchanged: r.FilesUnchanged,
|
||||
LuaErr: r.LuaErr,
|
||||
ParseErr: r.ParseErr,
|
||||
OtherErr: r.OtherErr,
|
||||
Edits: r.Edits,
|
||||
Light: light,
|
||||
})
|
||||
}
|
||||
sort.Slice(out, func(i, j int) bool { return out[i].Name < out[j].Name })
|
||||
return out
|
||||
}
|
||||
@@ -0,0 +1,65 @@
|
||||
package chef
|
||||
|
||||
import (
|
||||
"runtime/debug"
|
||||
"strings"
|
||||
)
|
||||
|
||||
// Set by -ldflags at build time (build.sh).
|
||||
var (
|
||||
Version = "dev"
|
||||
Commit = ""
|
||||
BuildDate = ""
|
||||
)
|
||||
|
||||
func VersionString() string {
|
||||
v := Version
|
||||
c := Commit
|
||||
d := BuildDate
|
||||
|
||||
if info, ok := debug.ReadBuildInfo(); ok {
|
||||
for _, s := range info.Settings {
|
||||
v, c, d = applyBuildSetting(s, v, c, d)
|
||||
}
|
||||
}
|
||||
|
||||
if c != "" && len(c) > 12 {
|
||||
c = c[:12]
|
||||
}
|
||||
|
||||
return joinVersionParts(v, c, d)
|
||||
}
|
||||
|
||||
func applyBuildSetting(s debug.BuildSetting, v, c, d string) (string, string, string) {
|
||||
switch s.Key {
|
||||
case "vcs.revision":
|
||||
if c == "" {
|
||||
c = s.Value
|
||||
}
|
||||
case "vcs.time":
|
||||
if d == "" {
|
||||
d = s.Value
|
||||
}
|
||||
case "vcs.modified":
|
||||
v = markDirtyVersion(v, s.Value)
|
||||
}
|
||||
return v, c, d
|
||||
}
|
||||
|
||||
func markDirtyVersion(v, value string) string {
|
||||
if value == "true" && !strings.HasSuffix(v, "+dirty") {
|
||||
return v + "+dirty"
|
||||
}
|
||||
return v
|
||||
}
|
||||
|
||||
func joinVersionParts(v, c, d string) string {
|
||||
parts := []string{v}
|
||||
if c != "" {
|
||||
parts = append(parts, c)
|
||||
}
|
||||
if d != "" {
|
||||
parts = append(parts, d)
|
||||
}
|
||||
return strings.Join(parts, " ")
|
||||
}
|
||||
@@ -0,0 +1,90 @@
|
||||
package chef
|
||||
|
||||
import (
|
||||
"fmt"
|
||||
"io"
|
||||
"os"
|
||||
"sort"
|
||||
"strings"
|
||||
|
||||
"cook/processor"
|
||||
)
|
||||
|
||||
type XMLSearchConfig struct {
|
||||
Expr string
|
||||
Files []string
|
||||
Stdout io.Writer
|
||||
Stderr io.Writer
|
||||
}
|
||||
|
||||
// RunXMLSearch evaluates an XPath expression against each file and prints
|
||||
// every line containing a match, ripgrep style. args[0] is the expression;
|
||||
// remaining args are files, or the current directory is searched recursively
|
||||
// for *.xml files. Nothing is printed when no file matches.
|
||||
func RunXMLSearch(args []string, stdout, stderr io.Writer) error {
|
||||
if len(args) == 0 {
|
||||
return fmt.Errorf("missing xpath expression")
|
||||
}
|
||||
cfg := XMLSearchConfig{
|
||||
Expr: args[0],
|
||||
Files: args[1:],
|
||||
Stdout: stdout,
|
||||
Stderr: stderr,
|
||||
}
|
||||
return runXMLSearch(cfg)
|
||||
}
|
||||
|
||||
func runXMLSearch(cfg XMLSearchConfig) error {
|
||||
if err := processor.ValidateXMLXPath(cfg.Expr); err != nil {
|
||||
return fmt.Errorf("invalid xpath expression %q: %w", cfg.Expr, err)
|
||||
}
|
||||
cfg.Stdout, cfg.Stderr = defaultWriters(cfg.Stdout, cfg.Stderr)
|
||||
|
||||
files, err := searchFileArgs(cfg.Files, ".xml")
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
return searchXMLFiles(cfg.Expr, files, cfg)
|
||||
}
|
||||
|
||||
func searchXMLFiles(expr string, files []string, cfg XMLSearchConfig) error {
|
||||
return runSearchOverFiles(searchIO{stdout: cfg.Stdout, stderr: cfg.Stderr, prefix: "xj"}, files, func(file string) ([]int, string, error) {
|
||||
data, err := os.ReadFile(file)
|
||||
if err != nil {
|
||||
return nil, "", err
|
||||
}
|
||||
return searchXMLContent(expr, data)
|
||||
})
|
||||
}
|
||||
|
||||
// searchXMLContent evaluates expr against data and returns the matched line
|
||||
// numbers together with the normalized content they refer to.
|
||||
func searchXMLContent(expr string, data []byte) ([]int, string, error) {
|
||||
content := strings.TrimPrefix(string(data), "\xEF\xBB\xBF")
|
||||
root, err := processor.ParseXMLWithPositions(content)
|
||||
if err != nil {
|
||||
return nil, "", fmt.Errorf("parse XML: %w", err)
|
||||
}
|
||||
if root == nil {
|
||||
return nil, content, nil
|
||||
}
|
||||
matches, err := processor.SelectXMLXPathMatches(root, expr)
|
||||
if err != nil {
|
||||
return nil, "", fmt.Errorf("evaluate xpath %q: %w", expr, err)
|
||||
}
|
||||
|
||||
seen := make(map[int]bool)
|
||||
var lines []int
|
||||
for _, m := range matches {
|
||||
startLine := searchLineOf(content, int(m.StartPos))
|
||||
endLine := searchLineOf(content, int(m.EndPos))
|
||||
for l := startLine; l <= endLine; l++ {
|
||||
if !seen[l] {
|
||||
seen[l] = true
|
||||
lines = append(lines, l)
|
||||
}
|
||||
}
|
||||
}
|
||||
sort.Ints(lines)
|
||||
return lines, content, nil
|
||||
}
|
||||
@@ -0,0 +1,108 @@
|
||||
package chef
|
||||
|
||||
import (
|
||||
"bytes"
|
||||
"io"
|
||||
"os"
|
||||
"path/filepath"
|
||||
"testing"
|
||||
|
||||
"cook/processor"
|
||||
|
||||
"github.com/stretchr/testify/assert"
|
||||
"github.com/stretchr/testify/require"
|
||||
)
|
||||
|
||||
func runXJSearch(expr string, files []string, stdout, stderr io.Writer) error {
|
||||
return RunXMLSearch(append([]string{expr}, files...), stdout, stderr)
|
||||
}
|
||||
|
||||
func TestSelectXMLXPathMatches(t *testing.T) {
|
||||
content := `<root>
|
||||
<item id="1">alpha</item>
|
||||
<item id="2">beta</item>
|
||||
</root>
|
||||
`
|
||||
root, err := processor.ParseXMLWithPositions(content)
|
||||
require.NoError(t, err)
|
||||
require.NotNil(t, root)
|
||||
|
||||
t.Run("unit/xj/descendant_elements", func(t *testing.T) {
|
||||
matches, err := processor.SelectXMLXPathMatches(root, "//item")
|
||||
require.NoError(t, err)
|
||||
require.Len(t, matches, 2)
|
||||
assert.Equal(t, int64(9), matches[0].StartPos)
|
||||
assert.Equal(t, int64(34), matches[0].EndPos)
|
||||
assert.Equal(t, int64(37), matches[1].StartPos)
|
||||
})
|
||||
|
||||
t.Run("unit/xj/absolute_path", func(t *testing.T) {
|
||||
matches, err := processor.SelectXMLXPathMatches(root, "/root/item")
|
||||
require.NoError(t, err)
|
||||
assert.Len(t, matches, 2)
|
||||
})
|
||||
|
||||
t.Run("unit/xj/predicate", func(t *testing.T) {
|
||||
matches, err := processor.SelectXMLXPathMatches(root, `//item[@id="2"]`)
|
||||
require.NoError(t, err)
|
||||
require.Len(t, matches, 1)
|
||||
assert.Equal(t, int64(37), matches[0].StartPos)
|
||||
})
|
||||
|
||||
t.Run("unit/xj/attribute_selection", func(t *testing.T) {
|
||||
matches, err := processor.SelectXMLXPathMatches(root, "//item/@id")
|
||||
require.NoError(t, err)
|
||||
require.Len(t, matches, 2)
|
||||
assert.Equal(t, "1", content[matches[0].StartPos:matches[0].EndPos])
|
||||
assert.Equal(t, "2", content[matches[1].StartPos:matches[1].EndPos])
|
||||
})
|
||||
|
||||
t.Run("unit/xj/text_selection", func(t *testing.T) {
|
||||
matches, err := processor.SelectXMLXPathMatches(root, "//item/text()")
|
||||
require.NoError(t, err)
|
||||
require.Len(t, matches, 2)
|
||||
assert.Equal(t, "alpha", content[matches[0].StartPos:matches[0].EndPos])
|
||||
assert.Equal(t, "beta", content[matches[1].StartPos:matches[1].EndPos])
|
||||
})
|
||||
|
||||
t.Run("unit/xj/invalid_expression", func(t *testing.T) {
|
||||
_, err := processor.SelectXMLXPathMatches(root, "//[")
|
||||
require.Error(t, err)
|
||||
})
|
||||
}
|
||||
|
||||
func TestRunXMLSearch(t *testing.T) {
|
||||
dir := t.TempDir()
|
||||
write := func(name, content string) string {
|
||||
p := filepath.Join(dir, name)
|
||||
require.NoError(t, os.WriteFile(p, []byte(content), 0644))
|
||||
return p
|
||||
}
|
||||
fileA := write("a.xml", "<root>\n <ammo>arrow</ammo>\n</root>\n")
|
||||
fileB := write("b.xml", "<root>\n <other/>\n</root>\n")
|
||||
|
||||
t.Run("unit/xj/multi_file_heading_no_trailing_blank", func(t *testing.T) {
|
||||
var out bytes.Buffer
|
||||
var errOut bytes.Buffer
|
||||
err := runXJSearch("//ammo", []string{fileA, fileB}, &out, &errOut)
|
||||
require.NoError(t, err)
|
||||
assert.Equal(t, fileA+"\n2: <ammo>arrow</ammo>\n", out.String())
|
||||
})
|
||||
|
||||
t.Run("unit/xj/multiline_element", func(t *testing.T) {
|
||||
multi := write("multi.xml", "<root>\n <outer>\n <inner/>\n </outer>\n</root>\n")
|
||||
var out bytes.Buffer
|
||||
var errOut bytes.Buffer
|
||||
err := runXJSearch("//outer", []string{multi}, &out, &errOut)
|
||||
require.NoError(t, err)
|
||||
assert.Equal(t, "2: <outer>\n3: <inner/>\n4: </outer>\n", out.String())
|
||||
})
|
||||
|
||||
t.Run("unit/xj/invalid_expression_errors", func(t *testing.T) {
|
||||
var out bytes.Buffer
|
||||
var errOut bytes.Buffer
|
||||
err := runXJSearch("//[", []string{fileA}, &out, &errOut)
|
||||
require.Error(t, err)
|
||||
assert.Contains(t, err.Error(), "invalid xpath")
|
||||
})
|
||||
}
|
||||
@@ -1,465 +0,0 @@
|
||||
package logger
|
||||
|
||||
import (
|
||||
"bytes"
|
||||
"fmt"
|
||||
"io"
|
||||
"log"
|
||||
"os"
|
||||
"path/filepath"
|
||||
"runtime"
|
||||
"strconv"
|
||||
"strings"
|
||||
"sync"
|
||||
"time"
|
||||
)
|
||||
|
||||
// LogLevel defines the severity of log messages
|
||||
type LogLevel int
|
||||
|
||||
const (
|
||||
// LevelError is for critical errors that should always be displayed
|
||||
LevelError LogLevel = iota
|
||||
// LevelWarning is for important warnings
|
||||
LevelWarning
|
||||
// LevelInfo is for informational messages
|
||||
LevelInfo
|
||||
// LevelDebug is for detailed debugging information
|
||||
LevelDebug
|
||||
// LevelTrace is for very detailed tracing information
|
||||
LevelTrace
|
||||
// LevelLua is specifically for output from Lua scripts
|
||||
LevelLua
|
||||
)
|
||||
|
||||
var levelNames = map[LogLevel]string{
|
||||
LevelError: "ERROR",
|
||||
LevelWarning: "WARNING",
|
||||
LevelInfo: "INFO",
|
||||
LevelDebug: "DEBUG",
|
||||
LevelTrace: "TRACE",
|
||||
LevelLua: "LUA",
|
||||
}
|
||||
|
||||
var levelColors = map[LogLevel]string{
|
||||
LevelError: "\033[1;31m", // Bold Red
|
||||
LevelWarning: "\033[1;33m", // Bold Yellow
|
||||
LevelInfo: "\033[1;32m", // Bold Green
|
||||
LevelDebug: "\033[1;36m", // Bold Cyan
|
||||
LevelTrace: "\033[1;35m", // Bold Magenta
|
||||
LevelLua: "\033[1;34m", // Bold Blue
|
||||
}
|
||||
|
||||
// ResetColor is the ANSI code to reset text color
|
||||
const ResetColor = "\033[0m"
|
||||
|
||||
// Logger is our custom logger with level support
|
||||
type Logger struct {
|
||||
mu sync.Mutex
|
||||
out io.Writer
|
||||
currentLevel LogLevel
|
||||
prefix string
|
||||
flag int
|
||||
useColors bool
|
||||
callerOffset int
|
||||
defaultFields map[string]interface{}
|
||||
showGoroutine bool
|
||||
}
|
||||
|
||||
var (
|
||||
// DefaultLogger is the global logger instance
|
||||
DefaultLogger *Logger
|
||||
// defaultLogLevel is the default log level if not specified
|
||||
defaultLogLevel = LevelInfo
|
||||
// Global mutex for DefaultLogger initialization
|
||||
initMutex sync.Mutex
|
||||
)
|
||||
|
||||
// ParseLevel converts a string log level to LogLevel
|
||||
func ParseLevel(levelStr string) LogLevel {
|
||||
switch strings.ToUpper(levelStr) {
|
||||
case "ERROR":
|
||||
return LevelError
|
||||
case "WARNING", "WARN":
|
||||
return LevelWarning
|
||||
case "INFO":
|
||||
return LevelInfo
|
||||
case "DEBUG":
|
||||
return LevelDebug
|
||||
case "TRACE":
|
||||
return LevelTrace
|
||||
case "LUA":
|
||||
return LevelLua
|
||||
default:
|
||||
return defaultLogLevel
|
||||
}
|
||||
}
|
||||
|
||||
// String returns the string representation of the log level
|
||||
func (l LogLevel) String() string {
|
||||
if name, ok := levelNames[l]; ok {
|
||||
return name
|
||||
}
|
||||
return fmt.Sprintf("Level(%d)", l)
|
||||
}
|
||||
|
||||
// New creates a new Logger instance
|
||||
func New(out io.Writer, prefix string, flag int) *Logger {
|
||||
return &Logger{
|
||||
out: out,
|
||||
currentLevel: defaultLogLevel,
|
||||
prefix: prefix,
|
||||
flag: flag,
|
||||
useColors: true,
|
||||
callerOffset: 0,
|
||||
defaultFields: make(map[string]interface{}),
|
||||
showGoroutine: true,
|
||||
}
|
||||
}
|
||||
|
||||
// Init initializes the DefaultLogger
|
||||
func Init(level LogLevel) {
|
||||
initMutex.Lock()
|
||||
defer initMutex.Unlock()
|
||||
|
||||
if DefaultLogger == nil {
|
||||
DefaultLogger = New(os.Stdout, "", log.Lmicroseconds|log.Lshortfile)
|
||||
}
|
||||
DefaultLogger.SetLevel(level)
|
||||
}
|
||||
|
||||
// SetLevel sets the current log level
|
||||
func (l *Logger) SetLevel(level LogLevel) {
|
||||
l.mu.Lock()
|
||||
defer l.mu.Unlock()
|
||||
l.currentLevel = level
|
||||
}
|
||||
|
||||
// GetLevel returns the current log level
|
||||
func (l *Logger) GetLevel() LogLevel {
|
||||
l.mu.Lock()
|
||||
defer l.mu.Unlock()
|
||||
return l.currentLevel
|
||||
}
|
||||
|
||||
// SetCallerOffset sets the caller offset for correct file and line reporting
|
||||
func (l *Logger) SetCallerOffset(offset int) {
|
||||
l.mu.Lock()
|
||||
defer l.mu.Unlock()
|
||||
l.callerOffset = offset
|
||||
}
|
||||
|
||||
// SetShowGoroutine sets whether to include goroutine ID in log messages
|
||||
func (l *Logger) SetShowGoroutine(show bool) {
|
||||
l.mu.Lock()
|
||||
defer l.mu.Unlock()
|
||||
l.showGoroutine = show
|
||||
}
|
||||
|
||||
// ShowGoroutine returns whether goroutine ID is included in log messages
|
||||
func (l *Logger) ShowGoroutine() bool {
|
||||
l.mu.Lock()
|
||||
defer l.mu.Unlock()
|
||||
return l.showGoroutine
|
||||
}
|
||||
|
||||
// WithField adds a field to the logger's context
|
||||
func (l *Logger) WithField(key string, value interface{}) *Logger {
|
||||
newLogger := &Logger{
|
||||
out: l.out,
|
||||
currentLevel: l.currentLevel,
|
||||
prefix: l.prefix,
|
||||
flag: l.flag,
|
||||
useColors: l.useColors,
|
||||
callerOffset: l.callerOffset,
|
||||
defaultFields: make(map[string]interface{}),
|
||||
showGoroutine: l.showGoroutine,
|
||||
}
|
||||
|
||||
// Copy existing fields
|
||||
for k, v := range l.defaultFields {
|
||||
newLogger.defaultFields[k] = v
|
||||
}
|
||||
|
||||
// Add new field
|
||||
newLogger.defaultFields[key] = value
|
||||
return newLogger
|
||||
}
|
||||
|
||||
// WithFields adds multiple fields to the logger's context
|
||||
func (l *Logger) WithFields(fields map[string]interface{}) *Logger {
|
||||
newLogger := &Logger{
|
||||
out: l.out,
|
||||
currentLevel: l.currentLevel,
|
||||
prefix: l.prefix,
|
||||
flag: l.flag,
|
||||
useColors: l.useColors,
|
||||
callerOffset: l.callerOffset,
|
||||
defaultFields: make(map[string]interface{}),
|
||||
showGoroutine: l.showGoroutine,
|
||||
}
|
||||
|
||||
// Copy existing fields
|
||||
for k, v := range l.defaultFields {
|
||||
newLogger.defaultFields[k] = v
|
||||
}
|
||||
|
||||
// Add new fields
|
||||
for k, v := range fields {
|
||||
newLogger.defaultFields[k] = v
|
||||
}
|
||||
return newLogger
|
||||
}
|
||||
|
||||
// GetGoroutineID extracts the goroutine ID from the runtime stack
|
||||
func GetGoroutineID() string {
|
||||
buf := make([]byte, 64)
|
||||
n := runtime.Stack(buf, false)
|
||||
// Format of first line is "goroutine N [state]:"
|
||||
// We only need the N part
|
||||
buf = buf[:n]
|
||||
idField := bytes.Fields(bytes.Split(buf, []byte{':'})[0])[1]
|
||||
return string(idField)
|
||||
}
|
||||
|
||||
// formatMessage formats a log message with level, time, file, and line information
|
||||
func (l *Logger) formatMessage(level LogLevel, format string, args ...interface{}) string {
|
||||
var msg string
|
||||
if len(args) > 0 {
|
||||
msg = fmt.Sprintf(format, args...)
|
||||
} else {
|
||||
msg = format
|
||||
}
|
||||
|
||||
// Format default fields if any
|
||||
var fields string
|
||||
if len(l.defaultFields) > 0 {
|
||||
var pairs []string
|
||||
for k, v := range l.defaultFields {
|
||||
pairs = append(pairs, fmt.Sprintf("%s=%v", k, v))
|
||||
}
|
||||
fields = " " + strings.Join(pairs, " ")
|
||||
}
|
||||
|
||||
var levelColor, resetColor string
|
||||
if l.useColors {
|
||||
levelColor = levelColors[level]
|
||||
resetColor = ResetColor
|
||||
}
|
||||
|
||||
var caller string
|
||||
if l.flag&log.Lshortfile != 0 || l.flag&log.Llongfile != 0 {
|
||||
// Find the actual caller by scanning up the stack
|
||||
// until we find a function outside the logger package
|
||||
var file string
|
||||
var line int
|
||||
var ok bool
|
||||
|
||||
// Start at a reasonable depth and scan up to 10 frames
|
||||
for depth := 4; depth < 15; depth++ {
|
||||
_, file, line, ok = runtime.Caller(depth)
|
||||
if !ok {
|
||||
break
|
||||
}
|
||||
|
||||
// If the caller is not in the logger package, we found our caller
|
||||
if !strings.Contains(file, "logger/logger.go") {
|
||||
break
|
||||
}
|
||||
}
|
||||
|
||||
if !ok {
|
||||
file = "???"
|
||||
line = 0
|
||||
}
|
||||
|
||||
if l.flag&log.Lshortfile != 0 {
|
||||
file = filepath.Base(file)
|
||||
}
|
||||
caller = fmt.Sprintf("%-25s ", file+":"+strconv.Itoa(line))
|
||||
}
|
||||
|
||||
// Format the timestamp with fixed width
|
||||
var timeStr string
|
||||
if l.flag&(log.Ldate|log.Ltime|log.Lmicroseconds) != 0 {
|
||||
t := time.Now()
|
||||
if l.flag&log.Ldate != 0 {
|
||||
timeStr += fmt.Sprintf("%04d/%02d/%02d ", t.Year(), t.Month(), t.Day())
|
||||
}
|
||||
if l.flag&(log.Ltime|log.Lmicroseconds) != 0 {
|
||||
timeStr += fmt.Sprintf("%02d:%02d:%02d", t.Hour(), t.Minute(), t.Second())
|
||||
if l.flag&log.Lmicroseconds != 0 {
|
||||
timeStr += fmt.Sprintf(".%06d", t.Nanosecond()/1000)
|
||||
}
|
||||
}
|
||||
timeStr = fmt.Sprintf("%-15s ", timeStr)
|
||||
}
|
||||
|
||||
// Add goroutine ID if enabled, with fixed width
|
||||
var goroutineStr string
|
||||
if l.showGoroutine {
|
||||
goroutineID := GetGoroutineID()
|
||||
goroutineStr = fmt.Sprintf("[g:%-4s] ", goroutineID)
|
||||
}
|
||||
|
||||
// Create a colored level indicator with both brackets colored
|
||||
levelStr := fmt.Sprintf("%s[%s]%s", levelColor, levelNames[level], levelColor)
|
||||
// Add a space after the level and before the reset color
|
||||
levelColumn := fmt.Sprintf("%s %s", levelStr, resetColor)
|
||||
|
||||
return fmt.Sprintf("%s%s%s%s%s%s%s\n",
|
||||
l.prefix, timeStr, caller, goroutineStr, levelColumn, msg, fields)
|
||||
}
|
||||
|
||||
// log logs a message at the specified level
|
||||
func (l *Logger) log(level LogLevel, format string, args ...interface{}) {
|
||||
// Always show LUA level logs regardless of the current log level
|
||||
if level != LevelLua && level > l.currentLevel {
|
||||
return
|
||||
}
|
||||
|
||||
l.mu.Lock()
|
||||
defer l.mu.Unlock()
|
||||
|
||||
msg := l.formatMessage(level, format, args...)
|
||||
fmt.Fprint(l.out, msg)
|
||||
}
|
||||
|
||||
// Error logs an error message
|
||||
func (l *Logger) Error(format string, args ...interface{}) {
|
||||
l.log(LevelError, format, args...)
|
||||
}
|
||||
|
||||
// Warning logs a warning message
|
||||
func (l *Logger) Warning(format string, args ...interface{}) {
|
||||
l.log(LevelWarning, format, args...)
|
||||
}
|
||||
|
||||
// Info logs an informational message
|
||||
func (l *Logger) Info(format string, args ...interface{}) {
|
||||
l.log(LevelInfo, format, args...)
|
||||
}
|
||||
|
||||
// Debug logs a debug message
|
||||
func (l *Logger) Debug(format string, args ...interface{}) {
|
||||
l.log(LevelDebug, format, args...)
|
||||
}
|
||||
|
||||
// Trace logs a trace message
|
||||
func (l *Logger) Trace(format string, args ...interface{}) {
|
||||
l.log(LevelTrace, format, args...)
|
||||
}
|
||||
|
||||
// Lua logs a Lua message
|
||||
func (l *Logger) Lua(format string, args ...interface{}) {
|
||||
l.log(LevelLua, format, args...)
|
||||
}
|
||||
|
||||
// Global log functions that use DefaultLogger
|
||||
|
||||
// Error logs an error message using the default logger
|
||||
func Error(format string, args ...interface{}) {
|
||||
if DefaultLogger == nil {
|
||||
Init(defaultLogLevel)
|
||||
}
|
||||
DefaultLogger.Error(format, args...)
|
||||
}
|
||||
|
||||
// Warning logs a warning message using the default logger
|
||||
func Warning(format string, args ...interface{}) {
|
||||
if DefaultLogger == nil {
|
||||
Init(defaultLogLevel)
|
||||
}
|
||||
DefaultLogger.Warning(format, args...)
|
||||
}
|
||||
|
||||
// Info logs an informational message using the default logger
|
||||
func Info(format string, args ...interface{}) {
|
||||
if DefaultLogger == nil {
|
||||
Init(defaultLogLevel)
|
||||
}
|
||||
DefaultLogger.Info(format, args...)
|
||||
}
|
||||
|
||||
// Debug logs a debug message using the default logger
|
||||
func Debug(format string, args ...interface{}) {
|
||||
if DefaultLogger == nil {
|
||||
Init(defaultLogLevel)
|
||||
}
|
||||
DefaultLogger.Debug(format, args...)
|
||||
}
|
||||
|
||||
// Trace logs a trace message using the default logger
|
||||
func Trace(format string, args ...interface{}) {
|
||||
if DefaultLogger == nil {
|
||||
Init(defaultLogLevel)
|
||||
}
|
||||
DefaultLogger.Trace(format, args...)
|
||||
}
|
||||
|
||||
// Lua logs a Lua message using the default logger
|
||||
func Lua(format string, args ...interface{}) {
|
||||
if DefaultLogger == nil {
|
||||
Init(defaultLogLevel)
|
||||
}
|
||||
DefaultLogger.Lua(format, args...)
|
||||
}
|
||||
|
||||
// LogPanic logs a panic error and its stack trace
|
||||
func LogPanic(r interface{}) {
|
||||
if DefaultLogger == nil {
|
||||
Init(defaultLogLevel)
|
||||
}
|
||||
stack := make([]byte, 4096)
|
||||
n := runtime.Stack(stack, false)
|
||||
DefaultLogger.Error("PANIC: %v\n%s", r, stack[:n])
|
||||
}
|
||||
|
||||
// SetLevel sets the log level for the default logger
|
||||
func SetLevel(level LogLevel) {
|
||||
if DefaultLogger == nil {
|
||||
Init(level)
|
||||
return
|
||||
}
|
||||
DefaultLogger.SetLevel(level)
|
||||
}
|
||||
|
||||
// GetLevel gets the log level for the default logger
|
||||
func GetLevel() LogLevel {
|
||||
if DefaultLogger == nil {
|
||||
Init(defaultLogLevel)
|
||||
}
|
||||
return DefaultLogger.GetLevel()
|
||||
}
|
||||
|
||||
// WithField returns a new logger with the field added to the default logger's context
|
||||
func WithField(key string, value interface{}) *Logger {
|
||||
if DefaultLogger == nil {
|
||||
Init(defaultLogLevel)
|
||||
}
|
||||
return DefaultLogger.WithField(key, value)
|
||||
}
|
||||
|
||||
// WithFields returns a new logger with the fields added to the default logger's context
|
||||
func WithFields(fields map[string]interface{}) *Logger {
|
||||
if DefaultLogger == nil {
|
||||
Init(defaultLogLevel)
|
||||
}
|
||||
return DefaultLogger.WithFields(fields)
|
||||
}
|
||||
|
||||
// SetShowGoroutine enables or disables goroutine ID display in the default logger
|
||||
func SetShowGoroutine(show bool) {
|
||||
if DefaultLogger == nil {
|
||||
Init(defaultLogLevel)
|
||||
}
|
||||
DefaultLogger.SetShowGoroutine(show)
|
||||
}
|
||||
|
||||
// ShowGoroutine returns whether goroutine ID is included in default logger's messages
|
||||
func ShowGoroutine() bool {
|
||||
if DefaultLogger == nil {
|
||||
Init(defaultLogLevel)
|
||||
}
|
||||
return DefaultLogger.ShowGoroutine()
|
||||
}
|
||||
@@ -1,49 +0,0 @@
|
||||
package logger
|
||||
|
||||
import (
|
||||
"fmt"
|
||||
"runtime/debug"
|
||||
)
|
||||
|
||||
// PanicHandler handles a panic and logs it
|
||||
func PanicHandler() {
|
||||
if r := recover(); r != nil {
|
||||
goroutineID := GetGoroutineID()
|
||||
stackTrace := debug.Stack()
|
||||
Error("PANIC in goroutine %s: %v\n%s", goroutineID, r, stackTrace)
|
||||
}
|
||||
}
|
||||
|
||||
// SafeGo launches a goroutine with panic recovery
|
||||
// Usage: logger.SafeGo(func() { ... your code ... })
|
||||
func SafeGo(f func()) {
|
||||
go func() {
|
||||
defer PanicHandler()
|
||||
f()
|
||||
}()
|
||||
}
|
||||
|
||||
// SafeGoWithArgs launches a goroutine with panic recovery and passes arguments
|
||||
// Usage: logger.SafeGoWithArgs(func(arg1, arg2 interface{}) { ... }, "value1", 42)
|
||||
func SafeGoWithArgs(f func(...interface{}), args ...interface{}) {
|
||||
go func() {
|
||||
defer PanicHandler()
|
||||
f(args...)
|
||||
}()
|
||||
}
|
||||
|
||||
// SafeExec executes a function with panic recovery
|
||||
// Useful for code that should not panic
|
||||
func SafeExec(f func()) (err error) {
|
||||
defer func() {
|
||||
if r := recover(); r != nil {
|
||||
goroutineID := GetGoroutineID()
|
||||
stackTrace := debug.Stack()
|
||||
Error("PANIC in goroutine %s: %v\n%s", goroutineID, r, stackTrace)
|
||||
err = fmt.Errorf("panic recovered: %v", r)
|
||||
}
|
||||
}()
|
||||
|
||||
f()
|
||||
return nil
|
||||
}
|
||||
@@ -1,327 +1,16 @@
|
||||
package main
|
||||
|
||||
import (
|
||||
"flag"
|
||||
"fmt"
|
||||
"os"
|
||||
"sort"
|
||||
"sync"
|
||||
"time"
|
||||
|
||||
"modify/processor"
|
||||
"modify/utils"
|
||||
"cook/cmd"
|
||||
|
||||
"github.com/go-git/go-git/v5"
|
||||
|
||||
"modify/logger"
|
||||
)
|
||||
|
||||
type GlobalStats struct {
|
||||
TotalMatches int
|
||||
TotalModifications int
|
||||
ProcessedFiles int
|
||||
FailedFiles int
|
||||
ModificationsPerCommand sync.Map
|
||||
}
|
||||
|
||||
var (
|
||||
repo *git.Repository
|
||||
worktree *git.Worktree
|
||||
stats GlobalStats = GlobalStats{
|
||||
ModificationsPerCommand: sync.Map{},
|
||||
}
|
||||
"github.com/spf13/cobra"
|
||||
)
|
||||
|
||||
func main() {
|
||||
flag.Usage = func() {
|
||||
fmt.Fprintf(os.Stderr, "Usage: %s [options] <pattern> <lua_expression> <...files_or_globs>\n", os.Args[0])
|
||||
fmt.Fprintf(os.Stderr, "\nOptions:\n")
|
||||
fmt.Fprintf(os.Stderr, " -git\n")
|
||||
fmt.Fprintf(os.Stderr, " Use git to manage files\n")
|
||||
fmt.Fprintf(os.Stderr, " -reset\n")
|
||||
fmt.Fprintf(os.Stderr, " Reset files to their original state\n")
|
||||
fmt.Fprintf(os.Stderr, " -loglevel string\n")
|
||||
fmt.Fprintf(os.Stderr, " Set logging level: ERROR, WARNING, INFO, DEBUG, TRACE (default \"INFO\")\n")
|
||||
fmt.Fprintf(os.Stderr, "\nExamples:\n")
|
||||
fmt.Fprintf(os.Stderr, " Regex mode (default):\n")
|
||||
fmt.Fprintf(os.Stderr, " %s \"<value>(\\d+)</value>\" \"*1.5\" data.xml\n", os.Args[0])
|
||||
fmt.Fprintf(os.Stderr, "\nNote: v1, v2, etc. are used to refer to capture groups as numbers.\n")
|
||||
fmt.Fprintf(os.Stderr, " s1, s2, etc. are used to refer to capture groups as strings.\n")
|
||||
fmt.Fprintf(os.Stderr, " Helper functions: num(str) converts string to number, str(num) converts number to string\n")
|
||||
fmt.Fprintf(os.Stderr, " is_number(str) checks if a string is numeric\n")
|
||||
fmt.Fprintf(os.Stderr, " If expression starts with an operator like *, /, +, -, =, etc., v1 is automatically prepended\n")
|
||||
fmt.Fprintf(os.Stderr, " You can use any valid Lua code, including if statements, loops, etc.\n")
|
||||
fmt.Fprintf(os.Stderr, " Glob patterns are supported for file selection (*.xml, data/**.xml, etc.)\n")
|
||||
}
|
||||
// TODO: Fix bed shitting when doing *.yml in barotrauma directory
|
||||
flag.Parse()
|
||||
args := flag.Args()
|
||||
|
||||
level := logger.ParseLevel(*utils.LogLevel)
|
||||
logger.Init(level)
|
||||
logger.Info("Initializing with log level: %s", level.String())
|
||||
|
||||
// The plan is:
|
||||
// Load all commands
|
||||
commands, err := utils.LoadCommands(args)
|
||||
if err != nil {
|
||||
logger.Error("Failed to load commands: %v", err)
|
||||
flag.Usage()
|
||||
return
|
||||
}
|
||||
|
||||
if *utils.Filter != "" {
|
||||
logger.Info("Filtering commands by name: %s", *utils.Filter)
|
||||
commands = utils.FilterCommands(commands, *utils.Filter)
|
||||
logger.Info("Filtered %d commands", len(commands))
|
||||
}
|
||||
|
||||
// Then aggregate all the globs and deduplicate them
|
||||
globs := utils.AggregateGlobs(commands)
|
||||
logger.Debug("Aggregated %d globs before deduplication", utils.CountGlobsBeforeDedup(commands))
|
||||
|
||||
for _, command := range commands {
|
||||
logger.Trace("Command: %s", command.Name)
|
||||
logger.Trace("Regex: %s", command.Regex)
|
||||
logger.Trace("Files: %v", command.Files)
|
||||
logger.Trace("Lua: %s", command.Lua)
|
||||
logger.Trace("Git: %t", command.Git)
|
||||
logger.Trace("Reset: %t", command.Reset)
|
||||
logger.Trace("Isolate: %t", command.Isolate)
|
||||
logger.Trace("LogLevel: %s", command.LogLevel)
|
||||
}
|
||||
|
||||
// Resolve all the files for all the globs
|
||||
logger.Info("Found %d unique file patterns", len(globs))
|
||||
files, err := utils.ExpandGLobs(globs)
|
||||
if err != nil {
|
||||
logger.Error("Failed to expand file patterns: %v", err)
|
||||
return
|
||||
}
|
||||
logger.Info("Found %d files to process", len(files))
|
||||
|
||||
// Somehow connect files to commands via globs..
|
||||
// For each file check every glob of every command
|
||||
// Maybe memoize this part
|
||||
// That way we know what commands affect what files
|
||||
associations, err := utils.AssociateFilesWithCommands(files, commands)
|
||||
if err != nil {
|
||||
logger.Error("Failed to associate files with commands: %v", err)
|
||||
return
|
||||
}
|
||||
|
||||
// Then for each file run all commands associated with the file
|
||||
workers := make(chan struct{}, *utils.ParallelFiles)
|
||||
wg := sync.WaitGroup{}
|
||||
|
||||
// Add performance tracking
|
||||
startTime := time.Now()
|
||||
var fileMutex sync.Mutex
|
||||
|
||||
// Create a map to store loggers for each command
|
||||
commandLoggers := make(map[string]*logger.Logger)
|
||||
for _, command := range commands {
|
||||
// Create a named logger for each command
|
||||
cmdName := command.Name
|
||||
if cmdName == "" {
|
||||
// If no name is provided, use a short version of the regex pattern
|
||||
if len(command.Regex) > 20 {
|
||||
cmdName = command.Regex[:17] + "..."
|
||||
} else {
|
||||
cmdName = command.Regex
|
||||
}
|
||||
}
|
||||
|
||||
// Parse the log level for this specific command
|
||||
cmdLogLevel := logger.ParseLevel(command.LogLevel)
|
||||
|
||||
// Create a logger with the command name as a field
|
||||
commandLoggers[command.Name] = logger.WithField("command", cmdName)
|
||||
commandLoggers[command.Name].SetLevel(cmdLogLevel)
|
||||
|
||||
logger.Debug("Created logger for command %q with log level %s", cmdName, cmdLogLevel.String())
|
||||
}
|
||||
|
||||
// This aggregation is great but what if one modification replaces the whole entire file?
|
||||
// Shit......
|
||||
// TODO: Add "Isolate" field to modifications which makes them run alone
|
||||
for file, association := range associations {
|
||||
workers <- struct{}{}
|
||||
wg.Add(1)
|
||||
logger.SafeGoWithArgs(func(args ...interface{}) {
|
||||
defer func() { <-workers }()
|
||||
defer wg.Done()
|
||||
|
||||
// Track per-file processing time
|
||||
fileStartTime := time.Now()
|
||||
|
||||
fileData, err := os.ReadFile(file)
|
||||
if err != nil {
|
||||
logger.Error("Failed to read file %q: %v", file, err)
|
||||
return
|
||||
}
|
||||
fileDataStr := string(fileData)
|
||||
|
||||
fileDataStr, err = RunIsolateCommands(association, file, fileDataStr, &fileMutex)
|
||||
if err != nil {
|
||||
logger.Error("Failed to run isolate commands for file %q: %v", file, err)
|
||||
return
|
||||
}
|
||||
|
||||
fileDataStr, err = RunOtherCommands(file, fileDataStr, association, &fileMutex, commandLoggers)
|
||||
if err != nil {
|
||||
logger.Error("Failed to run other commands for file %q: %v", file, err)
|
||||
return
|
||||
}
|
||||
|
||||
err = os.WriteFile(file, []byte(fileDataStr), 0644)
|
||||
if err != nil {
|
||||
logger.Error("Failed to write file %q: %v", file, err)
|
||||
return
|
||||
}
|
||||
|
||||
logger.Debug("File %q processed in %v", file, time.Since(fileStartTime))
|
||||
}, file, commands)
|
||||
}
|
||||
wg.Wait()
|
||||
|
||||
processingTime := time.Since(startTime)
|
||||
logger.Info("Processing completed in %v", processingTime)
|
||||
if stats.ProcessedFiles > 0 {
|
||||
logger.Info("Average time per file: %v", processingTime/time.Duration(stats.ProcessedFiles))
|
||||
}
|
||||
|
||||
// TODO: Also give each command its own logger, maybe prefix it with something... Maybe give commands a name?
|
||||
// Do that with logger.WithField("loglevel", level.String())
|
||||
// Since each command also has its own log level
|
||||
// TODO: Maybe even figure out how to run individual commands...?
|
||||
// TODO: What to do with git? Figure it out ....
|
||||
|
||||
// if *gitFlag {
|
||||
// logger.Info("Git integration enabled, setting up git repository")
|
||||
// err := setupGit()
|
||||
// if err != nil {
|
||||
// logger.Error("Failed to setup git: %v", err)
|
||||
// fmt.Fprintf(os.Stderr, "Error setting up git: %v\n", err)
|
||||
// return
|
||||
// }
|
||||
// }
|
||||
|
||||
// logger.Debug("Expanding file patterns")
|
||||
// files, err := expandFilePatterns(filePatterns)
|
||||
// if err != nil {
|
||||
// logger.Error("Failed to expand file patterns: %v", err)
|
||||
// fmt.Fprintf(os.Stderr, "Error expanding file patterns: %v\n", err)
|
||||
// return
|
||||
// }
|
||||
|
||||
// if *gitFlag {
|
||||
// logger.Info("Cleaning up git files before processing")
|
||||
// err := cleanupGitFiles(files)
|
||||
// if err != nil {
|
||||
// logger.Error("Failed to cleanup git files: %v", err)
|
||||
// fmt.Fprintf(os.Stderr, "Error cleaning up git files: %v\n", err)
|
||||
// return
|
||||
// }
|
||||
// }
|
||||
// if *resetFlag {
|
||||
// logger.Info("Files reset to their original state, nothing more to do")
|
||||
// log.Printf("Files reset to their original state, nothing more to do")
|
||||
// return
|
||||
// }
|
||||
|
||||
// Print summary
|
||||
if stats.TotalModifications == 0 {
|
||||
logger.Warning("No modifications were made in any files")
|
||||
} else {
|
||||
logger.Info("Operation complete! Modified %d values in %d/%d files",
|
||||
stats.TotalModifications, stats.ProcessedFiles, stats.ProcessedFiles+stats.FailedFiles)
|
||||
sortedCommands := []string{}
|
||||
stats.ModificationsPerCommand.Range(func(key, value interface{}) bool {
|
||||
sortedCommands = append(sortedCommands, key.(string))
|
||||
return true
|
||||
})
|
||||
sort.Strings(sortedCommands)
|
||||
|
||||
for _, command := range sortedCommands {
|
||||
count, _ := stats.ModificationsPerCommand.Load(command)
|
||||
if count.(int) > 0 {
|
||||
logger.Info("\tCommand %q made %d modifications", command, count)
|
||||
} else {
|
||||
logger.Warning("\tCommand %q made no modifications", command)
|
||||
}
|
||||
}
|
||||
cobra.EnablePrefixMatching = true
|
||||
if err := cmd.Execute(); err != nil {
|
||||
os.Exit(1)
|
||||
}
|
||||
}
|
||||
|
||||
func RunOtherCommands(file string, fileDataStr string, association utils.FileCommandAssociation, fileMutex *sync.Mutex, commandLoggers map[string]*logger.Logger) (string, error) {
|
||||
// Aggregate all the modifications and execute them
|
||||
modifications := []utils.ReplaceCommand{}
|
||||
for _, command := range association.Commands {
|
||||
// Use command-specific logger if available, otherwise fall back to default logger
|
||||
cmdLogger := logger.DefaultLogger
|
||||
if cmdLog, ok := commandLoggers[command.Name]; ok {
|
||||
cmdLogger = cmdLog
|
||||
}
|
||||
|
||||
cmdLogger.Info("Processing file %q with command %q", file, command.Regex)
|
||||
newModifications, err := processor.ProcessRegex(fileDataStr, command, file)
|
||||
if err != nil {
|
||||
return fileDataStr, fmt.Errorf("failed to process file %q with command %q: %w", file, command.Regex, err)
|
||||
}
|
||||
modifications = append(modifications, newModifications...)
|
||||
// It is not guranteed that all the commands will be executed...
|
||||
// TODO: Make this better
|
||||
// We'd have to pass the map to executemodifications or something...
|
||||
count, ok := stats.ModificationsPerCommand.Load(command.Name)
|
||||
if !ok {
|
||||
count = 0
|
||||
}
|
||||
stats.ModificationsPerCommand.Store(command.Name, count.(int)+len(newModifications))
|
||||
|
||||
cmdLogger.Debug("Command %q generated %d modifications", command.Name, len(newModifications))
|
||||
}
|
||||
|
||||
if len(modifications) == 0 {
|
||||
logger.Info("No modifications found for file %q", file)
|
||||
return fileDataStr, nil
|
||||
}
|
||||
|
||||
// Sort commands in reverse order for safe replacements
|
||||
var count int
|
||||
fileDataStr, count = utils.ExecuteModifications(modifications, fileDataStr)
|
||||
|
||||
fileMutex.Lock()
|
||||
stats.ProcessedFiles++
|
||||
stats.TotalModifications += count
|
||||
fileMutex.Unlock()
|
||||
|
||||
logger.Info("Executed %d modifications for file %q", count, file)
|
||||
return fileDataStr, nil
|
||||
}
|
||||
|
||||
func RunIsolateCommands(association utils.FileCommandAssociation, file string, fileDataStr string, fileMutex *sync.Mutex) (string, error) {
|
||||
for _, isolateCommand := range association.IsolateCommands {
|
||||
logger.Info("Processing file %q with isolate command %q", file, isolateCommand.Regex)
|
||||
modifications, err := processor.ProcessRegex(fileDataStr, isolateCommand, file)
|
||||
if err != nil {
|
||||
return fileDataStr, fmt.Errorf("failed to process file %q with isolate command %q: %w", file, isolateCommand.Regex, err)
|
||||
}
|
||||
|
||||
if len(modifications) == 0 {
|
||||
logger.Warning("No modifications found for file %q", file)
|
||||
return fileDataStr, nil
|
||||
}
|
||||
|
||||
var count int
|
||||
fileDataStr, count = utils.ExecuteModifications(modifications, fileDataStr)
|
||||
|
||||
fileMutex.Lock()
|
||||
stats.ProcessedFiles++
|
||||
stats.TotalModifications += count
|
||||
fileMutex.Unlock()
|
||||
|
||||
logger.Info("Executed %d isolate modifications for file %q", count, file)
|
||||
}
|
||||
return fileDataStr, nil
|
||||
}
|
||||
@@ -0,0 +1,31 @@
|
||||
//go:build e2e
|
||||
|
||||
package main
|
||||
|
||||
import (
|
||||
"os"
|
||||
"testing"
|
||||
|
||||
"cook/cmd"
|
||||
|
||||
"github.com/stretchr/testify/require"
|
||||
)
|
||||
|
||||
func TestMainGoDelegatesChefExecute(t *testing.T) {
|
||||
t.Run("e2e/main_go/calls_execute_with_version_flag", func(t *testing.T) {
|
||||
tmp := t.TempDir()
|
||||
wd, err := os.Getwd()
|
||||
require.NoError(t, err)
|
||||
require.NoError(t, os.Chdir(tmp))
|
||||
t.Cleanup(func() {
|
||||
if err := os.Chdir(wd); err != nil {
|
||||
return
|
||||
}
|
||||
})
|
||||
old := os.Args
|
||||
t.Cleanup(func() { os.Args = old })
|
||||
os.Args = []string{"chef", "--version"}
|
||||
err = cmd.Execute()
|
||||
require.NoError(t, err)
|
||||
})
|
||||
}
|
||||
Loaded 100 of 272 files, more files were not shown because too many files have changed in this diff.
Show more
Reference in new issue
Block a user