Skip to content

Commit a0202e3

Browse files
committed
Remove duplicates from the list of home-ish env vars.
Also tighten up code to work with Node 12.
1 parent f6c1b34 commit a0202e3

File tree

1 file changed

+22
-7
lines changed

1 file changed

+22
-7
lines changed

src/config.ts

Lines changed: 22 additions & 7 deletions
Original file line numberDiff line numberDiff line change
@@ -516,6 +516,18 @@ export function bufferFromFileOrString(file?: string, data?: string): Buffer | n
516516
return null;
517517
}
518518

519+
function dropDuplicatesAndNils(a): string[] {
520+
return a.reduce((acceptedValues, currentValue) => {
521+
// Good-enough algorithm for reducing a small (3 items at this point) array into an ordered list
522+
// of unique non-empty strings.
523+
if (currentValue && !acceptedValues.includes(currentValue)) {
524+
return acceptedValues.concat(currentValue);
525+
} else {
526+
return acceptedValues;
527+
}
528+
}, [] as string[]);
529+
}
530+
519531
// Only public for testing.
520532
export function findHomeDir(): string | null {
521533
if (process.platform !== 'win32') {
@@ -529,8 +541,8 @@ export function findHomeDir(): string | null {
529541
return null;
530542
}
531543
const homeDrivePath = process.env.HOMEDRIVE && process.env.HOMEPATH ? path.join(process.env.HOMEDRIVE, process.env.HOMEPATH) : null;
532-
const dirList1 = [process.env.HOME, homeDrivePath, process.env.USERPROFILE].filter(x => x);
533-
const dirList2 = [process.env.HOME, process.env.USERPROFILE, homeDrivePath].filter(x => x);
544+
const dirList1: string[] = dropDuplicatesAndNils([process.env.HOME, homeDrivePath, process.env.USERPROFILE]);
545+
const dirList2: string[] = dropDuplicatesAndNils([process.env.HOME, process.env.USERPROFILE, homeDrivePath]);
534546
// 1. the first of %HOME%, %HOMEDRIVE%%HOMEPATH%, %USERPROFILE% containing a `.kube\config` file is returned.
535547
for (const dir of dirList1) {
536548
try {
@@ -541,11 +553,14 @@ export function findHomeDir(): string | null {
541553
}
542554
// 2. ...the first of %HOME%, %USERPROFILE%, %HOMEDRIVE%%HOMEPATH% that exists and is writeable is returned
543555
for (const dir of dirList2) {
544-
const lstat = fs.lstatSync(dir, { throwIfNoEntry: false });
545-
// tslint:disable-next-line:no-bitwise
546-
if (lstat && (lstat.mode & fs.constants.S_IXUSR) === fs.constants.S_IXUSR) {
547-
return dir;
548-
}
556+
try {
557+
const lstat = fs.lstatSync(dir);
558+
// tslint:disable-next-line:no-bitwise
559+
if (lstat && (lstat.mode & fs.constants.S_IXUSR) === fs.constants.S_IXUSR) {
560+
return dir;
561+
}
562+
// tslint:disable-next-line:no-empty
563+
} catch (ignore) {}
549564
}
550565
// 3. ...the first of %HOME%, %USERPROFILE%, %HOMEDRIVE%%HOMEPATH% that exists is returned.
551566
for (const dir of dirList2) {

0 commit comments

Comments
 (0)