| 1 |
# run-and-redirect.cmake -- Runs a command and validates exit code |
| 2 |
|
| 3 |
# Copyright (C) 2021 Nathan Moinvaziri |
| 4 |
# Licensed under the Zlib license, see LICENSE.md for details |
| 5 |
|
| 6 |
# Normally ctest will always fail with non-zero exit code, but we have tests |
| 7 |
# that need to check specific exit codes. |
| 8 |
|
| 9 |
# Required Variables |
| 10 |
# COMMAND - Command to run |
| 11 |
|
| 12 |
# Optional Variables |
| 13 |
# INPUT - Standard input |
| 14 |
# OUTPUT - Standard output (default: /dev/null) |
| 15 |
# SUCCESS_EXIT - List of successful exit codes (default: 0, ie: 0;1) |
| 16 |
|
| 17 |
# If no output is specified, discard output |
| 18 |
if(NOT DEFINED OUTPUT) |
| 19 |
if(WIN32) |
| 20 |
set(OUTPUT NUL) |
| 21 |
else() |
| 22 |
set(OUTPUT /dev/null) |
| 23 |
endif() |
| 24 |
endif() |
| 25 |
|
| 26 |
if(INPUT) |
| 27 |
# Check to see that input file exists |
| 28 |
if(NOT EXISTS ${INPUT}) |
| 29 |
message(FATAL_ERROR "Cannot find input: ${INPUT}") |
| 30 |
endif() |
| 31 |
# Execute with both stdin and stdout file |
| 32 |
execute_process(COMMAND ${COMMAND} |
| 33 |
RESULT_VARIABLE CMD_RESULT |
| 34 |
INPUT_FILE ${INPUT} |
| 35 |
OUTPUT_FILE ${OUTPUT}) |
| 36 |
else() |
| 37 |
# Execute with only stdout file |
| 38 |
execute_process(COMMAND ${COMMAND} |
| 39 |
RESULT_VARIABLE CMD_RESULT |
| 40 |
OUTPUT_FILE ${OUTPUT}) |
| 41 |
endif() |
| 42 |
|
| 43 |
# Check if exit code is in list of successful exit codes |
| 44 |
if(SUCCESS_EXIT) |
| 45 |
list(FIND SUCCESS_EXIT ${CMD_RESULT} _INDEX) |
| 46 |
if (${_INDEX} GREATER -1) |
| 47 |
set(CMD_RESULT 0) |
| 48 |
endif() |
| 49 |
endif() |
| 50 |
|
| 51 |
# Check to see if successful |
| 52 |
if(CMD_RESULT) |
| 53 |
message(FATAL_ERROR "${COMMAND} failed: ${CMD_RESULT}") |
| 54 |
endif() |