os#platform TypeScript Examples
The following examples show how to use
os#platform.
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: utils.ts From VSCode-R-Debugger with MIT License | 7 votes |
export function getRDownloadLink(packageName: string): string{
let url: string = config().get<string>('packageURL', '');
if(url === ''){
const platform: string = process.platform;
const version: string = String(packageJson.version); // e.g. "0.1.2"
const urlBase =
'https://github.com/ManuelHentschel/VSCode-R-Debugger/releases/download/v' +
version +
'/' +
packageName +
'_' +
version;
if(platform === 'win32'){
url = urlBase + '.zip';
} else if(platform === 'darwin'){
url = urlBase + '.tgz';
} else{
url = urlBase + '.tar.gz';
}
}
return url;
}
Example #2
Source File: command-config.ts From swarm-cli with BSD 3-Clause "New" or "Revised" License | 6 votes |
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 #3
Source File: extension.ts From sorbet-lsp with MIT License | 6 votes |
spawnWithBash = (cmd, opts) => {
if (platform().match(/darwin|linux/)) {
// OSX and Linux need to use an explicit login shell in order to find
// the correct Ruby environment through installation managers like rvm
// and rbenv.
var shell = env.shell || '/bin/bash';
if (shell.endsWith('bash') || shell.endsWith('zsh')) {
var shellCmd = shellEscape(cmd);
if (opts['cwd']) {
shellCmd = `${shellEscape(['cd', opts['cwd']])} && ${shellCmd}`;
}
var shellArgs = [shellCmd];
shellArgs.unshift('-c');
shellArgs.unshift('-l');
return child_process.spawn(shell, shellArgs, { shell, ...opts });
} else {
return crossSpawn(cmd.shift(), cmd, opts);
}
} else {
return crossSpawn(cmd.shift(), cmd, opts);
}
}
Example #4
Source File: config.ts From nodestatus with MIT License | 6 votes |
config = {
NODE_ENV: process.env.NODE_ENV,
database,
port: Number(process.env.PORT || options.port),
interval: Number(process.env.INTERVAL || options.interval),
verbose: process.env.VERBOSE === 'true',
theme: process.env.THEME || 'hotaru-theme',
pingInterval: Number(process.env.PING_INTERVAL || 30),
useIpc: process.env.USE_IPC !== 'false',
useWeb: process.env.USE_WEB !== 'false',
usePush: process.env.USE_PUSH !== 'false',
webUsername: process.env.WEB_USERNAME || 'admin',
webPassword: process.env.WEB_PASSWORD || '',
webSecret: process.env.WEB_SECRET || 'secret',
ipcAddress: process.env.IPC_ADDRESS || (platform() !== 'win32' ? '/tmp/status_unix.sock' : '\\\\.\\pipe\\status_ipc'),
pushTimeOut: Number(process.env.PUSH_TIMEOUT ?? 120),
pushDelay: Number(process.env.PUSH_DELAY ?? 15),
telegram: {
proxy: process.env.TGBOT_PROXY,
bot_token: process.env.TGBOT_TOKEN || '',
chat_id: process.env.TGBOT_CHATID || '',
web_hook: process.env.TGBOT_WEBHOOK
}
}
Example #5
Source File: tray.ts From mysterium-vpn-desktop with MIT License | 6 votes |
trayIconPath = (connectionStatus: ConnectionStatus): string => {
const connected = connectionStatus === ConnectionStatus.CONNECTED
switch (process.platform) {
case "darwin":
return staticAssetPath(`tray/macOS/${connected ? "ActiveTemplate" : "PassiveTemplate"}.png`)
case "win32":
return staticAssetPath(`tray/windows/${connected ? "logo-active" : "logo"}.ico`)
}
return staticAssetPath(`tray/linux/${connected ? "logo-active" : "logo"}.png`)
}
Example #6
Source File: resolver.ts From devoirs with MIT License | 6 votes |
async resolve(): Promise<string> {
const context = createChromiumContext();
const chromiumDirectory = context.directory;
const temporaryDirectory = await this.resolver.resolve(chromiumDirectory);
const executable = join(temporaryDirectory, context.executable);
if (platform() !== 'win32') {
// Change mode to `rwx r-x r-x`
await chmodDirectory(
temporaryDirectory,
S_IRUSR | S_IWUSR | S_IXUSR | S_IRGRP | S_IXGRP | S_IROTH | S_IXOTH // 755
);
}
return executable;
}
Example #7
Source File: playwright.config.ts From excalideck with MIT License | 6 votes |
config: PlaywrightTestConfig = {
testDir: "test/scenario",
forbidOnly: IS_CI,
retries: IS_CI ? 4 : 0,
webServer: {
command: "yarn start",
port: 1234,
env: {
EXCALIDRAW_ELEMENTS_INPUT_ONCHANGE_CHECK_INTERVAL: "1",
SLIDE_MINIATURES_DROP_TRANSITION_DURATION: "0",
SORTABLE_SLIDE_MINIATURE_MOVE_TRANSITION_DURATION: "0",
SLIDE_MINIATURE_IMAGE_RENDER_DEBOUNCE: "1",
},
},
use: {
trace: "retain-on-failure",
},
reporter: IS_CI ? [["github"], ["list"]] : "list",
projects: compact([
{
name: "chromium",
use: { browserName: "chromium" },
},
{
name: "firefox",
use: { browserName: "firefox" },
},
// Re-enable when @playwright/test v1.17.0 is released. See
// microsoft/playwright issue #9811
platform() !== "darwin"
? {
name: "webkit",
use: { browserName: "webkit" },
}
: null,
]),
}
Example #8
Source File: spFormat.ts From sourcepawn-vscode with MIT License | 6 votes |
getNativeBinary() {
let nativeBinary;
const sysPlatform = platform();
const sysArch = arch();
const ext = extensions.getExtension("Sarrus.sourcepawn-vscode");
if (ext === undefined) {
throw Error("Extension not found.");
}
const myExtDir = ext.extensionPath;
if (sysPlatform === "win32") {
nativeBinary = join(myExtDir, "/bin/win32/clang-format.exe");
} else {
nativeBinary = join(
myExtDir,
`/bin/${sysPlatform}_${sysArch}/clang-format`
);
}
if (existsSync(nativeBinary)) {
return nativeBinary;
}
// Let arm64 macOS fall back to x64
if (sysPlatform === "darwin" && sysArch === "arm64") {
nativeBinary = join(myExtDir, `/bin/darwin_x64/clang-format`);
if (existsSync(nativeBinary)) {
return nativeBinary;
}
}
const message =
"This module doesn't bundle the clang-format executable for your platform. " +
`(${sysPlatform}_${sysArch})\n` +
"Please let the author know on GitHub.\n";
throw new Error(message);
}
Example #9
Source File: user.ts From mysterium-vpn-desktop with MIT License | 6 votes |
uid = (): string => {
let uid = 0
// getuid only available on POSIX
// and it's not needed on windows anyway
if (platform() !== "win32") {
uid = process.getuid()
}
return uid.toString()
}
Example #10
Source File: paths.ts From coffeesense with MIT License | 6 votes |
export function getFilePath(documentUri: string): string {
const IS_WINDOWS = platform() === 'win32';
if (IS_WINDOWS) {
// Windows have a leading slash like /C:/Users/pine
// vscode-uri use lower-case drive letter
// https://github.com/microsoft/vscode-uri/blob/95e03c06f87d38f25eda1ae3c343fe5b7eec3f52/src/index.ts#L1017
return URI.parse(documentUri).path.replace(/^\/[a-zA-Z]/, (s: string) => s.slice(1).toLowerCase());
} else {
return URI.parse(documentUri).path;
}
}
Example #11
Source File: submit_problem.ts From CodePal with GNU General Public License v3.0 | 6 votes |
submitProblem = async (path: string) => {
try {
path = Utils.pathRefine(path, platform() === "win32"?OS.windows : OS.linuxMac);
if (vscode.window.activeTextEditor) {
path = vscode.window.activeTextEditor.document.uri.fsPath;
path = path.replace(/\\/g, '/');
}
// ************ copying code to the clipboard **********************
const code = fs.readFileSync(path).toString();
vscode.env.clipboard.writeText(code);
//******************************************************************
const jsonPath = path.substr(0, path.lastIndexOf("/")) + `/.problem.json`;
const jsonData = JSON.parse(fs.readFileSync(jsonPath).toString());
vscode.env.openExternal(vscode.Uri.parse(`https://codeforces.com/contest/${jsonData.contestID}/submit/${jsonData.index}`, true));
vscode.window.showInformationMessage("Submit problem page opened");
} catch (err) {
vscode.window.showErrorMessage(err);
}
}
Example #12
Source File: index.ts From action with MIT License | 6 votes |
function getPlatformArch (a: string, p: string): string {
const platform = {
win32: 'windows'
}
const arch = {
x64: 'amd64',
x32: '386'
}
return (platform[p] ? platform[p] : p) + '/' + (arch[a] ? arch[a] : a)
}
Example #13
Source File: utils.ts From cli with MIT License | 6 votes |
compareFileChange = async (
fromGlob: string[],
toGlob: string[],
options?: any
) => {
options = options || {};
if (!options.cwd) {
options.cwd = process.cwd();
}
options.stats = true;
const isWindows = platform() === 'win32';
if (isWindows) {
fromGlob = fromGlob.map(pattern => {
return pattern.replace(/\\+/g, '/');
});
toGlob = toGlob.map(pattern => {
return pattern.replace(/\\+/g, '/');
});
}
const fromFiles: any = await globby(fromGlob, options);
const toFiles: any = await globby(toGlob, options);
if (!fromFiles || !fromFiles.length) {
return [];
}
if (!toFiles || !toFiles.length) {
return fromFiles.map((file: any) => file.path);
}
let latestFilesChangeTime = 0;
for (const file of toFiles) {
if (file.stats.mtimeMs > latestFilesChangeTime) {
latestFilesChangeTime = file.stats.mtimeMs;
}
}
const result = [];
for (const file of fromFiles) {
if (file.stats.mtimeMs > latestFilesChangeTime) {
result.push(file.path);
}
}
return result;
}
Example #14
Source File: VoiceProviderManager.ts From discord-qt with GNU General Public License v3.0 | 6 votes |
constructor() {
const architecture = arch();
switch (platform()) {
case 'linux':
this.provider = new LinuxVoiceProvider();
break;
case 'win32':
if (['ia32', 'x64'].includes(architecture)) {
this.provider = new Win32VoiceProvider();
} else {
warnNoSupport();
}
break;
case 'darwin':
if (architecture === 'x64') {
this.provider = new DarwinVoiceProvider();
} else {
warnNoSupport();
}
break;
default:
}
}
Example #15
Source File: index.ts From cli with MIT License | 6 votes |
private async handleClose(isExit?, signal?) {
if (this.spin) {
this.spin.stop();
}
if (this.child) {
const childExitError = 'childExitError';
const closeChildRes = await new Promise(resolve => {
if (this.child.connected) {
const id = Date.now() + ':exit:' + Math.random();
setTimeout(() => {
delete this.processMessageMap[id];
resolve(childExitError);
}, 2000);
this.processMessageMap[id] = resolve;
this.child.send({ type: 'exit', id });
} else {
resolve(void 0);
}
});
if (closeChildRes === childExitError) {
const isWin = platform() === 'win32';
try {
if (!isWin) {
execSync(`kill -9 ${this.child.pid} || true`);
}
this.log('Pre Process Force Exit.');
} catch (e) {
this.error('Pre Process Force Exit Error', e.message);
}
}
if (this.child?.kill) {
this.child.kill();
}
this.child = null;
}
if (isExit) {
process.exit(signal);
}
}
Example #16
Source File: open_problem_statement.ts From CodePal with GNU General Public License v3.0 | 6 votes |
openProblemStatement = (path: string) => {
try {
path = Utils.pathRefine(path, platform() === "win32"?OS.windows : OS.linuxMac);
console.log(path);
if (vscode.window.activeTextEditor) {
path = vscode.window.activeTextEditor.document.uri.fsPath;
path = path.replace(/\\/g, '/');
}
const jsonPath = path.substr(0, path.lastIndexOf("/")) + `/.problem.json`;
const jsonData = JSON.parse(fs.readFileSync(jsonPath).toString());
vscode.env.openExternal(vscode.Uri.parse(`https://codeforces.com/contest/${jsonData.contestID}/problem/${jsonData.index}`, true));
vscode.window.showInformationMessage("Opened problem statement");
} catch (err) {
vscode.window.showErrorMessage(err);
}
}
Example #17
Source File: mysteriumNode.ts From mysterium-vpn-desktop with MIT License | 5 votes |
mystBin = (): string => {
let mystBinaryName = "bin/myst"
if (platform() === "win32") {
mystBinaryName += ".exe"
}
return staticAssetPath(mystBinaryName)
}
Example #18
Source File: config.ts From nodestatus with MIT License | 5 votes |
program
.option('-db, --database <db>', 'the path of database', platform() === 'win32' ? `file:${resolve(homedir(), '.nodestatus/db.sqlite')}` : 'file:/usr/local/NodeStatus/server/db.sqlite')
.option('-p, --port <port>', 'the port of NodeStatus', '35601')
.option('-i, --interval <interval>', 'update interval', '1500')
.parse(process.argv);
Example #19
Source File: index.ts From cli with MIT License | 5 votes |
private async makeZip(sourceDirection: string, targetFileName: string) {
let ignore = [];
if (this.core.service?.experimentalFeatures?.removeUselessFiles) {
this.core.cli.log(' - Experimental Feature RemoveUselessFiles');
ignore = uselessFilesMatch;
}
const globbyMatched = ['**'];
const npmClient = this.getNPMClient();
if (npmClient?.startsWith('pnpm')) {
globbyMatched.push('**/.pnpm/**');
}
const fileList = await globby(globbyMatched, {
onlyFiles: false,
followSymbolicLinks: false,
cwd: sourceDirection,
ignore,
});
const zip = new JSZip();
const isWindows = platform() === 'win32';
for (const fileName of fileList) {
const absPath = join(sourceDirection, fileName);
const stats = await lstat(absPath);
if (stats.isDirectory()) {
zip.folder(fileName);
} else if (stats.isSymbolicLink()) {
let link = await readlink(absPath);
if (isWindows) {
link = relative(dirname(absPath), link).replace(/\\/g, '/');
}
zip.file(fileName, link, {
binary: false,
createFolders: true,
unixPermissions: stats.mode,
});
} else if (stats.isFile()) {
const fileData = await readFile(absPath);
zip.file(fileName, fileData, {
binary: true,
createFolders: true,
unixPermissions: stats.mode,
});
}
}
await new Promise((res, rej) => {
zip
.generateNodeStream({
platform: 'UNIX',
compression: 'DEFLATE',
compressionOptions: {
level: 6,
},
})
.pipe(createWriteStream(targetFileName))
.once('finish', res)
.once('error', rej);
});
}
Example #20
Source File: supervisor.ts From mysterium-vpn-desktop with MIT License | 5 votes |
isWin = platform() === "win32"
Example #21
Source File: FFProvider.ts From discord-qt with GNU General Public License v3.0 | 5 votes |
export function getFFmpeg() {
if (platform() === 'linux') {
return 'ffmpeg';
}
return join(__dirname, `ffmpeg${platform() === 'win32' ? '.exe' : ''}`);
}
Example #22
Source File: register.ts From swc-node with MIT License | 5 votes |
PLATFORM = platform()
Example #23
Source File: ip.ts From TidGi-Desktop with Mozilla Public License 2.0 | 5 votes |
/**
* Copy from https://github.com/silverwind/default-gateway 's index.js, to fix its weird behavior on windows. Its require statement will always require sunos
* @returns
*/
async function defaultGatewayV4(): Promise<IDefaultGatewayInfo | undefined> {
const plat = platform();
if (supportedPlatforms.has(plat)) {
let gatewayQueryFileName: NodeJS.Platform | 'ibmi' = plat;
if (plat === 'aix') {
gatewayQueryFileName = type() === 'OS400' ? 'ibmi' : 'sunos'; // AIX `netstat` output is compatible with Solaris
}
switch (gatewayQueryFileName) {
case 'ibmi': {
const defaultGateway = await import('default-gateway/ibmi');
return await defaultGateway.v4();
}
case 'android': {
const defaultGateway = await import('default-gateway/android');
return await defaultGateway.v4();
}
case 'darwin': {
const defaultGateway = await import('default-gateway/darwin');
return await defaultGateway.v4();
}
case 'freebsd': {
const defaultGateway = await import('default-gateway/freebsd');
return await defaultGateway.v4();
}
case 'linux': {
const defaultGateway = await import('default-gateway/linux');
return await defaultGateway.v4();
}
case 'openbsd': {
const defaultGateway = await import('default-gateway/openbsd');
return await defaultGateway.v4();
}
case 'sunos': {
const defaultGateway = await import('default-gateway/sunos');
return await defaultGateway.v4();
}
case 'win32': {
const defaultGateway = await import('default-gateway/win32');
return await defaultGateway.v4();
}
}
}
}
Example #24
Source File: index.ts From cli with MIT License | 5 votes |
// dep size anlysis
private async biggestDep() {
if (platform() === 'win32') {
return;
}
let sizeRes;
try {
sizeRes = await exec({
cmd: 'du -hs * | sort -h',
baseDir: join(this.midwayBuildPath, 'node_modules'),
slience: true,
});
} catch {
// ignore catch
}
if (!sizeRes) {
return;
}
const biggestModList = [];
sizeRes
.split('\n')
.slice(-10)
.forEach(mod => {
if (!mod) {
return;
}
const info = mod.split('\t');
const size = info[0];
let name = info[1];
if (!size) {
return;
}
name = name.replace(/^_|@\d.*$/g, '').replace('_', '/');
if (name[0] === '@' && !name.includes('/')) {
return;
}
biggestModList.push({
size,
name,
});
});
if (!biggestModList.length) {
return;
}
this.core.cli.log(' - Biggest Dependencies list:');
biggestModList
.slice(-5)
.reverse()
.forEach(modInfo => {
this.core.cli.log(` ${modInfo.size}\t${modInfo.name}`);
});
}
Example #25
Source File: index.ts From action with MIT License | 5 votes |
async function installer (version? : string): Promise<string> {
core.info(`downloading semantic-release@${version || 'latest'}`)
const v = version ? `/${version}` : ''
const path = await tc.downloadTool(`https://get-release.xyz/semantic-release/${getPlatformArch(arch(), platform())}${v}`)
await fs.chmod(path, '0755')
return path
}
Example #26
Source File: spinner.ts From swarm-cli with BSD 3-Clause "New" or "Revised" License | 5 votes |
isWindows = platform() === 'win32'
Example #27
Source File: variableResolver.ts From vscode-openscad with GNU General Public License v3.0 | 5 votes |
// private _config: ScadConfig;
constructor() {
// this._config = config
this._isWindows = platform() === 'win32';
}
Example #28
Source File: action.ts From backstage with Apache License 2.0 | 5 votes |
export function createCodemodAction(name: string) {
return async (dirs: string[], opts: OptionValues) => {
const transformPath = relativePath(
process.cwd(),
paths.resolveOwn('transforms', `${name}.js`),
);
const args = [
'--parser=tsx',
'--extensions=tsx,js,ts,tsx',
'--transform',
transformPath,
'--ignore-pattern=**/node_modules/**',
];
if (opts.dry) {
args.push('--dry');
}
if (dirs.length) {
args.push(...dirs);
} else {
args.push('.');
}
console.log(`Running jscodeshift with these arguments: ${args.join(' ')}`);
let command;
if (platform() === 'win32') {
command = 'jscodeshift';
} else {
// jscodeshift ships a slightly broken bin script with windows
// line endings so we need to execute it using node rather than
// letting the `#!/usr/bin/env node` take care of it
command = process.argv0;
args.unshift(require.resolve('.bin/jscodeshift'));
}
const child = spawn(command, args, {
stdio: 'inherit',
shell: true,
env: {
...process.env,
FORCE_COLOR: 'true',
},
});
if (typeof child.exitCode === 'number') {
if (child.exitCode) {
throw new ExitCodeError(child.exitCode, name);
}
return;
}
await new Promise<void>((resolve, reject) => {
child.once('error', error => reject(error));
child.once('exit', code => {
if (code) {
reject(new ExitCodeError(code, name));
} else {
resolve();
}
});
});
};
}
Example #29
Source File: installSM.ts From sourcepawn-vscode with MIT License | 5 votes |
Platform = platform()