-
-
Save nissoh/43bf4193d71cc18293bc to your computer and use it in GitHub Desktop.
Cool tricks with ES6 templated strings
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
import {p} from './get-path'; | |
console.log(p`${'userDesktop'}/MyApp`); | |
// On Windows | |
>> C:\Users\TheUser\Desktop\MyApp | |
// On OS X | |
>> /Users/TheUser/Desktop/MyApp | |
console.log(p`${'HOME'}/Downloads`) | |
// On Windows | |
>> C:\Users\TheUser\Downloads | |
// On OS X | |
>> /Users/TheUser/Downloads |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
import _ from 'lodash'; | |
import path from 'path'; | |
let electronApp = null; | |
if (process.type === 'renderer') { | |
electronApp = require('remote').require('app'); | |
} else { | |
electronApp = require('app'); | |
} | |
// NB: Some environment variables are known to app.getPath and we don't have | |
// to worry about them disappearing on us. Use them instead. | |
const environmentVariableAliases = { | |
'HOME': 'home', | |
'USERPROFILE': 'home', | |
'APPDATA': 'appData', | |
'TEMP': 'temp', | |
'TMPDIR': 'temp' | |
}; | |
const pathCache = { }; | |
export function getPath(key) { | |
if (pathCache[key]) return pathCache[key]; | |
let aliasKey = null; | |
if (environmentVariableAliases[key]) { | |
aliasKey = environmentVariableAliases[key]; | |
} | |
let result = null; | |
try { | |
result = electronApp.getPath(aliasKey || key); | |
} catch (e) { | |
console.log(e); | |
} | |
result = result || process.env[key]; | |
if (!result) { | |
// NB: Try to fix up the most commonly fucked environment variables | |
if (key.toLowerCase() === 'appdata' && process.env.USERPROFILE) { | |
result = path.join(process.env.USERPROFILE, 'AppData', 'Roaming'); | |
} | |
if (key.toLowerCase() === 'localappdata' && process.env.USERPROFILE) { | |
result = path.join(process.env.USERPROFILE, 'AppData', 'Local'); | |
} | |
} | |
if (result) pathCache[key] = result; | |
return result; | |
} | |
export function p(strings, ...values) { | |
let newVals = _.map(values, (x) => getPath(x)); | |
let newPath = String.raw(strings, ...newVals); | |
let parts = _.map(newPath.split(/[\\\/]/), (x) => x || '/'); | |
try { | |
return path.resolve(...parts); | |
} catch (e) { | |
return path.join(...parts); | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment