How to use version method in Airtest

Best Python code snippet using Airtest

VersionController.js

Source:VersionController.js Github

copy

Full Screen

1/**2 * VersionController3 *4 * @description :: Server-side logic for handling version requests5 * @help        :: See http://sailsjs.org/#!/documentation/concepts/Controllers6 */7var actionUtil = require('sails/lib/hooks/blueprints/actionUtil');8var url = require('url');9var Promise = require('bluebird');10var semver = require('semver');11var compareVersions = require('compare-versions');12const availabilityFilter = () => ({ '<=': (new Date()).toISOString() });13module.exports = {14  /**15   * Set availability date of specified version16   *17   * (PUT /version/availability/:version/:timestamp)18   */19  availability: (req, res) => {20    const { version, timestamp } = req.params;21    if (!version) return res.badRequest('Requires `version` parameter');22    if (!timestamp) return res.badRequest('Requires `timestamp` parameter');23    const availability = new Date(parseInt(timestamp, 10));24    if (isNaN(availability) || availability.getTime().toString() !== timestamp) {25      return res.badRequest('Parameter `timestamp` must be a valid unix timestamp in milliseconds');26    }27    Version28      .findOne(version)29      .then(foundVersion => {30        if (!foundVersion) return res.notFound('The specified `version` does not exist');31        if (availability < new Date(foundVersion.createdAt)) {32          return res.badRequest(33            'Parameter `timestamp` must be greater than or equal to the version creation date'34          );35        }36        return Version37          .update(version, { availability })38          .then(([updatedVersion]) => {39            Version.publishUpdate(version, updatedVersion, req);40            res.send(updatedVersion);41          });42      })43      .catch(res.negotiate);44  },45  /**46   * Redirect the update request to the appropriate endpoint47   * (GET /update)48   */49  redirect: function(req, res) {50    var platform = req.param('platform');51    var version = req.param('version');52    if (!version) {53      return res.badRequest('Requires "version" parameter');54    }55    if (!platform) {56      return res.badRequest('Requires "platform" parameter');57    }58    return res.redirect('/update/' + platform + '/' + version);59  },60  /**61   * Sorts versions and returns pages sorted by by sermver62   *63   * ( GET /versions/sorted )64   */65  list: function (req, res) {66    Version67      .find()68      .then(versions => {69        var count = versions.length;70        var page = req.param('page') || req.query.page || 0;71        var start = page * sails.config.views.pageSize;72        var end = start + sails.config.views.pageSize;73        var items = versions74          .sort(function (a, b) {75            return -compareVersions(a.name, b.name);76          })77          .slice(start, end);78        const response = {79          total: count,80          offset: start,81          page: page,82          items: items83        }84        return Promise.all([85          // load channels86          new Promise(function (resolve, reject) {87            Promise.all(items.map(function (version) {88              return Channel.findOne({89                name: version.channel90              })91            }))92            .then(resolve)93            .catch(reject)94          }),95          // load assets96          new Promise(function (resolve, reject) {97            Promise.all(items.map(function (version) {98              return Asset.find({99                version: version.id100              })101            }))102            .then(resolve)103            .catch(reject)104          }),105          // load flavors106          new Promise((resolve, reject) => Promise107            .map(items, version => Flavor.findOne(version.flavor))108            .then(resolve)109            .catch(reject)110          )111        ])112        .then(function (results) {113          response.items = response.items.map(function (item, index) {114            return {115              id: item.id,116              channel: results[0][index],117              assets: results[1][index].map(function (asset) {118                return {119                  id: asset.id,120                  name: asset.name,121                  platform: asset.platform,122                  filetype: asset.filetype,123                  hash: asset.hash,124                  size: asset.size,125                  download_count: asset.download_count,126                  fd: asset.fd,127                  createdAt: asset.createdAt,128                  updatedAt: asset.updatedAt129                }130              }),131              flavor: results[2][index],132              name: item.name,133              notes: item.notes,134              createdAt: item.createdAt,135              updatedAt: item.updatedAt,136              availability: item.availability137            }138          })139          return response140        })141      })142      .then(response => {143        res.send(response);144      })145      .catch(res.negotiate);146  },147  /**148   * Serves auto-updates: Status and Squirrel.Mac149   *150   * Assumes stable channel & default flavor unless specified151   *152   * (GET /update/:platform/:version/:channel)153   * (GET /update/flavor/:flavor/:platform/:version/:channel?)154   */155  general: function(req, res) {156    var platform = req.param('platform');157    var version = req.param('version');158    var channel = req.param('channel') || 'stable';159    const flavor = req.params.flavor || 'default';160    if (!version) {161      return res.badRequest('Requires `version` parameter');162    }163    if (!platform) {164      return res.badRequest('Requires `platform` parameter');165    }166    var platforms = PlatformService.detect(platform, true);167    sails.log.debug('Update Search Query', {168      platform: platforms,169      version: version,170      channel: channel,171      flavor172    });173    // Get specified version object, it's time will be used for the general174    // cutoff.175    Version176      .findOne({177        name: version,178        flavor179      })180      .then(function(currentVersion) {181        var applicableChannels, createdAtFilter;182        applicableChannels = ChannelService.getApplicableChannels(channel);183        sails.log.debug('Applicable Channels', applicableChannels);184        if (currentVersion) {185          createdAtFilter = {186            '>': currentVersion.createdAt187          };188        } else {189          sails.log.debug('The specified `version` does not exist');190        }191        sails.log.debug('Time Filter', createdAtFilter);192        return Version193          .find(UtilityService.getTruthyObject({194            channel: applicableChannels,195            createdAt: createdAtFilter,196            availability: availabilityFilter(),197            flavor198          }))199          .populate('assets', {200            platform: platforms201          })202          .then(function(newerVersions) {203            // Sort versions which were added after the current one by semver in204            // descending order.205            newerVersions.sort(UtilityService.compareVersion);206            var latestVersion;207            sails.log.debug('Newer Versions', newerVersions);208            var releaseNotes = _.reduce(209              newerVersions,210              function(prevNotes, newVersion) {211                newVersion.assets = _.filter(newVersion.assets, function(asset) {212                  return asset.filetype === '.zip';213                });214                // If one of the assets for this verison apply to our desired215                // platform then we will skip this version216                if (!newVersion.assets.length) {217                  return prevNotes;218                }219                if (!latestVersion && semver.lt(version, newVersion.name)) {220                  latestVersion = newVersion;221                }222                // Skip if no notes available for this version223                if (!newVersion.notes || !newVersion.notes.length) {224                  return prevNotes;225                }226                // If not the first changenote, prefix with new line227                var newChangeNote = !prevNotes.length ? '' : '\n';228                newChangeNote += '## ' + newVersion.name + '\n' + newVersion.notes;229                return prevNotes + newChangeNote;230              },231              '');232            var currentVersionName = _.get(currentVersion, 'name');233            sails.log.debug('Version candidate', latestVersion);234            sails.log.debug('Current version', currentVersionName);235            if (!latestVersion || latestVersion.name === currentVersionName) {236              sails.log.debug('Version candidate denied');237              return res.status(204).send('No updates.');238            }239            sails.log.debug('Version candidate accepted');240            return res.ok({241              url: url.resolve(242                sails.config.appUrl,243                `/download/flavor/${flavor}/${latestVersion.name}/` +244                latestVersion.assets[0].platform + '?filetype=zip'245              ),246              name: latestVersion.name,247              notes: releaseNotes,248              pub_date: latestVersion.availability.toISOString()249            });250          });251      })252      .catch(res.negotiate);253  },254  /**255   * Serves auto-updates: Squirrel.Windows: serve RELEASES from latest version256   * Currently, it will only serve a full.nupkg of the latest release with a257   * normalized filename (for pre-release)258   *259   * (GET /update/:platform/:version/:channel/RELEASES)260   * (GET /update/flavor/:flavor/:platform/:version/:channel/RELEASES)261   */262  windows: function(req, res) {263    var platform = req.param('platform');264    var version = req.param('version');265    var channel = req.param('channel') || 'stable';266    const flavor = req.params.flavor || 'default';267    if (!version) {268      return res.badRequest('Requires `version` parameter');269    }270    if (!platform) {271      return res.badRequest('Requires `platform` parameter');272    }273    var platforms = PlatformService.detect(platform, true);274    sails.log.debug('Windows Update Search Query', {275      platform: platforms,276      version: version,277      channel: channel,278      flavor279    });280    // Get specified version object, it's time will be used for the general281    // cutoff.282    Version283      .findOne({284        name: version,285        flavor286      })287      .then(function(currentVersion) {288        var applicableChannels, createdAtFilter;289        applicableChannels = ChannelService.getApplicableChannels(channel);290        sails.log.debug('Applicable Channels', applicableChannels);291        if (currentVersion) {292          createdAtFilter = {293            '>=': currentVersion.createdAt294          };295        } else {296          sails.log.debug('The specified `version` does not exist');297        }298        sails.log.debug('Time Filter', createdAtFilter);299        return Version300          .find(UtilityService.getTruthyObject({301            channel: applicableChannels,302            createdAt: createdAtFilter,303            availability: availabilityFilter(),304            flavor305          }))306          .populate('assets', {307            platform: platforms308          })309          .then(function(newerVersions) {310            // Sort versions which were added after the current one by semver in311            // descending order.312            newerVersions.sort(UtilityService.compareVersion);313            var latestVersion = _.find(314              newerVersions,315              function(newVersion) {316                _.remove(newVersion.assets, function(o) {317                  return o.filetype !== '.nupkg' || !o.hash;318                });319                // Make sure the last version is a version with full asset320                // so RELEASES contains at least one full asset (which is mandatory for Squirrel.Windows)321                let v = _.filter(322                    newVersion.assets,323                    function(o) {324                      return _.includes(o.name.toLowerCase(), '-full');325                    }326                  );327                return v.length && semver.lte(328                  version, newVersion.name329                );330              });331            if (!latestVersion) {332              sails.log.debug('Version not found');333              return res.status(500).send('Version not found');334            }335            // Add Delta assets from other versions336            var deltaAssets = _.reduce(337              newerVersions,338              function(assets, newVersion) {339                return assets.concat(340                  _.filter(341                    newVersion.assets,342                    function(asset) {343                      return asset.filetype === '.nupkg'344                        && _.includes(asset.name.toLowerCase(), '-delta')345                        && semver.lte(version, asset.version)346                        && semver.gt(latestVersion.name, asset.version);347                    }));348              }, []);349            Array.prototype.unshift.apply(latestVersion.assets, deltaAssets);350            latestVersion.assets.sort(function(a1, a2) {351              return semver.compare(a1.version, a2.version);352            });353            sails.log.debug('Latest Windows Version', latestVersion);354            // Change asset name to use full download link355            const assets = _.map(latestVersion.assets, function(asset) {356              asset.name = url.resolve(357                sails.config.appUrl,358                `/download/flavor/${flavor}/${latestVersion.name}/${asset.platform}/` +359                asset.name360              );361              return asset;362            });363            var output = WindowsReleaseService.generate(assets);364            res.header('Content-Length', output.length);365            res.attachment('RELEASES');366            return res.send(output);367          });368      })369      .catch(res.negotiate);370  },371  /**372   * Get electron-updater win yml for a specific channel373   * (GET /update/:platform/latest.yml)374   * (GET /update/:platform/:channel.yml)375   * (GET /update/:platform/:channel/latest.yml)376   * (GET /update/flavor/:flavor/:platform/latest.yml)377   * (GET /update/flavor/:flavor/:platform/:channel.yml)378   * (GET /update/flavor/:flavor/:platform/:channel/latest.yml)379   */380  electronUpdaterWin: function(req, res) {381    var platform = req.param('platform');382    var channel = req.param('channel') || 'stable';383    const flavor = req.params.flavor || 'default';384    if (!platform) {385      return res.badRequest('Requires `platform` parameter');386    }387    var platforms = PlatformService.detect(platform, true);388    sails.log.debug('NSIS electron-updater Search Query', {389      platform: platforms,390      channel: channel,391      flavor392    });393    var applicableChannels = ChannelService.getApplicableChannels(channel);394    sails.log.debug('Applicable Channels', applicableChannels);395    // Get latest version that has a windows asset396    Version397      .find({398        channel: applicableChannels,399        availability: availabilityFilter(),400        flavor401      })402      .populate('assets')403      .then(function(versions) {404        // TODO: Implement method to get latest version with available asset405        var sortedVersions = versions.sort(UtilityService.compareVersion);406        var latestVersion = null;407        var asset = null;408        for (var i = 0; i < sortedVersions.length; i++) {409          var currentVersion = sortedVersions[i];410          if (currentVersion.assets) {411            for (var j = 0; j < currentVersion.assets.length; j++) {412              var currentAsset = currentVersion.assets[j];413              if (currentAsset.filetype === '.exe' && _.includes(platforms, currentAsset.platform)) {414                latestVersion = currentVersion;415                asset = currentAsset;416                break;417              }418            }419            if (latestVersion) {420              break;421            }422          }423        }424        if (latestVersion) {425          var downloadPath = url.resolve(426            //sails.config.appUrl,427            "",428            `/download/flavor/${flavor}/${latestVersion.name}/${asset.platform}/` +429            asset.name430          );431          const sha512 = asset.hash ? asset.hash : null;432          var latestYml = "version: " + latestVersion.name433                          + "\nfiles:"434                          + "\n  - url: " + downloadPath435                          + "\n    sha512: " + sha512436                          + "\n    size: " + asset.size437                          + "\nreleaseDate: " + latestVersion.updatedAt438                          + "\npath: " + downloadPath439                          + "\nsha512: " + sha512440                          + "\nsize: " + asset.size;441          res.ok(latestYml);442        } else {443          res.notFound();444        }445      });446  },447  /**448   * Get electron-updater mac yml for a specific channel449   * (GET /update/:platform/latest-mac.yml)450   * (GET /update/:platform/:channel-mac.yml)451   * (GET /update/:platform/:channel/latest-mac.yml)452   * (GET /update/flavor/:flavor/:platform/latest-mac.yml)453   * (GET /update/flavor/:flavor/:platform/:channel-mac.yml)454   * (GET /update/flavor/:flavor/:platform/:channel/latest-mac.yml)455   */456  electronUpdaterMac: function(req, res) {457    var platform = req.param('platform');458    var channel = req.param('channel') || 'stable';459    const flavor = req.params.flavor || 'default';460    if (!platform) {461      return res.badRequest('Requires `platform` parameter');462    }463    var platforms = PlatformService.detect(platform, true);464    sails.log.debug('Mac electron-updater Search Query', {465      platform: platforms,466      channel: channel,467      flavor468    });469    var applicableChannels = ChannelService.getApplicableChannels(channel);470    sails.log.debug('Applicable Channels', applicableChannels);471    // Get latest version that has a mac asset472    Version473      .find({474        channel: applicableChannels,475        availability: availabilityFilter(),476        flavor477      })478      .populate('assets')479      .then(function(versions) {480        // TODO: Implement method to get latest version with available asset481        var sortedVersions = versions.sort(UtilityService.compareVersion);482        var latestVersion = null;483        var asset = null;484        for (var i = 0; i < sortedVersions.length; i++) {485          var currentVersion = sortedVersions[i];486          if (currentVersion.assets) {487            for (var j = 0; j < currentVersion.assets.length; j++) {488              var currentAsset = currentVersion.assets[j];489              if (currentAsset.filetype === '.zip' && _.includes(platforms, currentAsset.platform)) {490                latestVersion = currentVersion;491                asset = currentAsset;492                break;493              }494            }495            if (latestVersion) {496              break;497            }498          }499        }500        if (latestVersion) {501          var downloadPath = url.resolve(502            //sails.config.appUrl,503            "",504            `/download/flavor/${flavor}/${latestVersion.name}/${asset.platform}/` +505            asset.name506          );507          const sha512 = asset.hash ? asset.hash : null;508          var latestYml = "version: " + latestVersion.name509                          + "\nfiles:"510                          + "\n  - url: " + downloadPath511                          + "\n    sha512: " + sha512512                          + "\n    size: " + asset.size513                          + "\nreleaseDate: " + latestVersion.updatedAt514                          + "\npath: " + downloadPath515                          + "\nsha512: " + sha512516                          + "\nsize: " + asset.size;517          res.ok(latestYml);518        } else {519          res.notFound();520        }521      });522  },523  /**524   * Get release notes for a specific version525   * (GET /notes/:version/:flavor?)526   */527  releaseNotes: function(req, res) {528    var version = req.params.version;529    const flavor = req.params.flavor || 'default';530    Version531      .findOne({532        name: version,533        availability: availabilityFilter(),534        flavor535      })536      .then(function(currentVersion) {537        if (!currentVersion) {538          return res.notFound('The specified version does not exist');539        }540        return res.format({541          'application/json': function() {542            res.send({543              'notes': currentVersion.notes,544              'pub_date': currentVersion.availability.toISOString()545            });546          },547          'default': function() {548            res.send(currentVersion.notes);549          }550        });551      })552      .catch(res.negotiate);553  },554  /**555   * Overloaded blueprint function556   * Changes:557   *  - Delete all associated assets & their files558   * @param  {[type]} req [description]559   * @param  {[type]} res [description]560   * @return {[type]}     [description]561   */562  destroy: function(req, res) {563    var pk = actionUtil.requirePk(req);564    var query = Version.findOne(pk);565    query.populate('assets');566    query.exec(function foundRecord(err, record) {567      if (err) return res.serverError(err);568      if (!record) return res.notFound(569        'No record found with the specified `name`.'570      );571      var deletePromises = _.map(record.assets, function(asset) {572        return Promise.join(573          AssetService.destroy(asset, req),574          AssetService.deleteFile(asset),575          function() {576            sails.log.info('Destroyed asset: ', asset);577          });578      });579      Promise.all(deletePromises)580        .then(function allDeleted() {581          return Version.destroy(pk)582            .then(function destroyedRecord() {583              if (sails.hooks.pubsub) {584                Version.publishDestroy(585                  pk, !req._sails.config.blueprints.mirror && req, {586                    previous: record587                  }588                );589                if (req.isSocket) {590                  Version.unsubscribe(req, record);591                  Version.retire(record);592                }593              }594              sails.log.info('Destroyed version: ', record);595              return res.ok(record);596            });597        })598        .error(res.negotiate);599    });600  }...

Full Screen

Full Screen

check_reqs.js

Source:check_reqs.js Github

copy

Full Screen

1/*2       Licensed to the Apache Software Foundation (ASF) under one3       or more contributor license agreements.  See the NOTICE file4       distributed with this work for additional information5       regarding copyright ownership.  The ASF licenses this file6       to you under the Apache License, Version 2.0 (the7       "License"); you may not use this file except in compliance8       with the License.  You may obtain a copy of the License at9         http://www.apache.org/licenses/LICENSE-2.010       Unless required by applicable law or agreed to in writing,11       software distributed under the License is distributed on an12       "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY13       KIND, either express or implied.  See the License for the14       specific language governing permissions and limitations15       under the License.16*/17/*jshint node:true*/18var Q     = require('q');19var os    = require('os');20var path  = require('path');21var shell = require('shelljs');22var spawn = require('cordova-common').superspawn.spawn;23var CordovaError = require('cordova-common').CordovaError;24var ConfigParser, MSBuildTools, Version;25try {26    ConfigParser = require('../../template/cordova/lib/ConfigParser');27    MSBuildTools = require('../../template/cordova/lib/MSBuildTools');28    Version = require('../../template/cordova/lib/Version');29} catch (ex) {30    // If previous import fails, we're probably running this script31    // from installed platform and the module location is different.32    ConfigParser = require('./ConfigParser');33    MSBuildTools = require('./MSBuildTools');34    Version = require('./Version');35}36// The constant for VS2013 Upd2 PackageVersion. See MSDN for37// reference: https://msdn.microsoft.com/en-us/library/bb164659(v=vs.120).aspx38var VS2013_UPDATE2_RC = new Version(12, 0, 30324);39var REQUIRED_VERSIONS = {40    '8.0': {41        os: '6.2',42        msbuild: '11.0',43        visualstudio: '11.0',44        windowssdk: '8.0'45    },46    '8.1': {47        os: '6.3',48        msbuild: '12.0',49        visualstudio: '12.0',50        windowssdk: '8.1',51        phonesdk: '8.1'52    },53    '10.0': {54        // Note that Windows 10 target is also supported on Windows 7, so this should look55        // like '6.1 || >=6.3', but due to Version module restricted functionality we handle56        // this case separately in checkOS function below.57        os: '6.3',58        msbuild: '14.0',59        visualstudio: '14.0',60        windowssdk: '10.0',61        phonesdk: '10.0'62    }63};64function getConfig() {65    try {66        return new ConfigParser(path.join(__dirname, '../../config.xml'));67    } catch (e) {68        throw new CordovaError('Can\'t check requirements for Windows platform.' +69            'The config.xml file is either missing or malformed.');70    }71}72function getMinimalRequiredVersionFor (requirement) {73    var config = getConfig();74    var windowsTargetVersion = config.getWindowsTargetVersion();75    var windowsPhoneTargetVersion = config.getWindowsPhoneTargetVersion();76    var windowsReqVersion = Version.tryParse(REQUIRED_VERSIONS[windowsTargetVersion][requirement]);77    var phoneReqVersion = Version.tryParse(REQUIRED_VERSIONS[windowsPhoneTargetVersion][requirement]);78    // If we're searching for Windows SDK, we're not79    // interested in Phone's version and and vice versa.80    if (requirement === 'windowssdk') return windowsReqVersion;81    if (requirement === 'phonesdk') return phoneReqVersion;82    // If both windowsReqVersion and phoneReqVersion is valid Versions, choose the max one83    if (windowsReqVersion && phoneReqVersion) {84        return windowsReqVersion.gt(phoneReqVersion) ?85            windowsReqVersion :86            phoneReqVersion;87    }88    // Otherwise return that one which is defined and valid89    return windowsReqVersion || phoneReqVersion;90}91function getHighestAppropriateVersion (versions, requiredVersion) {92    return versions.map(function (version) {93        return Version.tryParse(version);94    })95    .sort(Version.comparer)96    .filter(function (toolVersion) {97        return toolVersion.gte(requiredVersion);98    })[0];99}100/**101 * Return Version object for current Windows version. User 'ver' binary or102 *   os.release() in case of errors.103 *104 * @return  {Version}  Version information for current OS.105 */106function getWindowsVersion() {107    return spawn('ver').then(function (output) {108        var match = /\[Version (.*)\]\s*$/.exec(output);109        return Version.fromString(match[1]);110    }).fail(function () {111        return Version.fromString(os.release());112    });113}114/**115 * Lists all Visual Studio versions insalled. For VS 2013 if it present, alao116 *   checks if Update 2 is installed.117 *118 * @return  {String[]}  List of installed Visual Studio versions.119 */120function getInstalledVSVersions() {121    // Query all keys with Install value equal to 1, then filter out122    // those, which are not related to VS itself123    return spawn('reg', ['query', 'HKLM\\SOFTWARE\\Microsoft\\DevDiv\\vs\\Servicing', '/s', '/v', 'Install', '/f', '1', '/d', '/e', '/reg:32'])124    .fail(function () { return ''; })125    .then(function (output) {126        return output.split('\n')127        .reduce(function (installedVersions, line) {128            var match = /(\d+\.\d+)\\(ultimate|professional|premium|community)/.exec(line);129            if (match && match[1] && installedVersions.indexOf(match[1]) === -1)130                installedVersions.push(match[1]);131            return installedVersions;132        }, []);133    })134    .then(function (installedVersions) {135        // If there is no VS2013 installed, the we have nothing to do136        if (installedVersions.indexOf('12.0') === -1) return installedVersions;137        // special case for VS 2013. We need to check if VS2013 update 2 is installed138        return spawn('reg', ['query','HKLM\\SOFTWARE\\Microsoft\\Updates\\Microsoft Visual Studio 2013\\vsupdate_KB2829760','/v','PackageVersion','/reg:32'])139        .then(function (output) {140            var updateVer = Version.fromString(/PackageVersion\s+REG_SZ\s+(.*)/i.exec(output)[1]);141            // if update version is lover than Update2, reject the promise142            if (VS2013_UPDATE2_RC.gte(updateVer)) return Q.reject();143            return installedVersions;144        })145        .fail(function () {146            // if we got any errors on previous steps, we're assuming that147            // required VS update is not installed.148            installedVersions.splice(installedVersions.indexOf('12.0'));149            return installedVersions;150        });151    });152}153/**154 * Gets list of installed Windows SDKs155 *156 * @return  {Version[]}  List of installed SDKs' versions157 */158function getInstalledWindowsSdks () {159    var installedSdks = [];160    return spawn('reg', ['query','HKLM\\SOFTWARE\\Microsoft\\Microsoft SDKs\\Windows','/s','/v','InstallationFolder','/reg:32'])161    .fail(function () { return ''; })162    .then(function (output) {163        var re = /\\Microsoft SDKs\\Windows\\v(\d+\.\d+)\s*InstallationFolder\s+REG_SZ\s+(.*)/gim;164        var match;165        while ((match = re.exec(output))){166            var sdkPath = match[2];167            // Verify that SDKs is really installed by checking SDKManifest file at SDK root168            if (shell.test('-e', path.join(sdkPath, 'SDKManifest.xml'))) {169                installedSdks.push(Version.tryParse(match[1]));170            }171        }172    })173    .thenResolve(installedSdks);174}175/**176 * Gets list of installed Windows Phone SDKs. Separately searches for 8.1 Phone177 *   SDK and Windows 10 SDK, because the latter is needed for both Windows and178 *   Windows Phone applications.179 *180 * @return  {Version[]}  List of installed Phone SDKs' versions.181 */182function getInstalledPhoneSdks () {183    var installedSdks = [];184    return spawn('reg', ['query','HKLM\\SOFTWARE\\Microsoft\\Microsoft SDKs\\Windows Phone\\v8.1','/v','InstallationFolder','/reg:32'])185    .fail(function () { return ''; })186    .then(function (output) {187        var match = /\\Microsoft SDKs\\Windows Phone\\v(\d+\.\d+)\s*InstallationFolder\s+REG_SZ\s+(.*)/gim.exec(output);188        if (match && shell.test('-e', path.join(match[2], 'SDKManifest.xml'))) {189            installedSdks.push(Version.tryParse(match[1]));190        }191    })192    .then(function () {193        return spawn('reg', ['query','HKLM\\SOFTWARE\\Microsoft\\Microsoft SDKs\\Windows\\v10.0','/v','InstallationFolder','/reg:32']);194    })195    .fail(function () { return ''; })196    .then(function (output) {197        var match = /\\Microsoft SDKs\\Windows\\v(\d+\.\d+)\s*InstallationFolder\s+REG_SZ\s+(.*)/gim.exec(output);198        if (match && shell.test('-e', path.join(match[2], 'SDKManifest.xml'))) {199            installedSdks.push(Version.tryParse(match[1]));200        }201    })202    .thenResolve(installedSdks);203}204/**205 * Shortens version string or Version object by leaving only first two segments206 *   (major and minor).207 * @param   {String|Version}  version  The version identifier. Either Version208 *   object or string that looks like "12.5.6"209 * @return  {String}          Shortened version, or undefined if provided210 *   parameter is not a valid version211 */212function shortenVersion (version) {213    return /^(\d+(?:\.\d+)?)/.exec(version.toString())[1];214}215function mapWindowsVersionToName(version) {216    var map = {217        '6.2': 'Windows 8',218        '6.3': 'Windows 8.1',219        '10.0': 'Windows 10'220    };221    var majorMinor = shortenVersion(version);222    return map[majorMinor];223}224function mapVSVersionToName(version) {225    var map = {226        '11.0': '2012 Express for Windows',227        '12.0': '2013 Express for Windows Update2',228        '14.0': '2015 Community'229    };230    var majorMinor = shortenVersion(version);231    return map[majorMinor];232}233/**234 * Check if current OS is supports building windows platform235 * @return {Promise} Promise either fullfilled or rejected with error message.236 */237var checkOS = function () {238    if (process.platform !== 'win32') {239        // Build Universal windows apps available for windows platform only, so we reject on others platforms240        return Q.reject('Cordova tooling for Windows requires Windows OS to build project');241    }242    return getWindowsVersion().then(function (actualVersion) {243        var requiredOsVersion = getMinimalRequiredVersionFor('os');244        if (actualVersion.gte(requiredOsVersion) ||245            // Special case for Windows 10/Phone 10  targets which can be built on Windows 7 (version 6.1)246            actualVersion.major === 6 && actualVersion.minor === 1 && getConfig().getWindowsTargetVersion() === '10.0') {247            return mapWindowsVersionToName(actualVersion);248        }249        return Q.reject('Current Windows version doesn\'t support building this project. ' +250            'Consider upgrading your OS to ' + mapWindowsVersionToName(requiredOsVersion));251    });252};253/**254 * Checks if MSBuild tools is available.255 * @return {Promise} Promise either fullfilled with MSBuild version256 *                           or rejected with error message.257 */258var checkMSBuild = function () {259    return MSBuildTools.findAllAvailableVersions()260    .then(function (msbuildToolsVersions) {261        var msbuildRequiredVersion = getMinimalRequiredVersionFor('msbuild');262        msbuildToolsVersions = msbuildToolsVersions.map(function (msbuildToolsVersion) {263            return msbuildToolsVersion.version;264        });265        var appropriateVersion = getHighestAppropriateVersion(msbuildToolsVersions, msbuildRequiredVersion);266        return appropriateVersion ?267            shortenVersion(appropriateVersion) :268            Q.reject('MSBuild tools v.' + shortenVersion(msbuildRequiredVersion) + ' not found. ' +269                'Please install Visual Studio ' + mapVSVersionToName(getMinimalRequiredVersionFor('visualstudio')) +270                ' from https://www.visualstudio.com/downloads/download-visual-studio-vs');271    });272};273var checkVS = function () {274    var vsRequiredVersion = getMinimalRequiredVersionFor('visualstudio');275    return getInstalledVSVersions()276    .then(function (installedVersions) {277        var appropriateVersion = getHighestAppropriateVersion(installedVersions, vsRequiredVersion);278        return appropriateVersion ?279            shortenVersion(appropriateVersion) :280            Q.reject('Required version of Visual Studio not found. Please install Visual Studio ' +281                mapVSVersionToName(vsRequiredVersion) +282                ' from https://www.visualstudio.com/downloads/download-visual-studio-vs');283    });284};285var checkWinSdk = function () {286    return getInstalledWindowsSdks()287    .then(function (installedSdks) {288        var requiredVersion = getMinimalRequiredVersionFor('windowssdk');289        var hasSdkInstalled = installedSdks.some(function (installedSdk) {290            return installedSdk.eq(requiredVersion);291        });292        if (!hasSdkInstalled) {293            return Q.reject('Windows SDK not found. Please ensure that you have installed ' +294                'Windows ' + shortenVersion(requiredVersion) + ' SDK along with Visual Studio or install ' +295                'Windows ' + shortenVersion(requiredVersion) + ' SDK separately from ' +296                'https://dev.windows.com/en-us/downloads');297        }298        return shortenVersion(requiredVersion);299    });300};301var checkPhoneSdk = function () {302    var requiredVersion = getMinimalRequiredVersionFor('phonesdk');303    return getInstalledPhoneSdks()304    .then(function (installedSdks) {305        var requiredVersion = getMinimalRequiredVersionFor('phonesdk');306        var hasSdkInstalled = installedSdks.some(function (installedSdk) {307            return installedSdk.eq(requiredVersion);308        });309        return hasSdkInstalled ?310            shortenVersion(requiredVersion) :311            Q.reject();312    })313    .fail(function () {314        return Q.reject('Windows Phone SDK not found. Please ensure that you have installed ' +315            'Windows Phone ' + shortenVersion(requiredVersion) + ' SDK along with Visual Studio or install ' +316            'Windows Phone ' + shortenVersion(requiredVersion) + ' SDK separately from ' +317            'https://dev.windows.com/develop/download-phone-sdk');318    });319};320module.exports.run = function () {321    return checkOS().then(function () {322        return MSBuildTools.findAvailableVersion();323    });324};325/**326 * Object that represents one of requirements for current platform.327 * @param {String}  id        The unique identifier for this requirements.328 * @param {String}  name      The name of requirements. Human-readable field.329 * @param {Boolean} isFatal   Marks the requirement as fatal. If such requirement will fail330 *                            next requirements' checks will be skipped.331 */332var Requirement = function (id, name, isFatal) {333    this.id = id;334    this.name = name;335    this.installed = false;336    this.metadata = {};337    this.isFatal = isFatal || false;338};339var requirements = [340    new Requirement('os', 'Windows OS', true),341    new Requirement('msbuild', 'MSBuild Tools'),342    new Requirement('visualstudio', 'Visual Studio'),343    new Requirement('windowssdk', 'Windows SDK'),344    new Requirement('phonesdk', 'Windows Phone SDK')345];346// Define list of checks needs to be performed347var checkFns = [checkOS, checkMSBuild, checkVS, checkWinSdk, checkPhoneSdk];348/**349 * Methods that runs all checks one by one and returns a result of checks350 * as an array of Requirement objects. This method intended to be used by cordova-lib check_reqs method.351 * @return Promise<Requirement[]> Array of requirements. Due to implementation, promise is always fulfilled.352 */353module.exports.check_all = function() {354    var result = [];355    var fatalIsHit = false;356    // Then execute requirement checks one-by-one357    return checkFns.reduce(function (promise, checkFn, idx) {358        return promise.then(function () {359            // If fatal requirement is failed,360            // we don't need to check others361            if (fatalIsHit) return Q();362            var requirement = requirements[idx];363            return checkFn()364            .then(function (version) {365                requirement.installed = true;366                requirement.metadata.version = version;367                result.push(requirement);368            }, function (err) {369                if (requirement.isFatal) fatalIsHit = true;370                requirement.metadata.reason = err;371                result.push(requirement);372            });373        });374    }, Q())375    .then(function () {376        // When chain is completed, return requirements array to upstream API377        return result;378    });379};380module.exports.help = function () {381    console.log('Usage: check_reqs or node check_reqs');...

Full Screen

Full Screen

Version.js

Source:Version.js Github

copy

Full Screen

1/**2 * @author Jacky Nguyen <jacky@sencha.com>3 * @docauthor Jacky Nguyen <jacky@sencha.com>4 * @class Ext.Version5 *6 * A utility class that wrap around a string version number and provide convenient7 * method to perform comparison. See also: {@link Ext.Version#compare compare}. Example:8    var version = new Ext.Version('1.0.2beta');9    console.log("Version is " + version); // Version is 1.0.2beta10    console.log(version.getMajor()); // 111    console.log(version.getMinor()); // 012    console.log(version.getPatch()); // 213    console.log(version.getBuild()); // 014    console.log(version.getRelease()); // beta15    console.log(version.isGreaterThan('1.0.1')); // True16    console.log(version.isGreaterThan('1.0.2alpha')); // True17    console.log(version.isGreaterThan('1.0.2RC')); // False18    console.log(version.isGreaterThan('1.0.2')); // False19    console.log(version.isLessThan('1.0.2')); // True20    console.log(version.match(1.0)); // True21    console.log(version.match('1.0.2')); // True22 * @markdown23 */24(function() {25// Current core version26var version = '4.1.0', Version;27    Ext.Version = Version = Ext.extend(Object, {28        /**29         * Creates new Version object.30         * @param {String/Number} version The version number in the follow standard format: major[.minor[.patch[.build[release]]]]31         * Examples: 1.0 or 1.2.3beta or 1.2.3.4RC32         * @return {Ext.Version} this33         */34        constructor: function(version) {35            var toNumber = this.toNumber,36                parts, releaseStartIndex;37            if (version instanceof Version) {38                return version;39            }40            this.version = this.shortVersion = String(version).toLowerCase().replace(/_/g, '.').replace(/[\-+]/g, '');41            releaseStartIndex = this.version.search(/([^\d\.])/);42            if (releaseStartIndex !== -1) {43                this.release = this.version.substr(releaseStartIndex, version.length);44                this.shortVersion = this.version.substr(0, releaseStartIndex);45            }46            this.shortVersion = this.shortVersion.replace(/[^\d]/g, '');47            parts = this.version.split('.');48            this.major = toNumber(parts.shift());49            this.minor = toNumber(parts.shift());50            this.patch = toNumber(parts.shift());51            this.build = toNumber(parts.shift());52            return this;53        },54        toNumber: function(value) {55            value = parseInt(value || 0, 10);56            if (isNaN(value)) {57                value = 0;58            }59            return value;60        },61        /**62         * Override the native toString method63         * @private64         * @return {String} version65         */66        toString: function() {67            return this.version;68        },69        /**70         * Override the native valueOf method71         * @private72         * @return {String} version73         */74        valueOf: function() {75            return this.version;76        },77        /**78         * Returns the major component value79         * @return {Number} major80         */81        getMajor: function() {82            return this.major || 0;83        },84        /**85         * Returns the minor component value86         * @return {Number} minor87         */88        getMinor: function() {89            return this.minor || 0;90        },91        /**92         * Returns the patch component value93         * @return {Number} patch94         */95        getPatch: function() {96            return this.patch || 0;97        },98        /**99         * Returns the build component value100         * @return {Number} build101         */102        getBuild: function() {103            return this.build || 0;104        },105        /**106         * Returns the release component value107         * @return {Number} release108         */109        getRelease: function() {110            return this.release || '';111        },112        /**113         * Returns whether this version if greater than the supplied argument114         * @param {String/Number} target The version to compare with115         * @return {Boolean} True if this version if greater than the target, false otherwise116         */117        isGreaterThan: function(target) {118            return Version.compare(this.version, target) === 1;119        },120        /**121         * Returns whether this version if greater than or equal to the supplied argument122         * @param {String/Number} target The version to compare with123         * @return {Boolean} True if this version if greater than or equal to the target, false otherwise124         */125        isGreaterThanOrEqual: function(target) {126            return Version.compare(this.version, target) >= 0;127        },128        /**129         * Returns whether this version if smaller than the supplied argument130         * @param {String/Number} target The version to compare with131         * @return {Boolean} True if this version if smaller than the target, false otherwise132         */133        isLessThan: function(target) {134            return Version.compare(this.version, target) === -1;135        },136        /**137         * Returns whether this version if less than or equal to the supplied argument138         * @param {String/Number} target The version to compare with139         * @return {Boolean} True if this version if less than or equal to the target, false otherwise140         */141        isLessThanOrEqual: function(target) {142            return Version.compare(this.version, target) <= 0;143        },144        /**145         * Returns whether this version equals to the supplied argument146         * @param {String/Number} target The version to compare with147         * @return {Boolean} True if this version equals to the target, false otherwise148         */149        equals: function(target) {150            return Version.compare(this.version, target) === 0;151        },152        /**153         * Returns whether this version matches the supplied argument. Example:154         * <pre><code>155         * var version = new Ext.Version('1.0.2beta');156         * console.log(version.match(1)); // True157         * console.log(version.match(1.0)); // True158         * console.log(version.match('1.0.2')); // True159         * console.log(version.match('1.0.2RC')); // False160         * </code></pre>161         * @param {String/Number} target The version to compare with162         * @return {Boolean} True if this version matches the target, false otherwise163         */164        match: function(target) {165            target = String(target);166            return this.version.substr(0, target.length) === target;167        },168        /**169         * Returns this format: [major, minor, patch, build, release]. Useful for comparison170         * @return {Number[]}171         */172        toArray: function() {173            return [this.getMajor(), this.getMinor(), this.getPatch(), this.getBuild(), this.getRelease()];174        },175        /**176         * Returns shortVersion version without dots and release177         * @return {String}178         */179        getShortVersion: function() {180            return this.shortVersion;181        },182        /**183         * Convenient alias to {@link Ext.Version#isGreaterThan isGreaterThan}184         * @param {String/Number} target185         * @return {Boolean}186         */187        gt: function() {188            return this.isGreaterThan.apply(this, arguments);189        },190        /**191         * Convenient alias to {@link Ext.Version#isLessThan isLessThan}192         * @param {String/Number} target193         * @return {Boolean}194         */195        lt: function() {196            return this.isLessThan.apply(this, arguments);197        },198        /**199         * Convenient alias to {@link Ext.Version#isGreaterThanOrEqual isGreaterThanOrEqual}200         * @param {String/Number} target201         * @return {Boolean}202         */203        gtEq: function() {204            return this.isGreaterThanOrEqual.apply(this, arguments);205        },206        /**207         * Convenient alias to {@link Ext.Version#isLessThanOrEqual isLessThanOrEqual}208         * @param {String/Number} target209         * @return {Boolean}210         */211        ltEq: function() {212            return this.isLessThanOrEqual.apply(this, arguments);213        }214    });215    Ext.apply(Version, {216        // @private217        releaseValueMap: {218            'dev': -6,219            'alpha': -5,220            'a': -5,221            'beta': -4,222            'b': -4,223            'rc': -3,224            '#': -2,225            'p': -1,226            'pl': -1227        },228        /**229         * Converts a version component to a comparable value230         *231         * @static232         * @param {Object} value The value to convert233         * @return {Object}234         */235        getComponentValue: function(value) {236            return !value ? 0 : (isNaN(value) ? this.releaseValueMap[value] || value : parseInt(value, 10));237        },238        /**239         * Compare 2 specified versions, starting from left to right. If a part contains special version strings,240         * they are handled in the following order:241         * 'dev' < 'alpha' = 'a' < 'beta' = 'b' < 'RC' = 'rc' < '#' < 'pl' = 'p' < 'anything else'242         *243         * @static244         * @param {String} current The current version to compare to245         * @param {String} target The target version to compare to246         * @return {Number} Returns -1 if the current version is smaller than the target version, 1 if greater, and 0 if they're equivalent247         */248        compare: function(current, target) {249            var currentValue, targetValue, i;250            current = new Version(current).toArray();251            target = new Version(target).toArray();252            for (i = 0; i < Math.max(current.length, target.length); i++) {253                currentValue = this.getComponentValue(current[i]);254                targetValue = this.getComponentValue(target[i]);255                if (currentValue < targetValue) {256                    return -1;257                } else if (currentValue > targetValue) {258                    return 1;259                }260            }261            return 0;262        }263    });264    Ext.apply(Ext, {265        /**266         * @private267         */268        versions: {},269        /**270         * @private271         */272        lastRegisteredVersion: null,273        /**274         * Set version number for the given package name.275         *276         * @param {String} packageName The package name, for example: 'core', 'touch', 'extjs'277         * @param {String/Ext.Version} version The version, for example: '1.2.3alpha', '2.4.0-dev'278         * @return {Ext}279         */280        setVersion: function(packageName, version) {281            Ext.versions[packageName] = new Version(version);282            Ext.lastRegisteredVersion = Ext.versions[packageName];283            return this;284        },285        /**286         * Get the version number of the supplied package name; will return the last registered version287         * (last Ext.setVersion call) if there's no package name given.288         *289         * @param {String} packageName (Optional) The package name, for example: 'core', 'touch', 'extjs'290         * @return {Ext.Version} The version291         */292        getVersion: function(packageName) {293            if (packageName === undefined) {294                return Ext.lastRegisteredVersion;295            }296            return Ext.versions[packageName];297        },298        /**299         * Create a closure for deprecated code.300         *301    // This means Ext.oldMethod is only supported in 4.0.0beta and older.302    // If Ext.getVersion('extjs') returns a version that is later than '4.0.0beta', for example '4.0.0RC',303    // the closure will not be invoked304    Ext.deprecate('extjs', '4.0.0beta', function() {305        Ext.oldMethod = Ext.newMethod;306        ...307    });308         * @param {String} packageName The package name309         * @param {String} since The last version before it's deprecated310         * @param {Function} closure The callback function to be executed with the specified version is less than the current version311         * @param {Object} scope The execution scope (<tt>this</tt>) if the closure312         * @markdown313         */314        deprecate: function(packageName, since, closure, scope) {315            if (Version.compare(Ext.getVersion(packageName), since) < 1) {316                closure.call(scope);317            }318        }319    }); // End Versioning320    Ext.setVersion('core', version);...

Full Screen

Full Screen

index.js

Source:index.js Github

copy

Full Screen

1var _               = require('underscore'),2    when            = require('when'),3    series          = require('when/sequence'),4    errors          = require('../../errorHandling'),5    knex            = require('../../models/base').knex,6    defaultSettings = require('../default-settings'),7    Settings        = require('../../models/settings').Settings,8    fixtures        = require('../fixtures'),9    initialVersion  = '000',10    defaultDatabaseVersion;11// Default Database Version12// The migration version number according to the hardcoded default settings13// This is the version the database should be at or migrated to14function getDefaultDatabaseVersion() {15    if (!defaultDatabaseVersion) {16        // This be the current version according to the software17        defaultDatabaseVersion = _.find(defaultSettings.core, function (setting) {18            return setting.key === 'databaseVersion';19        }).defaultValue;20    }21    return defaultDatabaseVersion;22}23// Database Current Version24// The migration version number according to the database25// This is what the database is currently at and may need to be updated26function getDatabaseVersion() {27    return knex.schema.hasTable('settings').then(function (exists) {28        // Check for the current version from the settings table29        if (exists) {30            // Temporary code to deal with old databases with currentVersion settings31            return knex('settings')32                .where('key', 'databaseVersion')33                .orWhere('key', 'currentVersion')34                .select('value')35                .then(function (versions) {36                    var databaseVersion = _.reduce(versions, function (memo, version) {37                        if (isNaN(version.value)) {38                            errors.throwError('Database version is not recognised');39                        }40                        return parseInt(version.value, 10) > parseInt(memo, 10) ? version.value : memo;41                    }, initialVersion);42                    if (!databaseVersion || databaseVersion.length === 0) {43                        // we didn't get a response we understood, assume initialVersion44                        databaseVersion = initialVersion;45                    }46                    return databaseVersion;47                });48        }49        return when.reject('Settings table does not exist');50    });51}52function setDatabaseVersion() {53    return knex('settings')54        .where('key', 'databaseVersion')55        .update({ 'value': defaultDatabaseVersion });56}57module.exports = {58    getDatabaseVersion: getDatabaseVersion,59    // Check for whether data is needed to be bootstrapped or not60    init: function () {61        var self = this;62        // There are 4 possibilities:63        // 1. The database exists and is up-to-date64        // 2. The database exists but is out of date65        // 3. The database exists but the currentVersion setting does not or cannot be understood66        // 4. The database has not yet been created67        return getDatabaseVersion().then(function (databaseVersion) {68            var defaultVersion = getDefaultDatabaseVersion();69            if (databaseVersion === defaultVersion) {70                // 1. The database exists and is up-to-date71                return when.resolve();72            }73            if (databaseVersion < defaultVersion) {74                // 2. The database exists but is out of date75                return self.migrateUpFromVersion(databaseVersion);76            }77            if (databaseVersion > defaultVersion) {78                // 3. The database exists but the currentVersion setting does not or cannot be understood79                // In this case we don't understand the version because it is too high80                errors.logErrorAndExit(81                    'Your database is not compatible with this version of Ghost',82                    'You will need to create a new database'83                );84            }85        }, function (err) {86            if (err === 'Settings table does not exist') {87                // 4. The database has not yet been created88                // Bring everything up from initial version.89                return self.migrateUpFreshDb();90            }91            // 3. The database exists but the currentVersion setting does not or cannot be understood92            // In this case the setting was missing or there was some other problem93            errors.logErrorAndExit('There is a problem with the database', err.message || err);94        });95    },96    // ### Reset97    // Migrate from where we are down to nothing.98    reset: function () {99        var self = this;100        return getDatabaseVersion().then(function (databaseVersion) {101            // bring everything down from the current version102            return self.migrateDownFromVersion(databaseVersion);103        }, function () {104            // If the settings table doesn't exist, bring everything down from initial version.105            return self.migrateDownFromVersion(initialVersion);106        });107    },108    // Only do this if we have no database at all109    migrateUpFreshDb: function () {110        var migration = require('./' + initialVersion);111        return migration.up().then(function () {112            // Load the fixtures113            return fixtures.populateFixtures();114        }).then(function () {115            // Initialise the default settings116            return Settings.populateDefaults();117        });118    },119    // Migrate from a specific version to the latest120    migrateUpFromVersion: function (version, max) {121        var versions = [],122            maxVersion = max || this.getVersionAfter(getDefaultDatabaseVersion()),123            currVersion = version,124            tasks = [];125        // Aggregate all the versions we need to do migrations for126        while (currVersion !== maxVersion) {127            versions.push(currVersion);128            currVersion = this.getVersionAfter(currVersion);129        }130        // Aggregate all the individual up calls to use in the series(...) below131        tasks = _.map(versions, function (taskVersion) {132            return function () {133                try {134                    var migration = require('./' + taskVersion);135                    return migration.up();136                } catch (e) {137                    errors.logError(e);138                    return when.reject(e);139                }140            };141        });142        // Run each migration in series143        return series(tasks).then(function () {144            // Finally update the databases current version145            return setDatabaseVersion();146        });147    },148    migrateDownFromVersion: function (version) {149        var self = this,150            versions = [],151            minVersion = this.getVersionBefore(initialVersion),152            currVersion = version,153            tasks = [];154        // Aggregate all the versions we need to do migrations for155        while (currVersion !== minVersion) {156            versions.push(currVersion);157            currVersion = this.getVersionBefore(currVersion);158        }159        // Aggregate all the individual up calls to use in the series(...) below160        tasks = _.map(versions, function (taskVersion) {161            return function () {162                try {163                    var migration = require('./' + taskVersion);164                    return migration.down();165                } catch (e) {166                    errors.logError(e);167                    return self.migrateDownFromVersion(initialVersion);168                }169            };170        });171        // Run each migration in series172        return series(tasks);173    },174    // Get the following version based on the current175    getVersionAfter: function (currVersion) {176        var currVersionNum = parseInt(currVersion, 10),177            nextVersion;178        // Default to initialVersion if not parsed179        if (isNaN(currVersionNum)) {180            currVersionNum = parseInt(initialVersion, 10);181        }182        currVersionNum += 1;183        nextVersion = String(currVersionNum);184        // Pad with 0's until 3 digits185        while (nextVersion.length < 3) {186            nextVersion = "0" + nextVersion;187        }188        return nextVersion;189    },190    getVersionBefore: function (currVersion) {191        var currVersionNum = parseInt(currVersion, 10),192            prevVersion;193        if (isNaN(currVersionNum)) {194            currVersionNum = parseInt(initialVersion, 10);195        }196        currVersionNum -= 1;197        prevVersion = String(currVersionNum);198               // Pad with 0's until 3 digits199        while (prevVersion.length < 3) {200            prevVersion = "0" + prevVersion;201        }202        return prevVersion;203    }...

Full Screen

Full Screen

Automation Testing Tutorials

Learn to execute automation testing from scratch with LambdaTest Learning Hub. Right from setting up the prerequisites to run your first automation test, to following best practices and diving deeper into advanced test scenarios. LambdaTest Learning Hubs compile a list of step-by-step guides to help you be proficient with different test automation frameworks i.e. Selenium, Cypress, TestNG etc.

LambdaTest Learning Hubs:

YouTube

You could also refer to video tutorials over LambdaTest YouTube channel to get step by step demonstration from industry experts.

Run Airtest automation tests on LambdaTest cloud grid

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

Try LambdaTest Now !!

Get 100 minutes of automation test minutes FREE!!

Next-Gen App & Browser Testing Cloud

Was this article helpful?

Helpful

NotHelpful