Created
June 27, 2017 03:09
-
-
Save andrejewski/bca21da808de36ae6a9d771f1aa44f10 to your computer and use it in GitHub Desktop.
Refactor example of donejs/cli
This file contains hidden or 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
| // OLD | |
| // Returns a .then-able function that installs a single module | |
| // if it is not available in the current path | |
| var installIfMissing = exports.installIfMissing = function(root, module, range) { | |
| var location = module ? path.join(root, module) : root; | |
| if(!module) { | |
| module = root; | |
| } | |
| debug('Looking for and installing if missing', module); | |
| return function() { | |
| try { | |
| return Q(require.resolve(location)); | |
| } catch (e) { | |
| if(range) { | |
| module = module + '@' + range; | |
| } | |
| console.log('Installing ' + module); | |
| return runCommand('npm', ['install', module, '--loglevel', 'error']); | |
| } | |
| }; | |
| }; | |
| // NEW | |
| function ensurePackage (projectRoot, qualifiedName) { | |
| var packageName = qualifiedName.split('@'); | |
| if (hasPackage(projectRoot, packageName)) { | |
| return Promise.resolve(); | |
| } | |
| return installPackage(qualifiedName); | |
| } | |
| function hasPackage (projectRoot, name) { | |
| var packagesFolder = path.join(projectRoot, 'node_modules'); | |
| var packageFolder = path.join(packagesFolder, name); | |
| try { | |
| require.resolve(packageFolder); | |
| return true; | |
| } catch (error) { | |
| return false; | |
| } | |
| } | |
| function installPackage (qualifiedName) { | |
| return runCommand('npm', ['install', qualifiedName, '--no-shrinkwrap', '--loglevel', 'error']); | |
| } |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment