mirror of
https://github.com/zhigang1992/npm.git
synced 2026-06-16 19:51:26 +08:00
60 lines
2.1 KiB
JavaScript
60 lines
2.1 KiB
JavaScript
|
|
module.exports = writeShim
|
|
writeShim.ifExists = shimIfExists
|
|
|
|
var fs = require("./graceful-fs")
|
|
, path = require("path")
|
|
, relativize = require("./relativize")
|
|
, mkdir = require("./mkdir-p")
|
|
, log = require("./log")
|
|
|
|
function shimIfExists (from, to, dep, cb) {
|
|
if (!cb) cb = dep, dep = false
|
|
fs.stat(from, function (er) {
|
|
if (er) return cb()
|
|
writeShim(from, to, dep, cb)
|
|
})
|
|
}
|
|
|
|
function writeShim (from, to, dep, cb) {
|
|
if (!cb) cb = dep, dep = false
|
|
log.silly([from,to], "writeShim")
|
|
if (dep) dep = relativize(dep, to)
|
|
from = relativize(from, to).replace(/\.(js|node)$/, '')
|
|
// todo: remove this dep juggling when 0.2.x is deprecated,
|
|
// and node_modules is picked up automatically.2
|
|
var code = "#!/usr/bin/env node\n"
|
|
+ "// generated by npm, please don't touch!\n"
|
|
+ (dep ? "var dep = require('path').join(__dirname, "
|
|
+ JSON.stringify(dep) + ")\n"
|
|
+ "var depMet = require.paths.indexOf(dep) !== -1\n"
|
|
+ "var bundle = dep.replace(/node_modules$/, "
|
|
+ "'package/node_modules')\n"
|
|
+ "var bundleMet = require.paths.indexOf(bundle) !== -1\n"
|
|
: "")
|
|
+ "var from = "+JSON.stringify(from)+"\n"
|
|
+ "\n"
|
|
+ (dep ? "if (!depMet) require.paths.unshift(dep)\n"
|
|
+ "if (!bundleMet) require.paths.unshift(bundle)\n"
|
|
: "")
|
|
+ "module.exports = require(from)\n"
|
|
+ "\n"
|
|
+ (dep ? "if (!depMet) {\n"
|
|
+ " var i = require.paths.indexOf(dep)\n"
|
|
+ " if (i !== -1) require.paths.splice(i, 1)\n"
|
|
+ "}\n"
|
|
+ "if (!bundleMet) {\n"
|
|
+ " var i = require.paths.indexOf(bundle)\n"
|
|
+ " if (i !== -1) require.paths.slice(i, 1)\n"
|
|
+ "}\n"
|
|
: "")
|
|
|
|
mkdir(path.dirname(to), function (er) {
|
|
if (er) return cb(er)
|
|
fs.writeFile(to, code, "ascii", function (er, ok) {
|
|
if (er) return cb(er)
|
|
fs.chmod(to, 0755, cb)
|
|
})
|
|
})
|
|
}
|