summaryrefslogtreecommitdiff
path: root/deps/npm/node_modules/pacote/tarball.js
blob: e0ad52ab3e4311e9fcf6fca2ab382c62837ec9eb (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
'use strict'

const BB = require('bluebird')

const fs = require('fs')
const getStream = require('get-stream')
const mkdirp = BB.promisify(require('mkdirp'))
const npa = require('npm-package-arg')
const optCheck = require('./lib/util/opt-check.js')
const PassThrough = require('stream').PassThrough
const path = require('path')
const rimraf = BB.promisify(require('rimraf'))
const withTarballStream = require('./lib/with-tarball-stream.js')

module.exports = tarball
function tarball (spec, opts) {
  opts = optCheck(opts)
  spec = npa(spec, opts.where)
  return withTarballStream(spec, opts, stream => getStream.buffer(stream))
}

module.exports.stream = tarballStream
function tarballStream (spec, opts) {
  opts = optCheck(opts)
  spec = npa(spec, opts.where)
  const output = new PassThrough()
  let hasTouchedOutput = false
  let lastError = null
  withTarballStream(spec, opts, stream => {
    if (hasTouchedOutput && lastError) {
      throw lastError
    } else if (hasTouchedOutput) {
      throw new Error('abort, abort!')
    } else {
      return new BB((resolve, reject) => {
        stream.on('error', reject)
        output.on('error', reject)
        output.on('error', () => { hasTouchedOutput = true })
        output.on('finish', resolve)
        stream.pipe(output)
        stream.once('data', () => { hasTouchedOutput = true })
      }).catch(err => {
        lastError = err
        throw err
      })
    }
  })
    .catch(err => output.emit('error', err))
  return output
}

module.exports.toFile = tarballToFile
function tarballToFile (spec, dest, opts) {
  opts = optCheck(opts)
  spec = npa(spec, opts.where)
  return mkdirp(path.dirname(dest))
    .then(() => withTarballStream(spec, opts, stream => {
      return rimraf(dest)
        .then(() => new BB((resolve, reject) => {
          const writer = fs.createWriteStream(dest)
          stream.on('error', reject)
          writer.on('error', reject)
          writer.on('close', resolve)
          stream.pipe(writer)
        }))
    }))
}