-
-
Notifications
You must be signed in to change notification settings - Fork 27
/
addEnv.ts
235 lines (210 loc) · 7.45 KB
/
addEnv.ts
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
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
import { addPath as ghAddPath, exportVariable, info, setFailed } from "@actions/core"
import { grantUserWriteAccess } from "admina"
import { GITHUB_ACTIONS } from "ci-info"
import { error, warning } from "ci-log"
import escapeSpace from "escape-path-with-spaces"
import escapeQuote from "escape-quotes"
import { execPowershell } from "exec-powershell"
import { appendFile, readFile, writeFile } from "fs/promises"
import { delimiter } from "path"
import { pathExists } from "path-exists"
import { untildifyUser } from "untildify-user"
type AddEnvOptions = {
/** If true, the value will be escaped with quotes and spaces will be escaped with backslash */
shouldEscapeSpace: boolean
/** If true, the variable will be only added if it is not defined */
shouldAddOnlyIfNotDefined: boolean
}
const defaultAddEnvOptions: AddEnvOptions = {
shouldEscapeSpace: false,
shouldAddOnlyIfNotDefined: false,
}
/**
* Add an environment variable.
*
* This function is cross-platforms and works in all the local or CI systems.
*/
export async function addEnv(
name: string,
valGiven: string | undefined,
givenOptions: Partial<AddEnvOptions> = defaultAddEnvOptions,
) {
const options = { ...defaultAddEnvOptions, ...givenOptions }
const val = escapeString(valGiven ?? "", options.shouldEscapeSpace)
try {
if (GITHUB_ACTIONS) {
try {
if (options.shouldAddOnlyIfNotDefined) {
if (process.env[name] !== undefined) {
info(`Environment variable ${name} is already defined. Skipping.`)
return
}
}
exportVariable(name, val)
} catch (err) {
error(err as Error)
await addEnvSystem(name, val, options)
}
} else {
await addEnvSystem(name, val, options)
}
} catch (err) {
error(err as Error)
setFailed(`Failed to export environment variable ${name}=${val}. You should add it manually.`)
}
}
function escapeString(valGiven: string, shouldEscapeSpace: boolean = false) {
const spaceEscaped = shouldEscapeSpace ? escapeSpace(valGiven) : valGiven
return escapeQuote(spaceEscaped, "\"", "\\")
}
const ignoredPaths = [/\/usr\/bin\/?/, /\/usr\/local\/bin\/?/]
/** Skip adding /usr/bin to PATH if it is already there */
function isIgnoredPath(path: string) {
if (ignoredPaths.some((checkedPath) => checkedPath.test(path))) {
const paths = process.env.PATH?.split(delimiter) ?? []
return paths.includes(path)
}
return false
}
/**
* Add a path to the PATH environment variable.
*
* This function is cross-platforms and works in all the local or CI systems.
*/
export async function addPath(path: string) {
if (isIgnoredPath(path)) {
return
}
process.env.PATH = `${path}${delimiter}${process.env.PATH}`
try {
if (GITHUB_ACTIONS) {
try {
ghAddPath(path)
} catch (err) {
error(err as Error)
await addPathSystem(path)
}
} else {
await addPathSystem(path)
}
} catch (err) {
error(err as Error)
setFailed(`Failed to add ${path} to the percistent PATH. You should add it manually.`)
}
}
export const cpprc_path = untildifyUser("~/.cpprc")
async function addEnvSystem(name: string, valGiven: string | undefined, options: AddEnvOptions) {
const val = valGiven ?? ""
switch (process.platform) {
case "win32": {
if (options.shouldAddOnlyIfNotDefined) {
if (process.env[name] !== undefined) {
info(`Environment variable ${name} is already defined. Skipping.`)
return
}
}
// We do not use `execaSync(`setx PATH "${path};%PATH%"`)` because of its character limit
await execPowershell(`[Environment]::SetEnvironmentVariable('${name}', '${val}', "User")`)
info(`${name}='${val}' was set in the environment.`)
return
}
case "linux":
case "darwin": {
await sourceCpprc()
if (options.shouldAddOnlyIfNotDefined) {
await appendFile(cpprc_path, `\nif [ -z "\${${name}}" ]; then export ${name}="${val}"; fi\n`)
info(`if not defined ${name} then ${name}="${val}" was added to "${cpprc_path}`)
} else {
await appendFile(cpprc_path, `\nexport ${name}="${val}"\n`)
info(`${name}="${val}" was added to "${cpprc_path}`)
}
return
}
default: {
// fall through shell path modification
}
}
process.env[name] = val
}
async function addPathSystem(path: string) {
switch (process.platform) {
case "win32": {
// We do not use `execaSync(`setx PATH "${path};%PATH%"`)` because of its character limit and also because %PATH% is different for user and system
await execPowershell(
`$USER_PATH=([Environment]::GetEnvironmentVariable("PATH", "User")); [Environment]::SetEnvironmentVariable("PATH", "${path};$USER_PATH", "User")`,
)
info(`"${path}" was added to the PATH.`)
return
}
case "linux":
case "darwin": {
await sourceCpprc()
await appendFile(cpprc_path, `\nexport PATH="${path}:$PATH"\n`)
info(`"${path}" was added to "${cpprc_path}"`)
return
}
default: {
return
}
}
}
/* eslint-disable require-atomic-updates */
let setupCppInProfile_called = false
/// handles adding conditions to source .cpprc file from .bashrc and .profile
export async function sourceCpprc() {
if (setupCppInProfile_called) {
return
}
const source_cpprc_string =
`\n# source .cpprc if SOURCE_CPPRC is not set to 0\nif [[ "$SOURCE_CPPRC" != 0 && -f "${cpprc_path}" ]]; then source "${cpprc_path}"; fi\n`
try {
await Promise.all([
addCpprcHeader(),
sourceCpprcInProfile(source_cpprc_string),
sourceCpprcInBashrc(source_cpprc_string),
])
} catch (err) {
warning(`Failed to add ${source_cpprc_string} to .profile or .bashrc. You should add it manually: ${err}`)
}
setupCppInProfile_called = true
}
async function addCpprcHeader() {
// a variable that prevents source_cpprc from being called from .bashrc and .profile
const cpprc_header = "# Automatically Generated by setup-cpp\nexport SOURCE_CPPRC=0"
if (await pathExists(cpprc_path)) {
const cpprc_content = await readFile(cpprc_path, "utf8")
if (!cpprc_content.includes(cpprc_header)) {
// already executed setupCppInProfile
await appendFile(cpprc_path, `\n${cpprc_header}\n`)
info(`Added ${cpprc_header} to ${cpprc_path}`)
}
}
}
async function sourceCpprcInBashrc(source_cpprc_string: string) {
const bashrc_path = untildifyUser("~/.bashrc")
if (await pathExists(bashrc_path)) {
const bashrcContent = await readFile(bashrc_path, "utf-8")
if (!bashrcContent.includes(source_cpprc_string)) {
await appendFile(bashrc_path, source_cpprc_string)
info(`${source_cpprc_string} was added to ${bashrc_path}`)
}
}
}
async function sourceCpprcInProfile(source_cpprc_string: string) {
const profile_path = untildifyUser("~/.profile")
if (await pathExists(profile_path)) {
const profileContent = await readFile(profile_path, "utf-8")
if (!profileContent.includes(source_cpprc_string)) {
await appendFile(profile_path, source_cpprc_string)
info(`${source_cpprc_string} was added to ${profile_path}`)
}
}
}
export async function finalizeCpprc() {
if (await pathExists(cpprc_path)) {
const entries = (await readFile(cpprc_path, "utf-8")).split("\n")
const unique_entries = [...new Set(entries.reverse())].reverse() // remove duplicates, keeping the latest entry
await writeFile(cpprc_path, unique_entries.join("\n"))
await grantUserWriteAccess(cpprc_path)
}
}