Skip to content
Permalink

Comparing changes

Choose two branches to see what’s changed or to start a new pull request. If you need to, you can also or learn more about diff comparisons.

Open a pull request

Create a new pull request by comparing changes across two branches. If you need to, you can also . Learn more about diff comparisons here.
base repository: npm/bin-links
Failed to load repositories. Confirm that selected base ref is valid, then try again.
Loading
base: 3c7112104c3c4f68563a6b22b8abfee8ecb0707d
Choose a base ref
...
head repository: npm/bin-links
Failed to load repositories. Confirm that selected head ref is valid, then try again.
Loading
compare: ca8aad242a50b9ac92393ed17c1a34e048690907
Choose a head ref

Commits on Jan 22, 2019

  1. deps: bump deps

    Audrey Eschright committed Jan 22, 2019
    Copy the full SHA
    9d4127b View commit details
  2. deps: bump devDeps

    Audrey Eschright committed Jan 22, 2019

    Verified

    This commit was created on GitHub.com and signed with GitHub’s verified signature.
    Copy the full SHA
    67351fa View commit details

Commits on Jan 23, 2019

  1. test: updating CI config to match current Node LTS

    Audrey Eschright committed Jan 23, 2019
    Copy the full SHA
    cfd146b View commit details

Commits on Aug 14, 2019

  1. deps: cmd-shim@3.0.0

    isaacs committed Aug 14, 2019
    Copy the full SHA
    5640f35 View commit details
  2. chore(release): 1.1.3

    isaacs committed Aug 14, 2019
    Copy the full SHA
    24324d3 View commit details

Commits on Dec 9, 2019

  1. Copy the full SHA
    02bb9e1 View commit details
  2. Copy the full SHA
    25a34f9 View commit details
  3. chore(release): 1.1.4

    isaacs committed Dec 9, 2019
    Copy the full SHA
    fe39e10 View commit details
  4. github settings

    isaacs committed Dec 9, 2019
    Copy the full SHA
    181e36d View commit details

Commits on Dec 10, 2019

  1. Copy the full SHA
    b3cfd2e View commit details
  2. chore(release): 1.1.5

    isaacs committed Dec 10, 2019
    Copy the full SHA
    52e6525 View commit details

Commits on Dec 11, 2019

  1. update travis

    isaacs committed Dec 11, 2019
    Copy the full SHA
    bc69419 View commit details
  2. fix: prevent improper clobbering of man/bin links

    This uses the updated version of gentle-fs which has the binLink method,
    so that we don't need to fork based on OS, and will always check to
    ensure that the bin or cmd-shim is a reference into the folder being
    linked.
    
    Also perform a similar check on linked man pages.
    
    Fix #11
    
    PR-URL: #12
    Credit: @isaacs
    Close: #12
    Reviewed-by: @isaacs
    isaacs committed Dec 11, 2019
    Copy the full SHA
    642cd18 View commit details
  3. chore(release): 1.1.6

    isaacs committed Dec 11, 2019
    Copy the full SHA
    f315830 View commit details

Commits on Dec 26, 2019

  1. fix: resolve folder that is passed in

    Root cause of npm/cli#613
    isaacs committed Dec 26, 2019
    Copy the full SHA
    0bbd303 View commit details
  2. chore(release): 1.1.7

    isaacs committed Dec 26, 2019
    Copy the full SHA
    32132c9 View commit details

Commits on Jan 5, 2020

  1. chore: Use native Promises instead of Bluebird

    BREAKING CHANGE: Promises are now Promises, rather than blue birds.
    
    Fix #13
    isaacs committed Jan 5, 2020
    Copy the full SHA
    ee939c0 View commit details
  2. Copy the full SHA
    3fa88fa View commit details

Commits on Jan 6, 2020

  1. fix: do not require a log option

    Just use a no-op 'logger' if there isn't one in the options.
    isaacs committed Jan 6, 2020
    Copy the full SHA
    2c6fb91 View commit details

Commits on Jan 7, 2020

  1. Copy the full SHA
    49c3151 View commit details

Commits on Jan 27, 2020

  1. license: Artistic 2.0 -> ISC

    isaacs committed Jan 27, 2020
    Copy the full SHA
    2f8c1fa View commit details
  2. deps for new version

    isaacs committed Jan 27, 2020
    Copy the full SHA
    675263d View commit details
  3. tests for v2

    isaacs committed Jan 27, 2020
    Copy the full SHA
    d35c9b2 View commit details
  4. v2 implementation

    isaacs committed Jan 27, 2020
    Copy the full SHA
    a1272ee View commit details
  5. changelog for v2

    isaacs committed Jan 27, 2020
    Copy the full SHA
    3344f8d View commit details
  6. ignore most things

    isaacs committed Jan 27, 2020
    Copy the full SHA
    3af8c54 View commit details

Commits on Jan 31, 2020

  1. docs: update for v2

    PR-URL: #14
    Credit: @isaacs
    Close: #14
    Reviewed-by: @mikemimik
    isaacs committed Jan 31, 2020
    Copy the full SHA
    5ce48a1 View commit details
  2. 2.0.0

    isaacs committed Jan 31, 2020
    Copy the full SHA
    ca8aad2 View commit details
Showing with 3,839 additions and 5,245 deletions.
  1. +2 −0 .github/settings.yml
  2. +22 −4 .gitignore
  3. +4 −5 .travis.yml
  4. +48 −1 CHANGELOG.md
  5. +0 −144 CODE_OF_CONDUCT.md
  6. +0 −256 CONTRIBUTING.md
  7. +0 −7 ISSUE_TEMPLATE
  8. +12 −232 LICENSE
  9. +0 −7 PULL_REQUEST_TEMPLATE
  10. +27 −8 README.md
  11. +0 −22 appveyor.yml
  12. +45 −153 index.js
  13. +44 −0 lib/fix-bin.js
  14. +2 −0 lib/is-windows.js
  15. +9 −0 lib/link-bin.js
  16. +20 −0 lib/link-bins.js
  17. +57 −0 lib/link-gently.js
  18. +47 −0 lib/link-mans.js
  19. +64 −0 lib/shim-bin.js
  20. +3 −0 map.js
  21. +2,356 −4,279 package-lock.json
  22. +26 −30 package.json
  23. +542 −0 tap-snapshots/test-index.js-TAP.test.js
  24. +76 −0 test/fix-bin.js
  25. +68 −97 test/index.js
  26. +12 −0 test/is-windows.js
  27. +13 −0 test/link-bin.js
  28. +41 −0 test/link-bins.js
  29. +76 −0 test/link-gently.js
  30. +61 −0 test/link-mans.js
  31. +162 −0 test/shim-bin.js
2 changes: 2 additions & 0 deletions .github/settings.yml
Original file line number Diff line number Diff line change
@@ -0,0 +1,2 @@
---
_extends: 'open-source-project-boilerplate'
26 changes: 22 additions & 4 deletions .gitignore
Original file line number Diff line number Diff line change
@@ -1,4 +1,22 @@
/node_modules
/.nyc_output
/coverage
/test/cache
# ignore most things, include some others
/*
/.*

!bin/
!lib/
!docs/
!package.json
!package-lock.json
!README.md
!CONTRIBUTING.md
!LICENSE
!CHANGELOG.md
!example/
!scripts/
!tap-snapshots/
!test/
!.travis.yml
!.gitignore
!.gitattributes
!map.js
!index.js
9 changes: 4 additions & 5 deletions .travis.yml
Original file line number Diff line number Diff line change
@@ -1,7 +1,6 @@
language: node_js
sudo: false

node_js:
- "9"
- "8"
- "6"
- "4"
- node
- 12
- 10
49 changes: 48 additions & 1 deletion CHANGELOG.md
Original file line number Diff line number Diff line change
@@ -1,6 +1,53 @@
# Change Log

All notable changes to this project will be documented in this file. See [standard-version](https://github.com/conventional-changelog/standard-version) for commit guidelines.
## 2.0.0

* Rewrite to promisify and remove dependence on gentle-fs

<a name="1.1.7"></a>
## [1.1.7](https://github.com/npm/bin-links/compare/v1.1.6...v1.1.7) (2019-12-26)


### Bug Fixes

* resolve folder that is passed in ([0bbd303](https://github.com/npm/bin-links/commit/0bbd303))



<a name="1.1.6"></a>
## [1.1.6](https://github.com/npm/bin-links/compare/v1.1.5...v1.1.6) (2019-12-11)


### Bug Fixes

* prevent improper clobbering of man/bin links ([642cd18](https://github.com/npm/bin-links/commit/642cd18)), closes [#11](https://github.com/npm/bin-links/issues/11) [#12](https://github.com/npm/bin-links/issues/12)



<a name="1.1.5"></a>
## [1.1.5](https://github.com/npm/bin-links/compare/v1.1.4...v1.1.5) (2019-12-10)


### Bug Fixes

* don't filter out ./ man references ([b3cfd2e](https://github.com/npm/bin-links/commit/b3cfd2e))



<a name="1.1.4"></a>
## [1.1.4](https://github.com/npm/bin-links/compare/v1.1.3...v1.1.4) (2019-12-09)


### Bug Fixes

* sanitize and validate bin and man link targets ([25a34f9](https://github.com/npm/bin-links/commit/25a34f9))



<a name="1.1.3"></a>
## [1.1.3](https://github.com/npm/bin-links/compare/v1.1.2...v1.1.3) (2019-08-14)



<a name="1.1.2"></a>
## [1.1.2](https://github.com/npm/bin-links/compare/v1.1.1...v1.1.2) (2018-03-22)
144 changes: 0 additions & 144 deletions CODE_OF_CONDUCT.md

This file was deleted.

256 changes: 0 additions & 256 deletions CONTRIBUTING.md

This file was deleted.

7 changes: 0 additions & 7 deletions ISSUE_TEMPLATE

This file was deleted.

244 changes: 12 additions & 232 deletions LICENSE
Original file line number Diff line number Diff line change
@@ -1,235 +1,15 @@
The npm application
Copyright (c) npm, Inc. and Contributors
Licensed on the terms of The Artistic License 2.0
The ISC License

Node package dependencies of the npm application
Copyright (c) their respective copyright owners
Licensed on their respective license terms
Copyright (c) npm, Inc.

The npm public registry at https://registry.npmjs.org
and the npm website at https://www.npmjs.com
Operated by npm, Inc.
Use governed by terms published on https://www.npmjs.com
Permission to use, copy, modify, and/or distribute this software for any
purpose with or without fee is hereby granted, provided that the above
copyright notice and this permission notice appear in all copies.

"Node.js"
Trademark Joyent, Inc., https://joyent.com
Neither npm nor npm, Inc. are affiliated with Joyent, Inc.

The Node.js application
Project of Node Foundation, https://nodejs.org

The npm Logo
Copyright (c) Mathias Pettersson and Brian Hammond

"Gubblebum Blocky" typeface
Copyright (c) Tjarda Koster, https://jelloween.deviantart.com
Used with permission


--------


The Artistic License 2.0

Copyright (c) 2000-2006, The Perl Foundation.

Everyone is permitted to copy and distribute verbatim copies
of this license document, but changing it is not allowed.

Preamble

This license establishes the terms under which a given free software
Package may be copied, modified, distributed, and/or redistributed.
The intent is that the Copyright Holder maintains some artistic
control over the development of that Package while still keeping the
Package available as open source and free software.

You are always permitted to make arrangements wholly outside of this
license directly with the Copyright Holder of a given Package. If the
terms of this license do not permit the full use that you propose to
make of the Package, you should contact the Copyright Holder and seek
a different licensing arrangement.

Definitions

"Copyright Holder" means the individual(s) or organization(s)
named in the copyright notice for the entire Package.

"Contributor" means any party that has contributed code or other
material to the Package, in accordance with the Copyright Holder's
procedures.

"You" and "your" means any person who would like to copy,
distribute, or modify the Package.

"Package" means the collection of files distributed by the
Copyright Holder, and derivatives of that collection and/or of
those files. A given Package may consist of either the Standard
Version, or a Modified Version.

"Distribute" means providing a copy of the Package or making it
accessible to anyone else, or in the case of a company or
organization, to others outside of your company or organization.

"Distributor Fee" means any fee that you charge for Distributing
this Package or providing support for this Package to another
party. It does not mean licensing fees.

"Standard Version" refers to the Package if it has not been
modified, or has been modified only in ways explicitly requested
by the Copyright Holder.

"Modified Version" means the Package, if it has been changed, and
such changes were not explicitly requested by the Copyright
Holder.

"Original License" means this Artistic License as Distributed with
the Standard Version of the Package, in its current version or as
it may be modified by The Perl Foundation in the future.

"Source" form means the source code, documentation source, and
configuration files for the Package.

"Compiled" form means the compiled bytecode, object code, binary,
or any other form resulting from mechanical transformation or
translation of the Source form.


Permission for Use and Modification Without Distribution

(1) You are permitted to use the Standard Version and create and use
Modified Versions for any purpose without restriction, provided that
you do not Distribute the Modified Version.


Permissions for Redistribution of the Standard Version

(2) You may Distribute verbatim copies of the Source form of the
Standard Version of this Package in any medium without restriction,
either gratis or for a Distributor Fee, provided that you duplicate
all of the original copyright notices and associated disclaimers. At
your discretion, such verbatim copies may or may not include a
Compiled form of the Package.

(3) You may apply any bug fixes, portability changes, and other
modifications made available from the Copyright Holder. The resulting
Package will still be considered the Standard Version, and as such
will be subject to the Original License.


Distribution of Modified Versions of the Package as Source

(4) You may Distribute your Modified Version as Source (either gratis
or for a Distributor Fee, and with or without a Compiled form of the
Modified Version) provided that you clearly document how it differs
from the Standard Version, including, but not limited to, documenting
any non-standard features, executables, or modules, and provided that
you do at least ONE of the following:

(a) make the Modified Version available to the Copyright Holder
of the Standard Version, under the Original License, so that the
Copyright Holder may include your modifications in the Standard
Version.

(b) ensure that installation of your Modified Version does not
prevent the user installing or running the Standard Version. In
addition, the Modified Version must bear a name that is different
from the name of the Standard Version.

(c) allow anyone who receives a copy of the Modified Version to
make the Source form of the Modified Version available to others
under

(i) the Original License or

(ii) a license that permits the licensee to freely copy,
modify and redistribute the Modified Version using the same
licensing terms that apply to the copy that the licensee
received, and requires that the Source form of the Modified
Version, and of any works derived from it, be made freely
available in that license fees are prohibited but Distributor
Fees are allowed.


Distribution of Compiled Forms of the Standard Version
or Modified Versions without the Source

(5) You may Distribute Compiled forms of the Standard Version without
the Source, provided that you include complete instructions on how to
get the Source of the Standard Version. Such instructions must be
valid at the time of your distribution. If these instructions, at any
time while you are carrying out such distribution, become invalid, you
must provide new instructions on demand or cease further distribution.
If you provide valid instructions or cease distribution within thirty
days after you become aware that the instructions are invalid, then
you do not forfeit any of your rights under this license.

(6) You may Distribute a Modified Version in Compiled form without
the Source, provided that you comply with Section 4 with respect to
the Source of the Modified Version.


Aggregating or Linking the Package

(7) You may aggregate the Package (either the Standard Version or
Modified Version) with other packages and Distribute the resulting
aggregation provided that you do not charge a licensing fee for the
Package. Distributor Fees are permitted, and licensing fees for other
components in the aggregation are permitted. The terms of this license
apply to the use and Distribution of the Standard or Modified Versions
as included in the aggregation.

(8) You are permitted to link Modified and Standard Versions with
other works, to embed the Package in a larger work of your own, or to
build stand-alone binary or bytecode versions of applications that
include the Package, and Distribute the result without restriction,
provided the result does not expose a direct interface to the Package.


Items That are Not Considered Part of a Modified Version

(9) Works (including, but not limited to, modules and scripts) that
merely extend or make use of the Package, do not, by themselves, cause
the Package to be a Modified Version. In addition, such works are not
considered parts of the Package itself, and are not subject to the
terms of this license.


General Provisions

(10) Any use, modification, and distribution of the Standard or
Modified Versions is governed by this Artistic License. By using,
modifying or distributing the Package, you accept this license. Do not
use, modify, or distribute the Package, if you do not accept this
license.

(11) If your Modified Version has been derived from a Modified
Version made by someone other than you, you are nevertheless required
to ensure that your Modified Version complies with the requirements of
this license.

(12) This license does not grant you the right to use any trademark,
service mark, tradename, or logo of the Copyright Holder.

(13) This license includes the non-exclusive, worldwide,
free-of-charge patent license to make, have made, use, offer to sell,
sell, import and otherwise transfer the Package with respect to any
patent claims licensable by the Copyright Holder that are necessarily
infringed by the Package. If you institute patent litigation
(including a cross-claim or counterclaim) against any party alleging
that the Package constitutes direct or contributory patent
infringement, then this Artistic License to you shall terminate on the
date that such litigation is filed.

(14) Disclaimer of Warranty:
THE PACKAGE IS PROVIDED BY THE COPYRIGHT HOLDER AND CONTRIBUTORS "AS
IS' AND WITHOUT ANY EXPRESS OR IMPLIED WARRANTIES. THE IMPLIED
WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE, OR
NON-INFRINGEMENT ARE DISCLAIMED TO THE EXTENT PERMITTED BY YOUR LOCAL
LAW. UNLESS REQUIRED BY LAW, NO COPYRIGHT HOLDER OR CONTRIBUTOR WILL
BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, OR CONSEQUENTIAL
DAMAGES ARISING IN ANY WAY OUT OF THE USE OF THE PACKAGE, EVEN IF
ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.


--------
THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES
WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF
MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR
ANY SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES
WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN
ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF OR
IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE.
7 changes: 0 additions & 7 deletions PULL_REQUEST_TEMPLATE

This file was deleted.

35 changes: 27 additions & 8 deletions README.md
Original file line number Diff line number Diff line change
@@ -18,15 +18,32 @@ binaries and man pages for Javascript packages
### Example

```javascript
// todo
const binLinks = require('bin-links')
const readPackageJson = require('read-package-json-fast')
binLinks({
path: '/path/to/node_modules/some-package',
pkg: readPackageJson('/path/to/node_modules/some-package/package.json'),

// true if it's a global install, false for local. default: false
global: true,

// true if it's the top level package being installed, false otherwise
top: true,

// true if you'd like to recklessly overwrite files.
force: true,
})
```

### Features

* Links bin files listed under the `bin` property of pkg to the node_modules/.bin
directory of the installing environment.
* Links man files listed under the `man` property of pkg to the share/man directory
of the provided optional directory prefix.
* Links bin files listed under the `bin` property of pkg to the
`node_modules/.bin` directory of the installing environment. (Or
`${prefix}/bin` for top level global packages on unix, and `${prefix}`
for top level global packages on Windows.)
* Links man files listed under the `man` property of pkg to the share/man
directory. (This is only done for top-level global packages on Unix
systems.)

### Contributing

@@ -38,10 +55,12 @@ jump in if you'd like to, or even ask us questions if something isn't clear.

### API

#### <a name="binLinks"></a> `> binLinks(pkg, folder, global, opts, cb)`
#### <a name="binLinks"></a> `> binLinks({path, pkg, force, global, top})`

Returns a Promise that resolves when the requisite things have been linked.

##### Example

```javascript
binLinks(pkg, folder, global, opts, cb)
```
binLinks({path, pkg, force, global, top}).then(() => console.log('bins linked!'))
```
22 changes: 0 additions & 22 deletions appveyor.yml

This file was deleted.

198 changes: 45 additions & 153 deletions index.js
Original file line number Diff line number Diff line change
@@ -1,153 +1,45 @@
'use strict'

const path = require('path')
const fs = require('graceful-fs')
const BB = require('bluebird')
const linkIfExists = BB.promisify(require('gentle-fs').linkIfExists)
const cmdShimIfExists = BB.promisify(require('cmd-shim').ifExists)
const open = BB.promisify(fs.open)
const close = BB.promisify(fs.close)
const read = BB.promisify(fs.read, {multiArgs: true})
const chmod = BB.promisify(fs.chmod)
const readFile = BB.promisify(fs.readFile)
const writeFileAtomic = BB.promisify(require('write-file-atomic'))

module.exports = BB.promisify(binLinks)

function binLinks (pkg, folder, global, opts, cb) {
// if it's global, and folder is in {prefix}/node_modules,
// then bins are in {prefix}/bin
// otherwise, then bins are in folder/../.bin
var parent = pkg.name && pkg.name[0] === '@' ? path.dirname(path.dirname(folder)) : path.dirname(folder)
var gnm = global && opts.globalDir
var gtop = parent === gnm

opts.log.info('linkStuff', opts.pkgId)
opts.log.silly('linkStuff', opts.pkgId, 'has', parent, 'as its parent node_modules')
if (global) opts.log.silly('linkStuff', opts.pkgId, 'is part of a global install')
if (gnm) opts.log.silly('linkStuff', opts.pkgId, 'is installed into a global node_modules')
if (gtop) opts.log.silly('linkStuff', opts.pkgId, 'is installed into the top-level global node_modules')

return BB.join(
linkBins(pkg, folder, parent, gtop, opts),
linkMans(pkg, folder, parent, gtop, opts)
).asCallback(cb)
}

function isHashbangFile (file) {
return open(file, 'r').then(fileHandle => {
return read(fileHandle, Buffer.alloc(2), 0, 2, 0).spread((_, buf) => {
if (!hasHashbang(buf)) return []
return read(fileHandle, Buffer.alloc(2048), 0, 2048, 0)
}).spread((_, buf) => buf && hasCR(buf), () => false)
.finally(() => close(fileHandle))
}).catch(() => false)
}

function hasHashbang (buf) {
const str = buf.toString()
return str.slice(0, 2) === '#!'
}

function hasCR (buf) {
return /^#![^\n]+\r\n/.test(buf)
}

function dos2Unix (file) {
return readFile(file, 'utf8').then(content => {
return writeFileAtomic(file, content.replace(/^(#![^\n]+)\r\n/, '$1\n'))
})
}

function getLinkOpts (opts, gently) {
return Object.assign({}, opts, { gently: gently })
}

function linkBins (pkg, folder, parent, gtop, opts) {
if (!pkg.bin || (!gtop && path.basename(parent) !== 'node_modules')) {
return
}
var linkOpts = getLinkOpts(opts, gtop && folder)
var execMode = parseInt('0777', 8) & (~opts.umask)
var binRoot = gtop ? opts.globalBin
: path.resolve(parent, '.bin')
opts.log.verbose('linkBins', [pkg.bin, binRoot, gtop])

return BB.map(Object.keys(pkg.bin), bin => {
var dest = path.resolve(binRoot, bin)
var src = path.resolve(folder, pkg.bin[bin])

return linkBin(src, dest, linkOpts).then(() => {
// bins should always be executable.
// XXX skip chmod on windows?
return chmod(src, execMode)
}).then(() => {
return isHashbangFile(src)
}).then(isHashbang => {
if (!isHashbang) return
opts.log.silly('linkBins', 'Converting line endings of hashbang file:', src)
return dos2Unix(src)
}).then(() => {
if (!gtop) return
var dest = path.resolve(binRoot, bin)
var out = opts.parseable
? dest + '::' + src + ':BINFILE'
: dest + ' -> ' + src

if (!opts.json && !opts.parseable) {
opts.log.clearProgress()
console.log(out)
opts.log.showProgress()
}
}).catch(err => {
if (err.code === 'ENOENT' && opts.ignoreScripts) return
throw err
})
})
}

function linkBin (from, to, opts) {
if (process.platform !== 'win32') {
return linkIfExists(from, to, opts)
} else {
return cmdShimIfExists(from, to)
}
}

function linkMans (pkg, folder, parent, gtop, opts) {
if (!pkg.man || !gtop || process.platform === 'win32') return

var manRoot = path.resolve(opts.prefix, 'share', 'man')
opts.log.verbose('linkMans', 'man files are', pkg.man, 'in', manRoot)

// make sure that the mans are unique.
// otherwise, if there are dupes, it'll fail with EEXIST
var set = pkg.man.reduce(function (acc, man) {
acc[path.basename(man)] = man
return acc
}, {})
var manpages = pkg.man.filter(function (man) {
return set[path.basename(man)] === man
})

return BB.map(manpages, man => {
if (typeof man !== 'string') return
opts.log.silly('linkMans', 'preparing to link', man)
var parseMan = man.match(/(.*\.([0-9]+)(\.gz)?)$/)
if (!parseMan) {
throw new Error(
man + ' is not a valid name for a man file. ' +
'Man files must end with a number, ' +
'and optionally a .gz suffix if they are compressed.'
)
}

var stem = parseMan[1]
var sxn = parseMan[2]
var bn = path.basename(stem)
var manSrc = path.resolve(folder, man)
var manDest = path.join(manRoot, 'man' + sxn, bn)

return linkIfExists(manSrc, manDest, getLinkOpts(opts, gtop && folder))
})
}
const {basename, dirname } = require('path')
const isWindows = require('./lib/is-windows.js')

const linkBins = require('./lib/link-bins.js')
const linkMans = require('./lib/link-mans.js')

const binLinks = opts => {
const { path, pkg, force, global, top } = opts
// global top pkgs on windows get bins installed in {prefix}, and no mans
//
// unix global top pkgs get their bins installed in {prefix}/bin,
// and mans in {prefix}/share/man
//
// non-top pkgs get their bins installed in {prefix}/node_modules/.bin,
// and do not install mans
//
// non-global top pkgs don't have any bins or mans linked.
if (top && !global)
return Promise.resolve()

// now we know it's global and/or not top, so the path has to be
// {prefix}/node_modules/{name}. Can't rely on pkg.name, because
// it might be installed as an alias.
const scopeOrNm = dirname(path)
const nm = basename(scopeOrNm) === 'node_modules' ? scopeOrNm
: dirname(scopeOrNm)
const prefix = dirname(nm)

const binTarget = !top ? nm + '/.bin'
: isWindows ? prefix
: dirname(prefix) + '/bin'

const manTarget = !top || isWindows ? null
: dirname(prefix) + '/share/man'

return Promise.all([
// allow clobbering within the local node_modules/.bin folder.
// only global bins are protected in this way, or else it is
// yet another vector for excessive dependency conflicts.
linkBins({path, binTarget, pkg, force: force || !top}),
linkMans({path, manTarget, pkg, force}),
])
}

module.exports = binLinks
44 changes: 44 additions & 0 deletions lib/fix-bin.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,44 @@
// make sure that bins are executable, and that they don't have
// windows line-endings on the hashbang line.
const fs = require('fs')
const { promisify } = require('util')

const execMode = 0o777 & (~process.umask())

const writeFileAtomic = promisify(require('write-file-atomic'))
const open = promisify(fs.open)
const close = promisify(fs.close)
const read = promisify(fs.read)
const chmod = promisify(fs.chmod)
const readFile = promisify(fs.readFile)

const isWindowsHashBang = buf =>
buf[0] === '#'.charCodeAt(0) &&
buf[1] === '!'.charCodeAt(0) &&
/^#![^\n]+\r\n/.test(buf.toString())

const isWindowsHashbangFile = file => {
const FALSE = () => false
return open(file, 'r').then(fd => {
const buf = Buffer.alloc(2048)
return read(fd, buf, 0, 2048, 0)
.then(
() => {
const isWHB = isWindowsHashBang(buf)
return close(fd).then(() => isWHB, () => isWHB)
},
// don't leak FD if read() fails
() => close(fd).then(FALSE, FALSE)
)
}, FALSE)
}

const dos2Unix = file =>
readFile(file, 'utf8').then(content =>
writeFileAtomic(file, content.replace(/^(#![^\n]+)\r\n/, '$1\n')))

const fixBin = file => chmod(file, execMode)
.then(() => isWindowsHashbangFile(file))
.then(isWHB => isWHB ? dos2Unix(file) : null)

module.exports = fixBin
2 changes: 2 additions & 0 deletions lib/is-windows.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,2 @@
const platform = process.env.__TESTING_BIN_LINKS_PLATFORM__ || process.platform
module.exports = platform === 'win32'
9 changes: 9 additions & 0 deletions lib/link-bin.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,9 @@
const linkGently = require('./link-gently.js')
const fixBin = require('./fix-bin.js')

// linking bins is simple. just symlink, and if we linked it, fix the bin up
const linkBin = ({path, to, from, absFrom, force}) =>
linkGently({path, to, from, absFrom, force})
.then(linked => linked && fixBin(absFrom))

module.exports = linkBin
20 changes: 20 additions & 0 deletions lib/link-bins.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,20 @@
const isWindows = require('./is-windows.js')
const { dirname, resolve, relative } = require('path')
const linkBin = isWindows ? require('./shim-bin.js') : require('./link-bin.js')
const normalize = require('npm-normalize-package-bin')

const linkBins = ({path, binTarget, pkg, force}) => {
pkg = normalize(pkg)
if (!pkg.bin)
return Promise.resolve([])
const promises = []
for (const [key, val] of Object.entries(pkg.bin)) {
const to = resolve(binTarget, key)
const absFrom = resolve(path, val)
const from = relative(dirname(to), absFrom)
promises.push(linkBin({path, from, to, absFrom, force}))
}
return Promise.all(promises)
}

module.exports = linkBins
57 changes: 57 additions & 0 deletions lib/link-gently.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,57 @@
// if the thing isn't there, skip it
// if there's a non-symlink there already, eexist
// if there's a symlink already, pointing somewhere else, eexist
// if there's a symlink already, pointing into our pkg, remove it first
// then create the symlink

const { promisify } = require('util')
const { resolve, dirname } = require('path')
const mkdirp = require('mkdirp-infer-owner')
const fs = require('fs')
const symlink = promisify(fs.symlink)
const readlink = promisify(fs.readlink)
const lstat = promisify(fs.lstat)
const throwNonEnoent = er => { if (er.code !== 'ENOENT') throw er }

// disable glob in our rimraf calls
const rimraf = promisify(require('rimraf'))
const rm = path => rimraf(path, { glob: false })

const SKIP = Symbol('skip - missing or already installed')

const linkGently = ({path, to, from, absFrom, force}) => {
// if the script or manpage isn't there, just ignore it.
// this arguably *should* be an install error of some sort,
// or at least a warning, but npm has always behaved this
// way in the past, so it'd be a breaking change
return Promise.all([
lstat(absFrom).catch(throwNonEnoent),
lstat(to).catch(throwNonEnoent),
]).then(([stFrom, stTo]) => {
// not present in package, skip it
if (!stFrom)
return SKIP

// exists! maybe clobber if we can
if (stTo) {
if (!stTo.isSymbolicLink())
return force ? rm(to) : Promise.resolve()

return readlink(to).then(target => {
if (target === from)
return SKIP // skip it, already set up like we want it.

target = resolve(dirname(to), target)
if (target.indexOf(path) === 0 || force)
return rm(to)
})
} else {
// doesn't exist, dir might not either
return mkdirp(dirname(to))
}
})
// this will fail if we didn't remove it
.then(skip => skip !== SKIP && symlink(from, to, 'file').then(() => true))
}

module.exports = linkGently
47 changes: 47 additions & 0 deletions lib/link-mans.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,47 @@
const { dirname, relative, join, resolve, basename } = require('path')
const linkGently = require('./link-gently.js')
const linkMans = ({path, manTarget, pkg, force}) => {
if (!manTarget || !pkg.man || !Array.isArray(pkg.man))
return Promise.resolve([])

// break any links to c:\\blah or /foo/blah or ../blah
// and filter out duplicates
const set = [...new Set(pkg.man.map(man =>
man ? join('/', man).replace(/\\|:/g, '/').substr(1) : null)
.filter(man => typeof man === 'string'))]

return Promise.all(set.map(man => {
const parseMan = man.match(/(.*\.([0-9]+)(\.gz)?)$/)
if (!parseMan) {
return Promise.reject(Object.assign(new Error('invalid man entry name\n' +
'Man files must end with a number, ' +
'and optionally a .gz suffix if they are compressed.'
), {
code: 'EBADMAN',
path,
pkgid: pkg._id,
man,
}))
}
const stem = parseMan[1]
const sxn = parseMan[2]
const base = basename(stem)
const absFrom = resolve(path, man)
/* istanbul ignore if - that unpossible */
if (absFrom.indexOf(path) !== 0) {
return Promise.reject(Object.assign(new Error('invalid man entry'), {
code: 'EBADMAN',
path,
pkgid: pkg._id,
man,
}))
}

const to = resolve(manTarget, 'man' + sxn, base)
const from = relative(dirname(to), absFrom)

return linkGently({from, to, path, absFrom, force})
}))
}

module.exports = linkMans
64 changes: 64 additions & 0 deletions lib/shim-bin.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,64 @@
const { promisify } = require('util')
const { resolve, dirname } = require('path')
const fs = require('fs')
const lstat = promisify(fs.lstat)
const throwNonEnoent = er => { if (er.code !== 'ENOENT') throw er }

const cmdShim = require('cmd-shim')
const readCmdShim = require('read-cmd-shim')

const fixBin = require('./fix-bin.js')

const failEEXIST = ({path, to, from}) =>
Promise.reject(Object.assign(new Error('EEXIST: file already exists'), {
path: to,
dest: from,
code: 'EEXIST',
}))

const handleReadCmdShimError = ({er, from, to}) =>
er.code === 'ENOENT' ? null
: er.code === 'ENOTASHIM' ? failEEXIST({from, to})
: Promise.reject(er)

const SKIP = Symbol('skip - missing or already installed')
const shimBin = ({path, to, from, absFrom, force}) => {
const shims = [
to,
to + '.cmd',
to + '.ps1',
]
return Promise.all([
...shims,
absFrom,
].map(f => lstat(f).catch(throwNonEnoent))).then((stats) => {
const [
stToBase,
stToCmd,
stToPs1,
stFrom,
] = stats
if (!stFrom)
return SKIP

if (force)
return

return Promise.all(shims.map((s, i) => [s, stats[i]]).map(([s, st]) => {
if (!st)
return
return readCmdShim(s)
.then(target => {
target = resolve(dirname(to), target)
if (target.indexOf(resolve(path)) !== 0)
return failEEXIST({from, to, path})
}, er => handleReadCmdShimError({er, from, to}))
}))
})
.then(skip => skip !== SKIP && doShim(absFrom, to))
}

const doShim = (absFrom, to) =>
cmdShim(absFrom, to).then(() => fixBin(absFrom))

module.exports = shimBin
3 changes: 3 additions & 0 deletions map.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,3 @@
const {basename} = require('path')
const map = base => base === 'index.js' ? 'index.js' : `lib/${base}`
module.exports = test => map(basename(test))
6,635 changes: 2,356 additions & 4,279 deletions package-lock.json

Large diffs are not rendered by default.

56 changes: 26 additions & 30 deletions package.json
Original file line number Diff line number Diff line change
@@ -1,50 +1,46 @@
{
"name": "bin-links",
"version": "1.1.2",
"version": "2.0.0",
"description": "JavaScript package binary linker",
"main": "index.js",
"scripts": {
"prerelease": "npm t",
"postrelease": "npm publish && git push --follow-tags",
"pretest": "standard",
"release": "standard-version -s",
"test": "tap -J --nyc-arg=--all --coverage test/*.js",
"update-coc": "weallbehave -o . && git add CODE_OF_CONDUCT.md && git commit -m 'docs(coc): updated CODE_OF_CONDUCT.md'",
"update-contrib": "weallcontribute -o . && git add CONTRIBUTING.md && git commit -m 'docs(contributing): updated CONTRIBUTING.md'"
"preversion": "npm t",
"postversion": "npm publish",
"prepublishOnly": "git push --follow-tags",
"snap": "tap",
"test": "tap"
},
"repository": {
"type": "git",
"url": "git://github.com/npm/bin-links.git"
},
"keywords": [
"npm",
"gentle",
"fs"
"link",
"bins"
],
"author": "Mike Sherov",
"license": "Artistic-2.0",
"bugs": {
"url": "https://github.com/npm/bin-links/issues"
},
"homepage": "https://github.com/npm/bin-links#readme",
"license": "ISC",
"dependencies": {
"bluebird": "^3.5.0",
"cmd-shim": "^2.0.2",
"gentle-fs": "^2.0.0",
"graceful-fs": "^4.1.11",
"cmd-shim": "^4.0.1",
"mkdirp": "^1.0.3",
"npm-normalize-package-bin": "^1.0.0",
"read-cmd-shim": "^2.0.0",
"rimraf": "^3.0.0",
"write-file-atomic": "^2.3.0"
},
"devDependencies": {
"mkdirp": "^0.5.1",
"nyc": "^11.1.0",
"rimraf": "^2.6.2",
"standard": "^10.0.3",
"standard-version": "^4.2.0",
"tap": "^10.7.2",
"weallbehave": "^1.2.0",
"weallcontribute": "^1.0.8"
"require-inject": "^1.4.4",
"tap": "^14.10.6"
},
"tap": {
"check-coverage": true,
"coverage-map": "map.js"
},
"files": [
"index.js"
]
"index.js",
"lib"
],
"engines": {
"node": ">=10"
}
}
542 changes: 542 additions & 0 deletions tap-snapshots/test-index.js-TAP.test.js

Large diffs are not rendered by default.

76 changes: 76 additions & 0 deletions test/fix-bin.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,76 @@
const t = require('tap')
const requireInject = require('require-inject')
const fixBin = require('../lib/fix-bin.js')
const umask = process.umask()
const fs = require('fs')
const {readFileSync, statSync, chmodSync} = fs

t.test('fix windows hashbang', t => {
const dir = t.testdir({
whb: `#!/usr/bin/env node\r\nconsole.log('hello')\r\n`,
})
chmodSync(`${dir}/whb`, 0o644)
return fixBin(`${dir}/whb`).then(() => {
t.equal((statSync(`${dir}/whb`).mode & 0o777), 0o777 & (~umask), 'has exec perms')
t.equal(readFileSync(`${dir}/whb`, 'utf8'),
`#!/usr/bin/env node\nconsole.log('hello')\r\n`, 'fixed \\r on hashbang line')
})
})

t.test('dont fix non-windows hashbang file', t => {
const dir = t.testdir({
goodhb: `#!/usr/bin/env node\nconsole.log('hello')\r\n`,
})
chmodSync(`${dir}/goodhb`, 0o644)
return fixBin(`${dir}/goodhb`).then(() => {
t.equal((statSync(`${dir}/goodhb`).mode & 0o777), 0o777 & (~umask), 'has exec perms')
t.equal(readFileSync(`${dir}/goodhb`, 'utf8'),
`#!/usr/bin/env node\nconsole.log('hello')\r\n`, 'fixed \\r on hashbang line')
})
})

t.test('failure to read means not a windows hash bang file', t => {
const fsMock = {
...fs,
read: (a, b, c, d, e, cb) => {
fsMock.read = read
process.nextTick(() => cb(new Error('witaf')))
}
}
const fixBin = requireInject('../lib/fix-bin.js', {
fs: fsMock,
})

const dir = t.testdir({
whb: `#!/usr/bin/env node\r\nconsole.log('hello')\r\n`,
})
chmodSync(`${dir}/whb`, 0o644)
return fixBin(`${dir}/whb`).then(() => {
t.equal((statSync(`${dir}/whb`).mode & 0o777), 0o777 & (~umask), 'has exec perms')
t.equal(readFileSync(`${dir}/whb`, 'utf8'),
`#!/usr/bin/env node\r\nconsole.log('hello')\r\n`, 'did not fix \\r on hashbang line (failed read)')
})
})

t.test('failure to close is ignored', t => {
const fsMock = {
...fs,
close: (fd, cb) => {
fsMock.close = fs.close
process.nextTick(() => cb(new Error('witaf')))
}
}
const fixBin = requireInject('../lib/fix-bin.js', {
fs: fsMock,
})

const dir = t.testdir({
whb: `#!/usr/bin/env node\r\nconsole.log('hello')\r\n`,
})
chmodSync(`${dir}/whb`, 0o644)
return fixBin(`${dir}/whb`).then(() => {
t.equal((statSync(`${dir}/whb`).mode & 0o777), 0o777 & (~umask), 'has exec perms')
t.equal(readFileSync(`${dir}/whb`, 'utf8'),
`#!/usr/bin/env node\nconsole.log('hello')\r\n`, 'fixed \\r on hashbang line (ignored failed close)')
})
})
165 changes: 68 additions & 97 deletions test/index.js
Original file line number Diff line number Diff line change
@@ -1,106 +1,77 @@
const fs = require('graceful-fs')
const path = require('path')
const existsSync = fs.existsSync || path.existsSync
const t = require('tap')
const requireInject = require('require-inject')

const mkdirp = require('mkdirp')
const rimraf = require('rimraf')
const test = require('tap').test

const binLinks = require('../index.js')

const log = {
clearProgress () {},
info () {},
showProgress () {},
silly () {},
verbose () {}
}
const mockLinkBins = opt => opt
const mockLinkMans = opt => opt.manTarget ? opt : null

// root unit test. go through each combination and snapshot them all.
// the index just sets up paths and calls the appropriate functions,
// so this is enough to test that functionality.
const pkg = {
name: 'cli-dependency',
description: 'fixture',
version: '0.0.0',
bin: {
hashbang: './hashbang.js',
nohashbang: './nohashbang.js',
'hashbang-nocr': './hashbang-nocr.js'
}
foo: 'bar',
},
man: ['foo.1.gz'],
}
for (const isWindows of [true, false]) {
t.test(isWindows ? 'win32' : 'posix', t => {
t.plan(2)
for (const global of [true, false]) {
t.test(global ? 'global' : 'local', t => {
t.plan(2)
for (const top of [true, false]) {
t.test(top ? 'top' : 'nested', t => {
t.plan(2)
for (const force of [true, false]) {
t.test(`force=${force}`, t => {
const path = require('path')[isWindows ? 'win32' : 'posix']
const { resolve } = path
const prefix = isWindows ? (
global ? (
top ? 'c:\\path\\to\\prefix\\node_modules\\'
: 'c:\\path\\to\\prefix\\node_modules\\xyz\\node_modules\\'
) : (
top ? 'c:\\path\\to\\'
: 'c:\\path\\to\\project\\node_modules\\'
)
) : (
global ? (
top ? '/usr/local/lib/node_modules/'
: '/usr/local/lib/node_modules/xyz/node_modules/'
) : (
top ? '/path/to/'
: '/path/to/project/node_modules/'
)
)

const folder = path.join(__dirname, '..', 'fixtures', 'convert-windows-newlines')
const nodeModulesFolder = path.join(folder, 'node_modules')
const pkgFolder = path.join(nodeModulesFolder, pkg.name)

test('converts windows newlines correctly', function (t) {
cleanup()
mkdirp.sync(pkgFolder)

fs.writeFileSync(
path.join(pkgFolder, 'hashbang.js'),
'#!/usr/bin/env node\r\nconsole.log(\'Hello, world!\')\r\n'
)
fs.writeFileSync(
path.join(pkgFolder, 'hashbang-nocr.js'),
'#!/usr/bin/env node\nconsole.log(\'Hello, world!\')\r\n'
)
fs.writeFileSync(
path.join(pkgFolder, 'nohashbang.js'),
'\'use strict\'\r\nconsole.log(\'Goodbye, world!\')\r\n'
)
const binLinks = requireInject('../', {
path,
'../lib/is-windows.js': isWindows,
'../lib/link-bins.js': mockLinkBins,
'../lib/link-mans.js': mockLinkMans,
})

const defaultOpts = {
log: log,
pkgId: 'pkgId',
umask: 0,
prefixes: [nodeModulesFolder]
}

return binLinks(pkg, pkgFolder, false, defaultOpts).then(() => {
t.ok(
existsSync(path.resolve(folder, 'node_modules/.bin/hashbang')),
'hashbang installed'
)
t.ok(
existsSync(path.resolve(folder, 'node_modules/.bin/hashbang-nocr')),
'hashbang installed'
)
t.ok(
existsSync(path.resolve(folder, 'node_modules/.bin/nohashbang')),
'nohashbang installed'
)
const content = fs.readFileSync(
path.resolve(folder, 'node_modules/cli-dependency/hashbang.js'),
'utf8'
)
t.notLike(content, /^#![^\n]+\r\n/,
'hashbang dependency cli shebang newlines converted'
)
t.like(content, /\r\n/,
'hashbang dependency cli non-shebang newlines retained'
)

t.like(
fs.readFileSync(
path.resolve(folder, 'node_modules/cli-dependency/hashbang-nocr.js'),
'utf8'
), /\r\n/,
'hashbang-nocr dependency cli newlines retained'
)
t.like(
fs.readFileSync(
path.resolve(folder, 'node_modules/cli-dependency/nohashbang.js'),
'utf8'
), /\r\n/,
'nohashbang dependency cli newlines retained'
)
return Promise.all([
t.resolveMatchSnapshot(binLinks({
path: prefix + 'foo',
pkg,
force,
global,
top,
}), 'unscoped pkg'),
t.resolveMatchSnapshot(binLinks({
path: prefix + '@foo/bar',
pkg,
force,
global,
top,
}), 'scoped pkg')
])
})
}
})
}
})
}
})
})

test('cleanup', function (t) {
cleanup()
t.end()
})

function cleanup () {
rimraf.sync(folder)
}
12 changes: 12 additions & 0 deletions test/is-windows.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,12 @@
const t = require('tap')
const isWindows = require('../lib/is-windows.js')
if (!process.env.__TESTING_BIN_LINKS_PLATFORM__) {
t.spawn(process.execPath, [__filename], {
env: {
...process.env,
__TESTING_BIN_LINKS_PLATFORM__: isWindows ? 'posix' : 'win32',
},
})
}
const platform = process.env.__TESTING_BIN_LINKS_PLATFORM__ || process.platform
t.equal(isWindows, platform === 'win32')
13 changes: 13 additions & 0 deletions test/link-bin.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,13 @@
const requireInject = require('require-inject')
const t = require('tap')
const linkBin = requireInject('../lib/link-bin.js', {
// only link if forced, in this mock
'../lib/link-gently.js': ({force}) => Promise.resolve(force),
'../lib/fix-bin.js': absFrom => Promise.resolve(absFrom),
})

t.test('if not linked, dont fix bin', t =>
linkBin({absFrom:'/some/path', force: false}).then(f => t.equal(f, false)))

t.test('if linked, fix bin', t =>
linkBin({absFrom:'/some/path', force: true}).then(f => t.equal(f, '/some/path')))
41 changes: 41 additions & 0 deletions test/link-bins.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,41 @@
const requireInject = require('require-inject')
const t = require('tap')
const isWindows = require('../lib/is-windows.js')

if (!process.env.__TESTING_BIN_LINKS_PLATFORM__) {
const otherPlatform = isWindows ? 'posix' : 'win32'
t.spawn(process.execPath, [__filename], {
env: {
...process.env,
__TESTING_BIN_LINKS_PLATFORM__: otherPlatform,
},
}, otherPlatform)
}

const linkBins = requireInject('../lib/link-bins.js', {
// only link if forced, in this mock
'../lib/link-bin.js': ({from, to}) => Promise.resolve(`LINK ${from} ${to}`),
'../lib/shim-bin.js': ({from, to}) => Promise.resolve(`SHIM ${from} ${to}`),
path: require('path')[isWindows ? 'win32' : 'posix'],
})

const pkg = {
name: 'foo',
bin: 'foo.js',
}
const {resolve} = require('path')[isWindows ? 'win32' : 'posix']

t.test('link bins', t => linkBins({
path: resolve('/path/to/node_modules/foo'),
binTarget: resolve('/path/to/bin'),
pkg,
}).then(linked => t.strictSame(linked, [
isWindows ? 'SHIM ..\\node_modules\\foo\\foo.js \\path\\to\\bin\\foo'
: 'LINK ../node_modules/foo/foo.js /path/to/bin/foo'
])))

t.test('no bins to link', t => linkBins({
path: resolve('/path/to/node_modules/foo'),
binTarget: resolve('/path/to/bin'),
pkg: { name: 'foo' },
}).then(linked => t.strictSame(linked, [])))
76 changes: 76 additions & 0 deletions test/link-gently.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,76 @@
const t = require('tap')
const requireInject = require('require-inject')
const fs = require('fs')

t.test('make links gently', t => {
const dir = t.testdir({
pkg: {
'hello.js': `#!/usr/bin/env node\nconsole.log('hello')`,
},
otherpkg: {
'hello.js': `#!/usr/bin/env node\nconsole.log('other hello')`,
},
existingLink: t.fixture('symlink', './pkg/hello.js'),
existingFile: 'hello',
})

const linkGently = requireInject('../lib/link-gently.js', {})
return linkGently({
path: `${dir}/pkg`,
to: `${dir}/bin/hello`,
from: `../pkg/hello.js`,
absFrom: `${dir}/pkg/hello.js`,
}).then(() =>
t.equal(fs.readlinkSync(`${dir}/bin/hello`), '../pkg/hello.js'))
// call it again to test the 'SKIP' code path
.then(() => linkGently({
path: `${dir}/pkg`,
to: `${dir}/bin/hello`,
from: `../pkg/hello.js`,
absFrom: `${dir}/pkg/hello.js`,
}))
.then(() => t.rejects(linkGently({
path: `${dir}/otherpkg`,
to: `${dir}/bin/hello`,
from: `../otherpkg/hello.js`,
absFrom: `${dir}/otherpkg/hello.js`,
}), { code: 'EEXIST' }))
.then(() => linkGently({
path: `${dir}/otherpkg`,
to: `${dir}/bin/hello`,
from: `../otherpkg/hello.js`,
absFrom: `${dir}/otherpkg/hello.js`,
force: true,
}))
.then(() =>
t.equal(fs.readlinkSync(`${dir}/bin/hello`), '../otherpkg/hello.js'))
.then(() => t.rejects(linkGently({
path: `${dir}/pkg`,
to: `${dir}/existingFile/notadir`,
from: `../pkg/hello.js`,
absFrom: `${dir}/pkg/hello.js`,
}), { code: 'ENOTDIR' }))
.then(() => t.rejects(linkGently({
path: `${dir}/pkg`,
to: `${dir}/existingFile`,
from: `./pkg/hello.js`,
absFrom: `${dir}/pkg/hello.js`,
}), { code: 'EEXIST' }))
.then(() => linkGently({
path: `${dir}/pkg`,
to: `${dir}/existingFile`,
from: `./pkg/hello.js`,
absFrom: `${dir}/pkg/hello.js`,
force: true,
}))
.then(() =>
t.equal(fs.readlinkSync(`${dir}/existingFile`), './pkg/hello.js'))
.then(() => linkGently({
path: `${dir}/pkg`,
to: `${dir}/bin/missing`,
from: `../pkg/missing.js`,
absFrom: `${dir}/pkg/missing.js`,
}))
.then(() =>
t.throws(() => fs.readlinkSync(`${dir}/bin/missing`), { code: 'ENOENT' }))
})
61 changes: 61 additions & 0 deletions test/link-mans.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,61 @@
const t = require('tap')

const requireInject = require('require-inject')
const linkMans = requireInject('../lib/link-mans.js', {
'../lib/link-gently.js': ({from, to}) => Promise.resolve(`LINK ${from} ${to}`),
})

t.test('no manTarget', t => linkMans({
pkg: { man: ['foo.1'] },
manTarget: null,
path: '/usr/local/lib/node_modules/pkg',
}).then(res => t.strictSame(res, [])))

t.test('man not an array', t => linkMans({
pkg: { man: 'not an array' },
manTarget: '/usr/local/share/man',
path: '/usr/local/lib/node_modules/pkg',
}).then(res => t.strictSame(res, [])))

t.test('no man', t => linkMans({
pkg: {},
manTarget: '/usr/local/share/man',
path: '/usr/local/lib/node_modules/pkg',
}).then(res => t.strictSame(res, [])))

t.test('link some mans', t => linkMans({
pkg: {
man: [
'foo.1',
null,
'docs/foo.1',
'foo.1.gz',
'/path/to/etc/passwd.1',
'c:\\path\\to\\passwd.2',
],
},
manTarget: '/usr/local/share/man',
path: '/usr/local/lib/node_modules/pkg',
}).then(res => t.strictSame(res.sort((a,b)=>a.localeCompare(b)), [
'LINK ../../../lib/node_modules/pkg/c/path/to/passwd.2 /usr/local/share/man/man2/passwd.2',
'LINK ../../../lib/node_modules/pkg/docs/foo.1 /usr/local/share/man/man1/foo.1',
'LINK ../../../lib/node_modules/pkg/foo.1 /usr/local/share/man/man1/foo.1',
'LINK ../../../lib/node_modules/pkg/foo.1.gz /usr/local/share/man/man1/foo.1.gz',
'LINK ../../../lib/node_modules/pkg/path/to/etc/passwd.1 /usr/local/share/man/man1/passwd.1',
])))

t.test('bad man', t => t.rejects(linkMans({
pkg: {
_id: 'foo@1.2.3',
name: 'foo',
version: '1.2.3',
man: [
'foo.readme',
null,
'docs/foo.1',
'foo.1.gz',
],
},
manTarget: '/usr/local/share/man',
path: '/usr/local/lib/node_modules/pkg',
}), { code: 'EBADMAN' }))
162 changes: 162 additions & 0 deletions test/shim-bin.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,162 @@
const t = require('tap')
const requireInject = require('require-inject')
const fs = require('fs')
const {statSync} = fs
const path = require('path').win32
const mkdirp = require('mkdirp')

t.test('basic shim bin', t => {
const dir = t.testdir({
pkg: {
'hello.js': `#!/usr/bin/env node\r\nconsole.log('hello')`,
},
otherpkg: {
'hello.js': `#!/usr/bin/env node\r\nconsole.log('hello')`,
},
notashim: 'definitely not',
})
const shimBin = requireInject('../lib/shim-bin.js', { path, mkdirp })
return shimBin({
path: `${dir}/pkg`,
to: `${dir}/bin/hello`,
from: `../pkg/hello.js`,
absFrom: `${dir}/pkg/hello.js`,
}).then(() => {
const shims = ['hello', 'hello.cmd', 'hello.ps1'].map(f => `${dir}/bin/${f}`)
for (const shim of shims) {
t.equal(statSync(shim).mode & 0o100, 0o100, 'exists and executable')
}
})
.then(() => t.rejects(shimBin({
path: `${dir}/otherpkg`,
to: `${dir}/bin/hello`,
from: `../otherpkg/hello.js`,
absFrom: `${dir}/otherpkg/hello.js`,
}), { code: 'EEXIST' }))
.then(() => t.rejects(shimBin({
path: `${dir}/otherpkg`,
to: `${dir}/notashim`,
from: `./otherpkg/hello.js`,
absFrom: `${dir}/otherpkg/hello.js`,
}), { code: 'EEXIST' }))
.then(() => shimBin({
path: `${dir}/otherpkg`,
to: `${dir}/notashim`,
from: `./otherpkg/hello.js`,
absFrom: `${dir}/otherpkg/hello.js`,
force: true
}))
.then(() => statSync(`${dir}/notashim.cmd`))
.then(() => shimBin({
path: `${dir}/pkg`,
to: `${dir}/bin/hello`,
from: `../pkg/hello.js`,
absFrom: `${dir}/pkg/hello.js`,
}))
.then(() => shimBin({
path: `${dir}/pkg`,
to: `${dir}/bin/missing`,
from: `../pkg/missing.js`,
absFrom: `${dir}/pkg/missing.js`,
})).then(() => t.throws(() => statSync(`${dir}/bin/missing.cmd`)))
})

t.test('eperm on stat', t => {
const dir = t.testdir({
pkg: {
'hello.js': `#!/usr/bin/env node\r\nconsole.log('hello')`,
},
otherpkg: {
'hello.js': `#!/usr/bin/env node\r\nconsole.log('hello')`,
},
notashim: 'definitely not',
})
const shimBin = requireInject('../lib/shim-bin.js', {
path,
mkdirp,
fs: {
...fs,
lstat: (path, cb) => cb(Object.assign(new Error('wakawaka'), {
code: 'EPERM',
})),
},
})
return t.rejects(shimBin({
path: `${dir}/pkg`,
to: `${dir}/bin/hello`,
from: `../pkg/hello.js`,
absFrom: `${dir}/pkg/hello.js`,
}), { code: 'EPERM' })
})

t.test('strange enoent from read-cmd-shim', t => {
const dir = t.testdir({
pkg: {
'hello.js': `#!/usr/bin/env node\r\nconsole.log('hello')`,
},
otherpkg: {
'hello.js': `#!/usr/bin/env node\r\nconsole.log('hello')`,
},
notashim: 'definitely not',
})
const shimBin = requireInject('../lib/shim-bin.js', {
path,
mkdirp,
'read-cmd-shim': path => Promise.reject(Object.assign(new Error('xyz'), {
code: 'ENOENT',
}))
})
return shimBin({
path: `${dir}/pkg`,
to: `${dir}/bin/hello`,
from: `../pkg/hello.js`,
absFrom: `${dir}/pkg/hello.js`,
}).then(() => {
const shims = ['hello', 'hello.cmd', 'hello.ps1'].map(f => `${dir}/bin/${f}`)
for (const shim of shims) {
t.equal(statSync(shim).mode & 0o100, 0o100, 'exists and executable')
}
})
.then(() => shimBin({
path: `${dir}/pkg`,
to: `${dir}/bin/hello`,
from: `../pkg/hello.js`,
absFrom: `${dir}/pkg/hello.js`,
}))
})

t.test('unknown error from read-cmd-shim', t => {
const dir = t.testdir({
pkg: {
'hello.js': `#!/usr/bin/env node\r\nconsole.log('hello')`,
},
otherpkg: {
'hello.js': `#!/usr/bin/env node\r\nconsole.log('hello')`,
},
notashim: 'definitely not',
})
const shimBin = requireInject('../lib/shim-bin.js', {
path,
mkdirp,
'read-cmd-shim': path => Promise.reject(Object.assign(new Error('xyz'), {
code: 'ELDERGAWDS',
}))
})
return shimBin({
path: `${dir}/pkg`,
to: `${dir}/bin/hello`,
from: `../pkg/hello.js`,
absFrom: `${dir}/pkg/hello.js`,
}).then(() => {
const shims = ['hello', 'hello.cmd', 'hello.ps1'].map(f => `${dir}/bin/${f}`)
for (const shim of shims) {
t.equal(statSync(shim).mode & 0o100, 0o100, 'exists and executable')
}
})
.then(() => t.rejects(shimBin({
path: `${dir}/pkg`,
to: `${dir}/bin/hello`,
from: `../pkg/hello.js`,
absFrom: `${dir}/pkg/hello.js`,
}), { code: 'ELDERGAWDS' }))
})