Unix-style redirection from standard input for script mode (cmake -P)
Motivation
CMake's script mode is convenient, but it still requires that the script exist as a file on disk. That can be a hindrance, if all you really want to do is test the result of some one-off scripting command.
UNIX has had a solution to this for decades now: It's long been a convention that, where a command accepts a file path as an argument, using a single hyphen in place of the filename means "read the input from stdin instead of opening the named file".
Having the ability to pipe a script into cmake -P -
would allow CMake commands to be quickly evaluated, for testing or experimentation purposes, without having to first create a file and write the commands into it.
Potential use patterns (examples)
A cmake -P -
mode could permit all of the following uses:
Piping script commands to cmake
$ echo 'message(STATUS Test)' | cmake -P -
-- Test
Pasting/typing commands on stdin
$ cmake -P-
message(STATUS "This is my input")
^D
-- This is my input
Here-docs
cmake -P - << __SCRIPT__
message(STATUS "Here is the script")
message(STATUS "The script is here")
__SCRIPT__
-- Here is the script
-- The script is here
(Pointlessly) piping/redirecting from a file
# (Both Equivalent to `cmake -P some-script.cmake`)
$ cmake -P - < some-script.cmake
$ cat some-script.cmake | cmake -P-
With the virtual filename for script mode set to <stdin>
, the output of cmake -P - --trace
would resemble:
$ echo 'message(STATUS "Redirected")' | cmake -P - --trace
<stdin>(1): message(STATUS Redirected )
-- Redirected
Concerns
As its authors are probably well aware, the CMake command-line processing is very averse to accepting any arguments to a flag that themselves start with a -
. There are checks throughout the code that reject any argument capture when nextArg[0] == '-'
. Those checks are diametrically opposed to the needs of this feature, and implementing it would require relaxing them (at least for the -P
argument).
To avoid any destabilization of existing checks for arguments other than -P
, an entirely new values Type can be added to the cmCommandLineArgument::Values
enum: Values::OneOrHyphen
. This type would behave much like the previous Values::One
type used for -P
, but without the usual protection against nextArg[0] == '-'
.
Special-casing the argument type for a single flag, and the redundancy it creates in the code, isn't ideal. But it feels like a safe approach to supporting commands like cmake -P -
and cmake -P-
without destabilizing the existing processing (and protections) for all of the other arguments.