How to use getEnvVarVersion method in Cypress

Best JavaScript code snippet using cypress

Run Cypress automation tests on LambdaTest cloud grid

Perform automation testing on 3000+ real desktop and mobile devices online.

install.js

Source: install.js Github

copy
1"use strict";
2
3const _ = require('lodash');
4
5const arch = require('arch');
6
7const os = require('os');
8
9const path = require('path');
10
11const chalk = require('chalk');
12
13const debug = require('debug')('cypress:cli');
14
15const {
16  Listr
17} = require('listr2');
18
19const Promise = require('bluebird');
20
21const logSymbols = require('log-symbols');
22
23const {
24  stripIndent
25} = require('common-tags');
26
27const fs = require('../fs');
28
29const download = require('./download');
30
31const util = require('../util');
32
33const state = require('./state');
34
35const unzip = require('./unzip');
36
37const logger = require('../logger');
38
39const {
40  throwFormErrorText,
41  errors
42} = require('../errors');
43
44const verbose = require('../VerboseRenderer');
45
46const {
47  buildInfo,
48  version
49} = require('../../package.json');
50
51function _getBinaryUrlFromBuildInfo({
52  commitSha,
53  commitBranch
54}) {
55  return `https://cdn.cypress.io/beta/binary/${version}/${os.platform()}-${arch()}/${commitBranch}-${commitSha}/cypress.zip`;
56}
57
58const alreadyInstalledMsg = () => {
59  if (!util.isPostInstall()) {
60    logger.log(stripIndent`
61      Skipping installation:
62
63        Pass the ${chalk.yellow('--force')} option if you'd like to reinstall anyway.
64    `);
65  }
66};
67
68const displayCompletionMsg = () => {
69  // check here to see if we are globally installed
70  if (util.isInstalledGlobally()) {
71    // if we are display a warning
72    logger.log();
73    logger.warn(stripIndent`
74      ${logSymbols.warning} Warning: It looks like you\'ve installed Cypress globally.
75
76        This will work, but it'\s not recommended.
77
78        The recommended way to install Cypress is as a devDependency per project.
79
80        You should probably run these commands:
81
82        - ${chalk.cyan('npm uninstall -g cypress')}
83        - ${chalk.cyan('npm install --save-dev cypress')}
84    `);
85    return;
86  }
87
88  logger.log();
89  logger.log('You can now open Cypress by running:', chalk.cyan(path.join('node_modules', '.bin', 'cypress'), 'open'));
90  logger.log();
91  logger.log(chalk.grey('https://on.cypress.io/installing-cypress'));
92  logger.log();
93};
94
95const downloadAndUnzip = ({
96  version,
97  installDir,
98  downloadDir
99}) => {
100  const progress = {
101    throttle: 100,
102    onProgress: null
103  };
104  const downloadDestination = path.join(downloadDir, `cypress-${process.pid}.zip`);
105  const rendererOptions = getRendererOptions(); // let the user know what version of cypress we're downloading!
106
107  logger.log(`Installing Cypress ${chalk.gray(`(version: ${version})`)}`);
108  logger.log();
109  const tasks = new Listr([{
110    options: {
111      title: util.titleize('Downloading Cypress')
112    },
113    task: (ctx, task) => {
114      // as our download progresses indicate the status
115      progress.onProgress = progessify(task, 'Downloading Cypress');
116      return download.start({
117        version,
118        downloadDestination,
119        progress
120      }).then(redirectVersion => {
121        if (redirectVersion) version = redirectVersion;
122        debug(`finished downloading file: ${downloadDestination}`);
123      }).then(() => {
124        // save the download destination for unzipping
125        util.setTaskTitle(task, util.titleize(chalk.green('Downloaded Cypress')), rendererOptions.renderer);
126      });
127    }
128  }, unzipTask({
129    progress,
130    zipFilePath: downloadDestination,
131    installDir,
132    rendererOptions
133  }), {
134    options: {
135      title: util.titleize('Finishing Installation')
136    },
137    task: (ctx, task) => {
138      const cleanup = () => {
139        debug('removing zip file %s', downloadDestination);
140        return fs.removeAsync(downloadDestination);
141      };
142
143      return cleanup().then(() => {
144        debug('finished installation in', installDir);
145        util.setTaskTitle(task, util.titleize(chalk.green('Finished Installation'), chalk.gray(installDir)), rendererOptions.renderer);
146      });
147    }
148  }], {
149    rendererOptions
150  }); // start the tasks!
151
152  return Promise.resolve(tasks.run());
153};
154
155const validateOS = () => {
156  return util.getPlatformInfo().then(platformInfo => {
157    return platformInfo.match(/(darwin|linux|win32)-x64/);
158  });
159};
160/**
161 * Returns the version to install - either a string like `1.2.3` to be fetched
162 * from the download server or a file path or HTTP URL.
163 */
164
165
166function getVersionOverride({
167  envVarVersion,
168  buildInfo
169}) {
170  // let this environment variable reset the binary version we need
171  if (envVarVersion) {
172    return envVarVersion;
173  }
174
175  if (buildInfo && !buildInfo.stable) {
176    logger.log(chalk.yellow(stripIndent`
177        ${logSymbols.warning} Warning: You are installing a pre-release build of Cypress.
178
179        Bugs may be present which do not exist in production builds.
180
181        This build was created from:
182          * Commit SHA: ${buildInfo.commitSha}
183          * Commit Branch: ${buildInfo.commitBranch}
184          * Commit Timestamp: ${buildInfo.commitDate}
185      `));
186    logger.log();
187    return _getBinaryUrlFromBuildInfo(buildInfo);
188  }
189}
190
191function getEnvVarVersion() {
192  if (!util.getEnv('CYPRESS_INSTALL_BINARY')) return; // because passed file paths are often double quoted
193  // and might have extra whitespace around, be robust and trim the string
194
195  const trimAndRemoveDoubleQuotes = true;
196  const envVarVersion = util.getEnv('CYPRESS_INSTALL_BINARY', trimAndRemoveDoubleQuotes);
197  debug('using environment variable CYPRESS_INSTALL_BINARY "%s"', envVarVersion);
198  return envVarVersion;
199}
200
201const start = async (options = {}) => {
202  debug('installing with options %j', options);
203  const envVarVersion = getEnvVarVersion();
204
205  if (envVarVersion === '0') {
206    debug('environment variable CYPRESS_INSTALL_BINARY = 0, skipping install');
207    logger.log(stripIndent`
208        ${chalk.yellow('Note:')} Skipping binary installation: Environment variable CYPRESS_INSTALL_BINARY = 0.`);
209    logger.log();
210    return;
211  }
212
213  _.defaults(options, {
214    force: false,
215    buildInfo
216  });
217
218  if (util.getEnv('CYPRESS_CACHE_FOLDER')) {
219    const envCache = util.getEnv('CYPRESS_CACHE_FOLDER');
220    logger.log(stripIndent`
221        ${chalk.yellow('Note:')} Overriding Cypress cache directory to: ${chalk.cyan(envCache)}
222
223              Previous installs of Cypress may not be found.
224      `);
225    logger.log();
226  }
227
228  const pkgVersion = util.pkgVersion();
229  const versionOverride = getVersionOverride({
230    envVarVersion,
231    buildInfo: options.buildInfo
232  });
233  const versionToInstall = versionOverride || pkgVersion;
234  debug('version in package.json is %s, version to install is %s', pkgVersion, versionToInstall);
235  const installDir = state.getVersionDir(pkgVersion, options.buildInfo);
236  const cacheDir = state.getCacheDir();
237  const binaryDir = state.getBinaryDir(pkgVersion);
238
239  if (!(await validateOS())) {
240    return throwFormErrorText(errors.invalidOS)();
241  }
242
243  await fs.ensureDirAsync(cacheDir).catch({
244    code: 'EACCES'
245  }, err => {
246    return throwFormErrorText(errors.invalidCacheDirectory)(stripIndent`
247    Failed to access ${chalk.cyan(cacheDir)}:
248
249    ${err.message}
250    `);
251  });
252  const binaryPkg = await state.getBinaryPkgAsync(binaryDir);
253  const binaryVersion = await state.getBinaryPkgVersion(binaryPkg);
254
255  const shouldInstall = () => {
256    if (!binaryVersion) {
257      debug('no binary installed under cli version');
258      return true;
259    }
260
261    logger.log();
262    logger.log(stripIndent`
263      Cypress ${chalk.green(binaryVersion)} is installed in ${chalk.cyan(installDir)}
264      `);
265    logger.log();
266
267    if (options.force) {
268      debug('performing force install over existing binary');
269      return true;
270    }
271
272    if (binaryVersion === versionToInstall || !util.isSemver(versionToInstall)) {
273      // our version matches, tell the user this is a noop
274      alreadyInstalledMsg();
275      return false;
276    }
277
278    return true;
279  }; // noop if we've been told not to download
280
281
282  if (!shouldInstall()) {
283    return debug('Not downloading or installing binary');
284  }
285
286  if (envVarVersion) {
287    logger.log(chalk.yellow(stripIndent`
288        ${logSymbols.warning} Warning: Forcing a binary version different than the default.
289
290          The CLI expected to install version: ${chalk.green(pkgVersion)}
291
292          Instead we will install version: ${chalk.green(versionToInstall)}
293
294          These versions may not work properly together.
295      `));
296    logger.log();
297  }
298
299  const getLocalFilePath = async () => {
300    // see if version supplied is a path to a binary
301    if (await fs.pathExistsAsync(versionToInstall)) {
302      return path.extname(versionToInstall) === '.zip' ? versionToInstall : false;
303    }
304
305    const possibleFile = util.formAbsolutePath(versionToInstall);
306    debug('checking local file', possibleFile, 'cwd', process.cwd()); // if this exists return the path to it
307    // else false
308
309    if ((await fs.pathExistsAsync(possibleFile)) && path.extname(possibleFile) === '.zip') {
310      return possibleFile;
311    }
312
313    return false;
314  };
315
316  const pathToLocalFile = await getLocalFilePath();
317
318  if (pathToLocalFile) {
319    const absolutePath = path.resolve(versionToInstall);
320    debug('found local file at', absolutePath);
321    debug('skipping download');
322    const rendererOptions = getRendererOptions();
323    return new Listr([unzipTask({
324      progress: {
325        throttle: 100,
326        onProgress: null
327      },
328      zipFilePath: absolutePath,
329      installDir,
330      rendererOptions
331    })], {
332      rendererOptions
333    }).run();
334  }
335
336  if (options.force) {
337    debug('Cypress already installed at', installDir);
338    debug('but the installation was forced');
339  }
340
341  debug('preparing to download and unzip version ', versionToInstall, 'to path', installDir);
342  const downloadDir = os.tmpdir();
343  await downloadAndUnzip({
344    version: versionToInstall,
345    installDir,
346    downloadDir
347  }); // delay 1 sec for UX, unless we are testing
348
349  await Promise.delay(1000);
350  displayCompletionMsg();
351};
352
353module.exports = {
354  start,
355  _getBinaryUrlFromBuildInfo
356};
357
358const unzipTask = ({
359  zipFilePath,
360  installDir,
361  progress,
362  rendererOptions
363}) => {
364  return {
365    options: {
366      title: util.titleize('Unzipping Cypress')
367    },
368    task: (ctx, task) => {
369      // as our unzip progresses indicate the status
370      progress.onProgress = progessify(task, 'Unzipping Cypress');
371      return unzip.start({
372        zipFilePath,
373        installDir,
374        progress
375      }).then(() => {
376        util.setTaskTitle(task, util.titleize(chalk.green('Unzipped Cypress')), rendererOptions.renderer);
377      });
378    }
379  };
380};
381
382const progessify = (task, title) => {
383  // return higher order function
384  return (percentComplete, remaining) => {
385    percentComplete = chalk.white(` ${percentComplete}%`); // pluralize seconds remaining
386
387    remaining = chalk.gray(`${remaining}s`);
388    util.setTaskTitle(task, util.titleize(title, percentComplete, remaining), getRendererOptions().renderer);
389  };
390}; // if we are running in CI then use
391// the verbose renderer else use
392// the default
393
394
395const getRendererOptions = () => {
396  let renderer = util.isCi() ? verbose : 'default';
397
398  if (logger.logLevel() === 'silent') {
399    renderer = 'silent';
400  }
401
402  return {
403    renderer
404  };
405};
Full Screen

Accelerate Your Automation Test Cycles With LambdaTest

Leverage LambdaTest’s cloud-based platform to execute your automation tests in parallel and trim down your test execution time significantly. Your first 100 automation testing minutes are on us.

Try LambdaTest

Run JavaScript Tests on LambdaTest Cloud Grid

Execute automation tests with Cypress on a cloud-based Grid of 3000+ real browsers and operating systems for both web and mobile applications.

Test now for Free
LambdaTestX

We use cookies to give you the best experience. Cookies help to provide a more personalized experience and relevant advertising for you, and web analytics for us. Learn More in our Cookies policy, Privacy & Terms of service

Allow Cookie
Sarah

I hope you find the best code examples for your project.

If you want to accelerate automated browser testing, try LambdaTest. Your first 100 automation testing minutes are FREE.

Sarah Elson (Product & Growth Lead)