-
-
Notifications
You must be signed in to change notification settings - Fork 14
/
Copy pathindex.js
82 lines (67 loc) · 1.94 KB
/
index.js
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
import process from 'node:process';
import os from 'node:os';
import {execa, execaSync} from 'execa';
import memoize from 'memoize';
const getEnvironmentVariable = () => {
const {env} = process;
return (
env.SUDO_USER
|| env.C9_USER // Cloud9
|| env.LOGNAME
|| env.USER
|| env.LNAME
|| env.USERNAME
);
};
const getUsernameFromOsUserInfo = () => {
try {
return os.userInfo().username;
} catch {}
};
const cleanWindowsCommand = string => string.replace(/^.*\\/, '');
const makeUsernameFromId = userId => `no-username-${userId}`;
export const username = memoize(async () => {
const environmentVariable = getEnvironmentVariable();
if (environmentVariable) {
return environmentVariable;
}
const userInfoUsername = getUsernameFromOsUserInfo();
if (userInfoUsername) {
return userInfoUsername;
}
/**
First we try to get the ID of the user and then the actual username. We do this because in `docker run --user <uid>:<gid>` context, we don't have "username" available. Therefore, we have a fallback to `makeUsernameFromId` for such scenario. Applies also to the `sync()` method below.
*/
try {
if (process.platform === 'win32') {
const {stdout} = await execa('whoami');
return cleanWindowsCommand(stdout);
}
const {stdout: userId} = await execa('id', ['-u']);
try {
const {stdout} = await execa('id', ['-un', userId]);
return stdout;
} catch {}
return makeUsernameFromId(userId);
} catch {}
});
export const usernameSync = memoize(() => {
const envVariable = getEnvironmentVariable();
if (envVariable) {
return envVariable;
}
const userInfoUsername = getUsernameFromOsUserInfo();
if (userInfoUsername) {
return userInfoUsername;
}
try {
if (process.platform === 'win32') {
return cleanWindowsCommand(execaSync('whoami').stdout);
}
const {stdout: userId} = execaSync('id', ['-u']);
try {
return execaSync('id', ['-un', userId]).stdout;
} catch {}
return makeUsernameFromId(userId);
} catch {}
});