Skip to content

Commit

Permalink
Add fallback username for Docker run environment (#22)
Browse files Browse the repository at this point in the history
Co-authored-by: Sindre Sorhus <[email protected]>
  • Loading branch information
raido and sindresorhus committed Jun 12, 2019
1 parent affb6b5 commit c1e3590
Showing 1 changed file with 17 additions and 2 deletions.
19 changes: 17 additions & 2 deletions index.js
Original file line number Diff line number Diff line change
Expand Up @@ -24,6 +24,8 @@ const getUsernameFromOsUserInfo = () => {

const cleanWindowsCommand = string => string.replace(/^.*\\/, '');

const makeUsernameFromId = userId => `no-username-${userId}`;

module.exports = mem(async () => {
const envVariable = getEnvironmentVariable();
if (envVariable) {
Expand All @@ -35,12 +37,20 @@ module.exports = mem(async () => {
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') {
return cleanWindowsCommand(await execa.stdout('whoami'));
}

return await execa.stdout('id', ['-un']);
const userId = await execa.stdout('id', ['-u']);
try {
return await execa.stdout('id', ['-un', userId]);
} catch (_) {}

return makeUsernameFromId(userId);
} catch (_) {}
});

Expand All @@ -60,6 +70,11 @@ module.exports.sync = mem(() => {
return cleanWindowsCommand(execa.sync('whoami').stdout);
}

return execa.sync('id', ['-un']).stdout;
const userId = execa.sync('id', ['-u']).stdout;
try {
return execa.sync('id', ['-un', userId]).stdout;
} catch (_) {}

return makeUsernameFromId(userId);
} catch (_) {}
});

0 comments on commit c1e3590

Please sign in to comment.