File size: 6,021 Bytes
bc20498
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
"use strict";

const _ = require('lodash');
const la = require('lazy-ass');
const is = require('check-more-types');
const cp = require('child_process');
const os = require('os');
const yauzl = require('yauzl');
const debug = require('debug')('cypress:cli:unzip');
const extract = require('extract-zip');
const Promise = require('bluebird');
const readline = require('readline');
const {
  throwFormErrorText,
  errors
} = require('../errors');
const fs = require('../fs');
const util = require('../util');
const unzipTools = {
  extract
};

// expose this function for simple testing
const unzip = ({
  zipFilePath,
  installDir,
  progress
}) => {
  debug('unzipping from %s', zipFilePath);
  debug('into', installDir);
  if (!zipFilePath) {
    throw new Error('Missing zip filename');
  }
  const startTime = Date.now();
  let yauzlDoneTime = 0;
  return fs.ensureDirAsync(installDir).then(() => {
    return new Promise((resolve, reject) => {
      return yauzl.open(zipFilePath, (err, zipFile) => {
        yauzlDoneTime = Date.now();
        if (err) {
          debug('error using yauzl %s', err.message);
          return reject(err);
        }
        const total = zipFile.entryCount;
        debug('zipFile entries count', total);
        const started = new Date();
        let percent = 0;
        let count = 0;
        const notify = percent => {
          const elapsed = +new Date() - +started;
          const eta = util.calculateEta(percent, elapsed);
          progress.onProgress(percent, util.secsRemaining(eta));
        };
        const tick = () => {
          count += 1;
          percent = count / total * 100;
          const displayPercent = percent.toFixed(0);
          return notify(displayPercent);
        };
        const unzipWithNode = () => {
          debug('unzipping with node.js (slow)');
          const opts = {
            dir: installDir,
            onEntry: tick
          };
          debug('calling Node extract tool %s %o', zipFilePath, opts);
          return unzipTools.extract(zipFilePath, opts).then(() => {
            debug('node unzip finished');
            return resolve();
          }).catch(err => {
            const error = err || new Error('Unknown error with Node extract tool');
            debug('error %s', error.message);
            return reject(error);
          });
        };
        const unzipFallback = _.once(unzipWithNode);
        const unzipWithUnzipTool = () => {
          debug('unzipping via `unzip`');
          const inflatingRe = /inflating:/;
          const sp = cp.spawn('unzip', ['-o', zipFilePath, '-d', installDir]);
          sp.on('error', err => {
            debug('unzip tool error: %s', err.message);
            unzipFallback();
          });
          sp.on('close', code => {
            debug('unzip tool close with code %d', code);
            if (code === 0) {
              percent = 100;
              notify(percent);
              return resolve();
            }
            debug('`unzip` failed %o', {
              code
            });
            return unzipFallback();
          });
          sp.stdout.on('data', data => {
            if (inflatingRe.test(data)) {
              return tick();
            }
          });
          sp.stderr.on('data', data => {
            debug('`unzip` stderr %s', data);
          });
        };

        // we attempt to first unzip with the native osx
        // ditto because its less likely to have problems
        // with corruption, symlinks, or icons causing failures
        // and can handle resource forks
        // http://automatica.com.au/2011/02/unzip-mac-os-x-zip-in-terminal/
        const unzipWithOsx = () => {
          debug('unzipping via `ditto`');
          const copyingFileRe = /^copying file/;
          const sp = cp.spawn('ditto', ['-xkV', zipFilePath, installDir]);

          // f-it just unzip with node
          sp.on('error', err => {
            debug(err.message);
            unzipFallback();
          });
          sp.on('close', code => {
            if (code === 0) {
              // make sure we get to 100% on the progress bar
              // because reading in lines is not really accurate
              percent = 100;
              notify(percent);
              return resolve();
            }
            debug('`ditto` failed %o', {
              code
            });
            return unzipFallback();
          });
          return readline.createInterface({
            input: sp.stderr
          }).on('line', line => {
            if (copyingFileRe.test(line)) {
              return tick();
            }
          });
        };
        switch (os.platform()) {
          case 'darwin':
            return unzipWithOsx();
          case 'linux':
            return unzipWithUnzipTool();
          case 'win32':
            return unzipWithNode();
          default:
            return;
        }
      });
    }).tap(() => {
      debug('unzip completed %o', {
        yauzlMs: yauzlDoneTime - startTime,
        unzipMs: Date.now() - yauzlDoneTime
      });
    });
  });
};
function isMaybeWindowsMaxPathLengthError(err) {
  return os.platform() === 'win32' && err.code === 'ENOENT' && err.syscall === 'realpath';
}
const start = async ({
  zipFilePath,
  installDir,
  progress
}) => {
  la(is.unemptyString(installDir), 'missing installDir');
  if (!progress) {
    progress = {
      onProgress: () => {
        return {};
      }
    };
  }
  try {
    const installDirExists = await fs.pathExists(installDir);
    if (installDirExists) {
      debug('removing existing unzipped binary', installDir);
      await fs.removeAsync(installDir);
    }
    await unzip({
      zipFilePath,
      installDir,
      progress
    });
  } catch (err) {
    const errorTemplate = isMaybeWindowsMaxPathLengthError(err) ? errors.failedUnzipWindowsMaxPathLength : errors.failedUnzip;
    await throwFormErrorText(errorTemplate)(err);
  }
};
module.exports = {
  start,
  utils: {
    unzip,
    unzipTools
  }
};