Dataset Viewer
Auto-converted to Parquet Duplicate
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='[email protected]', 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 "[email protected]" --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); }); }); });
End of preview. Expand in Data Studio

digits

digits is a code dataset consisting of 900 public domain-like repos on GitHub.

The following languages included are:

  • C
  • C++
  • JavaScript
  • Python
  • R
  • PowerShell
  • Java
  • Kotlin
  • C#
  • Swift
  • Bourne Shell

This dataset is provided without warranty.

Downloads last month
-