text
stringlengths
92
5.09M
'use strict'; // config is in non-standard location. setting this env var will direct // node-config to the proper config files. process.env.NODE_CONFIG_DIR = './test/config'; var gulp = require('gulp'); var wiredep = require('wiredep').stream; //var sprite = require('css-sprite').stream; var config = require('config'); var cached = require('gulp-cached'); var es = require('event-stream'); var seq = require('run-sequence'); var lazypipe = require('lazypipe'); var nib = require('nib'); var ngAnnotate = require('gulp-ng-annotate'); var appDir = 'test/app/'; var distDir = 'test/dist/'; var tmpDir = 'test/.tmp/'; var componentSrcDir = 'src/'; var componentDistDir = 'dist/'; // for deployment var env = (process.env.NODE_ENV || 'development').toLowerCase(); var tag = env + '-' + new Date().getTime(); var DIST_DIR = distDir; var LIVERELOAD_PORT = 35729; if (process.env.NODE_ENV) { DIST_DIR = 'test/dist-'+process.env.NODE_ENV.toLowerCase(); } // Load plugins var $ = require('gulp-load-plugins')(); // Sass gulp.task('sass', function () { return gulp.src(appDir+'styles/deps.scss') .pipe(cached('sass')) .pipe($.rubySass({ style: 'expanded', loadPath: [appDir+'bower_components'] })) .pipe($.autoprefixer('last 1 version')) .pipe(wiredep({ directory: appDir+'/bower_components', ignorePath: appDir+'/bower_components/' })) .pipe(gulp.dest(tmpDir+'/styles')) .pipe($.size()); }); // JS gulp.task('js', function () { return gulp.src(appDir+'scripts/**/*.js') .pipe(cached('js')) .pipe($.jshint('.jshintrc')) .pipe($.jshint.reporter('default')) .pipe(gulp.dest(tmpDir+'/scripts')) .pipe($.size()); }); // Bower gulp.task('bowerjs', function() { return gulp.src(appDir+'bower_components/**/*.js') .pipe(gulp.dest(tmpDir+'/bower_components')) .pipe($.size()); }); gulp.task('bowercss', function() { return gulp.src(appDir+'bower_components/**/*.css') .pipe(gulp.dest(tmpDir+'/bower_components')) .pipe($.size()); }); // TODO: what a mess. maybe move all fonts into one dir? gulp.task('bower-fonts', function() { return gulp.src([ appDir+'bower_components/bootstrap-sass-official/assets/fonts/bootstrap/*.*', appDir+'bower_components/font-awesome/fonts/*.*' ]) .pipe(gulp.dest(tmpDir+'/fonts')) .pipe($.size()); }); // CoffeeScript gulp.task('coffee', function() { return gulp.src(appDir+'scripts/**/*.coffee') .pipe(cached('coffee')) .pipe($.coffee({bare: true})) .on('error', function(e) { $.util.log(e.toString()); this.emit('end'); }) .pipe(gulp.dest(tmpDir+'/scripts')) .pipe($.size()); }); gulp.task('component-coffee', function() { return gulp.src(componentSrcDir+'**/*.coffee') .pipe(cached('component-coffee')) .pipe($.coffee({bare: true})) .on('error', function(e) { $.util.log(e.toString()); this.emit('end'); }) .pipe(ngAnnotate()) .pipe(gulp.dest(componentDistDir)) .pipe(gulp.dest(tmpDir + 'scripts/')) .pipe($.uglify()) .pipe($.rename('ng-token-auth.min.js')) .pipe(gulp.dest(componentDistDir)) .pipe($.size()); }); // Images gulp.task('images', function () { return gulp.src(appDir+'images/**/*') .pipe(gulp.dest(tmpDir+'/images')) .pipe($.size()); }); gulp.task('css', function() { return gulp.src(appDir+'styles/**/*.css') .pipe(gulp.dest(tmpDir+'/styles')) .pipe($.size()); }); // Stylus gulp.task('stylus', function() { return gulp.src(appDir+'styles/main.styl') .pipe($.stylus({ paths: [appDir+'styles', tmpDir+'/styles'], //set: ['compress'], use: [nib()], import: [ //'sprite', 'globals/*.styl', 'pages/**/*.xs.styl', 'pages/**/*.sm.styl', 'pages/**/*.md.styl', 'pages/**/*.lg.styl', 'degrade.styl' ] })) .on('error', function(e) { $.util.log(e.toString()); this.emit('end'); }) .pipe(gulp.dest(tmpDir+'/styles')) .pipe($.size()); }); // Clean gulp.task('clean', function () { return gulp.src([distDir+'/*', tmpDir+'/*'], {read: false}).pipe($.clean()); }); // Transpile gulp.task('transpile', [ 'stylus', 'coffee', 'component-coffee', 'js', 'css', 'bowerjs', 'bowercss', 'bower-fonts' ]); // jade -> html var jadeify = lazypipe() .pipe($.jade, { pretty: true }); // inject global js vars var injectGlobals = lazypipe() .pipe($.frep, [ { pattern: '@@GLOBALS', replacement: JSON.stringify({ apiUrl: config.API_URL }) } ]); // Jade to HTML gulp.task('base-tmpl', function() { return gulp.src(appDir+'index.jade') .pipe($.changed(tmpDir)) .pipe(jadeify()) .pipe(injectGlobals()) .pipe($.inject($.bowerFiles({ paths: {bowerJson: 'test/bower.json'}, read: false }), { ignorePath: [appDir], starttag: '<!-- bower:{{ext}}-->', endtag: '<!-- endbower-->' })) .pipe($.inject(gulp.src( [ tmpDir+'/views/**/*.js', tmpDir+'/scripts/**/*.js', tmpDir+'/styles/**/*.css' ], {read: false} ), { ignorePath: [tmpDir], starttag: '<!-- inject:{{ext}}-->', endtag: '<!-- endinject-->' })) .pipe(gulp.dest(tmpDir)) .pipe($.size()); }); // Jade to JS gulp.task('js-tmpl', function() { return gulp.src(appDir+'views/**/*.jade') .pipe(cached('js-tmpl')) .pipe(jadeify()) .pipe($.ngHtml2js({ moduleName: 'ngTokenAuthTestPartials' })) .pipe(gulp.dest(tmpDir+'/views')); }); // useref gulp.task('useref', function () { $.util.log('running useref'); var jsFilter = $.filter(tmpDir+'/**/*.js'); var cssFilter = $.filter(tmpDir+'/**/*.css'); return es.merge( gulp.src(tmpDir+'/images/**/*.*', {base: tmpDir}), gulp.src(tmpDir+'/fonts/**/*.*', {base: tmpDir}), gulp.src(tmpDir+'/index.html', {base: tmpDir}) .pipe($.useref.assets()) .pipe(jsFilter) .pipe($.uglify()) .pipe(jsFilter.restore()) .pipe(cssFilter) .pipe($.minifyCss()) .pipe(cssFilter.restore()) .pipe($.useref.restore()) .pipe($.useref()) ) .pipe(gulp.dest(tmpDir)) .pipe($.if(/^((?!(index\.html)).)*$/, $.rev())) .pipe(gulp.dest(distDir)) .pipe($.rev.manifest()) .pipe(gulp.dest(tmpDir)) .pipe($.size()); }); // Update file version refs gulp.task('replace', function() { var manifest = require('./'+tmpDir+'rev-manifest'); var patterns = []; for (var k in manifest) { patterns.push({ pattern: k, replacement: manifest[k] }); } return gulp.src([ distDir+'/*.html', distDir+'/styles/**/*.css', distDir+'/scripts/main*.js' ], {base: distDir}) .pipe($.frep(patterns)) .pipe(gulp.dest(distDir)) .pipe($.size()); }); // CDNize gulp.task('cdnize', function() { return gulp.src([ distDir+'/*.html', distDir+'/styles/**/*.css' ], {base: distDir}) .pipe($.cdnizer({ defaultCDNBase: config.STATIC_URL, allowRev: true, allowMin: true, files: ['**/*.*'] })) .pipe(gulp.dest(distDir)) .pipe($.size()); }); // Deployment gulp.task('s3', function() { var headers = { 'Cache-Control': 'max-age=315360000, no-transform, public' }; var publisher = $.awspublish.create({ key: config.AWS_KEY, secret: config.AWS_SECRET, bucket: config.AWS_STATIC_BUCKET_NAME }); return gulp.src(distDir+'/**/*') .pipe($.awspublish.gzip()) .pipe(publisher.publish(headers)) .pipe(publisher.sync()) //.pipe(publisher.cache()) .pipe($.awspublish.reporter()); }); // Push to heroku gulp.task('push', $.shell.task([ 'git checkout -b '+tag, 'cp -R '+distDir+' '+DIST_DIR, 'cp test/config/'+env+'.yml test/config/default.yml', 'git add -u .', 'git add .', 'git commit -am "commit for '+tag+' push"', 'git push -f '+env+' '+tag+':master', 'git checkout master', 'git branch -D '+tag, 'rm -rf '+DIST_DIR ])); // E2E Protractor tests gulp.task('protractor', function() { require('coffee-script/register'); return gulp.src('test/e2e/**/*.coffee') .pipe($.protractor.protractor({ configFile: 'protractor.conf.js' })) .on('error', function(e) { $.util.log(e.toString()); this.emit('end'); }); }); gulp.task('test:e2e', ['protractor'], function() { gulp.watch('test/e2e/**/*.coffee', ['protractor']); }); // Watch gulp.task('watch', function () { var lr = require('tiny-lr')(); // start node server $.nodemon({ script: 'test/app.js', ext: 'html js', ignore: [], watch: [] }) .on('restart', function() { console.log('restarted'); }); // start livereload server lr.listen(LIVERELOAD_PORT); // Watch for changes in .tmp folder gulp.watch([ tmpDir+'/*.html', tmpDir+'/styles/**/*.css', tmpDir+'/scripts/**/*.js', tmpDir+'/images/**/*.*' ], function(event) { gulp.src(event.path, {read: false}) .pipe($.livereload(lr)); }); // Watch .scss files gulp.watch(appDir+'styles/**/*.scss', ['sass']); // Watch .styl files gulp.watch(appDir+'styles/**/*.styl', ['stylus']); // Watch sprites //gulp.watch(appDir+'images/sprites/**/*.png', ['sprites']); // Watch .js files gulp.watch(appDir+'scripts/**/*.js', ['js']); // Watch .coffee files gulp.watch(appDir+'scripts/**/*.coffee', ['coffee']); // Watch bower component gulp.watch(componentSrcDir+'**/*.coffee', ['component-coffee']); // Watch .jade files gulp.watch(appDir+'index.jade', ['base-tmpl']); gulp.watch(appDir+'views/**/*.jade', ['reload-js-tmpl']); // Watch image files gulp.watch(appDir+'images/**/*', ['images']); // Watch bower files gulp.watch(appDir+'bower_components/*', ['bowerjs', 'bowercss']); }); // Composite tasks // TODO: refactor when gulp adds support for synchronous tasks. // https://github.com/gulpjs/gulp/issues/347 gulp.task('build-dev', function(cb) { seq( 'clean', //'sprites', 'images', 'sass', 'transpile', 'js-tmpl', 'base-tmpl', cb ); }); gulp.task('dev', function(cb) { seq('build-dev', 'watch', cb); }); gulp.task('reload-js-tmpl', function(cb) { seq('js-tmpl', 'base-tmpl', cb); }); gulp.task('build-prod', function(cb) { seq( 'build-dev', 'useref', 'replace', //'cdnize', //'s3', cb ); }); gulp.task('deploy', function(cb) { if (!process.env.NODE_ENV) { throw 'Error: you forgot to set NODE_ENV'; } seq('build-prod', 'push', cb); });
if (typeof module !== 'undefined' && typeof exports !== 'undefined' && module.exports === exports) { module.exports = 'ng-token-auth'; } angular.module('ng-token-auth', ['ipCookie']).provider('$auth', function() { var configs, defaultConfigName; configs = { "default": { apiUrl: '/api', signOutUrl: '/auth/sign_out', emailSignInPath: '/auth/sign_in', emailRegistrationPath: '/auth', accountUpdatePath: '/auth', accountDeletePath: '/auth', confirmationSuccessUrl: function() { return window.location.href; }, passwordResetPath: '/auth/password', passwordUpdatePath: '/auth/password', passwordResetSuccessUrl: function() { return window.location.href; }, tokenValidationPath: '/auth/validate_token', proxyIf: function() { return false; }, proxyUrl: '/proxy', validateOnPageLoad: true, omniauthWindowType: 'sameWindow', storage: 'cookies', forceValidateToken: false, tokenFormat: { "access-token": "{{ token }}", "token-type": "Bearer", client: "{{ clientId }}", expiry: "{{ expiry }}", uid: "{{ uid }}" }, cookieOps: { path: "/", expires: 9999, expirationUnit: 'days', secure: false }, createPopup: function(url) { return window.open(url, '_blank', 'closebuttoncaption=Cancel'); }, parseExpiry: function(headers) { return (parseInt(headers['expiry'], 10) * 1000) || null; }, handleLoginResponse: function(resp) { return resp.data; }, handleAccountUpdateResponse: function(resp) { return resp.data; }, handleTokenValidationResponse: function(resp) { return resp.data; }, authProviderPaths: { github: '/auth/github', facebook: '/auth/facebook', google: '/auth/google_oauth2', apple: '/auth/apple' } } }; defaultConfigName = "default"; return { configure: function(params) { var conf, defaults, fullConfig, i, k, label, v, _i, _len; if (params instanceof Array && params.length) { for (i = _i = 0, _len = params.length; _i < _len; i = ++_i) { conf = params[i]; label = null; for (k in conf) { v = conf[k]; label = k; if (i === 0) { defaultConfigName = label; } } defaults = angular.copy(configs["default"]); fullConfig = {}; fullConfig[label] = angular.extend(defaults, conf[label]); angular.extend(configs, fullConfig); } if (defaultConfigName !== "default") { delete configs["default"]; } } else if (params instanceof Object) { angular.extend(configs["default"], params); } else { throw "Invalid argument: ng-token-auth config should be an Array or Object."; } return configs; }, $get: [ '$http', '$q', '$location', 'ipCookie', '$window', '$timeout', '$rootScope', '$interpolate', '$interval', (function(_this) { return function($http, $q, $location, ipCookie, $window, $timeout, $rootScope, $interpolate, $interval) { return { header: null, dfd: null, user: {}, mustResetPassword: false, listener: null, initialize: function() { this.initializeListeners(); this.cancelOmniauthInAppBrowserListeners = (function() {}); return this.addScopeMethods(); }, initializeListeners: function() { this.listener = angular.bind(this, this.handlePostMessage); if ($window.addEventListener) { return $window.addEventListener("message", this.listener, false); } }, cancel: function(reason) { if (this.requestCredentialsPollingTimer != null) { $timeout.cancel(this.requestCredentialsPollingTimer); } this.cancelOmniauthInAppBrowserListeners(); if (this.dfd != null) { this.rejectDfd(reason); } return $timeout(((function(_this) { return function() { return _this.requestCredentialsPollingTimer = null; }; })(this)), 0); }, destroy: function() { this.cancel(); if ($window.removeEventListener) { return $window.removeEventListener("message", this.listener, false); } }, handlePostMessage: function(ev) { var error, oauthRegistration; if (ev.data.message === 'deliverCredentials') { delete ev.data.message; oauthRegistration = ev.data.oauth_registration; delete ev.data.oauth_registration; this.handleValidAuth(ev.data, true); $rootScope.$broadcast('auth:login-success', ev.data); if (oauthRegistration) { $rootScope.$broadcast('auth:oauth-registration', ev.data); } } if (ev.data.message === 'authFailure') { error = { reason: 'unauthorized', errors: [ev.data.error] }; this.cancel(error); return $rootScope.$broadcast('auth:login-error', error); } }, addScopeMethods: function() { $rootScope.user = this.user; $rootScope.authenticate = angular.bind(this, this.authenticate); $rootScope.signOut = angular.bind(this, this.signOut); $rootScope.destroyAccount = angular.bind(this, this.destroyAccount); $rootScope.submitRegistration = angular.bind(this, this.submitRegistration); $rootScope.submitLogin = angular.bind(this, this.submitLogin); $rootScope.requestPasswordReset = angular.bind(this, this.requestPasswordReset); $rootScope.updatePassword = angular.bind(this, this.updatePassword); $rootScope.updateAccount = angular.bind(this, this.updateAccount); if (this.getConfig().validateOnPageLoad) { return this.validateUser({ config: this.getSavedConfig() }); } }, submitRegistration: function(params, opts) { var request, successUrl; if (opts == null) { opts = {}; } successUrl = this.getResultOrValue(this.getConfig(opts.config).confirmationSuccessUrl); angular.extend(params, { confirm_success_url: successUrl, config_name: this.getCurrentConfigName(opts.config) }); request = $http.post(this.apiUrl(opts.config) + this.getConfig(opts.config).emailRegistrationPath, params); request.then(function(resp) { return $rootScope.$broadcast('auth:registration-email-success', params); }, function(resp) { return $rootScope.$broadcast('auth:registration-email-error', resp.data); }); return request; }, submitLogin: function(params, opts, httpopts) { if (opts == null) { opts = {}; } if (httpopts == null) { httpopts = {}; } this.initDfd(); $http.post(this.apiUrl(opts.config) + this.getConfig(opts.config).emailSignInPath, params, httpopts).then((function(_this) { return function(resp) { var authData; _this.setConfigName(opts.config); authData = _this.getConfig(opts.config).handleLoginResponse(resp.data, _this); _this.handleValidAuth(authData); return $rootScope.$broadcast('auth:login-success', _this.user); }; })(this), (function(_this) { return function(resp) { _this.rejectDfd({ reason: 'unauthorized', errors: ['Invalid credentials'] }); return $rootScope.$broadcast('auth:login-error', resp.data); }; })(this)); return this.dfd.promise; }, userIsAuthenticated: function() { return this.retrieveData('auth_headers') && this.user.signedIn && !this.tokenHasExpired(); }, requestPasswordReset: function(params, opts) { var request, successUrl; if (opts == null) { opts = {}; } successUrl = this.getResultOrValue(this.getConfig(opts.config).passwordResetSuccessUrl); params.redirect_url = successUrl; if (opts.config != null) { params.config_name = opts.config; } request = $http.post(this.apiUrl(opts.config) + this.getConfig(opts.config).passwordResetPath, params); request.then(function(resp) { return $rootScope.$broadcast('auth:password-reset-request-success', params); }, function(resp) { return $rootScope.$broadcast('auth:password-reset-request-error', resp.data); }); return request; }, updatePassword: function(params) { var request; request = $http.put(this.apiUrl() + this.getConfig().passwordUpdatePath, params); request.then((function(_this) { return function(resp) { $rootScope.$broadcast('auth:password-change-success', resp.data); return _this.mustResetPassword = false; }; })(this), function(resp) { return $rootScope.$broadcast('auth:password-change-error', resp.data); }); return request; }, updateAccount: function(params) { var request; request = $http.put(this.apiUrl() + this.getConfig().accountUpdatePath, params); request.then((function(_this) { return function(resp) { var curHeaders, key, newHeaders, updateResponse, val, _ref; updateResponse = _this.getConfig().handleAccountUpdateResponse(resp.data); curHeaders = _this.retrieveData('auth_headers'); angular.extend(_this.user, updateResponse); if (curHeaders) { newHeaders = {}; _ref = _this.getConfig().tokenFormat; for (key in _ref) { val = _ref[key]; if (curHeaders[key] && updateResponse[key]) { newHeaders[key] = updateResponse[key]; } } _this.setAuthHeaders(newHeaders); } return $rootScope.$broadcast('auth:account-update-success', resp.data); }; })(this), function(resp) { return $rootScope.$broadcast('auth:account-update-error', resp.data); }); return request; }, destroyAccount: function(params) { var request; request = $http["delete"](this.apiUrl() + this.getConfig().accountUpdatePath, params); request.then((function(_this) { return function(resp) { _this.invalidateTokens(); return $rootScope.$broadcast('auth:account-destroy-success', resp.data); }; })(this), function(resp) { return $rootScope.$broadcast('auth:account-destroy-error', resp.data); }); return request; }, authenticate: function(provider, opts) { if (opts == null) { opts = {}; } if (this.dfd == null) { this.setConfigName(opts.config); this.initDfd(); this.openAuthWindow(provider, opts); } return this.dfd.promise; }, setConfigName: function(configName) { if (configName == null) { configName = defaultConfigName; } return this.persistData('currentConfigName', configName, configName); }, openAuthWindow: function(provider, opts) { var authUrl, omniauthWindowType; omniauthWindowType = this.getConfig(opts.config).omniauthWindowType; authUrl = this.buildAuthUrl(omniauthWindowType, provider, opts); if (omniauthWindowType === 'newWindow') { return this.requestCredentialsViaPostMessage(this.getConfig().createPopup(authUrl)); } else if (omniauthWindowType === 'inAppBrowser') { return this.requestCredentialsViaExecuteScript(this.getConfig().createPopup(authUrl)); } else if (omniauthWindowType === 'sameWindow') { return this.visitUrl(authUrl); } else { throw 'Unsupported omniauthWindowType "#{omniauthWindowType}"'; } }, visitUrl: function(url) { return $window.location.replace(url); }, buildAuthUrl: function(omniauthWindowType, provider, opts) { var authUrl, key, params, val; if (opts == null) { opts = {}; } authUrl = this.getConfig(opts.config).apiUrl; authUrl += this.getConfig(opts.config).authProviderPaths[provider]; authUrl += '?auth_origin_url=' + encodeURIComponent(opts.auth_origin_url || $window.location.href); params = angular.extend({}, opts.params || {}, { omniauth_window_type: omniauthWindowType }); for (key in params) { val = params[key]; authUrl += '&'; authUrl += encodeURIComponent(key); authUrl += '='; authUrl += encodeURIComponent(val); } return authUrl; }, requestCredentialsViaPostMessage: function(authWindow) { if (authWindow.closed) { return this.handleAuthWindowClose(authWindow); } else { authWindow.postMessage("requestCredentials", "*"); return this.requestCredentialsPollingTimer = $timeout(((function(_this) { return function() { return _this.requestCredentialsViaPostMessage(authWindow); }; })(this)), 500); } }, requestCredentialsViaExecuteScript: function(authWindow) { var handleAuthWindowClose, handleLoadStop, handlePostMessage; this.cancelOmniauthInAppBrowserListeners(); handleAuthWindowClose = this.handleAuthWindowClose.bind(this, authWindow); handleLoadStop = this.handleLoadStop.bind(this, authWindow); handlePostMessage = this.handlePostMessage.bind(this); authWindow.addEventListener('loadstop', handleLoadStop); authWindow.addEventListener('exit', handleAuthWindowClose); authWindow.addEventListener('message', handlePostMessage); return this.cancelOmniauthInAppBrowserListeners = function() { authWindow.removeEventListener('loadstop', handleLoadStop); authWindow.removeEventListener('exit', handleAuthWindowClose); return authWindow.addEventListener('message', handlePostMessage); }; }, handleLoadStop: function(authWindow) { var remoteCode; _this = this; remoteCode = "function performBestTransit() { var data = requestCredentials(); if (webkit && webkit.messageHandlers && webkit.messageHandlers.cordova_iab) { var dataWithDeliverMessage = Object.assign({}, data, { message: 'deliverCredentials' }); webkit.messageHandlers.cordova_iab.postMessage(JSON.stringify(dataWithDeliverMessage)); return 'postMessageSuccess'; } else { return data; } } performBestTransit();"; return authWindow.executeScript({ code: remoteCode }, function(response) { var data, ev; data = response[0]; if (data === 'postMessageSuccess') { return authWindow.close(); } else if (data) { ev = new Event('message'); ev.data = data; _this.cancelOmniauthInAppBrowserListeners(); $window.dispatchEvent(ev); _this.initDfd(); return authWindow.close(); } }); }, handleAuthWindowClose: function(authWindow) { this.cancel({ reason: 'unauthorized', errors: ['User canceled login'] }); this.cancelOmniauthInAppBrowserListeners; return $rootScope.$broadcast('auth:window-closed'); }, resolveDfd: function() { if (!this.dfd) { return; } this.dfd.resolve(this.user); return $timeout(((function(_this) { return function() { _this.dfd = null; if (!$rootScope.$$phase) { return $rootScope.$digest(); } }; })(this)), 0); }, buildQueryString: function(param, prefix) { var encoded, k, str, v; str = []; for (k in param) { v = param[k]; k = prefix ? prefix + "[" + k + "]" : k; encoded = angular.isObject(v) ? this.buildQueryString(v, k) : k + "=" + encodeURIComponent(v); str.push(encoded); } return str.join("&"); }, parseLocation: function(location) { var i, locationSubstring, obj, pair, pairs; locationSubstring = location.substring(1); obj = {}; if (locationSubstring) { pairs = locationSubstring.split('&'); pair = void 0; i = void 0; for (i in pairs) { i = i; if ((pairs[i] === '') || (typeof pairs[i] === 'function')) { continue; } pair = pairs[i].split('='); obj[decodeURIComponent(pair[0])] = decodeURIComponent(pair[1]); } } return obj; }, validateUser: function(opts) { var clientId, configName, expiry, location_parse, params, search, token, uid, url; if (opts == null) { opts = {}; } configName = opts.config; if (this.dfd == null) { this.initDfd(); if (this.userIsAuthenticated()) { this.resolveDfd(); } else { search = $location.search(); location_parse = this.parseLocation(window.location.search); params = Object.keys(search).length === 0 ? location_parse : search; token = params.auth_token || params.token; if (token !== void 0) { clientId = params.client_id; uid = params.uid; expiry = params.expiry; configName = params.config; this.setConfigName(configName); this.mustResetPassword = params.reset_password; this.firstTimeLogin = params.account_confirmation_success; this.oauthRegistration = params.oauth_registration; this.setAuthHeaders(this.buildAuthHeaders({ token: token, clientId: clientId, uid: uid, expiry: expiry })); url = $location.path() || '/'; ['auth_token', 'token', 'client_id', 'uid', 'expiry', 'config', 'reset_password', 'account_confirmation_success', 'oauth_registration'].forEach(function(prop) { return delete params[prop]; }); if (Object.keys(params).length > 0) { url += '?' + this.buildQueryString(params); } $location.url(url); } else if (this.retrieveData('currentConfigName')) { configName = this.retrieveData('currentConfigName'); } if (this.getConfig().forceValidateToken) { this.validateToken({ config: configName }); } else if (!isEmpty(this.retrieveData('auth_headers'))) { if (this.tokenHasExpired()) { $rootScope.$broadcast('auth:session-expired'); this.rejectDfd({ reason: 'unauthorized', errors: ['Session expired.'] }); } else { this.validateToken({ config: configName }); } } else { this.rejectDfd({ reason: 'unauthorized', errors: ['No credentials'] }); $rootScope.$broadcast('auth:invalid'); } } } return this.dfd.promise; }, validateToken: function(opts) { if (opts == null) { opts = {}; } if (!this.tokenHasExpired()) { return $http.get(this.apiUrl(opts.config) + this.getConfig(opts.config).tokenValidationPath).then((function(_this) { return function(resp) { var authData; authData = _this.getConfig(opts.config).handleTokenValidationResponse(resp.data); _this.handleValidAuth(authData); if (_this.firstTimeLogin) { $rootScope.$broadcast('auth:email-confirmation-success', _this.user); } if (_this.oauthRegistration) { $rootScope.$broadcast('auth:oauth-registration', _this.user); } if (_this.mustResetPassword) { $rootScope.$broadcast('auth:password-reset-confirm-success', _this.user); } return $rootScope.$broadcast('auth:validation-success', _this.user); }; })(this), (function(_this) { return function(resp) { if (_this.firstTimeLogin) { $rootScope.$broadcast('auth:email-confirmation-error', resp.data); } if (_this.mustResetPassword) { $rootScope.$broadcast('auth:password-reset-confirm-error', resp.data); } $rootScope.$broadcast('auth:validation-error', resp.data); return _this.rejectDfd({ reason: 'unauthorized', errors: resp.data != null ? resp.data.errors : ['Unspecified error'] }, resp.status > 0); }; })(this)); } else { return this.rejectDfd({ reason: 'unauthorized', errors: ['Expired credentials'] }); } }, tokenHasExpired: function() { var expiry, now; expiry = this.getExpiry(); now = new Date().getTime(); return expiry && expiry < now; }, getExpiry: function() { return this.getConfig().parseExpiry(this.retrieveData('auth_headers') || {}); }, invalidateTokens: function() { var key, val, _ref; _ref = this.user; for (key in _ref) { val = _ref[key]; delete this.user[key]; } this.deleteData('currentConfigName'); if (this.timer != null) { $interval.cancel(this.timer); } return this.deleteData('auth_headers'); }, signOut: function() { var request; request = $http["delete"](this.apiUrl() + this.getConfig().signOutUrl); request.then((function(_this) { return function(resp) { _this.invalidateTokens(); return $rootScope.$broadcast('auth:logout-success'); }; })(this), (function(_this) { return function(resp) { _this.invalidateTokens(); return $rootScope.$broadcast('auth:logout-error', resp.data); }; })(this)); return request; }, handleValidAuth: function(user, setHeader) { if (setHeader == null) { setHeader = false; } if (this.requestCredentialsPollingTimer != null) { $timeout.cancel(this.requestCredentialsPollingTimer); } this.cancelOmniauthInAppBrowserListeners(); angular.extend(this.user, user); this.user.signedIn = true; this.user.configName = this.getCurrentConfigName(); if (setHeader) { this.setAuthHeaders(this.buildAuthHeaders({ token: this.user.auth_token, clientId: this.user.client_id, uid: this.user.uid, expiry: this.user.expiry })); } return this.resolveDfd(); }, buildAuthHeaders: function(ctx) { var headers, key, val, _ref; headers = {}; _ref = this.getConfig().tokenFormat; for (key in _ref) { val = _ref[key]; headers[key] = $interpolate(val)(ctx); } return headers; }, persistData: function(key, val, configName) { if (this.getConfig(configName).storage instanceof Object) { return this.getConfig(configName).storage.persistData(key, val, this.getConfig(configName)); } else { switch (this.getConfig(configName).storage) { case 'localStorage': return $window.localStorage.setItem(key, JSON.stringify(val)); case 'sessionStorage': return $window.sessionStorage.setItem(key, JSON.stringify(val)); default: return ipCookie(key, val, this.getConfig().cookieOps); } } }, retrieveData: function(key) { var e; try { if (this.getConfig().storage instanceof Object) { return this.getConfig().storage.retrieveData(key); } else { switch (this.getConfig().storage) { case 'localStorage': return JSON.parse($window.localStorage.getItem(key)); case 'sessionStorage': return JSON.parse($window.sessionStorage.getItem(key)); default: return ipCookie(key); } } } catch (_error) { e = _error; if (e instanceof SyntaxError) { return void 0; } else { throw e; } } }, deleteData: function(key) { var cookieOps; if (this.getConfig().storage instanceof Object) { this.getConfig().storage.deleteData(key); } switch (this.getConfig().storage) { case 'localStorage': return $window.localStorage.removeItem(key); case 'sessionStorage': return $window.sessionStorage.removeItem(key); default: cookieOps = { path: this.getConfig().cookieOps.path }; if (this.getConfig().cookieOps.domain !== void 0) { cookieOps.domain = this.getConfig().cookieOps.domain; } return ipCookie.remove(key, cookieOps); } }, setAuthHeaders: function(h) { var expiry, newHeaders, now, result; newHeaders = angular.extend(this.retrieveData('auth_headers') || {}, h); result = this.persistData('auth_headers', newHeaders); expiry = this.getExpiry(); now = new Date().getTime(); if (expiry > now) { if (this.timer != null) { $interval.cancel(this.timer); } this.timer = $interval(((function(_this) { return function() { return _this.validateUser({ config: _this.getSavedConfig() }); }; })(this)), parseInt(expiry - now), 1); } return result; }, initDfd: function() { this.dfd = $q.defer(); return this.dfd.promise.then(angular.noop, angular.noop); }, rejectDfd: function(reason, invalidateTokens) { if (invalidateTokens == null) { invalidateTokens = true; } if (invalidateTokens === true) { this.invalidateTokens(); } if (this.dfd != null) { this.dfd.reject(reason); return $timeout(((function(_this) { return function() { return _this.dfd = null; }; })(this)), 0); } }, apiUrl: function(configName) { if (this.getConfig(configName).proxyIf()) { return this.getConfig(configName).proxyUrl; } else { return this.getConfig(configName).apiUrl; } }, getConfig: function(name) { return configs[this.getCurrentConfigName(name)]; }, getResultOrValue: function(arg) { if (typeof arg === 'function') { return arg(); } else { return arg; } }, getCurrentConfigName: function(name) { return name || this.getSavedConfig(); }, getSavedConfig: function() { var c, key; c = void 0; key = 'currentConfigName'; if (this.hasLocalStorage()) { if (c == null) { c = JSON.parse($window.localStorage.getItem(key)); } } else if (this.hasSessionStorage()) { if (c == null) { c = JSON.parse($window.sessionStorage.getItem(key)); } } if (c == null) { c = ipCookie(key); } return c || defaultConfigName; }, hasSessionStorage: function() { var error; if (this._hasSessionStorage == null) { this._hasSessionStorage = false; try { $window.sessionStorage.setItem('ng-token-auth-test', 'ng-token-auth-test'); $window.sessionStorage.removeItem('ng-token-auth-test'); this._hasSessionStorage = true; } catch (_error) { error = _error; } } return this._hasSessionStorage; }, hasLocalStorage: function() { var error; if (this._hasLocalStorage == null) { this._hasLocalStorage = false; try { $window.localStorage.setItem('ng-token-auth-test', 'ng-token-auth-test'); $window.localStorage.removeItem('ng-token-auth-test'); this._hasLocalStorage = true; } catch (_error) { error = _error; } } return this._hasLocalStorage; } }; }; })(this) ] }; }).config([ '$httpProvider', function($httpProvider) { var httpMethods, tokenIsCurrent, updateHeadersFromResponse; tokenIsCurrent = function($auth, headers) { var newTokenExpiry, oldTokenExpiry; oldTokenExpiry = Number($auth.getExpiry()); newTokenExpiry = Number($auth.getConfig().parseExpiry(headers || {})); return newTokenExpiry >= oldTokenExpiry; }; updateHeadersFromResponse = function($auth, resp) { var key, newHeaders, val, _ref; newHeaders = {}; _ref = $auth.getConfig().tokenFormat; for (key in _ref) { val = _ref[key]; if (resp.headers(key)) { newHeaders[key] = resp.headers(key); } } if (tokenIsCurrent($auth, newHeaders)) { return $auth.setAuthHeaders(newHeaders); } }; $httpProvider.interceptors.push([ '$injector', function($injector) { return { request: function(req) { $injector.invoke([ '$http', '$auth', function($http, $auth) { var key, val, _ref, _results; if (req.url.match($auth.apiUrl())) { _ref = $auth.retrieveData('auth_headers'); _results = []; for (key in _ref) { val = _ref[key]; _results.push(req.headers[key] = val); } return _results; } } ]); return req; }, response: function(resp) { $injector.invoke([ '$http', '$auth', function($http, $auth) { if (resp.config.url.match($auth.apiUrl())) { return updateHeadersFromResponse($auth, resp); } } ]); return resp; }, responseError: function(resp) { $injector.invoke([ '$http', '$auth', function($http, $auth) { if (resp && resp.config && resp.config.url && resp.config.url.match($auth.apiUrl())) { return updateHeadersFromResponse($auth, resp); } } ]); return $injector.get('$q').reject(resp); } }; } ]); httpMethods = ['get', 'post', 'put', 'patch', 'delete']; return angular.forEach(httpMethods, function(method) { var _base; if ((_base = $httpProvider.defaults.headers)[method] == null) { _base[method] = {}; } return $httpProvider.defaults.headers[method]['If-Modified-Since'] = 'Mon, 26 Jul 1997 05:00:00 GMT'; }); } ]).run([ '$auth', '$window', '$rootScope', function($auth, $window, $rootScope) { return $auth.initialize(); } ]); window.isOldIE = function() { var nav, out, version; out = false; nav = navigator.userAgent.toLowerCase(); if (nav && nav.indexOf('msie') !== -1) { version = parseInt(nav.split('msie')[1]); if (version < 10) { out = true; } } return out; }; window.isIE = function() { var nav; nav = navigator.userAgent.toLowerCase(); return (nav && nav.indexOf('msie') !== -1) || !!navigator.userAgent.match(/Trident.*rv\:11\./); }; window.isEmpty = function(obj) { var key, val; if (!obj) { return true; } if (obj.length > 0) { return false; } if (obj.length === 0) { return true; } for (key in obj) { val = obj[key]; if (Object.prototype.hasOwnProperty.call(obj, key)) { return false; } } return true; };
require('coffee-script/register'); var os = require('os'); exports.config = { allScriptsTimeout: 30000, sauceUser: process.env.SAUCE_USERNAME, sauceKey: process.env.SAUCE_ACCESS_KEY, specs: [ 'e2e/ng-token-auth/*.coffee' ], chromeOnly: true, capabilities: { 'browserName': 'chrome', 'name': 'ng e2e', 'tunnel-identifier': process.env.TRAVIS_JOB_NUMBER, 'build': process.env.TRAVIS_BUILD_NUMBER, 'chromeOptions': { 'args': ['show-fps-counter=true'] } }, baseUrl: 'http://'+os.hostname()+':7777/', framework: 'jasmine', jasmineNodeOpts: { defaultTimeoutInterval: 30000 } };
var crypto = require('crypto'); // params: dir, key, secret, expiration, bucket, acl, type, redirect module.exports = function(params) { var date = new Date(); var s3Policy = { expiration: params.expiration, conditions: [ ["starts-with", "$key", params.dir], {bucket: params.bucket}, {acl: params.acl}, ['starts-with', "$Content-Type", params.type] ] } // stringify and encode policy var stringPolicy = JSON.stringify(s3Policy); var base64Policy = Buffer(stringPolicy, 'utf-8').toString('base64'); // sign the base64 encoded policy var signature = crypto.createHmac('sha1', params.secret) .update(new Buffer(base64Policy, 'utf-8')) .digest('base64'); return { key: params.dir+"${filename}", AWSAccessKeyId: params.key, signature: signature, policy: base64Policy, acl: params.acl, 'Content-Type': params.type }; }
process.env.NODE_TLS_REJECT_UNAUTHORIZED = '0'; var express = require('express'); var request = require('request'); var s3Policy = require('./server/s3'); var sm = require('sitemap'); var os = require('os'); var port = process.env.PORT || 7777; var distDir = '/.tmp'; var app = express(); // must override env and then init CONFIG process.env.NODE_CONFIG_DIR = './test/config' var CONFIG = require('config'); console.log('@-->API URL', CONFIG.API_URL); console.log('@-->NODE_ENV', process.env.NODE_ENV); // env setup // TODO: comment this better if (process.env.NODE_ENV && process.env.NODE_ENV != 'development' && process.env.NODE_ENV != 'travis') { distDir = '/dist-'+process.env.NODE_ENV.toLowerCase(); } else { app.use(require('connect-livereload')()); } // sitemap sitemap = sm.createSitemap({ hostname: CONFIG.SITE_DOMAIN, cacheTime: 600000, urls: [ { url: '/', changefreq: 'monthly', priority: 0.9 } ] }); app.get('/sitemap.xml', function(req, res) { sitemap.toXML(function(xml) { res.header('Content-Type', 'application/xml'); res.send(xml); }); }); // proxy api requests (for older IE browsers) app.all('/proxy/*', function(req, res, next) { // transform request URL into remote URL var apiUrl = 'http:'+CONFIG.API_URL+'/'+req.params[0]; var r = null; // preserve GET params if (req._parsedUrl.search) { apiUrl += req._parsedUrl.search; } // handle POST / PUT if (req.method === 'POST' || req.method === 'PUT') { r = request[req.method.toLowerCase()]({uri: apiUrl, json: req.body}); } else { r = request(apiUrl); } // pipe request to remote API req.pipe(r).pipe(res); }); // provide s3 policy for direct uploads app.get('/policy/:fname', function(req, res) { var fname = req.params.fname; var contentType = 'image/png'; var acl = 'public-read'; var uploadDir = CONFIG.aws_upload_dir; var policy = s3Policy({ expiration: "2014-12-01T12:00:00.000Z", dir: uploadDir, bucket: CONFIG.aws_bucket, secret: CONFIG.aws_secret, key: CONFIG.aws_key, acl: acl, type: contentType }); res.send({ policy: policy, path: "//"+CONFIG.aws_bucket+".s3.amazonaws.com/"+uploadDir+fname, action: "//"+CONFIG.aws_bucket+".s3.amazonaws.com/" }); }); // redirect to push state url (i.e. /blog -> /#/blog) app.get(/^(\/[^#\.]+)$/, function(req, res) { var path = req.route.params[0] // preserve GET params if (req._parsedUrl.search) { path += req._parsedUrl.search; } res.redirect('/#'+path); }); app.use(express.static(__dirname + distDir)); app.listen(port);
#include <stdio.h> int def_in_dyn = 1234; extern int def_in_exec; void dyn_main() { puts("hello from dyn_main()!"); printf("dyn: def_in_exec=%d def_in_dyn=%d\n", def_in_exec, def_in_dyn); def_in_dyn = 2; def_in_exec = 4; printf("dyn: def_in_exec=%d def_in_dyn=%d\n", def_in_exec, def_in_dyn); puts("goodbye from dyn_main()!"); }
#include <stdio.h> extern int def_in_dyn; int def_in_exec = 5678; void dyn_main(); int main() { puts("hello from main()!"); printf("exec: def_in_exec=%d def_in_dyn=%d\n", def_in_exec, def_in_dyn); def_in_dyn = 1; def_in_exec = 3; printf("exec: def_in_exec=%d def_in_dyn=%d\n", def_in_exec, def_in_dyn); dyn_main(); printf("exec: def_in_exec=%d def_in_dyn=%d\n", def_in_exec, def_in_dyn); puts("goodbye from main()!"); }
#!/usr/bin/env python from setuptools import setup, find_packages import os, runpy pkg_root = os.path.dirname(__file__) __version__ = runpy.run_path( os.path.join(pkg_root, 'onedrive', '__init__.py') )['__version__'] # Error-handling here is to allow package to be built w/o README included try: readme = open(os.path.join(pkg_root, 'README.txt')).read() except IOError: readme = '' setup( name='python-onedrive', version=__version__, author='Mike Kazantsev, Antonio Chen', author_email='mk.fraggod@gmail.com', license='WTFPL', keywords=[ 'onedrive', 'skydrive', 'api', 'oauth2', 'rest', 'microsoft', 'cloud', 'live', 'liveconnect', 'json', 'storage', 'storage provider', 'file hosting' ], url='http://github.com/mk-fg/python-onedrive', description='Obsolete python/cli module for' ' MS SkyDrive/OneDrive old API, do not use for new projects', long_description=readme, classifiers=[ 'Development Status :: 4 - Beta', 'Environment :: Console', 'Intended Audience :: Developers', 'Intended Audience :: System Administrators', 'Intended Audience :: Information Technology', 'License :: OSI Approved', 'Operating System :: OS Independent', 'Programming Language :: Python', 'Programming Language :: Python :: 2.7', 'Programming Language :: Python :: 2 :: Only', 'Topic :: Internet', 'Topic :: Software Development', 'Topic :: System :: Archiving', 'Topic :: System :: Filesystems', 'Topic :: Utilities'], # install_requires = [], extras_require=dict( standalone=['requests'], cli=['PyYAML', 'requests'], conf=['PyYAML', 'requests']), packages=find_packages(), include_package_data=True, package_data={'': ['README.txt']}, exclude_package_data={'': ['README.*']}, entry_points=dict(console_scripts=[ 'onedrive-cli = onedrive.cli_tool:main']))
#!/usr/bin/env python #-*- coding: utf-8 -*- from __future__ import unicode_literals, print_function import itertools as it, operator as op, functools as ft import os, sys, re class FormatError(Exception): pass def main(): import argparse parser = argparse.ArgumentParser( description='Convert sphinx-produced autodoc.apidoc text to markdown.') parser.add_argument('src', nargs='?', help='Source file (default: use stdin).') optz = parser.parse_args() src = open(optz.src) if optz.src else sys.stdin dst = sys.stdout py_name = r'[\w_\d]+' out = ft.partial(print, file=dst) st_attrdoc = 0 st_cont, lse_nl = False, None for line in src: ls = line.strip() if not ls: # blank line out(line, end='') continue line_indent = re.search(r'^( +)', line) if not line_indent: line_indent = 0 else: line_indent = len(line_indent.group(1)) if line_indent % 3: raise FormatError('Weird indent size: {}'.format(line_indent)) line_indent = line_indent / 3 lp = line.split() lse = re.sub(r'(<\S+) at 0x[\da-f]+(>)', r'\1\2', ls) lse = re.sub(r'([_*<>])', r'\\\1', lse) for url in re.findall(r'\b\w+://\S+', lse): lse = lse.replace(url, url.replace(r'\_', '_')) lse = re.sub(r'\bu([\'"])', r'\1', lse) st_cont, lse_nl = bool(lse_nl), '' if re.search(r'\b\w+://\S+-$', lse) else '\n' st_attrdoc_reset = True if not line_indent: if len(lp) > 2 and lp[0] == lp[1]: if lp[0] in ('exception', 'class'): # class, exception out('\n' * 1, end='') out('* **{}**'.format(' '.join(lse.split()[1:]))) else: raise FormatError('Unhandled: {!r}'.format(line)) elif line_indent == 1: if re.search(r'^(\w+ )?{}\('.format(py_name), ls): # function out('\n' * 1, end='') out('{}* {}'.format(' ' * 4, lse)) st_attrdoc, st_attrdoc_reset = 8, False elif re.search(r'^{}\s+=\s+'.format(py_name), ls): # attribute out('{}* {}'.format(' ' * 4, lse)) st_attrdoc, st_attrdoc_reset = 8, False elif lp[0] == 'Bases:': # class bases out('{}{}'.format(' ' * 4, lse)) st_attrdoc, st_attrdoc_reset = 4, False else: out('{}{}'.format(' ' * (4 * st_cont), ls), end=lse_nl) # class docstring else: # description line if ls[0] in '-*': line = '\\' + line.lstrip() out('{}{}'.format(' ' * (st_attrdoc * st_cont), line.strip()), end=lse_nl) st_attrdoc_reset = False if st_attrdoc and st_attrdoc_reset: st_attrdoc = 0 if __name__ == '__main__': main()
#-*- coding: utf-8 -*- from __future__ import print_function import itertools as it, operator as op, functools as ft from collections import Iterable import os, sys, types, re from sphinx.ext.autodoc import Documenter _autodoc_add_line = Documenter.add_line @ft.wraps(_autodoc_add_line) def autodoc_add_line(self, line, *argz, **kwz): tee = self.env.app.config.autodoc_dump_rst if tee: tee_line = self.indent + line if isinstance(tee, file): tee.write(tee_line + '\n') elif tee is True: print(tee_line) else: raise ValueError('Unrecognized value for "autodoc_dump_rst" option: {!r}'.format(tee)) return _autodoc_add_line(self, line, *argz, **kwz) Documenter.add_line = autodoc_add_line def process_docstring(app, what, name, obj, options, lines): if not lines: return i, ld = 0, dict(enumerate(lines)) # to allow arbitrary peeks i_max = max(ld) def process_line(i): line, i_next = ld[i], i + 1 while i_next not in ld and i_next <= i_max: i_next += 1 line_next = ld.get(i_next) if line_next and line_next[0] in u' \t': # tabbed continuation of the sentence ld[i] = u'{} {}'.format(line, line_next.strip()) del ld[i_next] process_line(i) elif line.endswith(u'.') or (line_next and line_next[0].isupper()): ld[i + 0.5] = u'' for i in xrange(i_max + 1): if i not in ld: continue # was removed process_line(i) # Overwrite the list items inplace, extending the list if necessary for i, (k, line) in enumerate(sorted(ld.viewitems())): try: lines[i] = line except IndexError: lines.append(line) for i in xrange(max(0, i_max- i)): lines.pop() # trim the leftovers, if any def skip_override(app, what, name, obj, skip, options): if options.get('exclude-members'): include_only = set(re.compile(k[3:]) for k in options['exclude-members'] if k.startswith('rx:')) if include_only: for pat in include_only: if pat.search(name): break else: return True if what == 'exception': return False if name == '__init__' \ and isinstance(obj, types.UnboundMethodType) else True elif what == 'class': if ( name in ['__init__', '__call__'] \ and isinstance(obj, types.UnboundMethodType) )\ or getattr(obj, 'im_class', None) is type: return False return skip def setup(app): app.connect('autodoc-process-docstring', process_docstring) app.connect('autodoc-skip-member', skip_override) app.add_config_value('autodoc_dump_rst', None, True)
import sys, os from os.path import abspath, dirname, join doc_root = dirname(__file__) # autodoc_dump_rst = open(join(doc_root, 'autodoc.rst'), 'w') os.chdir(doc_root) sys.path.insert(0, abspath('..')) # for module itself sys.path.append(abspath('.')) # for extensions needs_sphinx = '1.1' extensions = ['sphinx.ext.autodoc', 'sphinx_local_hooks'] master_doc = 'api' pygments_style = 'sphinx' source_suffix = '.rst' # exclude_patterns = ['_build'] # templates_path = ['_templates'] autoclass_content = 'class' autodoc_member_order = 'bysource' autodoc_default_flags = ['members', 'undoc-members', 'show-inheritance']
#!/usr/bin/env python2 #-*- coding: utf-8 -*- from __future__ import unicode_literals, print_function import itertools as it, operator as op, functools as ft from os.path import dirname, basename, exists, isdir, join, abspath from posixpath import join as ujoin, dirname as udirname, basename as ubasename from collections import defaultdict import os, sys, io, logging, re, types, json try: import chardet except ImportError: chardet = None # completely optional try: import onedrive except ImportError: # Make sure tool works from a checkout if __name__ != '__main__': raise pkg_root = abspath(dirname(__file__)) for pkg_root in pkg_root, dirname(pkg_root): if isdir(join(pkg_root, 'onedrive'))\ and exists(join(pkg_root, 'setup.py')): sys.path.insert(0, dirname(__file__)) try: import onedrive except ImportError: pass else: break else: raise ImportError('Failed to find/import "onedrive" module') from onedrive import api_v5, conf force_encoding = None def tree_node(): return defaultdict(tree_node) def print_result(data, file, tpl=None, indent='', indent_first=None, indent_level=' '*2): # Custom printer is used because pyyaml isn't very pretty with unicode if isinstance(data, list): for v in data: print_result( v, file=file, tpl=tpl, indent=indent + ' ', indent_first=(indent_first if indent_first is not None else indent) + '- ' ) indent_first = None elif isinstance(data, dict): indent_cur = indent_first if indent_first is not None else indent if tpl is None: for k, v in sorted(data.viewitems(), key=op.itemgetter(0)): print(indent_cur + decode_obj(k, force=True) + ':', file=file, end='') indent_cur = indent if not isinstance(v, (list, dict)): # peek to display simple types inline print_result(v, file=file, tpl=tpl, indent=' ') else: print('', file=file) print_result(v, file=file, tpl=tpl, indent=indent_cur+indent_level) else: if '{' not in tpl and not re.search(r'^\s*$', tpl): tpl = '{{0[{}]}}'.format(tpl) try: data = tpl.format(data) except Exception as err: log.debug( 'Omitting object that does not match template' ' (%r) from output (error: %s %s): %r', tpl, type(err), err, data ) else: print_result(data, file=file, indent=indent_cur) else: if indent_first is not None: indent = indent_first print(indent + decode_obj(data, force=True), file=file) def decode_obj(obj, force=False): 'Convert or dump object to unicode.' if isinstance(obj, unicode): return obj elif isinstance(obj, bytes): if force_encoding is not None: return obj.decode(force_encoding) if chardet: enc_guess = chardet.detect(obj) if enc_guess['confidence'] > 0.7: return obj.decode(enc_guess['encoding']) return obj.decode('utf-8') else: return obj if not force else repr(obj) def size_units( size, _units=list(reversed(list((u, 2 ** (i * 10)) for i, u in enumerate('BKMGT')))) ): for u, u1 in _units: if size > u1: break return size / float(u1), u def id_match(s, _re_id=re.compile( r'^(' r'(file|folder)\.[0-9a-f]{16}\.[0-9A-F]{16}!\d+|folder\.[0-9a-f]{16}' # Force-resolving all "special-looking" paths here, because # there are separate commands (e.g. "quota") to get data from these # r'|me(/\w+(/.*)?)?' # special paths like "me/skydrive" r')$' ) ): return s if s and _re_id.search(s) else None def main(): import argparse parser = argparse.ArgumentParser( description='Tool to manipulate OneDrive contents.') parser.add_argument('-c', '--config', metavar='path', default=conf.ConfigMixin.conf_path_default, help='Writable configuration state-file (yaml).' ' Used to store authorization_code, access and refresh tokens.' ' Should initially contain at least something like "{client: {id: xxx, secret: yyy}}".' ' Default: %(default)s') parser.add_argument('-p', '--path', action='store_true', help='Interpret file/folder arguments only as human paths, not ids (default: guess).' ' Avoid using such paths if non-unique "name"' ' attributes of objects in the same parent folder might be used.') parser.add_argument('-i', '--id', action='store_true', help='Interpret file/folder arguments only as ids (default: guess).') parser.add_argument('-k', '--object-key', metavar='spec', help='If returned data is an object, or a list of objects, only print this key from there.' ' Supplied spec can be a template string for python str.format,' ' assuming that object gets passed as the first argument.' ' Objects that do not have specified key or cannot' ' be formatted using supplied template will be ignored entirely.' ' Example: {0[id]} {0[name]!r} {0[count]:03d} (uploader: {0[from][name]})') parser.add_argument('-e', '--encoding', metavar='enc', default='utf-8', help='Use specified encoding (example: utf-8) for CLI input/output.' ' See full list of supported encodings at:' ' http://docs.python.org/2/library/codecs.html#standard-encodings .' ' Pass empty string or "detect" to detect input encoding via' ' chardet module, if available, falling back to utf-8 and terminal encoding for output.' ' Forced utf-8 is used by default, for consistency and due to its ubiquity.') parser.add_argument('-V', '--version', action='version', version='python-onedrive {}'.format(onedrive.__version__), help='Print version number and exit.') parser.add_argument('--debug', action='store_true', help='Verbose operation mode.') cmds = parser.add_subparsers(title='Supported operations', dest='call') cmd = cmds.add_parser('auth', help='Perform user authentication.') cmd.add_argument('url', nargs='?', help='URL with the authorization_code.') cmds.add_parser('auth_refresh', help='Force-refresh OAuth2 access_token.' ' Should never be necessary under normal conditions.') cmds.add_parser('quota', help='Print quota information.') cmds.add_parser('user', help='Print user data.') cmds.add_parser('recent', help='List recently changed objects.') cmd = cmds.add_parser('info', help='Display object metadata.') cmd.add_argument('object', nargs='?', default='me/skydrive', help='Object to get info on (default: %(default)s).') cmd = cmds.add_parser('info_set', help='Manipulate object metadata.') cmd.add_argument('object', help='Object to manipulate metadata for.') cmd.add_argument('data', help='JSON mapping of values to set (example: {"name": "new_file_name.jpg"}).') cmd = cmds.add_parser('link', help='Get a link to a file.') cmd.add_argument('object', help='Object to get link for.') cmd.add_argument('-t', '--type', default='shared_read_link', help='Type of link to request. Possible values' ' (default: %(default)s): shared_read_link, embed, shared_edit_link.') cmd = cmds.add_parser('ls', help='List folder contents.') cmd.add_argument('folder', nargs='?', default='me/skydrive', help='Folder to list contents of (default: %(default)s).') cmd.add_argument('-r', '--range', metavar='{[offset]-[limit] | limit}', help='List only specified range of objects inside.' ' Can be either dash-separated "offset-limit" tuple' ' (any of these can be omitted) or a single "limit" number.') cmd.add_argument('-o', '--objects', action='store_true', help='Dump full objects, not just name and id.') cmd = cmds.add_parser('mkdir', help='Create a folder.') cmd.add_argument('name', help='Name (or a path consisting of dirname + basename) of a folder to create.') cmd.add_argument('folder', nargs='?', default=None, help='Parent folder (default: me/skydrive).') cmd.add_argument('-m', '--metadata', help='JSON mappings of metadata to set for the created folder.' ' Optonal. Example: {"description": "Photos from last trip to Mordor"}') cmd = cmds.add_parser('get', help='Download file contents.') cmd.add_argument('file', help='File (object) to read.') cmd.add_argument('file_dst', nargs='?', help='Name/path to save file (object) as.') cmd.add_argument('-b', '--byte-range', help='Specific range of bytes to read from a file (default: read all).' ' Should be specified in rfc2616 Range HTTP header format.' ' Examples: 0-499 (start - 499), -500 (end-500 to end).') cmd = cmds.add_parser('put', help='Upload a file.') cmd.add_argument('file', help='Path to a local file to upload.') cmd.add_argument('folder', nargs='?', default='me/skydrive', help='Folder to put file into (default: %(default)s).') cmd.add_argument('-n', '--no-overwrite', action='store_true', default=None, help='Do not overwrite existing files with the same "name" attribute (visible name).' ' Default (and documented) API behavior is to overwrite such files.') cmd.add_argument('-d', '--no-downsize', action='store_true', default=None, help='Disable automatic downsizing when uploading a large image.' ' Default (and documented) API behavior is to downsize images.') cmd.add_argument('-b', '--bits', action='store_true', help='Force usage of BITS API (uploads via multiple http requests).' ' Default is to only fallback to it for large (wrt API limits) files.') cmd.add_argument('--bits-frag-bytes', type=int, metavar='number', default=api_v5.PersistentOneDriveAPI.api_bits_default_frag_bytes, help='Fragment size for using BITS API (if used), in bytes. Default: %(default)s') cmd.add_argument('--bits-do-auth-refresh-before-commit-hack', action='store_true', help='Do auth_refresh trick before upload session commit request.' ' This is reported to avoid current (as of 2015-01-16) http 5XX errors from the API.' ' See github issue #39, gist with BITS API spec and the README file for more details.') cmd = cmds.add_parser('cp', help='Copy file to a folder.') cmd.add_argument('file', help='File (object) to copy.') cmd.add_argument('folder', nargs='?', default='me/skydrive', help='Folder to copy file to (default: %(default)s).') cmd = cmds.add_parser('mv', help='Move file to a folder.') cmd.add_argument('file', help='File (object) to move.') cmd.add_argument('folder', nargs='?', default='me/skydrive', help='Folder to move file to (default: %(default)s).') cmd = cmds.add_parser('rm', help='Remove object (file or folder).') cmd.add_argument('object', nargs='+', help='Object(s) to remove.') cmd = cmds.add_parser('comments', help='Show comments for a file, object or folder.') cmd.add_argument('object', help='Object to show comments for.') cmd = cmds.add_parser('comment_add', help='Add comment for a file, object or folder.') cmd.add_argument('object', help='Object to add comment for.') cmd.add_argument('message', help='Comment message to add.') cmd = cmds.add_parser('comment_delete', help='Delete comment from a file, object or folder.') cmd.add_argument('comment_id', help='ID of the comment to remove (use "comments"' ' action to get comment ids along with the messages).') cmd = cmds.add_parser('tree', help='Show contents of onedrive (or folder) as a tree of file/folder names.' ' Note that this operation will have to (separately) request a listing of every' ' folder under the specified one, so can be quite slow for large number of these.') cmd.add_argument('folder', nargs='?', default='me/skydrive', help='Folder to display contents of (default: %(default)s).') cmd.add_argument('-o', '--objects', action='store_true', help='Dump full objects, not just name and type.') optz = parser.parse_args() if optz.path and optz.id: parser.error('--path and --id options cannot be used together.') if optz.encoding.strip('"') in [None, '', 'detect']: optz.encoding = None if optz.encoding: global force_encoding force_encoding = optz.encoding reload(sys) sys.setdefaultencoding(force_encoding) global log log = logging.getLogger() logging.basicConfig(level=logging.WARNING if not optz.debug else logging.DEBUG) api = api_v5.PersistentOneDriveAPI.from_conf(optz.config) res = xres = None resolve_path = ( (lambda s: id_match(s) or api.resolve_path(s))\ if not optz.path else api.resolve_path ) if not optz.id else (lambda obj_id: obj_id) # Make best-effort to decode all CLI options to unicode for k, v in vars(optz).viewitems(): if isinstance(v, bytes): setattr(optz, k, decode_obj(v)) elif isinstance(v, list): setattr(optz, k, map(decode_obj, v)) if optz.call == 'auth': if not optz.url: print( 'Visit the following URL in any web browser (firefox, chrome, safari, etc),\n' ' authorize there, confirm access permissions, and paste URL of an empty page\n' ' (starting with "https://login.live.com/oauth20_desktop.srf")' ' you will get redirected to in the end.' ) print( 'Alternatively, use the returned (after redirects)' ' URL with "{} auth <URL>" command.\n'.format(sys.argv[0]) ) print('URL to visit: {}\n'.format(api.auth_user_get_url())) try: import readline # for better compatibility with terminal quirks, see #40 except ImportError: pass optz.url = raw_input('URL after last redirect: ').strip() if optz.url: api.auth_user_process_url(optz.url) api.auth_get_token() print('API authorization was completed successfully.') elif optz.call == 'auth_refresh': xres = dict(scope_granted=api.auth_get_token()) elif optz.call == 'quota': df, ds = map(size_units, api.get_quota()) res = dict(free='{:.1f}{}'.format(*df), quota='{:.1f}{}'.format(*ds)) elif optz.call == 'user': res = api.get_user_data() elif optz.call == 'recent': res = api('me/skydrive/recent_docs')['data'] elif optz.call == 'ls': offset = limit = None if optz.range: span = re.search(r'^(\d+)?[-:](\d+)?$', optz.range) try: if not span: limit = int(optz.range) else: offset, limit = map(int, span.groups()) except ValueError: parser.error( '--range argument must be in the "[offset]-[limit]"' ' or just "limit" format, with integers as both offset and' ' limit (if not omitted). Provided: {}'.format(optz.range) ) res = sorted( api.listdir(resolve_path(optz.folder), offset=offset, limit=limit), key=op.itemgetter('name') ) if not optz.objects: res = map(op.itemgetter('name'), res) elif optz.call == 'info': res = api.info(resolve_path(optz.object)) elif optz.call == 'info_set': xres = api.info_update(resolve_path(optz.object), json.loads(optz.data)) elif optz.call == 'link': res = api.link(resolve_path(optz.object), optz.type) elif optz.call == 'comments': res = api.comments(resolve_path(optz.object)) elif optz.call == 'comment_add': res = api.comment_add(resolve_path(optz.object), optz.message) elif optz.call == 'comment_delete': res = api.comment_delete(optz.comment_id) elif optz.call == 'mkdir': name, path = optz.name.replace('\\', '/'), optz.folder if '/' in name: name, path_ext = ubasename(name), udirname(name) path = ujoin(path, path_ext.strip('/')) if path else path_ext xres = api.mkdir( name=name, folder_id=resolve_path(path), metadata=optz.metadata and json.loads(optz.metadata) or dict() ) elif optz.call == 'get': contents = api.get(resolve_path(optz.file), byte_range=optz.byte_range) if optz.file_dst: dst_dir = dirname(abspath(optz.file_dst)) if not isdir(dst_dir): os.makedirs(dst_dir) with open(optz.file_dst, "wb") as dst: dst.write(contents) else: sys.stdout.write(contents) sys.stdout.flush() elif optz.call == 'put': dst = optz.folder if optz.bits_do_auth_refresh_before_commit_hack: api.api_bits_auth_refresh_before_commit_hack = True if optz.bits_frag_bytes > 0: api.api_bits_default_frag_bytes = optz.bits_frag_bytes if dst is not None: xres = api.put( optz.file, resolve_path(dst), bits_api_fallback=0 if optz.bits else True, # 0 = "always use BITS" overwrite=optz.no_overwrite and False, downsize=optz.no_downsize and False ) elif optz.call in ['cp', 'mv']: argz = map(resolve_path, [optz.file, optz.folder]) xres = (api.move if optz.call == 'mv' else api.copy)(*argz) elif optz.call == 'rm': for obj in it.imap(resolve_path, optz.object): xres = api.delete(obj) elif optz.call == 'tree': def recurse(obj_id): node = tree_node() for obj in api.listdir(obj_id): # Make sure to dump files as lists with -o, # not dicts, to make them distinguishable from dirs res = obj['type'] if not optz.objects else [obj['type'], obj] node[obj['name']] = recurse(obj['id']) \ if obj['type'] in ['folder', 'album'] else res return node root_id = resolve_path(optz.folder) res = {api.info(root_id)['name']: recurse(root_id)} else: parser.error('Unrecognized command: {}'.format(optz.call)) if res is not None: print_result(res, tpl=optz.object_key, file=sys.stdout) if optz.debug and xres is not None: buff = io.StringIO() print_result(xres, file=buff) log.debug('Call result:\n{0}\n{1}{0}'.format('-' * 20, buff.getvalue())) if __name__ == '__main__': main()
#-*- coding: utf-8 -*- from __future__ import unicode_literals, print_function import itertools as it, operator as op, functools as ft from datetime import datetime, timedelta from posixpath import join as ujoin # used for url pahs from os.path import join, basename, dirname, exists import os, sys, io, urllib, urlparse, json, types, re from onedrive.conf import ConfigMixin import logging log = logging.getLogger(__name__) class OneDriveInteractionError(Exception): pass class ProtocolError(OneDriveInteractionError): def __init__(self, code, msg, *args): assert isinstance(code, (int, types.NoneType)), code super(ProtocolError, self).__init__(code, msg, *args) self.code = code class AuthenticationError(OneDriveInteractionError): pass class AuthMissingError(AuthenticationError): pass class APIAuthError(AuthenticationError): pass class NoAPISupportError(OneDriveInteractionError): '''Request operation is known to be not supported by the OneDrive API. Can be raised on e.g. fallback from regular upload to BITS API due to file size limitations, where flags like "overwrite" are not supported (always on).''' class DoesNotExists(OneDriveInteractionError): 'Only raised from OneDriveAPI.resolve_path().' class BITSFragment(object): bs = 1 * 2**20 def __init__(self, src, frag_len): self.src, self.pos, self.frag_len = src, src.tell(), frag_len self.pos_max = self.pos + self.frag_len def fileno(self): return self.src.fileno() def seek(self, pos, flags=0): assert pos < self.frag_len and flags == 0, [pos, flags] self.src.seek(self.pos + pos) def read(self, bs=None): bs = min(bs, self.pos_max - self.src.tell())\ if bs is not None else (self.pos_max - self.src.tell()) return self.src.read(bs) def __iter__(self): return iter(ft.partial(self.read, self.bs), b'') class OneDriveHTTPClient(object): #: Extra keywords to pass to each "requests.Session.request()" call. #: For full list of these see: #: http://docs.python-requests.org/en/latest/api/#requests.Session.request request_extra_keywords = None # Example: dict(timeout=(20.0, 10.0)) #: Keywords to pass to "requests.adapters.HTTPAdapter" subclass init. #: Only used with later versions of "requests" than 1.0.0 (where adapters were introduced). #: Please do not touch these unless you've #: read requests module documentation on what they actually do. request_adapter_settings = None # Example: dict(pool_maxsize=50) #: Dict of headers to pass on with each request made. #: Can be useful if you want to e.g. disable gzip/deflate #: compression or other http features that are used by default. request_base_headers = None _requests_setup_done = False _requests_base_keywords = None def _requests_setup(self, requests, **adapter_kws): session, requests_version = None, requests.__version__ log.debug('Using "requests" module version: %r', requests_version) try: requests_version = tuple(it.imap(int, requests_version.split('.'))) except: requests_version = 999, 0, 0 # most likely some future version if requests_version < (0, 14, 0): raise RuntimeError( ( 'Version of the "requests" python module (used by python-onedrive)' ' is incompatible - need at least 0.14.0, but detected {}.' ' Please update it (or file an issue if it worked before).' )\ .format(requests.__version__) ) if requests_version >= (1, 0, 0): session = requests.Session() session.mount('https://', requests.adapters.HTTPAdapter(**adapter_kws)) else: log.warn( 'Not using request_adapter_settings, as these should not be' ' supported by detected requests module version: %s', requests_version ) if hasattr(sys, '_MEIPASS'): # Fix cacert.pem path for running from PyInstaller bundle cacert_pem = requests.certs.where() if not exists(cacert_pem): from pkg_resources import resource_filename cacert_pem = resource_filename('requests', 'cacert.pem') if not exists(cacert_pem): cacert_pem = join(sys._MEIPASS, 'requests', 'cacert.pem') if not exists(cacert_pem): cacert_pem = join(sys._MEIPASS, 'cacert.pem') if not exists(cacert_pem): raise OneDriveInteractionError( 'Failed to find requests cacert.pem bundle when running under PyInstaller.' ) self._requests_base_keywords = (self._requests_base_keywords or dict()).copy() self._requests_base_keywords.setdefault('verify', cacert_pem) log.debug( 'Adjusted "requests" default ca-bundle' ' path (to run under PyInstaller) to: %s', cacert_pem ) if requests_version >= (2, 4, 0): # Workaround for https://github.com/certifi/python-certifi/issues/26 import ssl if ssl.OPENSSL_VERSION_INFO < (1, 0, 2): try: import certifi except ImportError: pass else: certifi_issue_url = 'https://github.com/certifi/python-certifi/issues/26' if hasattr(certifi, 'old_where'): cacert_pem = certifi.old_where() else: cacert_pem = join(dirname(requests.certs.__file__), 'cacert.pem') if not exists(cacert_pem): cacert_pem = None log.warn( 'Failed to find requests' ' certificate bundle for woraround to %s', certifi_issue_url ) if cacert_pem: self._requests_base_keywords = (self._requests_base_keywords or dict()).copy() self._requests_base_keywords.setdefault('verify', cacert_pem) log.debug( 'Adjusted "requests" default ca-bundle path, to work around %s ' ' [OpenSSL version %s, requests %s (>2.4.0) and certifi available at %r], to: %s', certifi_issue_url, ssl.OPENSSL_VERSION_INFO, requests_version, certifi.__file__, cacert_pem ) self._requests_setup_done = True return session def request( self, url, method='get', data=None, files=None, raw=False, raw_all=False, headers=dict(), raise_for=dict(), session=None ): '''Make synchronous HTTP request. Can be overridden to use different http module (e.g. urllib2, twisted, etc).''' try: import requests # import here to avoid dependency on the module except ImportError as exc: exc.args = ( 'Unable to find/import "requests" module.' ' Please make sure that it is installed, e.g. by running "pip install requests" command.' '\nFor more info, visit: http://docs.python-requests.org/en/latest/user/install/',) raise exc if not self._requests_setup_done: patched_session = self._requests_setup( requests, **(self.request_adapter_settings or dict()) ) if patched_session is not None: self._requests_session = patched_session if session is None: session = getattr(self, '_requests_session', None) if not session: session = self._requests_session = requests.session() elif not session: session = requests method = method.lower() kwz = (self._requests_base_keywords or dict()).copy() kwz.update(self.request_extra_keywords or dict()) kwz, func = dict(), ft.partial(session.request, method.upper(), **kwz) kwz_headers = (self.request_base_headers or dict()).copy() kwz_headers.update(headers) if data is not None: if method in ['post', 'put']: if all(hasattr(data, k) for k in ['seek', 'read']): # Force chunked encoding for files, as uploads hang otherwise # See https://github.com/mk-fg/python-onedrive/issues/30 for details data.seek(0) kwz['data'] = iter(ft.partial(data.read, 200 * 2**10), b'') else: kwz['data'] = data else: kwz['data'] = json.dumps(data) kwz_headers.setdefault('Content-Type', 'application/json') if files is not None: # requests-2+ doesn't seem to add default content-type header for k, file_tuple in files.iteritems(): if len(file_tuple) == 2: files[k] = tuple(file_tuple) + ('application/octet-stream',) # Rewind is necessary because request can be repeated due to auth failure file_tuple[1].seek(0) kwz['files'] = files if kwz_headers: kwz['headers'] = kwz_headers code = res = None try: res = func(url, **kwz) # log.debug('Response headers: %s', res.headers) code = res.status_code if code == requests.codes.no_content: return if code != requests.codes.ok: res.raise_for_status() except requests.RequestException as err: message = b'{0} [type: {1}, repr: {0!r}]'.format(err, type(err)) if (res and getattr(res, 'text', None)) is not None: # "res" with non-200 code can be falsy message = res.text try: message = json.loads(message) except: message = '{}: {!r}'.format(str(err), message)[:300] else: msg_err, msg_data = message.pop('error', None), message if msg_err: message = '{}: {}'.format(msg_err.get('code', err), msg_err.get('message', msg_err)) if msg_data: message = '{} (data: {})'.format(message, msg_data) raise raise_for.get(code, ProtocolError)(code, message) if raw: res = res.content elif raw_all: res = code, dict(res.headers.items()), res.content else: res = json.loads(res.text) return res class OneDriveAuth(OneDriveHTTPClient): #: Client id/secret should be static on per-application basis. #: Can be received from LiveConnect by any registered user at: #: https://account.live.com/developers/applications/create #: API ToS can be found at: #: http://msdn.microsoft.com/en-US/library/live/ff765012 client_id = client_secret = None auth_url_user = 'https://login.live.com/oauth20_authorize.srf' auth_url_token = 'https://login.live.com/oauth20_token.srf' auth_scope = 'wl.skydrive', 'wl.skydrive_update', 'wl.offline_access' auth_redirect_uri_mobile = 'https://login.live.com/oauth20_desktop.srf' #: Set by auth_get_token() method, not used internally. #: Might be useful for debugging or extension purposes. auth_access_expires = auth_access_data_raw = None #: At least one of auth_code, auth_refresh_token #: or auth_access_token should be set before data requests. auth_code = auth_refresh_token = auth_access_token = None #: This (default) redirect_uri is special - app must be marked as "mobile" to use it. auth_redirect_uri = auth_redirect_uri_mobile def __init__(self, **config): 'Initialize API wrapper class with specified properties set.' for k, v in config.viewitems(): try: getattr(self, k) except AttributeError: raise AttributeError('Unrecognized configuration key: {}'.format(k)) setattr(self, k, v) def auth_user_get_url(self, scope=None): 'Build authorization URL for User Agent.' if not self.client_id: raise AuthMissingError('No client_id specified') return '{}?{}'.format(self.auth_url_user, urllib.urlencode(dict( client_id=self.client_id, scope=' '.join(scope or self.auth_scope), response_type='code', redirect_uri=self.auth_redirect_uri ))) def auth_user_process_url(self, url): 'Process tokens and errors from redirect_uri.' url = urlparse.urlparse(url) url_qs = dict(it.chain.from_iterable( urlparse.parse_qsl(v) for v in [url.query, url.fragment] )) if url_qs.get('error'): raise APIAuthError( '{} :: {}'.format(url_qs['error'], url_qs.get('error_description')) ) self.auth_code = url_qs['code'] return self.auth_code def auth_get_token(self, check_scope=True): 'Refresh or acquire access_token.' res = self.auth_access_data_raw = self._auth_token_request() return self._auth_token_process(res, check_scope=check_scope) def _auth_token_request(self): post_data = dict( client_id=self.client_id, client_secret=self.client_secret, redirect_uri=self.auth_redirect_uri ) if not (self.auth_refresh_token or self.auth_code): raise AuthMissingError( 'One of auth_refresh_token' ' or auth_code must be provided for authentication.' ) elif not self.auth_refresh_token: log.debug('Requesting new access_token through authorization_code grant') post_data.update(code=self.auth_code, grant_type='authorization_code') else: if self.auth_redirect_uri == self.auth_redirect_uri_mobile: del post_data['client_secret'] # not necessary for "mobile" apps log.debug('Refreshing access_token') post_data.update(refresh_token=self.auth_refresh_token, grant_type='refresh_token') post_data_missing_keys = list( k for k in ['client_id', 'client_secret', 'code', 'refresh_token', 'grant_type'] if k in post_data and not post_data[k] ) if post_data_missing_keys: raise AuthMissingError( 'Insufficient authentication' ' data provided (missing keys: {})'.format(post_data_missing_keys) ) return self.request(self.auth_url_token, method='post', data=post_data) def _auth_token_process(self, res, check_scope=True): assert res['token_type'] == 'bearer' for k in 'access_token', 'refresh_token': if k in res: setattr(self, 'auth_{}'.format(k), res[k]) self.auth_access_expires = None if 'expires_in' not in res\ else (datetime.utcnow() + timedelta(0, res['expires_in'])) scope_granted = res.get('scope', '').split() if check_scope and set(self.auth_scope) != set(scope_granted): raise AuthenticationError( 'Granted scope ({}) does not match requested one ({}).' .format(', '.join(scope_granted), ', '.join(self.auth_scope)) ) return scope_granted class OneDriveAPIWrapper(OneDriveAuth): '''Less-biased OneDrive API wrapper class. All calls made here return result of self.request() call directly, so it can easily be made async (e.g. return twisted deferred object) by overriding http request method in subclass.''' api_url_base = 'https://apis.live.net/v5.0/' #: Limit on file uploads via single PUT request, imposed by the API. #: Used to opportunistically fallback to BITS API #: (uploads via several http requests) in the "put" method. api_put_max_bytes = int(95e6) api_bits_url_by_id = ( 'https://cid-{user_id}.users.storage.live.com/items/{folder_id}/{filename}' ) api_bits_url_by_path = ( 'https://cid-{user_id}.users.storage.live.com' '/users/0x{user_id}/LiveFolders/{file_path}' ) api_bits_protocol_id = '{7df0354d-249b-430f-820d-3d2a9bef4931}' api_bits_default_frag_bytes = 10 * 2**20 # 10 MiB api_bits_auth_refresh_before_commit_hack = False _user_id = None # cached from get_user_id calls def _api_url( self, path_or_url, query=dict(), pass_access_token=True, pass_empty_values=False ): query = query.copy() if pass_access_token: query.setdefault('access_token', self.auth_access_token) if not pass_empty_values: for k, v in query.viewitems(): if not v and v != 0: raise AuthMissingError( 'Empty key {!r} for API call (path/url: {})'.format(k, path_or_url) ) if re.search(r'^(https?|spdy):', path_or_url): if '?' in path_or_url: raise AuthMissingError('URL must not include query: {}'.format(path_or_url)) path_or_url = path_or_url + '?{}'.format(urllib.urlencode(query)) else: path_or_url = urlparse.urljoin( self.api_url_base, '{}?{}'.format(path_or_url, urllib.urlencode(query)) ) return path_or_url def _api_url_join(self, *slugs): slugs = list( urllib.quote(slug.encode('utf-8') if isinstance(slug, unicode) else slug) for slug in slugs ) return ujoin(*slugs) def _process_upload_source(self, path_or_tuple): name, src = (basename(path_or_tuple), open(path_or_tuple, 'rb'))\ if isinstance(path_or_tuple, types.StringTypes)\ else (path_or_tuple[0], path_or_tuple[1]) if isinstance(src, types.StringTypes): src = io.BytesIO(src) return name, src def _translate_api_flag(self, val, name=None, special_vals=None): if special_vals and val in special_vals: return val flag_val_dict = { None: None, 'false': 'false', False: 'false', 'true': 'true', True: 'true' } try: return flag_val_dict[val] except KeyError: raise ValueError( 'Parameter{} value must be boolean True/False{}, not {!r}'\ .format( ' ({!r})'.format(name) if name else '', ' or one of {}'.format(list(special_vals)) if special_vals else '', val ) ) def __call__( self, url='me/skydrive', query=dict(), query_filter=True, auth_header=False, auto_refresh_token=True, **request_kwz ): '''Make an arbitrary call to LiveConnect API. Shouldn't be used directly under most circumstances.''' if query_filter: query = dict((k, v) for k, v in query.viewitems() if v is not None) if auth_header: request_kwz.setdefault('headers', dict())['Authorization'] =\ 'Bearer {}'.format(self.auth_access_token) kwz = request_kwz.copy() kwz.setdefault('raise_for', dict())[401] = APIAuthError api_url = ft.partial( self._api_url, url, query, pass_access_token=not auth_header ) try: return self.request(api_url(), **kwz) except APIAuthError: if not auto_refresh_token: raise self.auth_get_token() if auth_header: # update auth header with a new token request_kwz['headers']['Authorization'] =\ 'Bearer {}'.format(self.auth_access_token) return self.request(api_url(), **request_kwz) def get_quota(self): 'Get OneDrive object representing quota.' return self('me/skydrive/quota') def get_user_data(self): 'Get OneDrive object representing user metadata (including user "id").' return self('me') def get_user_id(self): 'Returns "id" of a OneDrive user.' if self._user_id is None: self._user_id = self.get_user_data()['id'] return self._user_id def listdir(self, folder_id='me/skydrive', limit=None, offset=None): 'Get OneDrive object representing list of objects in a folder.' return self(self._api_url_join(folder_id, 'files'), dict(limit=limit, offset=offset)) def info(self, obj_id='me/skydrive'): '''Return metadata of a specified object. See http://msdn.microsoft.com/en-us/library/live/hh243648.aspx for the list and description of metadata keys for each object type.''' return self(obj_id) def get(self, obj_id, byte_range=None): '''Download and return a file object or a specified byte_range from it. See HTTP Range header (rfc2616) for possible byte_range formats, Examples: "0-499" - byte offsets 0-499 (inclusive), "-500" - final 500 bytes.''' kwz = dict() if byte_range: kwz['headers'] = dict(Range='bytes={}'.format(byte_range)) return self(self._api_url_join(obj_id, 'content'), dict(download='true'), raw=True, **kwz) def put( self, path_or_tuple, folder_id='me/skydrive', overwrite=None, downsize=None, bits_api_fallback=True ): '''Upload a file (object), possibly overwriting (default behavior) a file with the same "name" attribute, if it exists. First argument can be either path to a local file or tuple of "(name, file)", where "file" can be either a file-like object or just a string of bytes. overwrite option can be set to False to allow two identically-named files or "ChooseNewName" to let OneDrive derive some similar unique name. Behavior of this option mimics underlying API. downsize is a true/false API flag, similar to overwrite. bits_api_fallback can be either True/False or an integer (number of bytes), and determines whether method will fall back to using BITS API (as implemented by "put_bits" method) for large files. Default "True" (bool) value will use non-BITS file size limit (api_put_max_bytes, ~100 MiB) as a fallback threshold, passing False will force using single-request uploads.''' api_overwrite = self._translate_api_flag(overwrite, 'overwrite', ['ChooseNewName']) api_downsize = self._translate_api_flag(downsize, 'downsize') name, src = self._process_upload_source(path_or_tuple) if not isinstance(bits_api_fallback, (int, float, long)): bits_api_fallback = bool(bits_api_fallback) if bits_api_fallback is not False: if bits_api_fallback is True: bits_api_fallback = self.api_put_max_bytes src.seek(0, os.SEEK_END) if src.tell() >= bits_api_fallback: if bits_api_fallback > 0: # not really a "fallback" in this case log.info( 'Falling-back to using BITS API due to file size (%.1f MiB > %.1f MiB)', *((float(v) / 2**20) for v in [src.tell(), bits_api_fallback]) ) if overwrite is not None and api_overwrite != 'true': raise NoAPISupportError( 'Passed "overwrite" flag (value: {!r})' ' is not supported by the BITS API (always "true" there)'.format(overwrite) ) if downsize is not None: log.info( 'Passed "downsize" flag (value: %r) will not' ' be used with BITS API, as it is not supported there', downsize ) file_id = self.put_bits(path_or_tuple, folder_id=folder_id) # XXX: overwrite/downsize return self.info(file_id) # PUT seem to have better support for unicode # filenames and is recommended in the API docs, see #19. # return self( self._api_url_join(folder_id, 'files'), # dict(overwrite=api_overwrite, downsize_photo_uploads=api_downsize), # method='post', files=dict(file=(name, src)) ) return self( self._api_url_join(folder_id, 'files', name), dict(overwrite=api_overwrite, downsize_photo_uploads=api_downsize), data=src, method='put', auth_header=True ) def put_bits( self, path_or_tuple, folder_id=None, folder_path=None, frag_bytes=None, raw_id=False, chunk_callback=None ): '''Upload a file (object) using BITS API (via several http requests), possibly overwriting (default behavior) a file with the same "name" attribute, if it exists. Unlike "put" method, uploads to "folder_path" (instead of folder_id) are supported here. Either folder path or id can be specified, but not both. Passed "chunk_callback" function (if any) will be called after each uploaded chunk with keyword parameters corresponding to upload state and BITS session info required to resume it, if necessary. Returns id of the uploaded file, as returned by the API if raw_id=True is passed, otherwise in a consistent (with other calls) "file.{user_id}.{file_id}" format (default).''' # XXX: overwrite/downsize are not documented/supported here (yet?) name, src = self._process_upload_source(path_or_tuple) if folder_id is not None and folder_path is not None: raise ValueError('Either "folder_id" or "folder_path" can be specified, but not both.') if folder_id is None and folder_path is None: folder_id = 'me/skydrive' if folder_id and re.search(r'^me(/.*)$', folder_id): folder_id = self.info(folder_id)['id'] if not frag_bytes: frag_bytes = self.api_bits_default_frag_bytes user_id = self.get_user_id() if folder_id: # workaround for API-ids inconsistency between BITS and regular API match = re.search( r'^(?i)folder.[a-f0-9]+.' '(?P<user_id>[a-f0-9]+(?P<folder_n>!\d+)?)$', folder_id ) if match and not match.group('folder_n'): # root folder is a special case and can't seem to be accessed by id folder_id, folder_path = None, '' else: if not match: raise ValueError('Failed to process folder_id for BITS API: {!r}'.format(folder_id)) folder_id = match.group('user_id') if folder_id: url = self.api_bits_url_by_id.format(folder_id=folder_id, user_id=user_id, filename=name) else: url = self.api_bits_url_by_path.format( folder_id=folder_id, user_id=user_id, file_path=ujoin(folder_path, name).lstrip('/') ) code, headers, body = self( url, method='post', auth_header=True, raw_all=True, headers={ 'X-Http-Method-Override': 'BITS_POST', 'BITS-Packet-Type': 'Create-Session', 'BITS-Supported-Protocols': self.api_bits_protocol_id }) h = lambda k,hs=dict((k.lower(), v) for k,v in headers.viewitems()): hs.get(k, '') checks = [ code == 201, h('bits-packet-type').lower() == 'ack', h('bits-protocol').lower() == self.api_bits_protocol_id.lower(), h('bits-session-id') ] if not all(checks): raise ProtocolError(code, 'Invalid BITS Create-Session response', headers, body, checks) bits_sid = h('bits-session-id') src.seek(0, os.SEEK_END) c, src_len = 0, src.tell() cn = src_len / frag_bytes if frag_bytes * cn != src_len: cn += 1 src.seek(0) for n in xrange(1, cn+1): log.debug( 'Uploading BITS fragment' ' %s / %s (max-size: %.2f MiB)', n, cn, frag_bytes / float(2**20) ) frag = BITSFragment(src, frag_bytes) c1 = c + frag_bytes self( url, method='post', raw=True, data=frag, headers={ 'X-Http-Method-Override': 'BITS_POST', 'BITS-Packet-Type': 'Fragment', 'BITS-Session-Id': bits_sid, 'Content-Range': 'bytes {}-{}/{}'.format(c, min(c1, src_len)-1, src_len) }) c = c1 if chunk_callback: chunk_callback( bytes_transferred=c, bytes_total=src_len, chunks_transferred=n, chunks_total=cn, bits_session_id=bits_sid ) if self.api_bits_auth_refresh_before_commit_hack: # As per #39 and comments under the gist with the spec, # apparently this trick fixes occasional http-5XX errors from the API self.auth_get_token() code, headers, body = self( url, method='post', auth_header=True, raw_all=True, headers={ 'X-Http-Method-Override': 'BITS_POST', 'BITS-Packet-Type': 'Close-Session', 'BITS-Session-Id': bits_sid }) h = lambda k,hs=dict((k.lower(), v) for k,v in headers.viewitems()): hs.get(k, '') checks = [code in [200, 201], h('bits-packet-type').lower() == 'ack' ] # int(h('bits-received-content-range') or 0) == src_len -- documented, but missing # h('bits-session-id') == bits_sid -- documented, but missing if not all(checks): raise ProtocolError(code, 'Invalid BITS Close-Session response', headers, body, checks) # Workaround for API-ids inconsistency between BITS and regular API file_id = h('x-resource-id') if not raw_id: file_id = 'file.{}.{}'.format(user_id, file_id) return file_id def mkdir(self, name=None, folder_id='me/skydrive', metadata=dict()): '''Create a folder with a specified "name" attribute. folder_id allows to specify a parent folder. metadata mapping may contain additional folder properties to pass to an API.''' metadata = metadata.copy() if name: metadata['name'] = name return self(folder_id, data=metadata, method='post', auth_header=True) def delete(self, obj_id): 'Delete specified object.' return self(obj_id, method='delete') def info_update(self, obj_id, data): '''Update metadata with of a specified object. See http://msdn.microsoft.com/en-us/library/live/hh243648.aspx for the list of RW keys for each object type.''' return self(obj_id, method='put', data=data, auth_header=True) def link(self, obj_id, link_type='shared_read_link'): '''Return a preauthenticated (usable by anyone) link to a specified object. Object will be considered "shared" by OneDrive, even if link is never actually used. link_type can be either "embed" (returns html), "shared_read_link" or "shared_edit_link".''' assert link_type in ['embed', 'shared_read_link', 'shared_edit_link'] return self(self._api_url_join(obj_id, link_type), method='get') def copy(self, obj_id, folder_id, move=False): '''Copy specified file (object) to a folder with a given ID. Well-known folder names (like "me/skydrive") don't seem to work here. Folders cannot be copied; this is an API limitation.''' return self( obj_id, method='copy' if not move else 'move', data=dict(destination=folder_id), auth_header=True ) def move(self, obj_id, folder_id): '''Move specified file (object) to a folder. Note that folders cannot be moved, this is an API limitation.''' return self.copy(obj_id, folder_id, move=True) def comments(self, obj_id): 'Get OneDrive object representing a list of comments for an object.' return self(self._api_url_join(obj_id, 'comments')) def comment_add(self, obj_id, message): 'Add comment message to a specified object.' return self( self._api_url_join(obj_id, 'comments'), method='post', data=dict(message=message), auth_header=True ) def comment_delete(self, comment_id): '''Delete specified comment. comment_id can be acquired by listing comments for an object.''' return self(comment_id, method='delete') class OneDriveAPI(OneDriveAPIWrapper): '''Biased synchronous OneDrive API interface. Adds some derivative convenience methods over OneDriveAPIWrapper.''' def resolve_path(self, path, root_id='me/skydrive', objects=False, listdir_limit=500): '''Return id (or metadata) of an object, specified by chain (iterable or fs-style path string) of "name" attributes of its ancestors, or raises DoesNotExists error. Requires many calls to resolve each name in path, so use with care. root_id parameter allows to specify path relative to some folder_id (default: me/skydrive).''' if path: if isinstance(path, types.StringTypes): if not path.startswith('me/skydrive'): # Split path by both kinds of slashes path = filter(None, it.chain.from_iterable(p.split('\\') for p in path.split('/'))) else: root_id, path = path, None if path: try: for i, name in enumerate(path): offset = None while True: obj_list = self.listdir(root_id, offset=offset, limit=listdir_limit) try: root_id = dict(it.imap(op.itemgetter('name', 'id'), obj_list))[name] except KeyError: if len(obj_list) < listdir_limit: raise # assuming that it's the last page offset = (offset or 0) + listdir_limit else: break except (KeyError, ProtocolError) as err: if isinstance(err, ProtocolError) and err.code != 404: raise raise DoesNotExists(root_id, path[i:]) return root_id if not objects else self.info(root_id) def get_quota(self): 'Return tuple of (bytes_available, bytes_quota).' return op.itemgetter('available', 'quota')(super(OneDriveAPI, self).get_quota()) def listdir(self, folder_id='me/skydrive', type_filter=None, limit=None, offset=None): '''Return a list of objects in the specified folder_id. limit is passed to the API, so might be used as optimization. type_filter can be set to type (str) or sequence of object types to return, post-api-call processing.''' lst = super(OneDriveAPI, self)\ .listdir(folder_id=folder_id, limit=limit, offset=offset)['data'] if type_filter: if isinstance(type_filter, types.StringTypes): type_filter = {type_filter} lst = list(obj for obj in lst if obj['type'] in type_filter) return lst def copy(self, obj_id, folder_id, move=False): '''Copy specified file (object) to a folder. Note that folders cannot be copied, this is an API limitation.''' if folder_id.startswith('me/skydrive'): log.info( 'Special folder names (like "me/skydrive") dont' ' seem to work with copy/move operations, resolving it to id' ) folder_id = self.info(folder_id)['id'] return super(OneDriveAPI, self).copy(obj_id, folder_id, move=move) def comments(self, obj_id): 'Get a list of comments (message + metadata) for an object.' return super(OneDriveAPI, self).comments(obj_id)['data'] class PersistentOneDriveAPI(OneDriveAPI, ConfigMixin): conf_raise_structure_errors = True @ft.wraps(OneDriveAPI.auth_get_token) def auth_get_token(self, *argz, **kwz): # Wrapped to push new tokens to storage asap. ret = super(PersistentOneDriveAPI, self).auth_get_token(*argz, **kwz) self.sync() return ret def __del__(self): self.sync()
#-*- coding: utf-8 -*- import os if os.name == 'nt': # Needs pywin32 to work on Windows (NT, 2K, XP, _not_ /95 or /98) try: import win32con, win32file, pywintypes except ImportError as err: raise ImportError( 'Failed to import pywin32' ' extensions (make sure pywin32 is installed correctly) - {}'.format(err) ) LOCK_EX = win32con.LOCKFILE_EXCLUSIVE_LOCK LOCK_SH = 0 # the default LOCK_NB = win32con.LOCKFILE_FAIL_IMMEDIATELY __overlapped = pywintypes.OVERLAPPED() def lock(file, flags): hfile = win32file._get_osfhandle(file.fileno()) win32file.LockFileEx(hfile, flags, 0, 0x7FFFFFFF, __overlapped) def unlock(file): hfile = win32file._get_osfhandle(file.fileno()) win32file.UnlockFileEx(hfile, 0, 0x7FFFFFFF, __overlapped) elif os.name == 'posix': from fcntl import lockf, LOCK_EX, LOCK_SH, LOCK_NB, LOCK_UN def lock(file, flags): lockf(file, flags) def unlock(file): lockf(file, LOCK_UN) else: raise RuntimeError('PortaLocker only defined for nt and posix platforms')
#-*- coding: utf-8 -*- from __future__ import unicode_literals, print_function import itertools as it, operator as op, functools as ft import os, sys, io, errno, tempfile, stat, re from os.path import dirname, basename import logging log = logging.getLogger(__name__) class ConfigMixin(object): #: Path to configuration file to use in from_conf() by default. conf_path_default = b'~/.lcrc' #: If set to some path, updates will be written back to it. conf_save = False #: Raise human-readable errors on structure issues, #: which assume that there is an user-accessible configuration file conf_raise_structure_errors = False #: Hierarchical list of keys to write back #: to configuration file (preserving the rest) on updates. conf_update_keys = dict( client={'id', 'secret'}, auth={'code', 'refresh_token', 'access_expires', 'access_token'}, request={'extra_keywords', 'adapter_settings', 'base_headers'} ) def __init__(self, **kwz): raise NotImplementedError('Init should be overidden with something configurable') @classmethod def from_conf(cls, path=None, **overrides): '''Initialize instance from YAML configuration file, writing updates (only to keys, specified by "conf_update_keys") back to it.''' from onedrive import portalocker import yaml if path is None: path = cls.conf_path_default log.debug('Using default state-file path: %r', path) path = os.path.expanduser(path) with open(path, 'rb') as src: portalocker.lock(src, portalocker.LOCK_SH) yaml_str = src.read() portalocker.unlock(src) conf = yaml.safe_load(yaml_str) conf.setdefault('conf_save', path) conf_cls = dict() for ns, keys in cls.conf_update_keys.viewitems(): for k in keys: try: v = conf.get(ns, dict()).get(k) except AttributeError: if not cls.conf_raise_structure_errors: raise raise KeyError(( 'Unable to get value for configuration parameter' ' "{k}" in section "{ns}", check configuration file (path: {path}) syntax' ' near the aforementioned section/value.' ).format(ns=ns, k=k, path=path)) if v is not None: conf_cls['{}_{}'.format(ns, k)] = conf[ns][k] conf_cls.update(overrides) # Hack to work around YAML parsing client_id of e.g. 000123 as an octal int if isinstance(conf.get('client', dict()).get('id'), (int, long)): log.warn( 'Detected client_id being parsed as an integer (as per yaml), trying to un-mangle it.' ' If requests will still fail afterwards, please replace it in the configuration file (path: %r),' ' also putting single or double quotes (either one should work) around the value.', path ) cid = conf['client']['id'] if not re.search(r'\b(0*)?{:d}\b'.format(cid), yaml_str)\ and re.search(r'\b(0*)?{:o}\b'.format(cid), yaml_str): cid = int('{:0}'.format(cid)) conf['client']['id'] = '{:016d}'.format(cid) self = cls(**conf_cls) self.conf_save = conf['conf_save'] return self def sync(self): if not self.conf_save: return from onedrive import portalocker import yaml retry = False with open(self.conf_save, 'r+b') as src: portalocker.lock(src, portalocker.LOCK_SH) conf_raw = src.read() conf = yaml.safe_load(io.BytesIO(conf_raw)) if conf_raw else dict() portalocker.unlock(src) conf_updated = False for ns, keys in self.conf_update_keys.viewitems(): for k in keys: v = getattr(self, '{}_{}'.format(ns, k), None) if isinstance(v, unicode): v = v.encode('utf-8') if v != conf.get(ns, dict()).get(k): # log.debug( # 'Different val ({}.{}): {!r} != {!r}'\ # .format(ns, k, v, conf.get(ns, dict()).get(k)) ) conf.setdefault(ns, dict())[k] = v conf_updated = True if conf_updated: log.debug('Updating configuration file (%r)', src.name) conf_new = yaml.safe_dump(conf, default_flow_style=False) if os.name == 'nt': # lockf + tempfile + rename doesn't work on windows due to # "[Error 32] ... being used by another process", # so this update can potentially leave broken file there # Should probably be fixed by someone who uses/knows about windows portalocker.lock(src, portalocker.LOCK_EX) src.seek(0) if src.read() != conf_raw: retry = True else: src.seek(0) src.truncate() src.write(conf_new) src.flush() portalocker.unlock(src) else: with tempfile.NamedTemporaryFile( prefix='{}.'.format(basename(self.conf_save)), dir=dirname(self.conf_save), delete=False) as tmp: try: portalocker.lock(src, portalocker.LOCK_EX) src.seek(0) if src.read() != conf_raw: retry = True else: portalocker.lock(tmp, portalocker.LOCK_EX) tmp.write(conf_new) os.fchmod(tmp.fileno(), stat.S_IMODE(os.fstat(src.fileno()).st_mode)) os.rename(tmp.name, src.name) # Non-atomic update for pids that already have fd to old file, # but (presumably) are waiting for the write-lock to be released src.seek(0) src.truncate() src.write(conf_new) finally: try: os.unlink(tmp.name) except OSError: pass if retry: log.debug( 'Configuration file (%r) was changed' ' during merge, restarting merge', self.conf_save ) return self.sync()
import { Writable } from "stream"; import { check } from "./blork.js"; /** * Create a stream that passes messages through while rewriting scope. * Replaces `[semantic-release]` with a custom scope (e.g. `[my-awesome-package]`) so output makes more sense. * * @param {stream.Writable} stream The actual stream to write messages to. * @param {string} scope The string scope for the stream (instances of the text `[semantic-release]` are replaced in the stream). * @returns {stream.Writable} Object that's compatible with stream.Writable (implements a `write()` property). * * @internal */ class RescopedStream extends Writable { // Constructor. constructor(stream, scope) { super(); check(scope, "scope: string"); check(stream, "stream: stream"); this._stream = stream; this._scope = scope; } // Custom write method. write(msg) { check(msg, "msg: string"); this._stream.write(msg.replace("[semantic-release]", `[${this._scope}]`)); } } // Exports. export default RescopedStream;
import semanticGetConfig from "semantic-release/lib/get-config.js"; import { WritableStreamBuffer } from "stream-buffers"; import { logger } from "./logger.js"; import signale from "signale"; const { Signale } = signale; /** * Get the release configuration options for a given directory. * Unfortunately we've had to copy this over from semantic-release, creating unnecessary duplication. * * @param {Object} context Object containing cwd, env, and logger properties that are passed to getConfig() * @param {Object} options Options object for the config. * @returns {Object} Returns what semantic-release's get config returns (object with options and plugins objects). * * @internal */ async function getConfigSemantic({ cwd, env, stdout, stderr }, options) { try { // Blackhole logger (so we don't clutter output with "loaded plugin" messages). const blackhole = new Signale({ stream: new WritableStreamBuffer() }); // Return semantic-release's getConfig script. return await semanticGetConfig({ cwd, env, stdout, stderr, logger: blackhole }, options); } catch (error) { // Log error and rethrow it. // istanbul ignore next (not important) logger.failure(`Error in semantic-release getConfig(): %0`, error); // istanbul ignore next (not important) throw error; } } // Exports. export default getConfigSemantic;
import { relative, resolve } from "path"; import gitLogParser from "git-log-parser"; import getStream from "get-stream"; import { execa } from "execa"; import { check, ValueError } from "./blork.js"; import cleanPath from "./cleanPath.js"; import { logger } from "./logger.js"; const { debug } = logger.withScope("msr:commitsFilter"); /** * Retrieve the list of commits on the current branch since the commit sha associated with the last release, or all the commits of the current branch if there is no last released version. * Commits are filtered to only return those that corresponding to the package directory. * * This is achieved by using "-- my/dir/path" with `git log` — passing this into gitLogParser() with * * @param {string} cwd Absolute path of the working directory the Git repo is in. * @param {string} dir Path to the target directory to filter by. Either absolute, or relative to cwd param. * @param {string|void} lastHead The SHA of the previous release * @param {string|void} firstParentBranch first-parent to determine which merges went into master * @return {Promise<Array<Commit>>} The list of commits on the branch `branch` since the last release. */ async function getCommitsFiltered(cwd, dir, lastHead = undefined, firstParentBranch) { // Clean paths and make sure directories exist. check(cwd, "cwd: directory"); check(dir, "dir: path"); cwd = cleanPath(cwd); dir = cleanPath(dir, cwd); check(dir, "dir: directory"); check(lastHead, "lastHead: alphanumeric{40}?"); // target must be inside and different than cwd. if (dir.indexOf(cwd) !== 0) throw new ValueError("dir: Must be inside cwd", dir); if (dir === cwd) throw new ValueError("dir: Must not be equal to cwd", dir); // Get top-level Git directory as it might be higher up the tree than cwd. const root = (await execa("git", ["rev-parse", "--show-toplevel"], { cwd })).stdout; // Add correct fields to gitLogParser. Object.assign(gitLogParser.fields, { hash: "H", message: "B", gitTags: "d", committerDate: { key: "ci", type: Date }, }); // Use git-log-parser to get the commits. const relpath = relative(root, dir); const firstParentBranchFilter = firstParentBranch ? ["--first-parent", firstParentBranch] : []; const gitLogFilterQuery = [...firstParentBranchFilter, lastHead ? `${lastHead}..HEAD` : "HEAD", "--", relpath]; const stream = gitLogParser.parse({ _: gitLogFilterQuery }, { cwd, env: process.env }); const commits = await getStream.array(stream); // Trim message and tags. commits.forEach((commit) => { commit.message = commit.message.trim(); commit.gitTags = commit.gitTags.trim(); }); debug("git log filter query: %o", gitLogFilterQuery); debug("filtered commits: %O", commits); // Return the commits. return commits; } // Exports. export default getCommitsFiltered;
/** * Lifted and tweaked from semantic-release because we follow how they bump their packages/dependencies. * https://github.com/semantic-release/semantic-release/blob/master/lib/utils.js */ import semver from "semver"; const { gt, lt, prerelease, rcompare } = semver; /** * Get tag objects and convert them to a list of stringified versions. * @param {array} tags Tags as object list. * @returns {array} Tags as string list. * @internal */ function tagsToVersions(tags) { if (!tags) return []; return tags.map(({ version }) => version); } /** * HOC that applies highest/lowest semver function. * @param {Function} predicate High order function to be called. * @param {string|undefined} version1 Version 1 to be compared with. * @param {string|undefined} version2 Version 2 to be compared with. * @returns {string|undefined} Highest or lowest version. * @internal */ const _selectVersionBy = (predicate, version1, version2) => { if (predicate && version1 && version2) { return predicate(version1, version2) ? version1 : version2; } return version1 || version2; }; /** * Gets highest semver function binding gt to the HOC selectVersionBy. */ const getHighestVersion = _selectVersionBy.bind(null, gt); /** * Gets lowest semver function binding gt to the HOC selectVersionBy. */ const getLowestVersion = _selectVersionBy.bind(null, lt); /** * Retrieve the latest version from a list of versions. * @param {array} versions Versions as string list. * @param {bool|undefined} withPrerelease Prerelease flag. * @returns {string|undefined} Latest version. * @internal */ function getLatestVersion(versions, withPrerelease) { return versions.filter((version) => withPrerelease || !prerelease(version)).sort(rcompare)[0]; } // https://github.com/sindresorhus/slash/blob/b5cdd12272f94cfc37c01ac9c2b4e22973e258e5/index.js#L1 function slash(path) { const isExtendedLengthPath = /^\\\\\?\\/.test(path); const hasNonAscii = /[^\u0000-\u0080]+/.test(path); // eslint-disable-line no-control-regex if (isExtendedLengthPath || hasNonAscii) { return path; } return path.replace(/\\/g, "/"); } export { tagsToVersions, getHighestVersion, getLowestVersion, getLatestVersion, slash };
import { existsSync, lstatSync, readFileSync } from "fs"; /** * Read the content of target package.json if exists. * * @param {string} path file path * @returns {string} file content * * @internal */ function readManifest(path) { // Check it exists. if (!existsSync(path)) throw new ReferenceError(`package.json file not found: "${path}"`); // Stat the file. let stat; try { stat = lstatSync(path); } catch (_) { // istanbul ignore next (hard to test — happens if no read access etc). throw new ReferenceError(`package.json cannot be read: "${path}"`); } // Check it's a file! if (!stat.isFile()) throw new ReferenceError(`package.json is not a file: "${path}"`); // Read the file. try { return readFileSync(path, "utf8"); } catch (_) { // istanbul ignore next (hard to test — happens if no read access etc). throw new ReferenceError(`package.json cannot be read: "${path}"`); } } /** * Get the parsed contents of a package.json manifest file. * * @param {string} path The path to the package.json manifest file. * @returns {object} The manifest file's contents. * * @internal */ function getManifest(path) { // Read the file. const contents = readManifest(path); // Parse the file. let manifest; try { manifest = JSON.parse(contents); } catch (_) { throw new SyntaxError(`package.json could not be parsed: "${path}"`); } // Must be an object. if (typeof manifest !== "object") throw new SyntaxError(`package.json was not an object: "${path}"`); // Must have a name. if (typeof manifest.name !== "string" || !manifest.name.length) throw new SyntaxError(`Package name must be non-empty string: "${path}"`); // Check dependencies. const checkDeps = (scope) => { if (manifest.hasOwnProperty(scope) && typeof manifest[scope] !== "object") throw new SyntaxError(`Package ${scope} must be object: "${path}"`); }; checkDeps("dependencies"); checkDeps("devDependencies"); checkDeps("peerDependencies"); checkDeps("optionalDependencies"); // NOTE non-enumerable prop is skipped by JSON.stringify Object.defineProperty(manifest, "__contents__", { enumerable: false, value: contents }); // Return contents. return manifest; } // Exports. export default getManifest;
import { normalize, isAbsolute, join } from "path"; import { check } from "./blork.js"; /** * Normalize and make a path absolute, optionally using a custom CWD. * Trims any trailing slashes from the path. * * @param {string} path The path to normalize and make absolute. * @param {string} cwd=process.cwd() The CWD to prepend to the path to make it absolute. * @returns {string} The absolute and normalized path. * * @internal */ function cleanPath(path, cwd = process.cwd()) { // Checks. check(path, "path: path"); check(cwd, "cwd: absolute"); // Normalize, absolutify, and trim trailing slashes from the path. return normalize(isAbsolute(path) ? path : join(cwd, path)).replace(/[/\\]+$/, ""); } // Exports. export default cleanPath;
import { execaSync } from "execa"; /** * Get all the tags for a given branch. * * @param {String} branch The branch for which to retrieve the tags. * @param {Object} [execaOptions] Options to pass to `execa`. * @param {Array<String>} filters List of string to be checked inside tags. * * @return {Array<String>} List of git tags. * @throws {Error} If the `git` command fails. * @internal */ function getTags(branch, execaOptions, filters) { let tags = execaSync("git", ["tag", "--merged", branch], execaOptions).stdout; tags = tags .split("\n") .map((tag) => tag.trim()) .filter(Boolean); if (!filters || !filters.length) return tags; const validateSubstr = (t, f) => f.every((v) => t.includes(v)); return tags.filter((tag) => validateSubstr(tag, filters)); } export { getTags };
import getCommitsFiltered from "./getCommitsFiltered.js"; import { updateManifestDeps, resolveReleaseType } from "./updateDeps.js"; import { logger } from "./logger.js"; const { debug } = logger.withScope("msr:inlinePlugin"); /** * Create an inline plugin creator for a multirelease. * This is caused once per multirelease and returns a function which should be called once per package within the release. * * @param {Package[]} packages The multi-semantic-release context. * @param {MultiContext} multiContext The multi-semantic-release context. * @param {Object} flags argv options * @returns {Function} A function that creates an inline package. * * @internal */ function createInlinePluginCreator(packages, multiContext, flags) { // Vars. const { cwd } = multiContext; /** * Create an inline plugin for an individual package in a multirelease. * This is called once per package and returns the inline plugin used for semanticRelease() * * @param {Package} pkg The package this function is being called on. * @returns {Object} A semantic-release inline plugin containing plugin step functions. * * @internal */ function createInlinePlugin(pkg) { // Vars. const { plugins, dir, name } = pkg; const debugPrefix = `[${name}]`; /** * @var {Commit[]} List of _filtered_ commits that only apply to this package. */ let commits; /** * @param {object} pluginOptions Options to configure this plugin. * @param {object} context The semantic-release context. * @returns {Promise<void>} void * @internal */ const verifyConditions = async (pluginOptions, context) => { // Restore context for plugins that does not rely on parsed opts. Object.assign(context.options, context.options._pkgOptions); // And bind the actual logger. Object.assign(pkg.fakeLogger, context.logger); const res = await plugins.verifyConditions(context); pkg._ready = true; debug(debugPrefix, "verified conditions"); return res; }; /** * Analyze commits step. * Responsible for determining the type of the next release (major, minor or patch). If multiple plugins with a analyzeCommits step are defined, the release type will be the highest one among plugins output. * * In multirelease: Returns "patch" if the package contains references to other local packages that have changed, or null if this package references no local packages or they have not changed. * Also updates the `context.commits` setting with one returned from `getCommitsFiltered()` (which is filtered by package directory). * * @param {object} pluginOptions Options to configure this plugin. * @param {object} context The semantic-release context. * @returns {Promise<void>} Promise that resolves when done. * * @internal */ const analyzeCommits = async (pluginOptions, context) => { const firstParentBranch = flags.firstParent ? context.branch.name : undefined; pkg._preRelease = context.branch.prerelease || null; pkg._branch = context.branch.name; // Filter commits by directory. commits = await getCommitsFiltered(cwd, dir, context.lastRelease.gitHead, firstParentBranch); // Set context.commits so analyzeCommits does correct analysis. context.commits = commits; // Set lastRelease for package from context. pkg._lastRelease = context.lastRelease; // Set nextType for package from plugins. pkg._nextType = await plugins.analyzeCommits(context); pkg._analyzed = true; // Make sure type is "patch" if the package has any deps that have been changed. pkg._nextType = resolveReleaseType(pkg, flags.deps.bump, flags.deps.release, [], flags.deps.prefix); debug(debugPrefix, "commits analyzed"); debug(debugPrefix, `release type: ${pkg._nextType}`); // Return type. return pkg._nextType; }; /** * Generate notes step (after). * Responsible for generating the content of the release note. If multiple plugins with a generateNotes step are defined, the release notes will be the result of the concatenation of each plugin output. * * In multirelease: Edit the H2 to insert the package name and add an upgrades section to the note. * We want this at the _end_ of the release note which is why it's stored in steps-after. * * Should look like: * * ## my-amazing-package [9.2.1](github.com/etc) 2018-12-01 * * ### Features * * * etc * * ### Dependencies * * * **my-amazing-plugin:** upgraded to 1.2.3 * * **my-other-plugin:** upgraded to 4.9.6 * * @param {object} pluginOptions Options to configure this plugin. * @param {object} context The semantic-release context. * @returns {Promise<void>} Promise that resolves to the string * * @internal */ const generateNotes = async (pluginOptions, context) => { // Set nextRelease for package. pkg._nextRelease = context.nextRelease; // Wait until all todo packages are ready to generate notes. // await waitForAll("_nextRelease", (p) => p._nextType); // Vars. const notes = []; // Set context.commits so analyzeCommits does correct analysis. // We need to redo this because context is a different instance each time. context.commits = commits; // Get subnotes and add to list. // Inject pkg name into title if it matches e.g. `# 1.0.0` or `## [1.0.1]` (as generate-release-notes does). const subs = await plugins.generateNotes(context); // istanbul ignore else (unnecessary to test) if (subs) notes.push(subs.replace(/^(#+) (\[?\d+\.\d+\.\d+\]?)/, `$1 ${name} $2`)); // If it has upgrades add an upgrades section. const upgrades = pkg.localDeps.filter((d) => d._nextRelease); if (upgrades.length) { notes.push(`### Dependencies`); const bullets = upgrades.map((d) => `* **${d.name}:** upgraded to ${d._nextRelease.version}`); notes.push(bullets.join("\n")); } debug(debugPrefix, "notes generated"); // Return the notes. return notes.join("\n\n"); }; const prepare = async (pluginOptions, context) => { updateManifestDeps(pkg); pkg._depsUpdated = true; // Set context.commits so analyzeCommits does correct analysis. // We need to redo this because context is a different instance each time. context.commits = commits; const res = await plugins.prepare(context); pkg._prepared = true; debug(debugPrefix, "prepared"); return res; }; const publish = async (pluginOptions, context) => { const res = await plugins.publish(context); pkg._published = true; debug(debugPrefix, "published"); // istanbul ignore next return res.length ? res[0] : {}; }; const inlinePlugin = { verifyConditions, analyzeCommits, generateNotes, prepare, publish, }; // Add labels for logs. Object.keys(inlinePlugin).forEach((type) => Reflect.defineProperty(inlinePlugin[type], "pluginName", { value: "Inline plugin", writable: false, enumerable: true, }) ); debug(debugPrefix, "inlinePlugin created"); return inlinePlugin; } // Return creator function. return createInlinePlugin; } // Exports. export default createInlinePluginCreator;
import { writeFileSync } from "fs"; import semver from "semver"; import { isObject, isEqual, transform } from "lodash-es"; import recognizeFormat from "./recognizeFormat.js"; import getManifest from "./getManifest.js"; import { getHighestVersion, getLatestVersion } from "./utils.js"; import { getTags } from "./git.js"; import { logger } from "./logger.js"; const { debug } = logger.withScope("msr:updateDeps"); /** * Resolve next package version. * * @param {Package} pkg Package object. * @returns {string|undefined} Next pkg version. * @internal */ const getNextVersion = (pkg) => { const lastVersion = pkg._lastRelease && pkg._lastRelease.version; return lastVersion && typeof pkg._nextType === "string" ? semver.inc(lastVersion, pkg._nextType) : lastVersion || "1.0.0"; }; /** * Resolve the package version from a tag * * @param {Package} pkg Package object. * @param {string} tag The tag containing the version to resolve * @returns {string|null} The version of the package or null if no tag was passed * @internal */ const getVersionFromTag = (pkg, tag) => { if (!pkg.name) return tag || null; if (!tag) return null; // TODO inherit semantic-release/lib/branches/get-tags.js const strMatch = tag.match(/[0-9].[0-9].[0-9][^+]*/); return strMatch && strMatch[0] && semver.valid(strMatch[0]) ? strMatch[0] : null; }; /** * Resolve next package version on prereleases. * * Will resolve highest next version of either: * * 1. The last release for the package during this multi-release cycle * 2. (if the package has pullTagsForPrerelease true): * a. the highest increment of the tags array provided * b. the highest increment of the gitTags for the prerelease * * @param {Package} pkg Package object. * @param {Array<string>} tags Override list of tags from specific pkg and branch. * @returns {string|undefined} Next pkg version. * @internal */ const getNextPreVersion = (pkg, tags) => { const tagFilters = [pkg._preRelease]; // Note: this is only set is a current multi-semantic-release released const lastVersionForCurrentRelease = pkg._lastRelease && pkg._lastRelease.version; if (!pkg.pullTagsForPrerelease && tags) { throw new Error("Supplied tags for NextPreVersion but the package does not use tags for next prerelease"); } // Extract tags: // 1. Set filter to extract only package tags // 2. Get tags from a branch considering the filters established // 3. Resolve the versions from the tags // TODO: replace {cwd: '.'} with multiContext.cwd if (pkg.name) tagFilters.push(pkg.name); if (!tags && pkg.pullTagsForPrerelease) { try { tags = getTags(pkg._branch, { cwd: pkg.dir }, tagFilters); } catch (e) { tags = []; console.warn(e); console.warn(`Try 'git pull ${pkg._branch}'`); } } const lastPreRelTag = getPreReleaseTag(lastVersionForCurrentRelease); const isNewPreRelTag = lastPreRelTag && lastPreRelTag !== pkg._preRelease; const versionToSet = isNewPreRelTag || !lastVersionForCurrentRelease ? `1.0.0-${pkg._preRelease}.1` : _nextPreVersionCases( tags ? tags.map((tag) => getVersionFromTag(pkg, tag)).filter((tag) => tag) : [], lastVersionForCurrentRelease, pkg._nextType, pkg._preRelease ); return versionToSet; }; /** * Parse the prerelease tag from a semver version. * * @param {string} version Semver version in a string format. * @returns {string|null} preReleaseTag Version prerelease tag or null. * @internal */ const getPreReleaseTag = (version) => { const parsed = semver.parse(version); if (!parsed) return null; return parsed.prerelease[0] || null; }; /** * Resolve next prerelease special cases: highest version from tags or major/minor/patch. * * @param {Array<string>} tags - if non-empty, we will use these tags as part fo the comparison * @param {string} lastVersionForCurrentMultiRelease Last package version released from multi-semantic-release * @param {string} pkgNextType Next type evaluated for the next package type. * @param {string} pkgPreRelease Package prerelease suffix. * @returns {string|undefined} Next pkg version. * @internal */ const _nextPreVersionCases = (tags, lastVersionForCurrentMultiRelease, pkgNextType, pkgPreRelease) => { // Case 1: Normal release on last version and is now converted to a prerelease if (!semver.prerelease(lastVersionForCurrentMultiRelease)) { const { major, minor, patch } = semver.parse(lastVersionForCurrentMultiRelease); return `${semver.inc(`${major}.${minor}.${patch}`, pkgNextType || "patch")}-${pkgPreRelease}.1`; } // Case 2: Validates version with tags const latestTag = getLatestVersion(tags, { withPrerelease: true }); return _nextPreHighestVersion(latestTag, lastVersionForCurrentMultiRelease, pkgPreRelease); }; /** * Resolve next prerelease comparing bumped tags versions with last version. * * @param {string|null} latestTag Last released tag from branch or null if non-existent. * @param {string} lastVersion Last version released. * @param {string} pkgPreRelease Prerelease tag from package to-be-released. * @returns {string} Next pkg version. * @internal */ const _nextPreHighestVersion = (latestTag, lastVersion, pkgPreRelease) => { const bumpFromTags = latestTag ? semver.inc(latestTag, "prerelease", pkgPreRelease) : null; const bumpFromLast = semver.inc(lastVersion, "prerelease", pkgPreRelease); return bumpFromTags ? getHighestVersion(bumpFromLast, bumpFromTags) : bumpFromLast; }; /** * Resolve package release type taking into account the cascading dependency update. * * @param {Package} pkg Package object. * @param {string|undefined} bumpStrategy Dependency resolution strategy: override, satisfy, inherit. * @param {string|undefined} releaseStrategy Release type triggered by deps updating: patch, minor, major, inherit. * @param {Package[]} ignore=[] Packages to ignore (to prevent infinite loops). * @param {string} prefix Dependency version prefix to be attached if `bumpStrategy='override'`. ^ | ~ | '' (defaults to empty string) * @returns {string|undefined} Resolved release type. * @internal */ const resolveReleaseType = (pkg, bumpStrategy = "override", releaseStrategy = "patch", ignore = [], prefix = "") => { // NOTE This fn also updates pkg deps, so it must be invoked anyway. const dependentReleaseType = getDependentRelease(pkg, bumpStrategy, releaseStrategy, ignore, prefix); // Define release type for dependent package if any of its deps changes. // `patch`, `minor`, `major` — strictly declare the release type that occurs when any dependency is updated. // `inherit` — applies the "highest" release of updated deps to the package. // For example, if any dep has a breaking change, `major` release will be applied to the all dependants up the chain. // If we want to inherit the release type from the dependent package const types = ["patch", "minor", "major"]; const depIndex = dependentReleaseType ? types.indexOf(dependentReleaseType) : types.length + 1; const pkgIndex = pkg._nextType ? types.indexOf(pkg._nextType) : types.length + 1; if (releaseStrategy === "inherit" && dependentReleaseType && depIndex >= pkgIndex) { return dependentReleaseType; } // Release type found by commitAnalyzer. if (pkg._nextType) { return pkg._nextType; } // No deps changed. if (!dependentReleaseType) { return undefined; } pkg._nextType = releaseStrategy === "inherit" ? dependentReleaseType : releaseStrategy; return pkg._nextType; }; /** * Get dependent release type by recursive scanning and updating pkg deps. * * @param {Package} pkg The package with local deps to check. * @param {string} bumpStrategy Dependency resolution strategy: override, satisfy, inherit. * @param {string} releaseStrategy Release type triggered by deps updating: patch, minor, major, inherit. * @param {Package[]} ignore Packages to ignore (to prevent infinite loops). * @param {string} prefix Dependency version prefix to be attached if `bumpStrategy='override'`. ^ | ~ | '' (defaults to empty string) * @returns {string|undefined} Returns the highest release type if found, undefined otherwise * @internal */ const getDependentRelease = (pkg, bumpStrategy, releaseStrategy, ignore, prefix) => { const severityOrder = ["patch", "minor", "major"]; const { localDeps, manifest = {} } = pkg; const lastVersion = pkg._lastRelease && pkg._lastRelease.version; const { dependencies = {}, devDependencies = {}, peerDependencies = {}, optionalDependencies = {} } = manifest; const scopes = [dependencies, devDependencies, peerDependencies, optionalDependencies]; const bumpDependency = (scope, name, nextVersion) => { const currentVersion = scope[name]; if (!nextVersion || !currentVersion) { return false; } const resolvedVersion = resolveNextVersion(currentVersion, nextVersion, bumpStrategy, prefix); if (currentVersion !== resolvedVersion) { scope[name] = resolvedVersion; return true; } return false; }; // prettier-ignore return localDeps .filter((p) => !ignore.includes(p)) .reduce((releaseType, p) => { // Has changed if... // 1. Any local dep package itself has changed // 2. Any local dep package has local deps that have changed. const nextType = resolveReleaseType(p, bumpStrategy, releaseStrategy,[...ignore, pkg], prefix); const nextVersion = nextType // Update the nextVersion only if there is a next type to be bumped ? p._preRelease ? getNextPreVersion(p) : getNextVersion(p) // Set the nextVersion fallback to the last local dependency package last version : p._lastRelease && p._lastRelease.version // 3. And this change should correspond to the manifest updating rule. const requireRelease = scopes .reduce((res, scope) => bumpDependency(scope, p.name, nextVersion) || res, !lastVersion) return requireRelease && (severityOrder.indexOf(nextType) > severityOrder.indexOf(releaseType)) ? nextType : releaseType; }, undefined); }; /** * Resolve next version of dependency. * * @param {string} currentVersion Current dep version * @param {string} nextVersion Next release type: patch, minor, major * @param {string|undefined} strategy Resolution strategy: inherit, override, satisfy * @param {string} prefix Dependency version prefix to be attached if `bumpStrategy='override'`. ^ | ~ | '' (defaults to empty string) * @returns {string} Next dependency version * @internal */ const resolveNextVersion = (currentVersion, nextVersion, strategy = "override", prefix = "") => { // Check the next pkg version against its current references. // If it matches (`*` matches to any, `1.1.0` matches `1.1.x`, `1.5.0` matches to `^1.0.0` and so on) // release will not be triggered, if not `override` strategy will be applied instead. if ((strategy === "satisfy" || strategy === "inherit") && semver.satisfies(nextVersion, currentVersion)) { return currentVersion; } // `inherit` will try to follow the current declaration version/range. // `~1.0.0` + `minor` turns into `~1.1.0`, `1.x` + `major` gives `2.x`, // but `1.x` + `minor` gives `1.x` so there will be no release, etc. if (strategy === "inherit") { const sep = "."; const nextChunks = nextVersion.split(sep); const currentChunks = currentVersion.split(sep); // prettier-ignore const resolvedChunks = currentChunks.map((chunk, i) => nextChunks[i] ? chunk.replace(/\d+/, nextChunks[i]) : chunk ); return resolvedChunks.join(sep); } // "override" // By default next package version would be set as is for the all dependants. return prefix + nextVersion; }; /** * Update pkg deps. * * @param {Package} pkg The package this function is being called on. * @returns {undefined} * @internal */ const updateManifestDeps = (pkg) => { const { manifest, path } = pkg; const { indent, trailingWhitespace } = recognizeFormat(manifest.__contents__); // We need to bump pkg.version for correct yarn.lock update // https://github.com/qiwi/multi-semantic-release/issues/58 manifest.version = pkg._nextRelease.version || manifest.version; // Loop through localDeps to verify release consistency. pkg.localDeps.forEach((d) => { // Get version of dependency. const release = d._nextRelease || d._lastRelease; // Cannot establish version. if (!release || !release.version) throw Error(`Cannot release ${pkg.name} because dependency ${d.name} has not been released yet`); }); if (!auditManifestChanges(manifest, path)) { return; } // Write package.json back out. writeFileSync(path, JSON.stringify(manifest, null, indent) + trailingWhitespace); }; // https://gist.github.com/Yimiprod/7ee176597fef230d1451 const difference = (object, base) => transform(object, (result, value, key) => { if (!isEqual(value, base[key])) { result[key] = isObject(value) && isObject(base[key]) ? difference(value, base[key]) : `${base[key]} → ${value}`; } }); /** * Clarify what exactly was changed in manifest file. * @param {object} actualManifest manifest object * @param {string} path manifest path * @returns {boolean} has changed or not * @internal */ const auditManifestChanges = (actualManifest, path) => { const debugPrefix = `[${actualManifest.name}]`; const oldManifest = getManifest(path); const depScopes = ["dependencies", "devDependencies", "peerDependencies", "optionalDependencies"]; const changes = depScopes.reduce((res, scope) => { const diff = difference(actualManifest[scope], oldManifest[scope]); if (Object.keys(diff).length) { res[scope] = diff; } return res; }, {}); debug(debugPrefix, "package.json path=", path); if (Object.keys(changes).length) { debug(debugPrefix, "changes=", changes); return true; } debug(debugPrefix, "no deps changes"); return false; }; export { getNextVersion, getNextPreVersion, getPreReleaseTag, updateManifestDeps, resolveReleaseType, resolveNextVersion, getVersionFromTag, };
import semanticRelease from "semantic-release"; import { uniq, template, sortBy } from "lodash-es"; import { topo } from "@semrel-extra/topo"; import { dirname, join } from "path"; import { check } from "./blork.js"; import { logger } from "./logger.js"; import getConfig from "./getConfig.js"; import getConfigMultiSemrel from "./getConfigMultiSemrel.js"; import getConfigSemantic from "./getConfigSemantic.js"; import getManifest from "./getManifest.js"; import cleanPath from "./cleanPath.js"; import RescopedStream from "./RescopedStream.js"; import createInlinePluginCreator from "./createInlinePluginCreator.js"; import { createRequire } from "module"; /** * The multirelease context. * @typedef MultiContext * @param {Package[]} packages Array of all packages in this multirelease. * @param {Package[]} releasing Array of packages that will release. * @param {string} cwd The current working directory. * @param {Object} env The environment variables. * @param {Logger} logger The logger for the multirelease. * @param {Stream} stdout The output stream for this multirelease. * @param {Stream} stderr The error stream for this multirelease. */ /** * Details about an individual package in a multirelease * @typedef Package * @param {string} path String path to `package.json` for the package. * @param {string} dir The working directory for the package. * @param {string} name The name of the package, e.g. `my-amazing-package` * @param {string[]} deps Array of all dependency package names for the package (merging dependencies, devDependencies, peerDependencies). * @param {Package[]} localDeps Array of local dependencies this package relies on. * @param {context|void} context The semantic-release context for this package's release (filled in once semantic-release runs). * @param {undefined|Result|false} result The result of semantic-release (object with lastRelease, nextRelease, commits, releases), false if this package was skipped (no changes or similar), or undefined if the package's release hasn't completed yet. * @param {Object} options Aggregate of semantic-release options for the package * @param {boolean} pullTagsForPrerelease if set to true, the package will use tags to determine if its dependencies need to change (legacy functionality) * @param {Object} _lastRelease The last release object for the package before its current release (set during anaylze-commit) * @param {Object} _nextRelease The next release object (the release the package is releasing for this cycle) (set during generateNotes) */ /** * Perform a multirelease. * * @param {string[]} paths An array of paths to package.json files. * @param {Object} inputOptions An object containing semantic-release options. * @param {Object} settings An object containing: cwd, env, stdout, stderr (mainly for configuring tests). * @param {Object} _flags Argv flags. * @returns {Promise<Package[]>} Promise that resolves to a list of package objects with `result` property describing whether it released or not. */ async function multiSemanticRelease( paths, inputOptions = {}, { cwd = process.cwd(), env = process.env, stdout = process.stdout, stderr = process.stderr } = {}, _flags ) { // Check params. if (paths) { check(paths, "paths: string[]"); } check(cwd, "cwd: directory"); check(env, "env: objectlike"); check(stdout, "stdout: stream"); check(stderr, "stderr: stream"); cwd = cleanPath(cwd); const flags = normalizeFlags(await getConfigMultiSemrel(cwd, _flags)); const require = createRequire(import.meta.url); const multisemrelPkgJson = require("../package.json"); const semrelPkgJson = require("semantic-release/package.json"); // Setup logger. logger.config.stdio = [stderr, stdout]; logger.config.level = flags.logLevel; if (flags.silent) { logger.config.level = "silent"; } if (flags.debug) { logger.config.level = "debug"; } logger.info(`multi-semantic-release version: ${multisemrelPkgJson.version}`); logger.info(`semantic-release version: ${semrelPkgJson.version}`); logger.info(`flags: ${JSON.stringify(flags, null, 2)}`); // Vars. const globalOptions = await getConfig(cwd); const multiContext = { globalOptions, inputOptions, cwd, env, stdout, stderr, pullTagsForPrerelease: flags.deps.pullTagsForPrerelease, }; const { queue, packages: _packages } = await topo({ cwd, workspacesExtra: Array.isArray(flags.ignorePackages) ? flags.ignorePackages.map((p) => `!${p}`) : [], filter: ({ manifest, manifestAbsPath, manifestRelPath }) => (!flags.ignorePrivate || !manifest.private) && (paths ? paths.includes(manifestAbsPath) || paths.includes(manifestRelPath) : true), }); // Get list of package.json paths according to workspaces. paths = paths || Object.values(_packages).map((pkg) => pkg.manifestPath); // Start. logger.complete(`Started multirelease! Loading ${paths.length} packages...`); // Load packages from paths. const packages = await Promise.all(paths.map((path) => getPackage(path, multiContext))); packages.forEach((pkg) => { // Once we load all the packages we can find their cross refs // Make a list of local dependencies. // Map dependency names (e.g. my-awesome-dep) to their actual package objects in the packages array. pkg.localDeps = uniq(pkg.deps.map((d) => packages.find((p) => d === p.name)).filter(Boolean)); logger.success(`Loaded package ${pkg.name}`); }); logger.complete(`Queued ${queue.length} packages! Starting release...`); // Release all packages. const createInlinePlugin = createInlinePluginCreator(packages, multiContext, flags); const released = await queue.reduce(async (_m, _name) => { const m = await _m; const pkg = packages.find(({ name }) => name === _name); if (pkg) { const { result } = await releasePackage(pkg, createInlinePlugin, multiContext, flags); if (result) { return m + 1; } } return m; }, Promise.resolve(0)); // Return packages list. logger.complete(`Released ${released} of ${queue.length} packages, semantically!`); return sortBy(packages, ({ name }) => queue.indexOf(name)); } /** * Load details about a package. * * @param {string} path The path to load details about. * @param {Object} allOptions Options that apply to all packages. * @param {MultiContext} multiContext Context object for the multirelease. * @returns {Promise<Package|void>} A package object, or void if the package was skipped. * * @internal */ async function getPackage(path, { globalOptions, inputOptions, env, cwd, stdout, stderr, pullTagsForPrerelease }) { // Make path absolute. path = cleanPath(path, cwd); const dir = dirname(path); // Get package.json file contents. const manifest = getManifest(path); const name = manifest.name; // Combine list of all dependency names. const deps = Object.keys({ ...manifest.dependencies, ...manifest.devDependencies, ...manifest.peerDependencies, ...manifest.optionalDependencies, }); // Load the package-specific options. const pkgOptions = await getConfig(dir); // The 'final options' are the global options merged with package-specific options. // We merge this ourselves because package-specific options can override global options. const finalOptions = Object.assign({}, globalOptions, pkgOptions, inputOptions); // Make a fake logger so semantic-release's get-config doesn't fail. const fakeLogger = { error() {}, log() {} }; // Use semantic-release's internal config with the final options (now we have the right `options.plugins` setting) to get the plugins object and the options including defaults. // We need this so we can call e.g. plugins.analyzeCommit() to be able to affect the input and output of the whole set of plugins. const { options, plugins } = await getConfigSemantic({ cwd: dir, env, stdout, stderr }, finalOptions); // Return package object. return { path, dir, name, manifest, deps, options, plugins, fakeLogger: fakeLogger, pullTagsForPrerelease: !!pullTagsForPrerelease, }; } /** * Release an individual package. * * @param {Package} pkg The specific package. * @param {Function} createInlinePlugin A function that creates an inline plugin. * @param {MultiContext} multiContext Context object for the multirelease. * @param {Object} flags Argv flags. * @returns {Promise<void>} Promise that resolves when done. * * @internal */ async function releasePackage(pkg, createInlinePlugin, multiContext, flags) { // Vars. const { options: pkgOptions, name, dir } = pkg; const { env, stdout, stderr } = multiContext; // Make an 'inline plugin' for this package. // The inline plugin is the only plugin we call semanticRelease() with. // The inline plugin functions then call e.g. plugins.analyzeCommits() manually and sometimes manipulate the responses. const inlinePlugin = createInlinePlugin(pkg); // Set the options that we call semanticRelease() with. // This consists of: // - The global options (e.g. from the top level package.json) // - The package options (e.g. from the specific package's package.json) const options = { ...pkgOptions, ...inlinePlugin }; // Add the package name into tagFormat. // Thought about doing a single release for the tag (merging several packages), but it's impossible to prevent Github releasing while allowing NPM to continue. // It'd also be difficult to merge all the assets into one release without full editing/overriding the plugins. const tagFormatCtx = { name, version: "${version}", }; const tagFormatDefault = "${name}@${version}"; options.tagFormat = template(flags.tagFormat || tagFormatDefault)(tagFormatCtx); // These are the only two options that MSR shares with semrel // Set them manually for now, defaulting to the msr versions // This is approach can be reviewed if there's ever more crossover. // - debug is only supported in semrel as a CLI arg, always default to MSR options.debug = flags.debug; // - dryRun should use the msr version if specified, otherwise fallback to semrel options.dryRun = flags.dryRun === undefined ? options.dryRun : flags.dryRun; // This options are needed for plugins that do not rely on `pluginOptions` and extract them independently. options._pkgOptions = pkgOptions; // Call semanticRelease() on the directory and save result to pkg. // Don't need to log out errors as semantic-release already does that. pkg.result = await semanticRelease(options, { cwd: dir, env, stdout: new RescopedStream(stdout, name), stderr: new RescopedStream(stderr, name), }); return pkg; } function normalizeFlags(_flags) { return { deps: { pullTagsForPrerelease: !!_flags.deps?.pullTagsForPrerelease, }, ..._flags, }; } // Exports. export default multiSemanticRelease;
import dbg from "debug"; import singnale from "signale"; const { Signale } = singnale; const severityOrder = ["error", "warn", "info", "debug", "trace"]; const assertLevel = (level, limit) => severityOrder.indexOf(level) <= severityOrder.indexOf(limit); const aliases = { failure: "error", log: "info", success: "info", complete: "info", }; export const logger = { prefix: "msr:", config: { _level: "info", _stderr: process.stderr, _stdout: process.stdout, _signale: {}, set level(l) { if (!l) { return; } if (assertLevel(l, "debug")) { dbg.enable("msr:"); } if (assertLevel(l, "trace")) { dbg.enable("semantic-release:"); } this._level = l; }, get level() { return this._level; }, set stdio([stderr, stdout]) { this._stdout = stdout; this._stderr = stderr; this._signale = new Signale({ config: { displayTimestamp: true, displayLabel: false }, // scope: "multirelease", stream: stdout, types: { error: { color: "red", label: "", stream: [stderr] }, log: { color: "magenta", label: "", stream: [stdout], badge: "•" }, success: { color: "green", label: "", stream: [stdout] }, complete: { color: "green", label: "", stream: [stdout], badge: "🎉" }, }, }); }, get stdio() { return [this._stderr, this._stdout]; }, }, withScope(prefix) { return { ...this, prefix, debug: dbg(prefix || this.prefix), }; }, ...[...severityOrder, ...Object.keys(aliases)].reduce((m, l) => { m[l] = function (...args) { if (assertLevel(aliases[l] || l, this.config.level)) { (this.config._signale[l] || console[l] || (() => {}))(this.prefix, ...args); } }; return m; }, {}), debug: dbg("msr:"), };
import { detectNewline } from "detect-newline"; import detectIndent from "detect-indent"; /** * Information about the format of a file. * @typedef FileFormat * @property {string|number} indent Indentation characters * @property {string} trailingWhitespace Trailing whitespace at the end of the file */ /** * Detects the indentation and trailing whitespace of a file. * * @param {string} contents contents of the file * @returns {FileFormat} Formatting of the file */ function recognizeFormat(contents) { return { indent: detectIndent(contents).indent, trailingWhitespace: detectNewline(contents) || "", }; } // Exports. export default recognizeFormat;
import resolveFrom from "resolve-from"; import { cosmiconfig } from "cosmiconfig"; import { pickBy, isNil, castArray, uniq } from "lodash-es"; import { createRequire } from "node:module"; /** * @typedef {Object} DepsConfig * @property {'override' | 'satisfy' | 'inherit'} bump * @property {'patch' | 'minor' | 'major' | 'inherit'} release * @property {'^' | '~' | ''} prefix * @property {boolean} pullTagsForPrerelease */ /** * @typedef {Object} MultiReleaseConfig * @property {boolean} sequentialInit * @property {boolean} sequentialPrepare * @property {boolean} firstParent * @property {boolean} debug * @property {boolean} ignorePrivate * @property {Array<string>} ignorePackages * @property {string} tagFormat * @property {boolean} dryRun * @property {DepsConfig} deps * @property {boolean} silent */ const CONFIG_NAME = "multi-release"; const CONFIG_FILES = [ "package.json", `.${CONFIG_NAME}rc`, `.${CONFIG_NAME}rc.json`, `.${CONFIG_NAME}rc.yaml`, `.${CONFIG_NAME}rc.yml`, `.${CONFIG_NAME}rc.js`, `.${CONFIG_NAME}rc.cjs`, `${CONFIG_NAME}.config.js`, `${CONFIG_NAME}.config.cjs`, ]; const mergeConfig = (a = {}, b = {}) => { return { ...a, // Remove `null` and `undefined` options so they can be replaced with default ones ...pickBy(b, (option) => !isNil(option)), // Treat nested objects differently as otherwise we'll loose undefined keys deps: { ...a.deps, ...pickBy(b.deps, (option) => !isNil(option)), }, // Treat arrays differently by merging them ignorePackages: uniq([...castArray(a.ignorePackages || []), ...castArray(b.ignorePackages || [])]), }; }; /** * Get the multi semantic release configuration options for a given directory. * * @param {string} cwd The directory to search. * @param {Object} cliOptions cli supplied options. * @returns {MultiReleaseConfig} The found configuration option * * @internal */ export default async function getConfig(cwd, cliOptions) { const { config } = (await cosmiconfig(CONFIG_NAME, { searchPlaces: CONFIG_FILES }).search(cwd)) || {}; const { extends: extendPaths, ...rest } = { ...config }; let options = rest; if (extendPaths) { const require = createRequire(import.meta.url); // If `extends` is defined, load and merge each shareable config const extendedOptions = castArray(extendPaths).reduce((result, extendPath) => { const extendsOptions = require(resolveFrom(cwd, extendPath)); return mergeConfig(result, extendsOptions); }, {}); options = mergeConfig(options, extendedOptions); } // Set default options values if not defined yet options = mergeConfig( { sequentialInit: false, sequentialPrepare: true, firstParent: false, debug: false, ignorePrivate: true, ignorePackages: [], tagFormat: "${name}@${version}", dryRun: undefined, deps: { bump: "override", release: "patch", prefix: "", pullTagsForPrerelease: false, }, silent: false, }, options ); // Finally merge CLI options last so they always win return mergeConfig(options, cliOptions); }
import { existsSync, lstatSync } from "fs"; import { checker, check, add, ValueError } from "blork"; import { Writable } from "stream"; import { WritableStreamBuffer } from "stream-buffers"; // Get some checkers. const isAbsolute = checker("absolute"); // Add a directory checker. add( "directory", (v) => isAbsolute(v) && existsSync(v) && lstatSync(v).isDirectory(), "directory that exists in the filesystem" ); // Add a writable stream checker. add( "stream", // istanbul ignore next (not important) (v) => v instanceof Writable || v instanceof WritableStreamBuffer, "instance of stream.Writable or WritableStreamBuffer" ); // Exports. export { checker, check, ValueError };
import { cosmiconfig } from "cosmiconfig"; // Copied from get-config.js in semantic-release const CONFIG_NAME = "release"; const CONFIG_FILES = [ "package.json", `.${CONFIG_NAME}rc`, `.${CONFIG_NAME}rc.json`, `.${CONFIG_NAME}rc.yaml`, `.${CONFIG_NAME}rc.yml`, `.${CONFIG_NAME}rc.js`, `.${CONFIG_NAME}rc.cjs`, `${CONFIG_NAME}.config.js`, `${CONFIG_NAME}.config.cjs`, ]; /** * Get the release configuration options for a given directory. * Unfortunately we've had to copy this over from semantic-release, creating unnecessary duplication. * * @param {string} cwd The directory to search. * @returns {Object} The found configuration option * * @internal */ export default async function getConfig(cwd) { // Call cosmiconfig. const config = await cosmiconfig(CONFIG_NAME, { searchPlaces: CONFIG_FILES }).search(cwd); // Return the found config or empty object. // istanbul ignore next (not important). return config ? config.config : {}; }
#!/usr/bin/env node import meow from "meow"; import process from "process"; import { toPairs, set } from "lodash-es"; import { logger } from "../lib/logger.js"; const cli = meow( ` Usage $ multi-semantic-release Options --dry-run Dry run mode. --debug Output debugging information. --silent Do not print configuration information. --sequential-init Avoid hypothetical concurrent initialization collisions. --sequential-prepare Avoid hypothetical concurrent preparation collisions. Do not use if your project have cyclic dependencies. --first-parent Apply commit filtering to current branch only. --deps.bump Define deps version updating rule. Allowed: override, satisfy, inherit. --deps.release Define release type for dependent package if any of its deps changes. Supported values: patch, minor, major, inherit. --deps.prefix Optional prefix to be attached to the next dep version if '--deps.bump' set to 'override'. Supported values: '^' | '~' | '' (empty string as default). --deps.pullTagsForPrerelease Optional flag to control using release tags for evaluating prerelease version bumping. This is almost always the correct option since semantic-release will be creating tags for every dependency and it would lead to us bumping to a non-existent version. Set to false if you've already compensated for this in your workflow previously (true as default) --ignore-packages Packages list to be ignored on bumping process --ignore-private Exclude private packages. Enabled by default, pass 'no-ignore-private' to disable. --tag-format Format to use for creating tag names. Should include "name" and "version" vars. Default: "\${name}@\${version}" generates "package-name@1.0.0" --help Help info. Examples $ multi-semantic-release --debug $ multi-semantic-release --deps.bump=satisfy --deps.release=patch $ multi-semantic-release --ignore-packages=packages/a/**,packages/b/** `, { importMeta: import.meta, get argv() { const argvStart = process.argv.includes("--") ? process.argv.indexOf("--") + 1 : 2; return process.argv.slice(argvStart); }, booleanDefault: undefined, flags: { sequentialInit: { type: "boolean", }, sequentialPrepare: { type: "boolean", }, firstParent: { type: "boolean", }, debug: { type: "boolean", }, "deps.bump": { type: "string", }, "deps.release": { type: "string", }, "deps.prefix": { type: "string", }, "deps.pullTagsForPrerelease": { type: "boolean", }, ignorePrivate: { type: "boolean", }, ignorePackages: { type: "string", }, tagFormat: { type: "string", }, dryRun: { type: "boolean", }, silent: { type: "boolean", }, }, } ); const processFlags = (flags) => { return toPairs(flags).reduce((m, [k, v]) => { if (k === "ignorePackages" && v) { return set(m, k, v.split(",")); } // FIXME Something is wrong with the default negate parser. if (flags[`no${k[0].toUpperCase()}${k.slice(1)}`]) { flags[k] = false; return set(m, k, false); } return set(m, k, v); }, {}); }; const runner = async (cliFlags) => { // Catch errors. try { // Imports. const multiSemanticRelease = (await import("../lib/multiSemanticRelease.js")).default; // Do multirelease (log out any errors). multiSemanticRelease(null, {}, {}, cliFlags).then( () => { // Success. process.exit(0); }, (error) => { // Log out errors. logger.error(`[multi-semantic-release]:`, error); process.exit(1); } ); } catch (error) { // Log out errors. logger.error(`[multi-semantic-release]:`, error); process.exit(1); } }; runner(processFlags(cli.flags));
import { getHighestVersion, getLowestVersion, getLatestVersion, tagsToVersions } from "../../lib/utils.js"; describe("tagsToVersions()", () => { // prettier-ignore const cases = [ [[{version: "1.0.0"}, {version: "1.1.0"}, {version: "1.2.0"}], ["1.0.0", "1.1.0", "1.2.0"]], [[],[]], [undefined, []], [null, []], ] cases.forEach(([tags, versions]) => { it(`${tags} gives versions as ${versions}`, () => { expect(tagsToVersions(tags)).toStrictEqual(versions); }); }); }); describe("getHighestVersion()", () => { // prettier-ignore const cases = [ ["1.0.0", "2.0.0", "2.0.0"], ["1.1.1", "1.0.0", "1.1.1"], [null, "1.0.0", "1.0.0"], ["1.0.0", undefined, "1.0.0"], [undefined, undefined, undefined], ] cases.forEach(([version1, version2, high]) => { it(`${version1}/${version2} gives highest as ${high}`, () => { expect(getHighestVersion(version1, version2)).toBe(high); }); }); }); describe("getLowestVersion()", () => { // prettier-ignore const cases = [ ["1.0.0", "2.0.0", "1.0.0"], ["1.1.1", "1.0.0", "1.0.0"], [null, "1.0.0", "1.0.0"], ["1.0.0", undefined, "1.0.0"], [undefined, undefined, undefined], ] cases.forEach(([version1, version2, low]) => { it(`${version1}/${version2} gives lowest as ${low}`, () => { expect(getLowestVersion(version1, version2, 0)).toBe(low); }); }); }); describe("getLatestVersion()", () => { // prettier-ignore const cases = [ [["1.2.3-alpha.3", "1.2.0", "1.0.1", "1.0.0-alpha.1"], null, "1.2.0"], [["1.2.3-alpha.3", "1.2.3-alpha.2"], null, undefined], [["1.2.3-alpha.3", "1.2.0", "1.0.1", "1.0.0-alpha.1"], true, "1.2.3-alpha.3"], [["1.2.3-alpha.3", "1.2.3-alpha.2"], true, "1.2.3-alpha.3"], [[], {}, undefined] ] cases.forEach(([versions, withPrerelease, latest]) => { it(`${versions}/${withPrerelease} gives latest as ${latest}`, () => { expect(getLatestVersion(versions, withPrerelease)).toBe(latest); }); }); });
import { readFileSync, writeFileSync } from "fs"; import { createRequire } from "module"; import { jest } from "@jest/globals"; import { WritableStreamBuffer } from "stream-buffers"; import { addPrereleaseToPackageRootConfig, copyDirectory, createNewTestingFiles } from "../helpers/file.js"; import { gitInit, gitAdd, gitCommit, gitCommitAll, gitInitOrigin, gitPush, gitTag, gitGetLog } from "../helpers/git"; import multiSemanticRelease from "../../lib/multiSemanticRelease.js"; const require = createRequire(import.meta.url); const env = {}; // Clear mocks before tests. beforeEach(() => { jest.clearAllMocks(); // Clear all mocks. // require.cache = {}; // Clear the require cache so modules are loaded fresh. }); // Tests. describe("multiSemanticRelease()", () => { test("Initial commit (changes in all packages)", async () => { // Create Git repo with copy of Yarn workspaces fixture. const cwd = gitInit(); copyDirectory(`test/fixtures/yarnWorkspaces/`, cwd); const sha = gitCommitAll(cwd, "feat: Initial release"); const url = gitInitOrigin(cwd); gitPush(cwd); // Capture output. const stdout = new WritableStreamBuffer(); const stderr = new WritableStreamBuffer(); // Call multiSemanticRelease() // Doesn't include plugins that actually publish. const result = await multiSemanticRelease( [ `packages/a/package.json`, `packages/b/package.json`, `packages/c/package.json`, `packages/d/package.json`, ], {}, { cwd, stdout, stderr, env } ); // Get stdout and stderr output. const err = stderr.getContentsAsString("utf8"); expect(err).toBe(false); const out = stdout.getContentsAsString("utf8"); expect(out).toMatch("Started multirelease! Loading 4 packages..."); expect(out).toMatch("Loaded package msr-test-a"); expect(out).toMatch("Loaded package msr-test-b"); expect(out).toMatch("Loaded package msr-test-c"); expect(out).toMatch("Loaded package msr-test-d"); expect(out).toMatch("Queued 4 packages! Starting release..."); expect(out).toMatch("Created tag msr-test-a@1.0.0"); expect(out).toMatch("Created tag msr-test-b@1.0.0"); expect(out).toMatch("Created tag msr-test-c@1.0.0"); expect(out).toMatch("Created tag msr-test-d@1.0.0"); expect(out).toMatch("Released 4 of 4 packages, semantically!"); // A. expect(result[0].name).toBe("msr-test-a"); expect(result[0].result.lastRelease).toEqual({}); expect(result[0].result.nextRelease).toMatchObject({ gitHead: sha, gitTag: "msr-test-a@1.0.0", type: "minor", version: "1.0.0", }); expect(result[0].result.nextRelease.notes).toMatch("# msr-test-a 1.0.0"); expect(result[0].result.nextRelease.notes).toMatch("### Features\n\n* Initial release"); // B. expect(result[2].name).toBe("msr-test-b"); expect(result[2].result.lastRelease).toEqual({}); expect(result[2].result.nextRelease).toMatchObject({ gitHead: sha, gitTag: "msr-test-b@1.0.0", type: "minor", version: "1.0.0", }); expect(result[2].result.nextRelease.notes).toMatch("# msr-test-b 1.0.0"); expect(result[2].result.nextRelease.notes).toMatch("### Features\n\n* Initial release"); expect(result[2].result.nextRelease.notes).toMatch("### Dependencies\n\n* **msr-test-a:** upgraded to 1.0.0"); // C. expect(result[3].name).toBe("msr-test-c"); expect(result[3].result.lastRelease).toEqual({}); expect(result[3].result.nextRelease).toMatchObject({ gitHead: sha, gitTag: "msr-test-c@1.0.0", type: "minor", version: "1.0.0", }); expect(result[3].result.nextRelease.notes).toMatch("# msr-test-c 1.0.0"); expect(result[3].result.nextRelease.notes).toMatch("### Features\n\n* Initial release"); expect(result[3].result.nextRelease.notes).toMatch("### Dependencies\n\n* **msr-test-b:** upgraded to 1.0.0"); // D. expect(result[1].name).toBe("msr-test-d"); expect(result[1].result.lastRelease).toEqual({}); expect(result[1].result.nextRelease).toMatchObject({ gitHead: sha, gitTag: "msr-test-d@1.0.0", type: "minor", version: "1.0.0", }); expect(result[1].result.nextRelease.notes).toMatch("# msr-test-d 1.0.0"); expect(result[1].result.nextRelease.notes).toMatch("### Features\n\n* Initial release"); expect(result[1].result.nextRelease.notes).not.toMatch("### Dependencies"); // ONLY four times. expect(result).toHaveLength(4); // Check manifests. expect(require(`${cwd}/packages/a/package.json`)).toMatchObject({ peerDependencies: { "left-pad": "latest", }, }); expect(require(`${cwd}/packages/b/package.json`)).toMatchObject({ dependencies: { "msr-test-a": "1.0.0", }, devDependencies: { "msr-test-d": "1.0.0", "left-pad": "latest", }, }); expect(require(`${cwd}/packages/c/package.json`)).toMatchObject({ devDependencies: { "msr-test-d": "1.0.0", }, }); }); test("Initial commit (changes in all packages with prereleases)", async () => { // Create Git repo with copy of Yarn workspaces fixture. const cwd = gitInit("master", "release"); copyDirectory(`test/fixtures/yarnWorkspaces/`, cwd); const sha = gitCommitAll(cwd, "feat: Initial release"); gitInitOrigin(cwd, "release"); gitPush(cwd); // Capture output. const stdout = new WritableStreamBuffer(); const stderr = new WritableStreamBuffer(); // Call multiSemanticRelease() // Doesn't include plugins that actually publish. const result = await multiSemanticRelease( [ `packages/a/package.json`, `packages/b/package.json`, `packages/c/package.json`, `packages/d/package.json`, ], { branches: [{ name: "master", prerelease: "dev" }, { name: "release" }], }, { cwd, stdout, stderr, env } ); // Get stdout and stderr output. const err = stderr.getContentsAsString("utf8"); expect(err).toBe(false); const out = stdout.getContentsAsString("utf8"); expect(out).toMatch("Started multirelease! Loading 4 packages..."); expect(out).toMatch("Loaded package msr-test-a"); expect(out).toMatch("Loaded package msr-test-b"); expect(out).toMatch("Loaded package msr-test-c"); expect(out).toMatch("Loaded package msr-test-d"); expect(out).toMatch("Queued 4 packages! Starting release..."); expect(out).toMatch("Created tag msr-test-a@1.0.0-dev.1"); expect(out).toMatch("Created tag msr-test-b@1.0.0-dev.1"); expect(out).toMatch("Created tag msr-test-c@1.0.0-dev.1"); expect(out).toMatch("Created tag msr-test-d@1.0.0-dev.1"); expect(out).toMatch("Released 4 of 4 packages, semantically!"); // A. expect(result[0].name).toBe("msr-test-a"); expect(result[0].result.lastRelease).toEqual({}); expect(result[0].result.nextRelease).toMatchObject({ gitHead: sha, gitTag: "msr-test-a@1.0.0-dev.1", type: "minor", version: "1.0.0-dev.1", }); expect(result[0].result.nextRelease.notes).toMatch("# msr-test-a 1.0.0-dev.1"); expect(result[0].result.nextRelease.notes).toMatch("### Features\n\n* Initial release"); // B. expect(result[2].name).toBe("msr-test-b"); expect(result[2].result.lastRelease).toEqual({}); expect(result[2].result.nextRelease).toMatchObject({ gitHead: sha, gitTag: "msr-test-b@1.0.0-dev.1", type: "minor", version: "1.0.0-dev.1", }); expect(result[2].result.nextRelease.notes).toMatch("# msr-test-b 1.0.0-dev.1"); expect(result[2].result.nextRelease.notes).toMatch("### Features\n\n* Initial release"); expect(result[2].result.nextRelease.notes).toMatch( "### Dependencies\n\n* **msr-test-a:** upgraded to 1.0.0-dev.1\n* **msr-test-d:** upgraded to 1.0.0-dev.1" ); // C. expect(result[3].name).toBe("msr-test-c"); expect(result[3].result.lastRelease).toEqual({}); expect(result[3].result.nextRelease).toMatchObject({ gitHead: sha, gitTag: "msr-test-c@1.0.0-dev.1", type: "minor", version: "1.0.0-dev.1", }); expect(result[3].result.nextRelease.notes).toMatch("# msr-test-c 1.0.0-dev.1"); expect(result[3].result.nextRelease.notes).toMatch("### Features\n\n* Initial release"); expect(result[3].result.nextRelease.notes).toMatch( "### Dependencies\n\n* **msr-test-b:** upgraded to 1.0.0-dev.1" ); expect(result[3].result.nextRelease.notes).toMatch("**msr-test-d:** upgraded to 1.0.0-dev.1"); // D. expect(result[1].name).toBe("msr-test-d"); expect(result[1].result.lastRelease).toEqual({}); expect(result[1].result.nextRelease).toMatchObject({ gitHead: sha, gitTag: "msr-test-d@1.0.0-dev.1", type: "minor", version: "1.0.0-dev.1", }); expect(result[1].result.nextRelease.notes).toMatch("# msr-test-d 1.0.0-dev.1"); expect(result[1].result.nextRelease.notes).toMatch("### Features\n\n* Initial release"); expect(result[1].result.nextRelease.notes).not.toMatch("### Dependencies"); // ONLY four times. expect(result).toHaveLength(4); // Check manifests. expect(require(`${cwd}/packages/a/package.json`)).toMatchObject({ peerDependencies: { "left-pad": "latest", }, }); expect(require(`${cwd}/packages/b/package.json`)).toMatchObject({ dependencies: { "msr-test-a": "1.0.0-dev.1", }, devDependencies: { "left-pad": "latest", "msr-test-d": "1.0.0-dev.1", }, }); expect(require(`${cwd}/packages/c/package.json`)).toMatchObject({ devDependencies: { "msr-test-b": "1.0.0-dev.1", "msr-test-d": "1.0.0-dev.1", }, }); }); test("Two separate releases (changes in only one package in second release with prereleases)", async () => { const packages = ["packages/c/", "packages/d/"]; // Create Git repo with copy of Yarn workspaces fixture. const cwd = gitInit("master", "release"); copyDirectory(`test/fixtures/yarnWorkspaces2Packages/`, cwd); const sha1 = gitCommitAll(cwd, "feat: Initial release"); gitInitOrigin(cwd, "release"); gitPush(cwd); let stdout = new WritableStreamBuffer(); let stderr = new WritableStreamBuffer(); // Call multiSemanticRelease() // Doesn't include plugins that actually publish. let result = await multiSemanticRelease( packages.map((folder) => `${folder}package.json`), { branches: [{ name: "master", prerelease: "dev" }, { name: "release" }], }, { cwd, stdout, stderr, env } ); // Add new testing files for a new release. createNewTestingFiles(["packages/c/"], cwd); const sha = gitCommitAll(cwd, "feat: New release on package c only"); gitPush(cwd); // Capture output. stdout = new WritableStreamBuffer(); stderr = new WritableStreamBuffer(); // Call multiSemanticRelease() for a second release // Doesn't include plugins that actually publish. result = await multiSemanticRelease( packages.map((folder) => `${folder}package.json`), { branches: [{ name: "master", prerelease: "dev" }, { name: "release" }], }, { cwd, stdout, stderr, env } ); // Get stdout and stderr output. const err = stderr.getContentsAsString("utf8"); expect(err).toBe(false); const out = stdout.getContentsAsString("utf8"); expect(out).toMatch("Started multirelease! Loading 2 packages..."); expect(out).toMatch("Loaded package msr-test-c"); expect(out).toMatch("Loaded package msr-test-d"); expect(out).toMatch("Queued 2 packages! Starting release..."); expect(out).toMatch("Created tag msr-test-c@1.0.0-dev.2"); expect(out).toMatch("Released 1 of 2 packages, semantically!"); // C. expect(result[1].name).toBe("msr-test-c"); expect(result[1].result.lastRelease).toEqual({ channels: ["master"], gitHead: sha1, gitTag: "msr-test-c@1.0.0-dev.1", name: "msr-test-c@1.0.0-dev.1", version: "1.0.0-dev.1", }); expect(result[1].result.nextRelease).toMatchObject({ gitHead: sha, gitTag: "msr-test-c@1.0.0-dev.2", type: "minor", version: "1.0.0-dev.2", }); expect(result[1].result.nextRelease.notes).toMatch("# msr-test-c [1.0.0-dev.2]"); expect(result[1].result.nextRelease.notes).toMatch("### Features\n\n* New release on package c only"); expect(result[1].result.nextRelease.notes).not.toMatch("### Dependencies"); // ONLY 2 time. expect(result).toHaveLength(2); // Check manifests. expect(require(`${cwd}/packages/c/package.json`)).toMatchObject({ dependencies: { "msr-test-d": "1.0.0-dev.1", }, }); }); test("Two separate releases (release to prerelease)", async () => { const packages = ["packages/c/", "packages/d/"]; // Create Git repo with copy of Yarn workspaces fixture. const cwd = gitInit("master", "release"); copyDirectory(`test/fixtures/yarnWorkspaces2Packages/`, cwd); const sha1 = gitCommitAll(cwd, "feat: Initial release"); gitInitOrigin(cwd, "release"); gitPush(cwd); let stdout = new WritableStreamBuffer(); let stderr = new WritableStreamBuffer(); // Call multiSemanticRelease() // Doesn't include plugins that actually publish. let result = await multiSemanticRelease( packages.map((folder) => `${folder}package.json`), { branches: [{ name: "master" }, { name: "release" }], }, { cwd, stdout, stderr, env } ); // Add new testing files for a new release. createNewTestingFiles(packages, cwd); const sha = gitCommitAll(cwd, "feat: New prerelease\n\nBREAKING CHANGE: bump to bigger value"); gitPush(cwd); // Capture output. stdout = new WritableStreamBuffer(); stderr = new WritableStreamBuffer(); // Call multiSemanticRelease() for a second release // Doesn't include plugins that actually publish. // Change the master branch from release to prerelease to test bumping. result = await multiSemanticRelease( packages.map((folder) => `${folder}package.json`), { branches: [{ name: "master", prerelease: "beta" }, { name: "release" }], }, { cwd, stdout, stderr, env } ); // Get stdout and stderr output. const err = stderr.getContentsAsString("utf8"); expect(err).toBe(false); const out = stdout.getContentsAsString("utf8"); expect(out).toMatch("Started multirelease! Loading 2 packages..."); expect(out).toMatch("Loaded package msr-test-c"); expect(out).toMatch("Loaded package msr-test-d"); expect(out).toMatch("Queued 2 packages! Starting release..."); expect(out).toMatch("Created tag msr-test-c@2.0.0-beta.1"); expect(out).toMatch("Created tag msr-test-d@2.0.0-beta.1"); expect(out).toMatch("Released 2 of 2 packages, semantically!"); // C. expect(result[1].name).toBe("msr-test-c"); expect(result[1].result.lastRelease).toEqual({ channels: [null], gitHead: sha1, gitTag: "msr-test-c@1.0.0", name: "msr-test-c@1.0.0", version: "1.0.0", }); expect(result[1].result.nextRelease).toMatchObject({ gitHead: sha, gitTag: "msr-test-c@2.0.0-beta.1", type: "major", version: "2.0.0-beta.1", }); expect(result[1].result.nextRelease.notes).toMatch("# msr-test-c [2.0.0-beta.1]"); expect(result[1].result.nextRelease.notes).toMatch("### Features\n\n* New prerelease"); expect(result[1].result.nextRelease.notes).toMatch( "### Dependencies\n\n* **msr-test-d:** upgraded to 2.0.0-beta.1" ); // D expect(result[0].result.nextRelease.notes).toMatch("# msr-test-d [2.0.0-beta.1]"); expect(result[0].result.nextRelease.notes).toMatch("### Features\n\n* New prerelease"); expect(result[0].result.nextRelease.notes).not.toMatch("### Dependencies"); // ONLY 2 times. expect(result).toHaveLength(2); // Check manifests. expect(require(`${cwd}/packages/c/package.json`)).toMatchObject({ dependencies: { "msr-test-d": "2.0.0-beta.1", }, }); }, 10000); test("Two separate releases (changes in all packages with prereleases)", async () => { const packages = ["packages/a/", "packages/b/", "packages/c/", "packages/d/"]; // Create Git repo with copy of Yarn workspaces fixture. const cwd = gitInit("master", "release"); copyDirectory(`test/fixtures/yarnWorkspaces/`, cwd); const sha1 = gitCommitAll(cwd, "feat: Initial release"); gitInitOrigin(cwd, "release"); gitPush(cwd); let stdout = new WritableStreamBuffer(); let stderr = new WritableStreamBuffer(); // Call multiSemanticRelease() // Doesn't include plugins that actually publish. let result = await multiSemanticRelease( packages.map((folder) => `${folder}package.json`), { branches: [{ name: "master", prerelease: "dev" }, { name: "release" }], }, { cwd, stdout, stderr, env } ); // Add new testing files for a new release. createNewTestingFiles(packages, cwd); const sha = gitCommitAll(cwd, "feat: New releases"); gitPush(cwd); // Capture output. stdout = new WritableStreamBuffer(); stderr = new WritableStreamBuffer(); // Call multiSemanticRelease() for a second release // Doesn't include plugins that actually publish. result = await multiSemanticRelease( packages.map((folder) => `${folder}package.json`), { branches: [{ name: "master", prerelease: "dev" }, { name: "release" }], }, { cwd, stdout, stderr, env } ); // Get stdout and stderr output. const err = stderr.getContentsAsString("utf8"); expect(err).toBe(false); const out = stdout.getContentsAsString("utf8"); expect(out).toMatch("Started multirelease! Loading 4 packages..."); expect(out).toMatch("Loaded package msr-test-a"); expect(out).toMatch("Loaded package msr-test-b"); expect(out).toMatch("Loaded package msr-test-c"); expect(out).toMatch("Loaded package msr-test-d"); expect(out).toMatch("Queued 4 packages! Starting release..."); expect(out).toMatch("Created tag msr-test-a@1.0.0-dev.2"); expect(out).toMatch("Created tag msr-test-b@1.0.0-dev.2"); expect(out).toMatch("Created tag msr-test-c@1.0.0-dev.2"); expect(out).toMatch("Created tag msr-test-d@1.0.0-dev.2"); expect(out).toMatch("Released 4 of 4 packages, semantically!"); // A. expect(result[0].name).toBe("msr-test-a"); expect(result[0].result.lastRelease).toEqual({ channels: ["master"], gitHead: sha1, gitTag: "msr-test-a@1.0.0-dev.1", name: "msr-test-a@1.0.0-dev.1", version: "1.0.0-dev.1", }); expect(result[0].result.nextRelease).toMatchObject({ gitHead: sha, gitTag: "msr-test-a@1.0.0-dev.2", type: "minor", version: "1.0.0-dev.2", }); expect(result[0].result.nextRelease.notes).toMatch("# msr-test-a [1.0.0-dev.2]"); expect(result[0].result.nextRelease.notes).toMatch("### Features\n\n* New releases"); // B. expect(result[2].name).toBe("msr-test-b"); expect(result[2].result.lastRelease).toEqual({ channels: ["master"], gitHead: sha1, gitTag: "msr-test-b@1.0.0-dev.1", name: "msr-test-b@1.0.0-dev.1", version: "1.0.0-dev.1", }); expect(result[2].result.nextRelease).toMatchObject({ gitHead: sha, gitTag: "msr-test-b@1.0.0-dev.2", type: "minor", version: "1.0.0-dev.2", }); expect(result[2].result.nextRelease.notes).toMatch("# msr-test-b [1.0.0-dev.2]"); expect(result[2].result.nextRelease.notes).toMatch("### Features\n\n* New releases"); expect(result[2].result.nextRelease.notes).toMatch( "### Dependencies\n\n* **msr-test-a:** upgraded to 1.0.0-dev.2\n* **msr-test-d:** upgraded to 1.0.0-dev.2" ); // C. expect(result[3].name).toBe("msr-test-c"); expect(result[3].result.lastRelease).toEqual({ channels: ["master"], gitHead: sha1, gitTag: "msr-test-c@1.0.0-dev.1", name: "msr-test-c@1.0.0-dev.1", version: "1.0.0-dev.1", }); expect(result[3].result.nextRelease).toMatchObject({ gitHead: sha, gitTag: "msr-test-c@1.0.0-dev.2", type: "minor", version: "1.0.0-dev.2", }); expect(result[3].result.nextRelease.notes).toMatch("# msr-test-c [1.0.0-dev.2]"); expect(result[3].result.nextRelease.notes).toMatch("### Features\n\n* New releases"); expect(result[3].result.nextRelease.notes).toMatch( "### Dependencies\n\n* **msr-test-b:** upgraded to 1.0.0-dev.2\n* **msr-test-d:** upgraded to 1.0.0-dev.2" ); // D. expect(result[1].name).toBe("msr-test-d"); expect(result[1].result.lastRelease).toEqual({ channels: ["master"], gitHead: sha1, gitTag: "msr-test-d@1.0.0-dev.1", name: "msr-test-d@1.0.0-dev.1", version: "1.0.0-dev.1", }); expect(result[1].result.nextRelease).toMatchObject({ gitHead: sha, gitTag: "msr-test-d@1.0.0-dev.2", type: "minor", version: "1.0.0-dev.2", }); expect(result[1].result.nextRelease.notes).toMatch("# msr-test-d [1.0.0-dev.2]"); expect(result[1].result.nextRelease.notes).toMatch("### Features\n\n* New releases"); expect(result[1].result.nextRelease.notes).not.toMatch("### Dependencies"); // ONLY four times. expect(result).toHaveLength(4); // Check manifests. expect(require(`${cwd}/packages/a/package.json`)).toMatchObject({ peerDependencies: { "left-pad": "latest", }, }); expect(require(`${cwd}/packages/b/package.json`)).toMatchObject({ dependencies: { "msr-test-a": "1.0.0-dev.2", }, devDependencies: { "msr-test-d": "1.0.0-dev.2", "left-pad": "latest", }, }); expect(require(`${cwd}/packages/c/package.json`)).toMatchObject({ devDependencies: { "msr-test-b": "1.0.0-dev.2", "msr-test-d": "1.0.0-dev.2", }, }); }, 20000); test("No changes in any packages", async () => { // Create Git repo with copy of Yarn workspaces fixture. const cwd = gitInit(); copyDirectory(`test/fixtures/yarnWorkspaces/`, cwd); const sha = gitCommitAll(cwd, "feat: Initial release"); // Creating the four tags so there are no changes in any packages. gitTag(cwd, "msr-test-a@1.0.0"); gitTag(cwd, "msr-test-b@1.0.0"); gitTag(cwd, "msr-test-c@1.0.0"); gitTag(cwd, "msr-test-d@1.0.0"); const url = gitInitOrigin(cwd); gitPush(cwd); // Capture output. const stdout = new WritableStreamBuffer(); const stderr = new WritableStreamBuffer(); // Call multiSemanticRelease() // Doesn't include plugins that actually publish. const result = await multiSemanticRelease( [ `packages/c/package.json`, `packages/a/package.json`, `packages/d/package.json`, `packages/b/package.json`, ], {}, { cwd, stdout, stderr, env } ); // Get stdout and stderr output. const err = stderr.getContentsAsString("utf8"); expect(err).toBe(false); const out = stdout.getContentsAsString("utf8"); expect(out).toMatch("Started multirelease! Loading 4 packages..."); expect(out).toMatch("Loaded package msr-test-a"); expect(out).toMatch("Loaded package msr-test-b"); expect(out).toMatch("Loaded package msr-test-c"); expect(out).toMatch("Loaded package msr-test-d"); expect(out).toMatch("Queued 4 packages! Starting release..."); expect(out).toMatch("There are no relevant changes, so no new version is released"); expect(out).not.toMatch("Created tag"); expect(out).toMatch("Released 0 of 4 packages, semantically!"); // Results. expect(result[0].result).toBe(false); expect(result[1].result).toBe(false); expect(result[2].result).toBe(false); expect(result[3].result).toBe(false); expect(result).toHaveLength(4); }); test("Changes in some packages", async () => { // Create Git repo. const cwd = gitInit(); // Initial commit. copyDirectory(`test/fixtures/yarnWorkspaces/`, cwd); const sha1 = gitCommitAll(cwd, "feat: Initial release"); gitTag(cwd, "msr-test-a@1.0.0"); gitTag(cwd, "msr-test-b@1.0.0"); gitTag(cwd, "msr-test-c@1.0.0"); gitTag(cwd, "msr-test-d@1.0.0"); // Second commit. writeFileSync(`${cwd}/packages/a/aaa.txt`, "AAA"); const sha2 = gitCommitAll(cwd, "feat(aaa): Add missing text file"); const url = gitInitOrigin(cwd); gitPush(cwd); // Capture output. const stdout = new WritableStreamBuffer(); const stderr = new WritableStreamBuffer(); // Call multiSemanticRelease() // Doesn't include plugins that actually publish. const result = await multiSemanticRelease( [ `packages/d/package.json`, `packages/b/package.json`, `packages/a/package.json`, `packages/c/package.json`, ], {}, { cwd, stdout, stderr, env }, { deps: {}, dryRun: false } ); // Get stdout and stderr output. const err = stderr.getContentsAsString("utf8"); expect(err).toBe(false); const out = stdout.getContentsAsString("utf8"); expect(out).toMatch("Started multirelease! Loading 4 packages..."); expect(out).toMatch("Loaded package msr-test-a"); expect(out).toMatch("Loaded package msr-test-b"); expect(out).toMatch("Loaded package msr-test-c"); expect(out).toMatch("Loaded package msr-test-d"); expect(out).toMatch("Queued 4 packages! Starting release..."); expect(out).toMatch("Created tag msr-test-a@1.1.0"); expect(out).toMatch("Created tag msr-test-b@1.0.1"); // expect(out).toMatch("Created tag msr-test-c@1.0.1"); expect(out).toMatch("There are no relevant changes, so no new version is released"); expect(out).toMatch("Released 3 of 4 packages, semantically!"); // A. expect(result[0].name).toBe("msr-test-a"); expect(result[0].result.lastRelease).toMatchObject({ gitHead: sha1, gitTag: "msr-test-a@1.0.0", version: "1.0.0", }); expect(result[0].result.nextRelease).toMatchObject({ gitHead: sha2, gitTag: "msr-test-a@1.1.0", type: "minor", version: "1.1.0", }); expect(result[0].result.nextRelease.notes).toMatch("# msr-test-a [1.1.0]"); expect(result[0].result.nextRelease.notes).toMatch("### Features\n\n* **aaa:** Add missing text file"); // expect(result[3].result.nextRelease.notes).toMatch("### Dependencies\n\n* **msr-test-c:** upgraded to 1.0.1"); // B. expect(result[2].name).toBe("msr-test-b"); expect(result[2].result.lastRelease).toEqual({ channels: [null], gitHead: sha1, gitTag: "msr-test-b@1.0.0", name: "msr-test-b@1.0.0", version: "1.0.0", }); expect(result[2].result.nextRelease).toMatchObject({ gitHead: sha2, gitTag: "msr-test-b@1.0.1", type: "patch", version: "1.0.1", }); expect(result[2].result.nextRelease.notes).toMatch("# msr-test-b [1.0.1]"); expect(result[2].result.nextRelease.notes).not.toMatch("### Features"); expect(result[2].result.nextRelease.notes).not.toMatch("### Bug Fixes"); expect(result[2].result.nextRelease.notes).toMatch("### Dependencies\n\n* **msr-test-a:** upgraded to 1.1.0"); // C. expect(result[3].name).toBe("msr-test-c"); expect(result[3].result.lastRelease).toEqual({ channels: [null], gitHead: sha1, gitTag: "msr-test-c@1.0.0", name: "msr-test-c@1.0.0", version: "1.0.0", }); expect(result[3].result.nextRelease).toMatchObject({ gitHead: sha2, gitTag: "msr-test-c@1.0.1", type: "patch", version: "1.0.1", }); expect(result[3].result.nextRelease.notes).toMatch("# msr-test-c [1.0.1]"); expect(result[3].result.nextRelease.notes).not.toMatch("### Features"); expect(result[3].result.nextRelease.notes).not.toMatch("### Bug Fixes"); expect(result[3].result.nextRelease.notes).toMatch("### Dependencies\n\n* **msr-test-b:** upgraded to 1.0.1"); // D. expect(result[1].name).toBe("msr-test-d"); expect(result[1].result).toBe(false); // ONLY four times. expect(result[4]).toBe(undefined); // Check manifests. expect(require(`${cwd}/packages/a/package.json`)).toMatchObject({ peerDependencies: { "left-pad": "latest", }, }); expect(require(`${cwd}/packages/b/package.json`)).toMatchObject({ dependencies: { "msr-test-a": "1.1.0", }, devDependencies: { "msr-test-d": "1.0.0", "left-pad": "latest", }, }); expect(require(`${cwd}/packages/c/package.json`)).toMatchObject({ devDependencies: { "msr-test-b": "1.0.1", "msr-test-d": "1.0.0", }, }); }); // Bug state that we need to ensure doesn't happen again test("Changes in some packages with correct prerelease bumping from stable", async () => { const preReleaseBranch = "alpha"; // Create Git repo. const cwd = gitInit(preReleaseBranch); // Initial commit. copyDirectory(`test/fixtures/yarnWorkspaces/`, cwd); addPrereleaseToPackageRootConfig(cwd, preReleaseBranch); const sha1 = gitCommitAll(cwd, "feat: Initial release"); gitTag(cwd, "msr-test-a@1.0.0"); gitTag(cwd, "msr-test-b@1.0.0"); gitTag(cwd, "msr-test-c@1.0.0"); gitTag(cwd, "msr-test-d@1.0.0"); // Second commit. writeFileSync(`${cwd}/packages/a/aaa.txt`, "AAA"); const sha2 = gitCommitAll(cwd, "feat(aaa): Add missing text file"); const url = gitInitOrigin(cwd); gitPush(cwd); // Capture output. const stdout = new WritableStreamBuffer(); const stderr = new WritableStreamBuffer(); // Call multiSemanticRelease() // Doesn't include plugins that actually publish. const result = await multiSemanticRelease( [ `packages/d/package.json`, `packages/b/package.json`, `packages/a/package.json`, `packages/c/package.json`, ], {}, { cwd, stdout, stderr, env }, { deps: {}, dryRun: false } ); // Get stdout and stderr output. const err = stderr.getContentsAsString("utf8"); expect(err).toBe(false); const out = stdout.getContentsAsString("utf8"); expect(out).toMatch("Started multirelease! Loading 4 packages..."); expect(out).toMatch("Loaded package msr-test-a"); expect(out).toMatch("Loaded package msr-test-b"); expect(out).toMatch("Loaded package msr-test-c"); expect(out).toMatch("Loaded package msr-test-d"); expect(out).toMatch("Queued 4 packages! Starting release..."); expect(out).toMatch(`Created tag msr-test-a@1.1.0-${preReleaseBranch}.1`); expect(out).toMatch(`Created tag msr-test-b@1.0.1-${preReleaseBranch}.1`); expect(out).toMatch(`Created tag msr-test-c@1.0.1-${preReleaseBranch}.1`); expect(out).toMatch("There are no relevant changes, so no new version is released"); expect(out).toMatch("Released 3 of 4 packages, semantically!"); // A. expect(result[0].name).toBe("msr-test-a"); expect(result[0].result.lastRelease).toMatchObject({ gitHead: sha1, gitTag: "msr-test-a@1.0.0", version: "1.0.0", }); expect(result[0].result.nextRelease).toMatchObject({ gitHead: sha2, gitTag: `msr-test-a@1.1.0-${preReleaseBranch}.1`, type: "minor", version: `1.1.0-${preReleaseBranch}.1`, }); expect(result[0].result.nextRelease.notes).toMatch(`# msr-test-a [1.1.0-${preReleaseBranch}.1]`); expect(result[0].result.nextRelease.notes).toMatch("### Features\n\n* **aaa:** Add missing text file"); // expect(result[3].result.nextRelease.notes).toMatch("### Dependencies\n\n* **msr-test-c:** upgraded to 1.0.1"); // B. expect(result[2].name).toBe("msr-test-b"); expect(result[2].result.lastRelease).toEqual({ channels: [null], gitHead: sha1, gitTag: "msr-test-b@1.0.0", name: "msr-test-b@1.0.0", version: "1.0.0", }); expect(result[2].result.nextRelease).toMatchObject({ gitHead: sha2, gitTag: `msr-test-b@1.0.1-${preReleaseBranch}.1`, type: "patch", version: `1.0.1-${preReleaseBranch}.1`, }); expect(result[2].result.nextRelease.notes).toMatch(`# msr-test-b [1.0.1-${preReleaseBranch}.1]`); expect(result[2].result.nextRelease.notes).not.toMatch("### Features"); expect(result[2].result.nextRelease.notes).not.toMatch("### Bug Fixes"); expect(result[2].result.nextRelease.notes).toMatch("### Dependencies\n\n* **msr-test-a:** upgraded to 1.1.0"); // C. expect(result[3].name).toBe("msr-test-c"); expect(result[3].result.lastRelease).toEqual({ channels: [null], gitHead: sha1, gitTag: "msr-test-c@1.0.0", name: "msr-test-c@1.0.0", version: "1.0.0", }); expect(result[3].result.nextRelease).toMatchObject({ gitHead: sha2, gitTag: `msr-test-c@1.0.1-${preReleaseBranch}.1`, type: "patch", version: `1.0.1-${preReleaseBranch}.1`, }); expect(result[3].result.nextRelease.notes).toMatch(`# msr-test-c [1.0.1-${preReleaseBranch}.1]`); expect(result[3].result.nextRelease.notes).not.toMatch("### Features"); expect(result[3].result.nextRelease.notes).not.toMatch("### Bug Fixes"); expect(result[3].result.nextRelease.notes).toMatch("### Dependencies\n\n* **msr-test-b:** upgraded to 1.0.1"); // D. expect(result[1].name).toBe("msr-test-d"); expect(result[1].result).toBe(false); // ONLY four times. expect(result[4]).toBe(undefined); // Check manifests. expect(require(`${cwd}/packages/a/package.json`)).toMatchObject({ peerDependencies: { "left-pad": "latest", }, }); expect(require(`${cwd}/packages/b/package.json`)).toMatchObject({ dependencies: { "msr-test-a": `1.1.0-${preReleaseBranch}.1`, }, devDependencies: { "msr-test-d": "1.0.0", "left-pad": "latest", }, }); expect(require(`${cwd}/packages/c/package.json`)).toMatchObject({ devDependencies: { "msr-test-b": `1.0.1-${preReleaseBranch}.1`, "msr-test-d": "1.0.0", }, }); // Commit this like the git plugin would (with a skippable syntax) gitCommitAll(cwd, "docs(release): Release everything"); // Release a second time to verify prerelease incrementation writeFileSync(`${cwd}/packages/a/bbb.txt`, "BBB"); const sha3 = gitCommitAll(cwd, "feat(bbb): Add missing text file"); gitPush(cwd); // Capture output. const stdout2 = new WritableStreamBuffer(); const stderr2 = new WritableStreamBuffer(); // NOTE: we call this again because we want to verify semantic-release // channel tagging instead of simulating // Call multiSemanticRelease() // Doesn't include plugins that actually publish. const result2 = await multiSemanticRelease( [ `packages/d/package.json`, `packages/b/package.json`, `packages/a/package.json`, `packages/c/package.json`, ], {}, { cwd, stdout: stdout2, stderr: stderr2, env }, { deps: {}, dryRun: false } ); // Get stdout and stderr output. const err2 = stderr2.getContentsAsString("utf8"); expect(err2).toBe(false); const out2 = stdout2.getContentsAsString("utf8"); expect(out2).toMatch("Started multirelease! Loading 4 packages..."); expect(out2).toMatch("Loaded package msr-test-a"); expect(out2).toMatch("Loaded package msr-test-b"); expect(out2).toMatch("Loaded package msr-test-c"); expect(out2).toMatch("Loaded package msr-test-d"); expect(out2).toMatch("Queued 4 packages! Starting release..."); expect(out2).toMatch(`Created tag msr-test-a@1.1.0-${preReleaseBranch}.2`); // Default behavior minor bumps expect(out2).toMatch(`Created tag msr-test-b@1.0.1-${preReleaseBranch}.2`); expect(out2).toMatch(`Created tag msr-test-c@1.0.1-${preReleaseBranch}.2`); expect(out2).toMatch("There are no relevant changes, so no new version is released"); expect(out2).toMatch("Released 3 of 4 packages, semantically!"); // A. expect(result2[0].name).toBe("msr-test-a"); expect(result2[0].result.lastRelease).toMatchObject({ gitHead: sha2, gitTag: `msr-test-a@1.1.0-${preReleaseBranch}.1`, version: `1.1.0-${preReleaseBranch}.1`, }); expect(result2[0].result.nextRelease).toMatchObject({ gitHead: sha3, gitTag: `msr-test-a@1.1.0-${preReleaseBranch}.2`, type: "minor", version: `1.1.0-${preReleaseBranch}.2`, }); expect(result2[0].result.nextRelease.notes).toMatch(`# msr-test-a [1.1.0-${preReleaseBranch}.2]`); expect(result2[0].result.nextRelease.notes).toMatch("### Features\n\n* **bbb:** Add missing text file"); // expect(result[3].result.nextRelease.notes).toMatch("### Dependencies\n\n* **msr-test-c:** upgraded to 1.0.1"); // B. expect(result2[2].name).toBe("msr-test-b"); expect(result2[2].result.lastRelease).toEqual({ channels: [preReleaseBranch], gitHead: sha2, gitTag: `msr-test-b@1.0.1-${preReleaseBranch}.1`, name: `msr-test-b@1.0.1-${preReleaseBranch}.1`, version: `1.0.1-${preReleaseBranch}.1`, }); expect(result2[2].result.nextRelease).toMatchObject({ gitHead: sha3, gitTag: `msr-test-b@1.0.1-${preReleaseBranch}.2`, type: "patch", version: `1.0.1-${preReleaseBranch}.2`, }); expect(result2[2].result.nextRelease.notes).toMatch(`# msr-test-b [1.0.1-${preReleaseBranch}.2]`); expect(result2[2].result.nextRelease.notes).not.toMatch("### Features"); expect(result2[2].result.nextRelease.notes).not.toMatch("### Bug Fixes"); expect(result2[2].result.nextRelease.notes).toMatch( `### Dependencies\n\n* **msr-test-a:** upgraded to 1.1.0-${preReleaseBranch}.2` ); // C. expect(result2[3].name).toBe("msr-test-c"); expect(result2[3].result.lastRelease).toEqual({ channels: [preReleaseBranch], gitHead: sha2, gitTag: `msr-test-c@1.0.1-${preReleaseBranch}.1`, name: `msr-test-c@1.0.1-${preReleaseBranch}.1`, version: `1.0.1-${preReleaseBranch}.1`, }); expect(result2[3].result.nextRelease).toMatchObject({ gitHead: sha3, gitTag: `msr-test-c@1.0.1-${preReleaseBranch}.2`, type: "patch", version: `1.0.1-${preReleaseBranch}.2`, }); expect(result2[3].result.nextRelease.notes).toMatch(`# msr-test-c [1.0.1-${preReleaseBranch}.2]`); expect(result2[3].result.nextRelease.notes).not.toMatch("### Features"); expect(result2[3].result.nextRelease.notes).not.toMatch("### Bug Fixes"); expect(result2[3].result.nextRelease.notes).toMatch( `### Dependencies\n\n* **msr-test-b:** upgraded to 1.0.1-${preReleaseBranch}.2` ); // D. expect(result2[1].name).toBe("msr-test-d"); expect(result2[1].result).toBe(false); // ONLY four times. expect(result2[4]).toBe(undefined); // Check manifests. expect(JSON.parse(readFileSync(`${cwd}/packages/a/package.json`).toString())).toMatchObject({ peerDependencies: { "left-pad": "latest", }, }); expect(JSON.parse(readFileSync(`${cwd}/packages/b/package.json`).toString())).toMatchObject({ dependencies: { "msr-test-a": `1.1.0-${preReleaseBranch}.2`, }, devDependencies: { "msr-test-d": "1.0.0", "left-pad": "latest", }, }); expect(JSON.parse(readFileSync(`${cwd}/packages/c/package.json`).toString())).toMatchObject({ devDependencies: { "msr-test-b": `1.0.1-${preReleaseBranch}.2`, "msr-test-d": "1.0.0", }, }); }); // Bug state that we want to keep for now in case of other people who have triaged it test("Changes in some packages with bugged prerelease bumping (pullTagsForPrerelease: true)", async () => { const preReleaseBranch = "alpha"; // Create Git repo. const cwd = gitInit(preReleaseBranch); // Initial commit. copyDirectory(`test/fixtures/yarnWorkspaces/`, cwd); addPrereleaseToPackageRootConfig(cwd, preReleaseBranch); const sha1 = gitCommitAll(cwd, "feat: Initial release"); gitTag(cwd, "msr-test-a@1.0.0"); gitTag(cwd, "msr-test-b@1.0.0"); gitTag(cwd, "msr-test-c@1.0.0"); gitTag(cwd, "msr-test-d@1.0.0"); // Second commit. writeFileSync(`${cwd}/packages/a/aaa.txt`, "AAA"); const sha2 = gitCommitAll(cwd, "feat(aaa): Add missing text file"); const url = gitInitOrigin(cwd); gitPush(cwd); // Capture output. const stdout = new WritableStreamBuffer(); const stderr = new WritableStreamBuffer(); // Call multiSemanticRelease() // Doesn't include plugins that actually publish. const result = await multiSemanticRelease( [ `packages/d/package.json`, `packages/b/package.json`, `packages/a/package.json`, `packages/c/package.json`, ], {}, { cwd, stdout, stderr, env }, { deps: { pullTagsForPrerelease: true, }, dryRun: false, } ); // Get stdout and stderr output. const err = stderr.getContentsAsString("utf8"); expect(err).toBe(false); const out = stdout.getContentsAsString("utf8"); expect(out).toMatch("Started multirelease! Loading 4 packages..."); expect(out).toMatch("Loaded package msr-test-a"); expect(out).toMatch("Loaded package msr-test-b"); expect(out).toMatch("Loaded package msr-test-c"); expect(out).toMatch("Loaded package msr-test-d"); expect(out).toMatch("Queued 4 packages! Starting release..."); expect(out).toMatch(`Created tag msr-test-a@1.1.0-${preReleaseBranch}.1`); expect(out).toMatch(`Created tag msr-test-b@1.0.1-${preReleaseBranch}.1`); expect(out).toMatch(`Created tag msr-test-c@1.0.1-${preReleaseBranch}.1`); expect(out).toMatch("There are no relevant changes, so no new version is released"); expect(out).toMatch("Released 3 of 4 packages, semantically!"); // A. expect(result[0].name).toBe("msr-test-a"); expect(result[0].result.lastRelease).toMatchObject({ gitHead: sha1, gitTag: "msr-test-a@1.0.0", version: "1.0.0", }); expect(result[0].result.nextRelease).toMatchObject({ gitHead: sha2, gitTag: `msr-test-a@1.1.0-${preReleaseBranch}.1`, type: "minor", version: `1.1.0-${preReleaseBranch}.1`, }); expect(result[0].result.nextRelease.notes).toMatch(`# msr-test-a [1.1.0-${preReleaseBranch}.1]`); expect(result[0].result.nextRelease.notes).toMatch("### Features\n\n* **aaa:** Add missing text file"); // expect(result[3].result.nextRelease.notes).toMatch("### Dependencies\n\n* **msr-test-c:** upgraded to 1.0.1"); // B. expect(result[2].name).toBe("msr-test-b"); expect(result[2].result.lastRelease).toEqual({ channels: [null], gitHead: sha1, gitTag: "msr-test-b@1.0.0", name: "msr-test-b@1.0.0", version: "1.0.0", }); expect(result[2].result.nextRelease).toMatchObject({ gitHead: sha2, gitTag: `msr-test-b@1.0.1-${preReleaseBranch}.1`, type: "patch", version: `1.0.1-${preReleaseBranch}.1`, }); expect(result[2].result.nextRelease.notes).toMatch(`# msr-test-b [1.0.1-${preReleaseBranch}.1]`); expect(result[2].result.nextRelease.notes).not.toMatch("### Features"); expect(result[2].result.nextRelease.notes).not.toMatch("### Bug Fixes"); expect(result[2].result.nextRelease.notes).toMatch("### Dependencies\n\n* **msr-test-a:** upgraded to 1.1.0"); // C. expect(result[3].name).toBe("msr-test-c"); expect(result[3].result.lastRelease).toEqual({ channels: [null], gitHead: sha1, gitTag: "msr-test-c@1.0.0", name: "msr-test-c@1.0.0", version: "1.0.0", }); expect(result[3].result.nextRelease).toMatchObject({ gitHead: sha2, gitTag: `msr-test-c@1.0.1-${preReleaseBranch}.1`, type: "patch", version: `1.0.1-${preReleaseBranch}.1`, }); expect(result[3].result.nextRelease.notes).toMatch(`# msr-test-c [1.0.1-${preReleaseBranch}.1]`); expect(result[3].result.nextRelease.notes).not.toMatch("### Features"); expect(result[3].result.nextRelease.notes).not.toMatch("### Bug Fixes"); expect(result[3].result.nextRelease.notes).toMatch("### Dependencies\n\n* **msr-test-b:** upgraded to 1.0.1"); // D. expect(result[1].name).toBe("msr-test-d"); expect(result[1].result).toBe(false); // ONLY four times. expect(result[4]).toBe(undefined); // Check manifests. expect(require(`${cwd}/packages/a/package.json`)).toMatchObject({ peerDependencies: { "left-pad": "latest", }, }); expect(require(`${cwd}/packages/b/package.json`)).toMatchObject({ dependencies: { "msr-test-a": `1.1.0-${preReleaseBranch}.1`, }, devDependencies: { "msr-test-d": "1.0.0", "left-pad": "latest", }, }); expect(require(`${cwd}/packages/c/package.json`)).toMatchObject({ devDependencies: { "msr-test-b": `1.0.1-${preReleaseBranch}.1`, "msr-test-d": "1.0.0", }, }); // Commit this like the git plugin would (with a skippable syntax) gitCommitAll(cwd, "docs(release): Release everything"); // Release a second time to verify prerelease incrementation writeFileSync(`${cwd}/packages/a/bbb.txt`, "BBB"); const sha3 = gitCommitAll(cwd, "feat(bbb): Add missing text file"); gitPush(cwd); // Capture output. const stdout2 = new WritableStreamBuffer(); const stderr2 = new WritableStreamBuffer(); // NOTE: we call this again because we want to verify semantic-release // channel tagging instead of simulating // Call multiSemanticRelease() // Doesn't include plugins that actually publish. const result2 = await multiSemanticRelease( [ `packages/d/package.json`, `packages/b/package.json`, `packages/a/package.json`, `packages/c/package.json`, ], {}, { cwd, stdout: stdout2, stderr: stderr2, env }, { deps: { pullTagsForPrerelease: true, }, dryRun: false, } ); // Get stdout and stderr output. const err2 = stderr2.getContentsAsString("utf8"); expect(err2).toBe(false); const out2 = stdout2.getContentsAsString("utf8"); expect(out2).toMatch("Started multirelease! Loading 4 packages..."); expect(out2).toMatch("Loaded package msr-test-a"); expect(out2).toMatch("Loaded package msr-test-b"); expect(out2).toMatch("Loaded package msr-test-c"); expect(out2).toMatch("Loaded package msr-test-d"); expect(out2).toMatch("Queued 4 packages! Starting release..."); expect(out2).toMatch(`Created tag msr-test-a@1.1.0-${preReleaseBranch}.2`); // Default behavior minor bumps expect(out2).toMatch(`Created tag msr-test-b@1.0.1-${preReleaseBranch}.2`); expect(out2).toMatch(`Created tag msr-test-c@1.0.1-${preReleaseBranch}.2`); expect(out2).toMatch("There are no relevant changes, so no new version is released"); expect(out2).toMatch("Released 3 of 4 packages, semantically!"); // A. expect(result2[0].name).toBe("msr-test-a"); expect(result2[0].result.lastRelease).toMatchObject({ gitHead: sha2, gitTag: `msr-test-a@1.1.0-${preReleaseBranch}.1`, version: `1.1.0-${preReleaseBranch}.1`, }); expect(result2[0].result.nextRelease).toMatchObject({ gitHead: sha3, gitTag: `msr-test-a@1.1.0-${preReleaseBranch}.2`, type: "minor", version: `1.1.0-${preReleaseBranch}.2`, }); expect(result2[0].result.nextRelease.notes).toMatch(`# msr-test-a [1.1.0-${preReleaseBranch}.2]`); expect(result2[0].result.nextRelease.notes).toMatch("### Features\n\n* **bbb:** Add missing text file"); // expect(result[3].result.nextRelease.notes).toMatch("### Dependencies\n\n* **msr-test-c:** upgraded to 1.0.1"); // B. expect(result2[2].name).toBe("msr-test-b"); expect(result2[2].result.lastRelease).toEqual({ channels: [preReleaseBranch], gitHead: sha2, gitTag: `msr-test-b@1.0.1-${preReleaseBranch}.1`, name: `msr-test-b@1.0.1-${preReleaseBranch}.1`, version: `1.0.1-${preReleaseBranch}.1`, }); expect(result2[2].result.nextRelease).toMatchObject({ gitHead: sha3, gitTag: `msr-test-b@1.0.1-${preReleaseBranch}.2`, type: "patch", version: `1.0.1-${preReleaseBranch}.2`, }); expect(result2[2].result.nextRelease.notes).toMatch(`# msr-test-b [1.0.1-${preReleaseBranch}.2]`); expect(result2[2].result.nextRelease.notes).not.toMatch("### Features"); expect(result2[2].result.nextRelease.notes).not.toMatch("### Bug Fixes"); expect(result2[2].result.nextRelease.notes).toMatch( `### Dependencies\n\n* **msr-test-a:** upgraded to 1.1.0-${preReleaseBranch}.2` ); // C. expect(result2[3].name).toBe("msr-test-c"); expect(result2[3].result.lastRelease).toEqual({ channels: [preReleaseBranch], gitHead: sha2, gitTag: `msr-test-c@1.0.1-${preReleaseBranch}.1`, name: `msr-test-c@1.0.1-${preReleaseBranch}.1`, version: `1.0.1-${preReleaseBranch}.1`, }); expect(result2[3].result.nextRelease).toMatchObject({ gitHead: sha3, gitTag: `msr-test-c@1.0.1-${preReleaseBranch}.2`, type: "patch", version: `1.0.1-${preReleaseBranch}.2`, }); expect(result2[3].result.nextRelease.notes).toMatch(`# msr-test-c [1.0.1-${preReleaseBranch}.2]`); expect(result2[3].result.nextRelease.notes).not.toMatch("### Features"); expect(result2[3].result.nextRelease.notes).not.toMatch("### Bug Fixes"); expect(result2[3].result.nextRelease.notes).toMatch( `### Dependencies\n\n* **msr-test-b:** upgraded to 1.0.1-${preReleaseBranch}.2` ); // D. expect(result2[1].name).toBe("msr-test-d"); expect(result2[1].result).toBe(false); // ONLY four times. expect(result2[4]).toBe(undefined); const pkgA = JSON.parse(readFileSync(`${cwd}/packages/a/package.json`).toString()); const pkgB = JSON.parse(readFileSync(`${cwd}/packages/b/package.json`).toString()); const pkgC = JSON.parse(readFileSync(`${cwd}/packages/c/package.json`).toString()); // Check manifests. (They have non-existent state) expect(JSON.parse(readFileSync(`${cwd}/packages/a/package.json`).toString())).toMatchObject({ peerDependencies: { "left-pad": "latest", }, }); expect(JSON.parse(readFileSync(`${cwd}/packages/b/package.json`).toString())).toMatchObject({ dependencies: { "msr-test-a": `1.1.0-${preReleaseBranch}.3`, }, devDependencies: { "msr-test-d": "1.0.0", "left-pad": "latest", }, }); expect(JSON.parse(readFileSync(`${cwd}/packages/c/package.json`).toString())).toMatchObject({ devDependencies: { "msr-test-b": `1.0.1-${preReleaseBranch}.3`, "msr-test-d": "1.0.0", }, }); }); test("Changes in child packages with sequentialPrepare", async () => { const mockPrepare = jest.fn(); // Create Git repo. const cwd = gitInit(); // Initial commit. copyDirectory(`test/fixtures/yarnWorkspaces2Packages/`, cwd); const sha1 = gitCommitAll(cwd, "feat: Initial release"); gitTag(cwd, "msr-test-c@1.0.0"); gitTag(cwd, "msr-test-d@1.0.0"); // Second commit. writeFileSync(`${cwd}/packages/d/aaa.txt`, "AAA"); const sha2 = gitCommitAll(cwd, "feat(aaa): Add missing text file"); const url = gitInitOrigin(cwd); gitPush(cwd); // Capture output. const stdout = new WritableStreamBuffer(); const stderr = new WritableStreamBuffer(); // Call multiSemanticRelease() // Doesn't include plugins that actually publish. const result = await multiSemanticRelease( [`packages/c/package.json`, `packages/d/package.json`], { plugins: [ { // Ensure that msr-test-c is always ready before msr-test-d verify: (_, { lastRelease: { name } }) => new Promise((resolvePromise) => { if (name.split("@")[0] === "msr-test-c") { resolvePromise(); } setTimeout(resolvePromise, 5000); }), }, { prepare: (_, { lastRelease: { name } }) => { mockPrepare(name.split("@")[0]); }, }, ], }, { cwd, stdout, stderr, env }, { deps: {}, dryRun: false, sequentialPrepare: true } ); expect(mockPrepare).toHaveBeenNthCalledWith(1, "msr-test-d"); expect(mockPrepare).toHaveBeenNthCalledWith(2, "msr-test-c"); // Get stdout and stderr output. const err = stderr.getContentsAsString("utf8"); expect(err).toBe(false); const out = stdout.getContentsAsString("utf8"); expect(out).toMatch("Started multirelease! Loading 2 packages..."); expect(out).toMatch("Loaded package msr-test-c"); expect(out).toMatch("Loaded package msr-test-d"); expect(out).toMatch("Queued 2 packages! Starting release..."); expect(out).toMatch("Created tag msr-test-d@1.1.0"); expect(out).toMatch("Created tag msr-test-c@1.0.1"); expect(out).toMatch("Released 2 of 2 packages, semantically!"); // C. expect(result[1].name).toBe("msr-test-c"); expect(result[1].result.lastRelease).toMatchObject({ gitHead: sha1, gitTag: "msr-test-c@1.0.0", version: "1.0.0", }); expect(result[1].result.nextRelease).toMatchObject({ gitHead: sha2, gitTag: "msr-test-c@1.0.1", type: "patch", version: "1.0.1", }); // D. expect(result[0].name).toBe("msr-test-d"); expect(result[0].result.lastRelease).toEqual({ channels: [null], gitHead: sha1, gitTag: "msr-test-d@1.0.0", name: "msr-test-d@1.0.0", version: "1.0.0", }); expect(result[0].result.nextRelease).toMatchObject({ gitHead: sha2, gitTag: "msr-test-d@1.1.0", type: "minor", version: "1.1.0", }); // ONLY three times. expect(result[2]).toBe(undefined); // Check manifests. expect(require(`${cwd}/packages/c/package.json`)).toMatchObject({ dependencies: { "msr-test-d": "1.1.0", }, }); }); test("Changes in parent packages with sequentialPrepare", async () => { // Create Git repo. const cwd = gitInit(); // Initial commit. copyDirectory(`test/fixtures/yarnWorkspaces2Packages/`, cwd); const sha1 = gitCommitAll(cwd, "feat: Initial release"); gitTag(cwd, "msr-test-c@1.0.0"); gitTag(cwd, "msr-test-d@1.0.0"); // Second commit. writeFileSync(`${cwd}/packages/c/aaa.txt`, "AAA"); const sha2 = gitCommitAll(cwd, "feat(aaa): Add missing text file"); const url = gitInitOrigin(cwd); gitPush(cwd); // Capture output. const stdout = new WritableStreamBuffer(); const stderr = new WritableStreamBuffer(); // Call multiSemanticRelease() // Doesn't include plugins that actually publish. const result = await multiSemanticRelease( null, {}, { cwd, stdout, stderr, env }, { deps: {}, dryRun: false, sequentialPrepare: true } ); // Get stdout and stderr output. const err = stderr.getContentsAsString("utf8"); expect(err).toBe(false); const out = stdout.getContentsAsString("utf8"); expect(out).toMatch("Started multirelease! Loading 2 packages..."); expect(out).toMatch("Loaded package msr-test-c"); expect(out).toMatch("Loaded package msr-test-d"); expect(out).toMatch("Queued 2 packages! Starting release..."); expect(out).toMatch("Created tag msr-test-c@1.1.0"); expect(out).toMatch("Released 1 of 2 packages, semantically!"); // C. expect(result[1].name).toBe("msr-test-c"); expect(result[1].result.lastRelease).toMatchObject({ gitHead: sha1, gitTag: "msr-test-c@1.0.0", version: "1.0.0", }); expect(result[1].result.nextRelease).toMatchObject({ gitHead: sha2, gitTag: "msr-test-c@1.1.0", type: "minor", version: "1.1.0", }); // D. expect(result[0].name).toBe("msr-test-d"); expect(result[0].result.nextRelease).toBeUndefined(); // ONLY two times. expect(result[2]).toBe(undefined); }); test("Changes in some packages (sequential-init)", async () => { // Create Git repo. const cwd = gitInit(); // Initial commit. copyDirectory(`test/fixtures/yarnWorkspaces/`, cwd); const sha1 = gitCommitAll(cwd, "feat: Initial release"); gitTag(cwd, "msr-test-a@1.0.0"); gitTag(cwd, "msr-test-b@1.0.0"); gitTag(cwd, "msr-test-c@1.0.0"); gitTag(cwd, "msr-test-d@1.0.0"); // Second commit. writeFileSync(`${cwd}/packages/a/aaa.txt`, "AAA"); const sha2 = gitCommitAll(cwd, "feat(aaa): Add missing text file"); const url = gitInitOrigin(cwd); gitPush(cwd); // Capture output. const stdout = new WritableStreamBuffer(); const stderr = new WritableStreamBuffer(); // Call multiSemanticRelease() // Doesn't include plugins that actually publish. const result = await multiSemanticRelease( [ `packages/c/package.json`, `packages/d/package.json`, `packages/b/package.json`, `packages/a/package.json`, ], {}, { cwd, stdout, stderr, env }, { sequentialInit: true } ); // Check manifests. expect(require(`${cwd}/packages/a/package.json`)).toMatchObject({ peerDependencies: { "left-pad": "latest", }, }); expect(require(`${cwd}/packages/b/package.json`)).toMatchObject({ version: "1.0.1", dependencies: { "msr-test-a": "1.1.0", }, devDependencies: { "msr-test-d": "1.0.0", "left-pad": "latest", }, }); expect(require(`${cwd}/packages/c/package.json`)).toMatchObject({ version: "1.0.1", devDependencies: { "msr-test-b": "1.0.1", "msr-test-d": "1.0.0", }, }); }); test("Error if release's local deps have no version number", async () => { // Create Git repo with copy of Yarn workspaces fixture. const cwd = gitInit(); copyDirectory(`test/fixtures/yarnWorkspaces/`, cwd); gitAdd(cwd, "packages/c/package.json"); const sha = gitCommit(cwd, "feat: Commit c package only"); const url = gitInitOrigin(cwd); gitPush(cwd); // Capture output. const stdout = new WritableStreamBuffer(); const stderr = new WritableStreamBuffer(); // Call multiSemanticRelease() try { const result = await multiSemanticRelease(null, {}, { cwd, stdout, stderr, env }); // Not reached. expect(false).toBe(true); } catch (e) { expect(e.message).toBe("Cannot release msr-test-c because dependency msr-test-b has not been released yet"); } }); test("Configured plugins are called as normal", async () => { // Create Git repo with copy of Yarn workspaces fixture. const cwd = gitInit(); copyDirectory(`test/fixtures/yarnWorkspaces/`, cwd); const sha = gitCommitAll(cwd, "feat: Initial release"); const url = gitInitOrigin(cwd); gitPush(cwd); // Make an inline plugin. const plugin = { verifyConditions: jest.fn(), analyzeCommits: jest.fn(), verifyRelease: jest.fn(), generateNotes: jest.fn(), prepare: jest.fn(), success: jest.fn(), fail: jest.fn(), }; // Capture output. const stdout = new WritableStreamBuffer(); const stderr = new WritableStreamBuffer(); // Call multiSemanticRelease() const result = await multiSemanticRelease( [`packages/d/package.json`], { // Override to add our own plugins. plugins: ["@semantic-release/release-notes-generator", plugin], analyzeCommits: ["@semantic-release/commit-analyzer"], }, { cwd, stdout, stderr, env } ); // Check calls. expect(plugin.verifyConditions).toBeCalledTimes(1); expect(plugin.analyzeCommits).toBeCalledTimes(0); // NOTE overridden expect(plugin.verifyRelease).toBeCalledTimes(1); expect(plugin.generateNotes).toBeCalledTimes(1); expect(plugin.prepare).toBeCalledTimes(1); expect(plugin.success).toBeCalledTimes(1); expect(plugin.fail).not.toBeCalled(); }); test("Bot commit release note should filetered", async () => { // Create Git repo. const cwd = gitInit(); // Initial commit. copyDirectory(`test/fixtures/yarnWorkspaces/`, cwd); const sha1 = gitCommitAll(cwd, "feat: Initial release"); gitTag(cwd, "msr-test-a@1.0.0"); gitTag(cwd, "msr-test-b@1.0.0"); gitTag(cwd, "msr-test-c@1.0.0"); gitTag(cwd, "msr-test-d@1.0.0"); // Second commit. writeFileSync(`${cwd}/packages/a/aaa.txt`, "AAA"); const sha2 = gitCommitAll(cwd, "feat(aaa): Add missing text file"); // Third commit. writeFileSync(`${cwd}/packages/b/bbb.txt`, "BBB"); const sha3 = gitCommitAll(cwd, "feat(bbb): Add missing text file"); const url = gitInitOrigin(cwd); gitPush(cwd); // Capture output. const stdout = new WritableStreamBuffer(); const stderr = new WritableStreamBuffer(); // Call multiSemanticRelease() // Include "@semantic-release/git" for made the git head changed const result = await multiSemanticRelease( [ `packages/c/package.json`, `packages/d/package.json`, `packages/b/package.json`, `packages/a/package.json`, ], { plugins: [ "@semantic-release/release-notes-generator", "@semantic-release/changelog", "@semantic-release/git", ], analyzeCommits: ["@semantic-release/commit-analyzer"], }, { cwd, stdout, stderr, env }, { deps: {}, dryRun: false } ); const logOutput = gitGetLog(cwd, 3, "HEAD"); expect(logOutput).not.toMatch(/.*aaa.*Add missing text file.*\n.*bbb.*Add missing text file.*/); }); test("Deep errors (e.g. in plugins) bubble up and out", async () => { // Create Git repo with copy of Yarn workspaces fixture. const cwd = gitInit(); copyDirectory(`test/fixtures/yarnWorkspaces/`, cwd); const sha = gitCommitAll(cwd, "feat: Initial release"); const url = gitInitOrigin(cwd); gitPush(cwd); // Capture output. const stdout = new WritableStreamBuffer(); const stderr = new WritableStreamBuffer(); // Release. // Call multiSemanticRelease() // Doesn't include plugins that actually publish. try { await multiSemanticRelease( [`packages/d/package.json`, `packages/a/package.json`], { // Override to add our own erroring plugin. plugins: [ { analyzeCommits: () => { throw new Error("NOPE"); }, }, ], }, { cwd, stdout, stderr, env } ); // Not reached. expect(false).toBe(true); } catch (e) { // Error bubbles up through semantic-release and multi-semantic-release and out. expect(e.message).toBe("NOPE"); } }); test("TypeError if CWD is not string", async () => { await expect(multiSemanticRelease(null, {}, { cwd: 123 })).rejects.toBeInstanceOf(TypeError); await expect(multiSemanticRelease(null, {}, { cwd: true })).rejects.toBeInstanceOf(TypeError); await expect(multiSemanticRelease(null, {}, { cwd: [] })).rejects.toBeInstanceOf(TypeError); }); test("TypeError if paths is not a list of strings", async () => { await expect(multiSemanticRelease(123)).rejects.toBeInstanceOf(TypeError); await expect(multiSemanticRelease("string")).rejects.toBeInstanceOf(TypeError); await expect(multiSemanticRelease(true)).rejects.toBeInstanceOf(TypeError); await expect(multiSemanticRelease([1, 2, 3])).rejects.toBeInstanceOf(TypeError); await expect(multiSemanticRelease([true, false])).rejects.toBeInstanceOf(TypeError); await expect(multiSemanticRelease([undefined])).rejects.toBeInstanceOf(TypeError); await expect(multiSemanticRelease([null])).rejects.toBeInstanceOf(TypeError); }); test("ReferenceError if paths points to a non-file", async () => { const stdout = new WritableStreamBuffer(); // Blackhole the output so it doesn't clutter Jest. const r1 = multiSemanticRelease(["test/fixtures/DOESNOTEXIST.json"], {}, { stdout }); await expect(r1).rejects.toBeInstanceOf(ReferenceError); // Path that does not exist. const r2 = multiSemanticRelease(["test/fixtures/DOESNOTEXIST/"], {}, { stdout }); await expect(r2).rejects.toBeInstanceOf(ReferenceError); // Path that does not exist. const r3 = multiSemanticRelease(["test/fixtures/"], {}, { stdout }); await expect(r3).rejects.toBeInstanceOf(ReferenceError); // Directory that exists. }); test("SyntaxError if paths points to package.json with bad syntax", async () => { const stdout = new WritableStreamBuffer(); // Blackhole the output so it doesn't clutter Jest. const r1 = multiSemanticRelease(["test/fixtures/invalidPackage.json"], {}, { stdout }); await expect(r1).rejects.toBeInstanceOf(SyntaxError); await expect(r1).rejects.toMatchObject({ message: expect.stringMatching("could not be parsed"), }); const r2 = multiSemanticRelease(["test/fixtures/numberPackage.json"], {}, { stdout }); await expect(r2).rejects.toBeInstanceOf(SyntaxError); await expect(r2).rejects.toMatchObject({ message: expect.stringMatching("not an object"), }); const r3 = multiSemanticRelease(["test/fixtures/badNamePackage.json"], {}, { stdout }); await expect(r3).rejects.toBeInstanceOf(SyntaxError); await expect(r3).rejects.toMatchObject({ message: expect.stringMatching("Package name must be non-empty string"), }); const r4 = multiSemanticRelease(["test/fixtures/badDepsPackage.json"], {}, { stdout }); await expect(r4).rejects.toBeInstanceOf(SyntaxError); await expect(r4).rejects.toMatchObject({ message: expect.stringMatching("Package dependencies must be object"), }); const r5 = multiSemanticRelease(["test/fixtures/badDevDepsPackage.json"], {}, { stdout }); await expect(r5).rejects.toBeInstanceOf(SyntaxError); await expect(r5).rejects.toMatchObject({ message: expect.stringMatching("Package devDependencies must be object"), }); const r6 = multiSemanticRelease(["test/fixtures/badPeerDepsPackage.json"], {}, { stdout }); await expect(r6).rejects.toBeInstanceOf(SyntaxError); await expect(r6).rejects.toMatchObject({ message: expect.stringMatching("Package peerDependencies must be object"), }); }); // test("ValueError if sequentialPrepare is enabled on a cyclic project", async () => { // // Create Git repo with copy of Yarn workspaces fixture. // const cwd = gitInit(); // copyDirectory(`test/fixtures/yarnWorkspaces/`, cwd); // const sha = gitCommitAll(cwd, "feat: Initial release"); // const url = gitInitOrigin(cwd); // gitPush(cwd); // // // Capture output. // const stdout = new WritableStreamBuffer(); // const stderr = new WritableStreamBuffer(); // // // Call multiSemanticRelease() // // Doesn't include plugins that actually publish. // const result = multiSemanticRelease( // [ // `packages/a/package.json`, // `packages/b/package.json`, // `packages/c/package.json`, // `packages/d/package.json`, // ], // {}, // { cwd, stdout, stderr }, // { sequentialPrepare: true, deps: {} } // ); // // await expect(result).rejects.toBeInstanceOf(ValueError); // await expect(result).rejects.toMatchObject({ // message: expect.stringMatching("can't have cyclic with sequentialPrepare option"), // }); // }); test("Generated tag with custom version format", async () => { // Create Git repo with copy of Yarn workspaces fixture. const cwd = await gitInit(); copyDirectory(`test/fixtures/yarnWorkspaces/`, cwd); await gitCommitAll(cwd, "feat: Initial release"); await gitInitOrigin(cwd); await gitPush(cwd); // Capture output. const stdout = new WritableStreamBuffer(); const stderr = new WritableStreamBuffer(); await multiSemanticRelease( [`packages/a/package.json`], {}, { cwd, stdout, stderr, env }, { tagFormat: "${name}/${version}", deps: {} } ); // Get stdout and stderr output. const err = stderr.getContentsAsString("utf8"); expect(err).toBe(false); const out = stdout.getContentsAsString("utf8"); expect(out).toMatch("Created tag msr-test-a/1.0.0"); }); });
import { temporaryDirectory } from "tempy"; import { WritableStreamBuffer } from "stream-buffers"; import { copyDirectory, createNewTestingFiles } from "../helpers/file.js"; import { gitInit, gitCommitAll, gitInitOrigin, gitPush } from "../helpers/git.js"; import { getTags } from "../../lib/git.js"; import multiSemanticRelease from "../../lib/multiSemanticRelease.js"; const env = {}; test("Fetch all tags on master after two package release", async () => { const packages = ["packages/c/", "packages/d/"]; // Create Git repo with copy of Yarn workspaces fixture. const cwd = gitInit("master", "release"); copyDirectory(`test/fixtures/yarnWorkspaces2Packages/`, cwd); const sha1 = gitCommitAll(cwd, "feat: Initial release"); gitInitOrigin(cwd, "release"); gitPush(cwd); const stdout = new WritableStreamBuffer(); const stderr = new WritableStreamBuffer(); // Call multiSemanticRelease() // Doesn't include plugins that actually publish. await multiSemanticRelease( packages.map((folder) => `${folder}package.json`), { branches: [{ name: "master" }, { name: "release" }], }, { cwd, stdout, stderr, env } ); const tags = getTags("master", { cwd }).sort(); expect(tags).toEqual(["msr-test-d@1.0.0", "msr-test-c@1.0.0"].sort()); }); test("Fetch only prerelease tags", async () => { const packages = ["packages/c/", "packages/d/"]; // Create Git repo with copy of Yarn workspaces fixture. const cwd = gitInit("master", "release"); copyDirectory(`test/fixtures/yarnWorkspaces2Packages/`, cwd); const sha1 = gitCommitAll(cwd, "feat: Initial release"); gitInitOrigin(cwd, "release"); gitPush(cwd); let stdout = new WritableStreamBuffer(); let stderr = new WritableStreamBuffer(); // Call multiSemanticRelease() // Doesn't include plugins that actually publish. await multiSemanticRelease( packages.map((folder) => `${folder}package.json`), { branches: [{ name: "master" }, { name: "release" }], }, { cwd, stdout, stderr, env } ); // Add new testing files for a new release. createNewTestingFiles(packages, cwd); const sha = gitCommitAll(cwd, "feat: New prerelease\n\nBREAKING CHANGE: bump to bigger value"); gitPush(cwd); // Capture output. stdout = new WritableStreamBuffer(); stderr = new WritableStreamBuffer(); // Call multiSemanticRelease() for a second release // Doesn't include plugins that actually publish. // Change the master branch from release to prerelease to test bumping. await multiSemanticRelease( packages.map((folder) => `${folder}package.json`), { branches: [{ name: "master", prerelease: "beta" }, { name: "release" }], }, { cwd, stdout, stderr, env } ); const tags = getTags("master", { cwd }, ["beta"]).sort(); expect(tags).toEqual(["msr-test-d@2.0.0-beta.1", "msr-test-c@2.0.0-beta.1"].sort()); }); test("Throws error if obtaining the tags fails", () => { const cwd = temporaryDirectory(); const t = () => { getTags("master", { cwd }); }; expect(t).toThrow(Error); });
import cleanPath from "../../lib/cleanPath.js"; // Tests. describe("cleanPath()", () => { test("Relative without CWD", () => { expect(cleanPath("aaa")).toBe(`${process.cwd()}/aaa`); expect(cleanPath("aaa/")).toBe(`${process.cwd()}/aaa`); }); test("Relative with CWD", () => { expect(cleanPath("ccc", "/a/b/")).toBe(`/a/b/ccc`); expect(cleanPath("ccc", "/a/b")).toBe(`/a/b/ccc`); }); test("Absolute without CWD", () => { expect(cleanPath("/aaa")).toBe(`/aaa`); expect(cleanPath("/aaa/")).toBe(`/aaa`); expect(cleanPath("/a/b/c")).toBe(`/a/b/c`); expect(cleanPath("/a/b/c/")).toBe(`/a/b/c`); }); test("Absolute with CWD", () => { expect(cleanPath("/aaa", "/x/y/z")).toBe(`/aaa`); expect(cleanPath("/aaa/", "/x/y/z")).toBe(`/aaa`); expect(cleanPath("/a/b/c", "/x/y/z")).toBe(`/a/b/c`); expect(cleanPath("/a/b/c/", "/x/y/z")).toBe(`/a/b/c`); }); });
import { resolve } from "path"; import { dirname } from "node:path"; import { fileURLToPath } from "node:url"; import { topo } from "@semrel-extra/topo"; const __dirname = dirname(fileURLToPath(import.meta.url)); const getPackagePaths = async (cwd, ignore = []) => { const workspacesExtra = ignore.map((item) => `!${item}`); const result = await topo({ cwd, workspacesExtra }); return Object.values(result.packages) .map((pkg) => pkg.manifestPath) .sort(); }; // Tests. describe("getPackagePaths()", () => { test("yarn: Works correctly with workspaces", async () => { const resolved = resolve(`${__dirname}/../fixtures/yarnWorkspaces`); expect(await getPackagePaths(resolved)).toEqual([ `${resolved}/packages/a/package.json`, `${resolved}/packages/b/package.json`, `${resolved}/packages/c/package.json`, `${resolved}/packages/d/package.json`, ]); }); test("yarn: Should ignore some packages", async () => { const resolved = resolve(`${__dirname}/../fixtures/yarnWorkspacesIgnore`); expect(await getPackagePaths(resolved)).toEqual([ `${resolved}/packages/a/package.json`, `${resolved}/packages/b/package.json`, `${resolved}/packages/c/package.json`, ]); const resolvedSplit = resolve(`${__dirname}/../fixtures/yarnWorkspacesIgnoreSplit`); expect(await getPackagePaths(resolvedSplit)).toEqual([ `${resolvedSplit}/packages/a/package.json`, `${resolvedSplit}/packages/c/package.json`, ]); }); test("yarn: Should ignore some packages via CLI", async () => { const resolved = resolve(`${__dirname}/../fixtures/yarnWorkspacesIgnore`); expect(await getPackagePaths(resolved, ["packages/a/**", "packages/b/**"])).toEqual([ `${resolved}/packages/c/package.json`, ]); const resolvedSplit = resolve(`${__dirname}/../fixtures/yarnWorkspacesIgnoreSplit`); expect(await getPackagePaths(resolvedSplit, ["packages/b", "packages/d"])).toEqual([ `${resolvedSplit}/packages/a/package.json`, `${resolvedSplit}/packages/c/package.json`, ]); }); // test("yarn: Should throw when ignored packages from CLI and workspaces sets an empty workspace list to be processed", async () => { // const resolved = resolve(`${__dirname}/../fixtures/yarnWorkspacesIgnore`); // expect(() => await getPackagePaths(resolved, ["packages/a/**", "packages/b/**", "packages/c/**"])).toThrow(TypeError); // expect(() => await getPackagePaths(resolved, ["packages/a/**", "packages/b/**", "packages/c/**"])).toThrow( // "package.json: Project must contain one or more workspace-packages" // ); // }); // test("yarn: Error if no workspaces setting", async () => { // const resolved = resolve(`${__dirname}/../fixtures/emptyYarnWorkspaces`); // expect(() => await getPackagePaths(resolved)).toThrow(Error); // expect(() => await getPackagePaths(resolved)).toThrow("contain one or more workspace-packages"); // }); test("yarn: Works correctly with workspaces.packages", async () => { const resolved = resolve(`${__dirname}/../fixtures/yarnWorkspacesPackages`); expect(await getPackagePaths(resolved)).toEqual([ `${resolved}/packages/a/package.json`, `${resolved}/packages/b/package.json`, `${resolved}/packages/c/package.json`, `${resolved}/packages/d/package.json`, ]); }); test("pnpm: Works correctly with workspace", async () => { const resolved = resolve(`${__dirname}/../fixtures/pnpmWorkspace`); expect(await getPackagePaths(resolved)).toEqual([ `${resolved}/packages/a/package.json`, `${resolved}/packages/b/package.json`, `${resolved}/packages/c/package.json`, `${resolved}/packages/d/package.json`, ]); }); // test("pnpm: Error if no workspaces setting", async () => { // const resolved = resolve(`${__dirname}/../fixtures/pnpmWorkspaceUndefined`); // expect(() => await getPackagePaths(resolved)).toThrow(Error); // expect(() => await getPackagePaths(resolved)).toThrow("contain one or more workspace-packages"); // }); test("pnpm: Should ignore some packages", async () => { const resolved = resolve(`${__dirname}/../fixtures/pnpmWorkspaceIgnore`); expect(await getPackagePaths(resolved)).toEqual([ `${resolved}/packages/a/package.json`, `${resolved}/packages/b/package.json`, `${resolved}/packages/c/package.json`, ]); }); test("pnpm: Should ignore some packages via CLI", async () => { const resolved = resolve(`${__dirname}/../fixtures/pnpmWorkspaceIgnore`); expect(await getPackagePaths(resolved, ["packages/a/**", "packages/b/**"])).toEqual([ `${resolved}/packages/c/package.json`, ]); }); test("bolt: Works correctly with workspaces", async () => { const resolved = resolve(`${__dirname}/../fixtures/boltWorkspaces`); expect(await getPackagePaths(resolved)).toEqual([ `${resolved}/packages/a/package.json`, `${resolved}/packages/b/package.json`, `${resolved}/packages/c/package.json`, `${resolved}/packages/d/package.json`, ]); }); // test("bolt: Error if no workspaces setting", async () => { // const resolved = resolve(`${__dirname}/../fixtures/boltWorkspacesUndefined`); // expect(() => await getPackagePaths(resolved)).toThrow(Error); // expect(() => await getPackagePaths(resolved)).toThrow("contain one or more workspace-packages"); // }); test("bolt: Should ignore some packages", async () => { const resolved = resolve(`${__dirname}/../fixtures/boltWorkspacesIgnore`); expect(await getPackagePaths(resolved)).toEqual([ `${resolved}/packages/a/package.json`, `${resolved}/packages/b/package.json`, `${resolved}/packages/c/package.json`, ]); }); test("bolt: Should ignore some packages via CLI", async () => { const resolved = resolve(`${__dirname}/../fixtures/boltWorkspacesIgnore`); expect(await getPackagePaths(resolved, ["packages/a/**", "packages/b/**"])).toEqual([ `${resolved}/packages/c/package.json`, ]); }); });
import { beforeAll, beforeEach, jest } from "@jest/globals"; jest.unstable_mockModule("../../lib/git.js", () => ({ getTags: jest.fn(), })); let resolveReleaseType, resolveNextVersion, getNextVersion, getNextPreVersion, getPreReleaseTag, getVersionFromTag, getTags; beforeAll(async () => { ({ getTags } = await import("../../lib/git.js")); ({ resolveReleaseType, resolveNextVersion, getNextVersion, getNextPreVersion, getPreReleaseTag, getVersionFromTag, } = await import("../../lib/updateDeps.js")); }); describe("resolveNextVersion()", () => { // prettier-ignore const cases = [ ["1.0.0", "1.0.1", undefined, "1.0.1"], ["1.0.0", "1.0.1", "override", "1.0.1"], ["*", "1.3.0", "satisfy", "*"], ["^1.0.0", "1.0.1", "satisfy", "^1.0.0"], ["^1.2.0", "1.3.0", "satisfy", "^1.2.0"], ["1.2.x", "1.2.2", "satisfy", "1.2.x"], ["~1.0.0", "1.1.0", "inherit", "~1.1.0"], ["1.2.x", "1.2.1", "inherit", "1.2.x"], ["1.2.x", "1.3.0", "inherit", "1.3.x"], ["^1.0.0", "2.0.0", "inherit", "^2.0.0"], ["*", "2.0.0", "inherit", "*"], ["~1.0", "2.0.0", "inherit", "~2.0"], ["~2.0", "2.1.0", "inherit", "~2.1"], ] cases.forEach(([currentVersion, nextVersion, strategy, resolvedVersion]) => { it(`${currentVersion}/${nextVersion}/${strategy} gives ${resolvedVersion}`, () => { expect(resolveNextVersion(currentVersion, nextVersion, strategy)).toBe(resolvedVersion); }); }); }); describe("resolveReleaseType()", () => { // prettier-ignore const cases = [ [ "returns own package's _nextType if exists", { _nextType: "patch", localDeps: [], }, undefined, undefined, "patch", ], [ "implements `inherit` strategy: returns the highest release type of any deps", { manifest: { dependencies: { a: "1.0.0" } }, _nextType: undefined, localDeps: [ { name: "a", manifest: { dependencies: { b: "1.0.0", c: "1.0.0", d: "1.0.0" } }, _lastRelease: { version: "1.0.0" }, _nextType: false, localDeps: [ { name: "b", _nextType: false, localDeps: [], _lastRelease: { version: "1.0.0" } }, { name: "c", _nextType: "patch", localDeps: [], _lastRelease: { version: "1.0.0" } }, { name: "d", _nextType: "major", localDeps: [], _lastRelease: { version: "1.0.0" } }, ], }, ], }, undefined, "inherit", "major" ], [ "implements `inherit` strategy: returns the highest release type of any deps even if the local package has changes", { manifest: { dependencies: { a: "1.0.0" } }, _nextType: "minor", localDeps: [ { name: "a", manifest: { dependencies: { b: "1.0.0", c: "1.0.0", d: "1.0.0" } }, _lastRelease: { version: "1.0.0" }, _nextType: false, localDeps: [ { name: "b", _nextType: false, localDeps: [], _lastRelease: { version: "1.0.0" } }, { name: "c", _nextType: "patch", localDeps: [], _lastRelease: { version: "1.0.0" } }, { name: "d", _nextType: "major", localDeps: [], _lastRelease: { version: "1.0.0" } }, ], }, ], }, undefined, "inherit", "major" ], [ "overrides dependent release type with custom value if defined", { manifest: { dependencies: { a: "1.0.0" } }, _nextType: undefined, localDeps: [ { name: "a", // _lastRelease: { version: "1.0.0" }, manifest: { dependencies: { b: "1.0.0", c: "1.0.0", d: "1.0.0" } }, _nextType: false, localDeps: [ { name: "b", _nextType: false, localDeps: [], _lastRelease: { version: "1.0.0" } }, { name: "c", _nextType: "minor", localDeps: [], _lastRelease: { version: "1.0.0" } }, { name: "d", _nextType: "patch", localDeps: [], _lastRelease: { version: "1.0.0" } }, ], }, ], }, undefined, "major", "major" ], [ "uses `patch` strategy as default (legacy flow)", { manifest: { dependencies: { a: "1.0.0" } }, _nextType: undefined, localDeps: [ { name: "a", _nextType: false, //_lastRelease: { version: "1.0.0" }, manifest: { dependencies: { b: "1.0.0", c: "1.0.0", d: "1.0.0" } }, localDeps: [ { name: "b", _nextType: false, localDeps: [], _lastRelease: { version: "1.0.0" } }, { name: "c", _nextType: "minor", localDeps: [], _lastRelease: { version: "1.0.0" } }, { name: "d", _nextType: "major", localDeps: [], _lastRelease: { version: "1.0.0" } }, ], }, ], }, undefined, undefined, "patch" ], [ "returns undefined if no _nextRelease found", { _nextType: undefined, localDeps: [ { _nextType: false, localDeps: [ { _nextType: false, localDeps: [] }, { _nextType: undefined, localDeps: [ { _nextType: undefined, localDeps: [] } ] }, ], }, ], }, undefined, undefined, undefined, ], ] cases.forEach(([name, pkg, bumpStrategy, releaseStrategy, result]) => { it(name, () => { expect(resolveReleaseType(pkg, bumpStrategy, releaseStrategy)).toBe(result); }); }); }); it("`override` + `prefix` injects carets to the manifest", () => { const pkgB = { name: "b", _nextType: false, localDeps: [], _lastRelease: { version: "1.0.0" } }; const pkgC = { name: "c", _nextType: "minor", localDeps: [], _lastRelease: { version: "1.0.0" } }; const pkgD = { name: "d", _nextType: "patch", localDeps: [], _lastRelease: { version: "1.0.0" } }; const pkgA = { name: "a", manifest: { dependencies: { b: "1.0.0", c: "1.0.0", d: "1.0.0" } }, _nextType: false, localDeps: [pkgB, pkgC, pkgD], }; const pkg = { name: "root", manifest: { dependencies: { a: "1.0.0" } }, _nextType: undefined, localDeps: [pkgA], }; const type = resolveReleaseType(pkg, "override", "patch", [], "^"); expect(type).toBe("patch"); expect(pkg._nextType).toBe("patch"); expect(pkg.manifest.dependencies.a).toBe("^1.0.0"); expect(pkgA.manifest.dependencies.b).toBe("^1.0.0"); expect(pkgA.manifest.dependencies.c).toBe("^1.1.0"); expect(pkgA.manifest.dependencies.d).toBe("^1.0.1"); }); describe("getNextVersion()", () => { // prettier-ignore const cases = [ [undefined, "patch", "1.0.0"], ["1.0.0", "patch", "1.0.1"], ["2.0.0", undefined, "2.0.0"], ["1.0.0-dev.1", "major", "1.0.0"], ["1.0.0-dev.1", undefined, "1.0.0-dev.1"], ["1.0.0-dev.1", "minor", "1.0.0"], ["1.0.0-dev.1", "patch", "1.0.0"], ] cases.forEach(([lastVersion, releaseType, nextVersion, preRelease]) => { it(`${lastVersion} and ${releaseType} gives ${nextVersion}`, () => { // prettier-ignore expect(getNextVersion({ _nextType: releaseType, _lastRelease: {version: lastVersion}, _preRelease: preRelease })).toBe(nextVersion); }); }); }); describe("getNextPreVersion()", () => { beforeEach(() => { jest.clearAllMocks(); }); // prettier-ignore const cases = [ [undefined, "patch", "rc", [], "1.0.0-rc.1"], [undefined, "patch", "rc", [], "1.0.0-rc.1"], [null, "patch", "rc", [], "1.0.0-rc.1"], [null, "patch", "rc", [], "1.0.0-rc.1"], ["1.0.0-rc.0", "minor", "dev", [], "1.0.0-dev.1"], ["1.0.0-dev.0", "major", "dev", [], "1.0.0-dev.1"], ["1.0.0-dev.0", "major", "dev", ["testing-package@1.0.0-dev.1"], "1.0.0-dev.2"], ["1.0.0-dev.0", "major", "dev", ["testing-package@1.0.0-dev.1", "1.0.1-dev.0"], "1.0.1-dev.1"], ["11.0.0", "major", "beta", [], "12.0.0-beta.1"], ["1.0.0", "minor", "beta", [], "1.1.0-beta.1"], ["1.0.0", "patch", "beta", [], "1.0.1-beta.1"], ] cases.forEach(([lastVersion, releaseType, preRelease, lastTags, nextVersion]) => { it(`${lastVersion} and ${releaseType} ${ lastTags.length ? "with existent tags " : "" }gives ${nextVersion}`, () => { // prettier-ignore expect(getNextPreVersion( { _nextType: releaseType, _lastRelease: {version: lastVersion}, _preRelease: preRelease, _branch: "master", name: "testing-package", pullTagsForPrerelease: true, }, lastTags, )).toBe(nextVersion); }); it(`${lastVersion} and ${releaseType} ${ lastTags.length ? "with looked up branch tags " : "" }gives ${nextVersion}`, () => { getTags.mockImplementation(() => { return lastTags; }); // prettier-ignore expect(getNextPreVersion( { _nextType: releaseType, _lastRelease: {version: lastVersion}, _preRelease: preRelease, _branch: "master", name: "testing-package", pullTagsForPrerelease: true, }, // No Tags array means we look them up )).toBe(nextVersion); expect(getTags).toHaveBeenCalledTimes(1); }); }); it("does not allow tags if pullTagsForPrerelease = false", () => { expect(() => getNextPreVersion( { _nextType: "patch", _lastRelease: { version: "1.0.0" }, _preRelease: "dev", _branch: "master", name: "testing-package", pullTagsForPrerelease: false, }, [] ) ).toThrowError("Supplied tags for NextPreVersion but the package does not use tags for next prerelease"); }); // Simulates us not using tags as criteria const noTagCases = [ // prerelease channels just bump up the pre-release ["1.0.0-rc.0", "minor", "rc", "1.0.0-rc.1"], ["1.0.0-dev.0", "major", "dev", "1.0.0-dev.1"], ["1.0.0-dev.0", "major", "dev", "1.0.0-dev.1"], ["1.0.1-dev.0", "major", "dev", "1.0.1-dev.1"], // main channels obey the release type ["11.0.0", "major", "beta", "12.0.0-beta.1"], ["1.0.0", "minor", "beta", "1.1.0-beta.1"], ["1.0.0", "patch", "beta", "1.0.1-beta.1"], ]; noTagCases.forEach(([lastVersion, releaseType, preRelease, nextVersion]) => { it(`${lastVersion} and ${releaseType} for channel ${preRelease} gives ${nextVersion} when pullTagsForPrerelease = false`, () => { // prettier-ignore expect(getNextPreVersion( { _nextType: releaseType, _lastRelease: {version: lastVersion}, _preRelease: preRelease, _branch: "master", name: "testing-package", pullTagsForPrerelease: false, }, )).toBe(nextVersion); }); }); }); describe("getPreReleaseTag()", () => { // prettier-ignore const cases = [ [undefined, null], [null, null], ["1.0.0-rc.0", "rc"], ["1.0.0-dev.0", "dev"], ["1.0.0-dev.2", "dev"], ["1.1.0-beta.0", "beta"], ["11.0.0", null], ["11.1.0", null], ["11.0.1", null], ] cases.forEach(([version, preReleaseTag]) => { it(`${version} gives ${preReleaseTag}`, () => { // prettier-ignore expect(getPreReleaseTag(version)).toBe(preReleaseTag); }); }); }); describe("getVersionFromTag()", () => { // prettier-ignore const cases = [ [{}, undefined, null], [{ name: undefined }, undefined, null], [{}, null, null], [{ name: null }, null, null], [{ name: undefined }, '1.0.0', '1.0.0'], [{ name: null }, '1.0.0', '1.0.0'], [{ name: 'abc' }, undefined, null], [{ name: 'abc' }, null, null], [{ name: 'abc' }, '1.0.0', '1.0.0'], [{ name: 'dev' }, '1.0.0-dev.1', '1.0.0-dev.1'], [{ name: 'app' }, 'app@1.0.0-dev.1', '1.0.0-dev.1'], [{ name: 'app' }, 'app@1.0.0-devapp@.1', null], [{ name: 'msr-test-a' }, 'msr-test-a@1.0.0-rc.1', '1.0.0-rc.1'], [{ name: 'msr.test.a' }, 'msr.test.a@1.0.0', '1.0.0'], [{ name: 'msr_test_a' }, 'msr_test_a@1.0.0', '1.0.0'], [{ name: 'msr@test@a' }, 'msr@test@a@1.0.0', '1.0.0'], [{ name: 'abc' }, 'a.b.c-rc.0', null], [{ name: 'abc' }, '1-rc.0', null], [{ name: 'abc' }, '1.0.x-rc.0', null], [{ name: 'abc' }, '1.x.0-rc.0', null], [{ name: 'abc' }, 'x.1.0-rc.0', null], ] cases.forEach(([pkg, tag, versionFromTag]) => { it(`${JSON.stringify(pkg)} pkg with tag ${tag} gives ${versionFromTag}`, () => { // prettier-ignore expect(getVersionFromTag(pkg, tag)).toBe(versionFromTag); }); }); });
import { resolveReleaseType } from "../../lib/updateDeps.js"; // Tests. describe("resolveReleaseType()", () => { test("Works correctly with no deps", () => { expect(resolveReleaseType({ localDeps: [] })).toBe(undefined); }); test("Works correctly with deps", () => { const pkg1 = { _nextType: "patch", localDeps: [] }; expect(resolveReleaseType(pkg1)).toBe("patch"); const pkg2 = { _nextType: undefined, localDeps: [] }; expect(resolveReleaseType(pkg2)).toBe(undefined); const pkg3 = { _nextType: undefined, localDeps: [ { _nextType: false, localDeps: [] }, { _nextType: false, localDeps: [] }, ], }; expect(resolveReleaseType(pkg3)).toBe(undefined); const pkg4 = { manifest: { dependencies: { a: "1.0.0" } }, _nextType: undefined, localDeps: [ { name: "a", _nextType: "patch", localDeps: [], _lastRelease: { version: "1.0.0" } }, { name: "b", _nextType: false, localDeps: [], _lastRelease: { version: "1.0.0" } }, ], }; expect(resolveReleaseType(pkg4)).toBe("patch"); const pkg5 = { _nextType: undefined, localDeps: [ { _nextType: false, localDeps: [ { _nextType: false, localDeps: [] }, { _nextType: false, localDeps: [] }, ], }, ], }; expect(resolveReleaseType(pkg5)).toBe(undefined); const pkg6 = { manifest: { dependencies: { a: "1.0.0" } }, _nextType: undefined, localDeps: [ { name: "a", _lastRelease: { version: "1.0.0" }, _nextType: false, manifest: { dependencies: { b: "1.0.0", c: "1.0.0", d: "1.0.0" } }, localDeps: [ { name: "b", _nextType: false, localDeps: [], _lastRelease: { version: "1.0.0" } }, { name: "c", _nextType: "patch", localDeps: [], _lastRelease: { version: "1.0.0" } }, { name: "d", _nextType: "major", localDeps: [], _lastRelease: { version: "1.0.0" } }, ], }, ], }; expect(resolveReleaseType(pkg6, "override", "inherit")).toBe("major"); }); test("No infinite loops", () => { const pkg1 = { _nextType: "patch", localDeps: [] }; pkg1.localDeps.push(pkg1); expect(resolveReleaseType(pkg1)).toBe("patch"); const pkg2 = { _nextType: undefined, localDeps: [] }; pkg2.localDeps.push(pkg2); expect(resolveReleaseType(pkg2)).toBe(undefined); const pkg3 = { _nextType: undefined, localDeps: [ { _nextType: false, localDeps: [] }, { _nextType: false, localDeps: [] }, ], }; pkg3.localDeps[0].localDeps.push(pkg3.localDeps[0]); expect(resolveReleaseType(pkg3)).toBe(undefined); const pkg4 = { manifest: { dependencies: { a: "1.0.0", b: "1.0.0" } }, _nextType: undefined, localDeps: [ { name: "a", _nextType: "patch", localDeps: [], _lastRelease: { version: "1.0.0" } }, { name: "b", _nextType: "major", localDeps: [], _lastRelease: { version: "1.0.0" } }, ], }; pkg4.localDeps[0].localDeps.push(pkg4.localDeps[0]); expect(resolveReleaseType(pkg4)).toBe("patch"); }); });
import { isAbsolute, join } from "path"; import { temporaryDirectory } from "tempy"; import { writeFileSync, mkdirSync } from "fs"; import getCommitsFiltered from "../../lib/getCommitsFiltered.js"; import { gitInit, gitCommitAll } from "../helpers/git.js"; // Tests. describe("getCommitsFiltered()", () => { test("Works correctly (no lastHead)", async () => { // Create Git repo with copy of Yarn workspaces fixture. const cwd = await gitInit(); writeFileSync(`${cwd}/AAA.txt`, "AAA"); const sha1 = await gitCommitAll(cwd, "Commit 1"); mkdirSync(`${cwd}/bbb`); writeFileSync(`${cwd}/bbb/BBB.txt`, "BBB"); const sha2 = await gitCommitAll(cwd, "Commit 2"); mkdirSync(`${cwd}/ccc`); writeFileSync(`${cwd}/ccc/CCC.txt`, "CCC"); const sha3 = await gitCommitAll(cwd, "Commit 3"); // Filter a single directory of the repo. const commits = await getCommitsFiltered(cwd, "bbb/"); expect(commits.length).toBe(1); expect(commits[0].hash).toBe(sha2); expect(commits[0].subject).toBe("Commit 2"); }); test("Works correctly (with lastHead)", async () => { // Create Git repo with copy of Yarn workspaces fixture. const cwd = await gitInit(); writeFileSync(`${cwd}/AAA.txt`, "AAA"); const sha1 = await gitCommitAll(cwd, "Commit 1"); mkdirSync(`${cwd}/bbb`); writeFileSync(`${cwd}/bbb/BBB.txt`, "BBB"); const sha2 = await gitCommitAll(cwd, "Commit 2"); mkdirSync(`${cwd}/ccc`); writeFileSync(`${cwd}/ccc/CCC.txt`, "CCC"); const sha3 = await gitCommitAll(cwd, "Commit 3"); // Filter a single directory of the repo since sha3 const commits = await getCommitsFiltered(cwd, "bbb/", sha3); expect(commits.length).toBe(0); }); test("Works correctly (initial commit)", async () => { // Create Git repo with copy of Yarn workspaces fixture. const cwd = await gitInit(); mkdirSync(`${cwd}/bbb`); mkdirSync(`${cwd}/ccc`); writeFileSync(`${cwd}/AAA.txt`, "AAA"); writeFileSync(`${cwd}/bbb/BBB.txt`, "BBB"); writeFileSync(`${cwd}/ccc/CCC.txt`, "CCC"); const sha = await gitCommitAll(cwd, "Initial commit"); // Filter a single directory of the repo. const commits = await getCommitsFiltered(cwd, "bbb/"); expect(commits.length).toBe(1); expect(commits[0].hash).toBe(sha); }); test("TypeError if cwd is not absolute path to directory", async () => { await expect(getCommitsFiltered(123, ".")).rejects.toBeInstanceOf(TypeError); await expect(getCommitsFiltered(123, ".")).rejects.toMatchObject({ message: expect.stringMatching("cwd: Must be directory that exists in the filesystem"), }); await expect(getCommitsFiltered("aaa", ".")).rejects.toBeInstanceOf(TypeError); await expect(getCommitsFiltered("aaa", ".")).rejects.toMatchObject({ message: expect.stringMatching("cwd: Must be directory that exists in the filesystem"), }); const cwd = temporaryDirectory(); await expect(getCommitsFiltered(`${cwd}/abc`, ".")).rejects.toBeInstanceOf(TypeError); await expect(getCommitsFiltered(`${cwd}/abc`, ".")).rejects.toMatchObject({ message: expect.stringMatching("cwd: Must be directory that exists in the filesystem"), }); }); test("TypeError if dir is not path to directory", async () => { const cwd = temporaryDirectory(); await expect(getCommitsFiltered(cwd, 123)).rejects.toBeInstanceOf(TypeError); await expect(getCommitsFiltered(cwd, 123)).rejects.toMatchObject({ message: expect.stringMatching("dir: Must be valid path"), }); await expect(getCommitsFiltered(cwd, "abc")).rejects.toBeInstanceOf(TypeError); await expect(getCommitsFiltered(cwd, "abc")).rejects.toMatchObject({ message: expect.stringMatching("dir: Must be directory that exists in the filesystem"), }); await expect(getCommitsFiltered(cwd, `${cwd}/abc`)).rejects.toBeInstanceOf(TypeError); await expect(getCommitsFiltered(cwd, `${cwd}/abc`)).rejects.toMatchObject({ message: expect.stringMatching("dir: Must be directory that exists in the filesystem"), }); }); test("TypeError if dir is equal to cwd", async () => { const cwd = temporaryDirectory(); await expect(getCommitsFiltered(cwd, cwd)).rejects.toBeInstanceOf(TypeError); await expect(getCommitsFiltered(cwd, cwd)).rejects.toMatchObject({ message: expect.stringMatching("dir: Must not be equal to cwd"), }); await expect(getCommitsFiltered(cwd, ".")).rejects.toBeInstanceOf(TypeError); await expect(getCommitsFiltered(cwd, ".")).rejects.toMatchObject({ message: expect.stringMatching("dir: Must not be equal to cwd"), }); }); test("TypeError if dir is not inside cwd", async () => { const cwd = temporaryDirectory(); const dir = temporaryDirectory(); await expect(getCommitsFiltered(cwd, dir)).rejects.toBeInstanceOf(TypeError); await expect(getCommitsFiltered(cwd, dir)).rejects.toMatchObject({ message: expect.stringMatching("dir: Must be inside cwd"), }); await expect(getCommitsFiltered(cwd, "..")).rejects.toBeInstanceOf(TypeError); await expect(getCommitsFiltered(cwd, "..")).rejects.toMatchObject({ message: expect.stringMatching("dir: Must be inside cwd"), }); }); test("TypeError if lastHead is not 40char alphanumeric Git SHA hash", async () => { const cwd = temporaryDirectory(); mkdirSync(join(cwd, "dir")); await expect(getCommitsFiltered(cwd, "dir", false)).rejects.toBeInstanceOf(TypeError); await expect(getCommitsFiltered(cwd, "dir", false)).rejects.toMatchObject({ message: expect.stringMatching("lastHead: Must be alphanumeric string with size 40 or empty"), }); await expect(getCommitsFiltered(cwd, "dir", 123)).rejects.toBeInstanceOf(TypeError); await expect(getCommitsFiltered(cwd, "dir", 123)).rejects.toMatchObject({ message: expect.stringMatching("lastHead: Must be alphanumeric string with size 40 or empty"), }); await expect(getCommitsFiltered(cwd, "dir", "nottherightlength")).rejects.toBeInstanceOf(TypeError); await expect(getCommitsFiltered(cwd, "dir", "nottherightlength")).rejects.toMatchObject({ message: expect.stringMatching("lastHead: Must be alphanumeric string with size 40 or empty"), }); }); });
import getConfig from "../../lib/getConfigMultiSemrel.js"; import { gitInit } from "../helpers/git.js"; import { copyDirectory } from "../helpers/file.js"; // Tests. describe("getConfig()", () => { test("Default options", async () => { const result = await getConfig(process.cwd(), {}); expect(result).toMatchObject({ sequentialInit: false, sequentialPrepare: true, firstParent: false, debug: false, ignorePrivate: true, ignorePackages: [], tagFormat: "${name}@${version}", dryRun: undefined, deps: { bump: "override", release: "patch", prefix: "", }, }); }); test("Only CLI flags and default options", async () => { const cliFlags = { debug: true, dryRun: false, ignorePackages: ["!packages/d/**"], deps: { bump: "inherit", }, }; const result = await getConfig(process.cwd(), cliFlags); expect(result).toMatchObject({ sequentialInit: false, sequentialPrepare: true, firstParent: false, debug: true, ignorePrivate: true, ignorePackages: ["!packages/d/**"], tagFormat: "${name}@${version}", dryRun: false, deps: { bump: "inherit", release: "patch", prefix: "", }, }); }); test("package.json config", async () => { const cwd = await gitInit(); copyDirectory(`test/fixtures/yarnWorkspacesConfig/`, cwd); const result = await getConfig(cwd, {}); expect(result).toMatchObject({ sequentialInit: false, sequentialPrepare: true, firstParent: false, debug: true, ignorePrivate: true, ignorePackages: ["!packages/d/**"], tagFormat: "${name}@${version}", dryRun: undefined, deps: { bump: "inherit", release: "patch", prefix: "", }, }); }); test("package.json config and CLI flags", async () => { const cwd = await gitInit(); const cliFlags = { debug: false, ignorePackages: ["!packages/c/**"], deps: { release: "minor", }, }; copyDirectory(`test/fixtures/yarnWorkspacesConfig/`, cwd); const result = await getConfig(cwd, cliFlags); expect(result).toMatchObject({ sequentialInit: false, sequentialPrepare: true, firstParent: false, debug: false, ignorePrivate: true, ignorePackages: ["!packages/d/**", "!packages/c/**"], tagFormat: "${name}@${version}", dryRun: undefined, deps: { bump: "inherit", release: "minor", prefix: "", }, }); }); test("package.json extends", async () => { const cwd = await gitInit(); copyDirectory(`test/fixtures/yarnWorkspacesConfigExtends/`, cwd); const result = await getConfig(cwd, {}); expect(result).toMatchObject({ sequentialInit: false, sequentialPrepare: true, firstParent: false, debug: true, ignorePrivate: true, ignorePackages: ["!packages/d/**"], tagFormat: "${name}@${version}", dryRun: undefined, deps: { bump: "satisfy", release: "patch", prefix: "", }, }); }); test("package.json extends and CLI flags", async () => { const cwd = await gitInit(); const cliFlags = { debug: false, ignorePackages: ["!packages/c/**"], deps: { release: "minor", }, }; copyDirectory(`test/fixtures/yarnWorkspacesConfigExtends/`, cwd); const result = await getConfig(cwd, cliFlags); expect(result).toMatchObject({ sequentialInit: false, sequentialPrepare: true, firstParent: false, debug: false, ignorePrivate: true, ignorePackages: ["!packages/d/**", "!packages/c/**"], tagFormat: "${name}@${version}", dryRun: undefined, deps: { bump: "satisfy", release: "minor", prefix: "", }, }); }); });
import recognizeFormat from "../../lib/recognizeFormat.js"; // Tests. describe("recognizeFormat()", () => { describe("Indentation", () => { test("Normal indentation", () => expect( recognizeFormat(`{ "a": "b", "c": { "d": "e" } }`).indent ).toBe("\t")); test("No indentation", () => expect(recognizeFormat('{"a": "b"}').indent).toBe("")); }); describe("Trailing whitespace", () => { test("No trailing whitespace", () => expect(recognizeFormat('{"a": "b"}').trailingWhitespace).toBe("")); test("Newline", () => expect(recognizeFormat('{"a": "b"}\n').trailingWhitespace).toBe("\n")); test("Multiple newlines", () => expect(recognizeFormat('{"a": "b"}\n\n').trailingWhitespace).toBe("\n")); }); });
/** * Lifted and tweaked from semantic-release because we follow how they test their internals. * https://github.com/semantic-release/semantic-release/blob/master/test/helpers/git-utils.js */ import { check } from "blork"; import { temporaryDirectory } from "tempy"; import { execaSync } from "execa"; import fileUrl from "file-url"; import gitLogParser from "git-log-parser"; import { array as getStreamArray } from "get-stream"; /** * @typedef {Object} Commit * @property {string} branch The commit branch. * @property {string} hash The commit hash. * @property {string} message The commit message. */ // Init. /** * Create a Git repository. * _Created in a temp folder._ * * @param {string} branch="master" The branch to initialize the repository to. * @return {Promise<string>} Promise that resolves to string pointing to the CWD for the created Git repository. */ function gitInit(branch = "master") { // Check params. check(branch, "branch: kebab"); // Init Git in a temp directory. const cwd = temporaryDirectory(); execaSync("git", ["init"], { cwd }); execaSync("git", ["checkout", "-b", branch], { cwd }); // Disable GPG signing for commits. gitConfig(cwd, "commit.gpgsign", false); gitUser(cwd); // Return directory. return cwd; } /** * Create a remote Git repository. * _Created in a temp folder._ * * @return {Promise<string>} Promise that resolves to string URL of the of the remote origin. */ function gitInitRemote() { // Init bare Git repository in a temp directory. const cwd = temporaryDirectory(); execaSync("git", ["init", "--bare"], { cwd }); // Turn remote path into a file URL. const url = fileUrl(cwd); // Return URL for remote. return url; } /** * Create a remote Git repository and set it as the origin for a Git repository. * _Created in a temp folder._ * * @param {string} cwd The cwd to create and set the origin for. * @param {string} releaseBranch="null" Optional branch to be added in case of prerelease is activated for a branch. * @return {Promise<string>} Promise that resolves to string URL of the of the remote origin. */ function gitInitOrigin(cwd, releaseBranch = null) { // Check params. check(cwd, "cwd: absolute"); // Turn remote path into a file URL. const url = gitInitRemote(); // Set origin on local repo. execaSync("git", ["remote", "add", "origin", url], { cwd }); // Set up a release branch. Return to master afterwards. if (releaseBranch) { execaSync("git", ["checkout", "-b", releaseBranch], { cwd }); execaSync("git", ["checkout", "master"], { cwd }); } execaSync("git", ["push", "--all", "origin"], { cwd }); // Return URL for remote. return url; } // Add. /** * Add files to staged commit in a Git repository. * * @param {string} cwd The cwd to create and set the origin for. * @param {string} file="." The file to add, defaulting to "." (all files). * @return {Promise<void>} Promise that resolves when done. */ function gitAdd(cwd, file = ".") { // Check params. check(cwd, "cwd: absolute"); // Await command. execaSync("git", ["add", file], { cwd }); } // Commits. /** * Create commit on a Git repository. * _Allows empty commits without any files added._ * * @param {string} cwd The CWD of the Git repository. * @param {string} message Commit message. * @returns {Promise<string>} Promise that resolves to the SHA for the commit. */ function gitCommit(cwd, message) { // Check params. check(cwd, "cwd: absolute"); check(message, "message: string+"); // Await the command. execaSync("git", ["commit", "-m", message, "--no-gpg-sign"], { cwd }); // Return HEAD SHA. return gitGetHead(cwd); } /** * `git add .` followed by `git commit` * _Allows empty commits without any files added._ * * @param {string} cwd The CWD of the Git repository. * @param {string} message Commit message. * @returns {Promise<string>} Promise that resolves to the SHA for the commit. */ function gitCommitAll(cwd, message) { // Check params. check(cwd, "cwd: absolute"); check(message, "message: string+"); // Await command. gitAdd(cwd); // Await command and return the SHA hash. return gitCommit(cwd, message); } // Push. /** * Push to a remote Git repository. * * @param {string} cwd The CWD of the Git repository. * @param {string} remote The remote repository URL or name. * @param {string} branch The branch to push. * @returns {Promise<void>} Promise that resolves when done. * @throws {Error} if the push failed. */ function gitPush(cwd, remote = "origin", branch = "master") { // Check params. check(cwd, "cwd: absolute"); check(remote, "remote: string"); check(branch, "branch: lower"); // Await command. execaSync("git", ["push", "--tags", remote, `HEAD:${branch}`], { cwd }); } /** * Sets git user data. * * @param {string} cwd The CWD of the Git repository. * @param {string} name Committer name. * @param {string} email Committer email. * @returns {void} Return void. */ function gitUser(cwd, name = "Foo Bar", email = "email@foo.bar") { execaSync("git", ["config", "--local", "user.email", email], { cwd }); execaSync("git", ["config", "--local", "user.name", name], { cwd }); } // Branches. /** * Create a branch in a local Git repository. * * @param {string} cwd The CWD of the Git repository. * @param {string} branch Branch name to create. * @returns {Promise<void>} Promise that resolves when done. */ function gitBranch(cwd, branch) { // Check params. check(cwd, "cwd: absolute"); check(branch, "branch: lower"); // Await command. execaSync("git", ["branch", branch], { cwd }); } /** * Checkout a branch in a local Git repository. * * @param {string} cwd The CWD of the Git repository. * @param {string} branch Branch name to checkout. * @returns {Promise<void>} Promise that resolves when done. */ function gitCheckout(cwd, branch) { // Check params. check(cwd, "cwd: absolute"); check(branch, "branch: lower"); // Await command. execaSync("git", ["checkout", branch], { cwd }); } // Hashes. /** * Get the current HEAD SHA in a local Git repository. * * @param {string} cwd The CWD of the Git repository. * @return {Promise<string>} Promise that resolves to the SHA of the head commit. */ function gitGetHead(cwd) { // Check params. check(cwd, "cwd: absolute"); // Await command and return HEAD SHA. return execaSync("git", ["rev-parse", "HEAD"], { cwd }).stdout; } // Tags. /** * Create a tag on the HEAD commit in a local Git repository. * * @param {string} cwd The CWD of the Git repository. * @param {string} tagName The tag name to create. * @param {string} hash=false SHA for the commit on which to create the tag. If falsy the tag is created on the latest commit. * @returns {Promise<void>} Promise that resolves when done. */ function gitTag(cwd, tagName, hash = undefined) { // Check params. check(cwd, "cwd: absolute"); check(tagName, "tagName: string+"); check(hash, "hash: alphanumeric{40}?"); // Run command. execaSync("git", hash ? ["tag", "-f", tagName, hash] : ["tag", tagName], { cwd }); } /** * Get the tag associated with a commit SHA. * * @param {string} cwd The CWD of the Git repository. * @param {string} hash The commit SHA for which to retrieve the associated tag. * @return {Promise<string>} The tag associated with the SHA in parameter or `null`. */ function gitGetTags(cwd, hash) { // Check params. check(cwd, "cwd: absolute"); check(hash, "hash: alphanumeric{40}"); // Run command. return execaSync("git", ["describe", "--tags", "--exact-match", hash], { cwd }).stdout; } /** * Get the first commit SHA tagged `tagName` in a local Git repository. * * @param {string} cwd The CWD of the Git repository. * @param {string} tagName Tag name for which to retrieve the commit sha. * @return {Promise<string>} Promise that resolves to the SHA of the first commit associated with `tagName`. */ function gitGetTagHash(cwd, tagName) { // Check params. check(cwd, "cwd: absolute"); check(tagName, "tagName: string+"); // Run command. return execaSync("git", ["rev-list", "-1", tagName], { cwd }).stdout; } // Configs. /** * Add a Git config setting. * * @param {string} cwd The CWD of the Git repository. * @param {string} name Config name. * @param {any} value Config value. * @returns {Promise<void>} Promise that resolves when done. */ function gitConfig(cwd, name, value) { // Check params. check(cwd, "cwd: absolute"); check(name, "name: string+"); // Run command. execaSync("git", ["config", "--add", name, value], { cwd }); } /** * Get a Git config setting. * * @param {string} cwd The CWD of the Git repository. * @param {string} name Config name. * @returns {Promise<void>} Promise that resolves when done. */ function gitGetConfig(cwd, name) { // Check params. check(cwd, "cwd: absolute"); check(name, "name: string+"); // Run command. execaSync("git", ["config", name], { cwd }).stdout; } /** * Get the commit message log of given commit SHA or branch name. * * @param {string} cwd The CWD of the Git repository. * @param {integer} number Limit the number of commits to output. * @param {string} hash The commit SHA or branch name. * @return {Promise<string>} Promise that resolve to commit log message. */ function gitGetLog(cwd, number, hash) { check(cwd, "cwd: absolute"); check(number, "number: integer"); check(hash, "hash: string+"); // Run command. return execaSync("git", ["log", `-${number}`, hash], { cwd }).stdout; } // Exports. export { gitInit, gitInitRemote, gitInitOrigin, gitAdd, gitCommit, gitCommitAll, gitPush, gitCheckout, gitGetHead, gitGetTags, gitTag, gitGetTagHash, gitConfig, gitGetConfig, gitGetLog, };
import { basename, join, resolve } from "path"; import { copyFileSync, existsSync, mkdirSync, lstatSync, readdirSync, readFileSync, writeFileSync } from "fs"; // Deep copy a directory. function copyDirectory(source, target) { // Checks. if (!isDirectory(source)) throw new Error("copyDirectory(): source must be an existant directory"); if (!isDirectory(target)) { // Try making it now (Tempy doesn't actually make the dir, just generates the path). mkdirSync(target); // If it doesn't exist after that there's an issue. if (!isDirectory(target)) throw new Error("copyDirectory(): target must be an existant directory"); } // Copy every file and dir in the dir. readdirSync(source).forEach((name) => { // Get full paths. const sourceFile = join(source, name); const targetFile = join(target, name); // Directory or file? if (isDirectory(sourceFile)) { // Possibly make directory. if (!existsSync(targetFile)) mkdirSync(targetFile); // Recursive copy directory. copyDirectory(sourceFile, targetFile); } else { // Copy file. copyFileSync(sourceFile, targetFile); } }); } // Is given path a directory? function isDirectory(path) { // String path that exists and is a directory. return typeof path === "string" && existsSync(path) && lstatSync(path).isDirectory(); } // Creates testing files on all specified folders. function createNewTestingFiles(folders, cwd) { folders.forEach((fld) => { writeFileSync(`${cwd}/${fld}test.txt`, fld); }); } function addPrereleaseToPackageRootConfig(rootDir, releaseBranch) { const packageUri = resolve(join(rootDir, "package.json")); const packageJson = JSON.parse(readFileSync(packageUri).toString()); packageJson.release.branches = ["master", { name: releaseBranch, prerelease: true }]; } // Exports. export { copyDirectory, isDirectory, createNewTestingFiles, addPrereleaseToPackageRootConfig };
import { execa } from "execa"; import { dirname, resolve } from "node:path"; import { fileURLToPath } from "node:url"; import { copyDirectory } from "../helpers/file.js"; import { gitInit, gitAdd, gitCommit, gitCommitAll, gitInitOrigin, gitPush, gitTag, gitGetTags, } from "../helpers/git.js"; const __dirname = dirname(fileURLToPath(import.meta.url)); const msrBin = resolve(__dirname, "../../bin/cli.js"); const env = { PATH: process.env.PATH, }; // Tests. describe("multi-semantic-release CLI", () => { test("Initial commit (changes in all packages)", async () => { // Create Git repo with copy of Yarn workspaces fixture. const cwd = gitInit(); copyDirectory(`test/fixtures/yarnWorkspaces/`, cwd); const sha = gitCommitAll(cwd, "feat: Initial release"); const url = gitInitOrigin(cwd); gitPush(cwd); // Run via command line. // const out = (await execa("node", [filepath, "-- --no-sequential-prepare"], { cwd })).stdout; // expect(out).toMatch("Started multirelease! Loading 4 packages..."); // expect(out).toMatch("Released 4 of 4 packages, semantically!"); try { await execa("node", [msrBin, "-- --no-sequential-prepare"], { cwd, extendEnv: false, env }); } catch (res) { const { stdout, stderr, exitCode } = res; expect(stdout).toMatch("Started multirelease! Loading 4 packages..."); expect(stderr).toMatch('Error: Cyclic dependency, node was:"msr-test-c"'); expect(exitCode).toBe(1); } }); test("Initial commit (changes in 2 packages, 2 filtered out)", async () => { // Create Git repo with copy of Yarn workspaces fixture. const cwd = gitInit(); copyDirectory(`test/fixtures/yarnWorkspaces/`, cwd); const sha = gitCommitAll(cwd, "feat: Initial release"); const url = gitInitOrigin(cwd); gitPush(cwd); // Run via command line. const out = ( await execa("node", [msrBin, "-- --ignore-packages=packages/c/**,packages/d/**"], { cwd, extendEnv: false, env, }) ).stdout; expect(out).toMatch("Started multirelease! Loading 2 packages..."); expect(out).toMatch("Released 2 of 2 packages, semantically!"); }); });
from migen import * from migen.build.generic_platform import * from migen.build.platforms.versaecp55g import Platform from migen.genlib.io import CRG from migen.genlib.cdc import MultiReg from microscope import * from ..gateware.platform.lattice_ecp5 import * from ..gateware.serdes import * from ..gateware.phy import * from ..vendor.pads import * from ..vendor.uart import * class LTSSMTestbench(Module): def __init__(self, **kwargs): self.platform = Platform(**kwargs) self.platform.add_extension([ ("tp0", 0, Pins("X3:5"), IOStandard("LVCMOS33")), ]) self.clock_domains.cd_serdes = ClockDomain() self.submodules.serdes = serdes = \ LatticeECP5PCIeSERDES(self.platform.request("pcie_x1")) self.comb += [ self.cd_serdes.clk.eq(serdes.rx_clk_o), serdes.rx_clk_i.eq(self.cd_serdes.clk), serdes.tx_clk_i.eq(self.cd_serdes.clk), ] with open("top.sdc", "w") as f: f.write("define_clock -name {n:serdes_ref_clk} -freq 100.000\n") f.write("define_clock -name {n:serdes_rx_clk_o} -freq 150.000\n") self.platform.add_source("top.sdc") # self.platform.add_platform_command("""FREQUENCY NET "serdes_ref_clk" 100 MHz;""") # self.platform.add_platform_command("""FREQUENCY NET "serdes_rx_clk_o" 125 MHz;""") self.submodules.aligner = aligner = \ ClockDomainsRenamer("rx")(PCIeSERDESAligner(serdes.lane)) self.submodules.phy = phy = \ ClockDomainsRenamer("rx")(PCIePHY(aligner, ms_cyc=125000)) led_att1 = self.platform.request("user_led") led_att2 = self.platform.request("user_led") led_sta1 = self.platform.request("user_led") led_sta2 = self.platform.request("user_led") led_err1 = self.platform.request("user_led") led_err2 = self.platform.request("user_led") led_err3 = self.platform.request("user_led") led_err4 = self.platform.request("user_led") self.comb += [ led_att1.eq(~(phy.rx.ts.link.valid)), led_att2.eq(~(phy.rx.ts.lane.valid)), led_sta1.eq(~(phy.rx.ts.valid)), led_sta2.eq(~(0)), led_err1.eq(~(~serdes.lane.rx_present)), led_err2.eq(~(~serdes.lane.rx_locked)), led_err3.eq(~(~serdes.lane.rx_aligned)), led_err4.eq(~(phy.rx.error)), ] tp0 = self.platform.request("tp0") self.comb += tp0.eq(phy.rx.ts.link.valid) uart_pads = Pads(self.platform.request("serial")) self.submodules += uart_pads self.submodules.uart = uart = ClockDomainsRenamer("rx")( UART(uart_pads, bit_cyc=uart_bit_cyc(125e6, 115200)[0]) ) self.comb += [ uart.rx_ack.eq(uart.rx_rdy), ] index = Signal(max=phy.ltssm_log.depth) offset = Signal(8) size = Signal(16) entry = Signal(phy.ltssm_log.width) self.comb += [ size.eq(phy.ltssm_log.width * phy.ltssm_log.depth // 8), entry.eq(Cat(phy.ltssm_log.data_o, phy.ltssm_log.time_o)), ] self.submodules.uart_fsm = ClockDomainsRenamer("rx")(FSM()) self.uart_fsm.act("WAIT", NextValue(uart.tx_ack, 0), If(uart.rx_rdy, NextValue(phy.ltssm_log.trigger, 1), NextValue(offset, 1), NextState("WIDTH") ) ) self.uart_fsm.act("WIDTH", NextValue(uart.tx_ack, 0), If(uart.tx_rdy & ~uart.tx_ack, NextValue(uart.tx_data, size.part(offset << 3, 8)), NextValue(uart.tx_ack, 1), If(offset == 0, NextValue(offset, phy.ltssm_log.width // 8 - 1), NextValue(index, phy.ltssm_log.depth - 1), NextState("DATA") ).Else( NextValue(offset, offset - 1) ) ) ) self.uart_fsm.act("DATA", NextValue(uart.tx_ack, 0), If(uart.tx_rdy & ~uart.tx_ack, NextValue(uart.tx_data, entry.part(offset << 3, 8)), NextValue(uart.tx_ack, 1), If(offset == 0, phy.ltssm_log.next.eq(1), NextValue(offset, phy.ltssm_log.width // 8 - 1), If(index == 0, NextValue(phy.ltssm_log.trigger, 0), NextState("WAIT") ).Else( NextValue(index, index - 1) ) ).Else( NextValue(offset, offset - 1) ) ) ) # ------------------------------------------------------------------------------------------------- import sys import serial import struct import subprocess if __name__ == "__main__": for arg in sys.argv[1:]: if arg == "build": toolchain = "diamond" if toolchain == "trellis": toolchain_path = "/usr/local/share/trellis" elif toolchain == "diamond": toolchain_path = "/usr/local/diamond/3.10_x64/bin/lin64" design = LTSSMTestbench(toolchain=toolchain) design.platform.build(design, toolchain_path=toolchain_path) if arg == "load": subprocess.call(["/home/whitequark/Projects/prjtrellis/tools/bit_to_svf.py", "build/top.bit", "build/top.svf"]) subprocess.call(["openocd", "-f", "/home/whitequark/Projects/" "prjtrellis/misc/openocd/ecp5-versa5g.cfg", "-c", "init; svf -quiet build/top.svf; exit"]) if arg == "sample": design = LTSSMTestbench() design.finalize() port = serial.Serial(port='/dev/ttyUSB1', baudrate=115200) port.write(b"\x00") length, = struct.unpack(">H", port.read(2)) data = port.read(length) offset = 0 start = None while offset < len(data): time, state = struct.unpack_from(">LB", data, offset) offset += struct.calcsize(">LB") if start is not None: delta = time - start else: delta = 0 print("%+10d cyc (%+10d us): %s" % (delta, delta / 125, design.phy.ltssm.decoding[state])) start = time
from migen import * from migen.build.generic_platform import * from migen.build.platforms.versaecp55g import Platform from migen.genlib.cdc import MultiReg from migen.genlib.fifo import AsyncFIFO from migen.genlib.fsm import FSM from ..gateware.serdes import * from ..gateware.phy import K, PCIePHYTX from ..gateware.align import * from ..gateware.platform.lattice_ecp5 import * from ..vendor.pads import * from ..vendor.uart import * class SERDESTestbench(Module): def __init__(self, capture_depth, **kwargs): self.platform = Platform(**kwargs) self.platform.add_extension([ ("tp0", 0, Pins("X3:5"), IOStandard("LVCMOS33")), ]) self.clock_domains.cd_ref = ClockDomain() self.clock_domains.cd_rx = ClockDomain() self.clock_domains.cd_tx = ClockDomain() self.submodules.serdes = serdes = \ LatticeECP5PCIeSERDES(self.platform.request("pcie_x1")) self.submodules.aligner = aligner = \ ClockDomainsRenamer("rx")(PCIeSERDESAligner(serdes.lane)) self.comb += [ self.cd_ref.clk.eq(serdes.ref_clk), serdes.rx_clk_i.eq(serdes.rx_clk_o), self.cd_rx.clk.eq(serdes.rx_clk_i), serdes.tx_clk_i.eq(serdes.tx_clk_o), self.cd_tx.clk.eq(serdes.tx_clk_i), ] self.submodules.tx_phy = ClockDomainsRenamer("tx")(PCIePHYTX(aligner)) self.comb += [ self.aligner.rx_align.eq(1), self.tx_phy.ts.n_fts.eq(0xff), self.tx_phy.ts.rate.gen1.eq(1), ] with open("top.sdc", "w") as f: f.write("define_clock -name {n:serdes_ref_clk} -freq 100.000\n") f.write("define_clock -name {n:serdes_tx_clk_o} -freq 150.000\n") f.write("define_clock -name {n:serdes_rx_clk_o} -freq 150.000\n") self.platform.add_source("top.sdc") self.platform.add_platform_command("""FREQUENCY NET "serdes_ref_clk" 100 MHz;""") self.platform.add_platform_command("""FREQUENCY NET "serdes_rx_clk_o" 125 MHz;""") self.platform.add_platform_command("""FREQUENCY NET "serdes_tx_clk_o" 125 MHz;""") refclkcounter = Signal(32) self.sync.ref += refclkcounter.eq(refclkcounter + 1) rxclkcounter = Signal(32) self.sync.rx += rxclkcounter.eq(rxclkcounter + 1) txclkcounter = Signal(32) self.sync.tx += txclkcounter.eq(txclkcounter + 1) led_att1 = self.platform.request("user_led") led_att2 = self.platform.request("user_led") led_sta1 = self.platform.request("user_led") led_sta2 = self.platform.request("user_led") led_err1 = self.platform.request("user_led") led_err2 = self.platform.request("user_led") led_err3 = self.platform.request("user_led") led_err4 = self.platform.request("user_led") self.comb += [ led_att1.eq(~(refclkcounter[25])), led_att2.eq(~(0)), led_sta1.eq(~(rxclkcounter[25])), led_sta2.eq(~(txclkcounter[25])), led_err1.eq(~(~serdes.lane.rx_present)), led_err2.eq(~(~serdes.lane.rx_locked)), led_err3.eq(~(~serdes.lane.rx_aligned)), led_err4.eq(~(0)), ] trigger_rx = Signal() trigger_ref = Signal() self.specials += MultiReg(trigger_ref, trigger_rx, odomain="rx") capture = Signal() self.submodules.symbols = symbols = ClockDomainsRenamer({ "write": "rx", "read": "ref" })( AsyncFIFO(width=18, depth=capture_depth) ) self.comb += [ symbols.din.eq(Cat(aligner.rx_symbol)), symbols.we.eq(capture) ] self.sync.rx += [ If(trigger_rx, capture.eq(1) ).Elif(~symbols.writable, capture.eq(0) ) ] uart_pads = Pads(self.platform.request("serial")) self.submodules += uart_pads self.submodules.uart = uart = ClockDomainsRenamer("ref")( UART(uart_pads, bit_cyc=uart_bit_cyc(100e6, 115200)[0]) ) self.comb += [ uart.rx_ack.eq(uart.rx_rdy), trigger_ref.eq(uart.rx_rdy) ] self.submodules.fsm = ClockDomainsRenamer("ref")(FSM(reset_state="WAIT")) self.fsm.act("WAIT", If(uart.rx_rdy, NextState("SYNC-1") ) ) self.fsm.act("SYNC-1", If(uart.tx_rdy, uart.tx_ack.eq(1), uart.tx_data.eq(0xff), NextState("SYNC-2") ) ) self.fsm.act("SYNC-2", If(uart.tx_rdy, uart.tx_ack.eq(1), uart.tx_data.eq(0xff), NextState("BYTE-0") ) ) self.fsm.act("BYTE-0", If(symbols.readable & uart.tx_rdy, uart.tx_ack.eq(1), uart.tx_data.eq(symbols.dout[16:]), NextState("BYTE-1") ).Elif(~symbols.readable, NextState("WAIT") ) ) self.fsm.act("BYTE-1", If(symbols.readable & uart.tx_rdy, uart.tx_ack.eq(1), uart.tx_data.eq(symbols.dout[8:]), NextState("BYTE-2") ) ) self.fsm.act("BYTE-2", If(symbols.readable & uart.tx_rdy, uart.tx_ack.eq(1), uart.tx_data.eq(symbols.dout[0:]), symbols.re.eq(1), NextState("BYTE-0") ) ) tp0 = self.platform.request("tp0") # self.comb += tp0.eq(serdes.rx_clk_o) # ------------------------------------------------------------------------------------------------- import sys import serial import subprocess CAPTURE_DEPTH = 1024 if __name__ == "__main__": for arg in sys.argv[1:]: if arg == "build": toolchain = "diamond" if toolchain == "trellis": toolchain_path = "/usr/local/share/trellis" elif toolchain == "diamond": toolchain_path = "/usr/local/diamond/3.10_x64/bin/lin64" design = SERDESTestbench(CAPTURE_DEPTH, toolchain=toolchain) design.platform.build(design, toolchain_path=toolchain_path) if arg == "load": subprocess.call(["/home/whitequark/Projects/prjtrellis/tools/bit_to_svf.py", "build/top.bit", "build/top.svf"]) subprocess.call(["openocd", "-f", "/home/whitequark/Projects/" "prjtrellis/misc/openocd/ecp5-versa5g.cfg", "-c", "init; svf -quiet build/top.svf; exit"]) if arg == "sample": port = serial.Serial(port='/dev/ttyUSB1', baudrate=115200) port.write(b"\x00") while True: while True: if port.read(1) == b"\xff": break if port.read(1) == b"\xff": break for x in range(CAPTURE_DEPTH): b2, b1, b0 = port.read(3) dword = (b2 << 16) | (b1 << 8) | b0 for word in (((dword >> 0) & 0x1ff), ((dword >> 9) & 0x1ff)): if word & 0x1ff == 0x1ee: print("KEEEEEEEE", end=" ") else: print("{}{:08b}".format( "K" if word & (1 << 8) else " ", word & 0xff, ), end=" ") if x % 4 == 3: print()
from migen import * __all__ = ['Pads'] class Pads(Module): """ Pad adapter. Provides a common interface to device pads, wrapping either a Migen platform request, or a Glasgow I/O port slice. Construct a pad adapter providing signals, records, or tristate triples; name may be specified explicitly with keyword arguments. For each signal, record field, or triple with name ``n``, the pad adapter will have an attribute ``n_t`` containing a tristate triple. ``None`` may also be provided, and is ignored; no attribute is added to the adapter. For example, if a Migen platform file contains the definitions :: _io = [ ("i2c", 0, Subsignal("scl", Pins("39")), Subsignal("sda", Pins("40")), ), # ... ] then a pad adapter constructed as ``Pads(platform.request("i2c"))`` will have attributes ``scl_t`` and ``sda_t`` containing tristate triples for their respective pins. If a Glasgow applet contains the code :: port = target.get_port(args.port) pads = Pads(tx=port[args.pin_tx], rx=port[args.pin_rx]) target.submodules += pads then the pad adapter ``pads`` will have attributes ``tx_t`` and ``rx_t`` containing tristate triples for their respective pins; since Glasgow I/O ports return tristate triples when slicing, the results of slicing are unchanged. """ def __init__(self, *args, **kwargs): for (i, elem) in enumerate(args): self._add_elem(elem, index=i) for name, elem in kwargs.items(): self._add_elem(elem, name) def _add_elem(self, elem, name=None, index=None): if elem is None: return elif isinstance(elem, Record): for field in elem.layout: if name is None: field_name = field[0] else: field_name = "{}_{}".format(name, field[0]) self._add_elem(getattr(elem, field[0]), field_name) return elif isinstance(elem, Signal): triple = TSTriple() self.specials += triple.get_tristate(elem) if name is None: name = elem.backtrace[-1][0] elif isinstance(elem, TSTriple): triple = elem if name is None and index is None: raise ValueError("Name must be provided for {!r}".format(elem)) elif name is None: raise ValueError("Name must be provided for {!r} (argument {})" .format(elem, index + 1)) triple_name = "{}_t".format(name) if hasattr(self, triple_name): raise ValueError("Cannot add {!r} as attribute {}; attribute already exists") setattr(self, triple_name, triple)
from migen import * from migen.genlib.fsm import * from migen.genlib.cdc import MultiReg __all__ = ['UART', 'uart_bit_cyc'] class UARTBus(Module): """ UART bus. Provides synchronization. """ def __init__(self, pads): self.has_rx = hasattr(pads, "rx_t") if self.has_rx: self.rx_t = pads.rx_t self.rx_i = Signal() self.has_tx = hasattr(pads, "tx_t") if self.has_tx: self.tx_t = pads.tx_t self.tx_o = Signal(reset=1) ### if self.has_tx: self.comb += [ self.tx_t.oe.eq(1), self.tx_t.o.eq(self.tx_o) ] if self.has_rx: self.specials += [ MultiReg(self.rx_t.i, self.rx_i, reset=1) ] def uart_bit_cyc(clk_freq, baud_rate, max_deviation=50000): """ Calculate bit time from clock frequency and baud rate. :param clk_freq: Input clock frequency, in Hz. :type clk_freq: int or float :param baud_rate: Baud rate, in bits per second. :type baud_rate: int or float :param max_deviation: Maximum deviation of actual baud rate from ``baud_rate``, in parts per million. :type max_deviation: int or float :returns: (int, int or float) -- bit time as a multiple of clock period, and actual baud rate as calculated based on bit time. :raises: ValueError -- if the baud rate is too high for the specified clock frequency, or if actual baud rate deviates from requested baud rate by more than a specified amount. """ bit_cyc = round(clk_freq // baud_rate) if bit_cyc <= 0: raise ValueError("baud rate {} is too high for input clock frequency {}" .format(baud_rate, clk_freq)) actual_baud_rate = round(clk_freq // bit_cyc) deviation = round(1000000 * (actual_baud_rate - baud_rate) // baud_rate) if deviation > max_deviation: raise ValueError("baud rate {} deviation from {} ({} ppm) is higher than {} ppm" .format(actual_baud_rate, baud_rate, deviation, max_deviation)) return bit_cyc + 1, actual_baud_rate class UART(Module): """ Asynchronous serial receiver-transmitter. Any number of data bits, any parity, and 1 stop bit are supported. :param bit_cyc: Bit time expressed as a multiple of system clock periods. Use :func:`uart_bit_cyc` to calculate bit time from system clock frequency and baud rate. :type bit_cyc: int :param data_bits: Data bit count. :type data_bits: int :param parity: Parity, one of ``"none"`` (default), ``"zero"``, ``"one"``, ``"even"``, ``"odd"``. :type parity: str :attr rx_data: Received data. Valid when ``rx_rdy`` is active. :attr rx_rdy: Receive ready flag. Becomes active after a stop bit of a valid frame is received. :attr rx_ack: Receive acknowledgement. If active when ``rx_rdy`` is active, ``rx_rdy`` is reset, and the receive state machine becomes ready for another frame. :attr rx_ferr: Receive frame error flag. Active for one cycle when a frame error is detected. :attr rx_ovf: Receive overflow flag. Active for one cycle when a new frame is started while ``rx_rdy`` is still active. Afterwards, the receive state machine is reset and starts receiving the new frame. :attr rx_err: Receive error flag. Logical OR of all other error flags. :attr tx_data: Data to transmit. Sampled when ``tx_rdy`` is active. :attr tx_rdy: Transmit ready flag. Active while the transmit state machine is idle, and can accept data to transmit. :attr tx_ack: Transmit acknowledgement. If active when ``tx_rdy`` is active, ``tx_rdy`` is reset, ``tx_data`` is sampled, and the transmit state machine starts transmitting a frame. """ def __init__(self, pads, bit_cyc, data_bits=8, parity="none"): self.rx_data = Signal(data_bits) self.rx_rdy = Signal() self.rx_ack = Signal() self.rx_ferr = Signal() self.rx_ovf = Signal() self.rx_perr = Signal() self.rx_err = Signal() self.tx_data = Signal(data_bits) self.tx_rdy = Signal() self.tx_ack = Signal() self.submodules.bus = bus = UARTBus(pads) ### bit_cyc = int(bit_cyc) def calc_parity(sig, kind): if kind in ("zero", "none"): return C(0, 1) elif kind == "one": return C(1, 1) else: bits, _ = value_bits_sign(sig) even_parity = sum([sig[b] for b in range(bits)]) & 1 if kind == "odd": return ~even_parity elif kind == "even": return even_parity else: assert False if bus.has_rx: rx_timer = Signal(max=bit_cyc) rx_stb = Signal() rx_shreg = Signal(data_bits) rx_bitno = Signal(max=rx_shreg.nbits) self.comb += self.rx_err.eq(self.rx_ferr | self.rx_ovf | self.rx_perr) self.sync += [ If(rx_timer == 0, rx_timer.eq(bit_cyc - 1) ).Else( rx_timer.eq(rx_timer - 1) ) ] self.comb += rx_stb.eq(rx_timer == 0) self.submodules.rx_fsm = FSM(reset_state="IDLE") self.rx_fsm.act("IDLE", NextValue(self.rx_rdy, 0), If(~bus.rx_i, NextValue(rx_timer, bit_cyc // 2), NextState("START") ) ) self.rx_fsm.act("START", If(rx_stb, NextState("DATA") ) ) self.rx_fsm.act("DATA", If(rx_stb, NextValue(rx_shreg, Cat(rx_shreg[1:8], bus.rx_i)), NextValue(rx_bitno, rx_bitno + 1), If(rx_bitno == rx_shreg.nbits - 1, If(parity == "none", NextState("STOP") ).Else( NextState("PARITY") ) ) ) ) self.rx_fsm.act("PARITY", If(rx_stb, If(bus.rx_i == calc_parity(rx_shreg, parity), NextState("STOP") ).Else( self.rx_perr.eq(1), NextState("IDLE") ) ) ) self.rx_fsm.act("STOP", If(rx_stb, If(~bus.rx_i, self.rx_ferr.eq(1), NextState("IDLE") ).Else( NextValue(self.rx_data, rx_shreg), NextState("READY") ) ) ) self.rx_fsm.act("READY", NextValue(self.rx_rdy, 1), If(self.rx_ack, NextState("IDLE") ).Elif(~bus.rx_i, self.rx_ovf.eq(1), NextState("IDLE") ) ) ### if bus.has_tx: tx_timer = Signal(max=bit_cyc) tx_stb = Signal() tx_shreg = Signal(data_bits) tx_bitno = Signal(max=tx_shreg.nbits) tx_parity = Signal() self.sync += [ If(tx_timer == 0, tx_timer.eq(bit_cyc - 1) ).Else( tx_timer.eq(tx_timer - 1) ) ] self.comb += tx_stb.eq(tx_timer == 0) self.submodules.tx_fsm = FSM(reset_state="IDLE") self.tx_fsm.act("IDLE", self.tx_rdy.eq(1), If(self.tx_ack, NextValue(tx_shreg, self.tx_data), If(parity != "none", NextValue(tx_parity, calc_parity(self.tx_data, parity)) ), NextValue(tx_timer, bit_cyc - 1), NextValue(bus.tx_o, 0), NextState("START") ).Else( NextValue(bus.tx_o, 1) ) ) self.tx_fsm.act("START", If(tx_stb, NextValue(bus.tx_o, tx_shreg[0]), NextValue(tx_shreg, Cat(tx_shreg[1:8], 0)), NextState("DATA") ) ) self.tx_fsm.act("DATA", If(tx_stb, NextValue(tx_bitno, tx_bitno + 1), If(tx_bitno != tx_shreg.nbits - 1, NextValue(bus.tx_o, tx_shreg[0]), NextValue(tx_shreg, Cat(tx_shreg[1:8], 0)), ).Else( If(parity == "none", NextValue(bus.tx_o, 1), NextState("STOP") ).Else( NextValue(bus.tx_o, tx_parity), NextState("PARITY") ) ) ) ) self.tx_fsm.act("PARITY", If(tx_stb, NextValue(bus.tx_o, 1), NextState("STOP") ) ) self.tx_fsm.act("STOP", If(tx_stb, NextState("IDLE") ) )
import unittest from migen import * from ..gateware.serdes import * from ..gateware.serdes import K, D from ..gateware.phy_rx import * from . import simulation_test class PCIePHYRXTestbench(Module): def __init__(self, ratio=1): self.submodules.lane = PCIeSERDESInterface(ratio) self.submodules.phy = PCIePHYRX(self.lane) def do_finalize(self): self.states = {v: k for k, v in self.phy.parser.fsm.encoding.items()} def phy_state(self): return self.states[(yield self.phy.parser.fsm.state)] def transmit(self, symbols): for i, word in enumerate(symbols): if i > 0: assert (yield self.phy.error) == 0 if isinstance(word, tuple): for j, symbol in enumerate(word): yield self.lane.rx_symbol.part(j * 9, 9).eq(symbol) else: yield self.lane.rx_symbol.eq(word) yield class _PCIePHYRXTestCase(unittest.TestCase): def assertState(self, tb, state): self.assertEqual((yield from tb.phy_state()), state) def assertSignal(self, signal, value): self.assertEqual((yield signal), value) class PCIePHYRXGear1xTestCase(_PCIePHYRXTestCase): def setUp(self): self.tb = PCIePHYRXTestbench() def simulationSetUp(self, tb): yield tb.lane.rx_valid.eq(1) @simulation_test def test_rx_tsn_cycle_by_cycle(self, tb): yield tb.lane.rx_symbol.eq(K(28,5)) yield yield from self.assertState(tb, "COMMA") yield tb.lane.rx_symbol.eq(D(1,0)) yield yield from self.assertState(tb, "TSn-LINK/SKP-0") yield tb.lane.rx_symbol.eq(D(2,0)) yield yield from self.assertSignal(tb.phy._tsZ.link.valid, 1) yield from self.assertSignal(tb.phy._tsZ.link.number, 1) yield from self.assertState(tb, "TSn-LANE") yield tb.lane.rx_symbol.eq(0xff) yield yield from self.assertSignal(tb.phy._tsZ.lane.valid, 1) yield from self.assertSignal(tb.phy._tsZ.lane.number, 2) yield from self.assertState(tb, "TSn-FTS") yield tb.lane.rx_symbol.eq(0b0010) yield yield from self.assertSignal(tb.phy._tsZ.n_fts, 0xff) yield from self.assertState(tb, "TSn-RATE") yield tb.lane.rx_symbol.eq(0b1111) yield yield from self.assertSignal(tb.phy._tsZ.rate.gen1, 1) yield from self.assertState(tb, "TSn-CTRL") yield tb.lane.rx_symbol.eq(D(5,2)) yield yield from self.assertSignal(tb.phy._tsZ.ctrl.hot_reset, 1) yield from self.assertSignal(tb.phy._tsZ.ctrl.disable_link, 1) yield from self.assertSignal(tb.phy._tsZ.ctrl.loopback, 1) yield from self.assertSignal(tb.phy._tsZ.ctrl.disable_scrambling, 1) yield from self.assertState(tb, "TSn-ID0") yield tb.lane.rx_symbol.eq(D(5,2)) yield yield from self.assertSignal(tb.phy._tsZ.ts_id, 1) yield from self.assertState(tb, "TSn-ID1") for n in range(2, 10): yield tb.lane.rx_symbol.eq(D(5,2)) yield yield from self.assertState(tb, "TSn-ID%d" % n) yield tb.lane.rx_symbol.eq(K(28,5)) yield yield from self.assertSignal(tb.phy._tsZ.valid, 1) yield from self.assertState(tb, "COMMA") def assertTSnState(self, tsN, valid=1, link_valid=0, link_number=0, lane_valid=0, lane_number=0, n_fts=0, rate_gen1=0, rate_gen2=0, ctrl_hot_reset=0, ctrl_disable_link=0, ctrl_loopback=0, ctrl_disable_scrambling=0, ts_id=0): yield from self.assertSignal(tsN.valid, valid) yield from self.assertSignal(tsN.link.valid, link_valid) yield from self.assertSignal(tsN.lane.valid, lane_valid) yield from self.assertSignal(tsN.n_fts, n_fts) yield from self.assertSignal(tsN.rate.gen1, rate_gen1) yield from self.assertSignal(tsN.rate.gen2, rate_gen2) yield from self.assertSignal(tsN.ctrl.hot_reset, ctrl_hot_reset) yield from self.assertSignal(tsN.ctrl.disable_link, ctrl_disable_link) yield from self.assertSignal(tsN.ctrl.loopback, ctrl_loopback) yield from self.assertSignal(tsN.ctrl.disable_scrambling, ctrl_disable_scrambling) yield from self.assertSignal(tsN.ts_id, ts_id) def assertError(self, tb): yield from self.assertSignal(tb.phy.error, 1) yield yield from self.assertSignal(tb.phy._tsZ.valid, 0) yield from self.assertState(tb, "COMMA") @simulation_test def test_rx_ts1_empty_valid(self, tb): yield from self.tb.transmit([ K(28,5), K(23,7), K(23,7), 0, 0b0000, 0b0000, *[D(10,2) for _ in range(10)], K(28,5), ]) yield from self.assertTSnState(tb.phy._tsZ, ts_id=0) @simulation_test def test_rx_ts2_empty_valid(self, tb): yield from self.tb.transmit([ K(28,5), K(23,7), K(23,7), 0, 0b0000, 0b0000, *[D(5,2) for _ in range(10)], K(28,5), ]) yield from self.assertTSnState(tb.phy._tsZ, ts_id=1) @simulation_test def test_rx_ts1_inverted_valid(self, tb): yield from self.tb.transmit([ K(28,5), K(23,7), K(23,7), D(0,0), D(0,0), D(0,0), *[D(21,5) for _ in range(10)], K(28,5), ]) yield from self.assertSignal(tb.lane.rx_invert, 1) yield from self.assertTSnState(tb.phy._tsZ) @simulation_test def test_rx_ts2_inverted_valid(self, tb): yield from self.tb.transmit([ K(28,5), K(23,7), K(23,7), D(0,0), D(0,0), D(0,0), *[D(26,5) for _ in range(10)], K(28,5), ]) yield from self.assertSignal(tb.lane.rx_invert, 1) yield from self.assertTSnState(tb.phy._tsZ) @simulation_test def test_rx_ts1_link_valid(self, tb): yield from self.tb.transmit([ K(28,5), 0xaa, K(23,7), 0, 0b0000, 0b0000, *[D(10,2) for _ in range(10)], K(28,5), ]) yield from self.assertTSnState(tb.phy._tsZ, link_valid=1, link_number=0xaa) @simulation_test def test_rx_ts1_link_invalid(self, tb): yield from self.tb.transmit([ K(28,5), 0x1ee, ]) yield from self.assertError(tb) @simulation_test def test_rx_ts1_lane_valid(self, tb): yield from self.tb.transmit([ K(28,5), 0xaa, 0x1a, 0, 0b0000, 0b0000, *[D(10,2) for _ in range(10)], K(28,5), ]) yield from self.assertTSnState(tb.phy._tsZ, link_valid=1, link_number=0xaa, lane_valid=1, lane_number=0x1a) @simulation_test def test_rx_ts1_lane_invalid(self, tb): yield from self.tb.transmit([ K(28,5), K(23,7), 0x1ee, ]) yield from self.assertError(tb) @simulation_test def test_rx_ts1_n_fts_valid(self, tb): yield from self.tb.transmit([ K(28,5), 0xaa, 0x1a, 0xff, 0b0000, 0b0000, *[D(10,2) for _ in range(10)], K(28,5), ]) yield from self.assertTSnState(tb.phy._tsZ, link_valid=1, link_number=0xaa, lane_valid=1, lane_number=0x1a, n_fts=255) @simulation_test def test_rx_ts1_n_fts_invalid(self, tb): yield from self.tb.transmit([ K(28,5), K(23,7), K(23,7), 0x1ee ]) yield from self.assertError(tb) @simulation_test def test_rx_ts1_n_rate_valid(self, tb): yield from self.tb.transmit([ K(28,5), 0xaa, 0x1a, 0xff, 0b0010, 0b0000, *[D(10,2) for _ in range(10)], K(28,5), ]) yield from self.assertTSnState(tb.phy._tsZ, link_valid=1, link_number=0xaa, lane_valid=1, lane_number=0x1a, n_fts=255, rate_gen1=1) @simulation_test def test_rx_ts1_n_rate_invalid(self, tb): yield from self.tb.transmit([ K(28,5), K(23,7), K(23,7), 0xff, 0x1ee ]) yield from self.assertError(tb) @simulation_test def test_rx_ts1_ctrl_valid(self, tb): for (ctrl, bit) in ( ("ctrl_hot_reset", 0b0001), ("ctrl_disable_link", 0b0010), ("ctrl_loopback", 0b0100), ("ctrl_disable_scrambling", 0b1000), ): yield from self.tb.transmit([ K(28,5), 0xaa, 0x1a, 0xff, 0b0010, bit, *[D(10,2) for _ in range(10)], ]) yield from self.assertTSnState(tb.phy._tsZ, link_valid=1, link_number=0xaa, lane_valid=1, lane_number=0x1a, n_fts=255, rate_gen1=1, **{ctrl:1}) @simulation_test def test_rx_ts1_ctrl_invalid(self, tb): yield from self.tb.transmit([ K(28,5), K(23,7), K(23,7), 0xff, 0b0010, 0x1ee ]) yield from self.assertError(tb) @simulation_test def test_rx_ts1_idN_invalid(self, tb): for n in range(10): yield self.tb.lane.rx_symbol.eq(0) yield yield from self.tb.transmit([ K(28,5), 0xaa, 0x1a, 0xff, 0b0010, 0b0001, *[D(10,2) for _ in range(n)], 0x1ee ]) yield from self.assertError(tb) @simulation_test def test_rx_ts1_2x_same_valid(self, tb): yield from self.tb.transmit([ K(28,5), 0xaa, 0x1a, 0xff, 0b0010, 0b0000, *[D(10,2) for _ in range(10)], K(28,5), 0xaa, 0x1a, 0xff, 0b0010, 0b0000, *[D(10,2) for _ in range(10)], K(28,5) ]) yield from self.assertSignal(tb.phy.ts.valid, 1) @simulation_test def test_rx_ts1_2x_different_invalid(self, tb): yield from self.tb.transmit([ K(28,5), 0xaa, 0x1a, 0xff, 0b0010, 0b0000, *[D(10,2) for _ in range(10)], K(28,5), 0xaa, 0x1a, 0xff, 0b0010, 0b0001, *[D(10,2) for _ in range(10)], K(28,5) ]) yield from self.assertSignal(tb.phy.ts.valid, 0) @simulation_test def test_rx_ts1_3x_same_different_invalid(self, tb): yield from self.tb.transmit([ K(28,5), 0xaa, 0x1a, 0xff, 0b0010, 0b0000, *[D(10,2) for _ in range(10)], K(28,5), 0xaa, 0x1a, 0xff, 0b0010, 0b0000, *[D(10,2) for _ in range(10)], K(28,5), 0xaa, 0x1a, 0xff, 0b0010, 0b0001, *[D(10,2) for _ in range(10)], K(28,5) ]) yield from self.assertSignal(tb.phy.ts.valid, 0) @simulation_test def test_rx_ts1_3x_same_different_invalid(self, tb): yield from self.tb.transmit([ K(28,5), 0xaa, 0x1a, 0xff, 0b0010, 0b0000, *[D(10,2) for _ in range(10)], K(28,5), 0xaa, 0x1a, 0xff, 0b0010, 0b0000, *[D(10,2) for _ in range(10)], K(28,5), 0xaa, 0x1a, 0xff, 0b0010, 0b0001, *[D(10,2) for _ in range(10)], K(28,5) ]) yield from self.assertSignal(tb.phy.ts.valid, 0) @simulation_test def test_rx_ts1_skp_ts1_valid(self, tb): yield from self.tb.transmit([ K(28,5), 0xaa, 0x1a, 0xff, 0b0010, 0b0000, *[D(10,2) for _ in range(10)], K(28,5), K(28,0), K(28,0), K(28,0), K(28,5), 0xaa, 0x1a, 0xff, 0b0010, 0b0000, *[D(10,2) for _ in range(10)], K(28,5) ]) yield from self.assertSignal(tb.phy.ts.valid, 1) class PCIePHYRXGear2xTestCase(_PCIePHYRXTestCase): def setUp(self): self.tb = PCIePHYRXTestbench(ratio=2) def simulationSetUp(self, tb): yield tb.lane.rx_valid.eq(1) @simulation_test def test_rx_ts1_2x_same_valid(self, tb): yield from self.tb.transmit([ (K(28,5), 0xaa), (0x1a, 0xff), (0b0010, 0b0000), *[(D(10,2), D(10,2)) for _ in range(5)], (K(28,5), 0xaa), (0x1a, 0xff), (0b0010, 0b0000), *[(D(10,2), D(10,2)) for _ in range(5)], (K(28,5), K(28,0)), ]) yield from self.assertSignal(tb.phy.ts.valid, 1)
import unittest from migen import * from ..gateware.align import * from . import simulation_test class SymbolSlipTestbench(Module): def __init__(self): self.submodules.dut = SymbolSlip(symbol_size=8, word_size=4, comma=0xaa) class SymbolSlipTestCase(unittest.TestCase): def setUp(self): self.tb = SymbolSlipTestbench() @simulation_test def test_no_slip(self, tb): yield tb.dut.i.eq(0x04030201) yield self.assertEqual((yield tb.dut.o), 0) yield tb.dut.i.eq(0x08070605) yield self.assertEqual((yield tb.dut.o), 0) yield tb.dut.i.eq(0x0c0b0a09) yield self.assertEqual((yield tb.dut.o), 0x04030201) yield tb.dut.i.eq(0) yield self.assertEqual((yield tb.dut.o), 0x08070605) yield self.assertEqual((yield tb.dut.o), 0x0c0b0a09) @simulation_test def test_slip(self, tb): yield tb.dut.i.eq(0x0403aa01) yield yield tb.dut.i.eq(0x08070605) yield self.assertEqual((yield tb.dut.o), 0) yield tb.dut.i.eq(0x0c0b0a09) yield self.assertEqual((yield tb.dut.o), 0x050403aa) yield tb.dut.i.eq(0x000f0e0d) yield self.assertEqual((yield tb.dut.o), 0x09080706) @simulation_test def test_slip_2(self, tb): yield tb.dut.i.eq(0x0403aa01) yield yield tb.dut.i.eq(0x080706aa) yield self.assertEqual((yield tb.dut.o), 0) yield tb.dut.i.eq(0x0c0b0a09) yield self.assertEqual((yield tb.dut.o), 0xaa0403aa) yield tb.dut.i.eq(0x000f0e0d) yield self.assertEqual((yield tb.dut.o), 0x080706aa) yield tb.dut.i.eq(0x14131210) yield self.assertEqual((yield tb.dut.o), 0x0c0b0a09) @simulation_test def test_enable(self, tb): yield tb.dut.en.eq(0) yield tb.dut.i.eq(0x0403aa01) yield yield tb.dut.i.eq(0x08070605) yield self.assertEqual((yield tb.dut.o), 0) yield tb.dut.i.eq(0x0c0b0a09) yield self.assertEqual((yield tb.dut.o), 0x0403aa01) yield tb.dut.i.eq(0x000f0e0d) yield self.assertEqual((yield tb.dut.o), 0x08070605)
import unittest from migen import * from ..gateware.debug import * from . import simulation_test class RingLogTestbench(Module): def __init__(self): self.submodules.dut = RingLog(timestamp_width=8, data_width=8, depth=4) def read_out(self): yield self.dut.trigger.eq(1) yield result = [] for _ in range(self.dut.depth): yield self.dut.next.eq(1) yield result.append(((yield self.dut.time_o), (yield self.dut.data_o))) yield self.dut.next.eq(0) yield yield self.dut.trigger.eq(0) yield return result class RingLogTestCase(unittest.TestCase): def setUp(self): self.tb = RingLogTestbench() @simulation_test def test_basic(self, tb): yield yield yield yield tb.dut.data_i.eq(0x55) yield yield yield yield yield yield tb.dut.data_i.eq(0xaa) yield self.assertEqual((yield from tb.read_out()), [ (0, 0), (0, 0), (4, 0x55), (9, 0xaa), ])
import functools from migen import * __all__ = ["simulation_test"] def simulation_test(case=None, **kwargs): def configure_wrapper(case): @functools.wraps(case) def wrapper(self): if hasattr(self, "configure"): self.configure(self.tb, **kwargs) def setup_wrapper(): if hasattr(self, "simulationSetUp"): yield from self.simulationSetUp(self.tb) yield from case(self, self.tb) run_simulation(self.tb, setup_wrapper(), vcd_name="test.vcd") return wrapper if case is None: return configure_wrapper else: return configure_wrapper(case)
import unittest from migen import * from ..gateware.serdes import * from ..gateware.serdes import K, D from ..gateware.phy_tx import * from . import simulation_test class PCIePHYTXTestbench(Module): def __init__(self, ratio=1): self.submodules.lane = PCIeSERDESInterface(ratio) self.submodules.phy = PCIePHYTX(self.lane) def do_finalize(self): self.states = {v: k for k, v in self.phy.emitter.fsm.encoding.items()} def phy_state(self): return self.states[(yield self.phy.emitter.fsm.state)] def receive(self, count): symbols = [] for _ in range(count): word = yield self.lane.tx_symbol if self.lane.ratio == 1: symbols.append(word) else: symbols.append(tuple((word >> (9 * n)) & 0x1ff for n in range(self.lane.ratio))) yield return symbols class _PCIePHYTXTestCase(unittest.TestCase): def assertReceive(self, tb, symbols): self.assertEqual((yield from tb.receive(len(symbols))), symbols) class PCIePHYTXGear1xTestCase(_PCIePHYTXTestCase): def setUp(self): self.tb = PCIePHYTXTestbench() def assertReceive(self, tb, symbols): self.assertEqual((yield from tb.receive(len(symbols))), symbols) @simulation_test def test_tx_ts1_pad(self, tb): yield tb.phy.ts.valid.eq(1) yield tb.phy.ts.n_fts.eq(0xff) yield tb.phy.ts.rate.gen1.eq(1) yield yield from self.assertReceive(tb, [ K(28,5), K(23,7), K(23,7), 0xff, 0b0010, 0b0000, *[D(10,2) for _ in range(10)], K(28,5) ]) @simulation_test def test_tx_ts1_link(self, tb): yield tb.phy.ts.valid.eq(1) yield tb.phy.ts.link.valid.eq(1) yield tb.phy.ts.link.number.eq(0xaa) yield tb.phy.ts.n_fts.eq(0xff) yield tb.phy.ts.rate.gen1.eq(1) yield yield from self.assertReceive(tb, [ K(28,5), 0xaa, K(23,7), 0xff, 0b0010, 0b0000, *[D(10,2) for _ in range(10)], K(28,5) ]) @simulation_test def test_tx_ts1_link_lane(self, tb): yield tb.phy.ts.valid.eq(1) yield tb.phy.ts.link.valid.eq(1) yield tb.phy.ts.link.number.eq(0xaa) yield tb.phy.ts.lane.valid.eq(1) yield tb.phy.ts.lane.number.eq(0x01) yield tb.phy.ts.n_fts.eq(0xff) yield tb.phy.ts.rate.gen1.eq(1) yield yield from self.assertReceive(tb, [ K(28,5), 0xaa, 0x01, 0xff, 0b0010, 0b0000, *[D(10,2) for _ in range(10)], K(28,5) ]) @simulation_test def test_tx_ts1_reset(self, tb): yield tb.phy.ts.valid.eq(1) yield tb.phy.ts.n_fts.eq(0xff) yield tb.phy.ts.rate.gen1.eq(1) yield tb.phy.ts.ctrl.hot_reset.eq(1) yield yield from self.assertReceive(tb, [ K(28,5), K(23,7), K(23,7), 0xff, 0b0010, 0b0001, *[D(10,2) for _ in range(10)], K(28,5) ]) @simulation_test def test_tx_ts2(self, tb): yield tb.phy.ts.valid.eq(1) yield tb.phy.ts.n_fts.eq(0xff) yield tb.phy.ts.rate.gen1.eq(1) yield tb.phy.ts.ts_id.eq(1) yield yield from self.assertReceive(tb, [ K(28,5), K(23,7), K(23,7), 0xff, 0b0010, 0b0000, *[D(5,2) for _ in range(10)], K(28,5) ]) class PCIePHYTXGear2xTestCase(_PCIePHYTXTestCase): def setUp(self): self.tb = PCIePHYTXTestbench(ratio=2) @simulation_test def test_tx_ts1_link_lane(self, tb): yield tb.phy.ts.valid.eq(1) yield tb.phy.ts.link.valid.eq(1) yield tb.phy.ts.link.number.eq(0xaa) yield tb.phy.ts.lane.valid.eq(1) yield tb.phy.ts.lane.number.eq(0x01) yield tb.phy.ts.n_fts.eq(0xff) yield tb.phy.ts.rate.gen1.eq(1) yield yield from self.assertReceive(tb, [ (K(28,5), 0xaa), (0x01, 0xff), (0b0010, 0b0000), *[(D(10,2), D(10,2)) for _ in range(5)], ])
__all__ = ["ts_layout"] ts_layout = [ ("valid", 1), ("link", [ ("valid", 1), ("number", 8), ]), ("lane", [ ("valid", 1), ("number", 5), ]), ("n_fts", 8), ("rate", [ ("reserved0", 1), ("gen1", 1), ("gen2", 1), ("reserved1", 3), ("autonomous_change", 1), ("speed_change", 1), ]), ("ctrl", [ ("hot_reset", 1), ("disable_link", 1), ("loopback", 1), ("disable_scrambling", 1), ("compliance_receive", 1), ]), ("ts_id", 1), # 0: TS1, 1: TS2 ]
from migen import * from .serdes import K, D from .protocol import * from .struct import * __all__ = ["PCIePHYTX"] class PCIePHYTX(Module): def __init__(self, lane): self.e_idle = Signal() self.comma = Signal() self.ts = Record(ts_layout) ### self.submodules.emitter = Emitter( symbol_size=12, word_size=lane.ratio, reset_rule="IDLE", layout=[ ("data", 8), ("ctrl", 1), ("set_disp", 1), ("disp", 1), ("e_idle", 1), ]) self.comb += [ lane.tx_symbol.eq(Cat( (self.emitter._o[n].data, self.emitter._o[n].ctrl) for n in range(lane.ratio) )), lane.tx_set_disp.eq(Cat(self.emitter._o[n].set_disp for n in range(lane.ratio))), lane.tx_disp .eq(Cat(self.emitter._o[n].disp for n in range(lane.ratio))), lane.tx_e_idle .eq(Cat(self.emitter._o[n].e_idle for n in range(lane.ratio))), ] self.emitter.rule( name="IDLE", cond=lambda: self.e_idle, succ="IDLE", action=lambda symbol: [ symbol.e_idle.eq(1) ] ) self.emitter.rule( name="IDLE", cond=lambda: self.ts.valid, succ="TSn-LINK", action=lambda symbol: [ self.comma.eq(1), symbol.raw_bits().eq(K(28,5)), symbol.set_disp.eq(1), symbol.disp.eq(0) ] ) self.emitter.rule( name="TSn-LINK", succ="TSn-LANE", action=lambda symbol: [ If(self.ts.link.valid, symbol.data.eq(self.ts.link.number) ).Else( symbol.raw_bits().eq(K(23,7)) ), ] ) self.emitter.rule( name="TSn-LANE", succ="TSn-FTS", action=lambda symbol: [ If(self.ts.lane.valid, symbol.data.eq(self.ts.lane.number) ).Else( symbol.raw_bits().eq(K(23,7)) ), ] ) self.emitter.rule( name="TSn-FTS", succ="TSn-RATE", action=lambda symbol: [ symbol.data.eq(self.ts.n_fts), ] ) self.emitter.rule( name="TSn-RATE", succ="TSn-CTRL", action=lambda symbol: [ symbol.data.eq(self.ts.rate.raw_bits()), ] ) self.emitter.rule( name="TSn-CTRL", succ="TSn-ID0", action=lambda symbol: [ symbol.data.eq(self.ts.ctrl.raw_bits()), ] ) for n in range(0, 10): self.emitter.rule( name="TSn-ID%d" % n, succ="IDLE" if n == 9 else "TSn-ID%d" % (n + 1), action=lambda symbol: [ If(self.ts.ts_id == 0, symbol.raw_bits().eq(D(10,2)) ).Else( symbol.raw_bits().eq(D(5,2)) ) ] )
from migen import * from migen.genlib.fsm import * from .protocol import * from .phy_rx import * from .phy_tx import * from .debug import RingLog __all__ = ["PCIePHY"] class PCIePHY(Module): def __init__(self, lane, ms_cyc): self.submodules.rx = rx = PCIePHYRX(lane) self.submodules.tx = tx = PCIePHYTX(lane) self.link_up = Signal() self.submodules.ltssm_log = RingLog(timestamp_width=32, data_width=8, depth=16) ### self.comb += [ tx.ts.rate.gen1.eq(1), ] rx_timer = Signal(max=64 * ms_cyc + 1) rx_ts_count = Signal(max=16 + 1) tx_ts_count = Signal(max=1024 + 1) # LTSSM implemented according to PCIe Base Specification Revision 2.1. # The Specification must be read side to side with this code in order to understand it. # Unfortunately, the Specification is copyrighted and probably cannot be quoted here # directly at length. self.submodules.ltssm = ltssm = ResetInserter()(FSM()) self.ltssm.act("Detect.Quiet", NextValue(tx.e_idle, 1), NextValue(self.link_up, 0), NextValue(rx_timer, 12 * ms_cyc), NextState("Detect.Quiet:Timeout") ) self.ltssm.act("Detect.Quiet:Timeout", NextValue(rx_timer, rx_timer - 1), If(lane.rx_present | (rx_timer == 0), NextValue(lane.det_enable, 1), NextState("Detect.Active") ) ) self.ltssm.act("Detect.Active", If(lane.det_valid, NextValue(lane.det_enable, 0), If(lane.det_status, NextState("Polling.Active") ).Else( NextState("Detect.Quiet") ) ) ) self.ltssm.act("Polling.Active", NextValue(tx.e_idle, 0), # Transmit TS1 Link=PAD Lane=PAD NextValue(tx.ts.valid, 1), NextValue(tx.ts.ts_id, 0), NextValue(tx.ts.link.valid, 0), NextValue(tx.ts.lane.valid, 0), NextValue(rx_timer, 24 * ms_cyc), NextValue(rx_ts_count, 0), NextValue(tx_ts_count, 0), NextState("Polling.Active:TS") ) self.ltssm.act("Polling.Active:TS", If(tx.comma, If(tx_ts_count != 1024, NextValue(tx_ts_count, tx_ts_count + 1) ) ), If((tx_ts_count == 1024), If(rx.comma, # Accept TS1 Link=PAD Lane=PAD Compliance=0 # Accept TS1 Link=PAD Lane=PAD Loopback=1 # Accept TS2 Link=PAD Lane=PAD If(rx.ts.valid & ~rx.ts.lane.valid & ~rx.ts.link.valid & (((rx.ts.ts_id == 0) & ~rx.ts.ctrl.compliance_receive) | ((rx.ts.ts_id == 0) & rx.ts.ctrl.loopback) | (rx.ts.ts_id == 1)), NextValue(rx_ts_count, rx_ts_count + 1), If(rx_ts_count == 8, NextState("Polling.Configuration") ) ).Else( NextValue(rx_ts_count, 0) ) ) ), NextValue(rx_timer, rx_timer - 1), If(rx_timer == 0, NextState("Detect.Quiet") ) ) self.ltssm.act("Polling.Configuration", # Transmit TS2 Link=PAD Lane=PAD NextValue(tx.ts.valid, 1), NextValue(tx.ts.ts_id, 1), NextValue(tx.ts.link.valid, 0), NextValue(tx.ts.lane.valid, 0), NextValue(rx_ts_count, 0), NextValue(tx_ts_count, 0), NextValue(rx_timer, 48 * ms_cyc), NextState("Polling.Configuration:TS") ) self.ltssm.act("Polling.Configuration:TS", If(tx.comma, If(rx_ts_count == 0, NextValue(tx_ts_count, 0) ).Else( NextValue(tx_ts_count, tx_ts_count + 1) ) ), If(rx.comma, # Accept TS2 Link=PAD Lane=PAD If(rx.ts.valid & (rx.ts.ts_id == 1) & ~rx.ts.link.valid & ~rx.ts.lane.valid, If(rx_ts_count == 8, If(tx_ts_count == 16, NextValue(rx_timer, 24 * ms_cyc), NextState("Configuration.Linkwidth.Start") ) ).Else( NextValue(rx_ts_count, rx_ts_count + 1) ) ).Else( NextValue(rx_ts_count, 0) ), ), NextValue(rx_timer, rx_timer - 1), If(rx_timer == 0, NextState("Detect.Quiet") ) ) self.ltssm.act("Configuration.Linkwidth.Start", # Transmit TS1 Link=PAD Lane=PAD NextValue(tx.ts.valid, 1), NextValue(tx.ts.ts_id, 0), NextValue(tx.ts.link.valid, 0), NextValue(tx.ts.lane.valid, 0), # Accept TS1 Link=Upstream-Link Lane=PAD If(rx.ts.valid & (rx.ts.ts_id == 0) & rx.ts.link.valid & ~rx.ts.lane.valid, # Transmit TS1 Link=Upstream-Link Lane=PAD NextValue(tx.ts.link.valid, 1), NextValue(tx.ts.link.number, rx.ts.link.number), NextValue(rx_timer, 2 * ms_cyc), NextState("Configuration.Linkwidth.Accept") ), NextValue(rx_timer, rx_timer - 1), If(rx_timer == 0, NextState("Detect.Quiet") ) ) self.ltssm.act("Configuration.Linkwidth.Accept", # Accept TS1 Link=Upstream-Link Lane=Upstream-Lane If(rx.ts.valid & (rx.ts.ts_id == 0) & rx.ts.link.valid & rx.ts.lane.valid, # Accept Upstream-Lane=0 If(rx.ts.lane.number == 0, # Transmit TS1 Link=Upstream-Link Lane=Upstream-Lane NextValue(tx.ts.lane.valid, 1), NextValue(tx.ts.lane.number, rx.ts.lane.number), NextValue(rx_timer, 2 * ms_cyc), NextState("Configuration.Lanenum.Wait") ) ), # Accept TS1 Link=PAD Lane=PAD If(rx.ts.valid & (rx.ts.ts_id == 0) & ~rx.ts.link.valid & ~rx.ts.lane.valid, NextState("Detect.Quiet") ), NextValue(rx_timer, rx_timer - 1), If(rx_timer == 0, NextState("Detect.Quiet") ) ) self.ltssm.act("Configuration.Lanenum.Wait", # Accept TS1 Link=Upstream-Link Lane=Upstream-Lane If(rx.ts.valid & (rx.ts.ts_id == 0) & rx.ts.link.valid & rx.ts.lane.valid, If(rx.ts.lane.number != tx.ts.lane.number, NextState("Configuration.Lanenum.Accept") ) ), # Accept TS2 If(rx.ts.valid & (rx.ts.ts_id == 1), NextState("Configuration.Lanenum.Accept") ), # Accept TS1 Link=PAD Lane=PAD If(rx.ts.valid & (rx.ts.ts_id == 0) & ~rx.ts.link.valid & ~rx.ts.lane.valid, NextState("Detect.Quiet") ), NextValue(rx_timer, rx_timer - 1), If(rx_timer == 0, NextState("Detect.Quiet") ) ) self.ltssm.act("Configuration.Lanenum.Accept", # Accept TS2 Link=Upstream-Link Lane=Upstream-Lane If(rx.ts.valid & (rx.ts.ts_id == 1) & rx.ts.link.valid & rx.ts.lane.valid, If((rx.ts.link.number == tx.ts.link.number) & (rx.ts.lane.number == tx.ts.lane.number), NextState("Configuration.Complete") ).Else( NextState("Detect.Quiet") ) ), # Accept TS1 Link=PAD Lane=PAD If(rx.ts.valid & (rx.ts.ts_id == 0) & ~rx.ts.link.valid & ~rx.ts.lane.valid, NextState("Detect.Quiet") ), ) self.ltssm.act("Configuration.Complete", # Transmit TS2 Link=Upstream-Link Lane=Upstream-Lane NextValue(tx.ts.ts_id, 1), NextValue(tx.ts.n_fts, 0xff), NextValue(rx_ts_count, 0), NextValue(tx_ts_count, 0), NextValue(rx_timer, 2 * ms_cyc), NextState("Configuration.Complete:TS") ) self.ltssm.act("Configuration.Complete:TS", If(tx.comma, If(rx_ts_count == 0, NextValue(tx_ts_count, 0) ).Else( NextValue(tx_ts_count, tx_ts_count + 1) ) ), If(rx.comma, # Accept TS2 Link=Upstream-Link Lane=Upstream-Lane If(rx.ts.valid & (rx.ts.ts_id == 1) & rx.ts.link.valid & rx.ts.lane.valid & (rx.ts.link.number == tx.ts.link.number) & (rx.ts.lane.number == tx.ts.lane.number), If(rx_ts_count == 8, If(tx_ts_count == 16, NextState("Configuration.Idle") ) ).Else( NextValue(rx_ts_count, rx_ts_count + 1) ) ).Else( NextValue(rx_ts_count, 0) ), ), NextValue(rx_timer, rx_timer - 1), If(rx_timer == 0, NextState("Detect.Quiet") ) ) self.ltssm.act("Configuration.Idle", NextValue(self.link_up, 1) ) def do_finalize(self): self.comb += self.ltssm_log.data_i.eq(self.ltssm.state)
from migen import * __all__ = ["SymbolSlip"] class SymbolSlip(Module): """ Symbol slip based comma aligner. Accepts and emits a sequence of words, shifting it such that if a comma symbol is encountered, it is always placed at the start of a word. If the input word contains multiple commas, the behavior is undefined. Parameters ---------- symbol_size : int Symbol width, in bits. word_size : int Word size, in symbols. comma : int Comma symbol, ``symbol_size`` bit wide. Attributes ---------- i : Signal(symbol_size * word_size) Input word. o : Signal(symbol_size * word_size) Output word. en : Signal Enable input. If asserted (the default), comma symbol affects alignment. Otherwise, comma symbol does nothing. """ def __init__(self, symbol_size, word_size, comma): width = symbol_size * word_size self.i = Signal(width) self.o = Signal(width) self.en = Signal(reset=1) ### shreg = Signal(width * 2) offset = Signal(max=symbol_size * (word_size - 1)) self.sync += shreg.eq(Cat(shreg[width:], self.i)) self.comb += self.o.eq(shreg.part(offset, width)) commas = Signal(word_size) self.sync += [ commas[n].eq(self.i.part(symbol_size * n, symbol_size) == comma) for n in range(word_size) ] self.sync += [ If(self.en, Case(commas, { (1 << n): offset.eq(symbol_size * n) for n in range(word_size) }) ) ]
from migen import * __all__ = ["RingLog"] class RingLog(Module): def __init__(self, timestamp_width, data_width, depth): self.width = timestamp_width + data_width self.depth = depth self.data_i = Signal(data_width) self.trigger = Signal() self.time_o = Signal(timestamp_width) self.data_o = Signal(data_width) self.next = Signal() ### timestamp = Signal(timestamp_width) self.sync += timestamp.eq(timestamp + 1) data_i_l = Signal.like(self.data_i) self.sync += data_i_l.eq(self.data_i) storage = Memory(width=self.width, depth=self.depth) self.specials += storage wrport = storage.get_port(write_capable=True) self.specials += wrport self.comb += [ wrport.we.eq(~self.trigger & (self.data_i != data_i_l)), wrport.dat_w.eq(Cat(timestamp, self.data_i)) ] self.sync += [ If(~self.trigger, If(self.data_i != data_i_l, wrport.adr.eq(wrport.adr + 1) ) ) ] trigger_s = Signal.like(self.trigger) self.sync += trigger_s.eq(self.trigger) rdport = storage.get_port() self.specials += rdport self.comb += [ Cat(self.time_o, self.data_o).eq(rdport.dat_r), ] self.sync += [ If(~self.trigger, rdport.adr.eq(wrport.adr + 1) ).Elif(self.next, rdport.adr.eq(rdport.adr + 1) ) ]
from migen import * from .serdes import K, D from .protocol import * from .struct import * __all__ = ["PCIePHYRX"] class PCIePHYRX(Module): def __init__(self, lane): self.error = Signal() self.comma = Signal() self.ts = Record(ts_layout) ### self.comb += lane.rx_align.eq(1) self._tsY = Record(ts_layout) # previous TS received self._tsZ = Record(ts_layout) # TS being received self.sync += If(self.error, self._tsZ.valid.eq(0)) ts_id = Signal(9) ts_inv = Signal() self.submodules.parser = Parser( symbol_size=9, word_size=lane.ratio, reset_rule="COMMA", layout=[ ("data", 8), ("ctrl", 1), ]) self.comb += [ self.parser.reset.eq(~lane.rx_valid), self.parser.i.eq(lane.rx_symbol), self.error.eq(self.parser.error) ] self.parser.rule( name="COMMA", cond=lambda symbol: symbol.raw_bits() == K(28,5), succ="TSn-LINK/SKP-0", action=lambda symbol: [ self.comma.eq(1), NextValue(self._tsZ.valid, 1), NextValue(self._tsY.raw_bits(), self._tsZ.raw_bits()), ] ) self.parser.rule( name="TSn-LINK/SKP-0", cond=lambda symbol: symbol.raw_bits() == K(28,0), succ="SKP-1" ) self.parser.rule( name="TSn-LINK/SKP-0", cond=lambda symbol: symbol.raw_bits() == K(23,7), succ="TSn-LANE", action=lambda symbol: [ NextValue(self._tsZ.link.valid, 0) ] ) self.parser.rule( name="TSn-LINK/SKP-0", cond=lambda symbol: ~symbol.ctrl, succ="TSn-LANE", action=lambda symbol: [ NextValue(self._tsZ.link.number, symbol.data), NextValue(self._tsZ.link.valid, 1) ] ) for n in range(1, 3): self.parser.rule( name="SKP-%d" % n, cond=lambda symbol: symbol.raw_bits() == K(28,0), succ="COMMA" if n == 2 else "SKP-%d" % (n + 1), ) self.parser.rule( name="TSn-LANE", cond=lambda symbol: symbol.raw_bits() == K(23,7), succ="TSn-FTS", action=lambda symbol: [ NextValue(self._tsZ.lane.valid, 0) ] ) self.parser.rule( name="TSn-LANE", cond=lambda symbol: ~symbol.ctrl, succ="TSn-FTS", action=lambda symbol: [ NextValue(self._tsZ.lane.number, symbol.data), NextValue(self._tsZ.lane.valid, 1) ] ) self.parser.rule( name="TSn-FTS", cond=lambda symbol: ~symbol.ctrl, succ="TSn-RATE", action=lambda symbol: [ NextValue(self._tsZ.n_fts, symbol.data) ] ) self.parser.rule( name="TSn-RATE", cond=lambda symbol: ~symbol.ctrl, succ="TSn-CTRL", action=lambda symbol: [ NextValue(self._tsZ.rate.raw_bits(), symbol.data) ] ) self.parser.rule( name="TSn-CTRL", cond=lambda symbol: ~symbol.ctrl, succ="TSn-ID0", action=lambda symbol: [ NextValue(self._tsZ.ctrl.raw_bits(), symbol.data) ] ) self.parser.rule( name="TSn-ID0", cond=lambda symbol: symbol.raw_bits() == D(10,2), succ="TSn-ID1", action=lambda symbol: [ NextMemory(ts_id, symbol.raw_bits()), NextValue(ts_inv, 0), NextValue(self._tsZ.ts_id, 0), ] ) self.parser.rule( name="TSn-ID0", cond=lambda symbol: symbol.raw_bits() == D(5,2), succ="TSn-ID1", action=lambda symbol: [ NextMemory(ts_id, symbol.raw_bits()), NextValue(ts_inv, 0), NextValue(self._tsZ.ts_id, 1), ] ) self.parser.rule( name="TSn-ID0", cond=lambda symbol: symbol.raw_bits() == D(21,5), succ="TSn-ID1", action=lambda symbol: [ NextMemory(ts_id, symbol.raw_bits()), NextValue(ts_inv, 1), ] ) self.parser.rule( name="TSn-ID0", cond=lambda symbol: symbol.raw_bits() == D(26,5), succ="TSn-ID1", action=lambda symbol: [ NextMemory(ts_id, symbol.raw_bits()), NextValue(ts_inv, 1), ] ) for n in range(1, 9): self.parser.rule( name="TSn-ID%d" % n, cond=lambda symbol: symbol.raw_bits() == Memory(ts_id), succ="TSn-ID%d" % (n + 1) ) self.parser.rule( name="TSn-ID9", cond=lambda symbol: symbol.raw_bits() == Memory(ts_id), succ="COMMA", action=lambda symbol: [ NextValue(self.ts.valid, 0), If(ts_inv, NextValue(lane.rx_invert, ~lane.rx_invert) ).Elif(self._tsZ.raw_bits() == self._tsY.raw_bits(), NextValue(self.ts.raw_bits(), self._tsY.raw_bits()) ), NextState("COMMA") ] )
from migen import * from .align import SymbolSlip __all__ = ["PCIeSERDESInterface", "PCIeSERDESAligner"] def K(x, y): return (1 << 8) | (y << 5) | x def D(x, y): return (0 << 8) | (y << 5) | x class PCIeSERDESInterface(Module): """ Interface of a single PCIe SERDES pair, connected to a single lane. Uses 1:**ratio** gearing for configurable **ratio**, i.e. **ratio** symbols are transmitted per clock cycle. Parameters ---------- ratio : int Gearbox ratio. rx_invert : Signal Assert to invert the received bits before 8b10b decoder. rx_align : Signal Assert to enable comma alignment state machine, deassert to lock alignment. rx_present : Signal Asserted if the receiver has detected signal. rx_locked : Signal Asserted if the receiver has recovered a valid clock. rx_aligned : Signal Asserted if the receiver has aligned to the comma symbol. rx_symbol : Signal(9 * ratio) Two 8b10b-decoded received symbols, with 9th bit indicating a control symbol. rx_valid : Signal(ratio) Asserted if the received symbol has no coding errors. If not asserted, ``rx_data`` and ``rx_control`` must be ignored, and may contain symbols that do not exist in 8b10b coding space. tx_locked : Signal Asserted if the transmitter is generating a valid clock. tx_symbol : Signal(9 * ratio) Symbol to 8b10b-encode and transmit, with 9th bit indicating a control symbol. tx_set_disp : Signal(ratio) Assert to indicate that the 8b10b encoder should choose an encoding with a specific running disparity instead of using its state, specified by ``tx_disp``. tx_disp : Signal(ratio) Assert to transmit a symbol with positive running disparity, deassert for negative running disparity. tx_e_idle : Signal(ratio) Assert to transmit Electrical Idle for that symbol. det_enable : Signal Rising edge starts the Receiver Detection test. Transmitter must be in Electrical Idle when ``det_enable`` is asserted. det_valid : Signal Asserted to indicate that the Receiver Detection test has finished, deasserted together with ``det_enable``. det_status : Signal Valid when ``det_valid`` is asserted. Indicates whether a receiver has been detected on this lane. """ def __init__(self, ratio=1): self.ratio = ratio self.rx_invert = Signal() self.rx_align = Signal() self.rx_present = Signal() self.rx_locked = Signal() self.rx_aligned = Signal() self.rx_symbol = Signal(ratio * 9) self.rx_valid = Signal(ratio) self.tx_symbol = Signal(ratio * 9) self.tx_set_disp = Signal(ratio) self.tx_disp = Signal(ratio) self.tx_e_idle = Signal(ratio) self.det_enable = Signal() self.det_valid = Signal() self.det_status = Signal() class PCIeSERDESAligner(PCIeSERDESInterface): """ A multiplexer that aligns commas to the first symbol of the word, for SERDESes that only perform bit alignment and not symbol alignment. """ def __init__(self, lane): self.ratio = lane.ratio self.rx_invert = lane.rx_invert self.rx_align = lane.rx_align self.rx_present = lane.rx_present self.rx_locked = lane.rx_locked self.rx_aligned = lane.rx_aligned self.rx_symbol = Signal(lane.ratio * 9) self.rx_valid = Signal(lane.ratio) self.tx_symbol = lane.tx_symbol self.tx_set_disp = lane.tx_set_disp self.tx_disp = lane.tx_disp self.tx_e_idle = lane.tx_e_idle self.det_enable = lane.det_enable self.det_valid = lane.det_valid self.det_status = lane.det_status ### self.submodules.slip = SymbolSlip(symbol_size=10, word_size=lane.ratio, comma=(1<<9)|K(28,5)) self.comb += [ self.slip.en.eq(self.rx_align), self.slip.i.eq(Cat( (lane.rx_symbol.part(9 * n, 9), lane.rx_valid[n]) for n in range(lane.ratio) )), self.rx_symbol.eq(Cat( self.slip.o.part(10 * n, 9) for n in range(lane.ratio) )), self.rx_valid.eq(Cat( self.slip.o[10 * n + 9] for n in range(lane.ratio) )), ]
import os from migen import * from .engine import _ProtocolFSM, _ProtocolEngine _DEBUG = os.getenv("DEBUG_PARSER") class Parser(_ProtocolEngine): def __init__(self, symbol_size, word_size, reset_rule, layout=None): super().__init__(symbol_size, word_size, reset_rule) self.reset = Signal() self.error = Signal() self.i = Signal(symbol_size * word_size) ### self._i = [self.i.part(n * symbol_size, symbol_size) for n in range(word_size)] if layout is not None: for n in range(word_size): irec = Record(layout) self.comb += irec.raw_bits().eq(self._i[n]) self._i[n] = irec def do_finalize(self): self.submodules.fsm = ResetInserter()(_ProtocolFSM()) self.comb += self.fsm.reset.eq(self.reset | self.error) if _DEBUG: print("Parser layout:") worklist = {self._reset_rule} processed = set() while worklist: rule_name = worklist.pop() processed.add(rule_name) if _DEBUG: print(" State %s" % rule_name) rule_tuples = set() self._get_rule_tuples(rule_name, rule_tuples) actions = [] for i, rule_tuple in enumerate(rule_tuples): if _DEBUG: print(" Input #%d %s -> %s" % (i, rule_name, " -> ".join(rule.succ for rule in rule_tuple))) succ = rule_tuple[-1].succ action = [ self.error.eq(0), NextState(succ) ] for j, rule in enumerate(reversed(rule_tuple)): symbol = self._i[self._word_size - j - 1] action = [ If(rule.cond(symbol), rule.action(symbol), *action ), ] actions.append(action) if succ not in processed: worklist.add(succ) self.fsm.act(rule_name, [ self.error.eq(1), *actions ])
from collections import namedtuple, defaultdict from migen import * from migen.fhdl.structure import _Value, _Statement from migen.genlib.fsm import _LowerNext, FSM class Memory(_Value): def __init__(self, target): self.target = target class NextMemory(_Statement): def __init__(self, target, value): self.target = target self.value = value class _LowerMemory(_LowerNext): def __init__(self, *args): super().__init__(*args) # (target, next_value_ce, next_value) self.memories = [] def _get_memory_control(self, memory): for target, next_value_ce, next_value in self.memories: if target is memory: break else: next_value_ce = Signal(related=memory) next_value = Signal(memory.nbits, related=memory) self.memories.append((memory, next_value_ce, next_value)) return next_value_ce, next_value def visit_unknown(self, node): if isinstance(node, Memory): next_value_ce, next_value = self._get_memory_control(node.target) return Mux(next_value_ce, next_value, node.target) elif isinstance(node, NextMemory): next_value_ce, next_value = self._get_memory_control(node.target) return next_value_ce.eq(1), next_value.eq(node.value) else: return super().visit_unknown(node) class _ProtocolFSM(FSM): def _lower_controls(self): return _LowerMemory(self.next_state, self.encoding, self.state_aliases) def _finalize_sync(self, ls): super()._finalize_sync(ls) for memory, next_value_ce, next_value in ls.memories: self.sync += If(next_value_ce, memory.eq(next_value)) _Rule = namedtuple("_Rule", ("name", "cond", "succ", "action")) class _ProtocolEngine(Module): def __init__(self, symbol_size, word_size, reset_rule): self._symbol_size = symbol_size self._word_size = word_size self._reset_rule = reset_rule # name -> [(cond, succ, action)] self._grammar = defaultdict(lambda: []) def rule(self, name, succ, cond=lambda *_: True, action=lambda symbol: []): self._grammar[name].append(_Rule(name, cond, succ, action)) def _get_rule_tuples(self, rule_name, rule_tuples, rule_path=()): if len(rule_path) == self._word_size: rule_tuples.add(rule_path) return for rule in self._grammar[rule_name]: self._get_rule_tuples(rule.succ, rule_tuples, rule_path + (rule,))
import os from migen import * from .engine import _ProtocolFSM, _ProtocolEngine _DEBUG = os.getenv("DEBUG_EMITTER") class Emitter(_ProtocolEngine): def __init__(self, symbol_size, word_size, reset_rule, layout=None): super().__init__(symbol_size, word_size, reset_rule) self.o = Signal(symbol_size * word_size) ### self._o = [Signal(symbol_size) for n in range(word_size)] self.comb += self.o.eq(Cat(self._o)) if layout is not None: for n in range(word_size): irec = Record(layout) self.comb += self._o[n].eq(irec.raw_bits()) self._o[n] = irec def do_finalize(self): self.submodules.fsm = _ProtocolFSM() if _DEBUG: print("Emitter layout:") worklist = {self._reset_rule} processed = set() while worklist: rule_name = worklist.pop() processed.add(rule_name) if _DEBUG: print(" State %s" % rule_name) rule_tuples = set() self._get_rule_tuples(rule_name, rule_tuples) conds = [] actions = [] for i, rule_tuple in enumerate(rule_tuples): if _DEBUG: print(" Output #%d %s -> %s" % (i, rule_name, " -> ".join(rule.succ for rule in rule_tuple))) succ = rule_tuple[-1].succ action = [NextState(succ)] for j, rule in enumerate(reversed(rule_tuple)): symbol = self._o[self._word_size - j - 1] action = [ If(rule.cond(), rule.action(symbol), *action ), ] actions.append(action) if succ not in processed: worklist.add(succ) self.fsm.act(rule_name, actions)
from migen import * from migen.genlib.cdc import * from ..serdes import * __all__ = ["LatticeECP5PCIeSERDES"] class LatticeECP5PCIeSERDES(Module): """ Lattice ECP5 DCU configured in PCIe mode. Assumes 100 MHz reference clock on SERDES clock input pair. Uses 1:2 gearing. Receiver Detection runs in TX clock domain. Only provides a single lane. Parameters ---------- ref_clk : Signal 100 MHz SERDES reference clock. rx_clk_o : Signal 125 MHz clock recovered from received data. rx_clk_i : Signal 125 MHz clock for the receive FIFO. tx_clk_o : Signal 125 MHz clock generated by transmit PLL. tx_clk_i : Signal 125 MHz clock for the transmit FIFO. """ def __init__(self, pins): self.ref_clk = Signal() # reference clock self.specials.extref0 = Instance("EXTREFB", i_REFCLKP=pins.clk_p, i_REFCLKN=pins.clk_n, o_REFCLKO=self.ref_clk, p_REFCK_PWDNB="0b1", p_REFCK_RTERM="0b1", # 100 Ohm ) self.extref0.attr.add(("LOC", "EXTREF0")) self.rx_clk_o = Signal() self.rx_clk_i = Signal() self.rx_bus = Signal(24) self.clock_domains.cd_rx = ClockDomain(reset_less=True) self.comb += self.cd_rx.clk.eq(self.rx_clk_i) rx_los = Signal() rx_los_s = Signal() rx_lol = Signal() rx_lol_s = Signal() rx_lsm = Signal() rx_lsm_s = Signal() rx_inv = Signal() rx_det = Signal() self.specials += [ MultiReg(rx_los, rx_los_s, odomain="rx"), MultiReg(rx_lol, rx_lol_s, odomain="rx"), MultiReg(rx_lsm, rx_lsm_s, odomain="rx"), ] self.tx_clk_o = Signal() self.tx_clk_i = Signal() self.tx_bus = Signal(24) self.clock_domains.cd_tx = ClockDomain(reset_less=True) self.comb += self.cd_tx.clk.eq(self.tx_clk_i) tx_lol = Signal() tx_lol_s = Signal() self.specials += [ MultiReg(tx_lol, tx_lol_s, odomain="tx") ] self.lane = lane = PCIeSERDESInterface(ratio=2) self.comb += [ rx_inv.eq(lane.rx_invert), rx_det.eq(lane.rx_align), lane.rx_present.eq(~rx_los_s), lane.rx_locked .eq(~rx_lol_s), lane.rx_aligned.eq(rx_lsm_s), lane.rx_symbol.eq(Cat(self.rx_bus[ 0: 9], self.rx_bus[12:21])), # In theory, ``rx_bus[9:11]`` has disparity error and coding violation status # signals, but in practice, they appear to be stuck at 1 and 0 respectively. # However, the 8b10b decoder replaces errors with a "K14.7", which is not a legal # point in 8b10b coding space, so we can use that as an indication. lane.rx_valid.eq(Cat(self.rx_bus[ 0: 9] != 0x1EE, self.rx_bus[12:21] != 0x1EE)), ] self.comb += [ self.tx_bus.eq(Cat(lane.tx_symbol[0: 9], lane.tx_set_disp[0], lane.tx_disp[0], lane.tx_e_idle[0], lane.tx_symbol[9:18], lane.tx_set_disp[1], lane.tx_disp[1], lane.tx_e_idle[1])), ] pcie_det_en = Signal() pcie_ct = Signal() pcie_done = Signal() pcie_done_s = Signal() pcie_con = Signal() pcie_con_s = Signal() self.specials += [ MultiReg(pcie_done, pcie_done_s, odomain="tx"), MultiReg(pcie_con, pcie_con_s, odomain="tx"), ] det_timer = Signal(max=16) # All comments below from TN1261. self.submodules.det_fsm = ResetInserter()(ClockDomainsRenamer("tx")(FSM())) self.comb += self.det_fsm.reset.eq(~lane.det_enable) # The PCIeSERDESInterface contract states that at det_enable rising edge the transmitter # is already in Electrical Idle state, but not how long it is there. self.det_fsm.act("START", # Before starting a Receiver Detection test, the transmitter must be put into # electrical idle by setting the tx_idle_ch#_c input high. The Receiver Detection # test can begin 120 ns after tx_elec_idle is set high by driving the appropriate # pci_det_en_ch#_c high. NextValue(det_timer, 15), NextState("SET-DETECT-H") ) self.det_fsm.act("SET-DETECT-H", # 1. The user drives pcie_det_en high, putting the corresponding TX driver into # receiver detect mode. [...] The TX driver takes some time to enter this state # so the pcie_det_en must be driven high for at least 120ns before pcie_ct # is asserted. If(det_timer == 0, NextValue(pcie_det_en, 1), NextValue(det_timer, 15), NextState("SET-STROBE-H") ).Else( NextValue(det_timer, det_timer - 1) ) ) self.det_fsm.act("SET-STROBE-H", # 2. The user drives pcie_ct high for four byte clocks. If(det_timer == 0, NextValue(pcie_ct, 1), NextValue(det_timer, 3), NextState("SET-STROBE-L") ).Else( NextValue(det_timer, det_timer - 1) ) ) self.det_fsm.act("SET-STROBE-L", # 3. SERDES drives the corresponding pcie_done low. # (this happens asynchronously, so we're going to observe a few samples of pcie_done # as high) If(det_timer == 0, NextValue(pcie_ct, 0), NextState("WAIT-DONE-L") ).Else( NextValue(det_timer, det_timer - 1) ) ) self.det_fsm.act("WAIT-DONE-L", # 6. SERDES drives the corresponding pcie_done high If(~pcie_done_s, NextState("WAIT-DONE-H") ) ) self.det_fsm.act("WAIT-DONE-H", # 7. The user can use this asserted state of pcie_done to sample the pcie_con status # to determine if the receiver detection was successful. If(pcie_done_s, NextValue(lane.det_status, pcie_con_s), NextState("DONE") ) ) self.det_fsm.act("DONE", # TN1261 Figure 17 specifies "tdeth" (Transmitter Detect hold time?) but never # elaborates on what value it should take. We currently assume tdeth=0. NextValue(lane.det_valid, 1), NextState("DONE") ) self.specials.dcu0 = Instance("DCUA", #============================ DCU # DCU — power management p_D_MACROPDB = "0b1", p_D_IB_PWDNB = "0b1", # undocumented (required for RX) p_D_TXPLL_PWDNB = "0b1", i_D_FFC_MACROPDB = 1, # DCU — reset i_D_FFC_MACRO_RST = 0, i_D_FFC_DUAL_RST = 0, i_D_FFC_TRST = 0, # DCU — clocking i_D_REFCLKI = self.ref_clk, o_D_FFS_PLOL = tx_lol, p_D_REFCK_MODE = "0b100", # 25x REFCLK p_D_TX_MAX_RATE = "2.5", # 2.5 Gbps p_D_TX_VCO_CK_DIV = "0b000", # DIV/1 p_D_BITCLK_LOCAL_EN = "0b1", # undocumented (PCIe sample code used) # DCU ­— unknown p_D_CMUSETBIASI = "0b00", # begin undocumented (PCIe sample code used) p_D_CMUSETI4CPP = "0d4", p_D_CMUSETI4CPZ = "0d3", p_D_CMUSETI4VCO = "0b00", p_D_CMUSETICP4P = "0b01", p_D_CMUSETICP4Z = "0b101", p_D_CMUSETINITVCT = "0b00", p_D_CMUSETISCL4VCO = "0b000", p_D_CMUSETP1GM = "0b000", p_D_CMUSETP2AGM = "0b000", p_D_CMUSETZGM = "0b100", p_D_SETIRPOLY_AUX = "0b10", p_D_SETICONST_AUX = "0b01", p_D_SETIRPOLY_CH = "0b10", p_D_SETICONST_CH = "0b10", p_D_SETPLLRC = "0d1", p_D_RG_EN = "0b1", p_D_RG_SET = "0b00", # end undocumented # DCU — FIFOs p_D_LOW_MARK = "0d4", p_D_HIGH_MARK = "0d12", #============================ CH0 common # CH0 — protocol p_CH0_PROTOCOL = "PCIE", p_CH0_PCIE_MODE = "0b1", #============================ CH0 receive # CH0 RX ­— power management p_CH0_RPWDNB = "0b1", i_CH0_FFC_RXPWDNB = 1, # CH0 RX ­— reset i_CH0_FFC_RRST = 0, i_CH0_FFC_LANE_RX_RST = 0, # CH0 RX ­— input i_CH0_HDINP = pins.rx_p, i_CH0_HDINN = pins.rx_n, i_CH0_FFC_SB_INV_RX = rx_inv, p_CH0_RTERM_RX = "0d22", # 50 Ohm (wizard value used, does not match D/S) p_CH0_RXIN_CM = "0b11", # CMFB (wizard value used) p_CH0_RXTERM_CM = "0b11", # RX Input (wizard value used) # CH0 RX ­— clocking i_CH0_RX_REFCLK = self.ref_clk, o_CH0_FF_RX_PCLK = self.rx_clk_o, i_CH0_FF_RXI_CLK = self.rx_clk_i, p_CH0_CDR_MAX_RATE = "2.5", # 2.5 Gbps p_CH0_RX_DCO_CK_DIV = "0b000", # DIV/1 p_CH0_RX_GEAR_MODE = "0b1", # 1:2 gearbox p_CH0_FF_RX_H_CLK_EN = "0b1", # enable DIV/2 output clock p_CH0_FF_RX_F_CLK_DIS = "0b1", # disable DIV/1 output clock p_CH0_SEL_SD_RX_CLK = "0b1", # FIFO driven by recovered clock p_CH0_AUTO_FACQ_EN = "0b1", # undocumented (wizard value used) p_CH0_AUTO_CALIB_EN = "0b1", # undocumented (wizard value used) p_CH0_PDEN_SEL = "0b1", # phase detector disabled on LOS p_CH0_DCOATDCFG = "0b00", # begin undocumented (PCIe sample code used) p_CH0_DCOATDDLY = "0b00", p_CH0_DCOBYPSATD = "0b1", p_CH0_DCOCALDIV = "0b010", p_CH0_DCOCTLGI = "0b011", p_CH0_DCODISBDAVOID = "0b1", p_CH0_DCOFLTDAC = "0b00", p_CH0_DCOFTNRG = "0b010", p_CH0_DCOIOSTUNE = "0b010", p_CH0_DCOITUNE = "0b00", p_CH0_DCOITUNE4LSB = "0b010", p_CH0_DCOIUPDNX2 = "0b1", p_CH0_DCONUOFLSB = "0b101", p_CH0_DCOSCALEI = "0b01", p_CH0_DCOSTARTVAL = "0b010", p_CH0_DCOSTEP = "0b11", # end undocumented # CH0 RX — loss of signal o_CH0_FFS_RLOS = rx_los, p_CH0_RLOS_SEL = "0b1", p_CH0_RX_LOS_EN = "0b1", p_CH0_RX_LOS_LVL = "0b100", # Lattice "TBD" (wizard value used) p_CH0_RX_LOS_CEQ = "0b11", # Lattice "TBD" (wizard value used) # CH0 RX — loss of lock o_CH0_FFS_RLOL = rx_lol, # CH0 RX — link state machine i_CH0_FFC_SIGNAL_DETECT = rx_det, o_CH0_FFS_LS_SYNC_STATUS= rx_lsm, p_CH0_ENABLE_CG_ALIGN = "0b1", p_CH0_UDF_COMMA_MASK = "0x3ff", # compare all 10 bits p_CH0_UDF_COMMA_A = "0x283", # K28.5 inverted p_CH0_UDF_COMMA_B = "0x17C", # K28.5 p_CH0_CTC_BYPASS = "0b1", # bypass CTC FIFO p_CH0_MIN_IPG_CNT = "0b11", # minimum interpacket gap of 4 p_CH0_MATCH_4_ENABLE = "0b1", # 4 character skip matching p_CH0_CC_MATCH_1 = "0x1BC", # K28.5 p_CH0_CC_MATCH_2 = "0x11C", # K28.0 p_CH0_CC_MATCH_3 = "0x11C", # K28.0 p_CH0_CC_MATCH_4 = "0x11C", # K28.0 # CH0 RX — data **{"o_CH0_FF_RX_D_%d" % n: self.rx_bus[n] for n in range(self.rx_bus.nbits)}, #============================ CH0 transmit # CH0 TX — power management p_CH0_TPWDNB = "0b1", i_CH0_FFC_TXPWDNB = 1, # CH0 TX ­— reset i_CH0_FFC_LANE_TX_RST = 0, # CH0 TX ­— output o_CH0_HDOUTP = pins.tx_p, o_CH0_HDOUTN = pins.tx_n, p_CH0_TXAMPLITUDE = "0d1000", # 1000 mV p_CH0_RTERM_TX = "0d19", # 50 Ohm p_CH0_TDRV_SLICE0_CUR = "0b011", # 400 uA p_CH0_TDRV_SLICE0_SEL = "0b01", # main data p_CH0_TDRV_SLICE1_CUR = "0b000", # 100 uA p_CH0_TDRV_SLICE1_SEL = "0b00", # power down p_CH0_TDRV_SLICE2_CUR = "0b11", # 3200 uA p_CH0_TDRV_SLICE2_SEL = "0b01", # main data p_CH0_TDRV_SLICE3_CUR = "0b11", # 3200 uA p_CH0_TDRV_SLICE3_SEL = "0b01", # main data p_CH0_TDRV_SLICE4_CUR = "0b11", # 3200 uA p_CH0_TDRV_SLICE4_SEL = "0b01", # main data p_CH0_TDRV_SLICE5_CUR = "0b00", # 800 uA p_CH0_TDRV_SLICE5_SEL = "0b00", # power down # CH0 TX ­— clocking o_CH0_FF_TX_PCLK = self.tx_clk_o, i_CH0_FF_TXI_CLK = self.tx_clk_i, p_CH0_TX_GEAR_MODE = "0b1", # 1:2 gearbox p_CH0_FF_TX_H_CLK_EN = "0b1", # enable DIV/2 output clock p_CH0_FF_TX_F_CLK_DIS = "0b1", # disable DIV/1 output clock # CH0 TX — data **{"o_CH0_FF_TX_D_%d" % n: self.tx_bus[n] for n in range(self.tx_bus.nbits)}, # CH0 DET i_CH0_FFC_PCIE_DET_EN = pcie_det_en, i_CH0_FFC_PCIE_CT = pcie_ct, o_CH0_FFS_PCIE_DONE = pcie_done, o_CH0_FFS_PCIE_CON = pcie_con, ) self.dcu0.attr.add(("LOC", "DCU0")) self.dcu0.attr.add(("CHAN", "CH0")) self.dcu0.attr.add(("BEL", "X42/Y71/DCU"))
// // AppDelegate.swift // KnightTouchBar2000 // // Created by Anthony Da Mota on 08/11/2016. // Copyright © 2016 Anthony Da Mota. All rights reserved. // import Cocoa @NSApplicationMain class AppDelegate: NSObject, NSApplicationDelegate { func applicationDidFinishLaunching(_ aNotification: Notification) { // Insert code here to initialize your application } func applicationWillTerminate(_ aNotification: Notification) { // Insert code here to tear down your application } }
// // ViewController.swift // KnightTouchBar2000 // // Created by Anthony Da Mota on 08/11/2016. // Copyright © 2016 Anthony Da Mota. All rights reserved. // import Cocoa class ViewController: NSViewController { @IBOutlet weak var scannerCheckbox: NSButton! @IBOutlet weak var kittCar: NSImageView! let scannerSound = NSSound(named: "KITT_scanner") override func viewDidLoad() { super.viewDidLoad() self.view.wantsLayer = true kittCar.image = NSImage(named: "kitt_car.gif") kittCar.frame = CGRect(x: 0, y: 0, width: 400, height: 300) kittCar.animates = true scannerSound?.loops = true isScannerChecked() } @IBAction func setScannerMusic(_ sender: Any) { isScannerChecked() } func isScannerChecked() { switch scannerCheckbox.state { case NSControl.StateValue.on: scannerCheckbox.title = "Scanner sound on" scannerSound?.play() default: scannerCheckbox.title = "Scanner sound off" scannerSound?.stop() } } override var representedObject: Any? { didSet { // Update the view, if already loaded. } } override func awakeFromNib() { if self.view.layer != nil { let bgColor: CGColor = NSColor(red: 0.988, green: 0.296, blue: 0.312, alpha: 1).cgColor self.view.layer?.backgroundColor = bgColor } } }
// // ToucharBarController.swift // KnightTouchBar2000 // // Created by Anthony Da Mota on 08/11/2016. // Copyright © 2016 Anthony Da Mota. All rights reserved. // import Cocoa @available(OSX 10.12.2, *) fileprivate extension NSTouchBar.CustomizationIdentifier { static let knightTouchBar = NSTouchBar.CustomizationIdentifier("com.AnthonyDaMota.KnightTouchBar2000") } @available(OSX 10.12.2, *) fileprivate extension NSTouchBarItem.Identifier { static let knightRider = NSTouchBarItem.Identifier("knightRider") } @available(OSX 10.12.1, *) class TouchBarController: NSWindowController, NSTouchBarDelegate, CAAnimationDelegate { let theKnightView = NSView() override func windowDidLoad() { super.windowDidLoad() } @available(OSX 10.12.2, *) override func makeTouchBar() -> NSTouchBar? { let touchBar = NSTouchBar() touchBar.delegate = self touchBar.customizationIdentifier = NSTouchBar.CustomizationIdentifier.knightTouchBar touchBar.defaultItemIdentifiers = [.knightRider] touchBar.customizationAllowedItemIdentifiers = [.knightRider] return touchBar } @available(OSX 10.12.2, *) func touchBar(_ touchBar: NSTouchBar, makeItemForIdentifier identifier: NSTouchBarItem.Identifier) -> NSTouchBarItem? { let wholeTouchBar = NSCustomTouchBarItem(identifier: identifier) switch identifier { case NSTouchBarItem.Identifier.knightRider: self.theKnightView.wantsLayer = true let theLEDs = CAShapeLayer() var between: Double = 12.5 for item in 0...86 { let aLEDLeft = createLED(x: between+(2.5*Double(item)), y: 7.5, width: 12.5, height: 15, xRadius: 2.0, yRadius: 2.0) let aLEDRight = createLED(x: between+(2.5*Double(item)), y: 7.5, width: 12.5, height: 15, xRadius: 2.0, yRadius: 2.0) theLEDs.addSublayer(aLEDLeft) theLEDs.addSublayer(aLEDRight) let theLEDAnimLeft = createAnim( duration: 2, delay: CACurrentMediaTime() + 0.023255814*Double(item), values: [0, 1, 0.00001, 0.0002, 0], keyTimes: [0, 0.125, 0.25, 0.375, 1], reverses: false) aLEDLeft.add(theLEDAnimLeft, forKey: "opacity") let theLEDAnimRight = createAnim( duration: 2, delay: 1+(CACurrentMediaTime() + 0.023255814*Double(43-item)), values: [0, 1, 0.00001, 0.0002, 0], keyTimes: [0, 0.125, 0.25, 0.375, 1], reverses: false) aLEDRight.add(theLEDAnimRight, forKey: "opacity") between += 12.5 } theKnightView.layer?.addSublayer(theLEDs) wholeTouchBar.view = theKnightView return wholeTouchBar default: return nil } } func createLED(x: Double, y: Double, width: Double, height: Double, xRadius: CGFloat, yRadius: CGFloat) -> CAShapeLayer { let aLED = CAShapeLayer() // LED shape let aLEDRect = CGRect(x: x, y: y, width: width, height: height) aLED.path = NSBezierPath(roundedRect: aLEDRect, xRadius: xRadius, yRadius: yRadius).cgPath aLED.opacity = 0 aLED.fillColor = NSColor.red.cgColor // LED color glow aLED.shadowColor = NSColor.red.cgColor aLED.shadowOffset = CGSize.zero aLED.shadowRadius = 6.0 aLED.shadowOpacity = 1.0 return aLED } func createAnim(duration: CFTimeInterval, delay: CFTimeInterval, values: [NSNumber], keyTimes: [NSNumber], reverses: Bool) -> CAKeyframeAnimation { let theLEDAnim = CAKeyframeAnimation(keyPath: "opacity") theLEDAnim.duration = duration theLEDAnim.beginTime = delay theLEDAnim.values = values theLEDAnim.keyTimes = keyTimes theLEDAnim.autoreverses = reverses theLEDAnim.repeatCount = .infinity theLEDAnim.delegate = self return theLEDAnim } } // Apple puts that code in the docs instead of just adding a CGPath accessor to NSBezierPath // From: http://stackoverflow.com/questions/1815568/how-can-i-convert-nsbezierpath-to-cgpath/39385101#39385101 extension NSBezierPath { public var cgPath: CGPath { let path = CGMutablePath() var points = [CGPoint](repeating: .zero, count: 3) for i in 0 ..< self.elementCount { let type = self.element(at: i, associatedPoints: &points) switch type { case .moveTo: path.move(to: points[0]) case .lineTo: path.addLine(to: points[0]) case .curveTo: path.addCurve(to: points[2], control1: points[0], control2: points[1]) case .closePath: path.closeSubpath() @unknown default: fatalError() } } return path } }
#!/bin/sh set -eux ROOT="$(dirname "$0")" PATH="$PATH:$HOME/.local/bin" error () { echo "ERROR: $@" >&2; exit 1; } cppcheck --error-exitcode=1 \ --enable=warning,performance,portability,unusedFunction,missingInclude \ --suppress=unusedFunction:"$ROOT/src/macros.h" --suppress=missingIncludeSystem \ "$ROOT"/src/*.[ch] cpplint --counting=detailed --recursive "$ROOT"/src grep -RF $'\t' "$ROOT"/src && error 'Tabs found. Use spaces.' || echo 'Whitespace OK' grep -RP '[^[:cntrl:][:print:]]' "$ROOT"/src && error 'No emojis.' || echo 'Emojis OK'
#!/bin/bash # If man had changed, rebuild its HTML and push to gh-pages set -eu [ "$GH_PASSWORD" ] || exit 12 head=$(git rev-parse HEAD) git clone -b gh-pages "https://kernc:$GH_PASSWORD@github.com/$GITHUB_REPOSITORY.git" gh-pages groff -wall -mandoc -Thtml doc/xsuspender.1 > gh-pages/xsuspender.1.html cd gh-pages ANALYTICS="<script>window.ga=window.ga||function(){(ga.q=ga.q||[]).push(arguments)};ga.l=+new Date;ga('create','UA-43663477-3','auto');ga('require','cleanUrlTracker',{indexFilename:'index.html',trailingSlash:'add'});ga('require','outboundLinkTracker',{events:['click','auxclick','contextmenu']});ga('require', 'maxScrollTracker');ga('require', 'pageVisibilityTracker');ga('send', 'pageview');setTimeout(function(){ga('send','event','pageview','view')},15000);</script><script async src='https://www.google-analytics.com/analytics.js'></script><script async src='https://cdnjs.cloudflare.com/ajax/libs/autotrack/2.4.1/autotrack.js'></script>" sed -i "s#</body>#$ANALYTICS</body>#i" xsuspender.1.html git add * git diff --staged --quiet && echo "$0: No changes to commit." && exit 0 if ! git config user.name; then git config user.name 'github-actions' git config user.email '41898282+github-actions[bot]@users.noreply.github.com' fi git commit -am "CI: Update xsuspender.1 from ${GITHUB_REF#refs/tags/} ($head)" git push
#include "events.h" #include <glib.h> #include <libwnck/libwnck.h> #include <sys/param.h> #include <time.h> #include "entry.h" #include "macros.h" void xsus_init_event_handlers () { WnckScreen *screen = wnck_handle_get_default_screen (handle); g_signal_connect (screen, "active-window-changed", G_CALLBACK (on_active_window_changed), NULL); // Periodically run handler tending to the suspension queue g_timeout_add_seconds_full ( G_PRIORITY_LOW, SUSPEND_PENDING_INTERVAL, on_suspend_pending_windows, NULL, NULL); // Periodically resume windows for a while so they get "up to date" g_timeout_add_seconds_full ( G_PRIORITY_LOW, PERIODIC_RESUME_INTERVAL, on_periodic_window_wake_up, NULL, NULL); // Periodically check if we're on battery power g_timeout_add_seconds_full ( G_PRIORITY_LOW, SLOW_INTERVAL, on_check_battery_powered, NULL, NULL); } static WnckWindow* get_main_window (WnckWindow *window) { if (! WNCK_IS_WINDOW (window)) return NULL; // Resolve transient (dependent, dialog) windows WnckWindow *parent; while ((parent = wnck_window_get_transient (window))) window = parent; // Ensure window is of correct type WnckWindowType type = wnck_window_get_window_type (window); if (type == WNCK_WINDOW_NORMAL || type == WNCK_WINDOW_DIALOG) return window; return NULL; } static inline gboolean windows_are_same_process (WnckWindow *w1, WnckWindow *w2) { // Consider windows to be of the same process when they // are one and the same window, if (w1 == w2) return TRUE; // Or when they have the same PID, map to the same rule, // and the rule says that signals should be sent. Rule *rule; return (WNCK_IS_WINDOW (w1) && WNCK_IS_WINDOW (w2) && wnck_window_get_pid (w1) == wnck_window_get_pid (w2) && (rule = xsus_window_get_rule (w1)) && rule->send_signals && rule == xsus_window_get_rule (w2)); } void on_active_window_changed (WnckScreen *screen, WnckWindow *prev_active_window) { WnckWindow *active_window = wnck_screen_get_active_window (screen); active_window = get_main_window (active_window); prev_active_window = get_main_window (prev_active_window); // Main windows are one and the same; do nothing if (windows_are_same_process (active_window, prev_active_window)) return; // Resume the active window if it was (to be) suspended if (active_window) xsus_window_resume (active_window); // Maybe suspend previously active window if (prev_active_window) xsus_window_suspend (prev_active_window); } static inline pid_t window_entry_get_pid (WindowEntry *entry) { WnckWindow *window = wnck_handle_get_window (handle, entry->xid); return window && wnck_window_get_pid (window) == entry->pid ? entry->pid : 0; } int on_suspend_pending_windows () { time_t now = time (NULL); GSList *l = queued_entries; while (l) { GSList *next = l->next; WindowEntry *entry = l->data; if (now >= entry->suspend_timestamp) { queued_entries = g_slist_delete_link (queued_entries, l); // Follow through with suspension. // This is safe even without ensuring `window_entry_get_pid (entry)` // because the OS simply won't will invalid PIDs, and we let the // exec_suspend= scripts run. // This fixes a bug where the app window minimizes to system tray, // making `wnck_window_get_pid` return invalid PID for an obviously // non-existent window, but the process/PID is still there, // letting us kill it. // In this configuration with systray, it is important to have // low resume_every= values to be able to get the iconified app back up! xsus_signal_stop (entry); } l = next; } return TRUE; } int on_periodic_window_wake_up () { time_t now = time (NULL); GSList *l = suspended_entries; while (l) { WindowEntry *entry = l->data; l = l->next; // Is it time to resume the process? if (entry->rule->resume_every && now - entry->suspend_timestamp >= entry->rule->resume_every) { g_debug ("Periodic awaking %#lx (%d) for %d seconds", entry->xid, entry->pid, entry->rule->resume_for); // Re-schedule suspension if window is still alive if (window_entry_get_pid (entry)) { // Make a copy because continuing below frees the entry WindowEntry *copy = xsus_window_entry_copy (entry); xsus_window_entry_enqueue (copy, entry->rule->resume_for); } xsus_signal_continue (entry); } } return TRUE; } static inline Rule* main_window_get_rule (WnckWindow *window) { return window == get_main_window (window) ? xsus_window_get_rule (window) : NULL; } static void iterate_windows_kill_matching () { WnckScreen *screen = wnck_handle_get_default_screen (handle); WnckWindow *active = wnck_screen_get_active_window (screen); for (GList *w = wnck_screen_get_windows (screen); w ; w = w->next) { WnckWindow *window = w->data; Rule *rule = main_window_get_rule (window); // Skip non-matching windows if (! rule) continue; // Skip currently focused window if (active != NULL && windows_are_same_process (window, active)) continue; // On battery, auto-suspend windows that allow it if (is_battery_powered && rule->auto_on_battery) { // Do nothing if we're already keeping track of this window if (xsus_entry_find_for_window_rule (window, rule, queued_entries) || xsus_entry_find_for_window_rule (window, rule, suspended_entries)) continue; // Otherwise, schedule the window for suspension shortly WindowEntry *entry = xsus_window_entry_new (window, rule); xsus_window_entry_enqueue (entry, rule->resume_for); // On AC, don't auto-resume windows that want to be suspended also // when on AC, e.g. VirtualBox with Windos } else if (!is_battery_powered && rule->only_on_battery) { xsus_window_resume (window); } } } static gboolean is_on_ac_power () { #ifdef __linux__ // Read AC power state from /sys/class/power_supply/*/online (== 1 on AC). // Should work in most cases. See: https://bugs.debian.org/473629 const char *DIRNAME = "/sys/class/power_supply"; const char *basename; g_autoptr (GError) err = NULL; g_autoptr (GDir) dir = g_dir_open (DIRNAME, 0, &err); if (err) { g_warning ("Cannot read battery/AC status: %s", err->message); return FALSE; } while ((basename = g_dir_read_name (dir))) { if (g_str_has_prefix (basename, "hid")) continue; // Skip HID devices, GH-38 g_autofree char *filename = g_build_filename (DIRNAME, basename, "online", NULL); g_autofree char *contents = NULL; if (! g_file_get_contents (filename, &contents, NULL, NULL)) continue; if (g_strcmp0 (g_strstrip (contents), "1") == 0) return TRUE; } return FALSE; #elif defined(__unix__) && defined(BSD) && !defined(__APPLE__) // On *BSD, run `apm -a` which returns '1' when AC is online g_autoptr (GError) err = NULL; g_autofree char *standard_output = NULL; char *argv[] = {"apm", "-a", NULL}; g_spawn_sync (NULL, argv, NULL, G_SPAWN_SEARCH_PATH | G_SPAWN_STDERR_TO_DEV_NULL, NULL, NULL, &standard_output, NULL, NULL, &err); if (err) g_warning ("Unexpected `apm -a` execution error: %s", err->message); return standard_output && 0 == g_strcmp0 (g_strstrip (standard_output), "1"); #else #warning "No battery / AC status support for your platform." #warning "Defaulting to as if 'always on battery' behavior. Patches welcome!" return FALSE; #endif } static inline gboolean any_rule_downclocks () { for (int i = 0; rules[i]; ++i) if (rules[i]->downclock_on_battery) return TRUE; return FALSE; } static void stop_downclocking (); int on_check_battery_powered () { gboolean previous_state = is_battery_powered; is_battery_powered = ! is_on_ac_power (); // On battery state change, suspend / resume matching windows if (previous_state != is_battery_powered) { g_debug ("AC power = %d; State changed. Suspending/resuming windows.", ! is_battery_powered); iterate_windows_kill_matching (); // If downclocking is enabled, also start/stop doing that if (any_rule_downclocks()) { if (is_battery_powered) { g_timeout_add_full ( G_PRIORITY_HIGH_IDLE, FAST_INTERVAL_MSEC, on_downclock_slice, NULL, NULL); g_timeout_add_seconds_full ( G_PRIORITY_LOW, SLOW_INTERVAL, on_update_downclocked_processes, NULL, NULL); on_update_downclocked_processes (); } else{ stop_downclocking (); } } } return TRUE; } typedef struct DownclockPair { WindowEntry *entry; guint32 counter; } DownclockPair; // Downclocked processes (configured with downclock_on_battery > 0) are // periodically sent STOP and CONT in short time slices. These two lists // of DownclockPair track them. static GList *downclock_suspended = NULL; static GSList *downclock_running = NULL; // Simple counter of allocated time slices; avoids querying sub-second time static guint32 downclock_slice_counter = 0; static inline DownclockPair* downclock_pair_new (WnckWindow *window, Rule *rule) { DownclockPair *pair = g_malloc (sizeof (DownclockPair)); pair->entry = xsus_window_entry_new (window, rule); pair->counter = downclock_slice_counter; return pair; } int on_downclock_slice () { if (! is_battery_powered) return FALSE; downclock_slice_counter ++; // Suspend processes that have ran for the past time slice for (GSList *l = downclock_running; l; l = l->next) { DownclockPair *pair = l->data; WindowEntry *entry = pair->entry; pid_t pid = window_entry_get_pid (entry); if (! pid) continue; // Suspend the process kill (pid, SIGSTOP); // Signal to raise after so-many time slices pair->counter = downclock_slice_counter + entry->rule->downclock_on_battery; // Put in "suspended" queue downclock_suspended = g_list_prepend (downclock_suspended, pair); } g_slist_free (downclock_running); downclock_running = NULL; // Resume processes that have been sleeping for the past few time slices GList *l = downclock_suspended; while (l) { GList *next = l->next; DownclockPair *pair = l->data; if (downclock_slice_counter >= pair->counter) { downclock_suspended = g_list_delete_link (downclock_suspended, l); WindowEntry *entry = pair->entry; pid_t pid = window_entry_get_pid (entry); if (! pid) continue; // Only downclock-resume the current process if it's not already // fully suspended by the other mechanism WnckWindow *window = wnck_handle_get_window (handle, entry->xid); if (! entry->rule->send_signals || ! xsus_entry_find_for_window_rule (window, entry->rule, suspended_entries)) kill (pid, SIGCONT); downclock_running = g_slist_prepend (downclock_running, pair); } l = next; } return TRUE; } int on_update_downclocked_processes () { if (! is_battery_powered) return FALSE; // A set of PIDs of already downclocked processes g_autoptr (GHashTable) old_pids = g_hash_table_new (g_direct_hash, g_direct_equal); // A set of PIDs that will become downclocked in the current function invocation g_autoptr (GHashTable) new_pids = g_hash_table_new (g_direct_hash, g_direct_equal); // Fill the set of known PIDs for (GSList *l = downclock_running; l; l = l->next) g_hash_table_add (old_pids, GINT_TO_POINTER (((DownclockPair*) l->data)->entry->pid)); for (GList *l = downclock_suspended; l; l = l->next) g_hash_table_add (old_pids, GINT_TO_POINTER (((DownclockPair*) l->data)->entry->pid)); // Iterate over all windows and find processes to downclock WnckScreen *screen = wnck_handle_get_default_screen (handle); for (GList *w = wnck_screen_get_windows (screen); w ; w = w->next) { WnckWindow *window = w->data; Rule *rule = main_window_get_rule (window); // Skip non-matching windows if (! rule || ! rule->downclock_on_battery) continue; // Skip any windows/PIDs we already know about pid_t pid = wnck_window_get_pid (window); if (g_hash_table_contains (old_pids, GINT_TO_POINTER (pid)) || g_hash_table_contains (new_pids, GINT_TO_POINTER (pid))) continue; g_hash_table_add (new_pids, GINT_TO_POINTER (pid)); // Begin downclocking the process DownclockPair *pair = downclock_pair_new (window, rule); g_debug ("Downclocking %#lx (%d): %s", pair->entry->xid, pair->entry->pid, pair->entry->wm_name); downclock_running = g_slist_prepend (downclock_running, pair); } return TRUE; } static void stop_downclocking () { // Resume downclocked processes for (GList *l = downclock_suspended; l; l = l->next) { WindowEntry *entry = ((DownclockPair*) l->data)->entry; g_debug ("Normal-clocking %#lx (%d): %s", entry->xid, entry->pid, entry->wm_name); kill (entry->pid, SIGCONT); } // Free entries for (GSList *l = downclock_running; l; l = l->next) xsus_window_entry_free (((DownclockPair*) l->data)->entry); for (GList *l = downclock_suspended; l; l = l->next) xsus_window_entry_free (((DownclockPair*) l->data)->entry); g_slist_free (downclock_running); g_list_free (downclock_suspended); downclock_running = NULL; downclock_suspended = NULL; } void xsus_exit_event_handlers () { stop_downclocking (); }
#include "entry.h" #include <glib.h> #include <libwnck/libwnck.h> WindowEntry* xsus_window_entry_new (WnckWindow *window, Rule *rule) { WindowEntry *entry = g_malloc (sizeof (WindowEntry)); entry->rule = rule; entry->pid = wnck_window_get_pid (window); entry->xid = wnck_window_get_xid (window); entry->wm_name = g_strdup (wnck_window_get_name (window)); return entry; } WindowEntry* xsus_window_entry_copy (WindowEntry *entry) { WindowEntry *copy = g_memdup2 (entry, sizeof (WindowEntry)); copy->wm_name = g_strdup (copy->wm_name); return copy; } void xsus_window_entry_free (WindowEntry *entry) { if (! entry) return; g_free (entry->wm_name); g_free (entry); } inline WindowEntry* xsus_entry_find_for_window_rule (WnckWindow *window, Rule *rule, GSList *list) { // If suspending by signals, find entry by PID ... if (rule->send_signals) { pid_t pid = wnck_window_get_pid (window); for (; list; list = list->next) { WindowEntry *entry = list->data; if (entry->pid == pid) return entry; } } else { // ... else find it by XID XID xid = wnck_window_get_xid (window); for (; list; list = list->next) { WindowEntry *entry = list->data; if (entry->xid == xid) return entry; } } return NULL; }
#include "exec.h" #include <string.h> #include <signal.h> #include <sys/types.h> #include "macros.h" static inline int execute (char **argv, char **envp, char **standard_output) { g_autoptr (GError) err = NULL; gint exit_status = -1; GSpawnFlags flags = G_SPAWN_STDERR_TO_DEV_NULL | (standard_output ? G_SPAWN_DEFAULT : G_SPAWN_STDOUT_TO_DEV_NULL); g_spawn_sync (NULL, argv, envp, flags | G_SPAWN_SEARCH_PATH, NULL, NULL, standard_output, NULL, &exit_status, &err); if (err) g_warning ("Unexpected subprocess execution error: %s", err->message); return exit_status; } int xsus_exec_subprocess (char **argv, WindowEntry *entry) { if (! argv) return 0; // Provide window data to subprocess via the environment char *envp[] = { g_strdup_printf ("PID=%d", entry->pid), g_strdup_printf ("XID=%#lx", entry->xid), g_strdup_printf ("WM_NAME=%s", entry->wm_name), g_strdup_printf ("PATH=%s", g_getenv ("PATH")), g_strdup_printf ("LC_ALL=C"), // Speeds up locale-aware shell utils NULL }; // Execute and return result g_debug ("Exec %#lx (%d): %s", entry->xid, entry->pid, argv[2]); int exit_status = execute (argv, envp, NULL); g_debug ("Exit status: %d", exit_status); // Free envp char **e = envp; while (*e) g_free(*e++); return exit_status; } static void kill_recursive (char* pid_str, int signal, char* cmd_pattern) { // Pgrep children char *argv[] = {"pgrep", "-fP", pid_str, cmd_pattern, NULL}; g_autofree char *standard_output = NULL; execute (argv, NULL, &standard_output); if (! standard_output || 0 == strlen(g_strstrip (standard_output))) return; // No children standard_output = g_strdelimit(standard_output, "\n", ' '); g_debug (" kill -%s %s", signal == SIGSTOP ? "STOP" : "CONT", standard_output); // Kill children and recurse g_auto (GStrv) child_pids = g_strsplit (standard_output, " ", 0); for (int i = 0; child_pids[i]; ++i) { pid_t child_pid = g_ascii_strtoll (child_pids[i], NULL, 10); kill (child_pid, signal); kill_recursive (child_pids[i], signal, cmd_pattern); } } void xsus_kill_subtree (pid_t pid, int signal, char *cmd_pattern) { if (! cmd_pattern) return; g_assert (signal == SIGSTOP || signal == SIGCONT); g_debug ("Exec: pstree %d (%s) | kill -%s", pid, cmd_pattern, signal == SIGSTOP ? "STOP" : "CONT"); g_debug (" kill -%s %d", signal == SIGSTOP ? "STOP" : "CONT", pid); kill (pid, signal); char pid_str[11]; g_snprintf ((char*) &pid_str, sizeof (pid_str), "%d", pid); kill_recursive (pid_str, signal, cmd_pattern); }
#include "xsuspender.h" #include <signal.h> #include <stdio.h> #include <stdlib.h> #include <time.h> #include <glib.h> #include <libwnck/libwnck.h> #include "config.h" #include "entry.h" #include "events.h" #include "exec.h" #include "macros.h" #include "rule.h" static GMainLoop *loop; WnckHandle *handle; gboolean is_battery_powered; GSList *suspended_entries; GSList *queued_entries; Rule **rules; gboolean xsus_signal_stop (WindowEntry *entry) { Rule *rule = entry->rule; // Run the windows' designated exec_suspend script, if any. // If the subprocess fails, exit early without stopping the process. if (xsus_exec_subprocess (rule->exec_suspend, entry) != 0) { g_debug ("Subprocess failed; not stopping the process."); return FALSE; } // Mark the process as suspended and kill it g_debug ("kill -STOP %d", entry->pid); suspended_entries = g_slist_prepend (suspended_entries, entry); if (rule->send_signals) { kill (entry->pid, SIGSTOP); xsus_kill_subtree (entry->pid, SIGSTOP, rule->subtree_pattern); } return TRUE; } gboolean xsus_signal_continue (WindowEntry *entry) { Rule *rule = entry->rule; // Run the window's designated exec_resume script, if any. // If the subprocess fails, continue the process anyway. Cause what were // you going to do with a stuck process??? if (xsus_exec_subprocess (rule->exec_resume, entry) != 0) g_debug ("Subprocess failed; resuming the process anyway."); // Mark the process as not suspended and kill it g_debug ("kill -CONT %d", entry->pid); suspended_entries = g_slist_remove (suspended_entries, entry); if (rule->send_signals) { // Resume subprocesses before parent process to avoid the parent // workers manager considering them "stuck" (cf. Firefox) xsus_kill_subtree (entry->pid, SIGCONT, rule->subtree_pattern); kill (entry->pid, SIGCONT); } // Free the entry now xsus_window_entry_free (entry); return TRUE; } void xsus_window_entry_enqueue (WindowEntry *entry, unsigned delay) { // Mark the time of suspension entry->suspend_timestamp = time (NULL) + delay; // Schedule suspension queued_entries = g_slist_prepend (queued_entries, entry); } void xsus_window_resume (WnckWindow *window) { Rule *rule = xsus_window_get_rule (window); // No matching configuration rule, window was not suspended if (! rule) return; WindowEntry *entry; // Remove the process from the pending queue if ((entry = xsus_entry_find_for_window_rule (window, rule, queued_entries))) { g_debug ("Removing window %#lx (%d) from suspension queue: %s", wnck_window_get_xid (window), wnck_window_get_pid (window), wnck_window_get_name (window)); queued_entries = g_slist_remove (queued_entries, entry); xsus_window_entry_free (entry); return; } // Continue the process if it was actually stopped if ((entry = xsus_entry_find_for_window_rule (window, rule, suspended_entries))) { g_debug ("Resuming window %#lx (%d): %s", wnck_window_get_xid (window), wnck_window_get_pid (window), wnck_window_get_name (window)); xsus_signal_continue (entry); return; } } void xsus_window_suspend (WnckWindow *window) { Rule *rule = xsus_window_get_rule (window); // No matching configuration rule, nothing to suspend if (! rule) return; // Rule only applies on battery power and we are not if (! is_battery_powered && rule->only_on_battery) return; // We shouldn't be having an entry for this window in the queues already ... #ifndef NDEBUG g_assert (! xsus_entry_find_for_window_rule (window, rule, suspended_entries)); g_assert (! xsus_entry_find_for_window_rule (window, rule, queued_entries)); #endif // Schedule window suspension g_debug ("Suspending window in %ds: %#lx (%d): %s", rule->delay, wnck_window_get_xid (window), wnck_window_get_pid (window), wnck_window_get_name (window)); WindowEntry *entry = xsus_window_entry_new (window, rule); xsus_window_entry_enqueue (entry, rule->delay); } int xsus_init () { g_debug ("Initializing."); handle = wnck_handle_new (WNCK_CLIENT_TYPE_PAGER); // Nowadays common to have a single screen which combines several physical // monitors. So it's ok to take the default. See: // https://developer.gnome.org/libwnck/stable/WnckScreen.html#WnckScreen.description // https://developer.gnome.org/gdk4/stable/GdkScreen.html#GdkScreen.description if (! wnck_handle_get_default_screen (handle)) g_critical ("Default screen is NULL. Not an X11 system? Too bad."); // Parse the configuration files rules = parse_config (); is_battery_powered = FALSE; // Init entry lists suspended_entries = NULL; queued_entries = NULL; xsus_init_event_handlers (); // Install exit signal handlers to exit gracefully signal (SIGINT, xsus_exit); signal (SIGTERM, xsus_exit); signal (SIGABRT, xsus_exit); // Don't call this function again, we're done return FALSE; } void xsus_exit () { // Quit the main loop and thus, hopefully, exit g_debug ("Exiting ..."); g_main_loop_quit (loop); } static inline void cleanup () { wnck_shutdown (); // Resume processes we have suspended; deallocate window entries GSList *l = suspended_entries; while (l) { WindowEntry *entry = l->data; l = l->next; xsus_signal_continue (entry); } for (GSList *e = queued_entries; e; e = e->next) xsus_window_entry_free (e->data); g_slist_free (suspended_entries); g_slist_free (queued_entries); // Resume downclocked processes xsus_exit_event_handlers (); // Delete rules for (int i = 0; rules[i]; ++i) xsus_rule_free (rules[i]); g_free (rules); } static void parse_args (int *argc, char **argv[]) { g_autoptr (GOptionContext) context = g_option_context_new (NULL); g_option_context_set_help_enabled (context, FALSE); g_option_context_set_summary (context, "Automatically suspend inactive (unfocused) X11 windows (processes)\n" "to save battery life. (v" PROJECT_VERSION ")"); g_option_context_set_description (context, "The program looks for configuration in ~/.config/xsuspender.conf.\n" "Example provided in " EXAMPLE_CONF ".\n" "You can copy it over and adapt it to taste.\n" "\n" "To debug new configuration before it is put into use (recommended),\n" "set environment variable G_MESSAGES_DEBUG=xsuspender, i.e.:\n" "\n" " G_MESSAGES_DEBUG=xsuspender xsuspender\n" "\n" "To daemonize the program, run it as:\n" "\n" " nohup xsuspender >/dev/null & disown\n" "\n" "or, better yet, ask your X session manager to run it for you.\n" "\n" "Read xsuspender(1) manual for more information."); if (! g_option_context_parse (context, argc, argv, NULL)) { printf ("%s", g_option_context_get_help (context, TRUE, NULL)); exit (EXIT_FAILURE); } } int main (int argc, char *argv[]) { // Parse command line arguments gdk_init (&argc, &argv); parse_args (&argc, &argv); // Make g_critical() always exit g_log_set_always_fatal (G_LOG_LEVEL_CRITICAL); // Delay initialization until we're within the loop g_timeout_add (1, xsus_init, NULL); // Enter the main loop loop = g_main_loop_new (NULL, FALSE); g_main_loop_run (loop); g_main_loop_unref (loop); cleanup (); g_debug ("Bye."); return EXIT_SUCCESS; }
#include "config.h" #include <stdlib.h> #include <glib.h> #include "rule.h" #include "macros.h" static gboolean error_encountered = FALSE; static gboolean is_error (GError **err) { if (g_error_matches (*err, G_KEY_FILE_ERROR, G_KEY_FILE_ERROR_INVALID_VALUE)) { g_warning ("Error parsing config: %s", (*err)->message); error_encountered = TRUE; } if (*err) { g_error_free (*err); *err = NULL; return TRUE; } return FALSE; } static char** parse_command (GKeyFile *file, char *section, char *key, GError **err) { g_autofree char *value = g_key_file_get_value (file, section, key, err); if (! value) return NULL; char **argv = NULL; // Empty command is same as no command value = g_strstrip (value); if (g_strcmp0 (value, "") != 0) { // Pass everything to /bin/sh as this is the most convenient for scripting char *args[4] = {"sh", "-c", value, NULL}; argv = g_strdupv (args); } return argv; } static void reassign_strv (char ***existing, char **replacement) { // This can be simple because the rest is done in parse_command() g_strfreev (*existing); *existing = replacement; } static void reassign_str (char **existing, char *replacement) { // If the key was missing, GError should catch it. // Perhaps an empty one, but replacement is definitely a string. g_assert (replacement != NULL); // Free the previous value g_free (*existing); *existing = NULL; // If replacement is a non-empty string, use it if (g_strcmp0 (replacement, "") != 0) *existing = replacement; else // Otherwise, we have no use for it g_free (replacement); } // Remove once glib-2.44+ is ubiquitous #if GLIB_MINOR_VERSION < 44 static inline gboolean g_strv_contains (const gchar *const *strv, const gchar *str) { for (; *strv; strv++) if (g_strcmp0 (str, *strv) == 0) return TRUE; return FALSE; } #endif static void read_section (GKeyFile *file, char *section, Rule *rule) { g_autoptr (GError) err = NULL; int val; val = g_key_file_get_boolean (file, section, CONFIG_KEY_ONLY_ON_BATTERY, &err); if (! is_error (&err)) rule->only_on_battery = (gboolean) val; val = g_key_file_get_boolean (file, section, CONFIG_KEY_AUTO_ON_BATTERY, &err); if (! is_error (&err)) rule->auto_on_battery = (gboolean) val; val = g_key_file_get_boolean (file, section, CONFIG_KEY_SEND_SIGNALS, &err); if (! is_error (&err)) rule->send_signals = (gboolean) val; val = g_key_file_get_integer (file, section, CONFIG_KEY_SUSPEND_DELAY, &err); if (! is_error (&err)) rule->delay = (guint16) CLAMP (val, 1, G_MAXUINT16); val = g_key_file_get_integer (file, section, CONFIG_KEY_RESUME_EVERY, &err); if (! is_error (&err)) rule->resume_every = (guint16) (val ? CLAMP (val, 1, G_MAXUINT16) : 0); val = g_key_file_get_integer (file, section, CONFIG_KEY_RESUME_FOR, &err); if (! is_error (&err)) rule->resume_for = (guint16) CLAMP (val, 1, G_MAXUINT16); val = g_key_file_get_integer (file, section, CONFIG_KEY_DOWNCLOCK_ON_BATTERY, &err); if (! is_error (&err)) rule->downclock_on_battery = (guint8) CLAMP (val, 0, 9); char *str; str = g_key_file_get_value (file, section, CONFIG_KEY_WM_CLASS_CONTAINS, &err); if (! is_error (&err)) reassign_str (&rule->needle_wm_class, str); str = g_key_file_get_value (file, section, CONFIG_KEY_WM_CLASS_GROUP_CONTAINS, &err); if (! is_error (&err)) reassign_str (&rule->needle_wm_class_group, str); str = g_key_file_get_value (file, section, CONFIG_KEY_WM_NAME_CONTAINS, &err); if (! is_error (&err)) reassign_str (&rule->needle_wm_name, str); str = g_key_file_get_value (file, section, CONFIG_KEY_SUBTREE_PATTERN, &err); if (! is_error (&err)) reassign_str (&rule->subtree_pattern, str); char **argv; argv = parse_command (file, section, CONFIG_KEY_EXEC_SUSPEND, &err); if (! is_error (&err)) reassign_strv (&rule->exec_suspend, argv); argv = parse_command (file, section, CONFIG_KEY_EXEC_RESUME, &err); if (! is_error (&err)) reassign_strv (&rule->exec_resume, argv); g_assert (err == NULL); // Already freed // Ensure all configuration keys are valid static const char* VALID_KEYS[] = CONFIG_VALID_KEYS; g_auto (GStrv) keys = g_key_file_get_keys (file, section, NULL, NULL); for (int i = 0; keys[i]; ++i) { if (! g_strv_contains (VALID_KEYS, keys[i])) { g_warning ("Invalid key in section '%s': %s", section, keys[i]); error_encountered = TRUE; } } // For non-Default sections, ensure at least one window-matching needle is specified if (g_strcmp0 (section, CONFIG_DEFAULT_SECTION) != 0 && ! rule->needle_wm_name && ! rule->needle_wm_class && ! rule->needle_wm_class_group) { g_warning ("Invalid rule '%s' matches all windows", section); error_encountered = TRUE; } } static void debug_print_rule (Rule *rule) { g_debug ("\n" "needle_wm_class = %s\n" "needle_wm_class_group = %s\n" "needle_wm_name = %s\n" "delay = %d\n" "resume_every = %d\n" "resume_for = %d\n" "only_on_battery = %d\n" "send_signals = %d\n" "subtree_pattern = %s\n" "downclock_on_battery = %d\n" "exec_suspend = %s\n" "exec_resume = %s\n", rule->needle_wm_class, rule->needle_wm_class_group, rule->needle_wm_name, rule->delay, rule->resume_every, rule->resume_for, rule->only_on_battery, rule->send_signals, rule->subtree_pattern, rule->downclock_on_battery, (rule->exec_suspend ? rule->exec_suspend[2] : NULL), (rule->exec_resume ? rule->exec_resume[2] : NULL) ); } Rule ** parse_config () { Rule defaults = { .needle_wm_name = NULL, .needle_wm_class = NULL, .needle_wm_class_group = NULL, .exec_suspend = NULL, .exec_resume = NULL, .subtree_pattern = NULL, .downclock_on_battery = 0, .delay = 10, .resume_every = 50, .resume_for = 5, .send_signals = TRUE, .only_on_battery = TRUE, .auto_on_battery = TRUE, }; g_autoptr (GKeyFile) file = g_key_file_new (); g_autoptr (GError) err = NULL; g_autofree char *path = g_build_path ("/", g_get_user_config_dir (), CONFIG_FILE_NAME, NULL); g_key_file_load_from_file (file, path, G_KEY_FILE_NONE, &err); if (err) g_critical ("Cannot read configuration file '%s': %s", path, err->message); // Process Default section gboolean has_default_section = g_key_file_has_group (file, CONFIG_DEFAULT_SECTION); if (has_default_section) read_section (file, CONFIG_DEFAULT_SECTION, &defaults); // Read all other sections (rules) gsize n_sections = 0; g_auto (GStrv) sections = g_key_file_get_groups (file, &n_sections); n_sections -= has_default_section; if (n_sections <= 0) g_critical ("No configuration rules found. Nothing to do. Exiting."); Rule **rules = g_malloc0_n (n_sections + 1, sizeof (Rule*)), **ptr = rules; for (int i = 0; sections[i]; ++i) { // Skip Default section; it was already handled above if (g_strcmp0 (sections[i], CONFIG_DEFAULT_SECTION) == 0) continue; Rule *rule = xsus_rule_copy (&defaults); read_section (file, sections[i], rule); *ptr++ = rule; } // Debug dump rules in effect for (int i = 0; rules[i]; ++i) debug_print_rule (rules[i]); if (error_encountered) g_critical ("Errors encountered while parsing config. Abort."); return rules; }
#include "rule.h" #include <glib.h> #include <libwnck/libwnck.h> #include "xsuspender.h" Rule* xsus_rule_copy (Rule *orig) { Rule *rule = g_memdup2 (orig, sizeof (Rule)); // Duplicate strings explicitly rule->needle_wm_name = g_strdup (orig->needle_wm_name); rule->needle_wm_class = g_strdup (orig->needle_wm_class); rule->needle_wm_class_group = g_strdup (orig->needle_wm_class_group); rule->exec_suspend = g_strdupv (orig->exec_suspend); rule->exec_resume = g_strdupv (orig->exec_resume); return rule; } void xsus_rule_free (Rule *rule) { g_free (rule->needle_wm_class); g_free (rule->needle_wm_class_group); g_free (rule->needle_wm_name); g_strfreev (rule->exec_suspend); g_strfreev (rule->exec_resume); g_free (rule); } static inline gboolean str_contains (const char *haystack, const char *needle) { if (! needle) return TRUE; if (! haystack) return FALSE; return g_strstr_len (haystack, -1, needle) != NULL; } Rule* xsus_window_get_rule (WnckWindow *window) { if (! WNCK_IS_WINDOW (window)) return NULL; const char *wm_name = wnck_window_get_name (window), *wm_class = wnck_window_get_class_instance_name (window), *wm_class_group = wnck_window_get_class_group_name (window); for (int i = 0; rules[i]; ++i) { Rule *rule = rules[i]; // If all provided matching specifiers match if (str_contains (wm_class_group, rule->needle_wm_class_group) && str_contains (wm_class, rule->needle_wm_class) && str_contains (wm_name, rule->needle_wm_name)) { return rule; } } return NULL; }
# Copyright 2018 Amazon.com, Inc. or its affiliates. All Rights Reserved. # # Permission is hereby granted, free of charge, to any person obtaining a copy of this # software and associated documentation files (the "Software"), to deal in the Software # without restriction, including without limitation the rights to use, copy, modify, # merge, publish, distribute, sublicense, and/or sell copies of the Software, and to # permit persons to whom the Software is furnished to do so. # # THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, # INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A # PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT # HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION # OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE # SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. import os import shutil import zipfile import time from pip._vendor.distlib.compat import raw_input from pynt import task import boto3 import botocore from botocore.exceptions import ClientError import json import re def write_dir_to_zip(src, zf): '''Write a directory tree to an open ZipFile object.''' abs_src = os.path.abspath(src) for dirname, subdirs, files in os.walk(src): for filename in files: absname = os.path.abspath(os.path.join(dirname, filename)) arcname = absname[len(abs_src) + 1:] print('zipping {} as {}'.format(os.path.join(dirname, filename), arcname)) zf.write(absname, arcname) def read_json(jsonf_path): '''Read a JSON file into a dict.''' with open(jsonf_path, 'r') as jsonf: json_text = jsonf.read() return json.loads(json_text) def check_bucket_exists(s3path): s3 = boto3.resource('s3') result = re.search('s3://(.*)/', s3path) bucketname = s3path if result is None else result.group(1) bucket = s3.Bucket(bucketname) exists = True try: s3.meta.client.head_bucket(Bucket=bucketname) except botocore.exceptions.ClientError as e: # If a client error is thrown, then check that it was a 404 error. # If it was a 404 error, then the bucket does not exist. error_code = int(e.response['Error']['Code']) if error_code == 404: exists = False return exists @task() def clean(): '''Clean build directory.''' print('Cleaning build directory...') if os.path.exists('build'): shutil.rmtree('build') os.mkdir('build') @task() def packagelambda(* functions): '''Package lambda functions into a deployment-ready zip files.''' if not os.path.exists('build'): os.mkdir('build') os.chdir("build") if len(functions) == 0: functions = ("athenarunner", "gluerunner", "ons3objectcreated") for function in functions: print('Packaging "{}" lambda function in directory'.format(function)) zipf = zipfile.ZipFile("%s.zip" % function, "w", zipfile.ZIP_DEFLATED) write_dir_to_zip("../lambda/{}/".format(function), zipf) zipf.close() os.chdir("..") return @task() def updatelambda(*functions): '''Directly update lambda function code in AWS (without upload to S3).''' lambda_client = boto3.client('lambda') if len(functions) == 0: functions = ("athenarunner", "gluerunner", "ons3objectcreated") for function in functions: with open('build/%s.zip' % function, 'rb') as zipf: lambda_client.update_function_code( FunctionName=function, ZipFile=zipf.read() ) return @task() def deploylambda(*functions, **kwargs): '''Upload lambda functions .zip file to S3 for download by CloudFormation stack during creation.''' if len(functions) == 0: functions = ("athenarunner", "gluerunner", "ons3objectcreated") region_name = boto3.session.Session().region_name s3_client = boto3.client("s3") print("Reading .lambda/s3-deployment-descriptor.json...") params = read_json("./lambda/s3-deployment-descriptor.json") for function in functions: src_s3_bucket_name = params[function]['ArtifactBucketName'] src_s3_key = params[function]['LambdaSourceS3Key'] if not src_s3_key and not src_s3_bucket_name: print( "ERROR: Both Artifact S3 bucket name and Lambda source S3 key must be specified for function '{}'. FUNCTION NOT DEPLOYED.".format( function)) continue print("Checking if S3 Bucket '{}' exists...".format(src_s3_bucket_name)) if not check_bucket_exists(src_s3_bucket_name): print("Bucket %s not found. Creating in region {}.".format(src_s3_bucket_name, region_name)) if region_name == "us-east-1": s3_client.create_bucket( # ACL="authenticated-read", Bucket=src_s3_bucket_name ) else: s3_client.create_bucket( # ACL="authenticated-read", Bucket=src_s3_bucket_name, CreateBucketConfiguration={ "LocationConstraint": region_name } ) print("Uploading function '{}' to '{}'".format(function, src_s3_key)) with open('build/{}.zip'.format(function), 'rb') as data: s3_client.upload_fileobj(data, src_s3_bucket_name, src_s3_key) return @task() def createstack(* stacks, **kwargs): '''Create stacks using CloudFormation.''' if len(stacks) == 0: print( "ERROR: Please specify a stack to create. Valid values are glue-resources, gluerunner-lambda, step-functions-resources.") return for stack in stacks: cfn_path = "cloudformation/{}.yaml".format(stack) cfn_params_path = "cloudformation/{}-params.json".format(stack) cfn_params = read_json(cfn_params_path) stack_name = stack cfn_file = open(cfn_path, 'r') cfn_template = cfn_file.read(51200) #Maximum size of a cfn template cfn_client = boto3.client('cloudformation') print("Attempting to CREATE '%s' stack using CloudFormation." % stack_name) start_t = time.time() response = cfn_client.create_stack( StackName=stack_name, TemplateBody=cfn_template, Parameters=cfn_params, Capabilities=[ 'CAPABILITY_NAMED_IAM', ], ) print("Waiting until '%s' stack status is CREATE_COMPLETE" % stack_name) try: # cc           +o cfn_stack_delete_waiter = cfn_client.get_waiter('stack_create_complete') cfn_stack_delete_waiter.wait(StackName=stack_name) print("Stack CREATED in approximately %d secs." % int(time.time() - start_t)) except Exception as e: print("Stack creation FAILED.") print(e.message) @task() def updatestack(* stacks, **kwargs): '''Update a CloudFormation stack.''' if len(stacks) == 0: print( "ERROR: Please specify a stack to create. Valid values are glue-resources, gluerunner-lambda, step-functions-resources.") return for stack in stacks: stack_name = stack cfn_path = "cloudformation/{}.yaml".format(stack) cfn_params_path = "cloudformation/{}-params.json".format(stack) cfn_params = read_json(cfn_params_path) cfn_file = open(cfn_path, 'r') cfn_template = cfn_file.read(51200) #Maximum size of a cfn template cfn_client = boto3.client('cloudformation') print("Attempting to UPDATE '%s' stack using CloudFormation." % stack_name) try: start_t = time.time() response = cfn_client.update_stack( StackName=stack_name, TemplateBody=cfn_template, Parameters=cfn_params, Capabilities=[ 'CAPABILITY_NAMED_IAM', ], ) print("Waiting until '%s' stack status is UPDATE_COMPLETE" % stack_name) cfn_stack_update_waiter = cfn_client.get_waiter('stack_update_complete') cfn_stack_update_waiter.wait(StackName=stack_name) print("Stack UPDATED in approximately %d secs." % int(time.time() - start_t)) except ClientError as e: print("EXCEPTION: " + e.response["Error"]["Message"]) @task() def stackstatus(* stacks): '''Check the status of a CloudFormation stack.''' if len(stacks) == 0: stacks = ("glue-resources", "gluerunner-lambda", "step-functions-resources") for stack in stacks: stack_name = stack cfn_client = boto3.client('cloudformation') try: response = cfn_client.describe_stacks( StackName=stack_name ) if response["Stacks"][0]: print("Stack '%s' has the status '%s'" % (stack_name, response["Stacks"][0]["StackStatus"])) except ClientError as e: print("EXCEPTION: " + e.response["Error"]["Message"]) @task() def deletestack(* stacks): '''Delete stacks using CloudFormation.''' if len(stacks) == 0: print("ERROR: Please specify a stack to delete.") return for stack in stacks: stack_name = stack cfn_client = boto3.client('cloudformation') print("Attempting to DELETE '%s' stack using CloudFormation." % stack_name) start_t = time.time() response = cfn_client.delete_stack( StackName=stack_name ) print("Waiting until '%s' stack status is DELETE_COMPLETE" % stack_name) cfn_stack_delete_waiter = cfn_client.get_waiter('stack_delete_complete') cfn_stack_delete_waiter.wait(StackName=stack_name) print("Stack DELETED in approximately %d secs." % int(time.time() - start_t)) @task() def deploygluescripts(**kwargs): '''Upload AWS Glue scripts to S3 for download by CloudFormation stack during creation.''' region_name = boto3.session.Session().region_name s3_client = boto3.client("s3") glue_scripts_path = "./glue-scripts/" glue_cfn_params = read_json("cloudformation/glue-resources-params.json") s3_etl_script_path = '' bucket_name = '' prefix = '' for param in glue_cfn_params: if param['ParameterKey'] == 'ArtifactBucketName': bucket_name = param['ParameterValue'] if param['ParameterKey'] == 'ETLScriptsPrefix': prefix = param['ParameterValue'] if not bucket_name or not prefix: print( "ERROR: ArtifactBucketName and ETLScriptsPrefix must be set in 'cloudformation/glue-resources-params.json'.") return s3_etl_script_path = 's3://' + bucket_name + '/' + prefix result = re.search('s3://(.+?)/(.*)', s3_etl_script_path) if result is None: print("ERROR: Invalid S3 ETL bucket name and/or script prefix.") return print("Checking if S3 Bucket '{}' exists...".format(bucket_name)) if not check_bucket_exists(bucket_name): print("ERROR: S3 bucket '{}' not found.".format(bucket_name)) return for dirname, subdirs, files in os.walk(glue_scripts_path): for filename in files: absname = os.path.abspath(os.path.join(dirname, filename)) print("Uploading AWS Glue script '{}' to '{}/{}'".format(absname, bucket_name, prefix)) with open(absname, 'rb') as data: s3_client.upload_fileobj(data, bucket_name, '{}/{}'.format(prefix, filename)) return @task() def deletes3bucket(name): '''DELETE ALL objects in an Amazon S3 bucket and THE BUCKET ITSELF. Use with caution!''' proceed = raw_input( "This command will DELETE ALL DATA in S3 bucket '%s' and the BUCKET ITSELF.\nDo you wish to continue? [Y/N] " \ % name) if proceed.lower() != 'y': print("Aborting deletion.") return print("Attempting to DELETE ALL OBJECTS in '%s' S3 bucket." % name) s3 = boto3.resource('s3') bucket = s3.Bucket(name) bucket.objects.delete() bucket.delete() return
# Copyright 2018 Amazon.com, Inc. or its affiliates. All Rights Reserved. # # Permission is hereby granted, free of charge, to any person obtaining a copy of this # software and associated documentation files (the "Software"), to deal in the Software # without restriction, including without limitation the rights to use, copy, modify, # merge, publish, distribute, sublicense, and/or sell copies of the Software, and to # permit persons to whom the Software is furnished to do so. # # THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, # INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A # PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT # HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION # OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE # SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. import boto3 import logging, logging.config import json from botocore.client import Config from boto3.dynamodb.conditions import Key, Attr def load_log_config(): # Basic config. Replace with your own logging config if required root = logging.getLogger() root.setLevel(logging.INFO) return root def load_config(): with open('athenarunner-config.json', 'r') as conf_file: conf_json = conf_file.read() return json.loads(conf_json) def is_json(jsonstring): try: json_object = json.loads(jsonstring) except ValueError: return False return True def start_athena_queries(config): ddb_table = dynamodb.Table(config["ddb_table"]) logger.debug('Athena runner started') sfn_activity_arn = config['sfn_activity_arn'] sfn_worker_name = config['sfn_worker_name'] # Loop until no tasks are available from Step Functions while True: logger.debug('Polling for Athena tasks for Step Functions Activity ARN: {}'.format(sfn_activity_arn)) try: response = sfn.get_activity_task( activityArn=sfn_activity_arn, workerName=sfn_worker_name ) except Exception as e: logger.critical(e.message) logger.critical( 'Unrecoverable error invoking get_activity_task for {}.'.format(sfn_activity_arn)) raise # Keep the new Task Token for reference later task_token = response.get('taskToken', '') # If there are no tasks, return if not task_token: logger.debug('No tasks available.') return logger.info('Received task. Task token: {}'.format(task_token)) # Parse task input and create Athena query input task_input = '' try: task_input = json.loads(response['input']) task_input_dict = json.loads(task_input) athena_named_query = task_input_dict.get('AthenaNamedQuery', None) if athena_named_query is None: athena_query_string = task_input_dict['AthenaQueryString'] athena_database = task_input_dict['AthenaDatabase'] else: logger.debug('Retrieving details of named query "{}" from Athena'.format(athena_named_query)) response = athena.get_named_query( NamedQueryId=athena_named_query ) athena_query_string = response['NamedQuery']['QueryString'] athena_database = response['NamedQuery']['Database'] athena_result_output_location = task_input_dict['AthenaResultOutputLocation'] athena_result_encryption_option = task_input_dict.get('AthenaResultEncryptionOption', None) athena_result_kms_key = task_input_dict.get('AthenaResultKmsKey', "NONE").capitalize() athena_result_encryption_config = {} if athena_result_encryption_option is not None: athena_result_encryption_config['EncryptionOption'] = athena_result_encryption_option if athena_result_encryption_option in ["SSE_KMS", "CSE_KMS"]: athena_result_encryption_config['KmsKey'] = athena_result_kms_key except (KeyError, Exception): logger.critical('Invalid Athena Runner input. Make sure required input parameters are properly specified.') raise # Run Athena Query logger.info('Querying "{}" Athena database using query string: "{}"'.format(athena_database, athena_query_string)) try: response = athena.start_query_execution( QueryString=athena_query_string, QueryExecutionContext={ 'Database': athena_database }, ResultConfiguration={ 'OutputLocation': athena_result_output_location, 'EncryptionConfiguration': athena_result_encryption_config } ) athena_query_execution_id = response['QueryExecutionId'] # Store SFN 'Task Token' and 'Query Execution Id' in DynamoDB item = { 'sfn_activity_arn': sfn_activity_arn, 'athena_query_execution_id': athena_query_execution_id, 'sfn_task_token': task_token } ddb_table.put_item(Item=item) except Exception as e: logger.error('Failed to query Athena database "{}" with query string "{}"..'.format(athena_database, athena_query_string)) logger.error('Reason: {}'.format(e.message)) logger.info('Sending "Task Failed" signal to Step Functions.') response = sfn.send_task_failure( taskToken=task_token, error='Failed to start Athena query. Check Athena Runner logs for more details.' ) return logger.info('Athena query started. Query Execution Id: {}'.format(athena_query_execution_id)) def check_athena_queries(config): # Query all items in table for a particular SFN activity ARN # This should retrieve records for all started athena queries for this particular activity ARN ddb_table = dynamodb.Table(config['ddb_table']) sfn_activity_arn = config['sfn_activity_arn'] ddb_resp = ddb_table.query( KeyConditionExpression=Key('sfn_activity_arn').eq(sfn_activity_arn), Limit=config['ddb_query_limit'] ) # For each item... for item in ddb_resp['Items']: athena_query_execution_id = item['athena_query_execution_id'] sfn_task_token = item['sfn_task_token'] try: logger.debug('Polling Athena query execution status..') # Query athena query execution status... athena_resp = athena.get_query_execution( QueryExecutionId=athena_query_execution_id ) query_exec_resp = athena_resp['QueryExecution'] query_exec_state = query_exec_resp['Status']['State'] query_state_change_reason = query_exec_resp['Status'].get('StateChangeReason', '') logger.debug('Query with Execution Id {} is currently in state "{}"'.format(query_exec_state, query_state_change_reason)) # If Athena query completed, return success: if query_exec_state in ['SUCCEEDED']: logger.info('Query with Execution Id {} SUCCEEDED.'.format(athena_query_execution_id)) # Build an output dict and format it as JSON task_output_dict = { "AthenaQueryString": query_exec_resp['Query'], "AthenaQueryExecutionId": athena_query_execution_id, "AthenaQueryExecutionState": query_exec_state, "AthenaQueryExecutionStateChangeReason": query_state_change_reason, "AthenaQuerySubmissionDateTime": query_exec_resp['Status'].get('SubmissionDateTime', '').strftime( '%x, %-I:%M %p %Z'), "AthenaQueryCompletionDateTime": query_exec_resp['Status'].get('CompletionDateTime', '').strftime( '%x, %-I:%M %p %Z'), "AthenaQueryEngineExecutionTimeInMillis": query_exec_resp['Statistics'].get( 'EngineExecutionTimeInMillis', 0), "AthenaQueryDataScannedInBytes": query_exec_resp['Statistics'].get('DataScannedInBytes', 0) } task_output_json = json.dumps(task_output_dict) logger.info('Sending "Task Succeeded" signal to Step Functions..') sfn_resp = sfn.send_task_success( taskToken=sfn_task_token, output=task_output_json ) # Delete item resp = ddb_table.delete_item( Key={ 'sfn_activity_arn': sfn_activity_arn, 'athena_query_execution_id': athena_query_execution_id } ) # Task succeeded, next item elif query_exec_state in ['RUNNING', 'QUEUED']: logger.debug( 'Query with Execution Id {} is in state hasn\'t completed yet.'.format(athena_query_execution_id)) # Send heartbeat sfn_resp = sfn.send_task_heartbeat( taskToken=sfn_task_token ) logger.debug('Heartbeat sent to Step Functions.') # Heartbeat sent, next item elif query_exec_state in ['FAILED', 'CANCELLED']: message = 'Athena query with Execution Id "{}" failed. Last state: {}. Error message: {}' \ .format(athena_query_execution_id, query_exec_state, query_state_change_reason) logger.error(message) message_json = { "AthenaQueryString": query_exec_resp['Query'], "AthenaQueryExecutionId": athena_query_execution_id, "AthenaQueryExecutionState": query_exec_state, "AthenaQueryExecutionStateChangeReason": query_state_change_reason, "AthenaQuerySubmissionDateTime": query_exec_resp['Status'].get('SubmissionDateTime', '').strftime( '%x, %-I:%M %p %Z'), "AthenaQueryCompletionDateTime": query_exec_resp['Status'].get('CompletionDateTime', '').strftime( '%x, %-I:%M %p %Z'), "AthenaQueryEngineExecutionTimeInMillis": query_exec_resp['Statistics'].get( 'EngineExecutionTimeInMillis', 0), "AthenaQueryDataScannedInBytes": query_exec_resp['Statistics'].get('DataScannedInBytes', 0) } sfn_resp = sfn.send_task_failure( taskToken=sfn_task_token, cause=json.dumps(message_json), error='AthenaQueryFailedError' ) # Delete item resp = ddb_table.delete_item( Key={ 'sfn_activity_arn': sfn_activity_arn, 'athena_query_execution_id': athena_query_execution_id } ) logger.error(message) except Exception as e: logger.error('There was a problem checking status of Athena query..') logger.error('Glue job Run Id "{}"'.format(athena_query_execution_id)) logger.error('Reason: {}'.format(e.message)) logger.info('Checking next Athena query.') # Task failed, next item athena = boto3.client('athena') # Because Step Functions client uses long polling, read timeout has to be > 60 seconds sfn_client_config = Config(connect_timeout=50, read_timeout=70) sfn = boto3.client('stepfunctions', config=sfn_client_config) dynamodb = boto3.resource('dynamodb') # Load logging config and create logger logger = load_log_config() def handler(event, context): logger.debug('*** Athena Runner lambda function starting ***') try: # Get config (including a single activity ARN) from local file config = load_config() # One round of starting Athena queries start_athena_queries(config) # One round of checking on Athena queries check_athena_queries(config) logger.debug('*** Master Athena Runner terminating ***') except Exception as e: logger.critical('*** ERROR: Athena runner lambda function failed ***') logger.critical(e.message) raise
# Copyright 2018 Amazon.com, Inc. or its affiliates. All Rights Reserved. # # Permission is hereby granted, free of charge, to any person obtaining a copy of this # software and associated documentation files (the "Software"), to deal in the Software # without restriction, including without limitation the rights to use, copy, modify, # merge, publish, distribute, sublicense, and/or sell copies of the Software, and to # permit persons to whom the Software is furnished to do so. # # THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, # INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A # PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT # HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION # OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE # SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. import boto3 import logging, logging.config import json from botocore.client import Config from boto3.dynamodb.conditions import Key, Attr def load_log_config(): # Basic config. Replace with your own logging config if required root = logging.getLogger() root.setLevel(logging.INFO) return root def load_config(): with open('gluerunner-config.json', 'r') as conf_file: conf_json = conf_file.read() return json.loads(conf_json) def is_json(jsonstring): try: json_object = json.loads(jsonstring) except ValueError: return False return True def start_glue_jobs(config): ddb_table = dynamodb.Table(config["ddb_table"]) logger.debug('Glue runner started') glue_job_capacity = config['glue_job_capacity'] sfn_activity_arn = config['sfn_activity_arn'] sfn_worker_name = config['sfn_worker_name'] # Loop until no tasks are available from Step Functions while True: logger.debug('Polling for Glue tasks for Step Functions Activity ARN: {}'.format(sfn_activity_arn)) try: response = sfn.get_activity_task( activityArn=sfn_activity_arn, workerName=sfn_worker_name ) except Exception as e: logger.critical(e.message) logger.critical( 'Unrecoverable error invoking get_activity_task for {}.'.format(sfn_activity_arn)) raise # Keep the new Task Token for reference later task_token = response.get('taskToken', '') # If there are no tasks, return if not task_token: logger.debug('No tasks available.') return logger.info('Received task. Task token: {}'.format(task_token)) # Parse task input and create Glue job input task_input = '' try: task_input = json.loads(response['input']) task_input_dict = json.loads(task_input) glue_job_name = task_input_dict['GlueJobName'] glue_job_capacity = int(task_input_dict.get('GlueJobCapacity', glue_job_capacity)) except (KeyError, Exception): logger.critical('Invalid Glue Runner input. Make sure required input parameters are properly specified.') raise # Extract additional Glue job inputs from task_input_dict glue_job_args = task_input_dict # Run Glue job logger.info('Running Glue job named "{}"..'.format(glue_job_name)) try: response = glue.start_job_run( JobName=glue_job_name, Arguments=glue_job_args, AllocatedCapacity=glue_job_capacity ) glue_job_run_id = response['JobRunId'] # Store SFN 'Task Token' and Glue Job 'Run Id' in DynamoDB item = { 'sfn_activity_arn': sfn_activity_arn, 'glue_job_name': glue_job_name, 'glue_job_run_id': glue_job_run_id, 'sfn_task_token': task_token } ddb_table.put_item(Item=item) except Exception as e: logger.error('Failed to start Glue job named "{}"..'.format(glue_job_name)) logger.error('Reason: {}'.format(e.message)) logger.info('Sending "Task Failed" signal to Step Functions.') response = sfn.send_task_failure( taskToken=task_token, error='Failed to start Glue job. Check Glue Runner logs for more details.' ) return logger.info('Glue job run started. Run Id: {}'.format(glue_job_run_id)) def check_glue_jobs(config): # Query all items in table for a particular SFN activity ARN # This should retrieve records for all started glue jobs for this particular activity ARN ddb_table = dynamodb.Table(config['ddb_table']) sfn_activity_arn = config['sfn_activity_arn'] ddb_resp = ddb_table.query( KeyConditionExpression=Key('sfn_activity_arn').eq(sfn_activity_arn), Limit=config['ddb_query_limit'] ) # For each item... for item in ddb_resp['Items']: glue_job_run_id = item['glue_job_run_id'] glue_job_name = item['glue_job_name'] sfn_task_token = item['sfn_task_token'] try: logger.debug('Polling Glue job run status..') # Query glue job status... glue_resp = glue.get_job_run( JobName=glue_job_name, RunId=glue_job_run_id, PredecessorsIncluded=False ) job_run_state = glue_resp['JobRun']['JobRunState'] job_run_error_message = glue_resp['JobRun'].get('ErrorMessage', '') logger.debug('Job with Run Id {} is currently in state "{}"'.format(glue_job_run_id, job_run_state)) # If Glue job completed, return success: if job_run_state in ['SUCCEEDED']: logger.info('Job with Run Id {} SUCCEEDED.'.format(glue_job_run_id)) # Build an output dict and format it as JSON task_output_dict = { "GlueJobName": glue_job_name, "GlueJobRunId": glue_job_run_id, "GlueJobRunState": job_run_state, "GlueJobStartedOn": glue_resp['JobRun'].get('StartedOn', '').strftime('%x, %-I:%M %p %Z'), "GlueJobCompletedOn": glue_resp['JobRun'].get('CompletedOn', '').strftime('%x, %-I:%M %p %Z'), "GlueJobLastModifiedOn": glue_resp['JobRun'].get('LastModifiedOn', '').strftime('%x, %-I:%M %p %Z') } task_output_json = json.dumps(task_output_dict) logger.info('Sending "Task Succeeded" signal to Step Functions..') sfn_resp = sfn.send_task_success( taskToken=sfn_task_token, output=task_output_json ) # Delete item resp = ddb_table.delete_item( Key={ 'sfn_activity_arn': sfn_activity_arn, 'glue_job_run_id': glue_job_run_id } ) # Task succeeded, next item elif job_run_state in ['STARTING', 'RUNNING', 'STARTING', 'STOPPING']: logger.debug('Job with Run Id {} hasn\'t succeeded yet.'.format(glue_job_run_id)) # Send heartbeat sfn_resp = sfn.send_task_heartbeat( taskToken=sfn_task_token ) logger.debug('Heartbeat sent to Step Functions.') # Heartbeat sent, next item elif job_run_state in ['FAILED', 'STOPPED']: message = 'Glue job "{}" run with Run Id "{}" failed. Last state: {}. Error message: {}' \ .format(glue_job_name, glue_job_run_id[:8] + "...", job_run_state, job_run_error_message) logger.error(message) message_json = { 'glue_job_name': glue_job_name, 'glue_job_run_id': glue_job_run_id, 'glue_job_run_state': job_run_state, 'glue_job_run_error_msg': job_run_error_message } sfn_resp = sfn.send_task_failure( taskToken=sfn_task_token, cause=json.dumps(message_json), error='GlueJobFailedError' ) # Delete item resp = ddb_table.delete_item( Key={ 'sfn_activity_arn': sfn_activity_arn, 'glue_job_run_id': glue_job_run_id } ) logger.error(message) # Task failed, next item except Exception as e: logger.error('There was a problem checking status of Glue job "{}"..'.format(glue_job_name)) logger.error('Glue job Run Id "{}"'.format(glue_job_run_id)) logger.error('Reason: {}'.format(e.message)) logger.info('Checking next Glue job.') glue = boto3.client('glue') # Because Step Functions client uses long polling, read timeout has to be > 60 seconds sfn_client_config = Config(connect_timeout=50, read_timeout=70) sfn = boto3.client('stepfunctions', config=sfn_client_config) dynamodb = boto3.resource('dynamodb') # Load logging config and create logger logger = load_log_config() def handler(event, context): logger.debug('*** Glue Runner lambda function starting ***') try: # Get config (including a single activity ARN) from local file config = load_config() # One round of starting Glue jobs start_glue_jobs(config) # One round of checking on Glue jobs check_glue_jobs(config) logger.debug('*** Master Glue Runner terminating ***') except Exception as e: logger.critical('*** ERROR: Glue runner lambda function failed ***') logger.critical(e.message) raise
from __future__ import print_function import json import urllib import boto3 import logging, logging.config from botocore.client import Config # Because Step Functions client uses long polling, read timeout has to be > 60 seconds sfn_client_config = Config(connect_timeout=50, read_timeout=70) sfn = boto3.client('stepfunctions', config=sfn_client_config) sts = boto3.client('sts') account_id = sts.get_caller_identity().get('Account') region_name = boto3.session.Session().region_name def load_log_config(): # Basic config. Replace with your own logging config if required root = logging.getLogger() root.setLevel(logging.INFO) return root def map_activity_arn(bucket, key): # Map s3 key to activity ARN based on a convention # Here, we simply map bucket name plus last element in the s3 object key (i.e. filename) to activity name key_elements = [x.strip() for x in key.split('/')] activity_name = '{}-{}'.format(bucket, key_elements[-1]) return 'arn:aws:states:{}:{}:activity:{}'.format(region_name, account_id, activity_name) # Load logging config and create logger logger = load_log_config() def handler(event, context): logger.info("Received event: " + json.dumps(event, indent=2)) # Get the object from the event and show its content type bucket = event['Records'][0]['s3']['bucket']['name'] key = urllib.unquote_plus(event['Records'][0]['s3']['object']['key'].encode('utf8')) # Based on a naming convention that maps s3 keys to activity ARNs, deduce the activity arn sfn_activity_arn = map_activity_arn(bucket, key) sfn_worker_name = 'on_s3_object_created' try: try: response = sfn.get_activity_task( activityArn=sfn_activity_arn, workerName=sfn_worker_name ) except Exception as e: logger.critical(e.message) logger.critical( 'Unrecoverable error invoking get_activity_task for {}.'.format(sfn_activity_arn)) raise # Get the Task Token sfn_task_token = response.get('taskToken', '') logger.info('Sending "Task Succeeded" signal to Step Functions..') # Build an output dict and format it as JSON task_output_dict = { 'S3BucketName': bucket, 'S3Key': key, 'SFNActivityArn': sfn_activity_arn } task_output_json = json.dumps(task_output_dict) sfn_resp = sfn.send_task_success( taskToken=sfn_task_token, output=task_output_json ) except Exception as e: logger.critical(e) raise e
# Copyright 2018 Amazon.com, Inc. or its affiliates. All Rights Reserved. # # Permission is hereby granted, free of charge, to any person obtaining a copy of this # software and associated documentation files (the "Software"), to deal in the Software # without restriction, including without limitation the rights to use, copy, modify, # merge, publish, distribute, sublicense, and/or sell copies of the Software, and to # permit persons to whom the Software is furnished to do so. # # THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, # INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A # PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT # HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION # OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE # SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. import sys import pyspark.sql.functions as func from awsglue.dynamicframe import DynamicFrame from awsglue.transforms import * from awsglue.utils import getResolvedOptions from pyspark.context import SparkContext from awsglue.context import GlueContext from awsglue.job import Job args = getResolvedOptions(sys.argv, ['JOB_NAME', 's3_output_path', 'database_name', 'table_name']) s3_output_path = args['s3_output_path'] database_name = args['database_name'] table_name = args['table_name'] sc = SparkContext.getOrCreate() glueContext = GlueContext(sc) spark = glueContext.spark_session job = Job(glueContext) job.init(args['JOB_NAME'], args) sales_DyF = glueContext.create_dynamic_frame\ .from_catalog(database=database_name, table_name=table_name) sales_DyF = ApplyMapping.apply(frame=sales_DyF, mappings=[ ('date', 'string', 'date', 'string'), ('lead name', 'string', 'lead_name', 'string'), ('forecasted monthly revenue', 'bigint', 'forecasted_monthly_revenue', 'bigint'), ('opportunity stage', 'string', 'opportunity_stage', 'string'), ('weighted revenue', 'bigint', 'weighted_revenue', 'bigint'), ('target close', 'string', 'target_close', 'string'), ('closed opportunity', 'string', 'closed_opportunity', 'string'), ('active opportunity', 'string', 'active_opportunity', 'string'), ('last status entry', 'string', 'last_status_entry', 'string'), ], transformation_ctx='applymapping1') sales_DyF.printSchema() sales_DF = sales_DyF.toDF() salesForecastedByDate_DF = \ sales_DF\ .where(sales_DF['opportunity_stage'] == 'Lead')\ .groupBy('date')\ .agg({'forecasted_monthly_revenue': 'sum', 'opportunity_stage': 'count'})\ .orderBy('date')\ .withColumnRenamed('count(opportunity_stage)', 'leads_generated')\ .withColumnRenamed('sum(forecasted_monthly_revenue)', 'forecasted_lead_revenue')\ .coalesce(1) salesForecastedByDate_DF.write\ .format('parquet')\ .option('header', 'true')\ .mode('overwrite')\ .save(s3_output_path) job.commit()
# Copyright 2018 Amazon.com, Inc. or its affiliates. All Rights Reserved. # # Permission is hereby granted, free of charge, to any person obtaining a copy of this # software and associated documentation files (the "Software"), to deal in the Software # without restriction, including without limitation the rights to use, copy, modify, # merge, publish, distribute, sublicense, and/or sell copies of the Software, and to # permit persons to whom the Software is furnished to do so. # # THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, # INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A # PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT # HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION # OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE # SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. import sys import pyspark.sql.functions as func from awsglue.dynamicframe import DynamicFrame from awsglue.transforms import * from awsglue.utils import getResolvedOptions from pyspark.context import SparkContext from awsglue.context import GlueContext from awsglue.job import Job args = getResolvedOptions(sys.argv, ['JOB_NAME', 's3_output_path', 's3_sales_data_path', 's3_marketing_data_path']) s3_output_path = args['s3_output_path'] s3_sales_data_path = args['s3_sales_data_path'] s3_marketing_data_path = args['s3_marketing_data_path'] sc = SparkContext.getOrCreate() glueContext = GlueContext(sc) spark = glueContext.spark_session job = Job(glueContext) job.init(args['JOB_NAME'], args) salesForecastedByDate_DF = \ glueContext.spark_session.read.option("header", "true")\ .load(s3_sales_data_path, format="parquet") mktg_DF = \ glueContext.spark_session.read.option("header", "true")\ .load(s3_marketing_data_path, format="parquet") salesForecastedByDate_DF\ .join(mktg_DF, 'date', 'inner')\ .orderBy(salesForecastedByDate_DF['date']) \ .write \ .format('csv') \ .option('header', 'true') \ .mode('overwrite') \ .save(s3_output_path)
# Copyright 2018 Amazon.com, Inc. or its affiliates. All Rights Reserved. # # Permission is hereby granted, free of charge, to any person obtaining a copy of this # software and associated documentation files (the "Software"), to deal in the Software # without restriction, including without limitation the rights to use, copy, modify, # merge, publish, distribute, sublicense, and/or sell copies of the Software, and to # permit persons to whom the Software is furnished to do so. # # THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, # INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A # PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT # HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION # OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE # SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. import sys import pyspark.sql.functions as func from awsglue.dynamicframe import DynamicFrame from awsglue.transforms import * from awsglue.utils import getResolvedOptions from pyspark.context import SparkContext from awsglue.context import GlueContext from awsglue.job import Job args = getResolvedOptions(sys.argv, ['JOB_NAME', 's3_output_path', 'database_name', 'table_name']) s3_output_path = args['s3_output_path'] database_name = args['database_name'] table_name = args['table_name'] sc = SparkContext.getOrCreate() glueContext = GlueContext(sc) spark = glueContext.spark_session job = Job(glueContext) job.init(args['JOB_NAME'], args) mktg_DyF = glueContext.create_dynamic_frame\ .from_catalog(database=database_name, table_name=table_name) mktg_DyF = ApplyMapping.apply(frame=mktg_DyF, mappings=[ ('date', 'string', 'date', 'string'), ('new visitors seo', 'bigint', 'new_visitors_seo', 'bigint'), ('new visitors cpc', 'bigint', 'new_visitors_cpc', 'bigint'), ('new visitors social media', 'bigint', 'new_visitors_social_media', 'bigint'), ('return visitors', 'bigint', 'return_visitors', 'bigint'), ], transformation_ctx='applymapping1') mktg_DyF.printSchema() mktg_DF = mktg_DyF.toDF() mktg_DF.write\ .format('parquet')\ .option('header', 'true')\ .mode('overwrite')\ .save(s3_output_path) job.commit()
const path = require("path"); const AwsSamPlugin = require("aws-sam-webpack-plugin"); const awsSamPlugin = new AwsSamPlugin(); module.exports = { // Loads the entry object from the AWS::Serverless::Function resources in your // SAM config. Setting this to a function will entry: () => awsSamPlugin.entry(), // Write the output to the .aws-sam/build folder output: { filename: (chunkData) => awsSamPlugin.filename(chunkData), libraryTarget: "commonjs2", path: path.resolve(".") }, // Create source maps devtool: "source-map", // Resolve .ts and .js extensions resolve: { extensions: [".ts", ".js"] }, // Target node target: "node", // AWS recommends always including the aws-sdk in your Lambda package but excluding can significantly reduce // the size of your deployment package. If you want to always include it then comment out this line. It has // been included conditionally because the node10.x docker image used by SAM local doesn't include it. externals: process.env.NODE_ENV === "development" ? [] : ["aws-sdk"], // Set the webpack mode mode: process.env.NODE_ENV || "production", // Add the TypeScript loader module: { rules: [{ test: /\.tsx?$/, loader: "ts-loader" }] }, // Add the AWS SAM Webpack plugin plugins: [awsSamPlugin] };
const AWSXRay = require('aws-xray-sdk') const AWS = AWSXRay.captureAWS(require('aws-sdk')) const DBclient = new AWS.DynamoDB.DocumentClient() const EVBclient = new AWS.EventBridge() var table = process.env.TABLE_NAME var eventBusName = process.env.EVENT_BUS_NAME const resolvers = { Mutation: { updateVacationRequest: async (ctx) => { let params; console.log(ctx.arguments.input) if (`${ctx.arguments.input.approvalStatus}` === "PENDING_APPROVAL") { // PERSIST DATA params = { TableName: table, Key: { "id": ctx.arguments.input.id }, UpdateExpression: "set approvalStatus = :new", ExpressionAttributeValues: { ":new": "PENDING_APPROVAL" }, ReturnValues: "ALL_NEW" } } else if (`${ctx.arguments.input.approvalStatus}` === "APPROVED") { params = { TableName: table, Key: { "id": ctx.arguments.input.id }, UpdateExpression: "set approvalStatus = :new", ExpressionAttributeValues: { ":new": "APPROVED" }, ReturnValues: "ALL_NEW" } } const data = await DBclient.update(params).promise() if (data.$response.error) { console.error("Unable to add item. Error JSON:", JSON.stringify(data.$response.error, null, 2)); } else { console.log("Successfully added item to database. " + JSON.stringify(ctx.arguments.input)) // SEND EVENT AFTER SUCCESSFULLY PERSISTING DATA if (`${ctx.arguments.input.approvalStatus}` === "PENDING_APPROVAL") { params = { "Entries": [ { "Detail": JSON.stringify(ctx.arguments.input), "DetailType": "VacationRequestValidated", "EventBusName": eventBusName, "Source": "VacationTrackerApp", "Time": new Date() } ] } const result = await EVBclient.putEvents(params).promise() if (result.$response.error) { console.error("Unable to send event. Error JSON:", JSON.stringify(result.$response.error, null, 2)); } else { console.log("Successfully sent event. " + JSON.stringify(result.$response.data)) } } } console.log("returning: " + JSON.stringify(data.$response.data.Attributes)) return data.$response.data.Attributes; } } } exports.handler = async function (event) { const typeHandler = resolvers[event.typeName]; if (typeHandler) { const resolver = typeHandler[event.fieldName]; if (resolver) { const result = await resolver(event); return result; } } };
const AWSXRay = require('aws-xray-sdk') const AWS = AWSXRay.captureAWS(require('aws-sdk')) const DBclient = new AWS.DynamoDB.DocumentClient() const EVBclient = new AWS.EventBridge() var table = process.env.TABLE_NAME var eventBusName = process.env.EVENT_BUS_NAME const resolvers = { Mutation: { submitVacationRequest: async (ctx) => { // PERSIST DATA var params = { TableName: table, Item: ctx.arguments.input } const data = await DBclient.put(params).promise() if (data.$response.error) { console.error("Unable to add item. Error JSON:", JSON.stringify(data.$response.error, null, 2)); } else { console.log("Successfully added item to database. " + JSON.stringify(ctx.arguments.input)) // SEND EVENT AFTER SUCCESSFULLY PERSISTING DATA params = { "Entries": [ { "Detail": JSON.stringify(ctx.arguments.input), "DetailType": "VacationRequestSubmited", "EventBusName": eventBusName, "Source": "VacationTrackerApp", "Time": new Date() } ] } var result = await EVBclient.putEvents(params).promise() if (result.$response.error) { console.error("Unable to send event. Error JSON:", JSON.stringify(result.$response.error, null, 2)); } else { console.log("Successfully sent event. " + JSON.stringify(result.$response.data)) return ctx.arguments.input; } } } } } exports.handler = async function (event) { const typeHandler = resolvers[event.typeName]; if (typeHandler) { const resolver = typeHandler[event.fieldName]; if (resolver) { const result = await resolver(event); return result; } } };
/* eslint-disable no-console */ require("es6-promise").polyfill(); require("isomorphic-fetch"); // eslint-disable-next-line import/no-extraneous-dependencies const Xray = require('aws-xray-sdk') const AWS = Xray.captureAWS(require('aws-sdk')) const AWSAppSyncClient = require("aws-appsync").default; const gql = require('graphql-tag') // graphql client. We define it outside of the lambda function in order for it to be reused during subsequent calls let client function initializeClient() { client = new AWSAppSyncClient({ url: process.env.APP_SYNC_API_URL, region: process.env.AWS_REGION, auth: { type: 'AWS_IAM', credentials: { accessKeyId: process.env.AWS_ACCESS_KEY_ID, secretAccessKey: process.env.AWS_SECRET_ACCESS_KEY, sessionToken: process.env.AWS_SESSION_TOKEN } }, disableOffline: true }); } // generic mutation function. A way to quickly reuse mutation statements async function executeMutation(mutation, variables) { if (!client) { initializeClient(); } try { const response = await client.mutate({ mutation, variables }) console.log(response.data.updateVacationRequest) return response.data; } catch (err) { console.log("Error while trying to mutate data: " + err.errorMessage); throw JSON.stringify(err); } } exports.handler = async (event) => { console.log(event) // FAKE VALIDATION LOGIC await executeMutation( gql`mutation updateVacationMutation($id:ID!) { updateVacationRequest(input:{ id:$id, approvalStatus: PENDING_APPROVAL }) { id category startDate endDate createdAt } }`, { "id": event.detail.id } ) }
module.exports = { mode: 'jit', content: [ './public/**/*.html', './src/**/*.{js,jsx,ts,tsx,vue}', ], theme: { extend: { margin: { '-120': '-500px', } }, }, variants: { extend: { opacity: ['disabled'] }, }, plugins: [], }
const cdk = require('@aws-cdk/core'); const eventbridge = require('@aws-cdk/aws-events'); const targets = require('@aws-cdk/aws-events-targets'); const lambda = require('@aws-cdk/aws-lambda'); const iam = require('@aws-cdk/aws-iam'); const assets = require('@aws-cdk/aws-s3-assets'); const { Duration } = require('@aws-cdk/core'); class InfrastructureStack extends cdk.Stack { /** * * @param {cdk.Construct} scope * @param {string} id * @param {cdk.StackProps=} props */ constructor(scope, id, props) { super(scope, id, props); // GLOBAL ENVIRONMENT VARIABLES // !!!! // REPLACE WITH YOUR OWN VALUES AFTER AMPLIFY PUSH // !!!! // var TableNameEnv = "VacationRequest-ckp2905llfbhvp3rzplgpjpocm-twitch"; // this is just an example. not a real value. var appSyncEndpointEnv = "https://5lex5fzaciqulcx4d5h67xgyz4.appsync-api.eu-west-1.amazonaws.com/graphql"; // this is just an example. not a real value. var evb = new eventbridge.EventBus(this, "VacationTrackerEventBus", { eventBusName: "VacationTrackerEvents" }); var dynamoPolicyStatement = new iam.PolicyStatement({ actions: [ "dynamodb:BatchGetItem", "dynamodb:BatchWriteItem", "dynamodb:ConditionCheckItem", "dynamodb:PutItem", "dynamodb:DescribeTable", "dynamodb:DeleteItem", "dynamodb:GetItem", "dynamodb:Scan", "dynamodb:Query", "dynamodb:UpdateItem" ], resources: ["*"], effect: iam.Effect.ALLOW }); var cloudwatchLogsStatement = new iam.PolicyStatement({ actions: [ "logs:CreateLogGroup", "logs:CreateLogStream", "logs:DescribeLogGroups", "logs:DescribeLogStreams", "logs:PutLogEvents", "logs:GetLogEvents", "logs:FilterLogEvents" ], resources: ["*"], effect: iam.Effect.ALLOW }); var EventableRole = new iam.Role(this, "dynamoAndEventBridgePutRole", { assumedBy: new iam.ServicePrincipal('lambda.amazonaws.com'), managedPolicies: [ iam.ManagedPolicy.fromAwsManagedPolicyName("AWSXrayWriteOnlyAccess"), iam.ManagedPolicy.fromAwsManagedPolicyName("AmazonEventBridgeFullAccess") ], inlinePolicies: [ new iam.PolicyDocument({ statements: [ dynamoPolicyStatement, cloudwatchLogsStatement ] }) ] }); var appSyncStatement = new iam.PolicyStatement({ actions: [ "appsync:*" ], resources: ["*"], effect: iam.Effect.ALLOW }); var AppSyncIntegrationRole = new iam.Role(this, "appSyncIntegrationRole", { assumedBy: new iam.ServicePrincipal('lambda.amazonaws.com'), managedPolicies: [ iam.ManagedPolicy.fromAwsManagedPolicyName("AWSXrayWriteOnlyAccess") ], inlinePolicies: [ new iam.PolicyDocument({ statements: [ appSyncStatement, cloudwatchLogsStatement ] }) ] }); const createVacationRequestAsset = new assets.Asset(this, 'createVacationRequestBundledAsset', { path: '../functions/createVacationRequest/' }); const updateVacationRequestAsset = new assets.Asset(this, 'updateVacationRequestBundledAsset', { path: '../functions/updateVacationRequest/' }); const validateVacationRequestAsset = new assets.Asset(this, 'vacationRequestValidationBundledAsset', { path: '../functions/vacationRequestValidation/' }); var createVacationRequestFunction = new lambda.Function(this, "createVacationRequestFunction", { runtime: lambda.Runtime.NODEJS_14_X, handler: 'app.handler', code: lambda.Code.fromBucket(createVacationRequestAsset.bucket, createVacationRequestAsset.s3ObjectKey), role: EventableRole, functionName: "createVacationRequestFunction", environment: { "TABLE_NAME": TableNameEnv, "EVENT_BUS_NAME": evb.eventBusName }, tracing: lambda.Tracing.ACTIVE, timeout: Duration.seconds(15), memorySize: 512 }); var updateVacationRequestFunction = new lambda.Function(this, "updateVacationRequestFunction", { runtime: lambda.Runtime.NODEJS_14_X, handler: 'app.handler', code: lambda.Code.fromBucket(updateVacationRequestAsset.bucket, updateVacationRequestAsset.s3ObjectKey), role: EventableRole, functionName: "updateVacationRequestFunction", environment: { "TABLE_NAME": TableNameEnv, "EVENT_BUS_NAME": evb.eventBusName }, tracing: lambda.Tracing.ACTIVE, timeout: Duration.seconds(15), memorySize: 512 }); var validateVacationRequestFunction = new lambda.Function(this, "validateVacationRequestFunction", { runtime: lambda.Runtime.NODEJS_14_X, handler: 'app.handler', code: lambda.Code.fromBucket(validateVacationRequestAsset.bucket, validateVacationRequestAsset.s3ObjectKey), role: AppSyncIntegrationRole, functionName: "validateVacationRequestFunction", environment: { "APP_SYNC_API_URL": appSyncEndpointEnv }, tracing: lambda.Tracing.ACTIVE, timeout: Duration.seconds(15), memorySize: 512 }); var vacationRequestSubmitedRule = new eventbridge.Rule(this, "ValidateVacationRequestOnSubmission", { enabled: true, eventBus: evb, ruleName: "ValidateVacationRequestOnSubmission", eventPattern: { source: ["VacationTrackerApp"], detailType: ["VacationRequestSubmited"] }, targets: [ new targets.LambdaFunction(validateVacationRequestFunction) ] }); var vacationRequestValidatedRule = new eventbridge.Rule(this, "VacationRequestValidated", { enabled: true, eventBus: evb, ruleName: "VacationRequestValidated", eventPattern: { source: ["VacationTrackerApp"], detailType: ["VacationRequestValidated"] } }); var vacationRequestApprovedRule = new eventbridge.Rule(this, "VacationRequestApproved", { enabled: true, eventBus: evb, ruleName: "VacationRequestApproved", eventPattern: { source: ["VacationTrackerApp"], detailType: ["VacationRequestApproved"] } }); } } module.exports = { InfrastructureStack }
#!/usr/bin/env node const cdk = require('@aws-cdk/core'); const { InfrastructureStack } = require('../lib/infrastructure-stack'); const app = new cdk.App(); new InfrastructureStack(app, 'InfrastructureStack', { /* If you don't specify 'env', this stack will be environment-agnostic. * Account/Region-dependent features and context lookups will not work, * but a single synthesized template can be deployed anywhere. */ /* Uncomment the next line to specialize this stack for the AWS Account * and Region that are implied by the current CLI configuration. */ // env: { account: process.env.CDK_DEFAULT_ACCOUNT, region: process.env.CDK_DEFAULT_REGION }, /* Uncomment the next line if you know exactly what Account and Region you * want to deploy the stack to. */ // env: { account: '123456789012', region: 'us-east-1' }, /* For more information, see https://docs.aws.amazon.com/cdk/latest/guide/environments.html */ });
/* eslint-disable */ // this is an auto generated file. This will be overwritten export const submitVacationRequest = /* GraphQL */ ` mutation SubmitVacationRequest($input: CreateVacationRequestInput!) { submitVacationRequest(input: $input) { id category description approvalStatus startDate endDate approvedBy owner rejectionReason createdAt updatedAt } } `; export const updateVacationRequest = /* GraphQL */ ` mutation UpdateVacationRequest($input: UpdateVacationRequestInput!) { updateVacationRequest(input: $input) { id category description approvalStatus startDate endDate approvedBy owner rejectionReason createdAt updatedAt } } `; export const deleteVacationRequest = /* GraphQL */ ` mutation DeleteVacationRequest( $input: DeleteVacationRequestInput! $condition: ModelVacationRequestConditionInput ) { deleteVacationRequest(input: $input, condition: $condition) { id category description approvalStatus startDate endDate approvedBy owner rejectionReason createdAt updatedAt } } `;
/* eslint-disable */ // this is an auto generated file. This will be overwritten export const onVacationRequestNotification = /* GraphQL */ ` subscription OnVacationRequestNotification($owner: String) { onVacationRequestNotification(owner: $owner) { id category description approvalStatus startDate endDate approvedBy owner rejectionReason createdAt updatedAt } } `; export const onDeleteVacationRequest = /* GraphQL */ ` subscription OnDeleteVacationRequest { onDeleteVacationRequest { id category description approvalStatus startDate endDate approvedBy owner rejectionReason createdAt updatedAt } } `;
/* eslint-disable */ // this is an auto generated file. This will be overwritten export const getVacationRequest = /* GraphQL */ ` query GetVacationRequest($id: ID!) { getVacationRequest(id: $id) { id category description approvalStatus startDate endDate approvedBy owner rejectionReason createdAt updatedAt } } `; export const listVacationRequests = /* GraphQL */ ` query ListVacationRequests( $filter: ModelVacationRequestFilterInput $limit: Int $nextToken: String ) { listVacationRequests( filter: $filter limit: $limit nextToken: $nextToken ) { items { id category description approvalStatus startDate endDate approvedBy owner rejectionReason createdAt updatedAt } nextToken } } `;
import { useState, useEffect } from "react"; import { API } from "aws-amplify"; import { listVacationRequests } from "../graphql/queries"; import { updateVacationRequest, deleteVacationRequest, } from "../graphql/mutations"; import AddVacation from "../components/AddVacation"; import moment from "moment"; import CustomTable from "../components/CustomTable"; function Vacations({ emmiter, user }) { emmiter.on("showModal", (visible, header, subtitle, component) => { getVacations(); }); const [vacations, setVacations] = useState([]); const [isApprover, setIsApprover] = useState(false); const [pendingApprovalSelected, setPendingApprovalSelected] = useState([]); const [comingUpSelected, setComingUpSelected] = useState([]); const headers = ["Name", "Start Date", "End Date", "Category", "Requester"]; useEffect(() => { getVacations(); }); function checkIsApprover() { if ( user?.signInUserSession.idToken.payload["cognito:groups"]?.includes( "Approvers" ) ) { setIsApprover(true); return true; } return false; } async function getVacations() { let result; if (!checkIsApprover()) { const filter = { owner: { eq: user.username, }, }; result = await API.graphql({ query: listVacationRequests, variables: { filter: filter }, authMode: "AMAZON_COGNITO_USER_POOLS", }); } else { result = await API.graphql({ query: listVacationRequests, authMode: "AMAZON_COGNITO_USER_POOLS", }); } setVacations(result.data.listVacationRequests?.items); } async function approveVacations() { let input; pendingApprovalSelected.forEach(async (id) => { input = { id: id, approvalStatus: "APPROVED", }; await API.graphql({ query: updateVacationRequest, variables: { input: input }, authMode: "AMAZON_COGNITO_USER_POOLS", }); }); setPendingApprovalSelected([]); await getVacations(); } async function deleteVacations() { let input; const fullList = pendingApprovalSelected.concat(comingUpSelected); // DELETE FROM LIST OF PENDING APPROVAL fullList.forEach(async (id) => { input = { id: id, }; console.log("Deleting vacation: " + id); await API.graphql({ query: deleteVacationRequest, variables: { input: input }, authMode: "AMAZON_COGNITO_USER_POOLS", }); }); setPendingApprovalSelected([]); setComingUpSelected([]); await getVacations(); } function showAddVacation() { emmiter.emit( "showModal", true, "New Vacation Request", "A good vacation description will help the approver.", <AddVacation emmiter={emmiter} /> ); } return ( <div> <div className='border-b-2 flex items-center'> <h1 className='text-purple-600 flex-grow'>VACATIONS</h1> {/* Vacations */} {/* Header */} {/* Actions */} <div> {isApprover && ( <button disabled={pendingApprovalSelected.length === 0} className='disabled:opacity-50 disabled:cursor-not-allowed bg-gray-100 text-base rounded text-gray-500 hover:bg-gray-50 transform transition shadow p-4 py-2 mr-4' onClick={approveVacations} > Approve </button> )} <button disabled={ pendingApprovalSelected.length === 0 && comingUpSelected.length === 0 } className='disabled:opacity-50 disabled:cursor-not-allowed bg-gray-100 text-base rounded text-gray-500 hover:bg-gray-50 transform transition shadow p-4 py-2 mr-4' onClick={deleteVacations} > Delete </button> <button className='bg-purple-600 text-base rounded text-white hover:bg-purple-800 transform transition shadow p-4 py-2 my-4' onClick={showAddVacation} > Add </button> </div> </div> {/* List Categories */} {vacations.filter( (item) => item.approvalStatus === "PENDING_APPROVAL" || item.approvalStatus === "PENDING_VALIDATION" ).length > 0 && ( <> <div className='flex justify-between'> <h3 className='text-xl mb-4 pt-4'>Pending approval</h3> </div> <CustomTable selectionSetter={setPendingApprovalSelected} emmiter={emmiter} headers={headers} rows={vacations.filter( (item) => item.approvalStatus === "PENDING_APPROVAL" || item.approvalStatus === "PENDING_VALIDATION" )} /> </> )} {/* List Categories */} {vacations.filter( (item) => item.approvalStatus === "APPROVED" && item.endDate > `${moment().format("YYYY-MM-DD")}Z` ).length > 0 && ( <> <div className='flex justify-between mt-6'> <h3 className='text-xl'>Coming up</h3> </div> <CustomTable selectionSetter={setComingUpSelected} headers={headers} rows={vacations.filter( (item) => item.approvalStatus === "APPROVED" && item.endDate > `${moment().format("YYYY-MM-DD")}Z` )} /> </> )} {/* List Categories */} {vacations.filter( (item) => item.approvalStatus === "APPROVED" && item.endDate <= `${moment().format("YYYY-MM-DD")}Z` ).length > 0 && ( <> <div className='flex justify-between mt-6'> <h3 className='text-xl'>Past vacations</h3> </div> <CustomTable readonly={true} headers={headers} rows={vacations.filter( (item) => item.approvalStatus === "APPROVED" && item.endDate <= `${moment().format("YYYY-MM-DD")}Z` )} /> </> )} </div> ); } export default Vacations;
function People() { return ( <div> <h1>PEOPLE</h1> <p className="font-extralight">Work in progress</p> </div> ) } export default People
function Teams() { return ( <div> <h1>TEAMS</h1> <p className="font-extralight">Work in progress</p> </div> ) } export default Teams
// import { useState, useEffect } from 'react' // import { listCategories } from '../graphql/queries' // import { API } from 'aws-amplify' // import CategoryItem from '../components/CategoryItem' // import AddCategory from '../components/AddCategory' function Settings({emmiter}) { // const [categories, setCategories] = useState([]) // useEffect(()=> { // getCategories() // }, []) // async function getCategories(){ // const result = await API.graphql({query: listCategories, authMode: 'AMAZON_COGNITO_USER_POOLS'}) // setCategories(result.data.listCategories.items) // } // function showAddCategory(){ // emmiter.emit("showModal", true, "Create Category", "Create a new category to help employees classify their vacations.", <AddCategory emmiter={emmiter} />) // } return ( <div> <h1 className="border-b-2 pb-2">SETTINGS</h1> {/* CATEGORIES */} {/* Header */} {/* <div className="flex justify-between mt-6"> <h3 className="text-xl">Categories</h3> <div> <button className="bg-yellow-600 text-base px-2 py-1 rounded text-white hover:bg-yellow-700 transform transition shadow" onClick={showAddCategory} >Add</button> </div> </div> */} {/* List Categories */} {/* { categories.map((category, index) => { return ( <CategoryItem key={index} category={category} /> ) }) } */} </div> ) } export default Settings
function Profile() { return ( <div> <h1>PROFILE</h1> <p className="font-extralight">Work in progress</p> </div> ) } export default Profile
import "./App.css"; import { PaperAirplaneIcon } from "@heroicons/react/outline"; import NavBar from "./components/NavBar"; import ProfileLink from "./components/ProfileLink"; import { withAuthenticator } from "@aws-amplify/ui-react"; import { BrowserRouter as Router, Routes, Route, Link } from "react-router-dom"; import Vacations from "./pages/Vacations"; import Teams from "./pages/Teams"; import People from "./pages/People"; import Settings from "./pages/Settings"; import Profile from "./pages/Profile"; import { useEffect, useState } from "react"; import { Auth } from "aws-amplify"; import Modal from "./components/Modal"; import { createNanoEvents } from "nanoevents"; function App() { const emmiter = createNanoEvents(); emmiter.on("showModal", (visible, header, subtitle, component) => { setModal({ header, subtitle, component }); setShowModal(visible); }); const [user, setUser] = useState(null); const [showModal, setShowModal] = useState(false); const [modal, setModal] = useState({ header: "", subtitle: "", component: null, }); useEffect(() => { checkUser(); }, []); async function checkUser() { await Auth.currentAuthenticatedUser() .then((data) => { setUser(data); }) .catch((err) => { console.log("user is not authenticated. redirecting..."); }); } if (!user) return null; return ( <Router> <div className='flex'> <div className='relative min-h-screen flex flex-grow'> {/* sidebar */} <div className='bg-gray-100 text-gray-800 w-64 pt-6 px-2 space-y-6 flex flex-col h-screen z-0 relative'> {/* logo */} <Link to='/'> <div className='text-gray-800 flex items-center space-x-2 pl-4 border-b-1'> <PaperAirplaneIcon className='w-8 h-8 text-purple-800' /> <span className='text-xl font-bold'>VacationTracker</span> </div> </Link> {/* nav */} <NavBar className='static' user={user} /> {/* Signed-in user */} <ProfileLink user={user} /> </div> {/* content */} <div className='p-6 text-2xl font-bold z-0 flex-1 flex-grow relative'> <Routes> <Route path='/' exact render={() => <Vacations emmiter={emmiter} user={user} />} /> <Route path='/vacations' render={() => <Vacations emmiter={emmiter} user={user} />} /> <Route path='/teams' element={<Teams />} /> <Route path='/people' element={<People />} /> <Route path='/settings' render={() => <Settings emmiter={emmiter} user={user} />} /> <Route path='/profile' element={<Profile />} /> </Routes> </div> </div> {/* popup */} {showModal && ( <Modal showModal={showModal} setShowModal={setShowModal} header={modal.header} subtitle={modal.subtitle} content={modal.component} /> )} </div> </Router> ); } export default withAuthenticator(App);
import { useState } from 'react' import { API } from 'aws-amplify' import { createCategory } from '../graphql/mutations' function AddCategory({ emmiter }) { const [name, setName] = useState("") async function addCategory() { const newCategory = { name: name } await API.graphql({ query: createCategory, variables: { input: newCategory }, authMode: 'AMAZON_COGNITO_USER_POOLS' }) emmiter.emit("showModal", false, "", "", null) } function cancel(){ emmiter.emit("showModal", false, "", "", null) } return ( <div className="space-y-3 h-full flex flex-col"> <div className="flex-grow pt-4 px-4"> <label className="block border-gray-600">Name</label> <input className="w-full border-gray-100 border-2 rounded p-1" type="text" onChange={(event) => setName(event.target.value)} /> </div> <div className="bg-gray-100 flex justify-end sticky"> <button className="bg-white text-base rounded text-gray-800 hover:bg-gray-50 transform transition shadow px-4 py-2 my-4 mr-4" onClick={cancel}>Cancel</button> <button className="bg-purple-600 text-base rounded text-white hover:bg-purple-800 transform transition shadow p-4 py-2 my-4 mr-4" onClick={addCategory}>Create</button> </div> </div> ) } export default AddCategory
import { UserIcon, UserGroupIcon, AdjustmentsIcon, CalendarIcon } from '@heroicons/react/solid' import { Link } from 'react-router-dom' import { useEffect, useState } from 'react' function NavBar({user}) { const [isAdmin, setIsAdmin] = useState(false) useEffect(() => { checkUserRole() }) async function checkUserRole() { if (user?.signInUserSession.idToken.payload['cognito:groups']?.includes("Approvers")) { setIsAdmin(true) } } return ( <nav className="flex-grow text-gray-500 sticky"> <Link to="/vacations"> <div className="py-2.5 px-4 flex items-center rounded-xl transform transition ease-in-out hover:bg-gray-200 hover:text-gray-900"> <CalendarIcon className="w-6 h-6" /> <span className="text-xl pl-2 pt-1">Vacations</span> </div> </Link> { isAdmin && <> <Link to="/teams"> <div className="py-2.5 px-4 flex items-center rounded-xl transform transition ease-in-out hover:bg-gray-200 hover:text-gray-900"> <UserGroupIcon className="w-6 h-6" /> <span className="text-xl pl-2 pt-1">Teams</span> </div> </Link> <Link to="/people"> <div className="py-2.5 px-4 flex items-center rounded-xl transform transition ease-in-out hover:bg-gray-200 hover:text-gray-900"> <UserIcon className="w-6 h-6" /> <span className="text-xl pl-2 pt-1">People</span> </div> </Link> <Link to="/settings"> <div className="py-2.5 px-4 flex items-center rounded-xl transform transition ease-in-out hover:bg-gray-200 hover:text-gray-900"> <AdjustmentsIcon className="w-6 h-6" /> <span className="text-xl pl-2 pt-1">Settings</span> </div> </Link> </> } </nav> ) } export default NavBar