2022-04-09 13:32:19 +02:00
|
|
|
import { pathExistsSync, readFileSync } from 'fs-extra';
|
2021-05-21 15:17:21 +02:00
|
|
|
|
2022-04-09 13:32:19 +02:00
|
|
|
// All these calls used to be async but certain scripts need to load config
|
|
|
|
// files early, so they've been converted to sync calls. Do not convert them
|
|
|
|
// back to async.
|
|
|
|
|
|
|
|
export function credentialDir() {
|
2021-05-21 15:17:21 +02:00
|
|
|
const username = require('os').userInfo().username;
|
|
|
|
|
|
|
|
const toTry = [
|
|
|
|
`c:/Users/${username}/joplin-credentials`,
|
|
|
|
`/mnt/c/Users/${username}/joplin-credentials`,
|
|
|
|
`/home/${username}/joplin-credentials`,
|
|
|
|
`/Users/${username}/joplin-credentials`,
|
|
|
|
];
|
|
|
|
|
|
|
|
for (const dirPath of toTry) {
|
2022-04-09 13:32:19 +02:00
|
|
|
if (pathExistsSync(dirPath)) return dirPath;
|
2021-05-21 15:17:21 +02:00
|
|
|
}
|
|
|
|
|
|
|
|
throw new Error(`Could not find credential directory in any of these paths: ${JSON.stringify(toTry)}`);
|
|
|
|
}
|
|
|
|
|
2022-04-09 13:32:19 +02:00
|
|
|
export function credentialFile(filename: string) {
|
|
|
|
const rootDir = credentialDir();
|
2021-05-21 15:17:21 +02:00
|
|
|
const output = `${rootDir}/${filename}`;
|
2022-04-09 13:32:19 +02:00
|
|
|
if (!(pathExistsSync(output))) throw new Error(`No such file: ${output}`);
|
2021-05-21 15:17:21 +02:00
|
|
|
return output;
|
|
|
|
}
|
|
|
|
|
2022-04-09 13:32:19 +02:00
|
|
|
export function readCredentialFile(filename: string, defaultValue: string = '') {
|
2021-05-25 11:49:47 +02:00
|
|
|
try {
|
2022-04-09 13:32:19 +02:00
|
|
|
const filePath = credentialFile(filename);
|
|
|
|
const r = readFileSync(filePath);
|
2021-06-02 21:59:53 +02:00
|
|
|
// There's normally no reason to keep the last new line character and it
|
|
|
|
// can cause problems in certain scripts, so trim it. Any other white
|
|
|
|
// space should also not be relevant.
|
|
|
|
return r.toString().trim();
|
2021-05-25 11:49:47 +02:00
|
|
|
} catch (error) {
|
|
|
|
return defaultValue;
|
|
|
|
}
|
2021-05-21 15:17:21 +02:00
|
|
|
}
|
2022-04-09 13:32:19 +02:00
|
|
|
|
|
|
|
export function readCredentialFileJson<T>(filename: string, defaultValue: T = null): T {
|
|
|
|
const v = readCredentialFile(filename);
|
|
|
|
if (!v) return defaultValue;
|
|
|
|
|
|
|
|
try {
|
|
|
|
const o = JSON.parse(v);
|
|
|
|
return o;
|
|
|
|
} catch (error) {
|
|
|
|
error.message = `Could not parse JSON file ${filename}: ${error.message}`;
|
|
|
|
throw error;
|
|
|
|
}
|
|
|
|
}
|