Created
June 10, 2019 04:07
-
-
Save brianonn/14780dfcb39bbf80e493abc2f4cc1704 to your computer and use it in GitHub Desktop.
awk script to detect the CI/CD environment
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
#!/usr/bin/awk -f | |
function usage() { | |
print "Usage: ci_detect [ detect | get envvar | dump ]" | |
exit -1 | |
} | |
function dumpargs() { | |
printf "ARGC = %d\n", ARGC | |
for (i = 0; i < ARGC ; ++i) { | |
printf "ARGV[%d] = %s\n", i, ARGV[i] | |
} | |
for (key in ENVIRON) { | |
printf "%s = %s\n", key, ENVIRON[key] | |
} | |
} | |
function startup() { | |
setup_globals() | |
} | |
function setup_globals() { | |
all_ci=" ci semaphore travis concourse circleci jenkins drone appveyor" | |
all_env="CI SEMAPHORE TRAVIS ATC_EXTERNAL_URL CIRCLECI JENKINS_URL DRONE APPVEYOR" | |
split(all_ci, ci, " ") | |
split(all_env, env, " ") | |
} | |
function detect() { | |
generic_ci = 0 | |
for ( idx in ci ) { | |
ci_var = ENVIRON[env[idx]] | |
if ( ci_var == "1" || ci_var == "true" ) { | |
if (ci[idx] == "ci") { # $CI is special, almost all CI environments set it | |
generic_ci = 1 | |
continue # just note it and continue | |
} | |
print ci[idx] | |
return 0 | |
} | |
} | |
if (generic_ci) { | |
print "generic" # print this only when we didn't detect a known CI server | |
return 0 | |
} | |
return 1 | |
} | |
function test(ci_name) { | |
for ( idx in ci ) { | |
if ( ci_name == ci[idx] ) { | |
if (ENVIRON[env[idx]]) { | |
exit 0 | |
} else { | |
exit 1 | |
} | |
break | |
} | |
} | |
} | |
function dump() { | |
for ( idx in ci ) { | |
print ci[idx], ":", env[idx] | |
} | |
} | |
BEGIN { | |
debug = 0 | |
FS=":" | |
setup_globals() | |
if (debug) dumpargs() | |
cmd = ARGV[1] | |
if (cmd == "detect") { | |
exit detect() | |
} else if (cmd == "test") { | |
if ( ARGC != 3 ) usage() | |
test(ARGV[2]) | |
} else if (cmd == "dump") { | |
dump() | |
} else { | |
usage() | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment