Initial commit
[yaffs-website] / node_modules / tar / lib / extract.js
1 // give it a tarball and a path, and it'll dump the contents
2
3 module.exports = Extract
4
5 var tar = require("../tar.js")
6   , fstream = require("fstream")
7   , inherits = require("inherits")
8   , path = require("path")
9
10 function Extract (opts) {
11   if (!(this instanceof Extract)) return new Extract(opts)
12   tar.Parse.apply(this)
13
14   if (typeof opts !== "object") {
15     opts = { path: opts }
16   }
17
18   // better to drop in cwd? seems more standard.
19   opts.path = opts.path || path.resolve("node-tar-extract")
20   opts.type = "Directory"
21   opts.Directory = true
22
23   // similar to --strip or --strip-components
24   opts.strip = +opts.strip
25   if (!opts.strip || opts.strip <= 0) opts.strip = 0
26
27   this._fst = fstream.Writer(opts)
28
29   this.pause()
30   var me = this
31
32   // Hardlinks in tarballs are relative to the root
33   // of the tarball.  So, they need to be resolved against
34   // the target directory in order to be created properly.
35   me.on("entry", function (entry) {
36     // if there's a "strip" argument, then strip off that many
37     // path components.
38     if (opts.strip) {
39       var p = entry.path.split("/").slice(opts.strip).join("/")
40       entry.path = entry.props.path = p
41       if (entry.linkpath) {
42         var lp = entry.linkpath.split("/").slice(opts.strip).join("/")
43         entry.linkpath = entry.props.linkpath = lp
44       }
45     }
46     if (entry.type === "Link") {
47       entry.linkpath = entry.props.linkpath =
48         path.join(opts.path, path.join("/", entry.props.linkpath))
49     }
50
51     if (entry.type === "SymbolicLink") {
52       var dn = path.dirname(entry.path) || ""
53       var linkpath = entry.props.linkpath
54       var target = path.resolve(opts.path, dn, linkpath)
55       if (target.indexOf(opts.path) !== 0) {
56         linkpath = path.join(opts.path, path.join("/", linkpath))
57       }
58       entry.linkpath = entry.props.linkpath = linkpath
59     }
60   })
61
62   this._fst.on("ready", function () {
63     me.pipe(me._fst, { end: false })
64     me.resume()
65   })
66
67   this._fst.on('error', function(err) {
68     me.emit('error', err)
69   })
70
71   this._fst.on('drain', function() {
72     me.emit('drain')
73   })
74
75   // this._fst.on("end", function () {
76   //   console.error("\nEEEE Extract End", me._fst.path)
77   // })
78
79   this._fst.on("close", function () {
80     // console.error("\nEEEE Extract End", me._fst.path)
81     me.emit("finish")
82     me.emit("end")
83     me.emit("close")
84   })
85 }
86
87 inherits(Extract, tar.Parse)
88
89 Extract.prototype._streamEnd = function () {
90   var me = this
91   if (!me._ended || me._entry) me.error("unexpected eof")
92   me._fst.end()
93   // my .end() is coming later.
94 }