// Slice the specified number of dotted parts from the given semver version. // e.g. slice('2.4.7', 'minor') -> '2.4' function slice(v, releaseType) { if (! semver.valid(v)) { return null; } const major = semver.major(v); const minor = semver.minor(v); const patch = semver.patch(v); const prerelease = semver.prerelease(v); const dottedParts = { major: [major], minor: [major, minor], patch: [major, minor, patch], }[releaseType]; if (dottedParts === undefined) { throw Error(`Unknown releaseType: ${releaseType}`); } const dotted = dottedParts.join('.'); if (prerelease) { return `${dotted}-${prerelease.join('.')}`; } else { return dotted; } }
npm.packages.range('react-native-windows', version, (err, release) => { if (err || !release) { return getLatestVersion() .then(latestVersion => { reject(new Error(`Could not find react-native-windows@${version}. ` + `Latest version of react-native-windows is ${latestVersion}, try switching to ` + `react-native@${semver.major(latestVersion)}.${semver.minor(latestVersion)}.*.`)); }).catch(error => reject(new Error(`Could not find react-native-windows@${version}.`))); } const matchedVersion = release.version; const matchedPrerelease = semver.prerelease(matchedVersion); const isPrerelease = tag && !!matchedPrerelease; if (!isVersionMatch(matchedVersion, version, tag) && (ignoreStable || isPrerelease)) { const versions = Object.keys(release.versions); const candidates = versions.filter(v => isVersionMatch(v, version, tag)).sort(semver.rcompare); if (candidates.length === 0) { const tagMatches = versions.filter(v => isTagMatch(v, tag)).sort(semver.rcompare); if (tagMatches.length === 0) { reject(new Error(`Could not find react-native-windows@${version}-${tag}.*.`)); } else { const latestVersion = tagMatches[0]; reject(new Error(`Could not find react-native-windows@${version}-${tag}.*. ` + `Latest version of react-native-windows for tag '${tag}' is ${latestVersion}, try switching to ` + `react-native@${semver.major(latestVersion)}.${semver.minor(latestVersion)}.*.`)); } } resolve(candidates[0]); } else { resolve(matchedVersion); } });
const getReactNativeVersion = function () { console.log('Reading react-native version from node_modules...'); if (fs.existsSync(REACT_NATIVE_PACKAGE_JSON_PATH())) { const version = JSON.parse(fs.readFileSync(REACT_NATIVE_PACKAGE_JSON_PATH(), 'utf-8')).version; return `${semver.major(version)}.${semver.minor(version)}.*`; } };
/** * Given a semver version, determine the type of version. * @param {string} version A semver version string. * @returns {string} The type of version. * @private */ function getReleaseType(version) { if (semver.patch(version) > 0) { return "patch"; } else if (semver.minor(version) > 0) { return "minor"; } else { return "major"; } }
grunt.registerTask('configure_videojs', function(releaseType='patch'){ // Get version info var vjsPackage = grunt.file.readJSON('node_modules/video.js/package.json'); var vjsVersion = vjsPackage.version; var swfVersion = vjsPackage.dependencies['videojs-swf']; var fontVersion = vjsPackage.dependencies['videojs-font']; // Check for a dynamic version, e.g. '^1.0.0' or '~1.0.0' // Hosted dependencies should be locked down to a specific version if (!fontVersion || /^\d/.test(fontVersion) !== true) { throw new Error('The video.js font version does not exist or is not locked down'); } if (!swfVersion || /^\d/.test(swfVersion) !== true) { throw new Error('The video.js swf version does not exist or is not locked down'); } // Set up the release type versions var cdnVersions = {}; cdnVersions.major = semver.major(vjsVersion); cdnVersions.minor = cdnVersions.major + '.' + semver.minor(vjsVersion); cdnVersions.patch = vjsVersion; // Get the source var vjs = grunt.file.read('build/temp/video.js/video.js'); var vjsMin = grunt.file.read('build/temp/video.js/video.min.js'); var cdnjs = grunt.file.read('build/temp/cdn.min.js'); // Update the cdn version and concat with video.js source cdnjs = cdnjs.replace('__CDN_VERSION__', cdnVersions[releaseType]); // Update the swf version to build the swf CDN url cdnjs = cdnjs.replace('__SWF_VERSION__', swfVersion); // Concat the CDN js to the video.js copies vjs = vjs + '\n' + cdnjs; vjsMin = vjsMin + '\n' + cdnjs; // Write the new source files grunt.file.write('build/temp/video.js/video.js', vjs); grunt.file.write('build/temp/video.js/video.min.js', vjsMin); var css = grunt.file.read('build/temp/video.js/video-js.css'); var cssMin = grunt.file.read('build/temp/video.js/video-js.min.css'); // Replace the font urls with CDN font urls // whether we're getting '../fonts/' or 'font/' var re = /font\/VideoJS\./g; var replaceWith = '../font/'+fontVersion+'/VideoJS.'; css = css.replace(re, replaceWith); cssMin = cssMin.replace(re, replaceWith); grunt.file.write('build/temp/video.js/video-js.css', css); grunt.file.write('build/temp/video.js/video-js.min.css', cssMin); });
function createShorthand(range) { var match = regex.minMax.exec(range); if (!match) { return range; } var _match$slice = match.slice(1), _match$slice2 = _slicedToArray(_match$slice, 2), min = _match$slice2[0], max = _match$slice2[1]; if (min === max) { // Exact range return min; } // Special handling for major version 0 if (semver.major(min) === 0 && semver.major(max) === 0) { // ^0.0.5 if (semver.minor(min) === 0 && semver.minor(max) === 0) { return `^${min}`; } // ~0.0.5 if (semver.minor(min) === 0) { return `~${min}`; } // ^0.5.0 return `^${min}`; } if (semver.major(min) !== semver.major(max)) { if (semver.major(min) === 0) { return '0'; } return `^${min}`; } return `~${min}`; }
.then(function () { let version = { major: semver.major(originVer), minor: semver.minor(originVer), patch: semver.patch(originVer) } version[type] += 1 getPackageVersion().should.equal(version.major + '.' + version.minor + '.' + version.patch + '-' + type + '.0') })
_pullDappHub (opts, target) { var _web3; if (opts.web3 === 'internal') { throw new Error('DappHub registry is not available on internal chains.'); } else { try { _web3 = req.Web3Factory.JSONRPC({web3: opts.web3}); } catch (e) { try { _web3 = req.Web3Factory.JSONRPC({web3: {host: '104.236.215.91', port: 8545}}); } catch (e) { throw new Error('Unable to connect to Ethereum client: ' + e); } } } // TODO - iterate through the list let address = opts.environment.registries[0]; let registryClass = Dapphub.getClasses().DappHubSimpleController; let dbClass = Dapphub.getClasses().DappHubDB; let dapphub = _web3.eth.contract(JSON.parse(registryClass.interface)).at(address); let dapphubdbAddress = dapphub._package_db(); let dapphubdb = _web3.eth.contract(JSON.parse(dbClass.interface)).at(dapphubdbAddress); // let dapphub = new req.dapphub.Class(_web3, 'morden'); if (this.getVersion() === 'latest') { this.path = this.getName(); this.version = dapphubdb.getLastVersion.call(this.getPath()).join('.'); } // TODO - DEBUG why the f**k this takes so long to call let packageHash = dapphubdb.getPackageHash.call( this.getPath(), semver.major(this.getVersion()), semver.minor(this.getVersion()), semver.patch(this.getVersion())); if (!packageHash || /^0x0?$/.test(packageHash)) { throw new Error('No IPFS hash found for ' + this.getPath() + '@' + this.getVersion()); } let packageHeaderHash = _web3.toAscii(packageHash); console.log(`package id: ${packageHeaderHash}`); if (!this.__ipfs) { let settings = req.Workspace.getDappleRC().environment('live'); // f**k you semistandard let Ipfs = req.ipfs; this.__ipfs = new Ipfs(settings); } let header = this.__ipfs.catJsonSync(packageHeaderHash); // TODO - recursively get the dependencies and install the as well this._pullIPFS(header.root, target); console.log('rdy'); }
var releases = releaseLinks.map(function(el) { // Trim the href attribute of leading "v" and trailing slash var releaseVersion = el.innerHTML.trim().replace(/^v/, '').replace(/\/$/, ''); var docsVersion = semver.major(releaseVersion) + '.' + semver.minor(releaseVersion); return { version: releaseVersion, docs: docsVersion, // Add repo for use in async.each call below repo: target.repo }; });
const shouldBumpPrerelease = (releaseType, version) => { if (!semver.prerelease(version)) { return true; } switch (releaseType) { case "major": return semver.minor(version) !== 0 || semver.patch(version) !== 0; case "minor": return semver.patch(version) !== 0; default: return false; } };
function getSemVerAppConfigs( version ) { if ( !semver.valid( version ) ) { return null; } var major = semver.major( version ); var minor = semver.minor( version ); return { major: 'appconfig.v' + major + '.json.gz', majorMinor: 'appconfig.v' + major + '.' + minor + '.json.gz' }; }
function getZeroDotDates (version /* : number | string */) { if (typeof version === 'number') { // make an assumption that 0.10.x is more likely / useful than 0.1.x version = version === 0.1 ? '0.10.0' : version + '.0' } if (version && typeof version === 'string') { version = semver.major(version) + '.' + semver.minor(version) return { release: new Date(Date.parse(versions[version].release)), end: new Date(Date.parse(versions[version].end)) } } }
Dependency.prototype.updateTo = function () { if (_.startsWith(this.current, '^')) { return '^' + this.latest; } else if (_.startsWith(this.current, '~')) { return '~' + this.latest; } else if (_.startsWith(this.current, '>=')) { return '>=' + this.latest; } else if (_.startsWith(this.current, '>')) { return '>' + this.latest; } else if (_.startsWith(this.current, 'v')) { return 'v' + this.latest; } else if (_.endsWith(this.current, '.x.x')) { return semver.major(this.latest) + '.x.x'; } else if (_.endsWith(this.current, '.x')) { return semver.major(this.latest) + '.' + semver.minor(this.latest) + '.x'; } else if (this.current.split('.').length === 2) { return semver.major(this.latest) + '.' + semver.minor(this.latest); } else if (this.current.split('.').length === 1) { return semver.major(this.latest); } else { return this.latest; } };
module.exports = function () { // Chromedriver should be specified as ~x.y where x and y match Electron major/minor const chromedriverVer = buildMetadata.dependencies['electron-chromedriver'] // Always use tilde on electron-chromedriver so that it can pick up the best patch vesion if (!chromedriverVer.startsWith('~')) { throw new Error(`electron-chromedriver version in script/package.json should start with a tilde to match latest patch version.`) } const electronVer = CONFIG.appMetadata.electronVersion if (!semver.satisfies(electronVer, chromedriverVer)) { throw new Error(`electron-chromedriver ${chromedriverVer} incompatible with electron ${electronVer}.\n` + 'Did you upgrade electron in package.json and forget to upgrade electron-chromedriver in ' + `script/package.json to '~${semver.major(electronVer)}.${semver.minor(electronVer)}' ?`) } }
a.forEach(asset => { // get the asset version console.log(asset.data().path); const version = asset.get('version'); // Update the document by merging in the new fields updatePromises.push( asset.ref.set({ version_major: semver.major(version), version_minor: semver.minor(version), version_patch: semver.patch(version), version_metadata: '', version_pre_release: semver.prerelease(version) || '' }, { merge: true }) ); });
command: function () { function createUploadCommand (version) { return ['mv dist ' + version, 'scp -i ~/.ssh/fuelcdn -r "' + version + '"/ ' + '<%= cdnLoginFile.user %>' + '@' + '<%= cdnLoginFile.server %>' + ':' + '<%= cdnLoginFile.folder %>', 'mv "' + version + '" dist', 'echo "Done uploading files."'].join(' && '); } var command = [ getPackage().version, semver.major(getPackage().version) + '.' + semver.minor(getPackage().version), semver.major(getPackage().version) ].map(createUploadCommand).join(' && '); grunt.log.write('Uploading: ' + command); grunt.log.writeln(''); return command; }
export const prettifyVersion = (version: string): string => { if (typeof version !== "string") { return version; } const parts = [semver.major(version)]; const minor = semver.minor(version); const patch = semver.patch(version); if (minor || patch) { parts.push(minor); } if (patch) { parts.push(patch); } return parts.join("."); };
function new_version(ver, cmd, setver) { if (cmd.match(/^[\.\d]+$/)) { ver = cmd; } else if (cmd === 'show') { console.log(ver); } else if (setver) { if (cmd === "patch") { ver = semver.major(ver) + "." + semver.minor(ver) + "." + setver; } else { throw new Error("Only supports setting version for patch"); } } else { ver = semver.inc(ver, cmd, null, 12); } return ver; }
_pullDappHub (web3Settings, target) { var web3; if (web3Settings === 'internal') { throw new Error('DappHub registry is not available on internal chains.'); } else { try { web3 = req.Web3Factory.JSONRPC({web3: web3Settings}); } catch (e) { try { web3 = req.Web3Factory.JSONRPC({web3: {host: '104.236.215.91', port: 8545 }}); } catch(e) { throw new Error('Unable to connect to Ethereum client: ' + e); } } } let dapphub = new req.dapphub.Class(web3, 'morden'); // TODO - DEBUG why the f**k this takes so long to call let packageHash = dapphub.objects.dapphubdb.getPackageHash.call( this.getPath(), semver.major(this.getVersion()), semver.minor(this.getVersion()), semver.patch(this.getVersion())); if (!packageHash || /^0x0?$/.test(packageHash)) { throw new Error('No IPFS hash found for ' + this.getPath() + '@' + this.getVersion()); } let packageHeaderHash = web3.toAscii(packageHash); if (!this.__ipfs) { let settings = req.Workspace.getDappleRC().environment('live'); // f**k you semistandard let Ipfs = req.ipfs; this.__ipfs = new Ipfs(settings); } let header = this.__ipfs.catJsonSync(packageHeaderHash); // TODO - recursively get the dependencies and install the as well this._pullIPFS(header.root, target); }
return function receiveIncomingSailsIOMsg(options) { app.log.verbose('Receiving incoming message from Socket.io: ', options.incomingSailsIOMsg); // If invalid callback function specified, freak out // (it's ok to NOT include a callback, but if it exists, it should be a function) if (options.socketIOClientCallback && !_.isFunction(options.socketIOClientCallback)) { delete options.socketIOClientCallback; return respondWithParseError('Could not parse request- callback may be omitted... but if provided, it must be a function.'); } // Check that URL is specified if (!options.incomingSailsIOMsg.url) { return respondWithParseError(util.format('No url provided in request: %s',options.incomingSailsIOMsg)); } // Check that URL is valid if (!_.isString(options.incomingSailsIOMsg.url)) { return respondWithParseError(util.format('Invalid url provided: %s',options.incomingSailsIOMsg.url)); } // Grab the metadata for the SDK var sdk = parseSdkMetadata(options.socket.handshake); // No more backwards-compatibility for clients < v0.11.0 // > Note that we round off the prerelease part of the SDK version, // > in case there is one. Otherwise, this check will always fail, // > no matter the version. For more information on this, see: // > • https://github.com/npm/node-semver/issues/130#issuecomment-120988399 // > • https://github.com/npm/node-semver/tree/44cbc8482ac4f0f8d2de0abb7f8808056d2d55f9#prerelease-tags var closestStableSdkVersion = semver.major(sdk.version)+'.'+semver.minor(sdk.version)+'.'+semver.patch(sdk.version); if (!semver.satisfies(closestStableSdkVersion, '>=0.11.0')) { return respondWithParseError(util.format('This version of Sails is not compatible with the socket.io/sails.io.js client SDK version you are using (%s). Please see https://sailsjs.com/documentation/upgrading/to-v-0-11 for more information-- then please continue upgrading all the way to the installed version of Sails.',sdk.version)); } // Try to get the express 'trust proxy' setting value var expressTrust; try { expressTrust = app.hooks.http.app.get('trust proxy fn'); } // Something went wrong while retrieving the express settings. Default's to no Trust catch (e) { expressTrust = function () { return false }; } // Dummy express req object so we can use proxy-addr var reqDummy = { connection: { remoteAddress: options.socket.handshake.address }, headers: options.socket.handshake.headers }; var ip = proxyaddr(reqDummy, expressTrust); var ips = proxyaddr.all(reqDummy, expressTrust); // reverse the order (to farthest -> closest) // and remove socket address ips.reverse().pop(); // Start building up the request context which we'll pass into the interpreter in Sails core: var requestContext = { transport: 'socket.io', // TODO: consider if this is really helpful or just a waste of LoC protocol: 'ws', // TODO: consider if this is really helpful or just a waste of LoC isSocket: true, ip : ip, ips : ips, port : null, // Access to underlying SIO socket socket : options.socket, url : options.incomingSailsIOMsg.url, path : url.parse(options.incomingSailsIOMsg.url).pathname || '/', // ^^ Uses || '/' because otherwise url.parse returns `null`, // which is not a string and thus bad when you try to check // .match() of it. method : options.eventName, // Attached data becomes simulated HTTP body (`req.body`) // (allow `params` or `data` to be specified for backwards/sideways-compatibility) body : _.isArray(options.incomingSailsIOMsg.data) ? options.incomingSailsIOMsg.data : _.extend({}, options.incomingSailsIOMsg.params || {}, options.incomingSailsIOMsg.data || {}), // Allow optional headers headers: _.defaults({ host: app.config.host, // Default the "cookie" request header to what was provided in the handshake. cookie: (function (){ var _cookie; try { _cookie = options.socket.handshake.headers.cookie; } catch (e) {} // console.log('REQUEST to "%s %s" IS USING COOKIE:', options.eventName, options.incomingSailsIOMsg.url, _cookie); return _cookie; })(), nosession: options.socket.handshake.headers.nosession ? true : undefined, }, options.incomingSailsIOMsg.headers || {}) }; // app.log.verbose('Interpreting socket.io message as virtual request to "%s %s"...', requestContext.method, requestContext.url); // app.log.verbose('(cookie: %s)', requestContext.headers.cookie); // Set the `origin` header to what was provided in the handshake // (the origin header CANNOT BE OVERRIDDEN by sockets at virtual request-time-- only // upon first connection.) if (requestContext.headers.origin){ // - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - // FUTURE: Further document security reasons why `origin` may not be passed manually // at VR (virtual request) time. Has to do w/ xdomain security concerns. // - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - app.log.verbose('Ignoring provided `origin` header in VR (virtual request) from socket.io: It would not be safe to change `origin` for this socket now!'); } requestContext.headers.origin = (function (){ var _origin; try { _origin = options.socket.handshake.headers.origin; } catch (e){} return _origin; })(); // console.log('handshake:',options.socket.handshake); app.log.verbose('Interpreting socket.io message as VR (virtual request) to "%s %s"...', requestContext.method, requestContext.url); // Start building up the response context which we'll pass into the interpreter in Sails core: var responseContext = { /** * This `_clientCallback` function we provide here will be used by Sails core as a final step * when trying to run methods like `res.send()`. * * Since Socket.io v1.x does not support streaming socket messages out of the box, * currently we'll just use this callback vs passing in a stream (so the client response * stream will just be buffered to build up clientRes.body) * * IMPORTANT: * The `clientRes` provided here is a Readable client response stream, not the same `res` * that is available in userland code. */ _clientCallback: function _clientCallback(clientRes) { // If no cookie was sent initially on the handshake, and a 'set-cookie' exists in response // headers, then save the cookie on the handshake (no need to send extra data over the wire // since we're maintaining a persistent connection on this side, plus this prevents client-side // js from accessing the cookie) // // This allows for anything relying on cookies (e.g. default `req.session` support) // to last as long as the socket connection (i.e. until the browser tab is closed) // // Note that we **STILL GENERATE A COOKIE** using socket.io middleware when the socket // initially connects. This is so that by the time we run the `onConnect` lifecycle event, // it has access to the real session. So in general, this should never fire. // // In the future, we may want to always reset the handshake's cookie based on the `set-cookie` // response header to allow for custom HTTP cookies to work completely via sockets, but that // should be evaluated carefully to avoid unexpected race conditions. try { if (!options.socket.handshake.headers.cookie && clientRes.headers['set-cookie']){ options.socket.handshake.headers.cookie = clientRes.headers['set-cookie'][0]; } } catch (e) { app.log.warn('Could not persist res.headers["set-cookie"] into the socket handshake:',e); } // If socket.io callback does not exist as a valid function, don't bother responding. if (!_.isFunction(options.socketIOClientCallback)) { return; } // Modern behavior // (builds a complete simulation of an HTTP response.) var jwr = { body: clientRes.body }; // Allow headers and status code to be disabled to allow for squeezing // out a little more performance when relevant (and reducing bandwidth usage). // To achieve this, set `sails.config.sockets.sendResponseHeaders=false` and/or // `sails.config.sockets.sendStatusCode=false`. if (app.config.sockets.sendResponseHeaders) { jwr.headers = clientRes.headers; } if (app.config.sockets.sendStatusCode) { jwr.statusCode = clientRes.statusCode; } // Remove 'set-cookie' header // (to prevent cookie from reaching client-side js) delete jwr.headers['set-cookie']; // TODO: // Try out http://socket.io/blog/introducing-socket-io-1-0/#socket.io-stream // to explore how we could make it work with Sails. // (the old way in 0.9 was streams1 style, just emitting `data` and `end` messages) // Send down response. options.socketIOClientCallback(jwr); return; } }; // Finally, lob a virtual request at the interpreter app.router.route(requestContext, responseContext); /** * Send a parse error back over the socket. * If a callback was provided by the socket.io client, it will be used, * but otherwise a low-level event will be emitted (since otherwise there's * no way to communicate with the client) * * Relies on closure scope for `options` and `app`. */ function respondWithParseError (detailedErrorMsg) { var error = ERRORPACK.PARSE_VIRTUAL_REQ('Failed to parse incoming socket.io request.'); error.details = detailedErrorMsg; // Log parse error app.log.error(error); // If callback is invalid or non-existent: if ( !_.isFunction(options.socketIOClientCallback) ) { // Emit parse error options.socket.emit('sails:parseError', error); return; } // Otherwise just send the error directly to the callback... return options.socketIOClientCallback(error); } };
/* @flow */ /* eslint-disable import/no-commonjs, import/no-nodejs-modules */ const { execSync } = require('child_process'); const semver = require('semver'); const isBetaVersion = require('../../../build/isBetaVersion'); const packageInfo = require('../../../package.json'); const announcementsSubreddit /*: string */ = 'RESAnnouncements'; const name /*: string */ = packageInfo.title; const version /*: string */ = packageInfo.version; const isBeta /*: boolean */ = isBetaVersion(version); const isPatch /*: boolean */ = semver.patch(version) !== 0; const isMinor /*: boolean */ = !isPatch && semver.minor(version) !== 0; const isMajor /*: boolean */ = !isPatch && !isMinor && semver.major(version) !== 0; const updatedURL /*: string */ = isBeta ? // link to the release listing page instead of a specific release page // so if someone goes from the previous version to a hotfix (e.g. 5.10.3 -> 5.12.1) // they see the big release notes for the minor release in addition to the changes in the hotfix `https://redditenhancementsuite.com/releases/beta/#v${version}` : `https://redditenhancementsuite.com/releases/#v${version}`; const homepageURL /*: string */ = packageInfo.homepage; const gitDescription /*: string */ = execSync('git describe', { encoding: 'utf8' }).trim(); module.exports = { announcementsSubreddit, name, version, isBeta, isPatch, isMinor,
ready: this.ready.bind(this) }) this.subscriptions.add(this.locator) return this.locator }, ready () { return true }, getEnvironment () { return Object.assign({}, process.env) }, version () { return semver.major(atom.appVersion) + '.' + semver.minor(atom.appVersion) + '.' + semver.patch(atom.appVersion) }, provide () { return this.get100Implementation() }, provide010 () { return this.get010Implementation() }, get100Implementation () { let executor = this.getExecutor() let locator = this.getLocator() return { executor: {
.then(latestVersion => { reject(new Error(`Could not find react-native-windows@${version}. ` + `Latest version of react-native-windows is ${latestVersion}, try switching to ` + `react-native@${semver.major(latestVersion)}.${semver.minor(latestVersion)}.*.`)); }).catch(error => reject(new Error(`Could not find react-native-windows@${version}.`)));
exports.getLatestVersion((error, latest) => { if (error) return callback(error, null) return callback(null, SemVer.minor(latest)) })
exports.getCurrentMinor = function () { return SemVer.minor(version) }
'use strict'; const _ = require('lodash'); const execSync = require('child_process').execSync; const fs = require('fs'); const semver = require('semver'); // Mocked in tests let version = process.version; let semVersion = semver.major(process.version) + '.' + semver.minor(process.version) + '.' + semver.patch(process.version); let platform = process.platform; let arch = process.arch; let distro = ''; let release = ''; let fips = ''; if (process.versions.openssl.indexOf('fips') !== -1) { // When in fips mode include `fips` as a match condition fips = 'fips'; } if (fs.existsSync('/etc/os-release')) { const osRelease = fs.readFileSync('/etc/os-release', 'utf8'); distro = osRelease.match(/\n\s*ID="?(.*)"?/)[1] || ''; const releaseMatch = osRelease.match(/\n\s*VERSION_ID="?(.*)"?/); release = releaseMatch ? (releaseMatch[1] || '') : ''; } else if (platform === 'darwin') { distro = 'macos'; release = execSync('sw_vers -productVersion').toString() || ''; } else if (platform === 'aix' ) {
export default async function wizard(pwd, name, toolchain) { let its = validateName(name); if (!its.validForNewPackages) { let errors = (its.errors || []).concat(its.warnings || []); throw new Error("Sorry, " + errors.join(" and ") + "."); } // check for a scoped name let scoped = name.match(/@([^\/]+)\/(.*)/); let [, scope, local] = scoped || [, null, name]; console.log("This utility will walk you through creating the " + style.project(name) + " Neon project."); console.log("It only covers the most common items, and tries to guess sensible defaults."); console.log(); console.log("Press ^C at any time to quit."); let root = path.resolve(pwd, local); let guess = await guessAuthor(); let answers = await prompt([ { type: 'input', name: 'version', message: "version", default: "0.1.0", validate: function (input) { if (semver.valid(input)) { return true; } return "Invalid version: " + input; } }, { type: 'input', name: 'description', message: "description" }, { type: 'input', name: 'node', message: "node entry point", default: "lib" + path.sep + "index.js" }, { type: 'input', name: 'git', message: "git repository" }, { type: 'input', name: 'author', message: "author", default: guess.author }, { type: 'input', name: 'email', message: "email", default: guess.email }, { type: 'input', name: 'license', message: "license", default: "MIT", validate: function (input) { let its = validateLicense(input); if (its.validForNewPackages) { return true; } let errors = (its.errors || []).concat(its.warnings || []); return "Sorry, " + errors.join(" and ") + "."; } } ]); answers.name = { npm: { full: name, scope: scope, local: local }, cargo: { external: local, internal: local.replace(/-/g, "_") } }; let version = await NEON_CLI_VERSION; let ctx = { project: answers, "neon-cli": { major: semver.major(version), minor: semver.minor(version), patch: semver.patch(version) }, build: { cargo: { cmd: toolchain === 'default' ? [] : ["multirust", "run", toolchain] } } }; let lib = path.resolve(root, path.dirname(answers.node)); let native_ = path.resolve(root, 'native'); let src = path.resolve(native_, 'src'); await mkdirs(lib); await mkdirs(src); await writeFile(path.resolve(root, '.gitignore'), (await GITIGNORE_TEMPLATE)(ctx), { flag: 'wx' }); await writeFile(path.resolve(root, 'package.json'), (await NPM_TEMPLATE)(ctx), { flag: 'wx' }); await writeFile(path.resolve(native_, 'Cargo.toml'), (await CARGO_TEMPLATE)(ctx), { flag: 'wx' }); await writeFile(path.resolve(root, 'README.md'), (await README_TEMPLATE)(ctx), { flag: 'wx' }); await writeFile(path.resolve(root, answers.node), (await INDEXJS_TEMPLATE)(ctx), { flag: 'wx' }); await writeFile(path.resolve(src, 'lib.rs'), (await LIBRS_TEMPLATE)(ctx), { flag: 'wx' }); let relativeRoot = path.relative(pwd, root); let relativeNode = path.relative(pwd, path.resolve(root, answers.node)); let relativeRust = path.relative(pwd, path.resolve(src, 'lib.rs')); console.log(); console.log("Woo-hoo! Your Neon project has been created in: " + style.path(relativeRoot)); console.log(); console.log("The main Node entry point is at: " + style.path(relativeNode)); console.log("The main Rust entry point is at: " + style.path(relativeRust)); console.log(); console.log("To build your project, just run " + style.command("npm install") + " from within the " + style.path(relativeRoot) + " directory."); console.log("Then you can test it out with " + style.command("node -e 'require(\"./\")'") + "."); console.log(); console.log("Happy hacking!"); };
var getMinorRange = function(range) { range = simpliFyRange(range); return semver.minor(range); }
var satisfiesRange = function(version, range) { var ans = false; var complexRange = false; var rangeMinor = undefined; var rangeMajor = undefined; var simpliFyRange = function(range) { var ans = replaceall('~', '', range); ans = replaceall('^', '', ans); ans = replaceall('>=','', ans); ans = replaceall('<=','', ans); ans = replaceall('>','', ans); ans = replaceall('<','', ans); ans = replaceall('=','', ans); ans = replaceall('x','0', ans); ans = replaceall('X','0', ans); ans = replaceall('*','0', ans); return ans; } var getMajorRange = function(range) { range = simpliFyRange(range); return semver.major(range); } var getMinorRange = function(range) { range = simpliFyRange(range); return semver.minor(range); } // NOTE: For complex range with multiple value // I use only semver.satisfies method. if (range.split(' ').length > 1) { complexRange = true; } else { // For range with single number set minor to 0 // Ex: 2 => major: 2, minor: 0 if (range.split('.').length == 1) { rangeMinor = 0 rangeMajor = range } else if (range.split('.').length == 2) { // Ex: 5.0 rangeMajor = range.split('.')[0] rangeMinor = range.split('.')[1] } else { rangeMinor = getMinorRange(range); rangeMajor = getMajorRange(range); } } var minor = semver.minor(version); var major = semver.major(version); if (semver.satisfies(version, range) || (!complexRange && rangeMajor == major && rangeMinor == minor && semver.gtr(version, simpliFyRange(range)))) { ans = true; } return ans; }
let contents; try { // If this is a yarn_install or npm_install then the cwd is $(bazel info // output_base)/external/<wksp>/node_modules/@angular/bazel so we can look for // the package.json file under $(bazel info // output_base)/external/angular/package.json const packagePath = path.resolve(process.cwd(), '../../../../angular/package.json'); contents = require(packagePath); } catch (e) { throw new Error('The angular repository is not installed in your Bazel WORKSPACE file'); } if (contents.name !== 'angular-srcs') { throw new Error('Invalid package.json in angular repository'); } // Be tolerant of versions such as "0.17.0-7-g76dc057" const angularPackageVersion = contents.version.split('-')[0]; // Should match only the major and minor versions const range = `${semver.major(angularPackageVersion)}.${semver.minor(angularPackageVersion)}.x`; if (!semver.satisfies(npmPackageVersion, range)) { throw new Error( `Expected angular npm version ${npmPackageVersion} to satisfy ${range}. ` + `Please update ANGULAR_VERSION in WORKSPACE file to match ${npmPackageVersion}`); } } else { // No version check console.warn(`WARNING: With self managed deps you must ensure the @angular/bazel npm package version matches the angular repository version. Use yarn_install or npm_install for this version to be checked automatically. `); }