This repository has been archived by the owner on Sep 22, 2020. It is now read-only.
-
Notifications
You must be signed in to change notification settings - Fork 1
/
Copy pathExec.chpl
90 lines (65 loc) · 2.01 KB
/
Exec.chpl
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
/* Execute commands... */
use "chpl_exec.h";
use "chpl_exec.c";
use Assert;
/* Run `cmd` and return exit code and output. */
proc run(cmd: string) {
extern proc chpl_run(cmd: c_string, ref stdout: c_string_copy): int;
var temp: c_string_copy,
output: string;
const env = getEnviron();
for key in env.domain {
setEnv(key, env[key]);
}
const result = chpl_run(cmd: c_string, temp);
output = toString(temp);
return output;
}
proc getEnviron() {
extern proc chpl_get_environ_size(): int;
extern proc chpl_get_environ(env: [] c_string_copy, envSize: int);
const envSize = 2 * chpl_get_environ_size();
var D = {1..envSize},
tempEnv: [D] c_string_copy,
envKeys: domain(string),
env: [envKeys] string;
chpl_get_environ(tempEnv, envSize);
for i in 1..envSize by 2 {
const key: string = tempEnv[i],
value: string = tempEnv[i+1];
env[key] = value;
}
return env;
}
/* Get the value of the envirionment variable. Returns empty string if variable
is unset.
:arg envVar: environment variable name
:type envVar: string
:returns: environment variable value
:rtype: string
*/
proc getEnv(envVar: string): string {
extern proc getenv(envKey: c_string): c_string;
const value = getenv(envVar);
return value: string;
}
/* Set the environment variable `envVar` to the given value.
:arg envVar: environment variable name
:type envVar: string
:arg value: environment variable value
:type value: string
*/
proc setEnv(envVar: string, value: string) {
extern proc setenv(envKey: c_string, envValue: c_string, overwrite: bool): int;
const result = setenv(envVar: c_string, value: c_string, true);
assert(result == 0, "Failed to set env var " + envVar);
}
/* Delete variable `envVar` from environment.
:arg envVar: environment variable name
:type envVar: string
*/
proc unsetEnv(envVar: string) {
extern proc unsetenv(envKey: c_string): int;
const result = unsetenv(envVar: c_string);
assert(result == 0, "Failed to unset env var " + envVar);
}