-
Notifications
You must be signed in to change notification settings - Fork 72
/
Copy pathconda.ts
304 lines (279 loc) · 9 KB
/
conda.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
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
//-----------------------------------------------------------------------
// Conda helpers
//-----------------------------------------------------------------------
import * as fs from "fs";
import * as path from "path";
import * as os from "os";
import * as core from "@actions/core";
import * as io from "@actions/io";
import * as types from "./types";
import * as constants from "./constants";
import * as utils from "./utils";
/**
* Provide current location of miniconda or location where it will be installed
*/
export function condaBasePath(options: types.IDynamicOptions): string {
let condaPath: string = constants.MINICONDA_DIR_PATH;
if (!options.useBundled) {
if (constants.IS_MAC) {
condaPath = "/Users/runner/miniconda3";
} else {
condaPath += "3";
}
}
return condaPath;
}
/**
* Provide conda CLI arguments for identifying an env by name or prefix/path
*
* ### Note
* Only really detects by presence of a path separator, as the path may not yet exist
*/
export function envCommandFlag(inputs: types.IActionInputs): string[] {
return [
inputs.activateEnvironment.match(/(\\|\/)/) ? "--prefix" : "--name",
inputs.activateEnvironment,
];
}
/**
* Provide cross platform location of conda/mamba executable
*/
export function condaExecutable(
options: types.IDynamicOptions,
subcommand?: string,
): string {
const dir: string = condaBasePath(options);
let condaExe: string;
let commandName = "conda";
if (
options.useMamba &&
(subcommand == null || constants.MAMBA_SUBCOMMANDS.includes(subcommand))
) {
commandName = "mamba";
}
commandName = constants.IS_WINDOWS ? commandName + ".bat" : commandName;
condaExe = path.join(dir, "condabin", commandName);
return condaExe;
}
/** Detect the presence of mamba */
export function isMambaInstalled(options: types.IDynamicOptions) {
const mamba = condaExecutable({ ...options, useMamba: true });
return fs.existsSync(mamba);
}
/**
* Run Conda command
*/
export async function condaCommand(
cmd: string[],
options: types.IDynamicOptions,
): Promise<void> {
const command = [condaExecutable(options, cmd[0]), ...cmd];
return await utils.execute(command);
}
/**
* Create a baseline .condarc
*/
export async function bootstrapConfig(): Promise<void> {
await fs.promises.writeFile(
constants.CONDARC_PATH,
constants.BOOTSTRAP_CONDARC,
);
}
/**
* Copy the given condarc file into place
*/
export async function copyConfig(inputs: types.IActionInputs) {
const sourcePath: string = path.join(
process.env["GITHUB_WORKSPACE"] || "",
inputs.condaConfigFile,
);
core.info(`Copying "${sourcePath}" to "${constants.CONDARC_PATH}..."`);
await io.cp(sourcePath, constants.CONDARC_PATH);
}
/**
* Setup Conda configuration
*/
export async function applyCondaConfiguration(
inputs: types.IActionInputs,
options: types.IDynamicOptions,
): Promise<void> {
const configEntries = Object.entries(inputs.condaConfig) as [
keyof types.ICondaConfig,
string,
][];
// Channels are special: if specified as an action input, these take priority
// over what is found in (at present) a YAML-based environment
let channels = inputs.condaConfig.channels
.trim()
.split(/,/)
.map((c) => c.trim())
.filter((c) => c.length);
if (!channels.length && options.envSpec?.yaml?.channels?.length) {
channels = options.envSpec.yaml.channels;
}
// LIFO: reverse order to preserve higher priority as listed in the option
// .slice ensures working against a copy
for (const channel of channels.slice().reverse()) {
core.info(`Adding channel '${channel}'`);
await condaCommand(["config", "--add", "channels", channel], options);
}
// All other options are just passed as their string representations
for (const [key, value] of configEntries) {
if (value.trim().length === 0 || key === "channels") {
continue;
}
core.info(`${key}: ${value}`);
try {
await condaCommand(["config", "--set", key, value], options);
} catch (err) {
core.warning(err as Error);
}
}
// Log all configuration information
await condaCommand(["config", "--show-sources"], options);
await condaCommand(["config", "--show"], options);
}
/**
* Initialize Conda
*/
export async function condaInit(
inputs: types.IActionInputs,
options: types.IDynamicOptions,
): Promise<void> {
let ownPath: string;
const isValidActivate = !utils.isBaseEnv(inputs.activateEnvironment);
const autoActivateBase: boolean =
options.condaConfig["auto_activate_base"] === "true";
// Fix ownership of folders
if (options.useBundled) {
if (constants.IS_MAC) {
core.info("Fixing conda folders ownership");
const userName: string = process.env.USER as string;
await utils.execute([
"sudo",
"chown",
"-R",
`${userName}:staff`,
condaBasePath(options),
]);
} else if (constants.IS_WINDOWS) {
for (let folder of constants.WIN_PERMS_FOLDERS) {
ownPath = path.join(condaBasePath(options), folder);
if (fs.existsSync(ownPath)) {
core.info(`Fixing ${folder} ownership`);
await utils.execute(["takeown", "/f", ownPath, "/r", "/d", "y"]);
}
}
}
}
// Remove profile files
if (inputs.removeProfiles == "true") {
for (let rc of constants.PROFILES) {
try {
let file: string = path.join(os.homedir(), rc);
if (fs.existsSync(file)) {
core.info(`Removing "${file}"`);
await io.rmRF(file);
}
} catch (err) {
core.warning(err as Error);
}
}
}
// Run conda init
for (let cmd of ["--all"]) {
await condaCommand(["init", cmd], options);
}
if (inputs.removeProfiles == "true") {
// Rename files
if (constants.IS_LINUX) {
let source: string = "~/.bashrc".replace("~", os.homedir());
let dest: string = "~/.profile".replace("~", os.homedir());
if (fs.existsSync(source)) {
core.info(`Renaming "${source}" to "${dest}"\n`);
await io.mv(source, dest);
}
} else if (constants.IS_MAC) {
let source: string = "~/.bash_profile".replace("~", os.homedir());
let dest: string = "~/.profile".replace("~", os.homedir());
if (fs.existsSync(source)) {
core.info(`Renaming "${source}" to "${dest}"\n`);
await io.mv(source, dest);
}
}
}
// PowerShell profiles
let powerExtraText = `
# ----------------------------------------------------------------------------`;
if (isValidActivate) {
powerExtraText += `
# Conda Setup Action: Custom activation
conda activate "${inputs.activateEnvironment}"`;
}
powerExtraText += `
# ----------------------------------------------------------------------------`;
// Bash profiles
let bashExtraText: string = `
# ----------------------------------------------------------------------------
# Conda Setup Action: Basic configuration
set -eo pipefail`;
if (isValidActivate) {
bashExtraText += `
# Conda Setup Action: Custom activation
conda activate "${inputs.activateEnvironment}"`;
bashExtraText += `
# ----------------------------------------------------------------------------`;
}
// Batch profiles
let batchExtraText = `
:: ---------------------------------------------------------------------------`;
if (autoActivateBase) {
batchExtraText += `
:: Conda Setup Action: Activate base
@CALL "%CONDA_BAT%" activate base`;
}
if (isValidActivate) {
batchExtraText += `
:: Conda Setup Action: Custom activation
@CALL "%CONDA_BAT%" activate "${inputs.activateEnvironment}"`;
}
batchExtraText += `
:: Conda Setup Action: Basic configuration
@SETLOCAL EnableExtensions
@SETLOCAL DisableDelayedExpansion
:: ---------------------------------------------------------------------------`;
let extraShells: types.IShells;
const shells: types.IShells = {
"~/.bash_profile": bashExtraText,
"~/.profile": bashExtraText,
"~/.zshrc": bashExtraText,
"~/.config/fish/config.fish": bashExtraText,
"~/.tcshrc": bashExtraText,
"~/.xonshrc": bashExtraText,
"~/.config/powershell/profile.ps1": powerExtraText,
"~/Documents/PowerShell/profile.ps1": powerExtraText,
"~/Documents/WindowsPowerShell/profile.ps1": powerExtraText,
};
if (options.useBundled) {
extraShells = {
"C:/Miniconda/etc/profile.d/conda.sh": bashExtraText,
"C:/Miniconda/etc/fish/conf.d/conda.fish": bashExtraText,
"C:/Miniconda/condabin/conda_hook.bat": batchExtraText,
};
} else {
extraShells = {
"C:/Miniconda3/etc/profile.d/conda.sh": bashExtraText,
"C:/Miniconda3/etc/fish/conf.d/conda.fish": bashExtraText,
"C:/Miniconda3/condabin/conda_hook.bat": batchExtraText,
};
}
const allShells: types.IShells = { ...shells, ...extraShells };
Object.keys(allShells).forEach((key) => {
let filePath: string = key.replace("~", os.homedir());
const text = allShells[key];
if (fs.existsSync(filePath)) {
core.info(`Append to "${filePath}":\n ${text} \n`);
fs.appendFileSync(filePath, text);
}
});
}