Skip to content

Add post_upload_command - #22

Open
djcrabhat wants to merge 11 commits into
zig-for:mainfrom
djcrabhat:main
Open

djcrabhat wants to merge 11 commits into
zig-for:mainfrom
djcrabhat:main

Conversation

@djcrabhat

@djcrabhat djcrabhat commented Aug 28, 2026 •

Copy link
Copy Markdown

Adds an optional post_upload_command to send_file. It runs a program after the ROM has been uploaded and booted, with details of the upload passed in as arguments.

I had the idea while automating my stream overlay: I use send_file.exe to map ROMs to my MSU packs, and wanted the chosen pack's name written to a file the overlay reads.

Config

post_upload_command is a list made up of the program to run and then its arguments, with variables filled in from the upload:

post_upload_command: ["C:/tools/obs-msu.exe", "--pack", "{destination_name}"]

Available variables: {rule_name}, {destination_name}, {destination_path}, {destination_rom_name}, {destination_file}, {source_path}, {source_name}. See snfm_config_example.yaml for details and examples, including how to use shell features like redirects.

How it runs

There's no shell and no std::system (src/command.cpp):

  • POSIX: posix_spawnp + waitpid. The exit code or signal is reported.
  • Windows: CreateProcessW, with a command line quoted according to the MSVC runtime's argument-parsing rules and arguments converted from UTF-8 to UTF-16. .bat/.cmd files are refused, since Windows always runs them through cmd.exe; the error recommends PowerShell instead.
  • send_file passes every variable as UTF-8, so non-ASCII ROM names survive on Windows.

Tests

This adds GoogleTest (via vcpkg), ctest, and a ctest step in CI:

  • Template expansion: values are never expanded again; brace groups and stray braces are handled.
  • Windows quoting round-trip: awkward strings plus 20,000 random cases, all round-tripped through CommandLineToArgvW.
  • End to end: an echo_args helper is launched with awkward arguments (quotes, backslashes, empty strings, shell/cmd metacharacters, non-ASCII), and each must arrive byte-for-byte. These tests also cover exit codes, a missing program, a program path containing spaces, and refusing batch files. On POSIX they also cover signals, the sh -c pattern, and reporting when the command's result can't be collected.
  • Config validation, and loading the documented examples.

All 34 pass on Windows, including under ctest -j. The Linux and macOS runs are waiting for workflow approval.

Also

  • send_file now stops with an error if booting the ROM fails (it was silently ignored before), and the post upload command doesn't run.
  • Fixes the upper-bound check when choosing a destination.
  • Uses the non-deprecated yaml-cpp::yaml-cpp target.

🤖 Generated with Claude Code

djcrabhat and others added 6 commits August 28, 2026 14:35
Adds an optional post_upload_script to the config, that when provided, executes a command, with {} replacement values.
3c7c8e7 was committed mid-edit and left send_file.cpp with character
literals that don't compile ('' and a raw newline for '\r'/'\n', and
''' for '\''). Restore them so the shell escaping works as intended:
single quotes on unix, carets with quotes dropped for cmd.exe. The
rest of the review fixes (escaping the substituted values, decoding
std::system's POSIX wait status, the destination picker's off-by-one)
went in with that commit already.

Also:
- Document that placeholders should be left unquoted since values are
  escaped, and put the redirect first in the Windows example so a
  destination name ending in a digit isn't parsed by cmd.exe as a
  stream number.
- Drop the unused protobuf::libprotoc link; only libprotobuf is needed
  for the generated pb.cc.

Co-Authored-By: Claude Opus 5 (1M context) <noreply@anthropic.com>
The tooling that applied the previous fixes rewrote the file with LF,
which churned all 252 lines against the CRLF the rest of the repo (and
this file's own history) uses. Content is unchanged from e13e0b6.

Co-Authored-By: Claude Opus 5 (1M context) <noreply@anthropic.com>
The post-upload script code had accumulated in send_file.cpp, which is
otherwise just the program's flow, and ExpandTemplate sat in config.cpp
even though the only thing that expands templates is the script runner.
Collect all three in one place:

- New shell.h / shell.cpp holding ExpandTemplate, EscapeForShell and
  RunPostUploadScript, moved as-is.
- send_file.cpp is back to do_error and main, with its include list
  restored to what it was before the feature plus shell.h.
- config.h / config.cpp keep only the post_upload_script field and its
  parsing, dropping the <utility> and <algorithm> includes that were
  there for ExpandTemplate.
- Name the script runner RunPostUploadScript to match the other two.

No behaviour change.

Co-Authored-By: Claude Opus 5 (1M context) <noreply@anthropic.com>
It came back in 96fb337 by accident - the file was staged wholesale
rather than re-diffed - and CMake's generate step fails on it because
the target isn'\''t exported. Nothing here uses protoc's compiler APIs,
only the generated pb.cc, which needs libprotobuf alone.

Co-Authored-By: Claude Opus 5 (1M context) <noreply@anthropic.com>
Reverts 3043616 and the same change in e13e0b6. The removal was a local
workaround that was sitting uncommitted in the working tree when the
review ran, and I should not have folded it into a commit. Whether this
link stays is the maintainer call, so main goes back to what it was.

Note that a fresh configure fails on this target with a current vcpkg;
CI pins vcpkg at 5bf0c55, where it still exists.

Co-Authored-By: Claude Opus 5 (1M context) <noreply@anthropic.com>

Copilot AI left a comment

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

🟡 Changes recommended

Hook placeholder expansion mishandles Windows arguments with spaces or empty values, skips placeholders inside shell brace groups, and supplies a relative source path despite promising an absolute one.

3 open issues
What changed in this PR

Adds an optional post_upload_script hook to send_file, enabling automation such as updating a stream overlay with the selected MSU destination.

Changes:

  • Loads the hook from YAML and invokes it after upload and the boot request.
  • Adds template variables for rule, destination, and source details, with platform-specific shell escaping and failure reporting.
  • Documents hook usage and fixes the destination-selection upper-bound check.
File Description
src/​shell.cpp Implements template expansion, shell escaping, and command execution.
src/​send_file.cpp Invokes the hook with upload details and corrects selection bounds.
src/​config.cpp Loads post_upload_script from YAML.
snfm_config_example.yaml Documents placeholders and Windows/Unix examples.
include/​shell.h Declares template and shell helpers.
include/​config.h Adds the optional script configuration field.
CMakeLists.txt Includes the shell implementation in send_file.

Review effort: Balanced

Comment thread src/send_file.cpp Resolved
Comment thread src/shell.cpp Resolved
Comment thread src/shell.cpp Resolved
ExpandTemplate used to swallow everything up to the next '}' when it hit an
unknown "{...}", so a placeholder inside a shell brace group never expanded.
Now it keeps the brace as literal text and resumes scanning right after it.
It only warns for text that looks like a placeholder ({identifier}).

{source_path} is now passed through std::filesystem::absolute, matching the
docs, which describe it as the full path.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
@djcrabhat

Copy link
Copy Markdown
Author

Thanks, agreed on both counts. Here's what I'd like to do before I write it:

1. Config: the command becomes a YAML list of arguments

post_upload_command: ["C:/tools/obs-msu.exe", "--pack", "{destination_name}", "--rom", "{source_path}"]
  • Placeholders are filled in separately for each argument, with the values inserted exactly as they are and no escaping. Because a value can never be split into more arguments or read as syntax, EscapeForShell gets deleted.
  • The first element is the program. It's looked up on PATH the usual way for each OS.
  • An unknown {identifier} placeholder, or a plain string where the list should be, is an error when the config loads. Right now we print a warning and run the command anyway. Braces that aren't {identifier}-shaped, such as a shell { ...; } group inside an sh -c argument, are left as literal text.
  • post_upload_script was only added in this PR and hasn't shipped, so I'll just replace it. There's nothing to stay compatible with.

2. Running it with OS primitives instead of std::system

  • POSIX: posix_spawnp with the argument vector, then waitpid. We report the exit code or the signal. No shell is involved anywhere.
  • Windows: CreateProcessW (UTF-8 → UTF-16), then WaitForSingleObject / GetExitCodeProcess. Windows only takes a single command-line string, so we still need one quoting function: the reverse of the CommandLineToArgvW / MSVCRT parsing rules (backslash runs before quotes, empty arguments, and so on). It follows a published spec and, unlike cmd.exe escaping, we can check it mechanically (see tests).
  • Batch files: .bat/.cmd always get re-parsed by cmd.exe, even through CreateProcess. That's the "BatBadBut" problem, and it would bring back the issue we're removing. I'd refuse a .bat/.cmd as the program and point people to PowerShell (["powershell", "-File", "msu.ps1", "{destination_name}"]) or an exe. Open question: is refusing too strict, or would you rather we allow it with a loud warning in the docs?
  • If someone wants shell features like redirects, they can opt in explicitly. On unix, ["sh", "-c", "echo \"$1\" > ~/msu.txt", "sh", "{destination_name}"] is still safe because the value goes in as $1 and is never pasted into the script text. The docs will show that pattern, plus the PowerShell one for Windows.

3. Tests

I'd add GoogleTest through vcpkg plus a ctest target:

  • ExpandTemplate: values that themselves contain braces or placeholders (to show there's no second round of expansion), unclosed braces, brace groups, unknown names.
  • Windows quoting round-trip: quote a list of awkward strings, parse the result back with CommandLineToArgvW, and assert we get the same strings. The list would cover spaces, ", trailing \, \", empty strings, cmd metacharacters ^&|<>()%!, and non-ASCII. I'd also add a randomized version of this test.
  • End-to-end on both OSes: a tiny echo_args test helper writes each argument it receives on its own line. We spawn it with the same awkward strings and check they arrive byte-for-byte. This also covers non-zero exit codes and reporting a missing program.
  • Config: a list loads, a plain string is rejected with a clear message, and an unknown placeholder is rejected.

(The two Copilot fixes, absolute source_path and brace-group expansion, are already pushed in a13dcf4.)

Does that direction work for you, especially the YAML list and the .bat decision? If so, I'll go ahead and build it.

djcrabhat and others added 2 commits November 7, 2026 12:12
Per review, post_upload_script (a string run through std::system) becomes
post_upload_command: a YAML list of the program and its arguments.
Placeholders are expanded into each argument separately, and values go in
verbatim. Because nothing is run through a shell, EscapeForShell is gone.

- POSIX: posix_spawnp + waitpid, reporting the exit code or signal.
- Windows: CreateProcessW with a command line quoted using the MSVC
  runtime's parsing rules. Batch files are refused, because Windows always
  runs them through cmd.exe, which would interpret the arguments.
- Config loading rejects a plain string, an empty list, and unknown
  {identifier} placeholders. Other braces, such as shell { ...; } groups,
  are left as literal text.
- send_file passes local paths in as UTF-8.

shell.h/.cpp are renamed to command.h/.cpp, now a small library shared by
send_file, config and the tests.

Adds GoogleTest (via vcpkg) and a ctest step in CI. The tests cover template
expansion, a Windows quoting round-trip through CommandLineToArgvW (including
randomized inputs), end-to-end runs through an echo_args helper with awkward
arguments, batch file refusal, and config validation.

Also switches to the non-deprecated yaml-cpp::yaml-cpp target.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
RunPostUploadCommand expects UTF-8, but on Windows destination_rom_name is
in the local code page when it comes from the ROM's file name, and
put_path's encoding depends on where the name came from. Keep a UTF-8 copy
of the ROM name for the command, and build {destination_file} from the
UTF-8 directory and name. The upload itself is unchanged.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
@djcrabhat

Copy link
Copy Markdown
Author

I've implemented the design from my last comment in 57e8e88 (plus d8b9e21).

What changed

  • post_upload_script is now post_upload_command, a YAML list made up of the program and then its arguments. Placeholders are filled in separately for each argument and no escaping is done, so EscapeForShell is gone.
  • The command runs with posix_spawnp / waitpid on POSIX and CreateProcessW on Windows. Nothing goes through a shell.
  • The one quoting function left is the Windows command-line builder, which follows the MSVC runtime's argument-parsing rules.
  • .bat/.cmd files are refused, and the error message recommends PowerShell instead.
  • Config loading now rejects a plain string, an empty list, or an unknown {identifier}. Other braces, such as a shell { ...; } group inside an sh -c argument, are treated as literal text.

Tests (GoogleTest via vcpkg, with a new ctest step in CI)

  • Template expansion: values are inserted exactly as given and never expanded again; brace groups and stray braces are handled.
  • Windows quoting: awkward strings (quotes, trailing and embedded backslashes, empty strings, cmd metacharacters, non-ASCII) plus 20,000 random cases, all round-tripped through CommandLineToArgvW.
  • End-to-end: a small echo_args helper is launched with the same strings, and each one has to arrive byte-for-byte. These tests also cover exit codes, a missing program, a program path containing spaces, and a .bat file that must not run.
  • Config validation, and a test that loads the documented examples.

All 33 pass locally on Windows. Linux and macOS (including the POSIX-only signal and sh -c tests) will get their first run from this push in CI.

Small extras: send_file now passes local paths as UTF-8 so non-ASCII ROM names survive on Windows, and the build uses the non-deprecated yaml-cpp::yaml-cpp target.

Copilot AI left a comment

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

🟡 Changes recommended

Config tests share a temporary filename across separate CTest processes, allowing parallel runs to overwrite or delete each other’s YAML and cause incorrect assertions or intermittent failures.

3 open issues
1 resolved since last review

Review effort: Balanced

Comment thread tests/config_test.cpp Resolved
ctest runs each discovered test in its own process, so with -j the config
tests could overwrite or delete each other's shared snfm_config_test.yaml.
Name the file after the test instead.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
@djcrabhat djcrabhat changed the title Add post_upload_script Add post_upload_command Nov 7, 2026
@djcrabhat
djcrabhat requested a balanced review from Copilot November 7, 2026 21:09
@djcrabhat
djcrabhat marked this pull request as ready for review November 7, 2026 21:12

Copilot AI left a comment

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

🔵 Needs a closer look

The overlay hook can run after a failed boot, and errors while waiting for the child command can go unreported.

No open issues 🎉

2 previously missed issues

In code that hasn't changed since last review

Medium severity Report waitpid failures after the child starts

src/​command.cpp:323

Errors after the child starts are silently ignored here. The POSIX branch sets started = true before waiting, then returns an error with the default exit code of zero if waitpid fails. For example, an inherited ignored SIGCHLD produces ECHILD, which reaches none of these reporting branches. Check result.error even when started is true so failure to obtain the command's result is reported.

Medium severity Run overlay hook only after a successful boot

src/​send_file.cpp:155

The hook runs even if booting fails. SNIConnection::bootFile in include/snfm.h:209–217 discards the BootFile RPC status, so a successful upload followed by a failed boot still invokes the overlay command as though the ROM had booted. Return the boot status and run the hook only after a successful boot.

3 resolved since last review

Review effort: Balanced

bootFile threw away the BootFile RPC status, so the post upload command ran
even when the ROM never booted. bootFile now returns whether it succeeded,
and send_file treats a failed boot like a failed upload.

RunPostUploadCommand only reported errors from a program that never started.
If the program started but its result couldn't be collected (waitpid
failing, e.g. with ECHILD when SIGCHLD is ignored), the failure went
unreported. Report that case too, and check WaitForSingleObject and
GetExitCodeProcess on Windows.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
@djcrabhat

Copy link
Copy Markdown
Author

Both of the issues from the latest Copilot review are fixed in 5d802f0:

  • Run the hook only after a successful boot: bootFile now returns the RPC status, and send_file treats a failed boot like a failed upload, so it reports the error, exits with 1, and skips post_upload_command.
  • Report waitpid failures after the child starts: RunPostUploadCommand now reports when the command started but its result couldn't be collected. On Windows, WaitForSingleObject / GetExitCodeProcess are now checked too. There's a new POSIX test that ignores SIGCHLD to force ECHILD, plus a cross-platform test of the command's reporting.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

2 participants