Compare commits

..
267 Commits
Author SHA1 Message Date
dave 4dff292de1 GET RID OF THE GOD DAMN FUCKING CRLF FUCK YOU WINDOWS FUCK OFF 2026-08-18 18:25:05 +02:00
dave c8301b5812 Fix version flag lookup, XML prefix matching, and Lua block line offsets 2026-08-16 20:26:53 +02:00
dave a3289906ae Add tests against the lua pipeline 2026-08-16 19:10:17 +02:00
dave 3f4f4cb1d5 "Fix" vet discard detection 2026-08-16 18:59:34 +02:00
dave 1e11e3866d Refactor the recent hallucination 2026-08-16 18:59:34 +02:00
dave 93a942a7a1 Rehallucinate everything everywhere
The goal is to get more accurate lua errors
2026-08-16 18:37:36 +02:00
dave feae7fd0ca Generate example cook_hooks.toml with chef -e 2026-08-15 16:22:17 +02:00
dave 9d0160f37f :) 2026-08-15 01:18:53 +02:00
dave 214ef4cbca Tidy up 2026-08-15 01:14:13 +02:00
dave 08ac1b5291 Remove a whole lotta garbage 2026-08-15 01:03:19 +02:00
dave 991fadaa4e Replace gripgrep glob matcher with doublestar 2026-08-15 00:31:51 +02:00
dave 6bc6c3e7f0 fixup! Remove the smears of shit we installed for funsies 2026-08-15 00:27:24 +02:00
dave aa6870ff4b Remove the smears of shit we installed for funsies 2026-08-15 00:23:04 +02:00
dave f2c1a60884 Split diff-chunk helpers into gen_diff and gen_pattern files 2026-08-15 00:08:31 +02:00
dave 32128d28a5 Replace doublestar globs with gripgrep parallel walker 2026-08-14 23:51:17 +02:00
dave 0aeb8ca052 Add name argument and minimal context trimming to chef gen 2026-08-09 21:26:17 +02:00
dave 6dc76788e2 Tidy up 2026-08-08 23:12:49 +02:00
dave f9d561ae57 Trim trailing whitespace when finding array append position 2026-08-08 23:07:21 +02:00
dave 546a0dd8d3 Add regression test for appending to root JSON array 2026-08-08 23:00:10 +02:00
dave 1b9f407264 Pre-register command stats before preparing associations 2026-08-08 22:50:44 +02:00
dave bde2b69b11 Add regression test for commands missing from command summary 2026-08-08 22:21:21 +02:00
dave 49e4f8a756 Run all *.toml cook files by default when no files given 2026-08-08 18:57:57 +02:00
dave e0a016c6ae Use fsnotify for watch 2026-08-08 17:55:56 +02:00
dave f5d03ffe54 Add watch command to re-run cook files on change 2026-08-08 17:43:02 +02:00
dave 2bdf3ecc9e Refactor everything 2026-08-08 17:03:16 +02:00
dave 5f0b2d75d6 Add regression test against writing back primitive values 2026-08-08 15:14:49 +02:00
dave 7395313229 Who fucked my vet!? 2026-08-08 15:04:10 +02:00
dave 9c9229cf8e Preserve Lua table key order in surgical JSON write-back 2026-08-08 15:03:09 +02:00
dave b9b50c8cf6 Silence no modifications log 2026-08-08 14:55:29 +02:00
dave bbb7247e25 Remove the .val .raw wrappers entirely
Seemed like a good idea at the time.....
But it's been a nightmare to work with
2026-08-08 14:44:24 +02:00
dave 65e30d4e84 Render Lua stack traces cleanly in TUI and compact Lua error messages 2026-08-08 13:48:17 +02:00
dave 14556d6260 Clean up Lua error messages for readable output 2026-08-08 13:08:52 +02:00
dave 4d53834f54 Add chef lua command to run Lua files with the helper library preloaded 2026-08-08 12:52:39 +02:00
dave eaf0a48146 Fix fucking something? 2026-08-05 14:40:06 +02:00
dave a08364ffa5 Add more god damn tests 2026-08-05 14:31:09 +02:00
dave a3beb56d50 "Fix" lua error source parsing again 2026-08-05 14:18:14 +02:00
dave ff24094656 Add more regression tests for the fucking errors 2026-08-05 13:46:19 +02:00
dave c14068f7be "Fix" lua error source lines 2026-08-05 13:11:39 +02:00
dave 2a43d41974 Add regression test against lua error source resolution 2026-08-05 12:52:10 +02:00
dave 3bd2ba4a86 "Refactor" shit around 2026-08-05 11:53:06 +02:00
dave 7e7bb30aa2 "Fix" null json keys being removed with no cause 2026-08-05 01:15:56 +02:00
dave f5432cea1d Add fresh regression test 2026-08-05 01:10:01 +02:00
dave 0c1aacf166 Make it actually compile :) 2026-08-04 22:42:33 +02:00
dave 4f7e704516 I guess we refactor now 2026-08-04 22:37:51 +02:00
dave 170b827db6 Update the example file with actual examples 2026-08-04 22:19:26 +02:00
dave c771a852f5 vet 2026-08-04 22:19:26 +02:00
dave cb02c5e47f Implement rj and xj - rg but json and xmlpath 2026-08-04 22:19:26 +02:00
dave 0fd1759760 Add qlty 2026-08-04 20:37:18 +02:00
dave 3b69ccbe9b Remove more fallbacks and legacy shims 2026-07-26 22:34:46 +02:00
dave 246655c279 Namespace all the helper functions 2026-07-26 22:16:58 +02:00
dave b9e843c607 Implement raw command mode for passing entire file content to Lua 2026-07-26 21:36:43 +02:00
dave 2279e803d7 Improve error messages with command/file/pattern context and upgrade no-modification logs to Warn 2026-07-22 11:20:29 +02:00
dave ab051e7351 Add a "ctx" to every lua script 2026-06-22 22:13:45 +02:00
dave 50d780d32a Code format 2026-06-22 22:07:09 +02:00
dave 3a1891e8b8 Fix the god damn tests 2026-06-22 22:06:51 +02:00
dave bafd131b8b Remove variables entirely
Replaced by hooks
2026-06-22 21:57:59 +02:00
dave 8e3aa43282 Implement hooks in the form of before/after_each 2026-06-22 21:37:30 +02:00
dave f87a9ff637 Add regression test (and fix) against loadjson overwriting data 2026-05-25 17:08:03 +02:00
dave 74b9f487ee Implement loadjson and loadxml
Does what it says on the tin really
2026-05-25 16:18:32 +02:00
dave 2b682c2eac Add JSON root array population test and improve JSON marshaling logic 2026-05-25 11:14:03 +02:00
dave 9ae81dc7db Fix issue where existing null keys are being removed 2026-05-23 21:07:05 +02:00
dave 54383ccc70 Add a regression test against removing null fields 2026-05-23 18:28:39 +02:00
dave 0ee640b601 Fucking make lua colored 2026-05-23 18:11:20 +02:00
dave 39a8b3019f Switch to logger v3 2026-05-23 14:12:47 +02:00
dave 299651c8c9 ONCE MORE fix the fucking source error resolution
BY ADDING YET MORE CODE!! MORE MORE MORE MORE MORE MORE MOREOMR EMO RMEO
RMEO RMEO RMEO!!! MRORE MORE MORE MORE !!!
2026-05-23 13:48:16 +02:00
dave 901f2e48d9 AAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAA 2026-05-23 13:45:28 +02:00
dave 34d613f336 Hallucinate more garbage code for resolving lua source
wow.
2026-05-23 13:43:17 +02:00
dave 1688b3501b Add regression test against lua stack trace source tracing 2026-05-23 13:20:18 +02:00
dave 8566df62c7 Actually print lua errors into multiple rows
Neat stack traces
2026-05-23 13:11:44 +02:00
dave 78cb4ad96d Implement - in a catastrophically terrible manner - the lua trace source resolution 2026-05-23 13:00:04 +02:00
dave ceb7424680 Assert lua errors are formated nicely 2026-05-23 12:48:09 +02:00
dave 709f51b2fa Add cmd to logs and color shit 2026-05-13 16:40:01 +02:00
dave 6eeac03dea Fix tui oopsie 2026-05-13 15:26:31 +02:00
dave 9900ca8eb6 Assert relative paths in tests 2026-05-13 15:25:36 +02:00
dave 7573caad0f Rework all paths to relative instead of absolute 2026-05-13 15:12:39 +02:00
dave 91bfd6de4d Fuck your moronic god damn wrappers 2026-05-13 14:23:56 +02:00
dave 0a166135aa FUCK YOUR ABSOLUTE PATHS 2026-05-13 13:49:22 +02:00
dave 9f3108376e Refactor some shit around 2026-05-13 13:26:01 +02:00
dave 2d4a9006ce Refactor some tests around 2026-05-13 12:43:00 +02:00
dave bfed7311b9 Refactor everything to a more cobra structure 2026-05-13 11:57:49 +02:00
dave b735f37952 Rework logging yet once more 2026-05-13 11:46:23 +02:00
dave 9d981f1e0d Add various e2e tests 2026-05-12 23:58:59 +02:00
dave a1e787dde4 Optimize json and xml parsing and fix setting sn
Previously only s1 was considered
2026-05-12 09:50:08 +02:00
dave bf1265a9ca Rework regex tests 2026-05-12 09:45:02 +02:00
dave 07cff80588 Ensure files are parsed only once 2026-05-11 14:15:55 +02:00
dave 9551d30b3d Have command files[] OVERWRITE root level files instead of append 2026-05-11 13:56:27 +02:00
dave 7e2649bfd2 Undo the xpath fail -> nil change, now return {} 2026-05-11 13:27:09 +02:00
dave 07dad250ed Implement root level files and command level files
Since we 99% define the same files for all
2026-05-11 00:24:39 +02:00
dave eb5a52f148 Add a bit more tests for the cloning 2026-05-10 20:34:57 +02:00
dave d40360c9b7 Add tests against the new clone functionality 2026-05-10 20:15:15 +02:00
dave 2927fb468f Add a clone helper 2026-05-10 20:09:27 +02:00
dave 9872c4b1a9 Update examples to dave style 2026-05-10 18:44:45 +02:00
dave 6968a1a63c Return nil instead of empty table for failing xpath or jpath 2026-05-10 15:05:53 +02:00
dave f737cbcb93 Cache glob results in db to hopefully speed up processing on large projects 2026-04-27 00:08:23 +02:00
dave 52cc91c3d5 Set logger level to warning for gen command 2026-04-02 15:50:35 +02:00
dave 632bbe6150 "s" on a file should run all commands within the file 2026-03-28 16:45:06 +01:00
dave e7c5ce5b54 Fix logs for commands ran simultaneously 2026-03-28 16:38:04 +01:00
dave de5db5d3c0 Render version in tui 2026-03-28 16:25:20 +01:00
dave 860c566b86 Reset files per file and not per command in tui mode 2026-03-28 16:21:32 +01:00
dave 5b52c745dd Add reset and dump binds 2026-03-28 16:10:25 +01:00
dave 1d278369a6 Add "f" to format command 2026-03-28 15:47:31 +01:00
dave 795f12252c Allegedly fix issue where commands were randomly losing their status indicators 2026-03-28 13:36:14 +01:00
dave 741b128664 s and w to run selected (highlighted) commands in v mode 2026-03-28 13:26:20 +01:00
dave d4ae64314f Running a command clears the logs of that command and not all others as well 2026-03-28 13:22:49 +01:00
dave 77c04e9c98 Rework how logs are printed onto screen to reduce redraws 2026-03-28 13:19:41 +01:00
dave 756f60f350 Make selection optional by triggering commands on mouseover command when nothing is selected 2026-03-28 13:09:31 +01:00
dave 3861597c02 Clear command logs when running a command 2026-03-28 13:02:11 +01:00
dave 39b2a1e5e8 Fix up some more of the tui command logs
commit e165575e509f7a27a4625ce5d96f6395fb6165c8
Author: PhatPhuckDave <david.majdandzic@hotmail.com>
Date:   Sat Mar 28 12:54:49 2026 +0100

    Remove unused code lol

commit 0e56b74ca7b94cda816f3052c382140f1f493e08
Author: PhatPhuckDave <david.majdandzic@hotmail.com>
Date:   Sat Mar 28 12:52:07 2026 +0100

    Enhance TUI command summary logging and normalization for improved display and consistency

commit 7383c6e6b81772041d212c4b04523d5110a979de
Author: PhatPhuckDave <david.majdandzic@hotmail.com>
Date:   Sat Mar 28 12:44:35 2026 +0100

    Print summary on tui ran commands
2026-03-28 12:55:06 +01:00
dave c96a713317 "Rework" the tui to display per command logs
commit db7c9360e8
Author: PhatPhuckDave <david.majdandzic@hotmail.com>
Date:   Sat Mar 28 12:04:09 2026 +0100

    Fix logs freaking out when selecting command

commit 0cc20ebbe9
Author: PhatPhuckDave <david.majdandzic@hotmail.com>
Date:   Sat Mar 28 12:01:39 2026 +0100

    Refactor TUI command processing and logging to streamline command execution and enhance log management

commit 4c2893fa54
Author: PhatPhuckDave <david.majdandzic@hotmail.com>
Date:   Sat Mar 28 11:53:58 2026 +0100

    Refactor TUI command and log handling to enhance log retrieval and improve performance

commit ca8c3ed741
Author: PhatPhuckDave <david.majdandzic@hotmail.com>
Date:   Sat Mar 28 11:51:10 2026 +0100

    Update cylogger dependency to v1.8.0 and refactor TUI log line wrapping for improved display

commit 9a95773437
Author: PhatPhuckDave <david.majdandzic@hotmail.com>
Date:   Sat Mar 28 11:49:11 2026 +0100

    Refactor TUI log handling to improve line wrapping and scrolling behavior

commit b76d137821
Author: PhatPhuckDave <david.majdandzic@hotmail.com>
Date:   Sat Mar 28 11:38:19 2026 +0100

    Enhance logging functionality in TUI by refining command log retrieval and processing logic

commit e13b57fd19
Author: PhatPhuckDave <david.majdandzic@hotmail.com>
Date:   Sat Mar 28 11:33:09 2026 +0100

    Refactor TUI command handling to improve logging and selection logic

commit 218fcd33d3
Author: PhatPhuckDave <david.majdandzic@hotmail.com>
Date:   Sat Mar 28 11:20:20 2026 +0100

    Rework the TUI to lazygit style (allegedly)
2026-03-28 12:34:52 +01:00
dave 1b8c014fd4 Change "r" to "s" key 2026-03-28 00:01:44 +01:00
dave 2622813bfe "Fix" logging everywhere 2026-03-28 00:00:14 +01:00
dave 55031de03e Demoronize the watch aka poll 2026-03-27 22:52:38 +01:00
dave 354cf423eb Key rows by filename and name instead of just name 2026-03-27 22:45:52 +01:00
dave a704864e5d Fix highlighting 2026-03-27 22:44:58 +01:00
dave 08ccd6e962 Enhance TUI key handling and improve style definitions for better visual feedback 2026-03-27 22:43:25 +01:00
dave 8d08c0bbd4 Render the fucking recipe files instead of target files as headers 2026-03-27 22:29:41 +01:00
dave 8a000fe3ee Refactor TUI command handling and improve file association logic 2026-03-27 22:24:51 +01:00
dave 2a29742b89 Move shit to tui and change the status icon yet again 2026-03-27 22:15:33 +01:00
dave 4c5125b528 Try fix logging and colors 2026-03-27 22:04:45 +01:00
dave 8ad7e91b57 Make the background less fucking white 2026-03-27 21:57:28 +01:00
dave 2ba4501201 Rework the TUI to be a fucking table like I asked 2026-03-27 21:55:59 +01:00
dave 7083681752 Disable logs in TUI and add some of the shit that's in the plan that was skipped 2026-03-27 21:53:06 +01:00
dave 0f55d18146 Fix some compile errors
How did I miss these???
2026-03-27 21:49:24 +01:00
dave 8b95b9561e Hallucinate the entire TUI stack in one go
No way any of this fucking works lmao
2026-03-27 21:45:10 +01:00
dave 2c126825c5 Hallucinate a plan 2026-03-27 21:36:54 +01:00
dave 2f3b937b3b Add a short and sweet "escape" command that turns text into regex matching that text 2026-03-27 21:25:05 +01:00
dave ac965de730 Hallucinate up a version string to -v 2026-03-23 10:01:53 +01:00
dave 04c930e027 Refactor main into many files 2026-03-23 09:27:58 +01:00
dave 28d36379b2 Improve the summary table by highlighting noops and errors 2026-03-23 08:42:29 +01:00
dave 11a7c187f8 Enhance XML processing error handling and add tests for XML parsing failures 2026-03-22 16:53:17 +01:00
dave 6b8ff8d31e Add coverage tests for unused functions :) 2026-03-21 14:04:01 +01:00
dave 5c4610d763 Rework type coercion and raw values
Now we convert primitive values to tables that are meant to be "transparent" primitives that also contain the .raw
2026-03-21 13:59:09 +01:00
dave aba25afc1c Fix deleting fields by setting them to nil 2026-03-21 12:46:55 +01:00
dave c1d24d0197 "Improve" logging by adding context to log lines 2026-03-21 12:30:40 +01:00
dave dfaead471b Add xpathrm and jpathrm to simplify removing elements 2026-03-21 12:13:19 +01:00
dave 2b8f5dc997 Add support for "regex_preds" that decide when a command runs and improve the end summary 2026-03-21 11:47:25 +01:00
dave e4d390214d Refactor command execution logic in main 2026-03-21 11:09:54 +01:00
dave 968c36577d Implement type coercion to force strings to numbers where possible
So we don't have to tonumber and str
2026-03-20 23:58:45 +01:00
dave 2ee9ccc0eb Ensure xpath and jpath always return tables to eliminate hollow if <> then 2026-03-20 23:38:53 +01:00
dave bf1c132bb7 Fix relative xpath // and add a regression test 2026-03-20 23:27:27 +01:00
dave af11cb23b0 Hallucinate a bunch of tests for everything 2026-03-20 23:15:23 +01:00
dave 133053e63a Implement jsonpath as well 2026-03-20 23:03:31 +01:00
dave 2c51343bab Add coverage tests to justify the existence of code 2026-03-20 22:47:12 +01:00
dave c6d6c45727 Hallucinate an xpath implementation for xml
Just use library ez
2026-03-20 22:36:19 +01:00
dave 21c5cdde54 Entirely invert reset to noreset 2026-03-19 21:55:34 +01:00
dave d64bf7fd84 Add a printf helper 2026-03-19 10:34:15 +01:00
dave 831a559256 Refactor gen and conv to separate cobra commands as well 2026-03-19 10:27:03 +01:00
dave 2654dc541a Move gen and conv to their own separate cobra commands
Good.
2026-03-19 10:18:15 +01:00
dave 6d619e37de Fix issue where we broke the main functionality 2026-03-19 10:09:28 +01:00
dave eab18ef1f0 Actually integrate fmt as a core part of chef 2026-03-19 10:00:55 +01:00
dave 28feb5924b Add a build.sh and use it in release.sh 2026-03-19 09:57:02 +01:00
dave 64773edfd4 Implement cookfmt for formatting lua within cookfiles 2026-03-19 09:54:25 +01:00
dave 9eba684da9 Update example and readme 2026-03-17 18:03:37 +01:00
dave d3974255f9 Absolutely refuck all the tests every single one 2026-03-17 18:00:04 +01:00
dave dbfcf06fa6 Ensure test coverage
At least it works right?
2026-03-17 17:27:25 +01:00
dave ec7ec3cb09 Deretardify xml to be identical to json like requested 2026-03-17 17:15:29 +01:00
dave f20a76f723 Hallucinate xml into the rest of the project 2026-03-17 15:55:28 +01:00
dave f67f2efb5c Hallucinate an implementation of xml "surgical" editing 2026-03-17 15:51:45 +01:00
dave f10465e54a Add support for pure addition and deletion diffs (ie. not replace) 2026-03-05 15:17:38 +01:00
dave 767b6d6430 Implement a --gen to generate commands out of a git diff 2026-03-05 14:56:13 +01:00
dave 0f47303091 Clean up more of the "docs" 2026-03-05 09:39:58 +01:00
dave e23808417f Rehallucinate the readme 2026-03-05 09:26:19 +01:00
dave 33eb969778 Change log level from Info to Debug for capture groups modification logging 2025-12-19 16:31:09 +01:00
dave 8b8fa70ce4 Implement tests for glob pattern aggregation 2025-12-19 16:30:27 +01:00
dave 4d0b91ed94 Refactor glob pattern handling, ensure relative globs are resolved against SourceDir 2025-12-19 16:28:25 +01:00
dave 12e0612b48 Parse the god damn fucking loglevel properly 2025-12-19 16:16:59 +01:00
dave 98e05f4998 Implement loading lua from separate files via @ 2025-12-19 14:07:39 +01:00
dave 2fa99ec3a2 Add lua meta to be used with luals and dumped via cook -m 2025-12-19 13:37:23 +01:00
dave 8dd212fc71 Code polish 2025-12-19 13:24:44 +01:00
dave a4bbaf9f27 Fix up the lua tests
To be less retarded...
2025-12-19 13:22:17 +01:00
dave 419a8118fc Update example with xml 2025-12-19 13:13:26 +01:00
dave da5b621cb6 Remove some unused shit and write tests for coverage 2025-12-19 13:13:26 +01:00
dave 1df0263a42 Rework modifiers to variables again 2025-12-19 11:54:25 +01:00
dave 74394cbde9 Integrate the xml processing with the rest of the project 2025-12-19 11:54:25 +01:00
dave f1ea0f9156 Hallucinate some xml helper functions in lua 2025-12-19 11:54:20 +01:00
dave fff8869aff Add testfiles 2025-12-19 11:54:20 +01:00
dave a0c5a5f18c Hallucinate up an xml parser implementation
Who knows if this will work...
2025-12-19 11:54:20 +01:00
dave b309e3e6f0 Update example file with json commands 2025-12-19 11:54:20 +01:00
dave 09cdc91761 Rework variables to not be commands... 2025-12-19 11:32:59 +01:00
dave a18573c9f8 Memoize the glob statement
Because we were doing the same work many times :(
2025-12-02 16:50:39 +01:00
dave eacc92ce4b Rename GLob to glob 2025-12-02 16:36:11 +01:00
dave 3bcc958dda Remove the error return value and instead just throw error 2025-11-15 18:10:24 +01:00
dave 11f0bbee53 "Rework" the csv parsing to cook metatable for header access instead of whatever the fuck I was doing 2025-11-15 18:06:21 +01:00
dave c145ad0900 Add headers to rowS (SSSSSSSSSSSSSSSS) and not individual row 2025-11-15 16:56:46 +01:00
dave e02c1f018f fixup! Add lua csv parser regression test(s) 2025-11-15 16:54:22 +01:00
dave 07fea6238f Add lua csv parser regression test(s) 2025-11-15 16:53:06 +01:00
dave 5f1fdfa6c1 Fix some go linter warnings 2025-11-15 16:53:06 +01:00
dave 4fb25d0463 Add a complex test for csv parser 2025-11-15 16:37:38 +01:00
dave bf23894188 Check options passed to csv parser 2025-11-15 16:30:53 +01:00
dave aec0f9f171 Update readme for csv parsing 2025-11-15 16:01:36 +01:00
dave 83fed68432 Fix csv header key assignment 2025-11-15 16:01:31 +01:00
dave 4311533445 Lowercase the csv options 2025-11-15 15:57:21 +01:00
dave ce28b948d0 Add an options parameter to csv parser and comment support 2025-11-15 15:51:49 +01:00
dave efc602e0ba Add a few more lua tests 2025-11-15 15:43:50 +01:00
dave 917063db0c Refactor lua helper script to separate file
And write a few tests for it
2025-11-15 15:42:57 +01:00
dave 3e552428a5 Improve the csv parser by reading header and assigning values to their header
So we have things like row[1] AND ALSO row["foobar"]
And also row.foobar of course
2025-11-15 15:39:49 +01:00
dave 50455c491d Add support for any SV like TSV 2025-11-15 15:25:18 +01:00
dave 12ec399b09 Do some retarded shit idk what claude did here hopefully something good this will probably get dropped 2025-11-11 12:53:53 +01:00
dave 5a49998c2c Add a toCSV to go along with the fromCSV 2025-11-03 19:28:00 +01:00
dave 590f19603e Make regex matching set INTEGER keys not string 2025-11-03 19:07:15 +01:00
dave ee8c4b9aa5 Ah oops, can't be local oopsie!! 2025-11-03 16:35:53 +01:00
dave e8d6613ac8 Add ParseCSV as lua function 2025-11-03 16:33:44 +01:00
dave 91ad9006fa Move the example generation to separate flag 2025-11-02 20:04:39 +01:00
dave 60ba3ad417 Fix some tests that broke for some good reason I'm sure 2025-10-26 17:10:42 +01:00
dave b74e4724d4 Convert \n to \r?\n because of windows thank you windows :) 2025-10-26 17:04:39 +01:00
dave 30246fd626 Fix logging the regex
It was adding backslashes and shit
2025-10-26 17:04:39 +01:00
dave 06aed7b27a Migrate from flag to cobra 2025-10-26 16:34:44 +01:00
dave b001dfe667 Embed the example file instead of generting it dynamically 2025-10-26 15:17:30 +01:00
dave d905ad027a Manually generate the example toml to "enforce" single quotes (looks nicer!) 2025-10-26 15:14:02 +01:00
dave 3f6a03aee8 Add conversion tests 2025-10-26 15:07:55 +01:00
dave 302e874710 Add conversion functionality from yml to toml 2025-10-26 15:05:22 +01:00
dave 9d9820072a Hallucinate a whole lotta tests for toml integration 2025-10-26 15:03:48 +01:00
dave 53d14345b9 Add support (and preference) to toml from yml 2025-10-26 14:56:04 +01:00
dave 67c3346f2f Add test for multiple isolate commands on same line of text 2025-10-24 17:13:28 +02:00
dave 346afdd143 Fix some shit 2025-10-23 00:19:07 +02:00
dave 48729cdfa4 Add isolate tests 2025-10-23 00:16:35 +02:00
dave b9574f0106 "Fix" isolate commands fucking each other (hallucinate) 2025-10-23 00:13:14 +02:00
dave 635ca463c0 Hallucinate fixes to some tests 2025-10-21 10:38:39 +02:00
dave 2459988ff0 Hallucinate a better logging lol 2025-10-21 10:10:16 +02:00
dave 6ab08fe97f Change something? 2025-10-21 09:57:09 +02:00
dave 2dafe4a981 Don't warn on no file in cache 2025-10-21 09:57:02 +02:00
dave ec24e0713d Simplify EvalRegex function by removing unnecessary panic handling and nil checks 2025-10-21 09:57:02 +02:00
dave 969ccae25c Use diffs for tests 2025-08-22 10:10:37 +02:00
dave 5b46ff0efd Fix broken test introduced in previous commit 2025-08-22 10:04:11 +02:00
dave d234616406 Add broken test 2025-08-22 09:53:00 +02:00
dave af3e55e518 Fix some retarded bullshit 2025-08-22 00:10:46 +02:00
dave 13b48229ac Fix some bullshit (the re) 2025-08-22 00:05:22 +02:00
dave 670f6ed7a0 Add tests for EvalRegex 2025-08-21 23:56:05 +02:00
dave bbc7c50fae Decringe 2025-08-21 23:17:36 +02:00
dave 779d1e0a0e Fix some more shit I guess 2025-08-21 23:16:23 +02:00
dave 54581f0216 Clean up the cringe 2025-08-21 23:10:18 +02:00
dave 3d01822e77 Fix failing test 2025-08-21 23:05:57 +02:00
dave 4e0ca92c77 Add failing test 2025-08-21 23:05:57 +02:00
dave 388e54b3e3 Add comprehensive help string for available Lua functions 2025-08-21 22:32:10 +02:00
dave 6f2e76221a Add real regex support to lua 2025-08-21 22:27:37 +02:00
dave e0d3b938e3 Fix tests 2025-08-21 22:26:20 +02:00
dave 491a030bf8 Hallucinate actual json fucking thing 2025-08-21 22:19:21 +02:00
dave bff7cc2a27 Hallucinate a json mode implementation 2025-08-21 20:39:35 +02:00
dave ff30b00e71 refactor(db.go, file.go): improve database error handling and file snapshot seeding 2025-08-09 16:12:26 +02:00
dave e1eb5eeaa6 Improve config readability by removing unnecessary fields and adding omitempty 2025-08-08 09:58:03 +02:00
dave 2a2e11d8e0 Add more examples to the configuration file generator 2025-08-08 09:52:47 +02:00
dave 6eb4f31127 Implement regexes, an entry option allow for same modification to apply to multiple regexes and variables that can be referenced in lua 2025-08-08 09:50:31 +02:00
dave 4b58e00c26 Hallucinate some logs
Hallucinate more logs

fix(utils/db.go): handle auto migration errors gracefully

fix(utils/modifycommand.go): improve file matching accuracy

fix(processor/regex.go): improve capture group deduplication logic

fix(utils/db.go): add logging for database wrapper initialization

feat(processor/regex.go): preserve input order when deduplicating capture groups

fix(utils/modifycommand.go): add logging for file matching skips

feat(processor/regex.go): add logging for capture group processing

feat(main.go): add trace logging for arguments and parallel workers

fix(main.go): add trace logging for file content

fix(utils/db.go): add logging for database opening

fix(main.go): add trace logging for file processing

fix(utils/modifycommand.go): improve file matching by using absolute paths

feat(modifycommand.go): add trace logging for file matching in AssociateFilesWithCommands

feat(main.go): add per-file association summary for better visibility when debugging
2025-08-08 08:10:51 +02:00
dave 8ffd8af13c Use atomic values instead of mutexes 2025-08-01 16:38:31 +02:00
dave 67861d4455 Now only save CHANGED files to database (before changes of course) 2025-08-01 16:34:48 +02:00
dave 299e6d8bfe Fix glob matching when backslashes are used as separators 2025-07-30 14:41:38 +02:00
dave 388822e90a Create example yml even when no args are provided
ie. invalid usage
2025-07-30 14:38:29 +02:00
dave 91993b4548 Improve error handling in ResetAllFiles function by logging warnings for failed file writes instead of returning errors 2025-07-27 12:47:21 +02:00
dave bb69558aaa Fix issue where invalid isolate commands would prevent other isolate commands from running 2025-07-21 21:28:12 +02:00
dave 052c670627 Add a simple trim to lua 2025-07-21 21:00:11 +02:00
dave 67fd215d0e Don't stroke out when backup doesn't exist in db 2025-07-20 11:48:55 +02:00
dave 9ecbbff6fa Implement special flags for dump and reset db 2025-07-20 11:47:45 +02:00
dave 774ac0f0ca Implement proper "reset" that reads snapshots from database 2025-07-20 11:43:25 +02:00
dave b785d24a08 Implement saving snapshots to a database 2025-07-20 11:38:08 +02:00
dave 22f991e72e Clean up shop a bit 2025-07-20 11:20:19 +02:00
dave 5518b27663 Remove deprecated flags and rename filter to f 2025-07-20 11:12:58 +02:00
dave 0b899dea2c Add Disabled flag to ModifyCommand 2025-07-19 11:08:51 +02:00
dave 3424fea8ad Dump a basic "config" to example usage on failed command 2025-07-19 01:15:48 +02:00
dave ddc1d83d58 Fix file associations
It was fucked because we were removing the static path and then cramming
that into assications
2025-04-22 10:53:25 +02:00
dave 4b0a85411d From cook FILE - F I L E - FILEEEEE
This is the 4th time I make the SAME fix
2025-04-22 10:46:03 +02:00
dave 46e871b626 Fix flag collision with logger 2025-04-22 10:45:11 +02:00
dave 258dcc88e7 Fix reference to utils 2025-04-18 12:48:24 +02:00
dave 75bf449bed Remove logger and replace it with a library 2025-04-18 12:47:47 +02:00
dave 58586395fb Add file util for later 2025-04-13 21:31:19 +02:00
dave c5a68af5e6 PROPERLY implement doublestar 2025-04-13 21:29:18 +02:00
dave b4c0284734 Add rimworld cook file 2025-04-09 09:47:53 +02:00
dave c5d1dad8de Rename project to "cook" and ditch loading fgrom args, now files exclusively 2025-04-09 09:47:53 +02:00
283 changed files with 111766 additions and 4158 deletions

No files matched your search

+2
View File
@@ -1,2 +1,4 @@
*.exe
.qodo
*.sqlite
.cursor/rules
+7
View File
@@ -0,0 +1,7 @@
*
!configs
!configs/**
!hooks
!hooks/**
!qlty.toml
!.gitignore
+1
View File
@@ -0,0 +1 @@
source-path=SCRIPTDIR
+81
View File
@@ -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
+67 -3
View File
@@ -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",
]
}
]
+291 -105
View File
@@ -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
View File
@@ -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.
+20
View File
@@ -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" .
+16
View File
@@ -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,
)
}
+72
View File
@@ -0,0 +1,72 @@
//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
}
})
cache, err := db2.GetGlobCache("*.txt")
assert.Error(t, err)
t.Logf("glob cache after clear: %v", cache)
})
}
+30
View File
@@ -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, args []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
View File
@@ -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,
)
}
+120
View File
@@ -0,0 +1,120 @@
//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)
aContent, aErr := os.ReadFile("a.toml")
bContent, bErr := os.ReadFile("b.toml")
require.NoError(t, aErr)
require.NoError(t, bErr)
assert.NotEmpty(t, aContent)
assert.NotEmpty(t, bContent)
})
}
+32
View File
@@ -0,0 +1,32 @@
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"}))
info, err := os.Stat(filepath.Join(tmpDir, "c.toml"))
assert.NoError(t, err)
t.Logf("c.toml info: %v", info)
}
+16
View File
@@ -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,
)
}
+51
View File
@@ -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)
})
}
+50
View File
@@ -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)
}
+21
View File
@@ -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
}
+59
View File
@@ -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
View File
@@ -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,
)
}
+64
View File
@@ -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")
})
}
+31
View File
@@ -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
View File
@@ -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)
},
}
}
+108
View File
@@ -0,0 +1,108 @@
//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"})
execOut, execErr := captureOutput(t, func() error { return root.Execute() })
require.Error(t, execErr)
t.Logf("captured output: %s", execOut)
})
}
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
}
})
}
+38
View File
@@ -0,0 +1,38 @@
package cmd
import (
"fmt"
"io"
"cook/internal/chef"
"github.com/spf13/cobra"
)
// writeLine writes a single line, returning the write error. It reports an
// error when the write is short, mirroring io.Writer contract checks.
func writeLine(w io.Writer, line string) error {
written, err := w.Write([]byte(line + "\n"))
if err != nil {
return err
}
if written != len(line)+1 {
return fmt.Errorf("short write: wrote %d of %d bytes", written, len(line)+1)
}
return nil
}
func newInternalCmd() *cobra.Command {
return &cobra.Command{
Use: "internal",
Short: "Write cook_internal.lua override of the builtin Lua helper",
Args: cobra.NoArgs,
RunE: func(cmd *cobra.Command, args []string) error {
path, err := chef.WriteInternalLua()
if err != nil {
return err
}
return writeLine(cmd.OutOrStdout(), "wrote "+path)
},
}
}
-27
View File
@@ -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)
}
+32
View File
@@ -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
}
+21
View File
@@ -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)
},
}
}
+16
View File
@@ -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,
)
}
+54
View File
@@ -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)
})
}
+46
View File
@@ -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))
}
+27
View File
@@ -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())
},
}
}
+74
View File
@@ -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")
})
}
+255
View File
@@ -0,0 +1,255 @@
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, err := cmd.Flags().GetBool("no-color")
if err != nil {
panic(err)
}
logLevelStr, err := cmd.Flags().GetString("loglevel")
if err != nil {
panic(err)
}
versionFlag, err := cmd.Root().Flags().GetBool("version")
if err != nil {
panic(err)
}
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 cook_hooks.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(newInternalCmd())
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 glob 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
- chef internal: write cook_internal.lua to override the builtin Lua helper
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 and the global hooks file cook_hooks.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
Write the builtin Lua helper override:
chef internal
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
}
+816
View File
@@ -0,0 +1,816 @@
//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, readErr := io.ReadAll(rOut)
if readErr != nil {
t.Fatalf("failed to read stdout: %v", readErr)
}
errBytes, err := io.ReadAll(rErr)
if err != nil {
t.Fatalf("failed to read stderr: %v", err)
}
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
output, 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)
t.Logf("captured output: %s", output)
p := filepath.Join(tmp, "example_cook.toml")
b, readErr := os.ReadFile(p)
require.NoError(t, readErr)
assert.NotEmpty(t, b)
h := filepath.Join(tmp, "cook_hooks.toml")
hb, hookErr := os.ReadFile(h)
require.NoError(t, hookErr)
assert.NotEmpty(t, hb)
})
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)
})
}
+13
View File
@@ -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
View File
@@ -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(&parallel, "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
}
+40
View File
@@ -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
}
+25
View File
@@ -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())
},
}
}
+73
View File
@@ -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")
})
}
-95
View File
@@ -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)
}
})
}
}
+48 -23
View File
@@ -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
)
+162 -83
View File
@@ -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=
+20
View File
@@ -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(utils.DB.ClearGlobCache)
if err != nil {
return fmt.Errorf("failed to clear glob cache: %w", err)
}
log.Info("Cleared glob cache")
return nil
}
+101
View File
@@ -0,0 +1,101 @@
package chef
import (
"log/slog"
"sync/atomic"
"cook/processor"
"cook/utils"
logger "git.site.quack-lab.dev/dave/cylogger/v3"
)
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
ctx processor.ResolveContext
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, ctx processor.ResolveContext) (string, error) {
log := logger.With("func", "RunOtherCommands", "target", file)
log.Debug("Running other commands for file")
r := &otherCommandRunner{
file: file,
fileDataStr: fileDataStr,
commandLoggers: commandLoggers,
ctx: ctx,
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
}
+158
View File
@@ -0,0 +1,158 @@
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
ctx processor.ResolveContext
log *slog.Logger
anythingDone bool
}
func RunIsolateCommands(association utils.FileCommandAssociation, file string, fileDataStr string, ctx processor.ResolveContext) (string, error) {
log := logger.With("func", "RunIsolateCommands", "target", file)
log.Debug("Running isolate commands for file")
runner := &isolateCommandRunner{
file: file,
fileDataStr: fileDataStr,
ctx: ctx,
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, r.ctx)
if err != nil {
incrementCommandError(commandName, err)
return
}
if len(modifications) > 0 {
fileDataStr, count := utils.ExecuteModificationsForFile(r.file, []string{commandName}, modifications, r.fileDataStr)
r.fileDataStr = fileDataStr
atomic.AddInt64(&stats.TotalModifications, int64(count))
r.anythingDone = true
}
}
func (r *isolateCommandRunner) runIsolateStructured(command utils.ModifyCommand, commandName string, cmdLog *slog.Logger, kind string, process func(string, utils.ModifyCommand, string, processor.ResolveContext) ([]utils.ReplaceCommand, error)) {
cmdLog.Debug("Begin processing file with " + kind + " isolate command")
modifications, err := process(r.fileDataStr, command, r.file, r.ctx)
if err != nil {
cmdLog.Error("Failed to process file with "+kind+" isolate command", "err", err)
incrementCommandError(commandName, err)
return
}
if len(modifications) == 0 {
cmdLog.Debug(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))
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, r.ctx)
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.Debug("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))
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)
})
}
}
+69
View File
@@ -0,0 +1,69 @@
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 := r.commandLoggers[command.Name]
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, r.ctx)
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)
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.Debug("Regex produced no modifications", "regex", pattern, "file", r.file)
}
}
return totalModsForCommand, hadError
}
+130
View File
@@ -0,0 +1,130 @@
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 := r.commandLoggers[command.Name]
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, r.ctx)
if err != nil {
incrementCommandError(commandName, err)
return
}
if len(modifications) > 0 {
fileDataStr, count := utils.ExecuteModificationsForFile(r.file, []string{commandName}, modifications, r.fileDataStr)
r.fileDataStr = fileDataStr
atomic.AddInt64(&stats.TotalModifications, int64(count))
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, r.ctx)
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)
})
}
}
func (r *otherCommandRunner) runXMLQueued() {
if len(r.xmlCommands) == 0 {
return
}
newModifications, counts, err := processor.ProcessXMLCommands(r.fileDataStr, r.xmlCommands, r.file, r.ctx)
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 := 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))
})
} else {
incrementCommandCounter(r.xmlCommandNames[i], func(cs *CommandStats) {
atomic.AddInt64(&cs.FilesNoMatch, 1)
})
}
}
}
+317
View File
@@ -0,0 +1,317 @@
package chef
import (
"bytes"
"encoding/json"
"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, buildCommandLoggers(association.Commands), testCtx())
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, buildCommandLoggers(association.Commands), testCtx())
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, buildCommandLoggers(association.Commands), testCtx())
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, buildCommandLoggers(association.Commands), testCtx())
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, buildCommandLoggers(association.Commands), testCtx())
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, fileHooks, err := utils.LoadCommandsFromTomlFile(tomlBytes)
require.NoError(t, err)
if fileHooks.Before != "" || fileHooks.After != "" {
t.Logf("loaded file hooks: before=%q after=%q", fileHooks.Before, fileHooks.After)
}
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")
hooksPath := filepath.Join(dir, "cook_hooks.toml")
globalBefore, globalAfter, err := utils.LoadGlobalHooks(hooksPath)
require.NoError(t, err)
ctx := processor.ResolveContext{
HookBefore: globalBefore,
HookAfter: globalAfter,
HooksFile: hooksPath,
}
file := "game_balance.json"
association := utils.FileCommandAssociation{
File: file,
Commands: []utils.ModifyCommand{cmd},
}
content, err := RunOtherCommands(file, string(inputBytes), association, buildCommandLoggers(association.Commands), ctx)
require.Error(t, err)
t.Logf("content length after failed run: %d", len(content))
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:56",
"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, testCtx())
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, testCtx())
require.NoError(t, err)
assert.Equal(t, `<root version="2"><item price="17" /></root>`, got)
assert.Equal(t, int32(2), atomic.LoadInt32(&parses))
})
}
+130
View File
@@ -0,0 +1,130 @@
package chef
import (
"fmt"
"os"
"regexp"
"strings"
"sync/atomic"
"cook/utils"
logger "git.site.quack-lab.dev/dave/cylogger/v3"
)
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, loaded := stats.CommandStats.LoadOrStore(commandName, created)
if loaded {
logger.Debug("Command stats already existed concurrently", "cmd", commandName)
}
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
}
+72
View File
@@ -0,0 +1,72 @@
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) {
resetRuntimeStats()
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, fileHooks, err := utils.LoadCommands([]string{cookFilename})
require.NoError(t, err)
require.NotEmpty(t, commands)
if len(fileHooks) > 0 {
t.Logf("loaded %d file hooks", len(fileHooks))
}
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)
}
})
}
+138
View File
@@ -0,0 +1,138 @@
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 := utils.ReadFile(filepath.FromSlash(yamlFilePath))
if err != nil {
flog.Error("Failed to read YAML file", "err", err)
return err
}
fileCommands, hooks, err := utils.LoadCommandsFromCookFile(yamlData)
if err != nil {
flog.Error("Failed to parse YAML file", "err", err)
return err
}
tomlData, err := convertCommandsToTOML(fileCommands, hooks)
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, hooks utils.FileHooks) ([]byte, error) {
log := logger.With("func", "convertCommandsToTOML")
log.Debug("Converting commands to TOML format", "count", len(commands))
tomlData := struct {
BeforeEach string `toml:"before_each,omitempty"`
AfterEach string `toml:"after_each,omitempty"`
Commands []utils.ModifyCommand `toml:"commands"`
}{
BeforeEach: hooks.Before,
AfterEach: hooks.After,
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
}
+146
View File
@@ -0,0 +1,146 @@
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"))
info, statErr := os.Stat(filepath.Join(tmpDir, "invalid.toml"))
assert.True(t, os.IsNotExist(statErr))
assert.Nil(t, info)
})
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)
info, err := os.Stat(tomlFile)
require.NoError(t, err)
t.Logf("stat %s: mode=%v", tomlFile, info.Mode())
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, fileHooks, err := utils.LoadCommandsFromTomlFiles(testTomlPath)
require.NoError(t, err)
assert.Len(t, commands, 2)
if len(fileHooks) > 0 {
t.Logf("loaded %d file hooks", len(fileHooks))
}
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\"")
})
}
+24
View File
@@ -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)
}
+31
View File
@@ -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
}
+49
View File
@@ -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)
}
+7
View File
@@ -0,0 +1,7 @@
package chef
import "errors"
var ErrNothingToDo = errors.New("nothing to do")
var ErrShowUsage = errors.New("show usage")
+55
View File
@@ -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
}
+713
View File
@@ -0,0 +1,713 @@
# 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 = '''
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']
# --- advanced json.jpath filters ---
# [?()] filters select array elements by predicate; `&&` chains conditions and
# `@.a.b` walks nested fields.
[[commands]]
name = 'Bump imager skill level'
json = true
lua = '''
local objects = json.jpath(data, "$[?(@.id == 'afs_imager' && @.use_action.level)]")
for _, obj in ipairs(objects) do
obj.use_action.level = obj.use_action.level + 1
end
modified = true
'''
files = ['config/**/*.json']
# `!@.field` matches elements where the field is absent.
[[commands]]
name = 'Repair recipe for parts missing one'
json = true
lua = '''
local objects = json.jpath(data, "$[?(@.type == 'vehicle_part' && !@.abstract && !@.requirements.repair)]")
for _, obj in ipairs(objects) do
if not obj.requirements then
obj.requirements = {}
end
obj.requirements.repair = { skills = { { "mechanics", 3 } }, time = "15 m" }
end
modified = true
'''
files = ['config/**/*.json']
# Wildcards span several levels; the final [?()] filter runs on the deepest
# elements, so `@` is the innermost value object.
[[commands]]
name = 'Scale power trickle bionics'
json = true
lua = '''
local objects = json.jpath(data, "$[*].enchantments[*].values[?(@.value == 'POWER_TRICKLE')]")
for _, obj in ipairs(objects) do
obj.add = obj.add * 2
end
modified = true
'''
files = ['config/**/*.json']
# A filter can nest inside another: `@.subtypes[?(@ == 'COMESTIBLE')]` matches
# when the subtypes array contains that exact element.
[[commands]]
name = 'Mark comestible items stackable'
json = true
lua = '''
local objects = json.jpath(data, "$[?(@.type == 'ITEM' && @.subtypes[?(@ == 'COMESTIBLE')])]")
for _, obj in ipairs(objects) do
obj.stackable = true
end
modified = true
'''
files = ['config/**/*.json']
# json.jpath works on any node, not just the root: re-query each match for its
# own nested arrays.
[[commands]]
name = 'Extend laspistol magazines'
json = true
lua = '''
local objects = json.jpath(data, "$[?(@.id == 'afs_archeotech_laspistol')]")
for _, obj in ipairs(objects) do
local restrictions = json.jpath(obj, "$.pocket_data[*].ammo_restriction")
for _, restriction in ipairs(restrictions) do
restriction[#restriction + 1] = "afs_cartridge"
end
end
modified = true
'''
files = ['config/**/*.json']
# Queries can be assembled at runtime; here a blocklist is turned into a chain
# of negated membership filters joined with `&&`.
[[commands]]
name = 'Flag uncategorized stackables'
json = true
lua = '''
local forbidden = { "TOOL", "ARMOR", "GUN", "MAGAZINE" }
local parts = {}
for _, subtype in ipairs(forbidden) do
parts[#parts + 1] = "!(@.subtypes[?(@ == '" .. subtype .. "')])"
end
local query = "$[?(@.type == 'ITEM' && (!(@.category) || @.category == 'other') && " ..
table.concat(parts, " && ") .. ")]"
local objects = json.jpath(data, query)
for _, obj in ipairs(objects) do
obj.stackable = true
end
modified = true
'''
files = ['config/**/*.json']
# A filter on a nested array with a transform applied to each hit.
[[commands]]
name = 'Cap pocket move cost'
json = true
lua = '''
local pockets = json.jpath(data, "$[*].pocket_data[?(@.moves)]")
for _, pocket in ipairs(pockets) do
pocket.moves = math.round(math.max(pocket.moves * 0.5, 1))
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']
[[commands]]
name = 'Clamp respawn time'
regex = 'respawnTime = !num'
lua = 'v1 = clamp(v1, 1, 60)'
files = ['Data\Config\gamestages.xml']
+128
View File
@@ -0,0 +1,128 @@
# cook_hooks.toml — the global hooks file.
#
# Generated alongside example_cook.toml by `chef -e`.
#
# This file is auto-loaded (via --hooks, default cook_hooks.toml) and its
# before_each / after_each are shared into EVERY command across EVERY cook
# file, unless a command sets its own. It is the right place for shared tuning
# constants and helper functions.
#
# A single `modifiers` table holds every balance knob and `cook()` scales
# values that carry units.
before_each = '''
-- Every cook file can read these; keep all tuning knobs in one place.
modifiers = {
quiver = {
capacity = 20,
},
pocket = {
volume = 40,
weight = 500,
length = 8,
moves = 1/4,
moves_min = 1,
},
fun = 20,
breaks_into = 8,
bionic = {
power_trickle = 128,
capacity = 10,
},
spells = {
damage = 1.5,
level_cap = 4,
max_range = 4,
},
vehicle_part = {
size = 100,
durability = 32,
epower = 2048,
bonus = 100,
repair_requirement = {
skills = { { "mechanics", 1 } },
time = "1 m",
using = { { "repair_welding_standard", 1 } },
},
},
}
-- cook(raw, mult) scales a number or a unit string ("1500 kJ") by `mult`,
-- converting back to the biggest applicable unit. Returns (value, err).
local unitModifiers = {
{ unit = "M", modifier = 1e6 },
{ unit = "k", modifier = 1e3 },
{ unit = "", modifier = 1 },
{ unit = "c", modifier = 0.01 },
{ unit = "m", modifier = 0.001 },
}
local modifierByUnit = {}
for i, modifier in pairs(unitModifiers) do
modifierByUnit[modifier.unit] = modifier.modifier
end
local applicableModifiers = {
['L'] = unitModifiers,
['l'] = unitModifiers,
['W'] = unitModifiers,
['J'] = unitModifiers,
['m'] = unitModifiers,
-- All but centi; centigram doesn't make much sense.
['g'] = {
unitModifiers[1],
unitModifiers[2],
unitModifiers[3],
unitModifiers[5],
},
}
---@param raw string|number
---@param mult number
---@return string
---@return string?
function cook(raw, mult)
local unit = nil
local modifier = 1
local characters = string.match(raw, "%a+") or ""
local length = #characters
if length == 2 then
unit = string.sub(characters, 2, 2)
modifier = modifierByUnit[string.sub(characters, 1, 1)]
elseif length == 1 then
unit = string.sub(characters, 1, 1)
modifier = 1
elseif length == 0 then
return string.format("%g", N(raw) * mult), nil
end
if not unit then
return raw, "Error: Unit is null"
end
local value = N(string.match(raw, "%d+%.?%d*"))
if not value then
return raw, "Error: Value is null"
end
-- Convert to base units, scale, then back to the biggest unit.
value = value * modifier
value = value * mult
local modifierTable = applicableModifiers[unit]
for _, modifier in pairs(modifierTable) do
if value >= modifier.modifier then
value = value / modifier.modifier
return string.format("%g %s%s", value, modifier.unit, unit)
end
end
return raw
end
'''
# after_each runs after every command; use it for per-command cleanup or
# accounting. command_name is available in every command's Lua state.
after_each = '''
print("finished command: " .. tostring(command_name))
'''
+107
View File
@@ -0,0 +1,107 @@
package chef
import (
"bytes"
"fmt"
"log/slog"
"os"
"os/exec"
"regexp"
"strings"
"cook/utils"
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 := utils.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
}
+61
View File
@@ -0,0 +1,61 @@
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")
}
out, err := styluaFormat("local x = 1")
require.Error(t, err)
assert.Empty(t, out)
assert.Contains(t, err.Error(), "stylua error")
t.Setenv("PATH", origPath)
})
}
+208
View File
@@ -0,0 +1,208 @@
package chef
import (
"fmt"
"io"
"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) {
log := logger.With("func", "generateCommandsFromUnifiedDiff")
files, preamble, err := gitdiff.Parse(strings.NewReader(normalizeNewlines(diffText)))
if err != nil {
return nil, 0, fmt.Errorf("failed to parse unified diff: %w", err)
}
if strings.TrimSpace(preamble) != "" {
log.Debug("Ignored preamble before first diff file", "chars", len(preamble))
}
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, err := utils.ReadFile(filePath)
if err != nil {
logger.Debug("Failed to read pristine file from disk; using empty content", "path", filePath, "err", err)
return nil
}
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 {
return nullDiffPaths[name]
}
var nullDiffPaths = map[string]bool{
"": true,
"/dev/null": true,
"a/dev/null": true,
"b/dev/null": true,
}
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
}
+100
View File
@@ -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
}
+125
View File
@@ -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()
}
+73
View File
@@ -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'''"
}
+353
View File
@@ -0,0 +1,353 @@
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, skipped, err := GenerateCommandsFromUnifiedDiff(diffText)
require.NoError(t, err)
assert.Equal(t, 0, skipped)
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, skipped, err := GenerateCommandsFromUnifiedDiff(diffText)
require.NoError(t, err)
assert.Equal(t, 0, skipped)
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, skipped, err := GenerateCommandsFromUnifiedDiff(diffText)
require.NoError(t, err)
assert.Equal(t, 0, skipped)
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, skipped, err := GenerateCommandsFromUnifiedDiff(diffText)
require.NoError(t, err)
assert.Equal(t, 0, skipped)
require.Len(t, commands, 1)
// Context trimming ran against the snapshot, not the on-disk content.
assert.Equal(t, minimalContextRegex, commands[0].Regex)
}
+19
View File
@@ -0,0 +1,19 @@
package chef
import (
"cook/processor"
logger "git.site.quack-lab.dev/dave/cylogger/v3"
)
// WriteInternalLua dumps cook_internal.lua (the builtin Lua helper override)
// into the working directory. It returns the written path.
func WriteInternalLua() (string, error) {
log := logger.With("func", "WriteInternalLua")
path, err := processor.WriteInternalLua()
if err != nil {
log.Error("Failed to write cook_internal.lua", "err", err)
return "", err
}
return path, nil
}
+385
View File
@@ -0,0 +1,385 @@
package chef
import (
"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, testCtx())
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, testCtx())
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, testCtx())
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, buildCommandLoggers(association.Commands), testCtx())
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},
},
},
}
content, err := RunOtherCommands(xmlTestFile, testContent, association, buildCommandLoggers(association.Commands), testCtx())
assert.Equal(t, ErrNothingToDo, err)
t.Logf("content length after no-op: %d", len(content))
}
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, testCtx())
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 := buildCommandLoggers(association.Commands)
finalResult, err := RunOtherCommands(testTxtPath, isolateResult, association, commandLoggers, testCtx())
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, testCtx())
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")
}
+149
View File
@@ -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
}
+128
View File
@@ -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
}
+15
View File
@@ -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})
}
+87
View File
@@ -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)
}
}
}
}
+121
View File
@@ -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):
}
})
}
+44
View File
@@ -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
}
+105
View File
@@ -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))
}
+98
View File
@@ -0,0 +1,98 @@
package chef
import (
"encoding/json"
"fmt"
"io"
"sort"
"strings"
"cook/utils"
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 := utils.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
}
+225
View File
@@ -0,0 +1,225 @@
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) {
start, end, ok := resolveJSONPointerRange(content, "/items/0/missing")
assert.False(t, ok)
if !ok {
t.Logf("missing member resolved to [%d, %d)", start, end)
}
})
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))
})
}
+135
View File
@@ -0,0 +1,135 @@
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"
//go:embed example_cook_hooks.toml
var exampleCookHooksToml string
const exampleCookHooksTomlPath = "cook_hooks.toml"
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 WriteExampleCookHooksToml() error {
log := logger.With("func", "WriteExampleCookHooksToml")
log.Debug("Writing global hooks file", "target", exampleCookHooksTomlPath)
err := os.WriteFile(exampleCookHooksTomlPath, []byte(exampleCookHooksToml), 0644)
if err != nil {
log.Error("Failed to write global hooks file", "err", err, "target", exampleCookHooksTomlPath)
return err
}
log.Info("Wrote global hooks file", "target", exampleCookHooksTomlPath)
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:
if err := WriteExampleCookToml(); err != nil {
return err
}
return WriteExampleCookHooksToml()
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)
}
+57
View File
@@ -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())
resetRuntimeStats()
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())
resetRuntimeStats()
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))
}
+59
View File
@@ -0,0 +1,59 @@
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 := exampleCookToml
assert.NotEmpty(t, s)
assert.Contains(t, s, "[[commands]]")
})
}
func TestExampleCookHooksTomlContent(t *testing.T) {
t.Run("unit/returns_non_empty_embedded_hooks", func(t *testing.T) {
s := exampleCookHooksToml
assert.NotEmpty(t, s)
assert.Contains(t, s, "before_each")
assert.Contains(t, s, "after_each")
})
}
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, exampleCookToml, string(b))
})
}
func TestWriteExampleCookHooksToml(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, WriteExampleCookHooksToml())
b, err := os.ReadFile(filepath.Join(tmp, "cook_hooks.toml"))
require.NoError(t, err)
assert.Equal(t, exampleCookHooksToml, string(b))
})
}
+90
View File
@@ -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)
}
}
}
}
+88
View File
@@ -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)
resetRuntimeStats()
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)
resetRuntimeStats()
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")
})
}
+320
View File
@@ -0,0 +1,320 @@
package chef
import (
"errors"
"fmt"
"log/slog"
"os"
"path/filepath"
"sync/atomic"
"time"
"cook/processor"
"cook/utils"
logger "git.site.quack-lab.dev/dave/cylogger/v3"
cyutils "git.site.quack-lab.dev/dave/cyutils"
)
const failedCloseDBMsg = "Failed to close database"
type RunCookfilesConfig struct {
CookPaths []string
Parallel int
Filter string
GlobalHooksPath string
}
func RunCookfiles(cfg RunCookfilesConfig) error {
log := logger.With("func", "RunCookfiles")
db, commands, ctx, 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(failedCloseDBMsg, "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, ctx)
processingTime := time.Since(startTime)
logRunSummary(processingTime)
printCommandSummaryTable()
return nil
}
func loadRunInputs(args []string, filterFlag string, globalHooksPath string) (utils.DB, []utils.ModifyCommand, processor.ResolveContext, 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, processor.ResolveContext{}, err
}
log.Debug("Database connection established")
commands, fileHooks, err := loadRunCommands(args, log)
if err != nil {
if cerr := db.Close(); cerr != nil {
log.Warn(failedCloseDBMsg, "err", cerr)
}
return nil, nil, processor.ResolveContext{}, err
}
ctx, err := resolveGlobalHooks(globalHooksPath, fileHooks)
if err != nil {
if cerr := db.Close(); cerr != nil {
log.Warn(failedCloseDBMsg, "err", cerr)
}
return nil, nil, processor.ResolveContext{}, err
}
commands = applyCommandFilter(commands, filterFlag, log)
return db, commands, ctx, nil
}
func loadRunCommands(args []string, log *slog.Logger) ([]utils.ModifyCommand, map[string]utils.FileHooks, error) {
log.Debug("Loading commands from arguments")
commands, fileHooks, 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, nil, fmt.Errorf("%w: %w", ErrShowUsage, err)
}
log.Info("Loaded commands", "count", len(commands))
return commands, fileHooks, nil
}
// resolveGlobalHooks loads the configured global hooks file into a resolver
// context shared by every command. When the path is empty, the returned context
// carries only the per-file hooks. The global hooks file is exactly the
// configured path — no other file is ever consulted.
func resolveGlobalHooks(globalHooksPath string, fileHooks map[string]utils.FileHooks) (processor.ResolveContext, error) {
ctx := processor.ResolveContext{FileHooks: fileHooks}
if globalHooksPath == "" {
return ctx, nil
}
globalBefore, globalAfter, err := utils.LoadGlobalHooks(globalHooksPath)
if err != nil {
return processor.ResolveContext{}, err
}
ctx.HookBefore = globalBefore
ctx.HookAfter = globalAfter
ctx.HooksFile = globalHooksPath
return ctx, 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, ctx processor.ResolveContext) {
log := logger.With("func", "processAssociations", "parallel", parallelFlag)
log.Debug("Starting file processing")
cyutils.WithWorkers(parallelFlag, associations, func(worker int, file string, association utils.FileCommandAssociation) {
args := processFileArgs{
worker: worker,
file: file,
association: association,
db: db,
commandLoggers: commandLoggers,
ctx: ctx,
}
processFile(args)
})
}
// processFileArgs bundles the inputs needed to process one target file.
type processFileArgs struct {
worker int
file string
association utils.FileCommandAssociation
db utils.DB
commandLoggers map[string]*slog.Logger
ctx processor.ResolveContext
}
func processFile(args processFileArgs) {
fileStartTime := time.Now()
log := logger.With("func", "processFile", "worker", args.worker, "target", args.file)
log.Debug("Reading file")
fileData, err := utils.ReadFile(filepath.FromSlash(args.file))
if err != nil {
log.Error("Failed to read file", "err", err)
atomic.AddInt64(&stats.FailedFiles, 1)
return
}
fileDataStr, isChanged, err := runFileCommands(args.file, string(fileData), args.association, args.commandLoggers, args.ctx)
if err != nil {
atomic.AddInt64(&stats.FailedFiles, 1)
return
}
if isChanged {
log.Debug("Saving file snapshot to database")
if err := args.db.SaveFile(args.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(args.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, ctx processor.ResolveContext) (string, bool, error) {
log := logger.With("func", "processFile", "target", file)
log.Debug("Running isolate commands")
fileDataStr, err := RunIsolateCommands(association, file, fileDataStr, ctx)
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, ctx)
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,
)
}
}
+46
View File
@@ -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))
resetRuntimeStats()
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))
}
+179
View File
@@ -0,0 +1,179 @@
package chef
import (
"fmt"
"io"
"os"
"path/filepath"
"sort"
"strings"
"cook/utils"
)
// resolveSearchFiles expands file arguments into a sorted, deduplicated list.
// Glob metacharacters are expanded; 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 expanded.
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")
}
+64
View File
@@ -0,0 +1,64 @@
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
}
})
files, err := searchFileArgs(nil, ".json")
require.Error(t, err)
assert.Empty(t, files)
assert.Contains(t, err.Error(), "no files matched")
})
}
+12
View File
@@ -0,0 +1,12 @@
package chef
import "sync"
type GlobalStats struct {
TotalModifications int64
ProcessedFiles int64
FailedFiles int64
CommandStats sync.Map
}
var stats GlobalStats
+9
View File
@@ -0,0 +1,9 @@
package chef
import "cook/processor"
// testCtx returns an empty ResolveContext for tests that exercise a command
// without global or file-level hooks.
func testCtx() processor.ResolveContext {
return processor.ResolveContext{}
}
File diff suppressed because it is too large. Load diff
@@ -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
+239
View File
@@ -0,0 +1,239 @@
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
fileHooks map[string]utils.FileHooks
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
}
if stopLogger != nil {
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 nil, 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
}
+186
View File
@@ -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]
}
}
+130
View File
@@ -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{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
}
+41
View File
@@ -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(""))
})
}
+162
View File
@@ -0,0 +1,162 @@
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, fileHooks, err := utils.LoadCommands(a.args)
if err != nil {
return fmt.Errorf("failed to load commands: %w", err)
}
a.fileHooks = fileHooks
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
}
+188
View File
@@ -0,0 +1,188 @@
package chef
import (
"bytes"
"fmt"
"log/slog"
"sort"
"strings"
"sync/atomic"
"time"
"cook/processor"
"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)
ctx := processor.ResolveContext{FileHooks: a.fileHooks}
processAssociations(a.parallel, associations, a.db, commandLoggers, ctx)
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
}
+65
View File
@@ -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, " ")
}
+90
View File
@@ -0,0 +1,90 @@
package chef
import (
"fmt"
"io"
"sort"
"strings"
"cook/processor"
"cook/utils"
)
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 := utils.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
}
+109
View File
@@ -0,0 +1,109 @@
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) {
matches, err := processor.SelectXMLXPathMatches(root, "//[")
require.Error(t, err)
assert.Empty(t, matches)
})
}
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")
})
}
Loaded 100 of 283 files, more files were not shown because too many files have changed in this diff. Show more