os#homedir TypeScript Examples

The following examples show how to use os#homedir. You can vote up the ones you like or vote down the ones you don't like, and go to the original project or source file by following the links above each example. You may check out the related API usage on the sidebar.
Example #1
Source File: management.ts    From tatum-kms with MIT License 6 votes vote down vote up
exportWallets = (path?: string) => {
    const pwd = config.getValue(ConfigOption.KMS_PASSWORD)
    const pathToWallet = path || homedir() + '/.tatumrc/wallet.dat';
    if (!existsSync(pathToWallet)) {
        console.error(JSON.stringify({error: `No such wallet file.`}, null, 2));
        return;
    }
    const data = readFileSync(pathToWallet, {encoding: 'utf8'});
    if (!data?.length) {
        console.error(JSON.stringify({error: `No such wallet file.`}, null, 2));
        return;
    }
    console.log(JSON.stringify(JSON.parse(AES.decrypt(data, pwd).toString(enc.Utf8)), null, 2));
}
Example #2
Source File: vim.ts    From action-setup-vim with MIT License 6 votes vote down vote up
async function installVimAssetOnWindows(file: string, url: string, dirSuffix: string): Promise<string> {
    const tmpdir = await makeTmpdir();
    const dlDir = path.join(tmpdir, 'vim-installer');
    await io.mkdirP(dlDir);
    const assetFile = path.join(dlDir, file);

    try {
        core.debug(`Downloading asset at ${url} to ${dlDir}`);
        const response = await fetch(url);
        if (!response.ok) {
            throw new Error(`Downloading asset failed: ${response.statusText}`);
        }
        const buffer = await response.buffer();
        await fs.writeFile(assetFile, buffer, { encoding: null });
        core.debug(`Downloaded installer from ${url} to ${assetFile}`);

        await exec('unzip', [assetFile], { cwd: dlDir });
    } catch (e) {
        const err = ensureError(e);
        core.debug(err.stack ?? err.message);
        throw new Error(`Could not download and unarchive asset ${url} at ${dlDir}: ${err.message}`);
    }

    const unzippedDir = path.join(dlDir, 'vim'); // Unarchived to 'vim' directory
    const vimDir = await getVimRootDirAt(unzippedDir);
    core.debug(`Unzipped installer from ${url} and found Vim directory ${vimDir}`);

    const destDir = path.join(homedir(), `vim-${dirSuffix}`);
    await io.mv(vimDir, destDir);
    core.debug(`Vim was installed to ${destDir}`);

    return destDir;
}
Example #3
Source File: utils.ts    From uivonim with GNU Affero General Public License v3.0 6 votes vote down vote up
$HOME = homedir
  ? homedir()
  : 'Why are you using this from the frontend? Stop it.'
Example #4
Source File: fileUtil.ts    From flood with GNU General Public License v3.0 6 votes vote down vote up
sanitizePath = (input?: string): string => {
  if (typeof input !== 'string') {
    throw accessDeniedError();
  }

  // eslint-disable-next-line no-control-regex
  const controlRe = /[\x00-\x1f\x80-\x9f]/g;

  return path.resolve(input.replace(/^~/, homedir()).replace(controlRe, ''));
}
Example #5
Source File: clientGatewayService.ts    From flood with GNU General Public License v3.0 6 votes vote down vote up
async getClientSessionDirectory(): Promise<{path: string; case: 'lower' | 'upper'}> {
    // qBittorrent API does not provide session directory.
    // We can only guess with the common locations here.
    switch (process.platform) {
      case 'win32':
        if (process.env.LOCALAPPDATA) {
          return {path: path.join(process.env.LOCALAPPDATA, '\\qBittorrent\\BT_backup'), case: 'lower'};
        }
        return {path: path.join(homedir(), '\\AppData\\Local\\qBittorrent\\BT_backup'), case: 'lower'};
      case 'darwin':
        return {path: path.join(homedir(), '/Library/Application Support/qBittorrent/BT_backup'), case: 'lower'};
      default:
        const legacyPath = path.join(homedir(), '/.local/share/data/qBittorrent/BT_backup');
        try {
          await fs.promises.access(legacyPath);
          return {path: legacyPath, case: 'lower'};
        } catch {
          return {path: path.join(homedir(), '/.local/share/qBittorrent/BT_backup'), case: 'lower'};
        }
    }
  }
Example #6
Source File: clientGatewayService.ts    From flood with GNU General Public License v3.0 6 votes vote down vote up
async getClientSessionDirectory(): Promise<{path: string; case: 'lower' | 'upper'}> {
    // Deluge API does not provide session directory.
    // We can only guess with the common locations here.
    switch (process.platform) {
      case 'win32':
        if (process.env.APPDATA) {
          return {path: path.join(process.env.APPDATA, '\\deluge\\state'), case: 'lower'};
        }
        return {path: path.join(homedir(), '\\AppData\\deluge\\state'), case: 'lower'};
      default:
        return {path: path.join(homedir(), '/.config/deluge/state'), case: 'lower'};
    }
  }
Example #7
Source File: config.ts    From devmoji with Apache License 2.0 6 votes vote down vote up
static async load(configFile?: string, cwd = process.cwd()) {
    if (configFile && !fs.existsSync(configFile))
      throw `Config file not found ${configFile}`

    if (!configFile) {
      const searchPaths = [
        cwd,
        Config.findRoot("./package.json"),
        Config.findRoot("./.git"),
        homedir(),
      ]
      for (const p of searchPaths) {
        if (p) {
          const file = path.resolve(p, "./devmoji.config.js")
          if (fs.existsSync(file)) {
            configFile = file
            break
          }
        }
      }
    }

    if (configFile) {
      configFile = path.resolve(cwd, configFile)
      // eslint-disable-next-line @typescript-eslint/no-unsafe-assignment
      const options = await import(configFile)
      return new Config(options)
    }

    return new Config()
  }
Example #8
Source File: command-config.ts    From swarm-cli with BSD 3-Clause "New" or "Revised" License 6 votes vote down vote up
private getConfigFolderPath(appName: string, configFolder?: string): string {
    if (configFolder) return configFolder

    const homePath = homedir()

    if (platform() === 'win32') {
      return join(homePath, 'AppData', appName)
    } else {
      return join(homePath, `.${appName}`)
    }
  }
Example #9
Source File: utils.ts    From squid with GNU General Public License v3.0 6 votes vote down vote up
configDirectory = resolve(homedir(), '.hydra-cli')
Example #10
Source File: management.ts    From tatum-kms with MIT License 6 votes vote down vote up
getManagedWallets = (pwd: string, chain: string, testnet: boolean, path?: string) => {
    const pathToWallet = path || homedir() + '/.tatumrc/wallet.dat';
    if (!existsSync(pathToWallet)) {
        console.error(JSON.stringify({error: `No such wallet file.`}, null, 2));
        return [];
    }
    const data = readFileSync(pathToWallet, {encoding: 'utf8'});
    if (!data?.length) {
        return [];
    }
    const wallets = JSON.parse(AES.decrypt(data, pwd).toString(enc.Utf8));
    const keys = [];
    for (const walletsKey in wallets) {
        if (chain === wallets[walletsKey].chain && testnet === wallets[walletsKey].testnet) {
            keys.push(walletsKey);
        }
    }
    return keys;
}
Example #11
Source File: authentication.ts    From openwhisk-vscode-extension with Apache License 2.0 6 votes vote down vote up
export function getLocalAuthInfo(): Promise<AuthInfo | null> {
    const wskPropEnvVarName = 'WSK_CONFIG_FILE';

    const wskPropFilePath =
        typeof process.env[wskPropEnvVarName] === undefined
            ? (process.env[wskPropEnvVarName] as string)
            : join(homedir(), '.wskprops');

    return readWskPropFile(wskPropFilePath);
}
Example #12
Source File: management.ts    From tatum-kms with MIT License 6 votes vote down vote up
storeWallet = async (chain: Currency, testnet: boolean, path?: string, mnemonic?: string) => {
    const pwd = config.getValue(ConfigOption.KMS_PASSWORD);
    const pathToWallet = path || homedir() + '/.tatumrc/wallet.dat';
    let wallet: any;
    if (chain === Currency.SOL) {
        wallet = await generateSolanaWallet();
    } else if (chain === Currency.KCS) {
        wallet = await generateKcsWallet(mnemonic, {testnet});
    } else if (chain === Currency.LUNA) {
        wallet = TatumTerraSDK({apiKey: process.env.TATUM_API_KEY as string}).wallet.wallet();
    } else {
        wallet = await generateWallet(chain, testnet, mnemonic);
    }
    const key = uuid();
    const entry = {[key]: {...wallet, chain, testnet}};
    if (!existsSync(pathToWallet)) {
        ensurePathExists(pathToWallet);
        writeFileSync(pathToWallet, AES.encrypt(JSON.stringify(entry), pwd).toString());
    } else {
        const data = readFileSync(pathToWallet, { encoding: 'utf8' });
        let walletData = entry;
        if (data?.length > 0) {
            walletData = { ...walletData, ...JSON.parse(AES.decrypt(data, pwd).toString(enc.Utf8)) };
        }
        writeFileSync(pathToWallet, AES.encrypt(JSON.stringify(walletData), pwd).toString());
    }
    const value: any = { signatureId: key };
    if (wallet.address) {
        value.address = wallet.address;
    }
    if (wallet.xpub) {
        value.xpub = wallet.xpub;
    }
    console.log(JSON.stringify(value, null, 2));
}
Example #13
Source File: management.ts    From tatum-kms with MIT License 6 votes vote down vote up
storePrivateKey = async (chain: Currency, testnet: boolean, privateKey: string, path?: string) => {
    const pwd = config.getValue(ConfigOption.KMS_PASSWORD)
    const pathToWallet = path || homedir() + '/.tatumrc/wallet.dat';
    const key = uuid();
    const entry = { [key]: { privateKey, chain, testnet } };
    if (!existsSync(pathToWallet)) {
        ensurePathExists(pathToWallet);
        writeFileSync(pathToWallet, AES.encrypt(JSON.stringify(entry), pwd).toString());
    } else {
        const data = readFileSync(pathToWallet, { encoding: 'utf8' });
        let walletData = entry;
        if (data?.length > 0) {
            walletData = { ...walletData, ...JSON.parse(AES.decrypt(data, pwd).toString(enc.Utf8)) };
        }
        writeFileSync(pathToWallet, AES.encrypt(JSON.stringify(walletData), pwd).toString());
    }
    console.log(JSON.stringify({ signatureId: key }, null, 2));
}
Example #14
Source File: management.ts    From tatum-kms with MIT License 6 votes vote down vote up
getWallet = async (id: string, path?: string, pwd?: string, print = true) => {
    const password = pwd ?? config.getValue(ConfigOption.KMS_PASSWORD);
    const pathToWallet = path || homedir() + '/.tatumrc/wallet.dat';
    if (!existsSync(pathToWallet)) {
        console.error(JSON.stringify({ error: `No such wallet for signatureId '${id}'.` }, null, 2));
        return;
    }
    const data = readFileSync(pathToWallet, { encoding: 'utf8' });
    if (!data?.length) {
        console.error(JSON.stringify({ error: `No such wallet for signatureId '${id}'.` }, null, 2));
        return;
    }
    try {
        const wallet = JSON.parse(AES.decrypt(data, password).toString(enc.Utf8));
        if (!wallet[id]) {
            console.error(JSON.stringify({ error: `No such wallet for signatureId '${id}'.` }, null, 2));
            return;
        }
        if (print) {
            console.log(JSON.stringify(wallet[id], null, 2));
        }
        return wallet[id];
    } catch (e) {
        console.error(JSON.stringify({ error: `Wrong password.` }, null, 2));
        return;
    }
}
Example #15
Source File: TenderlyApiService.ts    From hardhat-tenderly with GNU General Public License v3.0 6 votes vote down vote up
private static getTenderlyConfig(): TenderlyKeyConfig {
    const filepath = homedir() + sep + ".tenderly" + sep + "config.yaml";
    const fileData = fs.readFileSync(filepath);
    const yamlData: TenderlyKeyConfig = yaml.load(fileData.toString());

    if (yamlData.access_key == null) {
      throw new HardhatPluginError(
        PluginName,
        `Access token not provided at filepath ${filepath}.\n` +
          `You can find the token at ${TENDERLY_DASHBOARD_BASE_URL}/account/authorization`
      );
    }

    return yamlData;
  }
Example #16
Source File: management.ts    From tatum-kms with MIT License 6 votes vote down vote up
getPrivateKey = async (id: string, index: string, path?: string) => {
    const pwd = config.getValue(ConfigOption.KMS_PASSWORD)
    const pathToWallet = path || homedir() + '/.tatumrc/wallet.dat';
    if (!existsSync(pathToWallet)) {
        console.error(JSON.stringify({ error: `No such wallet for signatureId '${id}'.` }, null, 2));
        return;
    }
    const data = readFileSync(pathToWallet, { encoding: 'utf8' });
    if (!data?.length) {
        console.error(JSON.stringify({ error: `No such wallet for signatureId '${id}'.` }, null, 2));
        return;
    }
    const wallet = JSON.parse(AES.decrypt(data, pwd).toString(enc.Utf8));
    if (!wallet[id]) {
        console.error(JSON.stringify({ error: `No such wallet for signatureId '${id}'.` }, null, 2));
        return;
    }
    const pk = { privateKey: (wallet[id].secret
            ? wallet[id].secret
            : await generatePrivateKeyFromMnemonic(wallet[id].chain, wallet[id].testnet, wallet[id].mnemonic, parseInt(index))) };
    console.log(JSON.stringify(pk, null, 2));
}
Example #17
Source File: management.ts    From tatum-kms with MIT License 6 votes vote down vote up
getAddress = async (id: string, index: string, path?: string) => {
    const pwd = config.getValue(ConfigOption.KMS_PASSWORD)
    const pathToWallet = path || homedir() + '/.tatumrc/wallet.dat';
    if (!existsSync(pathToWallet)) {
        console.error(JSON.stringify({ error: `No such wallet for signatureId '${id}'.` }, null, 2));
        return;
    }
    const data = readFileSync(pathToWallet, { encoding: 'utf8' });
    if (!data?.length) {
        console.error(JSON.stringify({ error: `No such wallet for signatureId '${id}'.` }, null, 2));
        return;
    }
    const wallet = JSON.parse(AES.decrypt(data, pwd).toString(enc.Utf8));
    if (!wallet[id]) {
        console.error(JSON.stringify({ error: `No such wallet for signatureId '${id}'.` }, null, 2));
        return;
    }
    const pk = { address: (wallet[id].address ? wallet[id].address : await generateAddressFromXPub(wallet[id].chain, wallet[id].testnet, wallet[id].xpub, parseInt(index))) };
    console.log(JSON.stringify(pk, null, 2));
}
Example #18
Source File: management.ts    From tatum-kms with MIT License 6 votes vote down vote up
removeWallet = async (id: string, path?: string) => {
    const pwd = config.getValue(ConfigOption.KMS_PASSWORD)
    const pathToWallet = path || homedir() + '/.tatumrc/wallet.dat';
    if (!existsSync(pathToWallet)) {
        console.error(JSON.stringify({ error: `No such wallet for signatureId '${id}'.` }, null, 2));
        return;
    }
    const data = readFileSync(pathToWallet, { encoding: 'utf8' });
    if (!data?.length) {
        console.error(JSON.stringify({ error: `No such wallet for signatureId '${id}'.` }, null, 2));
        return;
    }
    const wallet = JSON.parse(AES.decrypt(data, pwd).toString(enc.Utf8));
    delete wallet[id];
    writeFileSync(pathToWallet, AES.encrypt(JSON.stringify(wallet), pwd).toString());
}
Example #19
Source File: change-project.tsx    From uivonim with GNU Affero General Public License v3.0 5 votes vote down vote up
api.nvim.watchState.cwd((cwd: string) => {
  if (cwd && homedir() !== cwd) renameCurrentToCwd(basename(cwd))
})
Example #20
Source File: neovim.ts    From action-setup-vim with MIT License 5 votes vote down vote up
// version = 'stable' or 'nightly' or version string
export async function downloadNeovim(version: string, os: Os): Promise<Installed> {
    const file = assetFileName(os);
    const destDir = path.join(homedir(), `nvim-${version}`);
    const url = `https://github.com/neovim/neovim/releases/download/${version}/${file}`;
    console.log(`Downloading Neovim ${version} on ${os} from ${url} to ${destDir}`);

    const dlDir = await makeTmpdir();
    const asset = path.join(dlDir, file);

    try {
        core.debug(`Downloading asset ${asset}`);
        const response = await fetch(url);
        if (!response.ok) {
            throw new Error(`Downloading asset failed: ${response.statusText}`);
        }
        const buffer = await response.buffer();
        await fs.writeFile(asset, buffer, { encoding: null });
        core.debug(`Downloaded asset ${asset}`);

        const unarchived = await unarchiveAsset(asset, assetDirName(version, os));
        core.debug(`Unarchived asset ${unarchived}`);

        await io.mv(unarchived, destDir);
        core.debug(`Installed Neovim ${version} on ${os} to ${destDir}`);

        return {
            executable: exeName(true, os),
            binDir: path.join(destDir, 'bin'),
        };
    } catch (e) {
        const err = ensureError(e);
        core.debug(err.stack ?? err.message);
        let msg = `Could not download Neovim release from ${url}: ${err.message}. Please visit https://github.com/neovim/neovim/releases/tag/${version} to check the asset for ${os} was really uploaded`;
        if (version === 'nightly') {
            msg += ". Note that some assets are sometimes missing on nightly build due to Neovim's CI failure";
        }
        throw new Error(msg);
    }
}
Example #21
Source File: neovim.ts    From action-setup-vim with MIT License 5 votes vote down vote up
// Build nightly Neovim from sources as fallback of downloading nightly assets from the nightly release page of
// neovim/neovim repository (#18).
// https://github.com/neovim/neovim/wiki/Building-Neovim
export async function buildNightlyNeovim(os: Os): Promise<Installed> {
    core.debug(`Installing Neovim by building from source on ${os}`);

    switch (os) {
        case 'linux':
            core.debug('Installing build dependencies via apt');
            await exec('sudo', [
                'apt-get',
                'install',
                '-y',
                '--no-install-recommends',
                'ninja-build',
                'gettext',
                'libtool',
                'libtool-bin',
                'autoconf',
                'automake',
                'cmake',
                'g++',
                'pkg-config',
                'unzip',
                'curl',
            ]);
            break;
        case 'macos':
            core.debug('Installing build dependencies via Homebrew');
            await exec('brew', ['install', 'ninja', 'libtool', 'automake', 'cmake', 'pkg-config', 'gettext', 'curl']);
            break;
        default:
            throw new Error(`Building Neovim from soruce is not supported for ${os} platform`);
    }

    // Add -nightly suffix since building stable Neovim from source may be supported in the future
    const installDir = path.join(homedir(), 'nvim-nightly');
    core.debug(`Building and installing Neovim to ${installDir}`);
    const dir = path.join(await makeTmpdir(), 'build-nightly-neovim');

    await exec('git', ['clone', '--depth=1', 'https://github.com/neovim/neovim.git', dir]);

    const opts = { cwd: dir };
    const makeArgs = ['-j', `CMAKE_EXTRA_FLAGS=-DCMAKE_INSTALL_PREFIX=${installDir}`, 'CMAKE_BUILD_TYPE=RelWithDebug'];
    await exec('make', makeArgs, opts);
    core.debug(`Built Neovim in ${opts.cwd}. Installing it via 'make install'`);
    await exec('make', ['install'], opts);
    core.debug(`Installed Neovim to ${installDir}`);

    return {
        executable: exeName(true, os),
        binDir: path.join(installDir, 'bin'),
    };
}
Example #22
Source File: post_action_check.ts    From action-setup-vim with MIT License 5 votes vote down vote up
function expectedExecutable(neovim: boolean, ver: string): string {
    if (neovim) {
        switch (process.platform) {
            case 'darwin':
                if (ver === 'stable') {
                    return '/usr/local/bin/nvim';
                } else {
                    // nightly or specific version
                    return path.join(homedir(), `nvim-${ver}/bin/nvim`);
                }
            case 'linux':
                return path.join(homedir(), `nvim-${ver}/bin/nvim`);
            case 'win32':
                return path.join(homedir(), `nvim-${ver}/bin/nvim.exe`);
            default:
                break;
        }
    } else {
        // vim
        switch (process.platform) {
            case 'darwin':
                if (ver === 'stable') {
                    return '/usr/local/bin/vim';
                } else {
                    // nightly or specific version
                    return path.join(homedir(), `vim-${ver}/bin/vim`);
                }
            case 'linux':
                if (ver === 'stable') {
                    return '/usr/bin/vim';
                } else {
                    // nightly or specific version
                    return path.join(homedir(), `vim-${ver}/bin/vim`);
                }
            case 'win32':
                return path.join(homedir(), `vim-${ver}/vim.exe`);
            default:
                break;
        }
    }
    throw new Error(`Unexpected platform '${process.platform}'`);
}
Example #23
Source File: vim.ts    From action-setup-vim with MIT License 5 votes vote down vote up
// Only available on macOS or Linux. Passing null to `version` means install HEAD
export async function buildVim(version: string, os: Os): Promise<Installed> {
    assert.notEqual(version, 'stable');
    const installDir = path.join(homedir(), `vim-${version}`);
    core.debug(`Building and installing Vim to ${installDir} (version=${version ?? 'HEAD'})`);
    const dir = path.join(await makeTmpdir(), 'vim');

    const args = ['clone', '--depth=1', '--single-branch'];
    if (version === 'nightly') {
        args.push('--no-tags');
    } else {
        args.push('--branch', version);
    }
    args.push('https://github.com/vim/vim', dir);

    await exec('git', args);

    const env: Env = {};
    if (os === 'macos' && versionIsOlderThan8_2_1119(version)) {
        const dir = await getXcode11DevDir();
        if (dir !== null) {
            // Vim before v8.2.1119 cannot be built with Xcode 12 or later. It requires Xcode 11.
            //   ref: https://github.com/vim/vim/commit/5289783e0b07cfc3f92ee933261ca4c4acdca007
            // By setting $DEVELOPER_DIR environment variable, Xcode11 is used to build Vim.
            //   ref: https://www.jessesquires.com/blog/2020/01/06/selecting-an-xcode-version-on-github-ci/
            // Note that xcode-select command is not available since it changes Xcode version in system global.
            env['DEVELOPER_DIR'] = dir;
            core.debug(`Building Vim older than 8.2.1119 on macOS with Xcode11 at ${dir} instead of the latest Xcode`);
        } else {
            core.warning(
                `Building Vim older than 8.2.1119 on macOS but proper Xcode is not found at ${dir}. Using the latest Xcode`,
            );
        }
    }

    const opts = { cwd: dir, env };
    await exec('./configure', [`--prefix=${installDir}`, '--with-features=huge', '--enable-fail-if-missing'], opts);
    await exec('make', ['-j'], opts);
    await exec('make', ['install'], opts);
    core.debug(`Built and installed Vim to ${installDir} (version=${version})`);

    return {
        executable: exeName(false, os),
        binDir: path.join(installDir, 'bin'),
    };
}
Example #24
Source File: change-project.tsx    From uivonim with GNU Affero General Public License v3.0 5 votes vote down vote up
$HOME = homedir()
Example #25
Source File: main.ts    From setup-rust with MIT License 5 votes vote down vote up
CACHE_PATH = [path.join(homedir(), ".rustup", "toolchains")]
Example #26
Source File: secureStore.ts    From zcli with Apache License 2.0 5 votes vote down vote up
pluginsPath = path.join(homedir(), '/.local/share/zcli')
Example #27
Source File: config.ts    From anchorcli with Apache License 2.0 5 votes vote down vote up
configFilePathTestnet = path.join(
  homedir(),
  'anchorcliTestnet.json',
)
Example #28
Source File: config.ts    From anchorcli with Apache License 2.0 5 votes vote down vote up
configFilePathMainnet = path.join(
  homedir(),
  'anchorcliMainnet.json',
)
Example #29
Source File: q-conn-manager.ts    From vscode-q with MIT License 5 votes vote down vote up
oldCfgPath = path.join(homedir(), '.vscode', 'q-server-cfg.json')