file_name large_stringlengths 4 140 | prefix large_stringlengths 0 39k | suffix large_stringlengths 0 36.1k | middle large_stringlengths 0 29.4k | fim_type large_stringclasses 4
values |
|---|---|---|---|---|
gulpfile.js | // ## Globals
var argv = require('minimist')(process.argv.slice(2));
var autoprefixer = require('gulp-autoprefixer');
var browserSync = require('browser-sync').create();
var changed = require('gulp-changed');
var concat = require('gulp-concat');
var flatten = require('gulp-flatten');
var gulp = require('gulp');
var gulpif = require('gulp-if');
var imagemin = require('gulp-imagemin');
var jshint = require('gulp-jshint');
var lazypipe = require('lazypipe');
var merge = require('merge-stream');
var cssNano = require('gulp-cssnano');
var plumber = require('gulp-plumber');
var rev = require('gulp-rev');
var runSequence = require('run-sequence');
var sass = require('gulp-sass');
var sourcemaps = require('gulp-sourcemaps');
var uglify = require('gulp-uglify');
var rename =require('gulp-rename');
var svgstore =require('gulp-svgstore');
var svgmin =require('gulp-svgmin');
var inject =require('gulp-inject');
// See https://github.com/austinpray/asset-builder
var manifest = require('asset-builder')('./assets/manifest.json');
// `path` - Paths to base asset directories. With trailing slashes.
// - `path.source` - Path to the source files. Default: `assets/`
// - `path.dist` - Path to the build directory. Default: `dist/`
var path = manifest.paths;
// `config` - Store arbitrary configuration values here.
var config = manifest.config || {};
// `globs` - These ultimately end up in their respective `gulp.src`.
// - `globs.js` - Array of asset-builder JS dependency objects. Example:
// ```
// {type: 'js', name: 'main.js', globs: []}
// ```
// - `globs.css` - Array of asset-builder CSS dependency objects. Example:
// ```
// {type: 'css', name: 'main.css', globs: []}
// ```
// - `globs.fonts` - Array of font path globs.
// - `globs.images` - Array of image path globs.
// - `globs.bower` - Array of all the main Bower files.
var globs = manifest.globs;
// `project` - paths to first-party assets.
// - `project.js` - Array of first-party JS assets.
// - `project.css` - Array of first-party CSS assets.
var project = manifest.getProjectGlobs();
// CLI options
var enabled = {
// Enable static asset revisioning when `--production`
rev: argv.production,
// Disable source maps when `--production`
maps: !argv.production,
//maps: false,
// Fail styles task on error when `--production`
failStyleTask: argv.production,
// Fail due to JSHint warnings only when `--production`
failJSHint: argv.production,
// Strip debug statments from javascript when `--production`
stripJSDebug: argv.production
};
// Path to the compiled assets manifest in the dist directory
var revManifest = path.dist + 'assets.json';
// ## Reusable Pipelines
// See https://github.com/OverZealous/lazypipe
// ### CSS processing pipeline
// Example
// ```
// gulp.src(cssFiles)
// .pipe(cssTasks('main.css')
// .pipe(gulp.dest(path.dist + 'styles'))
// ```
var cssTasks = function(filename) {
return lazypipe()
.pipe(function() {
return gulpif(!enabled.failStyleTask, plumber());
})
.pipe(function() {
return gulpif(enabled.maps, sourcemaps.init());
})
// .pipe(function() {
// return gulpif('*.less', less());
// })
.pipe(function() {
return gulpif('*.scss', sass({
outputStyle: 'nested', // libsass doesn't support expanded yet
precision: 10,
includePaths: ['.'],
errLogToConsole: !enabled.failStyleTask
}));
})
.pipe(concat, filename)
.pipe(autoprefixer, {
browsers: [
'last 2 versions',
'android 4',
'opera 12'
]
})
.pipe(cssNano, {
safe: true
})
.pipe(function() {
return gulpif(enabled.rev, rev());
})
.pipe(function() {
return gulpif(enabled.maps, sourcemaps.write('.', {
sourceRoot: '/'
}));
})();
};
// ### JS processing pipeline
// Example
// ```
// gulp.src(jsFiles)
// .pipe(jsTasks('main.js')
// .pipe(gulp.dest(path.dist + 'scripts'))
// ```
var jsTasks = function(filename) {
return lazypipe()
.pipe(function() {
return gulpif(enabled.maps, sourcemaps.init());
})
.pipe(concat, filename)
.pipe(uglify, {
compress: {
'drop_debugger': enabled.stripJSDebug
}
})
.pipe(function() {
return gulpif(enabled.rev, rev());
})
.pipe(function() {
return gulpif(enabled.maps, sourcemaps.write('.', {
sourceRoot: '/'
}));
})();
};
// ### Write to rev manifest
// If there are any revved files then write them to the rev manifest.
// See https://github.com/sindresorhus/gulp-rev
var writeToManifest = function(directory) {
return lazypipe()
.pipe(gulp.dest, path.dist + directory)
.pipe(browserSync.stream, {match: '**/*.{js,css}'})
.pipe(rev.manifest, revManifest, {
base: path.dist,
merge: true
})
.pipe(gulp.dest, path.dist)();
};
// ## Gulp tasks
// Run `gulp -T` for a task summary
// ### Styles
// `gulp styles` - Compiles, combines, and optimizes Bower CSS and project CSS.
// By default this task will only log a warning if a precompiler error is
// raised. If the `--production` flag is set: this task will fail outright.
gulp.task('styles', ['wiredep'], function() {
var merged = merge();
manifest.forEachDependency('css', function(dep) {
var cssTasksInstance = cssTasks(dep.name);
if (!enabled.failStyleTask) |
merged.add(gulp.src(dep.globs, {base: 'styles'})
.pipe(cssTasksInstance));
});
return merged
.pipe(writeToManifest('styles'));
});
// ### Scripts
// `gulp scripts` - Runs JSHint then compiles, combines, and optimizes Bower JS
// and project JS.
gulp.task('scripts', ['jshint'], function() {
var merged = merge();
manifest.forEachDependency('js', function(dep) {
merged.add(
gulp.src(dep.globs, {base: 'scripts'})
.pipe(jsTasks(dep.name))
);
});
return merged
.pipe(writeToManifest('scripts'));
});
// ### Fonts
// `gulp fonts` - Grabs all the fonts and outputs them in a flattened directory
// structure. See: https://github.com/armed/gulp-flatten
gulp.task('fonts', function() {
return gulp.src(globs.fonts)
.pipe(flatten())
.pipe(gulp.dest(path.dist + 'fonts'))
.pipe(browserSync.stream());
});
//SVG fonts inject
gulp.task('svgicons', function () {
var svgs = gulp
.src('assets/icons/*.svg')
.pipe(rename({prefix: 'icon-'}))
.pipe(svgmin())
.pipe(svgstore({ inlineSvg: true }));
function fileContents (filePath, file) {
return file.contents.toString();
}
return gulp
.src('templates/svg-icons.php')
.pipe(inject(svgs, { transform: fileContents }))
.pipe(gulp.dest('templates'));
});
// ### Images
// `gulp images` - Run lossless compression on all the images.
gulp.task('images', function() {
return gulp.src(globs.images)
.pipe(imagemin({
progressive: true,
interlaced: true,
svgoPlugins: [{removeUnknownsAndDefaults: false}, {cleanupIDs: false}]
}))
.pipe(gulp.dest(path.dist + 'images'))
.pipe(browserSync.stream());
});
// ### JSHint
// `gulp jshint` - Lints configuration JSON and project JS.
gulp.task('jshint', function() {
return gulp.src([
'bower.json', 'gulpfile.js'
].concat(project.js))
.pipe(jshint())
.pipe(jshint.reporter('jshint-stylish'))
.pipe(gulpif(enabled.failJSHint, jshint.reporter('fail')));
});
// ### Clean
// `gulp clean` - Deletes the build folder entirely.
gulp.task('clean', require('del').bind(null, [path.dist]));
// ### Watch
// `gulp watch` - Use BrowserSync to proxy your dev server and synchronize code
// changes across devices. Specify the hostname of your dev server at
// `manifest.config.devUrl`. When a modification is made to an asset, run the
// build step for that asset and inject the changes into the page.
// See: http://www.browsersync.io
gulp.task('watch', function() {
browserSync.init({
files: ['{lib,templates}/**/*.php', '*.php'],
proxy: config.devUrl,
notify: {
styles: {
top: 'auto',
bottom: '0',
right: 'auto',
left: '0',
margin: '0px',
padding: '5px',
position: 'fixed',
fontSize: '10px',
zIndex: '9999',
borderRadius: '0px 5px 0px',
color: 'white',
textAlign: 'center',
display: 'block',
backgroundColor: 'rgba(0, 0, 0, 0.5)'
}
},
snippetOptions: {
whitelist: ['/wp-admin/admin-ajax.php'],
blacklist: ['/wp-admin/**']
}
});
gulp.watch([path.source + 'styles/**/*'], ['styles']);
gulp.watch([path.source + 'scripts/**/*'], ['jshint', 'scripts']);
gulp.watch([path.source + 'fonts/**/*'], ['fonts']);
gulp.watch([path.source + 'images/**/*'], ['images']);
gulp.watch([path.source + 'icons/**/*.svg'], ['svgicons']);
gulp.watch(['bower.json', 'assets/manifest.json'], ['build']);
});
// ### Build
// `gulp build` - Run all the build tasks but don't clean up beforehand.
// Generally you should be running `gulp` instead of `gulp build`.
gulp.task('build', function(callback) {
runSequence('styles',
'scripts',
['fonts', 'images', 'svgicons'],
callback);
});
// ### Wiredep
// `gulp wiredep` - Automatically inject Less and Sass Bower dependencies. See
// https://github.com/taptapship/wiredep
gulp.task('wiredep', function() {
var wiredep = require('wiredep').stream;
return gulp.src(project.css)
.pipe(wiredep())
.pipe(changed(path.source + 'styles', {
hasChanged: changed.compareSha1Digest
}))
.pipe(gulp.dest(path.source + 'styles'));
});
// ### Gulp
// `gulp` - Run a complete build. To compile for production run `gulp --production`.
gulp.task('default', ['clean'], function() {
gulp.start('build');
});
| {
cssTasksInstance.on('error', function(err) {
console.error(err.message);
this.emit('end');
});
} | conditional_block |
gulpfile.js | // ## Globals
var argv = require('minimist')(process.argv.slice(2));
var autoprefixer = require('gulp-autoprefixer');
var browserSync = require('browser-sync').create();
var changed = require('gulp-changed');
var concat = require('gulp-concat');
var flatten = require('gulp-flatten');
var gulp = require('gulp');
var gulpif = require('gulp-if');
var imagemin = require('gulp-imagemin');
var jshint = require('gulp-jshint');
var lazypipe = require('lazypipe');
var merge = require('merge-stream');
var cssNano = require('gulp-cssnano');
var plumber = require('gulp-plumber');
var rev = require('gulp-rev');
var runSequence = require('run-sequence');
var sass = require('gulp-sass');
var sourcemaps = require('gulp-sourcemaps');
var uglify = require('gulp-uglify');
var rename =require('gulp-rename');
var svgstore =require('gulp-svgstore');
var svgmin =require('gulp-svgmin');
var inject =require('gulp-inject');
// See https://github.com/austinpray/asset-builder
var manifest = require('asset-builder')('./assets/manifest.json');
// `path` - Paths to base asset directories. With trailing slashes.
// - `path.source` - Path to the source files. Default: `assets/`
// - `path.dist` - Path to the build directory. Default: `dist/`
var path = manifest.paths;
// `config` - Store arbitrary configuration values here.
var config = manifest.config || {};
// `globs` - These ultimately end up in their respective `gulp.src`.
// - `globs.js` - Array of asset-builder JS dependency objects. Example:
// ```
// {type: 'js', name: 'main.js', globs: []}
// ```
// - `globs.css` - Array of asset-builder CSS dependency objects. Example:
// ```
// {type: 'css', name: 'main.css', globs: []}
// ```
// - `globs.fonts` - Array of font path globs.
// - `globs.images` - Array of image path globs.
// - `globs.bower` - Array of all the main Bower files.
var globs = manifest.globs;
// `project` - paths to first-party assets.
// - `project.js` - Array of first-party JS assets.
// - `project.css` - Array of first-party CSS assets.
var project = manifest.getProjectGlobs();
// CLI options
var enabled = {
// Enable static asset revisioning when `--production`
rev: argv.production,
// Disable source maps when `--production`
maps: !argv.production,
//maps: false,
// Fail styles task on error when `--production`
failStyleTask: argv.production,
// Fail due to JSHint warnings only when `--production`
failJSHint: argv.production,
// Strip debug statments from javascript when `--production`
stripJSDebug: argv.production
};
// Path to the compiled assets manifest in the dist directory
var revManifest = path.dist + 'assets.json';
// ## Reusable Pipelines
// See https://github.com/OverZealous/lazypipe
// ### CSS processing pipeline
// Example
// ```
// gulp.src(cssFiles)
// .pipe(cssTasks('main.css')
// .pipe(gulp.dest(path.dist + 'styles'))
// ```
var cssTasks = function(filename) {
return lazypipe()
.pipe(function() {
return gulpif(!enabled.failStyleTask, plumber());
})
.pipe(function() {
return gulpif(enabled.maps, sourcemaps.init());
})
// .pipe(function() {
// return gulpif('*.less', less());
// })
.pipe(function() {
return gulpif('*.scss', sass({
outputStyle: 'nested', // libsass doesn't support expanded yet
precision: 10,
includePaths: ['.'],
errLogToConsole: !enabled.failStyleTask
}));
})
.pipe(concat, filename)
.pipe(autoprefixer, {
browsers: [
'last 2 versions',
'android 4',
'opera 12'
]
})
.pipe(cssNano, {
safe: true
})
.pipe(function() {
return gulpif(enabled.rev, rev());
})
.pipe(function() {
return gulpif(enabled.maps, sourcemaps.write('.', {
sourceRoot: '/'
}));
})();
};
// ### JS processing pipeline
// Example
// ```
// gulp.src(jsFiles)
// .pipe(jsTasks('main.js')
// .pipe(gulp.dest(path.dist + 'scripts'))
// ```
var jsTasks = function(filename) {
return lazypipe()
.pipe(function() {
return gulpif(enabled.maps, sourcemaps.init());
})
.pipe(concat, filename)
.pipe(uglify, {
compress: {
'drop_debugger': enabled.stripJSDebug
}
})
.pipe(function() {
return gulpif(enabled.rev, rev());
})
.pipe(function() {
return gulpif(enabled.maps, sourcemaps.write('.', {
sourceRoot: '/'
}));
})();
};
// ### Write to rev manifest
// If there are any revved files then write them to the rev manifest.
// See https://github.com/sindresorhus/gulp-rev
var writeToManifest = function(directory) {
return lazypipe()
.pipe(gulp.dest, path.dist + directory)
.pipe(browserSync.stream, {match: '**/*.{js,css}'})
.pipe(rev.manifest, revManifest, {
base: path.dist,
merge: true
})
.pipe(gulp.dest, path.dist)();
};
// ## Gulp tasks
// Run `gulp -T` for a task summary
// ### Styles
// `gulp styles` - Compiles, combines, and optimizes Bower CSS and project CSS.
// By default this task will only log a warning if a precompiler error is
// raised. If the `--production` flag is set: this task will fail outright.
gulp.task('styles', ['wiredep'], function() {
var merged = merge();
manifest.forEachDependency('css', function(dep) {
var cssTasksInstance = cssTasks(dep.name);
if (!enabled.failStyleTask) {
cssTasksInstance.on('error', function(err) {
console.error(err.message);
this.emit('end');
});
}
merged.add(gulp.src(dep.globs, {base: 'styles'})
.pipe(cssTasksInstance));
});
return merged
.pipe(writeToManifest('styles'));
});
// ### Scripts
// `gulp scripts` - Runs JSHint then compiles, combines, and optimizes Bower JS
// and project JS.
gulp.task('scripts', ['jshint'], function() {
var merged = merge();
manifest.forEachDependency('js', function(dep) {
merged.add(
gulp.src(dep.globs, {base: 'scripts'})
.pipe(jsTasks(dep.name))
);
});
return merged
.pipe(writeToManifest('scripts'));
});
// ### Fonts
// `gulp fonts` - Grabs all the fonts and outputs them in a flattened directory
// structure. See: https://github.com/armed/gulp-flatten
gulp.task('fonts', function() {
return gulp.src(globs.fonts)
.pipe(flatten())
.pipe(gulp.dest(path.dist + 'fonts'))
.pipe(browserSync.stream());
});
//SVG fonts inject
gulp.task('svgicons', function () {
var svgs = gulp
.src('assets/icons/*.svg')
.pipe(rename({prefix: 'icon-'}))
.pipe(svgmin())
.pipe(svgstore({ inlineSvg: true }));
function fileContents (filePath, file) {
return file.contents.toString();
}
|
// ### Images
// `gulp images` - Run lossless compression on all the images.
gulp.task('images', function() {
return gulp.src(globs.images)
.pipe(imagemin({
progressive: true,
interlaced: true,
svgoPlugins: [{removeUnknownsAndDefaults: false}, {cleanupIDs: false}]
}))
.pipe(gulp.dest(path.dist + 'images'))
.pipe(browserSync.stream());
});
// ### JSHint
// `gulp jshint` - Lints configuration JSON and project JS.
gulp.task('jshint', function() {
return gulp.src([
'bower.json', 'gulpfile.js'
].concat(project.js))
.pipe(jshint())
.pipe(jshint.reporter('jshint-stylish'))
.pipe(gulpif(enabled.failJSHint, jshint.reporter('fail')));
});
// ### Clean
// `gulp clean` - Deletes the build folder entirely.
gulp.task('clean', require('del').bind(null, [path.dist]));
// ### Watch
// `gulp watch` - Use BrowserSync to proxy your dev server and synchronize code
// changes across devices. Specify the hostname of your dev server at
// `manifest.config.devUrl`. When a modification is made to an asset, run the
// build step for that asset and inject the changes into the page.
// See: http://www.browsersync.io
gulp.task('watch', function() {
browserSync.init({
files: ['{lib,templates}/**/*.php', '*.php'],
proxy: config.devUrl,
notify: {
styles: {
top: 'auto',
bottom: '0',
right: 'auto',
left: '0',
margin: '0px',
padding: '5px',
position: 'fixed',
fontSize: '10px',
zIndex: '9999',
borderRadius: '0px 5px 0px',
color: 'white',
textAlign: 'center',
display: 'block',
backgroundColor: 'rgba(0, 0, 0, 0.5)'
}
},
snippetOptions: {
whitelist: ['/wp-admin/admin-ajax.php'],
blacklist: ['/wp-admin/**']
}
});
gulp.watch([path.source + 'styles/**/*'], ['styles']);
gulp.watch([path.source + 'scripts/**/*'], ['jshint', 'scripts']);
gulp.watch([path.source + 'fonts/**/*'], ['fonts']);
gulp.watch([path.source + 'images/**/*'], ['images']);
gulp.watch([path.source + 'icons/**/*.svg'], ['svgicons']);
gulp.watch(['bower.json', 'assets/manifest.json'], ['build']);
});
// ### Build
// `gulp build` - Run all the build tasks but don't clean up beforehand.
// Generally you should be running `gulp` instead of `gulp build`.
gulp.task('build', function(callback) {
runSequence('styles',
'scripts',
['fonts', 'images', 'svgicons'],
callback);
});
// ### Wiredep
// `gulp wiredep` - Automatically inject Less and Sass Bower dependencies. See
// https://github.com/taptapship/wiredep
gulp.task('wiredep', function() {
var wiredep = require('wiredep').stream;
return gulp.src(project.css)
.pipe(wiredep())
.pipe(changed(path.source + 'styles', {
hasChanged: changed.compareSha1Digest
}))
.pipe(gulp.dest(path.source + 'styles'));
});
// ### Gulp
// `gulp` - Run a complete build. To compile for production run `gulp --production`.
gulp.task('default', ['clean'], function() {
gulp.start('build');
}); | return gulp
.src('templates/svg-icons.php')
.pipe(inject(svgs, { transform: fileContents }))
.pipe(gulp.dest('templates'));
}); | random_line_split |
shootout-k-nucleotide.rs | // Copyright 2014 The Rust Project Developers. See the COPYRIGHT
// file at the top-level directory of this distribution and at
// http://rust-lang.org/COPYRIGHT.
//
// Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or
// http://www.apache.org/licenses/LICENSE-2.0> or the MIT license
// <LICENSE-MIT or http://opensource.org/licenses/MIT>, at your
// option. This file may not be copied, modified, or distributed
// except according to those terms.
// ignore-android see #10393 #13206
use std::string::String;
use std::slice;
use std::sync::{Arc, Future};
static TABLE: [u8, ..4] = [ 'A' as u8, 'C' as u8, 'G' as u8, 'T' as u8 ];
static TABLE_SIZE: uint = 2 << 16;
static OCCURRENCES: [&'static str, ..5] = [
"GGT",
"GGTA",
"GGTATT",
"GGTATTTTAATT",
"GGTATTTTAATTTATAGT",
];
// Code implementation
#[deriving(PartialEq, PartialOrd, Ord, Eq)]
struct Code(u64);
impl Code {
fn hash(&self) -> u64 {
let Code(ret) = *self;
return ret;
}
fn push_char(&self, c: u8) -> Code {
Code((self.hash() << 2) + (pack_symbol(c) as u64))
}
fn rotate(&self, c: u8, frame: uint) -> Code {
Code(self.push_char(c).hash() & ((1u64 << (2 * frame)) - 1))
}
fn pack(string: &str) -> Code {
string.bytes().fold(Code(0u64), |a, b| a.push_char(b))
}
fn unpack(&self, frame: uint) -> String {
let mut key = self.hash();
let mut result = Vec::new();
for _ in range(0, frame) {
result.push(unpack_symbol((key as u8) & 3));
key >>= 2;
}
result.reverse();
String::from_utf8(result).unwrap()
}
}
// Hash table implementation
trait TableCallback {
fn f(&self, entry: &mut Entry);
}
struct BumpCallback;
impl TableCallback for BumpCallback {
fn f(&self, entry: &mut Entry) {
entry.count += 1;
}
}
struct PrintCallback(&'static str);
impl TableCallback for PrintCallback {
fn f(&self, entry: &mut Entry) {
let PrintCallback(s) = *self;
println!("{}\t{}", entry.count as int, s);
}
}
struct Entry {
code: Code,
count: uint,
next: Option<Box<Entry>>,
}
struct Table {
count: uint,
items: Vec<Option<Box<Entry>>> }
struct Items<'a> {
cur: Option<&'a Entry>,
items: slice::Items<'a, Option<Box<Entry>>>,
}
impl Table {
fn new() -> Table {
Table {
count: 0,
items: Vec::from_fn(TABLE_SIZE, |_| None),
}
}
fn search_remainder<C:TableCallback>(item: &mut Entry, key: Code, c: C) {
match item.next {
None => {
let mut entry = box Entry {
code: key,
count: 0,
next: None,
};
c.f(&mut *entry);
item.next = Some(entry);
}
Some(ref mut entry) => {
if entry.code == key {
c.f(&mut **entry);
return;
}
Table::search_remainder(&mut **entry, key, c)
}
}
}
fn lookup<C:TableCallback>(&mut self, key: Code, c: C) {
let index = key.hash() % (TABLE_SIZE as u64);
{
if self.items.get(index as uint).is_none() {
let mut entry = box Entry {
code: key,
count: 0,
next: None,
};
c.f(&mut *entry);
*self.items.get_mut(index as uint) = Some(entry);
return;
}
}
{
let entry = &mut *self.items.get_mut(index as uint).get_mut_ref();
if entry.code == key {
c.f(&mut **entry);
return;
}
Table::search_remainder(&mut **entry, key, c)
}
}
fn iter<'a>(&'a self) -> Items<'a> {
Items { cur: None, items: self.items.iter() }
}
}
impl<'a> Iterator<&'a Entry> for Items<'a> {
fn next(&mut self) -> Option<&'a Entry> {
let ret = match self.cur {
None => {
let i;
loop {
match self.items.next() {
None => return None,
Some(&None) => {}
Some(&Some(ref a)) => { i = &**a; break }
}
}
self.cur = Some(&*i);
&*i
}
Some(c) => c
};
match ret.next {
None => { self.cur = None; }
Some(ref next) => { self.cur = Some(&**next); }
}
return Some(ret);
}
}
// Main program
fn pack_symbol(c: u8) -> u8 {
match c as char {
'A' => 0,
'C' => 1,
'G' => 2,
'T' => 3,
_ => fail!("{}", c as char),
}
}
fn unpack_symbol(c: u8) -> u8 {
TABLE[c as uint]
}
fn generate_frequencies(mut input: &[u8], frame: uint) -> Table {
let mut frequencies = Table::new();
if input.len() < frame { return frequencies; }
let mut code = Code(0);
// Pull first frame.
for _ in range(0, frame) {
code = code.push_char(input[0]);
input = input.slice_from(1);
}
frequencies.lookup(code, BumpCallback);
while input.len() != 0 && input[0] != ('>' as u8) {
code = code.rotate(input[0], frame);
frequencies.lookup(code, BumpCallback);
input = input.slice_from(1);
}
frequencies
}
fn print_frequencies(frequencies: &Table, frame: uint) {
let mut vector = Vec::new();
for entry in frequencies.iter() {
vector.push((entry.count, entry.code));
}
vector.as_mut_slice().sort();
let mut total_count = 0;
for &(count, _) in vector.iter() {
total_count += count;
}
for &(count, key) in vector.iter().rev() {
println!("{} {:.3f}",
key.unpack(frame).as_slice(),
(count as f32 * 100.0) / (total_count as f32));
}
println!("");
}
fn print_occurrences(frequencies: &mut Table, occurrence: &'static str) {
frequencies.lookup(Code::pack(occurrence), PrintCallback(occurrence))
}
fn get_sequence<R: Buffer>(r: &mut R, key: &str) -> Vec<u8> {
let mut res = Vec::new();
for l in r.lines().map(|l| l.ok().unwrap())
.skip_while(|l| key != l.as_slice().slice_to(key.len())).skip(1)
{
res.push_all(l.as_slice().trim().as_bytes());
}
for b in res.mut_iter() {
*b = b.to_ascii().to_upper().to_byte();
}
res
}
fn main() {
let input = if std::os::getenv("RUST_BENCH").is_some() | else {
get_sequence(&mut std::io::stdin(), ">THREE")
};
let input = Arc::new(input);
let nb_freqs: Vec<(uint, Future<Table>)> = range(1u, 3).map(|i| {
let input = input.clone();
(i, Future::spawn(proc() generate_frequencies(input.as_slice(), i)))
}).collect();
let occ_freqs: Vec<Future<Table>> = OCCURRENCES.iter().map(|&occ| {
let input = input.clone();
Future::spawn(proc() generate_frequencies(input.as_slice(), occ.len()))
}).collect();
for (i, freq) in nb_freqs.move_iter() {
print_frequencies(&freq.unwrap(), i);
}
for (&occ, freq) in OCCURRENCES.iter().zip(occ_freqs.move_iter()) {
print_occurrences(&mut freq.unwrap(), occ);
}
}
| {
let fd = std::io::File::open(&Path::new("shootout-k-nucleotide.data"));
get_sequence(&mut std::io::BufferedReader::new(fd), ">THREE")
} | conditional_block |
shootout-k-nucleotide.rs | // Copyright 2014 The Rust Project Developers. See the COPYRIGHT
// file at the top-level directory of this distribution and at
// http://rust-lang.org/COPYRIGHT.
//
// Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or
// http://www.apache.org/licenses/LICENSE-2.0> or the MIT license
// <LICENSE-MIT or http://opensource.org/licenses/MIT>, at your
// option. This file may not be copied, modified, or distributed
// except according to those terms.
// ignore-android see #10393 #13206
use std::string::String;
use std::slice;
use std::sync::{Arc, Future};
static TABLE: [u8, ..4] = [ 'A' as u8, 'C' as u8, 'G' as u8, 'T' as u8 ];
static TABLE_SIZE: uint = 2 << 16;
static OCCURRENCES: [&'static str, ..5] = [
"GGT",
"GGTA",
"GGTATT",
"GGTATTTTAATT",
"GGTATTTTAATTTATAGT",
];
// Code implementation
#[deriving(PartialEq, PartialOrd, Ord, Eq)]
struct Code(u64);
impl Code {
fn hash(&self) -> u64 {
let Code(ret) = *self;
return ret;
}
fn push_char(&self, c: u8) -> Code {
Code((self.hash() << 2) + (pack_symbol(c) as u64))
}
fn rotate(&self, c: u8, frame: uint) -> Code {
Code(self.push_char(c).hash() & ((1u64 << (2 * frame)) - 1))
}
fn pack(string: &str) -> Code {
string.bytes().fold(Code(0u64), |a, b| a.push_char(b))
}
fn | (&self, frame: uint) -> String {
let mut key = self.hash();
let mut result = Vec::new();
for _ in range(0, frame) {
result.push(unpack_symbol((key as u8) & 3));
key >>= 2;
}
result.reverse();
String::from_utf8(result).unwrap()
}
}
// Hash table implementation
trait TableCallback {
fn f(&self, entry: &mut Entry);
}
struct BumpCallback;
impl TableCallback for BumpCallback {
fn f(&self, entry: &mut Entry) {
entry.count += 1;
}
}
struct PrintCallback(&'static str);
impl TableCallback for PrintCallback {
fn f(&self, entry: &mut Entry) {
let PrintCallback(s) = *self;
println!("{}\t{}", entry.count as int, s);
}
}
struct Entry {
code: Code,
count: uint,
next: Option<Box<Entry>>,
}
struct Table {
count: uint,
items: Vec<Option<Box<Entry>>> }
struct Items<'a> {
cur: Option<&'a Entry>,
items: slice::Items<'a, Option<Box<Entry>>>,
}
impl Table {
fn new() -> Table {
Table {
count: 0,
items: Vec::from_fn(TABLE_SIZE, |_| None),
}
}
fn search_remainder<C:TableCallback>(item: &mut Entry, key: Code, c: C) {
match item.next {
None => {
let mut entry = box Entry {
code: key,
count: 0,
next: None,
};
c.f(&mut *entry);
item.next = Some(entry);
}
Some(ref mut entry) => {
if entry.code == key {
c.f(&mut **entry);
return;
}
Table::search_remainder(&mut **entry, key, c)
}
}
}
fn lookup<C:TableCallback>(&mut self, key: Code, c: C) {
let index = key.hash() % (TABLE_SIZE as u64);
{
if self.items.get(index as uint).is_none() {
let mut entry = box Entry {
code: key,
count: 0,
next: None,
};
c.f(&mut *entry);
*self.items.get_mut(index as uint) = Some(entry);
return;
}
}
{
let entry = &mut *self.items.get_mut(index as uint).get_mut_ref();
if entry.code == key {
c.f(&mut **entry);
return;
}
Table::search_remainder(&mut **entry, key, c)
}
}
fn iter<'a>(&'a self) -> Items<'a> {
Items { cur: None, items: self.items.iter() }
}
}
impl<'a> Iterator<&'a Entry> for Items<'a> {
fn next(&mut self) -> Option<&'a Entry> {
let ret = match self.cur {
None => {
let i;
loop {
match self.items.next() {
None => return None,
Some(&None) => {}
Some(&Some(ref a)) => { i = &**a; break }
}
}
self.cur = Some(&*i);
&*i
}
Some(c) => c
};
match ret.next {
None => { self.cur = None; }
Some(ref next) => { self.cur = Some(&**next); }
}
return Some(ret);
}
}
// Main program
fn pack_symbol(c: u8) -> u8 {
match c as char {
'A' => 0,
'C' => 1,
'G' => 2,
'T' => 3,
_ => fail!("{}", c as char),
}
}
fn unpack_symbol(c: u8) -> u8 {
TABLE[c as uint]
}
fn generate_frequencies(mut input: &[u8], frame: uint) -> Table {
let mut frequencies = Table::new();
if input.len() < frame { return frequencies; }
let mut code = Code(0);
// Pull first frame.
for _ in range(0, frame) {
code = code.push_char(input[0]);
input = input.slice_from(1);
}
frequencies.lookup(code, BumpCallback);
while input.len() != 0 && input[0] != ('>' as u8) {
code = code.rotate(input[0], frame);
frequencies.lookup(code, BumpCallback);
input = input.slice_from(1);
}
frequencies
}
fn print_frequencies(frequencies: &Table, frame: uint) {
let mut vector = Vec::new();
for entry in frequencies.iter() {
vector.push((entry.count, entry.code));
}
vector.as_mut_slice().sort();
let mut total_count = 0;
for &(count, _) in vector.iter() {
total_count += count;
}
for &(count, key) in vector.iter().rev() {
println!("{} {:.3f}",
key.unpack(frame).as_slice(),
(count as f32 * 100.0) / (total_count as f32));
}
println!("");
}
fn print_occurrences(frequencies: &mut Table, occurrence: &'static str) {
frequencies.lookup(Code::pack(occurrence), PrintCallback(occurrence))
}
fn get_sequence<R: Buffer>(r: &mut R, key: &str) -> Vec<u8> {
let mut res = Vec::new();
for l in r.lines().map(|l| l.ok().unwrap())
.skip_while(|l| key != l.as_slice().slice_to(key.len())).skip(1)
{
res.push_all(l.as_slice().trim().as_bytes());
}
for b in res.mut_iter() {
*b = b.to_ascii().to_upper().to_byte();
}
res
}
fn main() {
let input = if std::os::getenv("RUST_BENCH").is_some() {
let fd = std::io::File::open(&Path::new("shootout-k-nucleotide.data"));
get_sequence(&mut std::io::BufferedReader::new(fd), ">THREE")
} else {
get_sequence(&mut std::io::stdin(), ">THREE")
};
let input = Arc::new(input);
let nb_freqs: Vec<(uint, Future<Table>)> = range(1u, 3).map(|i| {
let input = input.clone();
(i, Future::spawn(proc() generate_frequencies(input.as_slice(), i)))
}).collect();
let occ_freqs: Vec<Future<Table>> = OCCURRENCES.iter().map(|&occ| {
let input = input.clone();
Future::spawn(proc() generate_frequencies(input.as_slice(), occ.len()))
}).collect();
for (i, freq) in nb_freqs.move_iter() {
print_frequencies(&freq.unwrap(), i);
}
for (&occ, freq) in OCCURRENCES.iter().zip(occ_freqs.move_iter()) {
print_occurrences(&mut freq.unwrap(), occ);
}
}
| unpack | identifier_name |
shootout-k-nucleotide.rs | // Copyright 2014 The Rust Project Developers. See the COPYRIGHT
// file at the top-level directory of this distribution and at
// http://rust-lang.org/COPYRIGHT.
//
// Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or
// http://www.apache.org/licenses/LICENSE-2.0> or the MIT license
// <LICENSE-MIT or http://opensource.org/licenses/MIT>, at your
// option. This file may not be copied, modified, or distributed
// except according to those terms.
// ignore-android see #10393 #13206
use std::string::String;
use std::slice;
use std::sync::{Arc, Future};
static TABLE: [u8, ..4] = [ 'A' as u8, 'C' as u8, 'G' as u8, 'T' as u8 ];
static TABLE_SIZE: uint = 2 << 16;
static OCCURRENCES: [&'static str, ..5] = [
"GGT",
"GGTA",
"GGTATT",
"GGTATTTTAATT",
"GGTATTTTAATTTATAGT",
];
// Code implementation
#[deriving(PartialEq, PartialOrd, Ord, Eq)]
struct Code(u64);
impl Code {
fn hash(&self) -> u64 {
let Code(ret) = *self;
return ret;
}
fn push_char(&self, c: u8) -> Code {
Code((self.hash() << 2) + (pack_symbol(c) as u64))
}
fn rotate(&self, c: u8, frame: uint) -> Code {
Code(self.push_char(c).hash() & ((1u64 << (2 * frame)) - 1))
}
fn pack(string: &str) -> Code {
string.bytes().fold(Code(0u64), |a, b| a.push_char(b))
}
fn unpack(&self, frame: uint) -> String {
let mut key = self.hash();
let mut result = Vec::new();
for _ in range(0, frame) {
result.push(unpack_symbol((key as u8) & 3));
key >>= 2;
}
result.reverse();
String::from_utf8(result).unwrap()
}
}
// Hash table implementation
trait TableCallback {
fn f(&self, entry: &mut Entry);
}
struct BumpCallback;
impl TableCallback for BumpCallback {
fn f(&self, entry: &mut Entry) {
entry.count += 1;
}
}
struct PrintCallback(&'static str);
impl TableCallback for PrintCallback {
fn f(&self, entry: &mut Entry) {
let PrintCallback(s) = *self;
println!("{}\t{}", entry.count as int, s);
}
}
struct Entry {
code: Code,
count: uint,
next: Option<Box<Entry>>,
}
struct Table {
count: uint,
items: Vec<Option<Box<Entry>>> }
struct Items<'a> {
cur: Option<&'a Entry>,
items: slice::Items<'a, Option<Box<Entry>>>,
}
impl Table {
fn new() -> Table {
Table {
count: 0,
items: Vec::from_fn(TABLE_SIZE, |_| None),
}
}
fn search_remainder<C:TableCallback>(item: &mut Entry, key: Code, c: C) {
match item.next {
None => {
let mut entry = box Entry {
code: key,
count: 0,
next: None,
};
c.f(&mut *entry);
item.next = Some(entry);
}
Some(ref mut entry) => {
if entry.code == key {
c.f(&mut **entry);
return;
}
Table::search_remainder(&mut **entry, key, c)
}
}
}
fn lookup<C:TableCallback>(&mut self, key: Code, c: C) {
let index = key.hash() % (TABLE_SIZE as u64);
{
if self.items.get(index as uint).is_none() {
let mut entry = box Entry {
code: key,
count: 0,
next: None,
};
c.f(&mut *entry);
*self.items.get_mut(index as uint) = Some(entry);
return;
}
}
{
let entry = &mut *self.items.get_mut(index as uint).get_mut_ref(); | }
Table::search_remainder(&mut **entry, key, c)
}
}
fn iter<'a>(&'a self) -> Items<'a> {
Items { cur: None, items: self.items.iter() }
}
}
impl<'a> Iterator<&'a Entry> for Items<'a> {
fn next(&mut self) -> Option<&'a Entry> {
let ret = match self.cur {
None => {
let i;
loop {
match self.items.next() {
None => return None,
Some(&None) => {}
Some(&Some(ref a)) => { i = &**a; break }
}
}
self.cur = Some(&*i);
&*i
}
Some(c) => c
};
match ret.next {
None => { self.cur = None; }
Some(ref next) => { self.cur = Some(&**next); }
}
return Some(ret);
}
}
// Main program
fn pack_symbol(c: u8) -> u8 {
match c as char {
'A' => 0,
'C' => 1,
'G' => 2,
'T' => 3,
_ => fail!("{}", c as char),
}
}
fn unpack_symbol(c: u8) -> u8 {
TABLE[c as uint]
}
fn generate_frequencies(mut input: &[u8], frame: uint) -> Table {
let mut frequencies = Table::new();
if input.len() < frame { return frequencies; }
let mut code = Code(0);
// Pull first frame.
for _ in range(0, frame) {
code = code.push_char(input[0]);
input = input.slice_from(1);
}
frequencies.lookup(code, BumpCallback);
while input.len() != 0 && input[0] != ('>' as u8) {
code = code.rotate(input[0], frame);
frequencies.lookup(code, BumpCallback);
input = input.slice_from(1);
}
frequencies
}
fn print_frequencies(frequencies: &Table, frame: uint) {
let mut vector = Vec::new();
for entry in frequencies.iter() {
vector.push((entry.count, entry.code));
}
vector.as_mut_slice().sort();
let mut total_count = 0;
for &(count, _) in vector.iter() {
total_count += count;
}
for &(count, key) in vector.iter().rev() {
println!("{} {:.3f}",
key.unpack(frame).as_slice(),
(count as f32 * 100.0) / (total_count as f32));
}
println!("");
}
fn print_occurrences(frequencies: &mut Table, occurrence: &'static str) {
frequencies.lookup(Code::pack(occurrence), PrintCallback(occurrence))
}
fn get_sequence<R: Buffer>(r: &mut R, key: &str) -> Vec<u8> {
let mut res = Vec::new();
for l in r.lines().map(|l| l.ok().unwrap())
.skip_while(|l| key != l.as_slice().slice_to(key.len())).skip(1)
{
res.push_all(l.as_slice().trim().as_bytes());
}
for b in res.mut_iter() {
*b = b.to_ascii().to_upper().to_byte();
}
res
}
fn main() {
let input = if std::os::getenv("RUST_BENCH").is_some() {
let fd = std::io::File::open(&Path::new("shootout-k-nucleotide.data"));
get_sequence(&mut std::io::BufferedReader::new(fd), ">THREE")
} else {
get_sequence(&mut std::io::stdin(), ">THREE")
};
let input = Arc::new(input);
let nb_freqs: Vec<(uint, Future<Table>)> = range(1u, 3).map(|i| {
let input = input.clone();
(i, Future::spawn(proc() generate_frequencies(input.as_slice(), i)))
}).collect();
let occ_freqs: Vec<Future<Table>> = OCCURRENCES.iter().map(|&occ| {
let input = input.clone();
Future::spawn(proc() generate_frequencies(input.as_slice(), occ.len()))
}).collect();
for (i, freq) in nb_freqs.move_iter() {
print_frequencies(&freq.unwrap(), i);
}
for (&occ, freq) in OCCURRENCES.iter().zip(occ_freqs.move_iter()) {
print_occurrences(&mut freq.unwrap(), occ);
}
} | if entry.code == key {
c.f(&mut **entry);
return; | random_line_split |
invariants.ts | import assertHasKey from "./invariants/assertHasKey";
import assertNotArray from "../utils/assertNotArray";
import constants from "../constants";
import makeScope from "../utils/makeScope";
import wrapArray from "../utils/wrapArray";
import {
Config,
InvariantsBaseArgs,
InvariantsExtraArgs,
ReducerName
} from "../types";
export default function invariants(
baseArgs: InvariantsBaseArgs,
extraArgs: InvariantsExtraArgs
) | {
var config = extraArgs.config;
if (!config.resourceName) throw new Error("Expected config.resourceName");
const scope = makeScope(config, baseArgs.reducerName);
if (!config.key) throw new Error(scope + ": Expected config.key");
if (!extraArgs.record) throw new Error(scope + ": Expected record/s");
extraArgs.assertValidStore(scope, extraArgs.current);
if (!baseArgs.canBeArray) {
assertNotArray(extraArgs.config, baseArgs.reducerName, extraArgs.record);
}
assertHasKey(extraArgs.config, scope, extraArgs.record);
} | identifier_body | |
invariants.ts | import assertHasKey from "./invariants/assertHasKey";
import assertNotArray from "../utils/assertNotArray";
import constants from "../constants";
import makeScope from "../utils/makeScope";
import wrapArray from "../utils/wrapArray";
import {
Config,
InvariantsBaseArgs,
InvariantsExtraArgs,
ReducerName
} from "../types";
export default function | (
baseArgs: InvariantsBaseArgs,
extraArgs: InvariantsExtraArgs
) {
var config = extraArgs.config;
if (!config.resourceName) throw new Error("Expected config.resourceName");
const scope = makeScope(config, baseArgs.reducerName);
if (!config.key) throw new Error(scope + ": Expected config.key");
if (!extraArgs.record) throw new Error(scope + ": Expected record/s");
extraArgs.assertValidStore(scope, extraArgs.current);
if (!baseArgs.canBeArray) {
assertNotArray(extraArgs.config, baseArgs.reducerName, extraArgs.record);
}
assertHasKey(extraArgs.config, scope, extraArgs.record);
}
| invariants | identifier_name |
invariants.ts | import assertHasKey from "./invariants/assertHasKey"; |
import {
Config,
InvariantsBaseArgs,
InvariantsExtraArgs,
ReducerName
} from "../types";
export default function invariants(
baseArgs: InvariantsBaseArgs,
extraArgs: InvariantsExtraArgs
) {
var config = extraArgs.config;
if (!config.resourceName) throw new Error("Expected config.resourceName");
const scope = makeScope(config, baseArgs.reducerName);
if (!config.key) throw new Error(scope + ": Expected config.key");
if (!extraArgs.record) throw new Error(scope + ": Expected record/s");
extraArgs.assertValidStore(scope, extraArgs.current);
if (!baseArgs.canBeArray) {
assertNotArray(extraArgs.config, baseArgs.reducerName, extraArgs.record);
}
assertHasKey(extraArgs.config, scope, extraArgs.record);
} | import assertNotArray from "../utils/assertNotArray";
import constants from "../constants";
import makeScope from "../utils/makeScope";
import wrapArray from "../utils/wrapArray"; | random_line_split |
pat-tuple-2.rs | // Copyright 2016 The Rust Project Developers. See the COPYRIGHT
// file at the top-level directory of this distribution and at
// http://rust-lang.org/COPYRIGHT.
//
// Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or
// http://www.apache.org/licenses/LICENSE-2.0> or the MIT license
// <LICENSE-MIT or http://opensource.org/licenses/MIT>, at your
// option. This file may not be copied, modified, or distributed
// except according to those terms.
// run-pass
fn tuple() {
let x = (1,);
match x {
(2, ..) => panic!(),
(..) => ()
}
}
fn tuple_struct() {
struct S(u8);
let x = S(1);
match x {
S(2, ..) => panic!(),
S(..) => ()
}
}
fn | () {
tuple();
tuple_struct();
}
| main | identifier_name |
pat-tuple-2.rs | // Copyright 2016 The Rust Project Developers. See the COPYRIGHT
// file at the top-level directory of this distribution and at
// http://rust-lang.org/COPYRIGHT.
//
// Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or
// http://www.apache.org/licenses/LICENSE-2.0> or the MIT license
// <LICENSE-MIT or http://opensource.org/licenses/MIT>, at your
// option. This file may not be copied, modified, or distributed
// except according to those terms.
// run-pass
fn tuple() {
let x = (1,);
match x { | (..) => ()
}
}
fn tuple_struct() {
struct S(u8);
let x = S(1);
match x {
S(2, ..) => panic!(),
S(..) => ()
}
}
fn main() {
tuple();
tuple_struct();
} | (2, ..) => panic!(), | random_line_split |
cabi_x86_64.rs | // Copyright 2012-2013 The Rust Project Developers. See the COPYRIGHT
// file at the top-level directory of this distribution and at
// http://rust-lang.org/COPYRIGHT.
//
// Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or
// http://www.apache.org/licenses/LICENSE-2.0> or the MIT license
// <LICENSE-MIT or http://opensource.org/licenses/MIT>, at your
// option. This file may not be copied, modified, or distributed
// except according to those terms.
// The classification code for the x86_64 ABI is taken from the clay language
// https://github.com/jckarter/clay/blob/master/compiler/src/externals.cpp
#![allow(non_upper_case_globals)]
use self::RegClass::*;
use llvm::{Integer, Pointer, Float, Double};
use llvm::{Struct, Array, Attribute, Vector};
use trans::cabi::{ArgType, FnType};
use trans::context::CrateContext;
use trans::type_::Type;
use std::cmp;
use std::iter::repeat;
#[derive(Clone, Copy, PartialEq)]
enum RegClass {
NoClass,
Int,
SSEFs,
SSEFv,
SSEDs,
SSEDv,
SSEInt(/* bitwidth */ u64),
/// Data that can appear in the upper half of an SSE register.
SSEUp,
X87,
X87Up,
ComplexX87,
Memory
}
trait TypeMethods {
fn is_reg_ty(&self) -> bool;
}
impl TypeMethods for Type {
fn is_reg_ty(&self) -> bool {
match self.kind() {
Integer | Pointer | Float | Double => true,
_ => false
}
}
}
impl RegClass {
fn is_sse(&self) -> bool {
match *self {
SSEFs | SSEFv | SSEDs | SSEDv | SSEInt(_) => true,
_ => false
}
}
}
trait ClassList {
fn is_pass_byval(&self) -> bool;
fn is_ret_bysret(&self) -> bool;
}
impl ClassList for [RegClass] {
fn is_pass_byval(&self) -> bool {
if self.is_empty() { return false; }
let class = self[0];
class == Memory
|| class == X87
|| class == ComplexX87
}
fn is_ret_bysret(&self) -> bool {
if self.is_empty() { return false; }
self[0] == Memory
}
}
fn classify_ty(ty: Type) -> Vec<RegClass> {
fn align(off: usize, ty: Type) -> usize {
let a = ty_align(ty);
return (off + a - 1) / a * a;
}
fn ty_align(ty: Type) -> usize {
match ty.kind() {
Integer => ((ty.int_width() as usize) + 7) / 8,
Pointer => 8,
Float => 4,
Double => 8,
Struct => {
if ty.is_packed() {
1
} else {
let str_tys = ty.field_types();
str_tys.iter().fold(1, |a, t| cmp::max(a, ty_align(*t)))
}
}
Array => {
let elt = ty.element_type();
ty_align(elt)
}
Vector => {
let len = ty.vector_length();
let elt = ty.element_type();
ty_align(elt) * len
}
_ => panic!("ty_align: unhandled type")
}
}
fn ty_size(ty: Type) -> usize {
match ty.kind() {
Integer => (ty.int_width() as usize + 7) / 8,
Pointer => 8,
Float => 4,
Double => 8,
Struct => {
let str_tys = ty.field_types();
if ty.is_packed() {
str_tys.iter().fold(0, |s, t| s + ty_size(*t))
} else {
let size = str_tys.iter().fold(0, |s, t| align(s, *t) + ty_size(*t));
align(size, ty)
}
}
Array => {
let len = ty.array_length();
let elt = ty.element_type();
let eltsz = ty_size(elt);
len * eltsz
}
Vector => {
let len = ty.vector_length();
let elt = ty.element_type();
let eltsz = ty_size(elt);
len * eltsz
}
_ => panic!("ty_size: unhandled type")
}
}
fn all_mem(cls: &mut [RegClass]) {
for elt in cls {
*elt = Memory;
}
}
fn unify(cls: &mut [RegClass],
i: usize,
newv: RegClass) {
if cls[i] == newv { return }
let to_write = match (cls[i], newv) {
(NoClass, _) => newv,
(_, NoClass) => return,
(Memory, _) |
(_, Memory) => Memory,
(Int, _) |
(_, Int) => Int,
(X87, _) |
(X87Up, _) |
(ComplexX87, _) |
(_, X87) |
(_, X87Up) |
(_, ComplexX87) => Memory,
(SSEFv, SSEUp) |
(SSEFs, SSEUp) |
(SSEDv, SSEUp) |
(SSEDs, SSEUp) |
(SSEInt(_), SSEUp) => return,
(_, _) => newv
};
cls[i] = to_write;
}
fn classify_struct(tys: &[Type],
cls: &mut [RegClass],
i: usize,
off: usize,
packed: bool) {
let mut field_off = off;
for ty in tys {
if !packed {
field_off = align(field_off, *ty);
}
classify(*ty, cls, i, field_off);
field_off += ty_size(*ty);
}
}
fn classify(ty: Type,
cls: &mut [RegClass], ix: usize,
off: usize) {
let t_align = ty_align(ty);
let t_size = ty_size(ty);
let misalign = off % t_align;
if misalign != 0 {
let mut i = off / 8;
let e = (off + t_size + 7) / 8;
while i < e {
unify(cls, ix + i, Memory);
i += 1;
}
return;
}
match ty.kind() {
Integer |
Pointer => {
unify(cls, ix + off / 8, Int);
}
Float => {
if off % 8 == 4 {
unify(cls, ix + off / 8, SSEFv);
} else {
unify(cls, ix + off / 8, SSEFs);
}
}
Double => {
unify(cls, ix + off / 8, SSEDs);
}
Struct => {
classify_struct(&ty.field_types(), cls, ix, off, ty.is_packed());
}
Array => {
let len = ty.array_length();
let elt = ty.element_type();
let eltsz = ty_size(elt);
let mut i = 0;
while i < len {
classify(elt, cls, ix, off + i * eltsz);
i += 1;
}
}
Vector => {
let len = ty.vector_length();
let elt = ty.element_type();
let eltsz = ty_size(elt);
let mut reg = match elt.kind() {
Integer => SSEInt(elt.int_width()),
Float => SSEFv,
Double => SSEDv,
_ => panic!("classify: unhandled vector element type")
};
let mut i = 0;
while i < len {
unify(cls, ix + (off + i * eltsz) / 8, reg);
// everything after the first one is the upper
// half of a register.
reg = SSEUp;
i += 1;
}
}
_ => panic!("classify: unhandled type")
}
}
fn fixup(ty: Type, cls: &mut [RegClass]) {
let mut i = 0;
let ty_kind = ty.kind();
let e = cls.len();
if cls.len() > 2 && (ty_kind == Struct || ty_kind == Array || ty_kind == Vector) {
if cls[i].is_sse() {
i += 1;
while i < e {
if cls[i] != SSEUp {
all_mem(cls);
return;
}
i += 1;
}
} else {
all_mem(cls);
return
}
} else {
while i < e {
if cls[i] == Memory {
all_mem(cls);
return;
}
if cls[i] == X87Up {
// for darwin
// cls[i] = SSEDs;
all_mem(cls);
return;
}
if cls[i] == SSEUp {
cls[i] = SSEDv;
} else if cls[i].is_sse() {
i += 1;
while i != e && cls[i] == SSEUp { i += 1; }
} else if cls[i] == X87 {
i += 1;
while i != e && cls[i] == X87Up { i += 1; }
} else {
i += 1;
}
}
}
}
let words = (ty_size(ty) + 7) / 8;
let mut cls: Vec<_> = repeat(NoClass).take(words).collect();
if words > 4 {
all_mem(&mut cls);
return cls;
}
classify(ty, &mut cls, 0, 0);
fixup(ty, &mut cls);
return cls;
}
fn | (ccx: &CrateContext, cls: &[RegClass]) -> Type {
fn llvec_len(cls: &[RegClass]) -> usize {
let mut len = 1;
for c in cls {
if *c != SSEUp {
break;
}
len += 1;
}
return len;
}
let mut tys = Vec::new();
let mut i = 0;
let e = cls.len();
while i < e {
match cls[i] {
Int => {
tys.push(Type::i64(ccx));
}
SSEFv | SSEDv | SSEInt(_) => {
let (elts_per_word, elt_ty) = match cls[i] {
SSEFv => (2, Type::f32(ccx)),
SSEDv => (1, Type::f64(ccx)),
SSEInt(bits) => {
assert!(bits == 8 || bits == 16 || bits == 32 || bits == 64,
"llreg_ty: unsupported SSEInt width {}", bits);
(64 / bits, Type::ix(ccx, bits))
}
_ => unreachable!(),
};
let vec_len = llvec_len(&cls[i + 1..]);
let vec_ty = Type::vector(&elt_ty, vec_len as u64 * elts_per_word);
tys.push(vec_ty);
i += vec_len;
continue;
}
SSEFs => {
tys.push(Type::f32(ccx));
}
SSEDs => {
tys.push(Type::f64(ccx));
}
_ => panic!("llregtype: unhandled class")
}
i += 1;
}
if tys.len() == 1 && tys[0].kind() == Vector {
// if the type contains only a vector, pass it as that vector.
tys[0]
} else {
Type::struct_(ccx, &tys, false)
}
}
pub fn compute_abi_info(ccx: &CrateContext,
atys: &[Type],
rty: Type,
ret_def: bool) -> FnType {
fn x86_64_ty<F>(ccx: &CrateContext,
ty: Type,
is_mem_cls: F,
ind_attr: Attribute)
-> ArgType where
F: FnOnce(&[RegClass]) -> bool,
{
if !ty.is_reg_ty() {
let cls = classify_ty(ty);
if is_mem_cls(&cls) {
ArgType::indirect(ty, Some(ind_attr))
} else {
ArgType::direct(ty,
Some(llreg_ty(ccx, &cls)),
None,
None)
}
} else {
let attr = if ty == Type::i1(ccx) { Some(Attribute::ZExt) } else { None };
ArgType::direct(ty, None, None, attr)
}
}
let mut arg_tys = Vec::new();
for t in atys {
let ty = x86_64_ty(ccx, *t, |cls| cls.is_pass_byval(), Attribute::ByVal);
arg_tys.push(ty);
}
let ret_ty = if ret_def {
x86_64_ty(ccx, rty, |cls| cls.is_ret_bysret(), Attribute::StructRet)
} else {
ArgType::direct(Type::void(ccx), None, None, None)
};
return FnType {
arg_tys: arg_tys,
ret_ty: ret_ty,
};
}
| llreg_ty | identifier_name |
cabi_x86_64.rs | // Copyright 2012-2013 The Rust Project Developers. See the COPYRIGHT
// file at the top-level directory of this distribution and at
// http://rust-lang.org/COPYRIGHT.
//
// Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or
// http://www.apache.org/licenses/LICENSE-2.0> or the MIT license
// <LICENSE-MIT or http://opensource.org/licenses/MIT>, at your
// option. This file may not be copied, modified, or distributed
// except according to those terms.
// The classification code for the x86_64 ABI is taken from the clay language
// https://github.com/jckarter/clay/blob/master/compiler/src/externals.cpp
#![allow(non_upper_case_globals)]
use self::RegClass::*;
use llvm::{Integer, Pointer, Float, Double};
use llvm::{Struct, Array, Attribute, Vector};
use trans::cabi::{ArgType, FnType};
use trans::context::CrateContext;
use trans::type_::Type;
use std::cmp;
use std::iter::repeat;
#[derive(Clone, Copy, PartialEq)]
enum RegClass {
NoClass,
Int,
SSEFs,
SSEFv,
SSEDs,
SSEDv,
SSEInt(/* bitwidth */ u64),
/// Data that can appear in the upper half of an SSE register.
SSEUp,
X87,
X87Up,
ComplexX87,
Memory
}
trait TypeMethods {
fn is_reg_ty(&self) -> bool;
}
impl TypeMethods for Type {
fn is_reg_ty(&self) -> bool {
match self.kind() {
Integer | Pointer | Float | Double => true,
_ => false
}
}
}
impl RegClass {
fn is_sse(&self) -> bool {
match *self {
SSEFs | SSEFv | SSEDs | SSEDv | SSEInt(_) => true,
_ => false
}
}
}
trait ClassList {
fn is_pass_byval(&self) -> bool;
fn is_ret_bysret(&self) -> bool;
}
impl ClassList for [RegClass] {
fn is_pass_byval(&self) -> bool {
if self.is_empty() { return false; }
let class = self[0];
class == Memory
|| class == X87
|| class == ComplexX87
} | if self.is_empty() { return false; }
self[0] == Memory
}
}
fn classify_ty(ty: Type) -> Vec<RegClass> {
fn align(off: usize, ty: Type) -> usize {
let a = ty_align(ty);
return (off + a - 1) / a * a;
}
fn ty_align(ty: Type) -> usize {
match ty.kind() {
Integer => ((ty.int_width() as usize) + 7) / 8,
Pointer => 8,
Float => 4,
Double => 8,
Struct => {
if ty.is_packed() {
1
} else {
let str_tys = ty.field_types();
str_tys.iter().fold(1, |a, t| cmp::max(a, ty_align(*t)))
}
}
Array => {
let elt = ty.element_type();
ty_align(elt)
}
Vector => {
let len = ty.vector_length();
let elt = ty.element_type();
ty_align(elt) * len
}
_ => panic!("ty_align: unhandled type")
}
}
fn ty_size(ty: Type) -> usize {
match ty.kind() {
Integer => (ty.int_width() as usize + 7) / 8,
Pointer => 8,
Float => 4,
Double => 8,
Struct => {
let str_tys = ty.field_types();
if ty.is_packed() {
str_tys.iter().fold(0, |s, t| s + ty_size(*t))
} else {
let size = str_tys.iter().fold(0, |s, t| align(s, *t) + ty_size(*t));
align(size, ty)
}
}
Array => {
let len = ty.array_length();
let elt = ty.element_type();
let eltsz = ty_size(elt);
len * eltsz
}
Vector => {
let len = ty.vector_length();
let elt = ty.element_type();
let eltsz = ty_size(elt);
len * eltsz
}
_ => panic!("ty_size: unhandled type")
}
}
fn all_mem(cls: &mut [RegClass]) {
for elt in cls {
*elt = Memory;
}
}
fn unify(cls: &mut [RegClass],
i: usize,
newv: RegClass) {
if cls[i] == newv { return }
let to_write = match (cls[i], newv) {
(NoClass, _) => newv,
(_, NoClass) => return,
(Memory, _) |
(_, Memory) => Memory,
(Int, _) |
(_, Int) => Int,
(X87, _) |
(X87Up, _) |
(ComplexX87, _) |
(_, X87) |
(_, X87Up) |
(_, ComplexX87) => Memory,
(SSEFv, SSEUp) |
(SSEFs, SSEUp) |
(SSEDv, SSEUp) |
(SSEDs, SSEUp) |
(SSEInt(_), SSEUp) => return,
(_, _) => newv
};
cls[i] = to_write;
}
fn classify_struct(tys: &[Type],
cls: &mut [RegClass],
i: usize,
off: usize,
packed: bool) {
let mut field_off = off;
for ty in tys {
if !packed {
field_off = align(field_off, *ty);
}
classify(*ty, cls, i, field_off);
field_off += ty_size(*ty);
}
}
fn classify(ty: Type,
cls: &mut [RegClass], ix: usize,
off: usize) {
let t_align = ty_align(ty);
let t_size = ty_size(ty);
let misalign = off % t_align;
if misalign != 0 {
let mut i = off / 8;
let e = (off + t_size + 7) / 8;
while i < e {
unify(cls, ix + i, Memory);
i += 1;
}
return;
}
match ty.kind() {
Integer |
Pointer => {
unify(cls, ix + off / 8, Int);
}
Float => {
if off % 8 == 4 {
unify(cls, ix + off / 8, SSEFv);
} else {
unify(cls, ix + off / 8, SSEFs);
}
}
Double => {
unify(cls, ix + off / 8, SSEDs);
}
Struct => {
classify_struct(&ty.field_types(), cls, ix, off, ty.is_packed());
}
Array => {
let len = ty.array_length();
let elt = ty.element_type();
let eltsz = ty_size(elt);
let mut i = 0;
while i < len {
classify(elt, cls, ix, off + i * eltsz);
i += 1;
}
}
Vector => {
let len = ty.vector_length();
let elt = ty.element_type();
let eltsz = ty_size(elt);
let mut reg = match elt.kind() {
Integer => SSEInt(elt.int_width()),
Float => SSEFv,
Double => SSEDv,
_ => panic!("classify: unhandled vector element type")
};
let mut i = 0;
while i < len {
unify(cls, ix + (off + i * eltsz) / 8, reg);
// everything after the first one is the upper
// half of a register.
reg = SSEUp;
i += 1;
}
}
_ => panic!("classify: unhandled type")
}
}
fn fixup(ty: Type, cls: &mut [RegClass]) {
let mut i = 0;
let ty_kind = ty.kind();
let e = cls.len();
if cls.len() > 2 && (ty_kind == Struct || ty_kind == Array || ty_kind == Vector) {
if cls[i].is_sse() {
i += 1;
while i < e {
if cls[i] != SSEUp {
all_mem(cls);
return;
}
i += 1;
}
} else {
all_mem(cls);
return
}
} else {
while i < e {
if cls[i] == Memory {
all_mem(cls);
return;
}
if cls[i] == X87Up {
// for darwin
// cls[i] = SSEDs;
all_mem(cls);
return;
}
if cls[i] == SSEUp {
cls[i] = SSEDv;
} else if cls[i].is_sse() {
i += 1;
while i != e && cls[i] == SSEUp { i += 1; }
} else if cls[i] == X87 {
i += 1;
while i != e && cls[i] == X87Up { i += 1; }
} else {
i += 1;
}
}
}
}
let words = (ty_size(ty) + 7) / 8;
let mut cls: Vec<_> = repeat(NoClass).take(words).collect();
if words > 4 {
all_mem(&mut cls);
return cls;
}
classify(ty, &mut cls, 0, 0);
fixup(ty, &mut cls);
return cls;
}
fn llreg_ty(ccx: &CrateContext, cls: &[RegClass]) -> Type {
fn llvec_len(cls: &[RegClass]) -> usize {
let mut len = 1;
for c in cls {
if *c != SSEUp {
break;
}
len += 1;
}
return len;
}
let mut tys = Vec::new();
let mut i = 0;
let e = cls.len();
while i < e {
match cls[i] {
Int => {
tys.push(Type::i64(ccx));
}
SSEFv | SSEDv | SSEInt(_) => {
let (elts_per_word, elt_ty) = match cls[i] {
SSEFv => (2, Type::f32(ccx)),
SSEDv => (1, Type::f64(ccx)),
SSEInt(bits) => {
assert!(bits == 8 || bits == 16 || bits == 32 || bits == 64,
"llreg_ty: unsupported SSEInt width {}", bits);
(64 / bits, Type::ix(ccx, bits))
}
_ => unreachable!(),
};
let vec_len = llvec_len(&cls[i + 1..]);
let vec_ty = Type::vector(&elt_ty, vec_len as u64 * elts_per_word);
tys.push(vec_ty);
i += vec_len;
continue;
}
SSEFs => {
tys.push(Type::f32(ccx));
}
SSEDs => {
tys.push(Type::f64(ccx));
}
_ => panic!("llregtype: unhandled class")
}
i += 1;
}
if tys.len() == 1 && tys[0].kind() == Vector {
// if the type contains only a vector, pass it as that vector.
tys[0]
} else {
Type::struct_(ccx, &tys, false)
}
}
pub fn compute_abi_info(ccx: &CrateContext,
atys: &[Type],
rty: Type,
ret_def: bool) -> FnType {
fn x86_64_ty<F>(ccx: &CrateContext,
ty: Type,
is_mem_cls: F,
ind_attr: Attribute)
-> ArgType where
F: FnOnce(&[RegClass]) -> bool,
{
if !ty.is_reg_ty() {
let cls = classify_ty(ty);
if is_mem_cls(&cls) {
ArgType::indirect(ty, Some(ind_attr))
} else {
ArgType::direct(ty,
Some(llreg_ty(ccx, &cls)),
None,
None)
}
} else {
let attr = if ty == Type::i1(ccx) { Some(Attribute::ZExt) } else { None };
ArgType::direct(ty, None, None, attr)
}
}
let mut arg_tys = Vec::new();
for t in atys {
let ty = x86_64_ty(ccx, *t, |cls| cls.is_pass_byval(), Attribute::ByVal);
arg_tys.push(ty);
}
let ret_ty = if ret_def {
x86_64_ty(ccx, rty, |cls| cls.is_ret_bysret(), Attribute::StructRet)
} else {
ArgType::direct(Type::void(ccx), None, None, None)
};
return FnType {
arg_tys: arg_tys,
ret_ty: ret_ty,
};
} |
fn is_ret_bysret(&self) -> bool { | random_line_split |
cabi_x86_64.rs | // Copyright 2012-2013 The Rust Project Developers. See the COPYRIGHT
// file at the top-level directory of this distribution and at
// http://rust-lang.org/COPYRIGHT.
//
// Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or
// http://www.apache.org/licenses/LICENSE-2.0> or the MIT license
// <LICENSE-MIT or http://opensource.org/licenses/MIT>, at your
// option. This file may not be copied, modified, or distributed
// except according to those terms.
// The classification code for the x86_64 ABI is taken from the clay language
// https://github.com/jckarter/clay/blob/master/compiler/src/externals.cpp
#![allow(non_upper_case_globals)]
use self::RegClass::*;
use llvm::{Integer, Pointer, Float, Double};
use llvm::{Struct, Array, Attribute, Vector};
use trans::cabi::{ArgType, FnType};
use trans::context::CrateContext;
use trans::type_::Type;
use std::cmp;
use std::iter::repeat;
#[derive(Clone, Copy, PartialEq)]
enum RegClass {
NoClass,
Int,
SSEFs,
SSEFv,
SSEDs,
SSEDv,
SSEInt(/* bitwidth */ u64),
/// Data that can appear in the upper half of an SSE register.
SSEUp,
X87,
X87Up,
ComplexX87,
Memory
}
trait TypeMethods {
fn is_reg_ty(&self) -> bool;
}
impl TypeMethods for Type {
fn is_reg_ty(&self) -> bool {
match self.kind() {
Integer | Pointer | Float | Double => true,
_ => false
}
}
}
impl RegClass {
fn is_sse(&self) -> bool |
}
trait ClassList {
fn is_pass_byval(&self) -> bool;
fn is_ret_bysret(&self) -> bool;
}
impl ClassList for [RegClass] {
fn is_pass_byval(&self) -> bool {
if self.is_empty() { return false; }
let class = self[0];
class == Memory
|| class == X87
|| class == ComplexX87
}
fn is_ret_bysret(&self) -> bool {
if self.is_empty() { return false; }
self[0] == Memory
}
}
fn classify_ty(ty: Type) -> Vec<RegClass> {
fn align(off: usize, ty: Type) -> usize {
let a = ty_align(ty);
return (off + a - 1) / a * a;
}
fn ty_align(ty: Type) -> usize {
match ty.kind() {
Integer => ((ty.int_width() as usize) + 7) / 8,
Pointer => 8,
Float => 4,
Double => 8,
Struct => {
if ty.is_packed() {
1
} else {
let str_tys = ty.field_types();
str_tys.iter().fold(1, |a, t| cmp::max(a, ty_align(*t)))
}
}
Array => {
let elt = ty.element_type();
ty_align(elt)
}
Vector => {
let len = ty.vector_length();
let elt = ty.element_type();
ty_align(elt) * len
}
_ => panic!("ty_align: unhandled type")
}
}
fn ty_size(ty: Type) -> usize {
match ty.kind() {
Integer => (ty.int_width() as usize + 7) / 8,
Pointer => 8,
Float => 4,
Double => 8,
Struct => {
let str_tys = ty.field_types();
if ty.is_packed() {
str_tys.iter().fold(0, |s, t| s + ty_size(*t))
} else {
let size = str_tys.iter().fold(0, |s, t| align(s, *t) + ty_size(*t));
align(size, ty)
}
}
Array => {
let len = ty.array_length();
let elt = ty.element_type();
let eltsz = ty_size(elt);
len * eltsz
}
Vector => {
let len = ty.vector_length();
let elt = ty.element_type();
let eltsz = ty_size(elt);
len * eltsz
}
_ => panic!("ty_size: unhandled type")
}
}
fn all_mem(cls: &mut [RegClass]) {
for elt in cls {
*elt = Memory;
}
}
fn unify(cls: &mut [RegClass],
i: usize,
newv: RegClass) {
if cls[i] == newv { return }
let to_write = match (cls[i], newv) {
(NoClass, _) => newv,
(_, NoClass) => return,
(Memory, _) |
(_, Memory) => Memory,
(Int, _) |
(_, Int) => Int,
(X87, _) |
(X87Up, _) |
(ComplexX87, _) |
(_, X87) |
(_, X87Up) |
(_, ComplexX87) => Memory,
(SSEFv, SSEUp) |
(SSEFs, SSEUp) |
(SSEDv, SSEUp) |
(SSEDs, SSEUp) |
(SSEInt(_), SSEUp) => return,
(_, _) => newv
};
cls[i] = to_write;
}
fn classify_struct(tys: &[Type],
cls: &mut [RegClass],
i: usize,
off: usize,
packed: bool) {
let mut field_off = off;
for ty in tys {
if !packed {
field_off = align(field_off, *ty);
}
classify(*ty, cls, i, field_off);
field_off += ty_size(*ty);
}
}
fn classify(ty: Type,
cls: &mut [RegClass], ix: usize,
off: usize) {
let t_align = ty_align(ty);
let t_size = ty_size(ty);
let misalign = off % t_align;
if misalign != 0 {
let mut i = off / 8;
let e = (off + t_size + 7) / 8;
while i < e {
unify(cls, ix + i, Memory);
i += 1;
}
return;
}
match ty.kind() {
Integer |
Pointer => {
unify(cls, ix + off / 8, Int);
}
Float => {
if off % 8 == 4 {
unify(cls, ix + off / 8, SSEFv);
} else {
unify(cls, ix + off / 8, SSEFs);
}
}
Double => {
unify(cls, ix + off / 8, SSEDs);
}
Struct => {
classify_struct(&ty.field_types(), cls, ix, off, ty.is_packed());
}
Array => {
let len = ty.array_length();
let elt = ty.element_type();
let eltsz = ty_size(elt);
let mut i = 0;
while i < len {
classify(elt, cls, ix, off + i * eltsz);
i += 1;
}
}
Vector => {
let len = ty.vector_length();
let elt = ty.element_type();
let eltsz = ty_size(elt);
let mut reg = match elt.kind() {
Integer => SSEInt(elt.int_width()),
Float => SSEFv,
Double => SSEDv,
_ => panic!("classify: unhandled vector element type")
};
let mut i = 0;
while i < len {
unify(cls, ix + (off + i * eltsz) / 8, reg);
// everything after the first one is the upper
// half of a register.
reg = SSEUp;
i += 1;
}
}
_ => panic!("classify: unhandled type")
}
}
fn fixup(ty: Type, cls: &mut [RegClass]) {
let mut i = 0;
let ty_kind = ty.kind();
let e = cls.len();
if cls.len() > 2 && (ty_kind == Struct || ty_kind == Array || ty_kind == Vector) {
if cls[i].is_sse() {
i += 1;
while i < e {
if cls[i] != SSEUp {
all_mem(cls);
return;
}
i += 1;
}
} else {
all_mem(cls);
return
}
} else {
while i < e {
if cls[i] == Memory {
all_mem(cls);
return;
}
if cls[i] == X87Up {
// for darwin
// cls[i] = SSEDs;
all_mem(cls);
return;
}
if cls[i] == SSEUp {
cls[i] = SSEDv;
} else if cls[i].is_sse() {
i += 1;
while i != e && cls[i] == SSEUp { i += 1; }
} else if cls[i] == X87 {
i += 1;
while i != e && cls[i] == X87Up { i += 1; }
} else {
i += 1;
}
}
}
}
let words = (ty_size(ty) + 7) / 8;
let mut cls: Vec<_> = repeat(NoClass).take(words).collect();
if words > 4 {
all_mem(&mut cls);
return cls;
}
classify(ty, &mut cls, 0, 0);
fixup(ty, &mut cls);
return cls;
}
fn llreg_ty(ccx: &CrateContext, cls: &[RegClass]) -> Type {
fn llvec_len(cls: &[RegClass]) -> usize {
let mut len = 1;
for c in cls {
if *c != SSEUp {
break;
}
len += 1;
}
return len;
}
let mut tys = Vec::new();
let mut i = 0;
let e = cls.len();
while i < e {
match cls[i] {
Int => {
tys.push(Type::i64(ccx));
}
SSEFv | SSEDv | SSEInt(_) => {
let (elts_per_word, elt_ty) = match cls[i] {
SSEFv => (2, Type::f32(ccx)),
SSEDv => (1, Type::f64(ccx)),
SSEInt(bits) => {
assert!(bits == 8 || bits == 16 || bits == 32 || bits == 64,
"llreg_ty: unsupported SSEInt width {}", bits);
(64 / bits, Type::ix(ccx, bits))
}
_ => unreachable!(),
};
let vec_len = llvec_len(&cls[i + 1..]);
let vec_ty = Type::vector(&elt_ty, vec_len as u64 * elts_per_word);
tys.push(vec_ty);
i += vec_len;
continue;
}
SSEFs => {
tys.push(Type::f32(ccx));
}
SSEDs => {
tys.push(Type::f64(ccx));
}
_ => panic!("llregtype: unhandled class")
}
i += 1;
}
if tys.len() == 1 && tys[0].kind() == Vector {
// if the type contains only a vector, pass it as that vector.
tys[0]
} else {
Type::struct_(ccx, &tys, false)
}
}
pub fn compute_abi_info(ccx: &CrateContext,
atys: &[Type],
rty: Type,
ret_def: bool) -> FnType {
fn x86_64_ty<F>(ccx: &CrateContext,
ty: Type,
is_mem_cls: F,
ind_attr: Attribute)
-> ArgType where
F: FnOnce(&[RegClass]) -> bool,
{
if !ty.is_reg_ty() {
let cls = classify_ty(ty);
if is_mem_cls(&cls) {
ArgType::indirect(ty, Some(ind_attr))
} else {
ArgType::direct(ty,
Some(llreg_ty(ccx, &cls)),
None,
None)
}
} else {
let attr = if ty == Type::i1(ccx) { Some(Attribute::ZExt) } else { None };
ArgType::direct(ty, None, None, attr)
}
}
let mut arg_tys = Vec::new();
for t in atys {
let ty = x86_64_ty(ccx, *t, |cls| cls.is_pass_byval(), Attribute::ByVal);
arg_tys.push(ty);
}
let ret_ty = if ret_def {
x86_64_ty(ccx, rty, |cls| cls.is_ret_bysret(), Attribute::StructRet)
} else {
ArgType::direct(Type::void(ccx), None, None, None)
};
return FnType {
arg_tys: arg_tys,
ret_ty: ret_ty,
};
}
| {
match *self {
SSEFs | SSEFv | SSEDs | SSEDv | SSEInt(_) => true,
_ => false
}
} | identifier_body |
framework.py | # This file is part of ICLS.
#
# ICLS is free software: you can redistribute it and/or modify
# it under the terms of the GNU General Public License as published by
# the Free Software Foundation, either version 3 of the License, or
# (at your option) any later version.
#
# ICLS is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
# GNU General Public License for more details.
#
# You should have received a copy of the GNU General Public License
# along with ICLS. If not, see <http://www.gnu.org/licenses/>.
import xml.dom.minidom
from time import strftime, strptime
from sys import exit
from textwrap import wrap
from os import path
def colorize(the_color='blue',entry='',new_line=0):
color={'gray':30,'green':32,'red':31,'blue':34,'magenta':35,'cyan':36,'white':37,'highgreen':42,'highblue':44,'highred':41,'highgray':47}
if new_line==1:
new_line='\n'
else:
new_line=''
return_me='\033[1;'+str(color[the_color])+'m'+entry+'\033[1;m'+new_line
return return_me
def getText(nodelist):
rc = []
for node in nodelist:
if node.nodeType == node.TEXT_NODE:
rc.append(node.data)
return ''.join(rc)
# Only if error is one that halts things, stop script
def aws_print_error(error_obj):
error_code=getText(xml.dom.minidom.parseString(error_obj[2]).documentElement.getElementsByTagName('Code')[0].childNodes)
error_message=getText(xml.dom.minidom.parseString(error_obj[2]).documentElement.getElementsByTagName('Message')[0].childNodes)
error_message=colorize('red',"ERROR",1)+colorize('red',"AWS Error Code: ")+error_code+colorize('red',"\nError Message: ")+error_message
print error_message
exit()
return True
def print_error(error_text):
error_message=colorize('red',"ERROR",1)+colorize('red',"\nError Message: ")+error_text
print error_message
exit()
return True
#takes an entry, and makes it pretty!
def makeover(entry,ismonochrome=False):
if ismonochrome==False:
output=colorize('gray','========================================',1)
output+=colorize('cyan',entry['entry'],1)
output+=colorize('cyan',strftime("%H:%M %m.%d.%Y", strptime(entry['date'],"%Y-%m-%dT%H:%M:%S+0000")),1)
output+=colorize('gray','ID: '+entry.name,0)
else:
output="========================================\n"
output+=entry['entry']+"\n"
output+=strftime("%H:%M %m.%d.%Y", strptime(entry['date'],"%Y-%m-%dT%H:%M:%S+0000"))+"\n"
output+='ID: '+entry.name
return output
#If, during parsing, help was flagged print out help text and then exit TODO read it from a md file
def print_help():
filepath = path.join(path.dirname(path.abspath(__file__)), 'DOCUMENTATION.mkd') | f.close()
exit() | f = open(filepath,'r')
print f.read() | random_line_split |
framework.py | # This file is part of ICLS.
#
# ICLS is free software: you can redistribute it and/or modify
# it under the terms of the GNU General Public License as published by
# the Free Software Foundation, either version 3 of the License, or
# (at your option) any later version.
#
# ICLS is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
# GNU General Public License for more details.
#
# You should have received a copy of the GNU General Public License
# along with ICLS. If not, see <http://www.gnu.org/licenses/>.
import xml.dom.minidom
from time import strftime, strptime
from sys import exit
from textwrap import wrap
from os import path
def colorize(the_color='blue',entry='',new_line=0):
color={'gray':30,'green':32,'red':31,'blue':34,'magenta':35,'cyan':36,'white':37,'highgreen':42,'highblue':44,'highred':41,'highgray':47}
if new_line==1:
new_line='\n'
else:
new_line=''
return_me='\033[1;'+str(color[the_color])+'m'+entry+'\033[1;m'+new_line
return return_me
def getText(nodelist):
rc = []
for node in nodelist:
if node.nodeType == node.TEXT_NODE:
rc.append(node.data)
return ''.join(rc)
# Only if error is one that halts things, stop script
def aws_print_error(error_obj):
error_code=getText(xml.dom.minidom.parseString(error_obj[2]).documentElement.getElementsByTagName('Code')[0].childNodes)
error_message=getText(xml.dom.minidom.parseString(error_obj[2]).documentElement.getElementsByTagName('Message')[0].childNodes)
error_message=colorize('red',"ERROR",1)+colorize('red',"AWS Error Code: ")+error_code+colorize('red',"\nError Message: ")+error_message
print error_message
exit()
return True
def print_error(error_text):
error_message=colorize('red',"ERROR",1)+colorize('red',"\nError Message: ")+error_text
print error_message
exit()
return True
#takes an entry, and makes it pretty!
def makeover(entry,ismonochrome=False):
if ismonochrome==False:
output=colorize('gray','========================================',1)
output+=colorize('cyan',entry['entry'],1)
output+=colorize('cyan',strftime("%H:%M %m.%d.%Y", strptime(entry['date'],"%Y-%m-%dT%H:%M:%S+0000")),1)
output+=colorize('gray','ID: '+entry.name,0)
else:
|
return output
#If, during parsing, help was flagged print out help text and then exit TODO read it from a md file
def print_help():
filepath = path.join(path.dirname(path.abspath(__file__)), 'DOCUMENTATION.mkd')
f = open(filepath,'r')
print f.read()
f.close()
exit() | output="========================================\n"
output+=entry['entry']+"\n"
output+=strftime("%H:%M %m.%d.%Y", strptime(entry['date'],"%Y-%m-%dT%H:%M:%S+0000"))+"\n"
output+='ID: '+entry.name | conditional_block |
framework.py | # This file is part of ICLS.
#
# ICLS is free software: you can redistribute it and/or modify
# it under the terms of the GNU General Public License as published by
# the Free Software Foundation, either version 3 of the License, or
# (at your option) any later version.
#
# ICLS is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
# GNU General Public License for more details.
#
# You should have received a copy of the GNU General Public License
# along with ICLS. If not, see <http://www.gnu.org/licenses/>.
import xml.dom.minidom
from time import strftime, strptime
from sys import exit
from textwrap import wrap
from os import path
def | (the_color='blue',entry='',new_line=0):
color={'gray':30,'green':32,'red':31,'blue':34,'magenta':35,'cyan':36,'white':37,'highgreen':42,'highblue':44,'highred':41,'highgray':47}
if new_line==1:
new_line='\n'
else:
new_line=''
return_me='\033[1;'+str(color[the_color])+'m'+entry+'\033[1;m'+new_line
return return_me
def getText(nodelist):
rc = []
for node in nodelist:
if node.nodeType == node.TEXT_NODE:
rc.append(node.data)
return ''.join(rc)
# Only if error is one that halts things, stop script
def aws_print_error(error_obj):
error_code=getText(xml.dom.minidom.parseString(error_obj[2]).documentElement.getElementsByTagName('Code')[0].childNodes)
error_message=getText(xml.dom.minidom.parseString(error_obj[2]).documentElement.getElementsByTagName('Message')[0].childNodes)
error_message=colorize('red',"ERROR",1)+colorize('red',"AWS Error Code: ")+error_code+colorize('red',"\nError Message: ")+error_message
print error_message
exit()
return True
def print_error(error_text):
error_message=colorize('red',"ERROR",1)+colorize('red',"\nError Message: ")+error_text
print error_message
exit()
return True
#takes an entry, and makes it pretty!
def makeover(entry,ismonochrome=False):
if ismonochrome==False:
output=colorize('gray','========================================',1)
output+=colorize('cyan',entry['entry'],1)
output+=colorize('cyan',strftime("%H:%M %m.%d.%Y", strptime(entry['date'],"%Y-%m-%dT%H:%M:%S+0000")),1)
output+=colorize('gray','ID: '+entry.name,0)
else:
output="========================================\n"
output+=entry['entry']+"\n"
output+=strftime("%H:%M %m.%d.%Y", strptime(entry['date'],"%Y-%m-%dT%H:%M:%S+0000"))+"\n"
output+='ID: '+entry.name
return output
#If, during parsing, help was flagged print out help text and then exit TODO read it from a md file
def print_help():
filepath = path.join(path.dirname(path.abspath(__file__)), 'DOCUMENTATION.mkd')
f = open(filepath,'r')
print f.read()
f.close()
exit() | colorize | identifier_name |
framework.py | # This file is part of ICLS.
#
# ICLS is free software: you can redistribute it and/or modify
# it under the terms of the GNU General Public License as published by
# the Free Software Foundation, either version 3 of the License, or
# (at your option) any later version.
#
# ICLS is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
# GNU General Public License for more details.
#
# You should have received a copy of the GNU General Public License
# along with ICLS. If not, see <http://www.gnu.org/licenses/>.
import xml.dom.minidom
from time import strftime, strptime
from sys import exit
from textwrap import wrap
from os import path
def colorize(the_color='blue',entry='',new_line=0):
color={'gray':30,'green':32,'red':31,'blue':34,'magenta':35,'cyan':36,'white':37,'highgreen':42,'highblue':44,'highred':41,'highgray':47}
if new_line==1:
new_line='\n'
else:
new_line=''
return_me='\033[1;'+str(color[the_color])+'m'+entry+'\033[1;m'+new_line
return return_me
def getText(nodelist):
rc = []
for node in nodelist:
if node.nodeType == node.TEXT_NODE:
rc.append(node.data)
return ''.join(rc)
# Only if error is one that halts things, stop script
def aws_print_error(error_obj):
error_code=getText(xml.dom.minidom.parseString(error_obj[2]).documentElement.getElementsByTagName('Code')[0].childNodes)
error_message=getText(xml.dom.minidom.parseString(error_obj[2]).documentElement.getElementsByTagName('Message')[0].childNodes)
error_message=colorize('red',"ERROR",1)+colorize('red',"AWS Error Code: ")+error_code+colorize('red',"\nError Message: ")+error_message
print error_message
exit()
return True
def print_error(error_text):
error_message=colorize('red',"ERROR",1)+colorize('red',"\nError Message: ")+error_text
print error_message
exit()
return True
#takes an entry, and makes it pretty!
def makeover(entry,ismonochrome=False):
if ismonochrome==False:
output=colorize('gray','========================================',1)
output+=colorize('cyan',entry['entry'],1)
output+=colorize('cyan',strftime("%H:%M %m.%d.%Y", strptime(entry['date'],"%Y-%m-%dT%H:%M:%S+0000")),1)
output+=colorize('gray','ID: '+entry.name,0)
else:
output="========================================\n"
output+=entry['entry']+"\n"
output+=strftime("%H:%M %m.%d.%Y", strptime(entry['date'],"%Y-%m-%dT%H:%M:%S+0000"))+"\n"
output+='ID: '+entry.name
return output
#If, during parsing, help was flagged print out help text and then exit TODO read it from a md file
def print_help():
| filepath = path.join(path.dirname(path.abspath(__file__)), 'DOCUMENTATION.mkd')
f = open(filepath,'r')
print f.read()
f.close()
exit() | identifier_body | |
lib.rs | #[macro_use(expect)]
extern crate expectest;
extern crate sql;
pub mod lexer;
pub mod parser;
pub mod query_typer;
pub mod query_validator; | use sql::parser::parse;
use sql::query_typer::type_inferring_old;
use sql::query_validator::validate_old;
use sql::query_executer::{execute, ExecutionResult};
use sql::data_manager::DataManager;
use sql::catalog_manager::CatalogManager;
pub fn evaluate_query(query: &str, data_manager: &DataManager, catalog_manager: &CatalogManager) -> Result<ExecutionResult, String> {
tokenize(query)
.and_then(parse)
.and_then(|statement| type_inferring_old(catalog_manager, statement))
.and_then(|statement| validate_old(catalog_manager, statement))
.and_then(|statement| execute(catalog_manager, data_manager, statement))
} | pub mod query_executer;
pub mod catalog_manager;
pub mod data_manager;
use sql::lexer::tokenize; | random_line_split |
lib.rs | #[macro_use(expect)]
extern crate expectest;
extern crate sql;
pub mod lexer;
pub mod parser;
pub mod query_typer;
pub mod query_validator;
pub mod query_executer;
pub mod catalog_manager;
pub mod data_manager;
use sql::lexer::tokenize;
use sql::parser::parse;
use sql::query_typer::type_inferring_old;
use sql::query_validator::validate_old;
use sql::query_executer::{execute, ExecutionResult};
use sql::data_manager::DataManager;
use sql::catalog_manager::CatalogManager;
pub fn evaluate_query(query: &str, data_manager: &DataManager, catalog_manager: &CatalogManager) -> Result<ExecutionResult, String> | {
tokenize(query)
.and_then(parse)
.and_then(|statement| type_inferring_old(catalog_manager, statement))
.and_then(|statement| validate_old(catalog_manager, statement))
.and_then(|statement| execute(catalog_manager, data_manager, statement))
} | identifier_body | |
lib.rs | #[macro_use(expect)]
extern crate expectest;
extern crate sql;
pub mod lexer;
pub mod parser;
pub mod query_typer;
pub mod query_validator;
pub mod query_executer;
pub mod catalog_manager;
pub mod data_manager;
use sql::lexer::tokenize;
use sql::parser::parse;
use sql::query_typer::type_inferring_old;
use sql::query_validator::validate_old;
use sql::query_executer::{execute, ExecutionResult};
use sql::data_manager::DataManager;
use sql::catalog_manager::CatalogManager;
pub fn | (query: &str, data_manager: &DataManager, catalog_manager: &CatalogManager) -> Result<ExecutionResult, String> {
tokenize(query)
.and_then(parse)
.and_then(|statement| type_inferring_old(catalog_manager, statement))
.and_then(|statement| validate_old(catalog_manager, statement))
.and_then(|statement| execute(catalog_manager, data_manager, statement))
}
| evaluate_query | identifier_name |
openstack_cinder.py | # Copyright (C) 2009 Red Hat, Inc., Joey Boggs <jboggs@redhat.com>
# Copyright (C) 2012 Rackspace US, Inc.,
# Justin Shepherd <jshepher@rackspace.com>
# Copyright (C) 2013 Red Hat, Inc., Flavio Percoco <fpercoco@redhat.com>
# Copyright (C) 2013 Red Hat, Inc., Jeremy Agee <jagee@redhat.com>
# This program is free software; you can redistribute it and/or modify
# it under the terms of the GNU General Public License as published by
# the Free Software Foundation; either version 2 of the License, or
# (at your option) any later version.
# This program is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
# GNU General Public License for more details.
# You should have received a copy of the GNU General Public License
# along with this program; if not, write to the Free Software
# Foundation, Inc., 675 Mass Ave, Cambridge, MA 02139, USA.
from sos.plugins import Plugin, RedHatPlugin, DebianPlugin, UbuntuPlugin
class OpenStackCinder(Plugin):
"""OpenStack cinder
"""
plugin_name = "openstack_cinder"
profiles = ('openstack', 'openstack_controller')
option_list = [("db", "gathers openstack cinder db version", "slow",
False)]
def setup(self):
if self.get_option("db"):
self.add_cmd_output(
"cinder-manage db version",
suggest_filename="cinder_db_version")
self.add_copy_spec(["/etc/cinder/"])
self.limit = self.get_option("log_size")
if self.get_option("all_logs"):
self.add_copy_spec_limit("/var/log/cinder/",
sizelimit=self.limit)
else:
self.add_copy_spec_limit("/var/log/cinder/*.log",
sizelimit=self.limit)
def postproc(self):
protect_keys = [
"admin_password", "backup_tsm_password", "chap_password",
"nas_password", "cisco_fc_fabric_password", "coraid_password",
"eqlx_chap_password", "fc_fabric_password",
"hitachi_auth_password", "hitachi_horcm_password",
"hp3par_password", "hplefthand_password", "memcache_secret_key",
"netapp_password", "netapp_sa_password", "nexenta_password",
"password", "qpid_password", "rabbit_password", "san_password",
"ssl_key_password", "vmware_host_password", "zadara_password",
"zfssa_initiator_password", "connection", "zfssa_target_password",
"os_privileged_user_password", "hmac_keys"
]
regexp = r"((?m)^\s*(%s)\s*=\s*)(.*)" % "|".join(protect_keys)
self.do_path_regex_sub("/etc/cinder/*", regexp, r"\1*********")
class DebianCinder(OpenStackCinder, DebianPlugin, UbuntuPlugin):
cinder = False
packages = (
'cinder-api',
'cinder-backup',
'cinder-common',
'cinder-scheduler',
'cinder-volume',
'python-cinder',
'python-cinderclient'
) | self.cinder = self.is_installed("cinder-common")
return self.cinder
def setup(self):
super(DebianCinder, self).setup()
class RedHatCinder(OpenStackCinder, RedHatPlugin):
cinder = False
packages = ('openstack-cinder',
'python-cinder',
'python-cinderclient')
def check_enabled(self):
self.cinder = self.is_installed("openstack-cinder")
return self.cinder
def setup(self):
super(RedHatCinder, self).setup()
self.add_copy_spec(["/etc/sudoers.d/cinder"])
# vim: set et ts=4 sw=4 : |
def check_enabled(self): | random_line_split |
openstack_cinder.py | # Copyright (C) 2009 Red Hat, Inc., Joey Boggs <jboggs@redhat.com>
# Copyright (C) 2012 Rackspace US, Inc.,
# Justin Shepherd <jshepher@rackspace.com>
# Copyright (C) 2013 Red Hat, Inc., Flavio Percoco <fpercoco@redhat.com>
# Copyright (C) 2013 Red Hat, Inc., Jeremy Agee <jagee@redhat.com>
# This program is free software; you can redistribute it and/or modify
# it under the terms of the GNU General Public License as published by
# the Free Software Foundation; either version 2 of the License, or
# (at your option) any later version.
# This program is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
# GNU General Public License for more details.
# You should have received a copy of the GNU General Public License
# along with this program; if not, write to the Free Software
# Foundation, Inc., 675 Mass Ave, Cambridge, MA 02139, USA.
from sos.plugins import Plugin, RedHatPlugin, DebianPlugin, UbuntuPlugin
class OpenStackCinder(Plugin):
|
class DebianCinder(OpenStackCinder, DebianPlugin, UbuntuPlugin):
cinder = False
packages = (
'cinder-api',
'cinder-backup',
'cinder-common',
'cinder-scheduler',
'cinder-volume',
'python-cinder',
'python-cinderclient'
)
def check_enabled(self):
self.cinder = self.is_installed("cinder-common")
return self.cinder
def setup(self):
super(DebianCinder, self).setup()
class RedHatCinder(OpenStackCinder, RedHatPlugin):
cinder = False
packages = ('openstack-cinder',
'python-cinder',
'python-cinderclient')
def check_enabled(self):
self.cinder = self.is_installed("openstack-cinder")
return self.cinder
def setup(self):
super(RedHatCinder, self).setup()
self.add_copy_spec(["/etc/sudoers.d/cinder"])
# vim: set et ts=4 sw=4 :
| """OpenStack cinder
"""
plugin_name = "openstack_cinder"
profiles = ('openstack', 'openstack_controller')
option_list = [("db", "gathers openstack cinder db version", "slow",
False)]
def setup(self):
if self.get_option("db"):
self.add_cmd_output(
"cinder-manage db version",
suggest_filename="cinder_db_version")
self.add_copy_spec(["/etc/cinder/"])
self.limit = self.get_option("log_size")
if self.get_option("all_logs"):
self.add_copy_spec_limit("/var/log/cinder/",
sizelimit=self.limit)
else:
self.add_copy_spec_limit("/var/log/cinder/*.log",
sizelimit=self.limit)
def postproc(self):
protect_keys = [
"admin_password", "backup_tsm_password", "chap_password",
"nas_password", "cisco_fc_fabric_password", "coraid_password",
"eqlx_chap_password", "fc_fabric_password",
"hitachi_auth_password", "hitachi_horcm_password",
"hp3par_password", "hplefthand_password", "memcache_secret_key",
"netapp_password", "netapp_sa_password", "nexenta_password",
"password", "qpid_password", "rabbit_password", "san_password",
"ssl_key_password", "vmware_host_password", "zadara_password",
"zfssa_initiator_password", "connection", "zfssa_target_password",
"os_privileged_user_password", "hmac_keys"
]
regexp = r"((?m)^\s*(%s)\s*=\s*)(.*)" % "|".join(protect_keys)
self.do_path_regex_sub("/etc/cinder/*", regexp, r"\1*********") | identifier_body |
openstack_cinder.py | # Copyright (C) 2009 Red Hat, Inc., Joey Boggs <jboggs@redhat.com>
# Copyright (C) 2012 Rackspace US, Inc.,
# Justin Shepherd <jshepher@rackspace.com>
# Copyright (C) 2013 Red Hat, Inc., Flavio Percoco <fpercoco@redhat.com>
# Copyright (C) 2013 Red Hat, Inc., Jeremy Agee <jagee@redhat.com>
# This program is free software; you can redistribute it and/or modify
# it under the terms of the GNU General Public License as published by
# the Free Software Foundation; either version 2 of the License, or
# (at your option) any later version.
# This program is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
# GNU General Public License for more details.
# You should have received a copy of the GNU General Public License
# along with this program; if not, write to the Free Software
# Foundation, Inc., 675 Mass Ave, Cambridge, MA 02139, USA.
from sos.plugins import Plugin, RedHatPlugin, DebianPlugin, UbuntuPlugin
class OpenStackCinder(Plugin):
"""OpenStack cinder
"""
plugin_name = "openstack_cinder"
profiles = ('openstack', 'openstack_controller')
option_list = [("db", "gathers openstack cinder db version", "slow",
False)]
def setup(self):
if self.get_option("db"):
|
self.add_copy_spec(["/etc/cinder/"])
self.limit = self.get_option("log_size")
if self.get_option("all_logs"):
self.add_copy_spec_limit("/var/log/cinder/",
sizelimit=self.limit)
else:
self.add_copy_spec_limit("/var/log/cinder/*.log",
sizelimit=self.limit)
def postproc(self):
protect_keys = [
"admin_password", "backup_tsm_password", "chap_password",
"nas_password", "cisco_fc_fabric_password", "coraid_password",
"eqlx_chap_password", "fc_fabric_password",
"hitachi_auth_password", "hitachi_horcm_password",
"hp3par_password", "hplefthand_password", "memcache_secret_key",
"netapp_password", "netapp_sa_password", "nexenta_password",
"password", "qpid_password", "rabbit_password", "san_password",
"ssl_key_password", "vmware_host_password", "zadara_password",
"zfssa_initiator_password", "connection", "zfssa_target_password",
"os_privileged_user_password", "hmac_keys"
]
regexp = r"((?m)^\s*(%s)\s*=\s*)(.*)" % "|".join(protect_keys)
self.do_path_regex_sub("/etc/cinder/*", regexp, r"\1*********")
class DebianCinder(OpenStackCinder, DebianPlugin, UbuntuPlugin):
cinder = False
packages = (
'cinder-api',
'cinder-backup',
'cinder-common',
'cinder-scheduler',
'cinder-volume',
'python-cinder',
'python-cinderclient'
)
def check_enabled(self):
self.cinder = self.is_installed("cinder-common")
return self.cinder
def setup(self):
super(DebianCinder, self).setup()
class RedHatCinder(OpenStackCinder, RedHatPlugin):
cinder = False
packages = ('openstack-cinder',
'python-cinder',
'python-cinderclient')
def check_enabled(self):
self.cinder = self.is_installed("openstack-cinder")
return self.cinder
def setup(self):
super(RedHatCinder, self).setup()
self.add_copy_spec(["/etc/sudoers.d/cinder"])
# vim: set et ts=4 sw=4 :
| self.add_cmd_output(
"cinder-manage db version",
suggest_filename="cinder_db_version") | conditional_block |
openstack_cinder.py | # Copyright (C) 2009 Red Hat, Inc., Joey Boggs <jboggs@redhat.com>
# Copyright (C) 2012 Rackspace US, Inc.,
# Justin Shepherd <jshepher@rackspace.com>
# Copyright (C) 2013 Red Hat, Inc., Flavio Percoco <fpercoco@redhat.com>
# Copyright (C) 2013 Red Hat, Inc., Jeremy Agee <jagee@redhat.com>
# This program is free software; you can redistribute it and/or modify
# it under the terms of the GNU General Public License as published by
# the Free Software Foundation; either version 2 of the License, or
# (at your option) any later version.
# This program is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
# GNU General Public License for more details.
# You should have received a copy of the GNU General Public License
# along with this program; if not, write to the Free Software
# Foundation, Inc., 675 Mass Ave, Cambridge, MA 02139, USA.
from sos.plugins import Plugin, RedHatPlugin, DebianPlugin, UbuntuPlugin
class OpenStackCinder(Plugin):
"""OpenStack cinder
"""
plugin_name = "openstack_cinder"
profiles = ('openstack', 'openstack_controller')
option_list = [("db", "gathers openstack cinder db version", "slow",
False)]
def setup(self):
if self.get_option("db"):
self.add_cmd_output(
"cinder-manage db version",
suggest_filename="cinder_db_version")
self.add_copy_spec(["/etc/cinder/"])
self.limit = self.get_option("log_size")
if self.get_option("all_logs"):
self.add_copy_spec_limit("/var/log/cinder/",
sizelimit=self.limit)
else:
self.add_copy_spec_limit("/var/log/cinder/*.log",
sizelimit=self.limit)
def postproc(self):
protect_keys = [
"admin_password", "backup_tsm_password", "chap_password",
"nas_password", "cisco_fc_fabric_password", "coraid_password",
"eqlx_chap_password", "fc_fabric_password",
"hitachi_auth_password", "hitachi_horcm_password",
"hp3par_password", "hplefthand_password", "memcache_secret_key",
"netapp_password", "netapp_sa_password", "nexenta_password",
"password", "qpid_password", "rabbit_password", "san_password",
"ssl_key_password", "vmware_host_password", "zadara_password",
"zfssa_initiator_password", "connection", "zfssa_target_password",
"os_privileged_user_password", "hmac_keys"
]
regexp = r"((?m)^\s*(%s)\s*=\s*)(.*)" % "|".join(protect_keys)
self.do_path_regex_sub("/etc/cinder/*", regexp, r"\1*********")
class DebianCinder(OpenStackCinder, DebianPlugin, UbuntuPlugin):
cinder = False
packages = (
'cinder-api',
'cinder-backup',
'cinder-common',
'cinder-scheduler',
'cinder-volume',
'python-cinder',
'python-cinderclient'
)
def check_enabled(self):
self.cinder = self.is_installed("cinder-common")
return self.cinder
def | (self):
super(DebianCinder, self).setup()
class RedHatCinder(OpenStackCinder, RedHatPlugin):
cinder = False
packages = ('openstack-cinder',
'python-cinder',
'python-cinderclient')
def check_enabled(self):
self.cinder = self.is_installed("openstack-cinder")
return self.cinder
def setup(self):
super(RedHatCinder, self).setup()
self.add_copy_spec(["/etc/sudoers.d/cinder"])
# vim: set et ts=4 sw=4 :
| setup | identifier_name |
setup.py | import setuptools
with open("README.rst") as f:
long_description = f.read()
setuptools.setup(
name='django-diplomacy',
version="0.8.0", | description='A play-by-web app for Diplomacy',
long_description=long_description,
long_description_content_type='test/x-rst',
url='http://github.com/jbradberry/django-diplomacy',
packages=setuptools.find_packages(),
entry_points={
'turngeneration.plugins': ['diplomacy = diplomacy.plugins:TurnGeneration'],
},
classifiers=[
'Development Status :: 3 - Alpha',
'Environment :: Web Environment',
'Framework :: Django',
'License :: OSI Approved :: MIT License',
'Operating System :: OS Independent',
'Programming Language :: Python',
'Topic :: Games/Entertainment :: Turn Based Strategy'
],
) | author='Jeff Bradberry',
author_email='jeff.bradberry@gmail.com', | random_line_split |
discount.server.model.test.js | 'use strict';
/**
* Module dependencies.
*/
var should = require('should'),
mongoose = require('mongoose'),
User = mongoose.model('User'), | var user, discount;
/**
* Unit tests
*/
describe('Discount Model Unit Tests:', function() {
beforeEach(function(done) {
user = new User({
firstName: 'Full',
lastName: 'Name',
displayName: 'Full Name',
email: 'test@test.com',
username: 'username',
password: 'password'
});
user.save(function() {
discount = new Discount({
name: 'Discount Name',
user: user
});
done();
});
});
describe('Method Save', function() {
it('should be able to save without problems', function(done) {
return discount.save(function(err) {
should.not.exist(err);
done();
});
});
it('should be able to show an error when try to save without name', function(done) {
discount.name = '';
return discount.save(function(err) {
should.exist(err);
done();
});
});
});
afterEach(function(done) {
Discount.remove().exec();
User.remove().exec();
done();
});
}); | Discount = mongoose.model('Discount');
/**
* Globals
*/ | random_line_split |
0003_comment.py | # -*- coding: utf-8 -*-
# Generated by Django 1.11.4 on 2017-09-18 07:59
from __future__ import unicode_literals
from django.db import migrations, models
import django.db.models.deletion
import django.utils.timezone |
class Migration(migrations.Migration):
dependencies = [
('blog', '0002_post_subtitle'),
]
operations = [
migrations.CreateModel(
name='Comment',
fields=[
('id', models.AutoField(auto_created=True, primary_key=True, serialize=False, verbose_name='ID')),
('author', models.CharField(max_length=200)),
('text', models.TextField()),
('created_date', models.DateTimeField(default=django.utils.timezone.now)),
('approved_comment', models.BooleanField(default=False)),
('post', models.ForeignKey(on_delete=django.db.models.deletion.CASCADE, related_name='comments', to='blog.Post')),
],
),
] | random_line_split | |
0003_comment.py | # -*- coding: utf-8 -*-
# Generated by Django 1.11.4 on 2017-09-18 07:59
from __future__ import unicode_literals
from django.db import migrations, models
import django.db.models.deletion
import django.utils.timezone
class Migration(migrations.Migration):
| dependencies = [
('blog', '0002_post_subtitle'),
]
operations = [
migrations.CreateModel(
name='Comment',
fields=[
('id', models.AutoField(auto_created=True, primary_key=True, serialize=False, verbose_name='ID')),
('author', models.CharField(max_length=200)),
('text', models.TextField()),
('created_date', models.DateTimeField(default=django.utils.timezone.now)),
('approved_comment', models.BooleanField(default=False)),
('post', models.ForeignKey(on_delete=django.db.models.deletion.CASCADE, related_name='comments', to='blog.Post')),
],
),
] | identifier_body | |
0003_comment.py | # -*- coding: utf-8 -*-
# Generated by Django 1.11.4 on 2017-09-18 07:59
from __future__ import unicode_literals
from django.db import migrations, models
import django.db.models.deletion
import django.utils.timezone
class | (migrations.Migration):
dependencies = [
('blog', '0002_post_subtitle'),
]
operations = [
migrations.CreateModel(
name='Comment',
fields=[
('id', models.AutoField(auto_created=True, primary_key=True, serialize=False, verbose_name='ID')),
('author', models.CharField(max_length=200)),
('text', models.TextField()),
('created_date', models.DateTimeField(default=django.utils.timezone.now)),
('approved_comment', models.BooleanField(default=False)),
('post', models.ForeignKey(on_delete=django.db.models.deletion.CASCADE, related_name='comments', to='blog.Post')),
],
),
]
| Migration | identifier_name |
setup.py | #!/usr/bin/env python
from distutils.core import setup
import os
import sys
def main():
|
if __name__ == "__main__":
main()
| SHARE_PATH = os.path.join(os.path.dirname(os.path.abspath(__file__)),
"share")
data_files = []
# don't trash the users system icons!!
black_list = ['index.theme', 'index.theme~']
for path, dirs, files in os.walk(SHARE_PATH):
data_files.append(tuple((path.replace(SHARE_PATH,"share", 1),
[os.path.join(path, file) for file in files if file not in
black_list])))
setup(name="caffeine",
version="2.4.1",
description="""A status bar application able to temporarily prevent
the activation of both the screensaver and the "sleep" powersaving
mode.""",
author="The Caffeine Developers",
author_email="bnsmith@gmail.com",
url="https://launchpad.net/caffeine",
packages=["caffeine"],
data_files=data_files,
scripts=[os.path.join("bin", "caffeine")]
) | identifier_body |
setup.py | #!/usr/bin/env python
from distutils.core import setup
import os
import sys | def main():
SHARE_PATH = os.path.join(os.path.dirname(os.path.abspath(__file__)),
"share")
data_files = []
# don't trash the users system icons!!
black_list = ['index.theme', 'index.theme~']
for path, dirs, files in os.walk(SHARE_PATH):
data_files.append(tuple((path.replace(SHARE_PATH,"share", 1),
[os.path.join(path, file) for file in files if file not in
black_list])))
setup(name="caffeine",
version="2.4.1",
description="""A status bar application able to temporarily prevent
the activation of both the screensaver and the "sleep" powersaving
mode.""",
author="The Caffeine Developers",
author_email="bnsmith@gmail.com",
url="https://launchpad.net/caffeine",
packages=["caffeine"],
data_files=data_files,
scripts=[os.path.join("bin", "caffeine")]
)
if __name__ == "__main__":
main() | random_line_split | |
setup.py | #!/usr/bin/env python
from distutils.core import setup
import os
import sys
def main():
SHARE_PATH = os.path.join(os.path.dirname(os.path.abspath(__file__)),
"share")
data_files = []
# don't trash the users system icons!!
black_list = ['index.theme', 'index.theme~']
for path, dirs, files in os.walk(SHARE_PATH):
data_files.append(tuple((path.replace(SHARE_PATH,"share", 1),
[os.path.join(path, file) for file in files if file not in
black_list])))
setup(name="caffeine",
version="2.4.1",
description="""A status bar application able to temporarily prevent
the activation of both the screensaver and the "sleep" powersaving
mode.""",
author="The Caffeine Developers",
author_email="bnsmith@gmail.com",
url="https://launchpad.net/caffeine",
packages=["caffeine"],
data_files=data_files,
scripts=[os.path.join("bin", "caffeine")]
)
if __name__ == "__main__":
| main() | conditional_block | |
setup.py | #!/usr/bin/env python
from distutils.core import setup
import os
import sys
def | ():
SHARE_PATH = os.path.join(os.path.dirname(os.path.abspath(__file__)),
"share")
data_files = []
# don't trash the users system icons!!
black_list = ['index.theme', 'index.theme~']
for path, dirs, files in os.walk(SHARE_PATH):
data_files.append(tuple((path.replace(SHARE_PATH,"share", 1),
[os.path.join(path, file) for file in files if file not in
black_list])))
setup(name="caffeine",
version="2.4.1",
description="""A status bar application able to temporarily prevent
the activation of both the screensaver and the "sleep" powersaving
mode.""",
author="The Caffeine Developers",
author_email="bnsmith@gmail.com",
url="https://launchpad.net/caffeine",
packages=["caffeine"],
data_files=data_files,
scripts=[os.path.join("bin", "caffeine")]
)
if __name__ == "__main__":
main()
| main | identifier_name |
test2.js | /// <reference path="../test1.ts" />
var __extends = (this && this.__extends) || function (d, b) {
for (var p in b) if (b.hasOwnProperty(p)) d[p] = b[p];
function __() { this.constructor = d; }
d.prototype = b === null ? Object.create(b) : (__.prototype = b.prototype, new __());
};
var test2;
(function (test2) {
var Test2 = (function (_super) {
__extends(Test2, _super);
function Test2() {
_super.call(this);
console.log('extends');
console.log('prop1', this.getProp1()); | }
return Test2;
})(test1.Test1);
test2.Test2 = Test2;
})(test2 || (test2 = {}));
//# sourceMappingURL=/public/maps/subdir/test2.js.map | console.log('prop2', this.getProp2()); | random_line_split |
test2.js | /// <reference path="../test1.ts" />
var __extends = (this && this.__extends) || function (d, b) {
for (var p in b) if (b.hasOwnProperty(p)) d[p] = b[p];
function __() |
d.prototype = b === null ? Object.create(b) : (__.prototype = b.prototype, new __());
};
var test2;
(function (test2) {
var Test2 = (function (_super) {
__extends(Test2, _super);
function Test2() {
_super.call(this);
console.log('extends');
console.log('prop1', this.getProp1());
console.log('prop2', this.getProp2());
}
return Test2;
})(test1.Test1);
test2.Test2 = Test2;
})(test2 || (test2 = {}));
//# sourceMappingURL=/public/maps/subdir/test2.js.map | { this.constructor = d; } | identifier_body |
test2.js | /// <reference path="../test1.ts" />
var __extends = (this && this.__extends) || function (d, b) {
for (var p in b) if (b.hasOwnProperty(p)) d[p] = b[p];
function __() { this.constructor = d; }
d.prototype = b === null ? Object.create(b) : (__.prototype = b.prototype, new __());
};
var test2;
(function (test2) {
var Test2 = (function (_super) {
__extends(Test2, _super);
function | () {
_super.call(this);
console.log('extends');
console.log('prop1', this.getProp1());
console.log('prop2', this.getProp2());
}
return Test2;
})(test1.Test1);
test2.Test2 = Test2;
})(test2 || (test2 = {}));
//# sourceMappingURL=/public/maps/subdir/test2.js.map | Test2 | identifier_name |
index.js | /**
* @license Apache-2.0
*
* Copyright (c) 2018 The Stdlib Authors.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
'use strict';
var DiscreteUniform = require( './../lib' );
var discreteUniform = new DiscreteUniform( -2, 2 );
var mu = discreteUniform.mean;
console.log( 'Mean = %d', mu );
// => 'Mean = 0'
var median = discreteUniform.median;
console.log( 'Median = %d', median );
// => 'Median = 0'
var s2 = discreteUniform.variance;
console.log( 'Variance = %d', s2 );
// => 'Variance = 2'
| // => 'F(2.5) = 1' | var y = discreteUniform.cdf( 2.5 );
console.log( 'F(2.5) = %d', y ); | random_line_split |
uniprot_core.py | # reads uniprot core file and generates core features
from features_helpers import score_differences
def build_uniprot_to_index_to_core(sable_db_obj):
uniprot_to_index_to_core = {}
for line in sable_db_obj:
tokens = line.split()
try:
# PARSING ID
prot = tokens[0]
index = int(tokens[1])
core = tokens[2]
# PARSING ID
if uniprot_to_index_to_core.has_key(prot):
uniprot_to_index_to_core[prot][index] = core
else:
uniprot_to_index_to_core[prot] = {index: core}
except ValueError:
print "Cannot parse: " + line[0:len(line) - 1]
return uniprot_to_index_to_core
def get_sable_scores(map_file, f_sable_db_location, uniprot_core_output_location):
map_file_obj = open(map_file, 'r')
sable_db_obj = open(f_sable_db_location, 'r')
write_to = open(uniprot_core_output_location, 'w')
uniprot_to_index_to_core = build_uniprot_to_index_to_core(sable_db_obj)
for line in map_file_obj:
tokens = line.split()
asid = tokens[0].split("_")[0]
prot = tokens[1] | eend = int(tokens[5])
rough_a_length = int(int(tokens[0].split("_")[-1].split("=")[1]) / 3)
if asid[0] == "I":
rough_a_length = 0
c1_count = 0
a_count = 0
c2_count = 0
canonical_absolute = 0
if prot in uniprot_to_index_to_core:
c1_count = score_differences(uniprot_to_index_to_core, prot, sstart, start)
a_count = score_differences(uniprot_to_index_to_core, prot, start, end)
c2_count = score_differences(uniprot_to_index_to_core, prot, end, eend)
prot_len = int(line.split("\t")[7].strip())
canonical_absolute = score_differences(uniprot_to_index_to_core, prot, 1, prot_len)
print >> write_to, tokens[0] + "\t" + prot + "\t" + repr(c1_count) + "\t" + repr(a_count) + "\t" + repr(
c2_count) + "\t" + repr(canonical_absolute)
write_to.close() | sstart = int(tokens[2])
start = int(tokens[3])
end = int(tokens[4]) | random_line_split |
uniprot_core.py | # reads uniprot core file and generates core features
from features_helpers import score_differences
def build_uniprot_to_index_to_core(sable_db_obj):
uniprot_to_index_to_core = {}
for line in sable_db_obj:
tokens = line.split()
try:
# PARSING ID
prot = tokens[0]
index = int(tokens[1])
core = tokens[2]
# PARSING ID
if uniprot_to_index_to_core.has_key(prot):
|
else:
uniprot_to_index_to_core[prot] = {index: core}
except ValueError:
print "Cannot parse: " + line[0:len(line) - 1]
return uniprot_to_index_to_core
def get_sable_scores(map_file, f_sable_db_location, uniprot_core_output_location):
map_file_obj = open(map_file, 'r')
sable_db_obj = open(f_sable_db_location, 'r')
write_to = open(uniprot_core_output_location, 'w')
uniprot_to_index_to_core = build_uniprot_to_index_to_core(sable_db_obj)
for line in map_file_obj:
tokens = line.split()
asid = tokens[0].split("_")[0]
prot = tokens[1]
sstart = int(tokens[2])
start = int(tokens[3])
end = int(tokens[4])
eend = int(tokens[5])
rough_a_length = int(int(tokens[0].split("_")[-1].split("=")[1]) / 3)
if asid[0] == "I":
rough_a_length = 0
c1_count = 0
a_count = 0
c2_count = 0
canonical_absolute = 0
if prot in uniprot_to_index_to_core:
c1_count = score_differences(uniprot_to_index_to_core, prot, sstart, start)
a_count = score_differences(uniprot_to_index_to_core, prot, start, end)
c2_count = score_differences(uniprot_to_index_to_core, prot, end, eend)
prot_len = int(line.split("\t")[7].strip())
canonical_absolute = score_differences(uniprot_to_index_to_core, prot, 1, prot_len)
print >> write_to, tokens[0] + "\t" + prot + "\t" + repr(c1_count) + "\t" + repr(a_count) + "\t" + repr(
c2_count) + "\t" + repr(canonical_absolute)
write_to.close() | uniprot_to_index_to_core[prot][index] = core | conditional_block |
uniprot_core.py | # reads uniprot core file and generates core features
from features_helpers import score_differences
def build_uniprot_to_index_to_core(sable_db_obj):
uniprot_to_index_to_core = {}
for line in sable_db_obj:
tokens = line.split()
try:
# PARSING ID
prot = tokens[0]
index = int(tokens[1])
core = tokens[2]
# PARSING ID
if uniprot_to_index_to_core.has_key(prot):
uniprot_to_index_to_core[prot][index] = core
else:
uniprot_to_index_to_core[prot] = {index: core}
except ValueError:
print "Cannot parse: " + line[0:len(line) - 1]
return uniprot_to_index_to_core
def get_sable_scores(map_file, f_sable_db_location, uniprot_core_output_location):
| map_file_obj = open(map_file, 'r')
sable_db_obj = open(f_sable_db_location, 'r')
write_to = open(uniprot_core_output_location, 'w')
uniprot_to_index_to_core = build_uniprot_to_index_to_core(sable_db_obj)
for line in map_file_obj:
tokens = line.split()
asid = tokens[0].split("_")[0]
prot = tokens[1]
sstart = int(tokens[2])
start = int(tokens[3])
end = int(tokens[4])
eend = int(tokens[5])
rough_a_length = int(int(tokens[0].split("_")[-1].split("=")[1]) / 3)
if asid[0] == "I":
rough_a_length = 0
c1_count = 0
a_count = 0
c2_count = 0
canonical_absolute = 0
if prot in uniprot_to_index_to_core:
c1_count = score_differences(uniprot_to_index_to_core, prot, sstart, start)
a_count = score_differences(uniprot_to_index_to_core, prot, start, end)
c2_count = score_differences(uniprot_to_index_to_core, prot, end, eend)
prot_len = int(line.split("\t")[7].strip())
canonical_absolute = score_differences(uniprot_to_index_to_core, prot, 1, prot_len)
print >> write_to, tokens[0] + "\t" + prot + "\t" + repr(c1_count) + "\t" + repr(a_count) + "\t" + repr(
c2_count) + "\t" + repr(canonical_absolute)
write_to.close() | identifier_body | |
uniprot_core.py | # reads uniprot core file and generates core features
from features_helpers import score_differences
def | (sable_db_obj):
uniprot_to_index_to_core = {}
for line in sable_db_obj:
tokens = line.split()
try:
# PARSING ID
prot = tokens[0]
index = int(tokens[1])
core = tokens[2]
# PARSING ID
if uniprot_to_index_to_core.has_key(prot):
uniprot_to_index_to_core[prot][index] = core
else:
uniprot_to_index_to_core[prot] = {index: core}
except ValueError:
print "Cannot parse: " + line[0:len(line) - 1]
return uniprot_to_index_to_core
def get_sable_scores(map_file, f_sable_db_location, uniprot_core_output_location):
map_file_obj = open(map_file, 'r')
sable_db_obj = open(f_sable_db_location, 'r')
write_to = open(uniprot_core_output_location, 'w')
uniprot_to_index_to_core = build_uniprot_to_index_to_core(sable_db_obj)
for line in map_file_obj:
tokens = line.split()
asid = tokens[0].split("_")[0]
prot = tokens[1]
sstart = int(tokens[2])
start = int(tokens[3])
end = int(tokens[4])
eend = int(tokens[5])
rough_a_length = int(int(tokens[0].split("_")[-1].split("=")[1]) / 3)
if asid[0] == "I":
rough_a_length = 0
c1_count = 0
a_count = 0
c2_count = 0
canonical_absolute = 0
if prot in uniprot_to_index_to_core:
c1_count = score_differences(uniprot_to_index_to_core, prot, sstart, start)
a_count = score_differences(uniprot_to_index_to_core, prot, start, end)
c2_count = score_differences(uniprot_to_index_to_core, prot, end, eend)
prot_len = int(line.split("\t")[7].strip())
canonical_absolute = score_differences(uniprot_to_index_to_core, prot, 1, prot_len)
print >> write_to, tokens[0] + "\t" + prot + "\t" + repr(c1_count) + "\t" + repr(a_count) + "\t" + repr(
c2_count) + "\t" + repr(canonical_absolute)
write_to.close() | build_uniprot_to_index_to_core | identifier_name |
sh.py | #!/usr/bin/env python
# -*- coding: utf-8 -*-
# Copyright (c) 2012-2021 SoftBank Robotics. All rights reserved.
# Use of this source code is governed by a BSD-style license (see the COPYING file).
""" Common filesystem operations """
from __future__ import absolute_import
from __future__ import unicode_literals
from __future__ import print_function
import os
import sys
import stat
import time
import errno
import ntpath
import shutil
import tempfile
import warnings
import posixpath
import contextlib
import subprocess
from qisys import ui
try:
from xdg.BaseDirectory import xdg_cache_home, xdg_config_home, xdg_data_home
except ImportError:
xdg_config_home = os.path.expanduser("~/.config")
xdg_cache_home = os.path.expanduser("~/.cache")
xdg_data_home = os.path.expanduser("~/.local/share")
CONFIG_PATH = xdg_config_home
CACHE_PATH = xdg_cache_home
SHARE_PATH = xdg_data_home
def set_home(home):
""" Set Home """
# This module should be refactored into object to avoid the anti-pattern global statement
global CONFIG_PATH, CACHE_PATH, SHARE_PATH
CONFIG_PATH = os.path.join(home, "config")
CACHE_PATH = os.path.join(home, "cache")
SHARE_PATH = os.path.join(home, "share")
def get_config_path(*args):
"""
Get a config path to read or write some configuration.
:param args: a list of subfolders. Those will be created when needed
"""
return get_path(CONFIG_PATH, *args)
def get_cache_path(*args):
"""
Get a config path to read or write some cached data
:param args: a list of subfolders. Those will be created when needed
"""
return get_path(CACHE_PATH, *args)
def get_share_path(*args):
"""
Get a config path to read or write some persistent data
:param args: a list of subfolders. Those will be created when needed
"""
return get_path(SHARE_PATH, *args)
def get_path(*args):
""" Helper for get_*_path methods """
full_path = os.path.join(*args)
to_make = os.path.dirname(full_path)
mkdir(to_make, recursive=True)
full_path = to_native_path(full_path)
return full_path
def username():
""" Get the current user name """
if os.name != 'nt':
import pwd
uid = os.getuid() # pylint:disable=no-member
pw_info = pwd.getpwuid(uid)
if pw_info:
return pw_info.pw_name
_username = os.environ.get("USERNAME")
if _username:
return _username
return None
def mkdir(dest_dir, recursive=False):
""" Recursive mkdir (do not fail if file exists) """
try:
if recursive:
os.makedirs(dest_dir)
else:
os.mkdir(dest_dir)
except OSError as exc:
if exc.errno != 17:
raise
# Directory already exists -> no exception
def ln(src, dst, symlink=True):
""" ln (do not fail if file exists) """
try:
if symlink:
os.symlink(src, dst) # pylint:disable=no-member
else:
raise NotImplementedError
except OSError as exc:
if exc.errno != 17:
raise
def write_file_if_different(data, out_path, mode="w"):
""" Write the data to out_path if the content is different """
try:
with open(out_path, "r") as outr:
out_prev = outr.read()
if out_prev == data:
ui.debug("skipping write to %s: same content" % (out_path))
return
except Exception:
pass
with open(out_path, mode) as out_file:
out_file.write(data)
def configure_file__legacy(in_path, out_path, copy_only=False,
*args, **kwargs): # pylint:disable=keyword-arg-before-vararg
"""
Configure a file.
:param in_path: input file
:param out_path: output file
The out_path needs not to exist, missing leading directories will
be created if necessary.
If copy_only is True, the contents will be copied "as is".
If not, we will use the args and kwargs parameter as in::
in_content.format(*args, **kwargs)
"""
# This function seems to be never called, and has been renamed with __legacy suffix (2020-02-07)
# If nobody complains, remove this function in the next release
warnings.warn(
"Deprecated function: "
"This function seems to be never called, and has been renamed with __legacy suffix (2020-02-07)\n"
"If nobody complains, remove this function in the next release, else, deals with its bad args/kwargs signature",
DeprecationWarning)
mkdir(os.path.dirname(os.path.abspath(out_path)), recursive=True)
with open(in_path, "r") as in_file:
in_content = in_file.read()
if copy_only:
out_content = in_content
else:
out_content = in_content.format(*args, **kwargs)
write_file_if_different(out_content, out_path)
def _copy_link(src, dest, quiet):
""" Copy Link """
if not os.path.islink(src):
raise Exception("%s is not a link!" % src)
target = os.readlink(src) # pylint:disable=no-member
# remove existing stuff
if os.path.lexists(dest):
rm(dest)
if sys.stdout.isatty() and not quiet:
print("-- Installing %s -> %s" % (dest, target))
to_make = os.path.dirname(dest)
mkdir(to_make, recursive=True)
os.symlink(target, dest) # pylint:disable=no-member
def _handle_dirs(src, dest, root, directories, filter_fun, quiet):
""" Helper function used by install() """
installed = list()
rel_root = os.path.relpath(root, src)
# To avoid filering './' stuff
if rel_root == ".":
rel_root = ""
new_root = os.path.join(dest, rel_root)
for directory in directories:
to_filter = os.path.join(rel_root, directory)
if not filter_fun(to_filter):
continue
dsrc = os.path.join(root, directory)
ddest = os.path.join(new_root, directory)
if os.path.islink(dsrc):
_copy_link(dsrc, ddest, quiet)
installed.append(directory)
else:
if os.path.lexists(ddest) and not os.path.isdir(ddest):
raise Exception("Expecting a directory but found a file: %s" % ddest)
mkdir(ddest, recursive=True)
return installed
def _handle_files(src, dest, root, files, filter_fun, quiet):
""" Helper function used by install() """
installed = list()
rel_root = os.path.relpath(root, src)
if rel_root == ".":
rel_root = ""
new_root = os.path.join(dest, rel_root)
for f in files:
if not filter_fun(os.path.join(rel_root, f)):
continue
fsrc = os.path.join(root, f)
fdest = os.path.join(new_root, f)
rel_path = os.path.join(rel_root, f)
if os.path.islink(fsrc):
mkdir(new_root, recursive=True)
_copy_link(fsrc, fdest, quiet)
installed.append(rel_path)
else:
if os.path.lexists(fdest) and os.path.isdir(fdest):
raise Exception("Expecting a file but found a directory: %s" % fdest)
if not quiet:
print("-- Installing %s" % fdest.encode('ascii', "ignore"))
mkdir(new_root, recursive=True)
# We do not want to fail if dest exists but is read only
# (following what `install` does, but not what `cp` does)
rm(fdest)
shutil.copy(fsrc, fdest)
installed.append(rel_path)
return installed
def install(src, dest, filter_fun=None, quiet=False):
"""
Install a directory or a file to a destination.
If filter_fun is not None, then the file will only be
installed if filter_fun(relative/path/to/file) returns True.
If ``dest`` does not exist, it will be created first.
When installing files, if the destination already exists,
it will be removed first, then overwritten by the new file.
This function will preserve relative symlinks between directories,
used for instance in Mac frameworks::
|__ Versions
|__ Current -> 4.0
|__ 4 -> 4.0
|__ 4.0
Return the list of files installed (with relative paths)
"""
installed = list()
# FIXME: add a `safe mode` ala install?
if not os.path.exists(src):
mess = "Could not install '%s' to '%s'\n" % (src, dest)
mess += '%s does not exist' % src
raise Exception(mess)
src = to_native_path(src, normcase=False)
dest = to_native_path(dest, normcase=False)
ui.debug("Installing", src, "->", dest)
if filter_fun is None:
def no_filter_fun(_unused):
""" Filter Function Always True """
return True
filter_fun = no_filter_fun
if os.path.isdir(src):
if src == dest:
raise Exception("source and destination are the same directory")
for (root, dirs, files) in os.walk(src):
dirs = _handle_dirs(src, dest, root, dirs, filter_fun, quiet)
files = _handle_files(src, dest, root, files, filter_fun, quiet)
installed.extend(files)
else:
# Emulate posix `install' behavior:
# if dest is a dir, install in the directory, else
# simply copy the file.
if os.path.isdir(dest):
dest = os.path.join(dest, os.path.basename(src))
if src == dest:
raise Exception("source and destination are the same file")
mkdir(os.path.dirname(dest), recursive=True)
if sys.stdout.isatty() and not quiet:
print("-- Installing %s" % dest)
# We do not want to fail if dest exists but is read only
# (following what `install` does, but not what `cp` does)
rm(dest)
shutil.copy(src, dest)
installed.append(os.path.basename(src))
return installed
def safe_copy(src, dest):
"""
Copy a source file to a destination but
do not overwrite dest if it is more recent than src
Create any missing directories when necessary
If dest is a directory, src will be copied inside dest.
"""
if os.path.isdir(dest):
dest = os.path.join(dest, os.path.basename(src))
if not up_to_date(dest, src):
shutil.copy(src, dest)
def up_to_date(output_path, input_path):
"""" Return True if output_path exists and is more recent than input_path """
if not os.path.exists(output_path):
return False
out_mtime = os.stat(output_path).st_mtime
in_mtime = os.stat(input_path).st_mtime
return out_mtime > in_mtime
def copy_git_src(src, dest):
"""
Copy a source to a destination but only copy the files under version control.
Assumes that ``src`` is inside a git worktree
"""
process = subprocess.Popen(["git", "ls-files", "."], cwd=src,
stdout=subprocess.PIPE)
(out, _) = process.communicate()
for filename in out.splitlines():
src_file = os.path.join(src, filename.decode('ascii'))
dest_file = os.path.join(dest, filename.decode('ascii'))
install(src_file, dest_file, quiet=True)
def rm(name):
"""
This one can take a file or a directory.
Contrary to shutil.remove or os.remove, it:
* won't fail if the directory does not exist
* won't fail if the directory contains read-only files
* won't fail if the file does not exist
Please avoid using shutil.rmtree ...
"""
if not os.path.lexists(name):
return
if os.path.isdir(name) and not os.path.islink(name):
ui.debug("Removing directory:", name)
rmtree(name.encode('ascii', "ignore"))
else:
ui.debug("Removing", name)
os.remove(name)
def rmtree(path):
"""
shutil.rmtree() on steroids.
Taken from gclient source code (BSD license)
Recursively removes a directory, even if it's marked read-only.
shutil.rmtree() doesn't work on Windows if any of the files or directories
are read-only, which svn repositories and some .svn files are. We need to
be able to force the files to be writable (i.e., deletable) as we traverse
the tree.
Even with all this, Windows still sometimes fails to delete a file, citing
a permission error (maybe something to do with antivirus scans or disk
indexing). The best suggestion any of the user forums had was to wait a
bit and try again, so we do that too. It's hand-waving, but sometimes it
works. :/
On POSIX systems, things are a little bit simpler. The modes of the files
to be deleted doesn't matter, only the modes of the directories containing
them are significant. As the directory tree is traversed, each directory
has its mode set appropriately before descending into it. This should
result in the entire tree being removed, with the possible exception of
``path`` itself, because nothing attempts to change the mode of its parent.
Doing so would be hazardous, as it's not a directory slated for removal.
In the ordinary case, this is not a problem: for our purposes, the user
will never lack write permission on ``path``'s parent.
"""
if not os.path.exists(path):
return
if os.path.islink(path) or not os.path.isdir(path):
raise Exception('Called rmtree(%s) in non-directory' % path)
if sys.platform == 'win32':
# Some people don't have the APIs installed. In that case we'll do without.
win32api = None
win32con = None
try:
import win32api
import win32con
except ImportError:
pass
else:
# On POSIX systems, we need the x-bit set on the directory to access it,
# the r-bit to see its contents, and the w-bit to remove files from it.
# The actual modes of the files within the directory is irrelevant.
os.chmod(path, stat.S_IRUSR | stat.S_IWUSR | stat.S_IXUSR)
def remove(func, subpath):
""" Remove """
if sys.platform == 'win32':
os.chmod(subpath, stat.S_IWRITE)
if win32api and win32con:
win32api.SetFileAttributes(subpath, win32con.FILE_ATTRIBUTE_NORMAL)
try:
func(subpath)
except OSError as e:
if e.errno != errno.EACCES or sys.platform != 'win32':
raise
# Failed to delete, try again after a 100ms sleep.
time.sleep(0.1)
func(subpath)
for fn in os.listdir(path):
# If fullpath is a symbolic link that points to a directory, isdir will
# be True, but we don't want to descend into that as a directory, we just
# want to remove the link. Check islink and treat links as ordinary files
# would be treated regardless of what they reference.
fullpath = os.path.join(path, fn)
if os.path.islink(fullpath) or not os.path.isdir(fullpath):
remove(os.remove, fullpath)
else:
# Recurse.
rmtree(fullpath)
remove(os.rmdir, path)
def mv(src, dest):
""" Move a file into a directory, but do not crash if dest/src exists """
if src == dest:
return
if os.path.isdir(dest):
dest = os.path.join(dest, os.path.basename(src))
if os.path.exists(dest):
rm(dest)
ui.debug(src, "->", dest)
shutil.move(src, dest)
def ls_r(directory):
"""
Returns a sorted list of all the files present in a directory,
relative to this directory.
For instance, with::
foo
|__ eggs
| |__ c
| |__ d
|__ empty
|__ spam
|__a
|__b
ls_r(foo) returns:
["eggs/c", "eggs/d", "empty/", "spam/a", "spam/b"]
"""
res = list()
for root, dirs, files in os.walk(directory):
new_root = os.path.relpath(root, directory)
if new_root == "." and not files:
continue
if new_root == "." and files:
res.extend(files)
continue
if not files and not dirs:
res.append(new_root + os.path.sep)
continue
for f in files:
res.append(os.path.join(new_root, f))
return sorted(res)
def which(program):
"""
find program in the environment PATH
:return: path to program if found, None otherwise
"""
warnings.warn("qisys.sh.which is deprecated, "
"use qisys.command.find_program instead")
from qisys.command import find_program
return find_program(program)
def to_posix_path(path, fix_drive=False):
"""
Returns a POSIX path from a DOS path
:param fix_drive: if True, will replace c: by /c/ (ala mingw)
"""
res = os.path.expanduser(path)
res = os.path.abspath(res)
res = path.replace(ntpath.sep, posixpath.sep)
if fix_drive:
(drive, rest) = os.path.splitdrive(res)
letter = drive[0]
return "/" + letter + rest
return res
def to_dos_path(path):
"""
Return a DOS path from a "windows with /" path.
Useful because people sometimes use forward slash in
environment variable, for instance
"""
res = path.replace(posixpath.sep, ntpath.sep)
return res
def to_native_path(path, normcase=True):
"""
Return an absolute, native path from a path,
:param normcase: make sure the path is all lower-case on
case-insensitive filesystems
"""
path = os.path.expanduser(path)
if normcase:
path = os.path.normcase(path)
path = os.path.normpath(path)
path = os.path.abspath(path)
path = os.path.realpath(path)
if sys.platform.startswith("win"):
path = to_dos_path(path)
return path
def is_path_inside(a, b):
"""
Returns True if a is inside b
>>> is_path_inside("foo/bar", "foo")
True
>>> is_path_inside("gui/bar/libfoo", "lib")
False
"""
a = to_native_path(a)
b = to_native_path(b)
a_split = a.split(os.path.sep)
b_split = b.split(os.path.sep)
if len(a_split) < len(b_split):
return False
for (a_part, b_part) in zip(a_split, b_split):
if a_part != b_part:
return False
return True
def is_empty(path):
""" Check if a path is empty """
return os.listdir(path) == list()
class TempDir(object):
"""
This is a nice wrapper around tempfile module.
Usage::
with TempDir("foo-bar") as temp_dir:
subdir = os.path.join(temp_dir, "subdir")
do_foo(subdir)
This piece of code makes sure that:
* a temporary directory named temp_dir has been
created (guaranteed to exist, be empty, and writeable)
* the directory will be removed when the scope of
temp_dir has ended unless an exception has occurred
and DEBUG environment variable is set.
"""
def __init__(self, name="tmp"):
""" TempDir Init """
self._temp_dir = tempfile.mkdtemp(prefix=name + "-")
def __enter__(self):
""" Enter """
return self._temp_dir
def __exit__(self, _type, value, tb):
""" Exit """
if os.environ.get("DEBUG"):
if tb is not None:
print("==")
print("Not removing ", self._temp_dir)
print("==")
return
rm(self._temp_dir)
@contextlib.contextmanager
def change_cwd(directory):
""" Change the current working dir """
if not os.path.exists(directory):
mess = "Cannot change working dir to '%s'\n" % directory
mess += "This path does not exist"
raise Exception(mess)
previous_cwd = os.getcwd()
os.chdir(directory)
yield
os.chdir(previous_cwd)
def is_runtime(filename):
""" Filter function to only install runtime components of packages """
# FIXME: this looks like a hack.
# Maybe a user-generated MANIFEST at the root of the package path
# would be better?
basedir = filename.split(os.path.sep)[0]
if filename.startswith("bin") and sys.platform.startswith("win"):
return filename.endswith(".exe") or filename.endswith(".dll")
if filename.startswith("lib"):
is_lib_prefixed_runtime = not filename.endswith((".a", ".lib", ".la", ".pc"))
return is_lib_prefixed_runtime
if filename.startswith(os.path.join("share", "cmake")) or \
filename.startswith(os.path.join("share", "man")):
return False
if basedir == "include":
# Usually runtime dir names aren't include, but there is an exception for python:
return filename.endswith("pyconfig.h")
# True by default: better have too much stuff than not enough
# That includes these known cases:
# * filename.startswith("bin") but not sys.platform.startswith("win")
# * basedir == "share"
# * basedir.endswith(".framework")
return True
def broken_symlink(file_path):
""" Returns True if the file is a broken symlink """
return os.path.lexists(file_path) and not os.path.exists(file_path)
def is_binary(file_path):
""" Returns True if the file is binary """
with open(file_path, 'rb') as fp:
data = fp.read(1024)
if not data:
return False
if b'\0' in data:
return True
return False
def is_executable_binary(file_path):
"""
Returns true if the file:
* is executable
* is a binary (i.e not a script)
"""
if not os.path.isfile(file_path):
return False
if not os.access(file_path, os.X_OK):
return False
return is_binary(file_path)
class PreserveFileMetadata(object):
""" Preserve file metadata (permissions and times) """
def __init__(self, path):
|
def __enter__(self):
""" Enter method saving metadata """
st = os.stat(self.path)
self.time = (st.st_atime, st.st_mtime)
self.mode = st.st_mode
def __exit__(self, _type, value, tb):
""" Exit method restoring metadata """
os.chmod(self.path, self.mode)
os.utime(self.path, self.time)
| """ Preserve file metadata of 'path' """
self.path = path
self.time = None
self.mode = None | identifier_body |
sh.py | #!/usr/bin/env python
# -*- coding: utf-8 -*-
# Copyright (c) 2012-2021 SoftBank Robotics. All rights reserved.
# Use of this source code is governed by a BSD-style license (see the COPYING file).
""" Common filesystem operations """
from __future__ import absolute_import
from __future__ import unicode_literals
from __future__ import print_function
import os
import sys
import stat
import time
import errno
import ntpath
import shutil
import tempfile
import warnings
import posixpath
import contextlib
import subprocess
from qisys import ui
try:
from xdg.BaseDirectory import xdg_cache_home, xdg_config_home, xdg_data_home
except ImportError:
xdg_config_home = os.path.expanduser("~/.config")
xdg_cache_home = os.path.expanduser("~/.cache")
xdg_data_home = os.path.expanduser("~/.local/share")
CONFIG_PATH = xdg_config_home
CACHE_PATH = xdg_cache_home
SHARE_PATH = xdg_data_home
def set_home(home):
""" Set Home """
# This module should be refactored into object to avoid the anti-pattern global statement
global CONFIG_PATH, CACHE_PATH, SHARE_PATH
CONFIG_PATH = os.path.join(home, "config")
CACHE_PATH = os.path.join(home, "cache")
SHARE_PATH = os.path.join(home, "share")
def get_config_path(*args):
"""
Get a config path to read or write some configuration.
:param args: a list of subfolders. Those will be created when needed
"""
return get_path(CONFIG_PATH, *args)
def get_cache_path(*args):
"""
Get a config path to read or write some cached data
:param args: a list of subfolders. Those will be created when needed
"""
return get_path(CACHE_PATH, *args)
def get_share_path(*args):
"""
Get a config path to read or write some persistent data
:param args: a list of subfolders. Those will be created when needed
"""
return get_path(SHARE_PATH, *args)
def get_path(*args):
""" Helper for get_*_path methods """
full_path = os.path.join(*args)
to_make = os.path.dirname(full_path)
mkdir(to_make, recursive=True)
full_path = to_native_path(full_path)
return full_path
def username():
""" Get the current user name """
if os.name != 'nt':
import pwd
uid = os.getuid() # pylint:disable=no-member
pw_info = pwd.getpwuid(uid)
if pw_info:
return pw_info.pw_name
_username = os.environ.get("USERNAME")
if _username:
return _username
return None
def mkdir(dest_dir, recursive=False):
""" Recursive mkdir (do not fail if file exists) """
try:
if recursive:
os.makedirs(dest_dir)
else:
os.mkdir(dest_dir)
except OSError as exc:
if exc.errno != 17:
raise
# Directory already exists -> no exception
def ln(src, dst, symlink=True):
""" ln (do not fail if file exists) """
try:
if symlink:
os.symlink(src, dst) # pylint:disable=no-member
else:
raise NotImplementedError
except OSError as exc:
if exc.errno != 17:
raise
def write_file_if_different(data, out_path, mode="w"):
""" Write the data to out_path if the content is different """
try:
with open(out_path, "r") as outr:
out_prev = outr.read()
if out_prev == data:
ui.debug("skipping write to %s: same content" % (out_path))
return
except Exception:
pass
with open(out_path, mode) as out_file:
out_file.write(data)
def configure_file__legacy(in_path, out_path, copy_only=False,
*args, **kwargs): # pylint:disable=keyword-arg-before-vararg
"""
Configure a file.
:param in_path: input file
:param out_path: output file
The out_path needs not to exist, missing leading directories will
be created if necessary.
If copy_only is True, the contents will be copied "as is".
If not, we will use the args and kwargs parameter as in::
in_content.format(*args, **kwargs)
"""
# This function seems to be never called, and has been renamed with __legacy suffix (2020-02-07)
# If nobody complains, remove this function in the next release
warnings.warn(
"Deprecated function: "
"This function seems to be never called, and has been renamed with __legacy suffix (2020-02-07)\n"
"If nobody complains, remove this function in the next release, else, deals with its bad args/kwargs signature",
DeprecationWarning)
mkdir(os.path.dirname(os.path.abspath(out_path)), recursive=True)
with open(in_path, "r") as in_file:
in_content = in_file.read()
if copy_only:
out_content = in_content
else:
out_content = in_content.format(*args, **kwargs)
write_file_if_different(out_content, out_path)
def _copy_link(src, dest, quiet):
""" Copy Link """
if not os.path.islink(src):
raise Exception("%s is not a link!" % src)
target = os.readlink(src) # pylint:disable=no-member
# remove existing stuff
if os.path.lexists(dest):
rm(dest)
if sys.stdout.isatty() and not quiet:
print("-- Installing %s -> %s" % (dest, target))
to_make = os.path.dirname(dest)
mkdir(to_make, recursive=True)
os.symlink(target, dest) # pylint:disable=no-member
def _handle_dirs(src, dest, root, directories, filter_fun, quiet):
""" Helper function used by install() """
installed = list()
rel_root = os.path.relpath(root, src)
# To avoid filering './' stuff
if rel_root == ".":
rel_root = ""
new_root = os.path.join(dest, rel_root)
for directory in directories:
to_filter = os.path.join(rel_root, directory)
if not filter_fun(to_filter):
continue
dsrc = os.path.join(root, directory)
ddest = os.path.join(new_root, directory)
if os.path.islink(dsrc):
_copy_link(dsrc, ddest, quiet)
installed.append(directory)
else:
if os.path.lexists(ddest) and not os.path.isdir(ddest):
raise Exception("Expecting a directory but found a file: %s" % ddest)
mkdir(ddest, recursive=True)
return installed
def _handle_files(src, dest, root, files, filter_fun, quiet):
""" Helper function used by install() """
installed = list()
rel_root = os.path.relpath(root, src)
if rel_root == ".":
rel_root = ""
new_root = os.path.join(dest, rel_root)
for f in files:
if not filter_fun(os.path.join(rel_root, f)):
continue
fsrc = os.path.join(root, f)
fdest = os.path.join(new_root, f)
rel_path = os.path.join(rel_root, f)
if os.path.islink(fsrc):
mkdir(new_root, recursive=True)
_copy_link(fsrc, fdest, quiet)
installed.append(rel_path)
else:
if os.path.lexists(fdest) and os.path.isdir(fdest):
raise Exception("Expecting a file but found a directory: %s" % fdest)
if not quiet:
print("-- Installing %s" % fdest.encode('ascii', "ignore"))
mkdir(new_root, recursive=True)
# We do not want to fail if dest exists but is read only
# (following what `install` does, but not what `cp` does)
rm(fdest)
shutil.copy(fsrc, fdest)
installed.append(rel_path)
return installed
def install(src, dest, filter_fun=None, quiet=False):
"""
Install a directory or a file to a destination.
If filter_fun is not None, then the file will only be
installed if filter_fun(relative/path/to/file) returns True.
If ``dest`` does not exist, it will be created first.
When installing files, if the destination already exists,
it will be removed first, then overwritten by the new file.
This function will preserve relative symlinks between directories,
used for instance in Mac frameworks::
|__ Versions
|__ Current -> 4.0
|__ 4 -> 4.0
|__ 4.0
Return the list of files installed (with relative paths)
"""
installed = list()
# FIXME: add a `safe mode` ala install?
if not os.path.exists(src):
mess = "Could not install '%s' to '%s'\n" % (src, dest)
mess += '%s does not exist' % src
raise Exception(mess)
src = to_native_path(src, normcase=False)
dest = to_native_path(dest, normcase=False)
ui.debug("Installing", src, "->", dest)
if filter_fun is None:
def no_filter_fun(_unused):
""" Filter Function Always True """
return True
filter_fun = no_filter_fun
if os.path.isdir(src):
if src == dest:
raise Exception("source and destination are the same directory")
for (root, dirs, files) in os.walk(src):
dirs = _handle_dirs(src, dest, root, dirs, filter_fun, quiet)
files = _handle_files(src, dest, root, files, filter_fun, quiet)
installed.extend(files)
else:
# Emulate posix `install' behavior:
# if dest is a dir, install in the directory, else
# simply copy the file.
if os.path.isdir(dest):
dest = os.path.join(dest, os.path.basename(src))
if src == dest:
raise Exception("source and destination are the same file")
mkdir(os.path.dirname(dest), recursive=True)
if sys.stdout.isatty() and not quiet:
print("-- Installing %s" % dest)
# We do not want to fail if dest exists but is read only
# (following what `install` does, but not what `cp` does)
rm(dest)
shutil.copy(src, dest)
installed.append(os.path.basename(src))
return installed
def safe_copy(src, dest):
"""
Copy a source file to a destination but
do not overwrite dest if it is more recent than src
Create any missing directories when necessary
If dest is a directory, src will be copied inside dest.
"""
if os.path.isdir(dest):
dest = os.path.join(dest, os.path.basename(src))
if not up_to_date(dest, src):
shutil.copy(src, dest)
def up_to_date(output_path, input_path):
"""" Return True if output_path exists and is more recent than input_path """
if not os.path.exists(output_path):
return False
out_mtime = os.stat(output_path).st_mtime
in_mtime = os.stat(input_path).st_mtime
return out_mtime > in_mtime
def copy_git_src(src, dest):
"""
Copy a source to a destination but only copy the files under version control.
Assumes that ``src`` is inside a git worktree
"""
process = subprocess.Popen(["git", "ls-files", "."], cwd=src,
stdout=subprocess.PIPE)
(out, _) = process.communicate()
for filename in out.splitlines():
src_file = os.path.join(src, filename.decode('ascii'))
dest_file = os.path.join(dest, filename.decode('ascii'))
install(src_file, dest_file, quiet=True)
def rm(name):
"""
This one can take a file or a directory.
Contrary to shutil.remove or os.remove, it:
* won't fail if the directory does not exist
* won't fail if the directory contains read-only files
* won't fail if the file does not exist
Please avoid using shutil.rmtree ...
"""
if not os.path.lexists(name):
return
if os.path.isdir(name) and not os.path.islink(name):
ui.debug("Removing directory:", name)
rmtree(name.encode('ascii', "ignore"))
else:
ui.debug("Removing", name)
os.remove(name)
def rmtree(path):
"""
shutil.rmtree() on steroids.
Taken from gclient source code (BSD license)
Recursively removes a directory, even if it's marked read-only.
shutil.rmtree() doesn't work on Windows if any of the files or directories
are read-only, which svn repositories and some .svn files are. We need to
be able to force the files to be writable (i.e., deletable) as we traverse
the tree.
Even with all this, Windows still sometimes fails to delete a file, citing
a permission error (maybe something to do with antivirus scans or disk
indexing). The best suggestion any of the user forums had was to wait a
bit and try again, so we do that too. It's hand-waving, but sometimes it
works. :/
On POSIX systems, things are a little bit simpler. The modes of the files
to be deleted doesn't matter, only the modes of the directories containing
them are significant. As the directory tree is traversed, each directory
has its mode set appropriately before descending into it. This should
result in the entire tree being removed, with the possible exception of
``path`` itself, because nothing attempts to change the mode of its parent.
Doing so would be hazardous, as it's not a directory slated for removal.
In the ordinary case, this is not a problem: for our purposes, the user
will never lack write permission on ``path``'s parent.
"""
if not os.path.exists(path):
return
if os.path.islink(path) or not os.path.isdir(path):
raise Exception('Called rmtree(%s) in non-directory' % path)
if sys.platform == 'win32':
# Some people don't have the APIs installed. In that case we'll do without.
win32api = None
win32con = None
try:
import win32api
import win32con
except ImportError:
pass
else:
# On POSIX systems, we need the x-bit set on the directory to access it,
# the r-bit to see its contents, and the w-bit to remove files from it.
# The actual modes of the files within the directory is irrelevant.
os.chmod(path, stat.S_IRUSR | stat.S_IWUSR | stat.S_IXUSR)
def remove(func, subpath):
""" Remove """
if sys.platform == 'win32':
os.chmod(subpath, stat.S_IWRITE)
if win32api and win32con:
win32api.SetFileAttributes(subpath, win32con.FILE_ATTRIBUTE_NORMAL)
try:
func(subpath)
except OSError as e:
if e.errno != errno.EACCES or sys.platform != 'win32':
raise
# Failed to delete, try again after a 100ms sleep.
time.sleep(0.1)
func(subpath)
for fn in os.listdir(path):
# If fullpath is a symbolic link that points to a directory, isdir will
# be True, but we don't want to descend into that as a directory, we just
# want to remove the link. Check islink and treat links as ordinary files
# would be treated regardless of what they reference.
fullpath = os.path.join(path, fn)
if os.path.islink(fullpath) or not os.path.isdir(fullpath):
remove(os.remove, fullpath)
else:
# Recurse.
rmtree(fullpath)
remove(os.rmdir, path)
def mv(src, dest):
""" Move a file into a directory, but do not crash if dest/src exists """
if src == dest:
return
if os.path.isdir(dest):
dest = os.path.join(dest, os.path.basename(src))
if os.path.exists(dest):
rm(dest)
ui.debug(src, "->", dest)
shutil.move(src, dest)
def ls_r(directory):
"""
Returns a sorted list of all the files present in a directory,
relative to this directory.
For instance, with::
foo
|__ eggs
| |__ c
| |__ d
|__ empty
|__ spam
|__a
|__b
ls_r(foo) returns:
["eggs/c", "eggs/d", "empty/", "spam/a", "spam/b"]
"""
res = list()
for root, dirs, files in os.walk(directory):
new_root = os.path.relpath(root, directory)
if new_root == "." and not files:
continue
if new_root == "." and files:
res.extend(files)
continue
if not files and not dirs:
res.append(new_root + os.path.sep)
continue
for f in files:
res.append(os.path.join(new_root, f))
return sorted(res)
def which(program):
"""
find program in the environment PATH
:return: path to program if found, None otherwise
"""
warnings.warn("qisys.sh.which is deprecated, "
"use qisys.command.find_program instead")
from qisys.command import find_program
return find_program(program)
def to_posix_path(path, fix_drive=False):
"""
Returns a POSIX path from a DOS path
:param fix_drive: if True, will replace c: by /c/ (ala mingw)
"""
res = os.path.expanduser(path)
res = os.path.abspath(res)
res = path.replace(ntpath.sep, posixpath.sep)
if fix_drive:
(drive, rest) = os.path.splitdrive(res)
letter = drive[0]
return "/" + letter + rest
return res
def to_dos_path(path):
"""
Return a DOS path from a "windows with /" path.
Useful because people sometimes use forward slash in
environment variable, for instance
"""
res = path.replace(posixpath.sep, ntpath.sep)
return res
def to_native_path(path, normcase=True):
"""
Return an absolute, native path from a path,
:param normcase: make sure the path is all lower-case on
case-insensitive filesystems
"""
path = os.path.expanduser(path)
if normcase:
path = os.path.normcase(path)
path = os.path.normpath(path)
path = os.path.abspath(path)
path = os.path.realpath(path)
if sys.platform.startswith("win"):
path = to_dos_path(path)
return path
def is_path_inside(a, b):
"""
Returns True if a is inside b
>>> is_path_inside("foo/bar", "foo")
True
>>> is_path_inside("gui/bar/libfoo", "lib")
False
"""
a = to_native_path(a)
b = to_native_path(b)
a_split = a.split(os.path.sep)
b_split = b.split(os.path.sep)
if len(a_split) < len(b_split):
return False
for (a_part, b_part) in zip(a_split, b_split):
if a_part != b_part:
return False
return True
def is_empty(path):
""" Check if a path is empty """
return os.listdir(path) == list()
class | (object):
"""
This is a nice wrapper around tempfile module.
Usage::
with TempDir("foo-bar") as temp_dir:
subdir = os.path.join(temp_dir, "subdir")
do_foo(subdir)
This piece of code makes sure that:
* a temporary directory named temp_dir has been
created (guaranteed to exist, be empty, and writeable)
* the directory will be removed when the scope of
temp_dir has ended unless an exception has occurred
and DEBUG environment variable is set.
"""
def __init__(self, name="tmp"):
""" TempDir Init """
self._temp_dir = tempfile.mkdtemp(prefix=name + "-")
def __enter__(self):
""" Enter """
return self._temp_dir
def __exit__(self, _type, value, tb):
""" Exit """
if os.environ.get("DEBUG"):
if tb is not None:
print("==")
print("Not removing ", self._temp_dir)
print("==")
return
rm(self._temp_dir)
@contextlib.contextmanager
def change_cwd(directory):
""" Change the current working dir """
if not os.path.exists(directory):
mess = "Cannot change working dir to '%s'\n" % directory
mess += "This path does not exist"
raise Exception(mess)
previous_cwd = os.getcwd()
os.chdir(directory)
yield
os.chdir(previous_cwd)
def is_runtime(filename):
""" Filter function to only install runtime components of packages """
# FIXME: this looks like a hack.
# Maybe a user-generated MANIFEST at the root of the package path
# would be better?
basedir = filename.split(os.path.sep)[0]
if filename.startswith("bin") and sys.platform.startswith("win"):
return filename.endswith(".exe") or filename.endswith(".dll")
if filename.startswith("lib"):
is_lib_prefixed_runtime = not filename.endswith((".a", ".lib", ".la", ".pc"))
return is_lib_prefixed_runtime
if filename.startswith(os.path.join("share", "cmake")) or \
filename.startswith(os.path.join("share", "man")):
return False
if basedir == "include":
# Usually runtime dir names aren't include, but there is an exception for python:
return filename.endswith("pyconfig.h")
# True by default: better have too much stuff than not enough
# That includes these known cases:
# * filename.startswith("bin") but not sys.platform.startswith("win")
# * basedir == "share"
# * basedir.endswith(".framework")
return True
def broken_symlink(file_path):
""" Returns True if the file is a broken symlink """
return os.path.lexists(file_path) and not os.path.exists(file_path)
def is_binary(file_path):
""" Returns True if the file is binary """
with open(file_path, 'rb') as fp:
data = fp.read(1024)
if not data:
return False
if b'\0' in data:
return True
return False
def is_executable_binary(file_path):
"""
Returns true if the file:
* is executable
* is a binary (i.e not a script)
"""
if not os.path.isfile(file_path):
return False
if not os.access(file_path, os.X_OK):
return False
return is_binary(file_path)
class PreserveFileMetadata(object):
""" Preserve file metadata (permissions and times) """
def __init__(self, path):
""" Preserve file metadata of 'path' """
self.path = path
self.time = None
self.mode = None
def __enter__(self):
""" Enter method saving metadata """
st = os.stat(self.path)
self.time = (st.st_atime, st.st_mtime)
self.mode = st.st_mode
def __exit__(self, _type, value, tb):
""" Exit method restoring metadata """
os.chmod(self.path, self.mode)
os.utime(self.path, self.time)
| TempDir | identifier_name |
sh.py | #!/usr/bin/env python
# -*- coding: utf-8 -*-
# Copyright (c) 2012-2021 SoftBank Robotics. All rights reserved.
# Use of this source code is governed by a BSD-style license (see the COPYING file).
""" Common filesystem operations """
from __future__ import absolute_import
from __future__ import unicode_literals
from __future__ import print_function
import os
import sys
import stat
import time
import errno
import ntpath
import shutil
import tempfile
import warnings
import posixpath
import contextlib
import subprocess
from qisys import ui
try:
from xdg.BaseDirectory import xdg_cache_home, xdg_config_home, xdg_data_home
except ImportError:
xdg_config_home = os.path.expanduser("~/.config")
xdg_cache_home = os.path.expanduser("~/.cache")
xdg_data_home = os.path.expanduser("~/.local/share")
CONFIG_PATH = xdg_config_home
CACHE_PATH = xdg_cache_home
SHARE_PATH = xdg_data_home
def set_home(home):
""" Set Home """
# This module should be refactored into object to avoid the anti-pattern global statement
global CONFIG_PATH, CACHE_PATH, SHARE_PATH
CONFIG_PATH = os.path.join(home, "config")
CACHE_PATH = os.path.join(home, "cache")
SHARE_PATH = os.path.join(home, "share")
def get_config_path(*args):
"""
Get a config path to read or write some configuration.
:param args: a list of subfolders. Those will be created when needed
"""
return get_path(CONFIG_PATH, *args)
def get_cache_path(*args):
"""
Get a config path to read or write some cached data
:param args: a list of subfolders. Those will be created when needed
"""
return get_path(CACHE_PATH, *args)
def get_share_path(*args):
"""
Get a config path to read or write some persistent data
:param args: a list of subfolders. Those will be created when needed
"""
return get_path(SHARE_PATH, *args)
def get_path(*args):
""" Helper for get_*_path methods """
full_path = os.path.join(*args)
to_make = os.path.dirname(full_path)
mkdir(to_make, recursive=True)
full_path = to_native_path(full_path)
return full_path
def username():
""" Get the current user name """
if os.name != 'nt':
import pwd
uid = os.getuid() # pylint:disable=no-member
pw_info = pwd.getpwuid(uid)
if pw_info:
return pw_info.pw_name
_username = os.environ.get("USERNAME")
if _username:
return _username
return None
def mkdir(dest_dir, recursive=False):
""" Recursive mkdir (do not fail if file exists) """
try:
if recursive:
os.makedirs(dest_dir)
else:
os.mkdir(dest_dir)
except OSError as exc:
if exc.errno != 17:
raise
# Directory already exists -> no exception
def ln(src, dst, symlink=True):
""" ln (do not fail if file exists) """
try:
if symlink:
os.symlink(src, dst) # pylint:disable=no-member
else:
raise NotImplementedError
except OSError as exc:
if exc.errno != 17:
raise
def write_file_if_different(data, out_path, mode="w"):
""" Write the data to out_path if the content is different """
try:
with open(out_path, "r") as outr:
out_prev = outr.read()
if out_prev == data:
ui.debug("skipping write to %s: same content" % (out_path))
return
except Exception:
pass
with open(out_path, mode) as out_file:
out_file.write(data)
def configure_file__legacy(in_path, out_path, copy_only=False,
*args, **kwargs): # pylint:disable=keyword-arg-before-vararg
"""
Configure a file.
:param in_path: input file
:param out_path: output file
The out_path needs not to exist, missing leading directories will
be created if necessary.
If copy_only is True, the contents will be copied "as is".
If not, we will use the args and kwargs parameter as in::
in_content.format(*args, **kwargs)
"""
# This function seems to be never called, and has been renamed with __legacy suffix (2020-02-07)
# If nobody complains, remove this function in the next release
warnings.warn(
"Deprecated function: "
"This function seems to be never called, and has been renamed with __legacy suffix (2020-02-07)\n"
"If nobody complains, remove this function in the next release, else, deals with its bad args/kwargs signature",
DeprecationWarning)
mkdir(os.path.dirname(os.path.abspath(out_path)), recursive=True)
with open(in_path, "r") as in_file:
in_content = in_file.read()
if copy_only:
out_content = in_content
else:
out_content = in_content.format(*args, **kwargs)
write_file_if_different(out_content, out_path)
def _copy_link(src, dest, quiet):
""" Copy Link """
if not os.path.islink(src):
raise Exception("%s is not a link!" % src)
target = os.readlink(src) # pylint:disable=no-member
# remove existing stuff
if os.path.lexists(dest):
rm(dest)
if sys.stdout.isatty() and not quiet:
print("-- Installing %s -> %s" % (dest, target))
to_make = os.path.dirname(dest)
mkdir(to_make, recursive=True)
os.symlink(target, dest) # pylint:disable=no-member
def _handle_dirs(src, dest, root, directories, filter_fun, quiet):
""" Helper function used by install() """
installed = list()
rel_root = os.path.relpath(root, src)
# To avoid filering './' stuff
if rel_root == ".":
rel_root = ""
new_root = os.path.join(dest, rel_root)
for directory in directories:
to_filter = os.path.join(rel_root, directory)
if not filter_fun(to_filter):
continue
dsrc = os.path.join(root, directory)
ddest = os.path.join(new_root, directory)
if os.path.islink(dsrc):
_copy_link(dsrc, ddest, quiet)
installed.append(directory)
else:
if os.path.lexists(ddest) and not os.path.isdir(ddest):
raise Exception("Expecting a directory but found a file: %s" % ddest)
mkdir(ddest, recursive=True)
return installed
def _handle_files(src, dest, root, files, filter_fun, quiet):
""" Helper function used by install() """
installed = list()
rel_root = os.path.relpath(root, src)
if rel_root == ".":
rel_root = ""
new_root = os.path.join(dest, rel_root)
for f in files:
if not filter_fun(os.path.join(rel_root, f)):
continue
fsrc = os.path.join(root, f)
fdest = os.path.join(new_root, f)
rel_path = os.path.join(rel_root, f)
if os.path.islink(fsrc):
mkdir(new_root, recursive=True)
_copy_link(fsrc, fdest, quiet)
installed.append(rel_path)
else:
if os.path.lexists(fdest) and os.path.isdir(fdest):
raise Exception("Expecting a file but found a directory: %s" % fdest)
if not quiet:
print("-- Installing %s" % fdest.encode('ascii', "ignore"))
mkdir(new_root, recursive=True)
# We do not want to fail if dest exists but is read only
# (following what `install` does, but not what `cp` does)
rm(fdest)
shutil.copy(fsrc, fdest)
installed.append(rel_path)
return installed
def install(src, dest, filter_fun=None, quiet=False):
"""
Install a directory or a file to a destination.
If filter_fun is not None, then the file will only be
installed if filter_fun(relative/path/to/file) returns True.
If ``dest`` does not exist, it will be created first.
When installing files, if the destination already exists,
it will be removed first, then overwritten by the new file.
This function will preserve relative symlinks between directories,
used for instance in Mac frameworks::
|__ Versions
|__ Current -> 4.0
|__ 4 -> 4.0
|__ 4.0
Return the list of files installed (with relative paths)
"""
installed = list()
# FIXME: add a `safe mode` ala install?
if not os.path.exists(src):
mess = "Could not install '%s' to '%s'\n" % (src, dest)
mess += '%s does not exist' % src
raise Exception(mess)
src = to_native_path(src, normcase=False)
dest = to_native_path(dest, normcase=False)
ui.debug("Installing", src, "->", dest)
if filter_fun is None:
def no_filter_fun(_unused):
""" Filter Function Always True """
return True
filter_fun = no_filter_fun
if os.path.isdir(src):
if src == dest:
raise Exception("source and destination are the same directory")
for (root, dirs, files) in os.walk(src):
dirs = _handle_dirs(src, dest, root, dirs, filter_fun, quiet)
files = _handle_files(src, dest, root, files, filter_fun, quiet)
installed.extend(files)
else:
# Emulate posix `install' behavior:
# if dest is a dir, install in the directory, else
# simply copy the file.
if os.path.isdir(dest):
dest = os.path.join(dest, os.path.basename(src))
if src == dest:
raise Exception("source and destination are the same file")
mkdir(os.path.dirname(dest), recursive=True)
if sys.stdout.isatty() and not quiet:
print("-- Installing %s" % dest)
# We do not want to fail if dest exists but is read only
# (following what `install` does, but not what `cp` does)
rm(dest)
shutil.copy(src, dest)
installed.append(os.path.basename(src))
return installed
def safe_copy(src, dest):
"""
Copy a source file to a destination but
do not overwrite dest if it is more recent than src
Create any missing directories when necessary
If dest is a directory, src will be copied inside dest.
"""
if os.path.isdir(dest):
dest = os.path.join(dest, os.path.basename(src))
if not up_to_date(dest, src):
shutil.copy(src, dest)
def up_to_date(output_path, input_path):
"""" Return True if output_path exists and is more recent than input_path """
if not os.path.exists(output_path):
return False
out_mtime = os.stat(output_path).st_mtime
in_mtime = os.stat(input_path).st_mtime
return out_mtime > in_mtime
def copy_git_src(src, dest):
"""
Copy a source to a destination but only copy the files under version control.
Assumes that ``src`` is inside a git worktree
"""
process = subprocess.Popen(["git", "ls-files", "."], cwd=src,
stdout=subprocess.PIPE)
(out, _) = process.communicate()
for filename in out.splitlines():
src_file = os.path.join(src, filename.decode('ascii'))
dest_file = os.path.join(dest, filename.decode('ascii'))
install(src_file, dest_file, quiet=True)
def rm(name):
"""
This one can take a file or a directory.
Contrary to shutil.remove or os.remove, it:
* won't fail if the directory does not exist
* won't fail if the directory contains read-only files
* won't fail if the file does not exist
Please avoid using shutil.rmtree ...
"""
if not os.path.lexists(name):
return
if os.path.isdir(name) and not os.path.islink(name):
ui.debug("Removing directory:", name)
rmtree(name.encode('ascii', "ignore"))
else:
ui.debug("Removing", name)
os.remove(name)
def rmtree(path):
"""
shutil.rmtree() on steroids.
Taken from gclient source code (BSD license)
Recursively removes a directory, even if it's marked read-only.
shutil.rmtree() doesn't work on Windows if any of the files or directories
are read-only, which svn repositories and some .svn files are. We need to
be able to force the files to be writable (i.e., deletable) as we traverse
the tree.
Even with all this, Windows still sometimes fails to delete a file, citing
a permission error (maybe something to do with antivirus scans or disk
indexing). The best suggestion any of the user forums had was to wait a
bit and try again, so we do that too. It's hand-waving, but sometimes it
works. :/
On POSIX systems, things are a little bit simpler. The modes of the files
to be deleted doesn't matter, only the modes of the directories containing
them are significant. As the directory tree is traversed, each directory
has its mode set appropriately before descending into it. This should
result in the entire tree being removed, with the possible exception of
``path`` itself, because nothing attempts to change the mode of its parent.
Doing so would be hazardous, as it's not a directory slated for removal.
In the ordinary case, this is not a problem: for our purposes, the user
will never lack write permission on ``path``'s parent.
"""
if not os.path.exists(path):
return
if os.path.islink(path) or not os.path.isdir(path):
raise Exception('Called rmtree(%s) in non-directory' % path)
if sys.platform == 'win32':
# Some people don't have the APIs installed. In that case we'll do without.
win32api = None
win32con = None
try:
import win32api
import win32con
except ImportError:
pass
else:
# On POSIX systems, we need the x-bit set on the directory to access it,
# the r-bit to see its contents, and the w-bit to remove files from it.
# The actual modes of the files within the directory is irrelevant.
os.chmod(path, stat.S_IRUSR | stat.S_IWUSR | stat.S_IXUSR)
def remove(func, subpath):
""" Remove """
if sys.platform == 'win32':
os.chmod(subpath, stat.S_IWRITE)
if win32api and win32con:
win32api.SetFileAttributes(subpath, win32con.FILE_ATTRIBUTE_NORMAL)
try:
func(subpath)
except OSError as e:
if e.errno != errno.EACCES or sys.platform != 'win32':
raise
# Failed to delete, try again after a 100ms sleep.
time.sleep(0.1)
func(subpath)
for fn in os.listdir(path):
# If fullpath is a symbolic link that points to a directory, isdir will
# be True, but we don't want to descend into that as a directory, we just
# want to remove the link. Check islink and treat links as ordinary files
# would be treated regardless of what they reference.
fullpath = os.path.join(path, fn)
if os.path.islink(fullpath) or not os.path.isdir(fullpath):
remove(os.remove, fullpath)
else:
# Recurse.
rmtree(fullpath)
remove(os.rmdir, path)
def mv(src, dest):
""" Move a file into a directory, but do not crash if dest/src exists """
if src == dest:
return
if os.path.isdir(dest):
dest = os.path.join(dest, os.path.basename(src))
if os.path.exists(dest):
rm(dest)
ui.debug(src, "->", dest)
shutil.move(src, dest)
def ls_r(directory):
"""
Returns a sorted list of all the files present in a directory,
relative to this directory.
For instance, with::
foo
|__ eggs
| |__ c
| |__ d
|__ empty
|__ spam
|__a
|__b
ls_r(foo) returns:
["eggs/c", "eggs/d", "empty/", "spam/a", "spam/b"]
"""
res = list()
for root, dirs, files in os.walk(directory):
new_root = os.path.relpath(root, directory)
if new_root == "." and not files:
continue
if new_root == "." and files:
res.extend(files)
continue
if not files and not dirs:
res.append(new_root + os.path.sep)
continue
for f in files:
res.append(os.path.join(new_root, f))
return sorted(res)
def which(program):
"""
find program in the environment PATH
:return: path to program if found, None otherwise
"""
warnings.warn("qisys.sh.which is deprecated, "
"use qisys.command.find_program instead")
from qisys.command import find_program
return find_program(program)
def to_posix_path(path, fix_drive=False):
"""
Returns a POSIX path from a DOS path
:param fix_drive: if True, will replace c: by /c/ (ala mingw)
"""
res = os.path.expanduser(path)
res = os.path.abspath(res)
res = path.replace(ntpath.sep, posixpath.sep)
if fix_drive:
(drive, rest) = os.path.splitdrive(res)
letter = drive[0]
return "/" + letter + rest
return res
def to_dos_path(path):
"""
Return a DOS path from a "windows with /" path.
Useful because people sometimes use forward slash in
environment variable, for instance
"""
res = path.replace(posixpath.sep, ntpath.sep)
return res
def to_native_path(path, normcase=True):
"""
Return an absolute, native path from a path,
:param normcase: make sure the path is all lower-case on
case-insensitive filesystems
"""
path = os.path.expanduser(path)
if normcase:
path = os.path.normcase(path)
path = os.path.normpath(path)
path = os.path.abspath(path)
path = os.path.realpath(path)
if sys.platform.startswith("win"):
path = to_dos_path(path)
return path
def is_path_inside(a, b):
"""
Returns True if a is inside b
>>> is_path_inside("foo/bar", "foo")
True
>>> is_path_inside("gui/bar/libfoo", "lib")
False
"""
a = to_native_path(a)
b = to_native_path(b)
a_split = a.split(os.path.sep)
b_split = b.split(os.path.sep)
if len(a_split) < len(b_split):
return False
for (a_part, b_part) in zip(a_split, b_split):
if a_part != b_part:
return False
return True
def is_empty(path):
""" Check if a path is empty """
return os.listdir(path) == list()
class TempDir(object):
"""
This is a nice wrapper around tempfile module.
Usage::
with TempDir("foo-bar") as temp_dir:
subdir = os.path.join(temp_dir, "subdir")
do_foo(subdir)
This piece of code makes sure that:
* a temporary directory named temp_dir has been
created (guaranteed to exist, be empty, and writeable)
* the directory will be removed when the scope of
temp_dir has ended unless an exception has occurred
and DEBUG environment variable is set.
"""
def __init__(self, name="tmp"):
""" TempDir Init """
self._temp_dir = tempfile.mkdtemp(prefix=name + "-")
def __enter__(self):
""" Enter """
return self._temp_dir
def __exit__(self, _type, value, tb):
""" Exit """
if os.environ.get("DEBUG"):
if tb is not None:
print("==")
print("Not removing ", self._temp_dir)
print("==")
return
rm(self._temp_dir)
@contextlib.contextmanager
def change_cwd(directory):
""" Change the current working dir """
if not os.path.exists(directory):
mess = "Cannot change working dir to '%s'\n" % directory
mess += "This path does not exist"
raise Exception(mess)
previous_cwd = os.getcwd()
os.chdir(directory)
yield
os.chdir(previous_cwd)
def is_runtime(filename):
""" Filter function to only install runtime components of packages """
# FIXME: this looks like a hack.
# Maybe a user-generated MANIFEST at the root of the package path
# would be better?
basedir = filename.split(os.path.sep)[0]
if filename.startswith("bin") and sys.platform.startswith("win"):
return filename.endswith(".exe") or filename.endswith(".dll")
if filename.startswith("lib"):
is_lib_prefixed_runtime = not filename.endswith((".a", ".lib", ".la", ".pc"))
return is_lib_prefixed_runtime
if filename.startswith(os.path.join("share", "cmake")) or \
filename.startswith(os.path.join("share", "man")):
return False
if basedir == "include":
# Usually runtime dir names aren't include, but there is an exception for python:
return filename.endswith("pyconfig.h")
# True by default: better have too much stuff than not enough
# That includes these known cases:
# * filename.startswith("bin") but not sys.platform.startswith("win")
# * basedir == "share"
# * basedir.endswith(".framework")
return True
def broken_symlink(file_path):
""" Returns True if the file is a broken symlink """
return os.path.lexists(file_path) and not os.path.exists(file_path)
def is_binary(file_path):
""" Returns True if the file is binary """
with open(file_path, 'rb') as fp:
data = fp.read(1024)
if not data:
return False
if b'\0' in data: | """
Returns true if the file:
* is executable
* is a binary (i.e not a script)
"""
if not os.path.isfile(file_path):
return False
if not os.access(file_path, os.X_OK):
return False
return is_binary(file_path)
class PreserveFileMetadata(object):
""" Preserve file metadata (permissions and times) """
def __init__(self, path):
""" Preserve file metadata of 'path' """
self.path = path
self.time = None
self.mode = None
def __enter__(self):
""" Enter method saving metadata """
st = os.stat(self.path)
self.time = (st.st_atime, st.st_mtime)
self.mode = st.st_mode
def __exit__(self, _type, value, tb):
""" Exit method restoring metadata """
os.chmod(self.path, self.mode)
os.utime(self.path, self.time) | return True
return False
def is_executable_binary(file_path): | random_line_split |
sh.py | #!/usr/bin/env python
# -*- coding: utf-8 -*-
# Copyright (c) 2012-2021 SoftBank Robotics. All rights reserved.
# Use of this source code is governed by a BSD-style license (see the COPYING file).
""" Common filesystem operations """
from __future__ import absolute_import
from __future__ import unicode_literals
from __future__ import print_function
import os
import sys
import stat
import time
import errno
import ntpath
import shutil
import tempfile
import warnings
import posixpath
import contextlib
import subprocess
from qisys import ui
try:
from xdg.BaseDirectory import xdg_cache_home, xdg_config_home, xdg_data_home
except ImportError:
xdg_config_home = os.path.expanduser("~/.config")
xdg_cache_home = os.path.expanduser("~/.cache")
xdg_data_home = os.path.expanduser("~/.local/share")
CONFIG_PATH = xdg_config_home
CACHE_PATH = xdg_cache_home
SHARE_PATH = xdg_data_home
def set_home(home):
""" Set Home """
# This module should be refactored into object to avoid the anti-pattern global statement
global CONFIG_PATH, CACHE_PATH, SHARE_PATH
CONFIG_PATH = os.path.join(home, "config")
CACHE_PATH = os.path.join(home, "cache")
SHARE_PATH = os.path.join(home, "share")
def get_config_path(*args):
"""
Get a config path to read or write some configuration.
:param args: a list of subfolders. Those will be created when needed
"""
return get_path(CONFIG_PATH, *args)
def get_cache_path(*args):
"""
Get a config path to read or write some cached data
:param args: a list of subfolders. Those will be created when needed
"""
return get_path(CACHE_PATH, *args)
def get_share_path(*args):
"""
Get a config path to read or write some persistent data
:param args: a list of subfolders. Those will be created when needed
"""
return get_path(SHARE_PATH, *args)
def get_path(*args):
""" Helper for get_*_path methods """
full_path = os.path.join(*args)
to_make = os.path.dirname(full_path)
mkdir(to_make, recursive=True)
full_path = to_native_path(full_path)
return full_path
def username():
""" Get the current user name """
if os.name != 'nt':
|
_username = os.environ.get("USERNAME")
if _username:
return _username
return None
def mkdir(dest_dir, recursive=False):
""" Recursive mkdir (do not fail if file exists) """
try:
if recursive:
os.makedirs(dest_dir)
else:
os.mkdir(dest_dir)
except OSError as exc:
if exc.errno != 17:
raise
# Directory already exists -> no exception
def ln(src, dst, symlink=True):
""" ln (do not fail if file exists) """
try:
if symlink:
os.symlink(src, dst) # pylint:disable=no-member
else:
raise NotImplementedError
except OSError as exc:
if exc.errno != 17:
raise
def write_file_if_different(data, out_path, mode="w"):
""" Write the data to out_path if the content is different """
try:
with open(out_path, "r") as outr:
out_prev = outr.read()
if out_prev == data:
ui.debug("skipping write to %s: same content" % (out_path))
return
except Exception:
pass
with open(out_path, mode) as out_file:
out_file.write(data)
def configure_file__legacy(in_path, out_path, copy_only=False,
*args, **kwargs): # pylint:disable=keyword-arg-before-vararg
"""
Configure a file.
:param in_path: input file
:param out_path: output file
The out_path needs not to exist, missing leading directories will
be created if necessary.
If copy_only is True, the contents will be copied "as is".
If not, we will use the args and kwargs parameter as in::
in_content.format(*args, **kwargs)
"""
# This function seems to be never called, and has been renamed with __legacy suffix (2020-02-07)
# If nobody complains, remove this function in the next release
warnings.warn(
"Deprecated function: "
"This function seems to be never called, and has been renamed with __legacy suffix (2020-02-07)\n"
"If nobody complains, remove this function in the next release, else, deals with its bad args/kwargs signature",
DeprecationWarning)
mkdir(os.path.dirname(os.path.abspath(out_path)), recursive=True)
with open(in_path, "r") as in_file:
in_content = in_file.read()
if copy_only:
out_content = in_content
else:
out_content = in_content.format(*args, **kwargs)
write_file_if_different(out_content, out_path)
def _copy_link(src, dest, quiet):
""" Copy Link """
if not os.path.islink(src):
raise Exception("%s is not a link!" % src)
target = os.readlink(src) # pylint:disable=no-member
# remove existing stuff
if os.path.lexists(dest):
rm(dest)
if sys.stdout.isatty() and not quiet:
print("-- Installing %s -> %s" % (dest, target))
to_make = os.path.dirname(dest)
mkdir(to_make, recursive=True)
os.symlink(target, dest) # pylint:disable=no-member
def _handle_dirs(src, dest, root, directories, filter_fun, quiet):
""" Helper function used by install() """
installed = list()
rel_root = os.path.relpath(root, src)
# To avoid filering './' stuff
if rel_root == ".":
rel_root = ""
new_root = os.path.join(dest, rel_root)
for directory in directories:
to_filter = os.path.join(rel_root, directory)
if not filter_fun(to_filter):
continue
dsrc = os.path.join(root, directory)
ddest = os.path.join(new_root, directory)
if os.path.islink(dsrc):
_copy_link(dsrc, ddest, quiet)
installed.append(directory)
else:
if os.path.lexists(ddest) and not os.path.isdir(ddest):
raise Exception("Expecting a directory but found a file: %s" % ddest)
mkdir(ddest, recursive=True)
return installed
def _handle_files(src, dest, root, files, filter_fun, quiet):
""" Helper function used by install() """
installed = list()
rel_root = os.path.relpath(root, src)
if rel_root == ".":
rel_root = ""
new_root = os.path.join(dest, rel_root)
for f in files:
if not filter_fun(os.path.join(rel_root, f)):
continue
fsrc = os.path.join(root, f)
fdest = os.path.join(new_root, f)
rel_path = os.path.join(rel_root, f)
if os.path.islink(fsrc):
mkdir(new_root, recursive=True)
_copy_link(fsrc, fdest, quiet)
installed.append(rel_path)
else:
if os.path.lexists(fdest) and os.path.isdir(fdest):
raise Exception("Expecting a file but found a directory: %s" % fdest)
if not quiet:
print("-- Installing %s" % fdest.encode('ascii', "ignore"))
mkdir(new_root, recursive=True)
# We do not want to fail if dest exists but is read only
# (following what `install` does, but not what `cp` does)
rm(fdest)
shutil.copy(fsrc, fdest)
installed.append(rel_path)
return installed
def install(src, dest, filter_fun=None, quiet=False):
"""
Install a directory or a file to a destination.
If filter_fun is not None, then the file will only be
installed if filter_fun(relative/path/to/file) returns True.
If ``dest`` does not exist, it will be created first.
When installing files, if the destination already exists,
it will be removed first, then overwritten by the new file.
This function will preserve relative symlinks between directories,
used for instance in Mac frameworks::
|__ Versions
|__ Current -> 4.0
|__ 4 -> 4.0
|__ 4.0
Return the list of files installed (with relative paths)
"""
installed = list()
# FIXME: add a `safe mode` ala install?
if not os.path.exists(src):
mess = "Could not install '%s' to '%s'\n" % (src, dest)
mess += '%s does not exist' % src
raise Exception(mess)
src = to_native_path(src, normcase=False)
dest = to_native_path(dest, normcase=False)
ui.debug("Installing", src, "->", dest)
if filter_fun is None:
def no_filter_fun(_unused):
""" Filter Function Always True """
return True
filter_fun = no_filter_fun
if os.path.isdir(src):
if src == dest:
raise Exception("source and destination are the same directory")
for (root, dirs, files) in os.walk(src):
dirs = _handle_dirs(src, dest, root, dirs, filter_fun, quiet)
files = _handle_files(src, dest, root, files, filter_fun, quiet)
installed.extend(files)
else:
# Emulate posix `install' behavior:
# if dest is a dir, install in the directory, else
# simply copy the file.
if os.path.isdir(dest):
dest = os.path.join(dest, os.path.basename(src))
if src == dest:
raise Exception("source and destination are the same file")
mkdir(os.path.dirname(dest), recursive=True)
if sys.stdout.isatty() and not quiet:
print("-- Installing %s" % dest)
# We do not want to fail if dest exists but is read only
# (following what `install` does, but not what `cp` does)
rm(dest)
shutil.copy(src, dest)
installed.append(os.path.basename(src))
return installed
def safe_copy(src, dest):
"""
Copy a source file to a destination but
do not overwrite dest if it is more recent than src
Create any missing directories when necessary
If dest is a directory, src will be copied inside dest.
"""
if os.path.isdir(dest):
dest = os.path.join(dest, os.path.basename(src))
if not up_to_date(dest, src):
shutil.copy(src, dest)
def up_to_date(output_path, input_path):
"""" Return True if output_path exists and is more recent than input_path """
if not os.path.exists(output_path):
return False
out_mtime = os.stat(output_path).st_mtime
in_mtime = os.stat(input_path).st_mtime
return out_mtime > in_mtime
def copy_git_src(src, dest):
"""
Copy a source to a destination but only copy the files under version control.
Assumes that ``src`` is inside a git worktree
"""
process = subprocess.Popen(["git", "ls-files", "."], cwd=src,
stdout=subprocess.PIPE)
(out, _) = process.communicate()
for filename in out.splitlines():
src_file = os.path.join(src, filename.decode('ascii'))
dest_file = os.path.join(dest, filename.decode('ascii'))
install(src_file, dest_file, quiet=True)
def rm(name):
"""
This one can take a file or a directory.
Contrary to shutil.remove or os.remove, it:
* won't fail if the directory does not exist
* won't fail if the directory contains read-only files
* won't fail if the file does not exist
Please avoid using shutil.rmtree ...
"""
if not os.path.lexists(name):
return
if os.path.isdir(name) and not os.path.islink(name):
ui.debug("Removing directory:", name)
rmtree(name.encode('ascii', "ignore"))
else:
ui.debug("Removing", name)
os.remove(name)
def rmtree(path):
"""
shutil.rmtree() on steroids.
Taken from gclient source code (BSD license)
Recursively removes a directory, even if it's marked read-only.
shutil.rmtree() doesn't work on Windows if any of the files or directories
are read-only, which svn repositories and some .svn files are. We need to
be able to force the files to be writable (i.e., deletable) as we traverse
the tree.
Even with all this, Windows still sometimes fails to delete a file, citing
a permission error (maybe something to do with antivirus scans or disk
indexing). The best suggestion any of the user forums had was to wait a
bit and try again, so we do that too. It's hand-waving, but sometimes it
works. :/
On POSIX systems, things are a little bit simpler. The modes of the files
to be deleted doesn't matter, only the modes of the directories containing
them are significant. As the directory tree is traversed, each directory
has its mode set appropriately before descending into it. This should
result in the entire tree being removed, with the possible exception of
``path`` itself, because nothing attempts to change the mode of its parent.
Doing so would be hazardous, as it's not a directory slated for removal.
In the ordinary case, this is not a problem: for our purposes, the user
will never lack write permission on ``path``'s parent.
"""
if not os.path.exists(path):
return
if os.path.islink(path) or not os.path.isdir(path):
raise Exception('Called rmtree(%s) in non-directory' % path)
if sys.platform == 'win32':
# Some people don't have the APIs installed. In that case we'll do without.
win32api = None
win32con = None
try:
import win32api
import win32con
except ImportError:
pass
else:
# On POSIX systems, we need the x-bit set on the directory to access it,
# the r-bit to see its contents, and the w-bit to remove files from it.
# The actual modes of the files within the directory is irrelevant.
os.chmod(path, stat.S_IRUSR | stat.S_IWUSR | stat.S_IXUSR)
def remove(func, subpath):
""" Remove """
if sys.platform == 'win32':
os.chmod(subpath, stat.S_IWRITE)
if win32api and win32con:
win32api.SetFileAttributes(subpath, win32con.FILE_ATTRIBUTE_NORMAL)
try:
func(subpath)
except OSError as e:
if e.errno != errno.EACCES or sys.platform != 'win32':
raise
# Failed to delete, try again after a 100ms sleep.
time.sleep(0.1)
func(subpath)
for fn in os.listdir(path):
# If fullpath is a symbolic link that points to a directory, isdir will
# be True, but we don't want to descend into that as a directory, we just
# want to remove the link. Check islink and treat links as ordinary files
# would be treated regardless of what they reference.
fullpath = os.path.join(path, fn)
if os.path.islink(fullpath) or not os.path.isdir(fullpath):
remove(os.remove, fullpath)
else:
# Recurse.
rmtree(fullpath)
remove(os.rmdir, path)
def mv(src, dest):
""" Move a file into a directory, but do not crash if dest/src exists """
if src == dest:
return
if os.path.isdir(dest):
dest = os.path.join(dest, os.path.basename(src))
if os.path.exists(dest):
rm(dest)
ui.debug(src, "->", dest)
shutil.move(src, dest)
def ls_r(directory):
"""
Returns a sorted list of all the files present in a directory,
relative to this directory.
For instance, with::
foo
|__ eggs
| |__ c
| |__ d
|__ empty
|__ spam
|__a
|__b
ls_r(foo) returns:
["eggs/c", "eggs/d", "empty/", "spam/a", "spam/b"]
"""
res = list()
for root, dirs, files in os.walk(directory):
new_root = os.path.relpath(root, directory)
if new_root == "." and not files:
continue
if new_root == "." and files:
res.extend(files)
continue
if not files and not dirs:
res.append(new_root + os.path.sep)
continue
for f in files:
res.append(os.path.join(new_root, f))
return sorted(res)
def which(program):
"""
find program in the environment PATH
:return: path to program if found, None otherwise
"""
warnings.warn("qisys.sh.which is deprecated, "
"use qisys.command.find_program instead")
from qisys.command import find_program
return find_program(program)
def to_posix_path(path, fix_drive=False):
"""
Returns a POSIX path from a DOS path
:param fix_drive: if True, will replace c: by /c/ (ala mingw)
"""
res = os.path.expanduser(path)
res = os.path.abspath(res)
res = path.replace(ntpath.sep, posixpath.sep)
if fix_drive:
(drive, rest) = os.path.splitdrive(res)
letter = drive[0]
return "/" + letter + rest
return res
def to_dos_path(path):
"""
Return a DOS path from a "windows with /" path.
Useful because people sometimes use forward slash in
environment variable, for instance
"""
res = path.replace(posixpath.sep, ntpath.sep)
return res
def to_native_path(path, normcase=True):
"""
Return an absolute, native path from a path,
:param normcase: make sure the path is all lower-case on
case-insensitive filesystems
"""
path = os.path.expanduser(path)
if normcase:
path = os.path.normcase(path)
path = os.path.normpath(path)
path = os.path.abspath(path)
path = os.path.realpath(path)
if sys.platform.startswith("win"):
path = to_dos_path(path)
return path
def is_path_inside(a, b):
"""
Returns True if a is inside b
>>> is_path_inside("foo/bar", "foo")
True
>>> is_path_inside("gui/bar/libfoo", "lib")
False
"""
a = to_native_path(a)
b = to_native_path(b)
a_split = a.split(os.path.sep)
b_split = b.split(os.path.sep)
if len(a_split) < len(b_split):
return False
for (a_part, b_part) in zip(a_split, b_split):
if a_part != b_part:
return False
return True
def is_empty(path):
""" Check if a path is empty """
return os.listdir(path) == list()
class TempDir(object):
"""
This is a nice wrapper around tempfile module.
Usage::
with TempDir("foo-bar") as temp_dir:
subdir = os.path.join(temp_dir, "subdir")
do_foo(subdir)
This piece of code makes sure that:
* a temporary directory named temp_dir has been
created (guaranteed to exist, be empty, and writeable)
* the directory will be removed when the scope of
temp_dir has ended unless an exception has occurred
and DEBUG environment variable is set.
"""
def __init__(self, name="tmp"):
""" TempDir Init """
self._temp_dir = tempfile.mkdtemp(prefix=name + "-")
def __enter__(self):
""" Enter """
return self._temp_dir
def __exit__(self, _type, value, tb):
""" Exit """
if os.environ.get("DEBUG"):
if tb is not None:
print("==")
print("Not removing ", self._temp_dir)
print("==")
return
rm(self._temp_dir)
@contextlib.contextmanager
def change_cwd(directory):
""" Change the current working dir """
if not os.path.exists(directory):
mess = "Cannot change working dir to '%s'\n" % directory
mess += "This path does not exist"
raise Exception(mess)
previous_cwd = os.getcwd()
os.chdir(directory)
yield
os.chdir(previous_cwd)
def is_runtime(filename):
""" Filter function to only install runtime components of packages """
# FIXME: this looks like a hack.
# Maybe a user-generated MANIFEST at the root of the package path
# would be better?
basedir = filename.split(os.path.sep)[0]
if filename.startswith("bin") and sys.platform.startswith("win"):
return filename.endswith(".exe") or filename.endswith(".dll")
if filename.startswith("lib"):
is_lib_prefixed_runtime = not filename.endswith((".a", ".lib", ".la", ".pc"))
return is_lib_prefixed_runtime
if filename.startswith(os.path.join("share", "cmake")) or \
filename.startswith(os.path.join("share", "man")):
return False
if basedir == "include":
# Usually runtime dir names aren't include, but there is an exception for python:
return filename.endswith("pyconfig.h")
# True by default: better have too much stuff than not enough
# That includes these known cases:
# * filename.startswith("bin") but not sys.platform.startswith("win")
# * basedir == "share"
# * basedir.endswith(".framework")
return True
def broken_symlink(file_path):
""" Returns True if the file is a broken symlink """
return os.path.lexists(file_path) and not os.path.exists(file_path)
def is_binary(file_path):
""" Returns True if the file is binary """
with open(file_path, 'rb') as fp:
data = fp.read(1024)
if not data:
return False
if b'\0' in data:
return True
return False
def is_executable_binary(file_path):
"""
Returns true if the file:
* is executable
* is a binary (i.e not a script)
"""
if not os.path.isfile(file_path):
return False
if not os.access(file_path, os.X_OK):
return False
return is_binary(file_path)
class PreserveFileMetadata(object):
""" Preserve file metadata (permissions and times) """
def __init__(self, path):
""" Preserve file metadata of 'path' """
self.path = path
self.time = None
self.mode = None
def __enter__(self):
""" Enter method saving metadata """
st = os.stat(self.path)
self.time = (st.st_atime, st.st_mtime)
self.mode = st.st_mode
def __exit__(self, _type, value, tb):
""" Exit method restoring metadata """
os.chmod(self.path, self.mode)
os.utime(self.path, self.time)
| import pwd
uid = os.getuid() # pylint:disable=no-member
pw_info = pwd.getpwuid(uid)
if pw_info:
return pw_info.pw_name | conditional_block |
project-cache-issue-31849.rs | // run-pass
// Regression test for #31849: the problem here was actually a performance
// cliff, but I'm adding the test for reference.
pub trait Upcast<T> {
fn upcast(self) -> T;
}
impl<S1, S2, T1, T2> Upcast<(T1, T2)> for (S1,S2)
where S1: Upcast<T1>,
S2: Upcast<T2>,
{
fn upcast(self) -> (T1, T2) { (self.0.upcast(), self.1.upcast()) }
}
impl Upcast<()> for ()
{
fn upcast(self) -> () { () }
}
pub trait ToStatic {
type Static: 'static;
fn to_static(self) -> Self::Static where Self: Sized;
}
impl<T, U> ToStatic for (T, U)
where T: ToStatic,
U: ToStatic
{
type Static = (T::Static, U::Static);
fn to_static(self) -> Self::Static { (self.0.to_static(), self.1.to_static()) }
}
impl ToStatic for ()
{
type Static = ();
fn to_static(self) -> () { () }
}
trait Factory {
type Output; |
impl<S,T> Factory for (S, T)
where S: Factory,
T: Factory,
S::Output: ToStatic,
<S::Output as ToStatic>::Static: Upcast<S::Output>,
{
type Output = (S::Output, T::Output);
fn build(&self) -> Self::Output { (self.0.build().to_static().upcast(), self.1.build()) }
}
impl Factory for () {
type Output = ();
fn build(&self) -> Self::Output { () }
}
fn main() {
// More parens, more time.
let it = ((((((((((),()),()),()),()),()),()),()),()),());
it.build();
} | fn build(&self) -> Self::Output;
} | random_line_split |
project-cache-issue-31849.rs | // run-pass
// Regression test for #31849: the problem here was actually a performance
// cliff, but I'm adding the test for reference.
pub trait Upcast<T> {
fn upcast(self) -> T;
}
impl<S1, S2, T1, T2> Upcast<(T1, T2)> for (S1,S2)
where S1: Upcast<T1>,
S2: Upcast<T2>,
{
fn upcast(self) -> (T1, T2) |
}
impl Upcast<()> for ()
{
fn upcast(self) -> () { () }
}
pub trait ToStatic {
type Static: 'static;
fn to_static(self) -> Self::Static where Self: Sized;
}
impl<T, U> ToStatic for (T, U)
where T: ToStatic,
U: ToStatic
{
type Static = (T::Static, U::Static);
fn to_static(self) -> Self::Static { (self.0.to_static(), self.1.to_static()) }
}
impl ToStatic for ()
{
type Static = ();
fn to_static(self) -> () { () }
}
trait Factory {
type Output;
fn build(&self) -> Self::Output;
}
impl<S,T> Factory for (S, T)
where S: Factory,
T: Factory,
S::Output: ToStatic,
<S::Output as ToStatic>::Static: Upcast<S::Output>,
{
type Output = (S::Output, T::Output);
fn build(&self) -> Self::Output { (self.0.build().to_static().upcast(), self.1.build()) }
}
impl Factory for () {
type Output = ();
fn build(&self) -> Self::Output { () }
}
fn main() {
// More parens, more time.
let it = ((((((((((),()),()),()),()),()),()),()),()),());
it.build();
}
| { (self.0.upcast(), self.1.upcast()) } | identifier_body |
project-cache-issue-31849.rs | // run-pass
// Regression test for #31849: the problem here was actually a performance
// cliff, but I'm adding the test for reference.
pub trait Upcast<T> {
fn upcast(self) -> T;
}
impl<S1, S2, T1, T2> Upcast<(T1, T2)> for (S1,S2)
where S1: Upcast<T1>,
S2: Upcast<T2>,
{
fn upcast(self) -> (T1, T2) { (self.0.upcast(), self.1.upcast()) }
}
impl Upcast<()> for ()
{
fn upcast(self) -> () { () }
}
pub trait ToStatic {
type Static: 'static;
fn to_static(self) -> Self::Static where Self: Sized;
}
impl<T, U> ToStatic for (T, U)
where T: ToStatic,
U: ToStatic
{
type Static = (T::Static, U::Static);
fn | (self) -> Self::Static { (self.0.to_static(), self.1.to_static()) }
}
impl ToStatic for ()
{
type Static = ();
fn to_static(self) -> () { () }
}
trait Factory {
type Output;
fn build(&self) -> Self::Output;
}
impl<S,T> Factory for (S, T)
where S: Factory,
T: Factory,
S::Output: ToStatic,
<S::Output as ToStatic>::Static: Upcast<S::Output>,
{
type Output = (S::Output, T::Output);
fn build(&self) -> Self::Output { (self.0.build().to_static().upcast(), self.1.build()) }
}
impl Factory for () {
type Output = ();
fn build(&self) -> Self::Output { () }
}
fn main() {
// More parens, more time.
let it = ((((((((((),()),()),()),()),()),()),()),()),());
it.build();
}
| to_static | identifier_name |
terminal.ts | /*---------------------------------------------------------------------------------------------
* Copyright (c) Microsoft Corporation. All rights reserved.
* Licensed under the MIT License. See License.txt in the project root for license information.
*--------------------------------------------------------------------------------------------*/
import { Event } from 'vs/base/common/event';
import { IDisposable } from 'vs/base/common/lifecycle';
import { URI } from 'vs/base/common/uri';
import { FindReplaceState } from 'vs/editor/contrib/find/findState';
import { createDecorator } from 'vs/platform/instantiation/common/instantiation';
import { IShellLaunchConfig, ITerminalChildProcess, ITerminalDimensions, ITerminalLaunchError, ITerminalProfile, ITerminalTabLayoutInfoById, TerminalIcon, TitleEventSource, TerminalShellType, IExtensionTerminalProfile, ITerminalProfileType, TerminalLocation, ICreateContributedTerminalProfileOptions } from 'vs/platform/terminal/common/terminal';
import { ICommandTracker, INavigationMode, IOffProcessTerminalService, IRemoteTerminalAttachTarget, IStartExtensionTerminalRequest, ITerminalConfigHelper, ITerminalProcessExtHostProxy } from 'vs/workbench/contrib/terminal/common/terminal';
import type { Terminal as XTermTerminal } from 'xterm';
import type { SearchAddon as XTermSearchAddon } from 'xterm-addon-search';
import type { Unicode11Addon as XTermUnicode11Addon } from 'xterm-addon-unicode11';
import type { WebglAddon as XTermWebglAddon } from 'xterm-addon-webgl';
import { ITerminalStatusList } from 'vs/workbench/contrib/terminal/browser/terminalStatusList';
import { ICompleteTerminalConfiguration } from 'vs/workbench/contrib/terminal/common/remoteTerminalChannel';
import { Orientation } from 'vs/base/browser/ui/splitview/splitview';
import { IEditableData } from 'vs/workbench/common/views';
import { DeserializedTerminalEditorInput } from 'vs/workbench/contrib/terminal/browser/terminalEditorSerializer';
import { TerminalEditorInput } from 'vs/workbench/contrib/terminal/browser/terminalEditorInput';
import { EditorGroupColumn } from 'vs/workbench/services/editor/common/editorGroupColumn';
export const ITerminalService = createDecorator<ITerminalService>('terminalService');
export const ITerminalEditorService = createDecorator<ITerminalEditorService>('terminalEditorService');
export const ITerminalGroupService = createDecorator<ITerminalGroupService>('terminalGroupService');
export const ITerminalInstanceService = createDecorator<ITerminalInstanceService>('terminalInstanceService');
export const IRemoteTerminalService = createDecorator<IRemoteTerminalService>('remoteTerminalService');
/**
* A service used by TerminalInstance (and components owned by it) that allows it to break its
* dependency on electron-browser and node layers, while at the same time avoiding a cyclic
* dependency on ITerminalService.
*/
export interface ITerminalInstanceService {
readonly _serviceBrand: undefined;
onDidCreateInstance: Event<ITerminalInstance>;
getXtermConstructor(): Promise<typeof XTermTerminal>;
getXtermSearchConstructor(): Promise<typeof XTermSearchAddon>;
getXtermUnicode11Constructor(): Promise<typeof XTermUnicode11Addon>;
getXtermWebglConstructor(): Promise<typeof XTermWebglAddon>;
/**
* Takes a path and returns the properly escaped path to send to the terminal.
* On Windows, this included trying to prepare the path for WSL if needed.
*
* @param executable The executable off the shellLaunchConfig
* @param title The terminal's title
* @param path The path to be escaped and formatted.
* @param isRemote Whether the terminal's pty is remote.
* @returns An escaped version of the path to be execuded in the terminal.
*/
preparePathForTerminalAsync(path: string, executable: string | undefined, title: string, shellType: TerminalShellType, isRemote: boolean): Promise<string>;
createInstance(launchConfig: IShellLaunchConfig, target?: TerminalLocation, resource?: URI): ITerminalInstance;
}
export interface IBrowserTerminalConfigHelper extends ITerminalConfigHelper {
panelContainer: HTMLElement | undefined; | Up = 2,
Down = 3
}
export interface ITerminalGroup {
activeInstance: ITerminalInstance | undefined;
terminalInstances: ITerminalInstance[];
title: string;
readonly onDidDisposeInstance: Event<ITerminalInstance>;
readonly onDisposed: Event<ITerminalGroup>;
readonly onInstancesChanged: Event<void>;
readonly onPanelOrientationChanged: Event<Orientation>;
focusPreviousPane(): void;
focusNextPane(): void;
resizePane(direction: Direction): void;
resizePanes(relativeSizes: number[]): void;
setActiveInstanceByIndex(index: number, force?: boolean): void;
attachToElement(element: HTMLElement): void;
addInstance(instance: ITerminalInstance): void;
removeInstance(instance: ITerminalInstance): void;
moveInstance(instance: ITerminalInstance, index: number): void;
setVisible(visible: boolean): void;
layout(width: number, height: number): void;
addDisposable(disposable: IDisposable): void;
split(shellLaunchConfig: IShellLaunchConfig): ITerminalInstance;
getLayoutInfo(isActive: boolean): ITerminalTabLayoutInfoById;
}
export const enum TerminalConnectionState {
Connecting,
Connected
}
export interface ITerminalService extends ITerminalInstanceHost {
readonly _serviceBrand: undefined;
/** Gets all terminal instances, including editor and terminal view (group) instances. */
readonly instances: readonly ITerminalInstance[];
configHelper: ITerminalConfigHelper;
isProcessSupportRegistered: boolean;
readonly connectionState: TerminalConnectionState;
readonly availableProfiles: ITerminalProfile[];
readonly allProfiles: ITerminalProfileType[] | undefined;
readonly profilesReady: Promise<void>;
readonly defaultLocation: TerminalLocation;
initializeTerminals(): Promise<void>;
onDidChangeActiveGroup: Event<ITerminalGroup | undefined>;
onDidDisposeGroup: Event<ITerminalGroup>;
onDidCreateInstance: Event<ITerminalInstance>;
onDidReceiveProcessId: Event<ITerminalInstance>;
onDidChangeInstanceDimensions: Event<ITerminalInstance>;
onDidMaximumDimensionsChange: Event<ITerminalInstance>;
onDidRequestStartExtensionTerminal: Event<IStartExtensionTerminalRequest>;
onDidChangeInstanceTitle: Event<ITerminalInstance | undefined>;
onDidChangeInstanceIcon: Event<ITerminalInstance | undefined>;
onDidChangeInstanceColor: Event<ITerminalInstance | undefined>;
onDidChangeInstancePrimaryStatus: Event<ITerminalInstance>;
onDidInputInstanceData: Event<ITerminalInstance>;
onDidRegisterProcessSupport: Event<void>;
onDidChangeConnectionState: Event<void>;
onDidChangeAvailableProfiles: Event<ITerminalProfile[]>;
/**
* Creates a terminal.
* @param options The options to create the terminal with, when not specified the default
* profile will be used at the default target.
*/
createTerminal(options?: ICreateTerminalOptions): Promise<ITerminalInstance>;
/**
* Creates a raw terminal instance, this should not be used outside of the terminal part.
*/
getInstanceFromId(terminalId: number): ITerminalInstance | undefined;
getInstanceFromIndex(terminalIndex: number): ITerminalInstance;
getActiveOrCreateInstance(): Promise<ITerminalInstance>;
moveToEditor(source: ITerminalInstance): void;
moveToTerminalView(source?: ITerminalInstance | URI): Promise<void>;
getOffProcessTerminalService(): IOffProcessTerminalService | undefined;
/**
* Perform an action with the active terminal instance, if the terminal does
* not exist the callback will not be called.
* @param callback The callback that fires with the active terminal
*/
doWithActiveInstance<T>(callback: (terminal: ITerminalInstance) => T): T | void;
/**
* Fire the onActiveTabChanged event, this will trigger the terminal dropdown to be updated,
* among other things.
*/
refreshActiveGroup(): void;
registerProcessSupport(isSupported: boolean): void;
/**
* Registers a link provider that enables integrators to add links to the terminal.
* @param linkProvider When registered, the link provider is asked whenever a cell is hovered
* for links at that position. This lets the terminal know all links at a given area and also
* labels for what these links are going to do.
*/
registerLinkProvider(linkProvider: ITerminalExternalLinkProvider): IDisposable;
registerTerminalProfileProvider(extensionIdenfifier: string, id: string, profileProvider: ITerminalProfileProvider): IDisposable;
showProfileQuickPick(type: 'setDefault' | 'createInstance', cwd?: string | URI): Promise<ITerminalInstance | undefined>;
setContainers(panelContainer: HTMLElement, terminalContainer: HTMLElement): void;
requestStartExtensionTerminal(proxy: ITerminalProcessExtHostProxy, cols: number, rows: number): Promise<ITerminalLaunchError | undefined>;
isAttachedToTerminal(remoteTerm: IRemoteTerminalAttachTarget): boolean;
getEditableData(instance: ITerminalInstance): IEditableData | undefined;
setEditable(instance: ITerminalInstance, data: IEditableData | null): Promise<void>;
safeDisposeTerminal(instance: ITerminalInstance): Promise<void>;
getDefaultInstanceHost(): ITerminalInstanceHost;
getInstanceHost(target: ITerminalLocationOptions | undefined): ITerminalInstanceHost;
getFindHost(instance?: ITerminalInstance): ITerminalFindHost;
getDefaultProfileName(): string;
resolveLocation(location?: ITerminalLocationOptions): TerminalLocation | undefined
}
/**
* This service is responsible for integrating with the editor service and managing terminal
* editors.
*/
export interface ITerminalEditorService extends ITerminalInstanceHost, ITerminalFindHost {
readonly _serviceBrand: undefined;
/** Gets all _terminal editor_ instances. */
readonly instances: readonly ITerminalInstance[];
openEditor(instance: ITerminalInstance, editorOptions?: TerminalEditorLocation): Promise<void>;
detachActiveEditorInstance(): ITerminalInstance;
detachInstance(instance: ITerminalInstance): void;
splitInstance(instanceToSplit: ITerminalInstance, shellLaunchConfig?: IShellLaunchConfig): ITerminalInstance;
revealActiveEditor(preserveFocus?: boolean): void;
resolveResource(instance: ITerminalInstance | URI): URI;
reviveInput(deserializedInput: DeserializedTerminalEditorInput): TerminalEditorInput;
getInputFromResource(resource: URI): TerminalEditorInput;
}
export type ITerminalLocationOptions = TerminalLocation | TerminalEditorLocation | { parentTerminal: ITerminalInstance } | { splitActiveTerminal: boolean };
export interface ICreateTerminalOptions {
/**
* The shell launch config or profile to launch with, when not specified the default terminal
* profile will be used.
*/
config?: IShellLaunchConfig | ITerminalProfile | IExtensionTerminalProfile;
/**
* The current working directory to start with, this will override IShellLaunchConfig.cwd if
* specified.
*/
cwd?: string | URI;
/**
* The terminal's resource, passed when the terminal has moved windows.
*/
resource?: URI;
/**
* The terminal's location (editor or panel), it's terminal parent (split to the right), or editor group
*/
location?: ITerminalLocationOptions;
}
export interface TerminalEditorLocation {
viewColumn: EditorGroupColumn,
preserveFocus?: boolean
}
/**
* This service is responsible for managing terminal groups, that is the terminals that are hosted
* within the terminal panel, not in an editor.
*/
export interface ITerminalGroupService extends ITerminalInstanceHost, ITerminalFindHost {
readonly _serviceBrand: undefined;
/** Gets all _terminal view_ instances, ie. instances contained within terminal groups. */
readonly instances: readonly ITerminalInstance[];
readonly groups: readonly ITerminalGroup[];
activeGroup: ITerminalGroup | undefined;
readonly activeGroupIndex: number;
readonly onDidChangeActiveGroup: Event<ITerminalGroup | undefined>;
readonly onDidDisposeGroup: Event<ITerminalGroup>;
/** Fires when a group is created, disposed of, or shown (in the case of a background group). */
readonly onDidChangeGroups: Event<void>;
readonly onDidChangePanelOrientation: Event<Orientation>;
createGroup(shellLaunchConfig?: IShellLaunchConfig): ITerminalGroup;
createGroup(instance?: ITerminalInstance): ITerminalGroup;
getGroupForInstance(instance: ITerminalInstance): ITerminalGroup | undefined;
/**
* Moves a terminal instance's group to the target instance group's position.
* @param source The source instance to move.
* @param target The target instance to move the source instance to.
*/
moveGroup(source: ITerminalInstance, target: ITerminalInstance): void;
moveGroupToEnd(source: ITerminalInstance): void;
moveInstance(source: ITerminalInstance, target: ITerminalInstance, side: 'before' | 'after'): void;
unsplitInstance(instance: ITerminalInstance): void;
joinInstances(instances: ITerminalInstance[]): void;
instanceIsSplit(instance: ITerminalInstance): boolean;
getGroupLabels(): string[];
setActiveGroupByIndex(index: number): void;
setActiveGroupToNext(): void;
setActiveGroupToPrevious(): void;
setActiveInstanceByIndex(terminalIndex: number): void;
setContainer(container: HTMLElement): void;
showPanel(focus?: boolean): Promise<void>;
hidePanel(): void;
focusTabs(): void;
showTabs(): void;
}
/**
* An interface that indicates the implementer hosts terminal instances, exposing a common set of
* properties and events.
*/
export interface ITerminalInstanceHost {
readonly activeInstance: ITerminalInstance | undefined;
readonly instances: readonly ITerminalInstance[];
readonly onDidDisposeInstance: Event<ITerminalInstance>;
readonly onDidFocusInstance: Event<ITerminalInstance>;
readonly onDidChangeActiveInstance: Event<ITerminalInstance | undefined>;
readonly onDidChangeInstances: Event<void>;
setActiveInstance(instance: ITerminalInstance): void;
/**
* Gets an instance from a resource if it exists. This MUST be used instead of getInstanceFromId
* when you only know about a terminal's URI. (a URI's instance ID may not be this window's instance ID)
*/
getInstanceFromResource(resource: URI | undefined): ITerminalInstance | undefined;
}
export interface ITerminalFindHost {
focusFindWidget(): void;
hideFindWidget(): void;
getFindState(): FindReplaceState;
findNext(): void;
findPrevious(): void;
}
export interface IRemoteTerminalService extends IOffProcessTerminalService {
createProcess(
shellLaunchConfig: IShellLaunchConfig,
configuration: ICompleteTerminalConfiguration,
activeWorkspaceRootUri: URI | undefined,
cols: number,
rows: number,
unicodeVersion: '6' | '11',
shouldPersist: boolean
): Promise<ITerminalChildProcess>;
}
/**
* Similar to xterm.js' ILinkProvider but using promises and hides xterm.js internals (like buffer
* positions, decorations, etc.) from the rest of vscode. This is the interface to use for
* workbench integrations.
*/
export interface ITerminalExternalLinkProvider {
provideLinks(instance: ITerminalInstance, line: string): Promise<ITerminalLink[] | undefined>;
}
export interface ITerminalProfileProvider {
createContributedTerminalProfile(options: ICreateContributedTerminalProfileOptions): Promise<void>;
}
export interface ITerminalLink {
/** The startIndex of the link in the line. */
startIndex: number;
/** The length of the link in the line. */
length: number;
/** The descriptive label for what the link does when activated. */
label?: string;
/**
* Activates the link.
* @param text The text of the link.
*/
activate(text: string): void;
}
export interface ISearchOptions {
/** Whether the find should be done as a regex. */
regex?: boolean;
/** Whether only whole words should match. */
wholeWord?: boolean;
/** Whether find should pay attention to case. */
caseSensitive?: boolean;
/** Whether the search should start at the current search position (not the next row). */
incremental?: boolean;
}
export interface ITerminalBeforeHandleLinkEvent {
terminal?: ITerminalInstance;
/** The text of the link */
link: string;
/** Call with whether the link was handled by the interceptor */
resolve(wasHandled: boolean): void;
}
export interface ITerminalInstance {
/**
* The ID of the terminal instance, this is an arbitrary number only used to uniquely identify
* terminal instances within a window.
*/
readonly instanceId: number;
/**
* A unique URI for this terminal instance with the following encoding:
* path: /<workspace ID>/<instance ID>
* fragment: Title
* Note that when dragging terminals across windows, this will retain the original workspace ID /instance ID
* from the other window.
*/
readonly resource: URI;
readonly cols: number;
readonly rows: number;
readonly maxCols: number;
readonly maxRows: number;
readonly icon?: TerminalIcon;
readonly color?: string;
readonly statusList: ITerminalStatusList;
/**
* The process ID of the shell process, this is undefined when there is no process associated
* with this terminal.
*/
processId: number | undefined;
target?: TerminalLocation;
/**
* The id of a persistent process. This is defined if this is a terminal created by a pty host
* that supports reconnection.
*/
readonly persistentProcessId: number | undefined;
/**
* Whether the process should be persisted across reloads.
*/
readonly shouldPersist: boolean;
/**
* Whether the process communication channel has been disconnected.
*/
readonly isDisconnected: boolean;
/**
* Whether the terminal's pty is hosted on a remote.
*/
readonly isRemote: boolean;
/**
* Whether an element within this terminal is focused.
*/
readonly hasFocus: boolean;
/**
* An event that fires when the terminal instance's title changes.
*/
onTitleChanged: Event<ITerminalInstance>;
/**
* An event that fires when the terminal instance's icon changes.
*/
onIconChanged: Event<ITerminalInstance>;
/**
* An event that fires when the terminal instance is disposed.
*/
onDisposed: Event<ITerminalInstance>;
onProcessIdReady: Event<ITerminalInstance>;
onLinksReady: Event<ITerminalInstance>;
onRequestExtHostProcess: Event<ITerminalInstance>;
onDimensionsChanged: Event<void>;
onMaximumDimensionsChanged: Event<void>;
onDidChangeHasChildProcesses: Event<boolean>;
onDidFocus: Event<ITerminalInstance>;
onDidBlur: Event<ITerminalInstance>;
onDidInputData: Event<ITerminalInstance>;
/**
* An event that fires when a terminal is dropped on this instance via drag and drop.
*/
onRequestAddInstanceToGroup: Event<IRequestAddInstanceToGroupEvent>;
/**
* Attach a listener to the raw data stream coming from the pty, including ANSI escape
* sequences.
*/
onData: Event<string>;
/**
* Attach a listener to the binary data stream coming from xterm and going to pty
*/
onBinary: Event<string>;
/**
* Attach a listener to listen for new lines added to this terminal instance.
*
* @param listener The listener function which takes new line strings added to the terminal,
* excluding ANSI escape sequences. The line event will fire when an LF character is added to
* the terminal (ie. the line is not wrapped). Note that this means that the line data will
* not fire for the last line, until either the line is ended with a LF character of the process
* is exited. The lineData string will contain the fully wrapped line, not containing any LF/CR
* characters.
*/
onLineData: Event<string>;
/**
* Attach a listener that fires when the terminal's pty process exits. The number in the event
* is the processes' exit code, an exit code of null means the process was killed as a result of
* the ITerminalInstance being disposed.
*/
onExit: Event<number | undefined>;
readonly exitCode: number | undefined;
readonly areLinksReady: boolean;
/**
* Returns an array of data events that have fired within the first 10 seconds. If this is
* called 10 seconds after the terminal has existed the result will be undefined. This is useful
* when objects that depend on the data events have delayed initialization, like extension
* hosts.
*/
readonly initialDataEvents: string[] | undefined;
/** A promise that resolves when the terminal's pty/process have been created. */
readonly processReady: Promise<void>;
/** Whether the terminal's process has child processes (ie. is dirty/busy). */
readonly hasChildProcesses: boolean;
/**
* The title of the terminal. This is either title or the process currently running or an
* explicit name given to the terminal instance through the extension API.
*/
readonly title: string;
/**
* How the current title was set.
*/
readonly titleSource: TitleEventSource;
/**
* The shell type of the terminal.
*/
readonly shellType: TerminalShellType;
/**
* The focus state of the terminal before exiting.
*/
readonly hadFocusOnExit: boolean;
/**
* False when the title is set by an API or the user. We check this to make sure we
* do not override the title when the process title changes in the terminal.
*/
isTitleSetByProcess: boolean;
/**
* The shell launch config used to launch the shell.
*/
readonly shellLaunchConfig: IShellLaunchConfig;
/**
* Whether to disable layout for the terminal. This is useful when the size of the terminal is
* being manipulating (e.g. adding a split pane) and we want the terminal to ignore particular
* resize events.
*/
disableLayout: boolean;
/**
* An object that tracks when commands are run and enables navigating and selecting between
* them.
*/
readonly commandTracker: ICommandTracker | undefined;
readonly navigationMode: INavigationMode | undefined;
description: string | undefined;
/**
* Shows the environment information hover if the widget exists.
*/
showEnvironmentInfoHover(): void;
/**
* Dispose the terminal instance, removing it from the panel/service and freeing up resources.
*
* @param immediate Whether the kill should be immediate or not. Immediate should only be used
* when VS Code is shutting down or in cases where the terminal dispose was user initiated.
* The immediate===false exists to cover an edge case where the final output of the terminal can
* get cut off. If immediate kill any terminal processes immediately.
*/
dispose(immediate?: boolean): void;
/**
* Inform the process that the terminal is now detached.
*/
detachFromProcess(): Promise<void>;
/**
* Forces the terminal to redraw its viewport.
*/
forceRedraw(): void;
/**
* Check if anything is selected in terminal.
*/
hasSelection(): boolean;
/**
* Copies the terminal selection to the clipboard.
*/
copySelection(): Promise<void>;
/**
* Current selection in the terminal.
*/
readonly selection: string | undefined;
/**
* Clear current selection.
*/
clearSelection(): void;
/**
* Select all text in the terminal.
*/
selectAll(): void;
/**
* Find the next instance of the term
*/
findNext(term: string, searchOptions: ISearchOptions): boolean;
/**
* Find the previous instance of the term
*/
findPrevious(term: string, searchOptions: ISearchOptions): boolean;
/**
* Notifies the terminal that the find widget's focus state has been changed.
*/
notifyFindWidgetFocusChanged(isFocused: boolean): void;
/**
* Focuses the terminal instance if it's able to (xterm.js instance exists).
*
* @param focus Force focus even if there is a selection.
*/
focus(force?: boolean): void;
/**
* Focuses the terminal instance when it's ready (the xterm.js instance is created). Use this
* when the terminal is being shown.
*
* @param focus Force focus even if there is a selection.
*/
focusWhenReady(force?: boolean): Promise<void>;
/**
* Focuses and pastes the contents of the clipboard into the terminal instance.
*/
paste(): Promise<void>;
/**
* Focuses and pastes the contents of the selection clipboard into the terminal instance.
*/
pasteSelection(): Promise<void>;
/**
* Send text to the terminal instance. The text is written to the stdin of the underlying pty
* process (shell) of the terminal instance.
*
* @param text The text to send.
* @param addNewLine Whether to add a new line to the text being sent, this is normally
* required to run a command in the terminal. The character(s) added are \n or \r\n
* depending on the platform. This defaults to `true`.
*/
sendText(text: string, addNewLine: boolean): Promise<void>;
/** Scroll the terminal buffer down 1 line. */
scrollDownLine(): void;
/** Scroll the terminal buffer down 1 page. */
scrollDownPage(): void;
/** Scroll the terminal buffer to the bottom. */
scrollToBottom(): void;
/** Scroll the terminal buffer up 1 line. */
scrollUpLine(): void;
/** Scroll the terminal buffer up 1 page. */
scrollUpPage(): void;
/** Scroll the terminal buffer to the top. */
scrollToTop(): void;
/**
* Clears the terminal buffer, leaving only the prompt line.
*/
clear(): void;
/**
* Attaches the terminal instance to an element on the DOM, before this is called the terminal
* instance process may run in the background but cannot be displayed on the UI.
*
* @param container The element to attach the terminal instance to.
*/
attachToElement(container: HTMLElement): Promise<void> | void;
/**
* Detaches the terminal instance from the terminal editor DOM element.
*/
detachFromElement(): void;
/**
* Configure the dimensions of the terminal instance.
*
* @param dimension The dimensions of the container.
*/
layout(dimension: { width: number, height: number }): void;
/**
* Sets whether the terminal instance's element is visible in the DOM.
*
* @param visible Whether the element is visible.
*/
setVisible(visible: boolean): void;
/**
* Immediately kills the terminal's current pty process and launches a new one to replace it.
*
* @param shell The new launch configuration.
*/
reuseTerminal(shell: IShellLaunchConfig): Promise<void>;
/**
* Relaunches the terminal, killing it and reusing the launch config used initially. Any
* environment variable changes will be recalculated when this happens.
*/
relaunch(): void;
/**
* Sets the title of the terminal instance.
*/
setTitle(title: string, eventSource: TitleEventSource): void;
waitForTitle(): Promise<string>;
setDimensions(dimensions: ITerminalDimensions): void;
addDisposable(disposable: IDisposable): void;
toggleEscapeSequenceLogging(): void;
getInitialCwd(): Promise<string>;
getCwd(): Promise<string>;
/**
* @throws when called before xterm.js is ready.
*/
registerLinkProvider(provider: ITerminalExternalLinkProvider): IDisposable;
/**
* Sets the terminal name to the provided title or triggers a quick pick
* to take user input.
*/
rename(title?: string): Promise<void>;
/**
* Triggers a quick pick to change the icon of this terminal.
*/
changeIcon(): Promise<void>;
/**
* Triggers a quick pick to change the color of the associated terminal tab icon.
*/
changeColor(): Promise<void>;
}
export interface IRequestAddInstanceToGroupEvent {
uri: URI;
side: 'before' | 'after'
}
export const enum LinuxDistro {
Unknown = 1,
Fedora = 2,
Ubuntu = 3,
} | }
export const enum Direction {
Left = 0,
Right = 1, | random_line_split |
IConnection.d.ts | /*!
* Copyright Unlok, Vaughn Royko 2011-2019
* http://www.unlok.ca
*
* Credits & Thanks:
* http://www.unlok.ca/credits-thanks/
*
* Wayward is a copyrighted and licensed work. Modification and/or distribution of any source files is prohibited. If you wish to modify the game in any way, please refer to the modding guide:
* https://waywardgame.github.io/
*
*
*/
import { ConnectionState } from "Enums";
import { MatchmakingMessageData } from "multiplayer/matchmaking/IMatchmaking";
import { IPacket } from "multiplayer/packets/IPacket";
export interface IConnection {
playerIdentifier: string;
matchmakingIdentifier: string;
pid?: number;
/**
* Packets are queued while the player is connected.
* They are dequeued once the client loads the world - catch up logic
*/
queuedPackets: IPacket[];
buffer?: Uint8Array; | bufferOffset?: number;
bufferPacketId?: number;
lastPacketNumberSent?: number;
lastPacketNumberReceived?: number;
addConnectionTimeout(): void;
addKeepAliveTimeout(): void;
addTimeout(milliseconds: number, callback: () => void): void;
clearTimeout(): void;
close(): void;
getState(): ConnectionState;
isConnected(): boolean;
processMatchmakingMessage(message: ArrayBuffer | MatchmakingMessageData): Promise<boolean>;
queuePacketData(data: ArrayBuffer): void;
send(data: ArrayBuffer | Uint8Array): void;
setState(state: ConnectionState): void;
startKeepAlive(): void;
}
export interface IQueuedData {
data: ArrayBuffer;
byteOffset: number;
sendAfter: number | undefined;
retries?: number;
} | random_line_split | |
prime_field.rs | use normalize::*;
use pack::Pack;
use rand::Rand;
use std::marker::Sized;
use std::ops::Add;
use std::ops::AddAssign;
use std::ops::Div;
use std::ops::DivAssign;
use std::ops::Mul;
use std::ops::MulAssign;
use std::ops::Neg;
use std::ops::Sub;
use std::ops::SubAssign;
| Div<Self, Output = Self> + DivAssign<Self> +
MulAssign<i32> + MulAssign<i16> + MulAssign<i8> + MulAssign<Self> +
Mul<i32, Output = Self> + Mul<i16, Output = Self> +
Mul<i8, Output = Self> + Mul<Self, Output = Self> +
Neg<Output = Self> + Normalize + NormalizeEq + Pack + Rand + Sized +
SubAssign<i32> + SubAssign<i16> + SubAssign<i8> + SubAssign<Self> +
Sub<i32, Output = Self> + Sub<i16, Output = Self> +
Sub<i8, Output = Self> + Sub<Self, Output = Self> {
/// Get the number of bits in the number.
fn nbits() -> usize;
/// Get the bit given by idx. This normalizes the internal representation.
fn bit(&mut self, idx: usize) -> bool;
/// Get the bit given by idx, assuming the internal representation
/// is already normalized.
fn bit_normalized(&self, idx: usize) -> bool;
/// Set every bit of this number to the given bit.
fn fill(&mut self, bit: bool);
/// Generate a mask consisting entirely of the given bit.
fn filled(bit: bool) -> Self;
/// Normalize both arguments and bitwise-and assign.
fn normalize_bitand(&mut self, rhs: &mut Self);
/// Normalize self and bitwise-and assign.
fn normalize_self_bitand(&mut self, rhs: &Self);
/// Bitwise-and assign with both arguments normalized.
fn normalized_bitand(&mut self, rhs: &Self);
/// Normalize both arguments and bitwise-or assign.
fn normalize_bitor(&mut self, rhs: &mut Self);
/// Normalize self and bitwise-or assign.
fn normalize_self_bitor(&mut self, rhs: &Self);
/// Bitwise-or assign with both arguments normalized.
fn normalized_bitor(&mut self, rhs: &Self);
/// Get the representation of the value 0.
fn zero() -> Self;
/// Get the representation of the value 1.
fn one() -> Self;
/// Get the representation of the value -1.
fn m_one() -> Self;
/// Get the representation of the modulus.
fn modulus() -> Self;
/// In-place square.
fn square(&mut self);
/// Functional square.
fn squared(&self) -> Self;
/// In-place multiplicative inverse.
fn invert(&mut self);
/// Functional multiplicative inverse.
fn inverted(&self) -> Self;
/// Legendre symbol. This is 1 for a quadratic residue (meaning a
/// square root value exists), and -1 otherwise.
fn legendre(&self) -> Self;
/// Compute the square root. This has meaning only for quadratic
/// residue (legendre returns 1). Non-residues return a garbage
/// value.
fn sqrt(&self) -> Self;
/// Add a single digit (represented as an i32) in-place.
fn small_add_assign(&mut self, b: i32);
/// Add a single digit (represented as an i32).
fn small_add(&self, b: i32) -> Self;
/// Subtract a single digit (represented as an i32) in place.
fn small_sub_assign(&mut self, b: i32);
/// Subtract a single digit (represented as an i32).
fn small_sub(&self, b: i32) -> Self;
/// Multiply in-place by a single digit (represented as an i32).
fn small_mul_assign(&mut self, b: i32);
/// Multiply by a single digit (represented as an i32).
fn small_mul(&self, b: i32) -> Self;
}
/// Bitmasks corresponding to a PrimeField type. These are used as
/// arguments to bitwise and operations to retain or clear entire
/// PrimeField elements at once.
///
/// The primary use of this is to replace some branch operations with
/// bitwise tricks to eliminate data-dependent control-flow branches.
pub trait PrimeFieldMask {
/// Set every bit of this number to the given bit.
fn fill(&mut self, bit: bool);
/// Generate a mask consisting entirely of the given bit.
fn filled(bit: bool) -> Self;
} | /// Operations on prime fields.
pub trait PrimeField : Add<i32, Output = Self> + Add<i16, Output = Self> +
Add<i8, Output = Self> + Add<Self, Output = Self> +
AddAssign<i32> + AddAssign<i16> + AddAssign<i8> + AddAssign<Self> + | random_line_split |
sudokucsolver.js | self.importScripts('sudokuc.js');
const resultGrid = [];
let gridPtr = null;
const workingSeeds = [];
let workingSeedsHash = {};
function makeGridFromResult() {
for(let i=0, y=1; y<=9; y++) {
for(let x=1; x<=9; x++) |
}
return resultGrid;
}
function solveGrid(grid, Module) {
if (!gridPtr) {
return;
}
for(let i=0, y=1; y<=9; y++) {
for(let x=1; x<=9; x++) {
Module.HEAPU32[(gridPtr / Uint32Array.BYTES_PER_ELEMENT) + i] = grid[y][x];
i++;
}
}
let seed = Date.now();
let solved = Module.ccall('solveSudoku', 'bool', ['number', 'number'], [gridPtr, seed]);
if(solved) {
if(!workingSeedsHash[seed] && workingSeeds.length<30) {
workingSeedsHash[seed] = workingSeeds.length;
workingSeeds.push(seed);
}
} else if(workingSeeds.length) {
seed = workingSeeds[Math.floor(Math.random()*workingSeeds.length)];
solved = Module.ccall('solveSudoku', 'bool', ['number', 'number'], [gridPtr, seed]);
}
if(solved) {
return makeGridFromResult();
} else {
return grid;
}
}
function initialize() {
gridPtr = Module._malloc(9*9 * Uint32Array.BYTES_PER_ELEMENT);
for(let y=1;y<=9;y++) {
resultGrid[y] = [];
}
}
function destroy() {
Module._free(gridPtr);
}
if(typeof(Module)!=='undefined') {
Module.onRuntimeInitialized = initialize;
}
| {
resultGrid[y][x] = Module.HEAPU32[(gridPtr / Uint32Array.BYTES_PER_ELEMENT) + i];
i++;
} | conditional_block |
sudokucsolver.js | self.importScripts('sudokuc.js');
const resultGrid = [];
let gridPtr = null;
const workingSeeds = [];
let workingSeedsHash = {};
function makeGridFromResult() {
for(let i=0, y=1; y<=9; y++) {
for(let x=1; x<=9; x++) {
resultGrid[y][x] = Module.HEAPU32[(gridPtr / Uint32Array.BYTES_PER_ELEMENT) + i];
i++;
}
}
return resultGrid;
} | }
for(let i=0, y=1; y<=9; y++) {
for(let x=1; x<=9; x++) {
Module.HEAPU32[(gridPtr / Uint32Array.BYTES_PER_ELEMENT) + i] = grid[y][x];
i++;
}
}
let seed = Date.now();
let solved = Module.ccall('solveSudoku', 'bool', ['number', 'number'], [gridPtr, seed]);
if(solved) {
if(!workingSeedsHash[seed] && workingSeeds.length<30) {
workingSeedsHash[seed] = workingSeeds.length;
workingSeeds.push(seed);
}
} else if(workingSeeds.length) {
seed = workingSeeds[Math.floor(Math.random()*workingSeeds.length)];
solved = Module.ccall('solveSudoku', 'bool', ['number', 'number'], [gridPtr, seed]);
}
if(solved) {
return makeGridFromResult();
} else {
return grid;
}
}
function initialize() {
gridPtr = Module._malloc(9*9 * Uint32Array.BYTES_PER_ELEMENT);
for(let y=1;y<=9;y++) {
resultGrid[y] = [];
}
}
function destroy() {
Module._free(gridPtr);
}
if(typeof(Module)!=='undefined') {
Module.onRuntimeInitialized = initialize;
} |
function solveGrid(grid, Module) {
if (!gridPtr) {
return; | random_line_split |
sudokucsolver.js | self.importScripts('sudokuc.js');
const resultGrid = [];
let gridPtr = null;
const workingSeeds = [];
let workingSeedsHash = {};
function makeGridFromResult() {
for(let i=0, y=1; y<=9; y++) {
for(let x=1; x<=9; x++) {
resultGrid[y][x] = Module.HEAPU32[(gridPtr / Uint32Array.BYTES_PER_ELEMENT) + i];
i++;
}
}
return resultGrid;
}
function solveGrid(grid, Module) {
if (!gridPtr) {
return;
}
for(let i=0, y=1; y<=9; y++) {
for(let x=1; x<=9; x++) {
Module.HEAPU32[(gridPtr / Uint32Array.BYTES_PER_ELEMENT) + i] = grid[y][x];
i++;
}
}
let seed = Date.now();
let solved = Module.ccall('solveSudoku', 'bool', ['number', 'number'], [gridPtr, seed]);
if(solved) {
if(!workingSeedsHash[seed] && workingSeeds.length<30) {
workingSeedsHash[seed] = workingSeeds.length;
workingSeeds.push(seed);
}
} else if(workingSeeds.length) {
seed = workingSeeds[Math.floor(Math.random()*workingSeeds.length)];
solved = Module.ccall('solveSudoku', 'bool', ['number', 'number'], [gridPtr, seed]);
}
if(solved) {
return makeGridFromResult();
} else {
return grid;
}
}
function initialize() {
gridPtr = Module._malloc(9*9 * Uint32Array.BYTES_PER_ELEMENT);
for(let y=1;y<=9;y++) {
resultGrid[y] = [];
}
}
function destroy() |
if(typeof(Module)!=='undefined') {
Module.onRuntimeInitialized = initialize;
}
| {
Module._free(gridPtr);
} | identifier_body |
sudokucsolver.js | self.importScripts('sudokuc.js');
const resultGrid = [];
let gridPtr = null;
const workingSeeds = [];
let workingSeedsHash = {};
function makeGridFromResult() {
for(let i=0, y=1; y<=9; y++) {
for(let x=1; x<=9; x++) {
resultGrid[y][x] = Module.HEAPU32[(gridPtr / Uint32Array.BYTES_PER_ELEMENT) + i];
i++;
}
}
return resultGrid;
}
function | (grid, Module) {
if (!gridPtr) {
return;
}
for(let i=0, y=1; y<=9; y++) {
for(let x=1; x<=9; x++) {
Module.HEAPU32[(gridPtr / Uint32Array.BYTES_PER_ELEMENT) + i] = grid[y][x];
i++;
}
}
let seed = Date.now();
let solved = Module.ccall('solveSudoku', 'bool', ['number', 'number'], [gridPtr, seed]);
if(solved) {
if(!workingSeedsHash[seed] && workingSeeds.length<30) {
workingSeedsHash[seed] = workingSeeds.length;
workingSeeds.push(seed);
}
} else if(workingSeeds.length) {
seed = workingSeeds[Math.floor(Math.random()*workingSeeds.length)];
solved = Module.ccall('solveSudoku', 'bool', ['number', 'number'], [gridPtr, seed]);
}
if(solved) {
return makeGridFromResult();
} else {
return grid;
}
}
function initialize() {
gridPtr = Module._malloc(9*9 * Uint32Array.BYTES_PER_ELEMENT);
for(let y=1;y<=9;y++) {
resultGrid[y] = [];
}
}
function destroy() {
Module._free(gridPtr);
}
if(typeof(Module)!=='undefined') {
Module.onRuntimeInitialized = initialize;
}
| solveGrid | identifier_name |
lib.rs | //! D-Bus bindings for Rust
//!
//! [D-Bus](http://dbus.freedesktop.org/) is a message bus, and is mainly used in Linux
//! for communication between processes. It is present by default on almost every
//! Linux distribution out there, and runs in two instances - one per session, and one
//! system-wide.
//!
//! See the examples directory for some examples to get you started.
extern crate libc;
pub use ffi::DBusBusType as BusType;
pub use ffi::DBusNameFlag as NameFlag;
pub use ffi::DBusRequestNameReply as RequestNameReply;
pub use ffi::DBusReleaseNameReply as ReleaseNameReply;
pub use ffi::DBusMessageType as MessageType;
pub use message::{Message, MessageItem, FromMessageItem, OwnedFd, OPath, ArrayError};
pub use prop::PropHandler;
pub use prop::Props;
/// A TypeSig describes the type of a MessageItem.
pub type TypeSig<'a> = std::borrow::Cow<'a, str>;
use std::ffi::{CString, CStr};
use std::ptr::{self};
use std::collections::LinkedList;
use std::cell::{Cell, RefCell};
mod ffi;
mod message;
mod prop;
mod objpath;
/// Contains functionality for the "server" of a D-Bus object. A remote application can
/// introspect this object and call methods on it.
pub mod obj {
pub use objpath::{ObjectPath, Interface, Property, Signal, Argument};
pub use objpath::{Method, MethodHandler, MethodResult};
pub use objpath::{PropertyROHandler, PropertyRWHandler, PropertyWOHandler, PropertyGetResult, PropertySetResult};
}
static INITDBUS: std::sync::Once = std::sync::ONCE_INIT;
fn init_dbus() {
INITDBUS.call_once(|| {
if unsafe { ffi::dbus_threads_init_default() } == 0 {
panic!("Out of memory when trying to initialize D-Bus library!");
}
});
}
/// D-Bus Error wrapper
pub struct Error {
e: ffi::DBusError,
}
unsafe impl Send for Error {}
fn c_str_to_slice(c: & *const libc::c_char) -> Option<&str> {
if *c == ptr::null() { None }
else { std::str::from_utf8( unsafe { CStr::from_ptr(*c).to_bytes() }).ok() }
}
fn to_c_str(n: &str) -> CString { CString::new(n.as_bytes()).unwrap() }
impl Error {
pub fn new_custom(name: &str, message: &str) -> Error {
let n = to_c_str(name);
let m = to_c_str(&message.replace("%","%%"));
let mut e = Error::empty();
unsafe { ffi::dbus_set_error(e.get_mut(), n.as_ptr(), m.as_ptr()) };
e
}
fn empty() -> Error {
init_dbus();
let mut e = ffi::DBusError {
name: ptr::null(),
message: ptr::null(),
dummy: 0,
padding1: ptr::null()
};
unsafe { ffi::dbus_error_init(&mut e); }
Error{ e: e }
}
/// Error name/type, e g 'org.freedesktop.DBus.Error.Failed'
pub fn name(&self) -> Option<&str> {
c_str_to_slice(&self.e.name)
}
/// Custom message, e g 'Could not find a matching object path'
pub fn message(&self) -> Option<&str> {
c_str_to_slice(&self.e.message)
}
fn get_mut(&mut self) -> &mut ffi::DBusError { &mut self.e }
}
impl Drop for Error {
fn drop(&mut self) {
unsafe { ffi::dbus_error_free(&mut self.e); }
}
}
impl std::fmt::Debug for Error {
fn fmt(&self, f: &mut std::fmt::Formatter) -> Result<(), std::fmt::Error> {
write!(f, "D-Bus error: {} ({})", self.message().unwrap_or(""),
self.name().unwrap_or(""))
}
}
impl std::error::Error for Error {
fn description(&self) -> &str { "D-Bus error" }
}
impl std::fmt::Display for Error {
fn fmt(&self, f: &mut std::fmt::Formatter) -> Result<(),std::fmt::Error> {
if let Some(x) = self.message() {
write!(f, "{:?}", x.to_string())
} else { Ok(()) }
}
}
/// When listening for incoming events on the D-Bus, this enum will tell you what type
/// of incoming event has happened.
#[derive(Debug)]
pub enum ConnectionItem {
Nothing,
MethodCall(Message),
Signal(Message),
}
/// ConnectionItem iterator
pub struct ConnectionItems<'a> {
c: &'a Connection,
timeout_ms: i32,
}
impl<'a> Iterator for ConnectionItems<'a> {
type Item = ConnectionItem;
fn next(&mut self) -> Option<ConnectionItem> {
loop {
let i = self.c.i.pending_items.borrow_mut().pop_front();
if i.is_some() { return i; }
let r = unsafe { ffi::dbus_connection_read_write_dispatch(self.c.conn(), self.timeout_ms as libc::c_int) };
if !self.c.i.pending_items.borrow().is_empty() { continue };
if r == 0 { return None; }
return Some(ConnectionItem::Nothing);
}
}
}
/* Since we register callbacks with userdata pointers,
we need to make sure the connection pointer does not move around.
Hence this extra indirection. */
struct IConnection {
conn: Cell<*mut ffi::DBusConnection>,
pending_items: RefCell<LinkedList<ConnectionItem>>,
}
/// A D-Bus connection. Start here if you want to get on the D-Bus!
pub struct Connection {
i: Box<IConnection>,
}
extern "C" fn filter_message_cb(conn: *mut ffi::DBusConnection, msg: *mut ffi::DBusMessage,
user_data: *mut libc::c_void) -> ffi::DBusHandlerResult {
let m = message::message_from_ptr(msg, true);
let i: &IConnection = unsafe { std::mem::transmute(user_data) };
assert!(i.conn.get() == conn);
let mtype: ffi::DBusMessageType = unsafe { std::mem::transmute(ffi::dbus_message_get_type(msg)) };
let r = match mtype {
ffi::DBusMessageType::Signal => {
i.pending_items.borrow_mut().push_back(ConnectionItem::Signal(m));
ffi::DBusHandlerResult::Handled
}
_ => ffi::DBusHandlerResult::NotYetHandled,
};
r
}
extern "C" fn object_path_message_cb(conn: *mut ffi::DBusConnection, msg: *mut ffi::DBusMessage,
user_data: *mut libc::c_void) -> ffi::DBusHandlerResult {
let m = message::message_from_ptr(msg, true);
let i: &IConnection = unsafe { std::mem::transmute(user_data) };
assert!(i.conn.get() == conn);
i.pending_items.borrow_mut().push_back(ConnectionItem::MethodCall(m));
ffi::DBusHandlerResult::Handled
}
impl Connection {
#[inline(always)]
fn conn(&self) -> *mut ffi::DBusConnection {
self.i.conn.get()
}
/// Creates a new D-Bus connection.
pub fn get_private(bus: BusType) -> Result<Connection, Error> {
let mut e = Error::empty();
let conn = unsafe { ffi::dbus_bus_get_private(bus, e.get_mut()) };
if conn == ptr::null_mut() {
return Err(e)
}
let c = Connection { i: Box::new(IConnection { conn: Cell::new(conn), pending_items: RefCell::new(LinkedList::new()) })};
/* No, we don't want our app to suddenly quit if dbus goes down */
unsafe { ffi::dbus_connection_set_exit_on_disconnect(conn, 0) };
assert!(unsafe {
ffi::dbus_connection_add_filter(c.conn(), Some(filter_message_cb as ffi::DBusCallback), std::mem::transmute(&*c.i), None)
} != 0);
Ok(c)
}
/// Sends a message over the D-Bus and waits for a reply.
/// This is usually used for method calls.
pub fn send_with_reply_and_block(&self, msg: Message, timeout_ms: i32) -> Result<Message, Error> {
let mut e = Error::empty();
let response = unsafe {
ffi::dbus_connection_send_with_reply_and_block(self.conn(), message::get_message_ptr(&msg),
timeout_ms as libc::c_int, e.get_mut())
};
if response == ptr::null_mut() {
return Err(e);
}
Ok(message::message_from_ptr(response, false))
}
/// Sends a message over the D-Bus without waiting. Useful for sending signals and method call replies.
pub fn send(&self, msg: Message) -> Result<u32,()> {
let mut serial = 0u32;
let r = unsafe { ffi::dbus_connection_send(self.conn(), message::get_message_ptr(&msg), &mut serial) };
if r == 0 { return Err(()); }
unsafe { ffi::dbus_connection_flush(self.conn()) };
Ok(serial)
}
pub fn unique_name(&self) -> String {
let c = unsafe { ffi::dbus_bus_get_unique_name(self.conn()) };
c_str_to_slice(&c).unwrap_or("").to_string()
}
// Check if there are new incoming events
pub fn iter(&self, timeout_ms: i32) -> ConnectionItems {
ConnectionItems {
c: self,
timeout_ms: timeout_ms,
}
}
pub fn register_object_path(&self, path: &str) -> Result<(), Error> {
let mut e = Error::empty();
let p = to_c_str(path);
let vtable = ffi::DBusObjectPathVTable {
unregister_function: None,
message_function: Some(object_path_message_cb as ffi::DBusCallback),
dbus_internal_pad1: None,
dbus_internal_pad2: None,
dbus_internal_pad3: None,
dbus_internal_pad4: None,
};
let r = unsafe {
let user_data: *mut libc::c_void = std::mem::transmute(&*self.i);
ffi::dbus_connection_try_register_object_path(self.conn(), p.as_ptr(), &vtable, user_data, e.get_mut())
};
if r == 0 { Err(e) } else { Ok(()) }
}
pub fn unregister_object_path(&self, path: &str) {
let p = to_c_str(path);
let r = unsafe { ffi::dbus_connection_unregister_object_path(self.conn(), p.as_ptr()) };
if r == 0 { panic!("Out of memory"); }
}
pub fn list_registered_object_paths(&self, path: &str) -> Vec<String> {
let p = to_c_str(path);
let mut clist: *mut *mut libc::c_char = ptr::null_mut();
let r = unsafe { ffi::dbus_connection_list_registered(self.conn(), p.as_ptr(), &mut clist) };
if r == 0 |
let mut v = Vec::new();
let mut i = 0;
loop {
let s = unsafe {
let citer = clist.offset(i);
if *citer == ptr::null_mut() { break };
std::mem::transmute(citer)
};
v.push(format!("{}", c_str_to_slice(s).unwrap()));
i += 1;
}
unsafe { ffi::dbus_free_string_array(clist) };
v
}
pub fn register_name(&self, name: &str, flags: u32) -> Result<RequestNameReply, Error> {
let mut e = Error::empty();
let n = to_c_str(name);
let r = unsafe { ffi::dbus_bus_request_name(self.conn(), n.as_ptr(), flags, e.get_mut()) };
if r == -1 { Err(e) } else { Ok(unsafe { std::mem::transmute(r) }) }
}
pub fn release_name(&self, name: &str) -> Result<ReleaseNameReply, Error> {
let mut e = Error::empty();
let n = to_c_str(name);
let r = unsafe { ffi::dbus_bus_release_name(self.conn(), n.as_ptr(), e.get_mut()) };
if r == -1 { Err(e) } else { Ok(unsafe { std::mem::transmute(r) }) }
}
pub fn add_match(&self, rule: &str) -> Result<(), Error> {
let mut e = Error::empty();
let n = to_c_str(rule);
unsafe { ffi::dbus_bus_add_match(self.conn(), n.as_ptr(), e.get_mut()) };
if e.name().is_some() { Err(e) } else { Ok(()) }
}
pub fn remove_match(&self, rule: &str) -> Result<(), Error> {
let mut e = Error::empty();
let n = to_c_str(rule);
unsafe { ffi::dbus_bus_remove_match(self.conn(), n.as_ptr(), e.get_mut()) };
if e.name().is_some() { Err(e) } else { Ok(()) }
}
}
impl Drop for Connection {
fn drop(&mut self) {
unsafe {
ffi::dbus_connection_close(self.conn());
ffi::dbus_connection_unref(self.conn());
}
}
}
impl std::fmt::Debug for Connection {
fn fmt(&self, f: &mut std::fmt::Formatter) -> Result<(), std::fmt::Error> {
write!(f, "D-Bus Connection({})", self.unique_name())
}
}
#[cfg(test)]
mod test {
use super::{Connection, Message, BusType, MessageItem, ConnectionItem, NameFlag,
RequestNameReply, ReleaseNameReply};
#[test]
fn connection() {
let c = Connection::get_private(BusType::Session).unwrap();
let n = c.unique_name();
assert!(n.starts_with(":1."));
println!("Connected to DBus, unique name: {}", n);
}
#[test]
fn invalid_message() {
let c = Connection::get_private(BusType::Session).unwrap();
let m = Message::new_method_call("foo.bar", "/", "foo.bar", "FooBar").unwrap();
let e = c.send_with_reply_and_block(m, 2000).err().unwrap();
assert!(e.name().unwrap() == "org.freedesktop.DBus.Error.ServiceUnknown");
}
#[test]
fn message_listnames() {
let c = Connection::get_private(BusType::Session).unwrap();
let m = Message::new_method_call("org.freedesktop.DBus", "/", "org.freedesktop.DBus", "ListNames").unwrap();
let r = c.send_with_reply_and_block(m, 2000).unwrap();
let reply = r.get_items();
println!("{:?}", reply);
}
#[test]
fn message_namehasowner() {
let c = Connection::get_private(BusType::Session).unwrap();
let mut m = Message::new_method_call("org.freedesktop.DBus", "/", "org.freedesktop.DBus", "NameHasOwner").unwrap();
m.append_items(&[MessageItem::Str("org.freedesktop.DBus".to_string())]);
let r = c.send_with_reply_and_block(m, 2000).unwrap();
let reply = r.get_items();
println!("{:?}", reply);
assert_eq!(reply, vec!(MessageItem::Bool(true)));
}
#[test]
fn object_path() {
use std::sync::mpsc;
let (tx, rx) = mpsc::channel();
let thread = ::std::thread::spawn(move || {
let c = Connection::get_private(BusType::Session).unwrap();
c.register_object_path("/hello").unwrap();
// println!("Waiting...");
tx.send(c.unique_name()).unwrap();
for n in c.iter(1000) {
// println!("Found message... ({})", n);
match n {
ConnectionItem::MethodCall(ref m) => {
let reply = Message::new_method_return(m).unwrap();
c.send(reply).unwrap();
break;
}
_ => {}
}
}
c.unregister_object_path("/hello");
});
let c = Connection::get_private(BusType::Session).unwrap();
let n = rx.recv().unwrap();
let m = Message::new_method_call(&n, "/hello", "com.example.hello", "Hello").unwrap();
println!("Sending...");
let r = c.send_with_reply_and_block(m, 8000).unwrap();
let reply = r.get_items();
println!("{:?}", reply);
thread.join().unwrap();
}
#[test]
fn register_name() {
let c = Connection::get_private(BusType::Session).unwrap();
let n = format!("com.example.hello.test.register_name");
assert_eq!(c.register_name(&n, NameFlag::ReplaceExisting as u32).unwrap(), RequestNameReply::PrimaryOwner);
assert_eq!(c.release_name(&n).unwrap(), ReleaseNameReply::Released);
}
#[test]
fn signal() {
let c = Connection::get_private(BusType::Session).unwrap();
let iface = "com.example.signaltest";
let mstr = format!("interface='{}',member='ThisIsASignal'", iface);
c.add_match(&mstr).unwrap();
let m = Message::new_signal("/mysignal", iface, "ThisIsASignal").unwrap();
let uname = c.unique_name();
c.send(m).unwrap();
for n in c.iter(1000) {
match n {
ConnectionItem::Signal(s) => {
let (_, p, i, m) = s.headers();
match (&*p.unwrap(), &*i.unwrap(), &*m.unwrap()) {
("/mysignal", "com.example.signaltest", "ThisIsASignal") => {
assert_eq!(s.sender().unwrap(), uname);
break;
},
(_, _, _) => println!("Other signal: {:?}", s.headers()),
}
}
_ => {},
}
}
c.remove_match(&mstr).unwrap();
}
}
| { panic!("Out of memory"); } | conditional_block |
lib.rs | //! D-Bus bindings for Rust
//!
//! [D-Bus](http://dbus.freedesktop.org/) is a message bus, and is mainly used in Linux
//! for communication between processes. It is present by default on almost every
//! Linux distribution out there, and runs in two instances - one per session, and one
//! system-wide.
//!
//! See the examples directory for some examples to get you started.
extern crate libc;
pub use ffi::DBusBusType as BusType;
pub use ffi::DBusNameFlag as NameFlag;
pub use ffi::DBusRequestNameReply as RequestNameReply;
pub use ffi::DBusReleaseNameReply as ReleaseNameReply;
pub use ffi::DBusMessageType as MessageType;
pub use message::{Message, MessageItem, FromMessageItem, OwnedFd, OPath, ArrayError};
pub use prop::PropHandler;
pub use prop::Props;
/// A TypeSig describes the type of a MessageItem.
pub type TypeSig<'a> = std::borrow::Cow<'a, str>;
use std::ffi::{CString, CStr};
use std::ptr::{self};
use std::collections::LinkedList;
use std::cell::{Cell, RefCell};
mod ffi;
mod message;
mod prop;
mod objpath;
/// Contains functionality for the "server" of a D-Bus object. A remote application can
/// introspect this object and call methods on it.
pub mod obj {
pub use objpath::{ObjectPath, Interface, Property, Signal, Argument};
pub use objpath::{Method, MethodHandler, MethodResult};
pub use objpath::{PropertyROHandler, PropertyRWHandler, PropertyWOHandler, PropertyGetResult, PropertySetResult};
}
static INITDBUS: std::sync::Once = std::sync::ONCE_INIT;
fn init_dbus() {
INITDBUS.call_once(|| {
if unsafe { ffi::dbus_threads_init_default() } == 0 {
panic!("Out of memory when trying to initialize D-Bus library!");
}
});
}
/// D-Bus Error wrapper
pub struct Error {
e: ffi::DBusError,
}
unsafe impl Send for Error {}
fn c_str_to_slice(c: & *const libc::c_char) -> Option<&str> {
if *c == ptr::null() { None }
else { std::str::from_utf8( unsafe { CStr::from_ptr(*c).to_bytes() }).ok() }
}
fn to_c_str(n: &str) -> CString { CString::new(n.as_bytes()).unwrap() }
impl Error {
pub fn new_custom(name: &str, message: &str) -> Error {
let n = to_c_str(name);
let m = to_c_str(&message.replace("%","%%"));
let mut e = Error::empty();
unsafe { ffi::dbus_set_error(e.get_mut(), n.as_ptr(), m.as_ptr()) };
e
}
fn empty() -> Error {
init_dbus();
let mut e = ffi::DBusError {
name: ptr::null(),
message: ptr::null(),
dummy: 0,
padding1: ptr::null()
};
unsafe { ffi::dbus_error_init(&mut e); }
Error{ e: e }
}
/// Error name/type, e g 'org.freedesktop.DBus.Error.Failed'
pub fn name(&self) -> Option<&str> {
c_str_to_slice(&self.e.name)
}
/// Custom message, e g 'Could not find a matching object path'
pub fn message(&self) -> Option<&str> {
c_str_to_slice(&self.e.message)
}
fn get_mut(&mut self) -> &mut ffi::DBusError { &mut self.e }
}
impl Drop for Error {
fn drop(&mut self) {
unsafe { ffi::dbus_error_free(&mut self.e); }
}
}
impl std::fmt::Debug for Error {
fn fmt(&self, f: &mut std::fmt::Formatter) -> Result<(), std::fmt::Error> {
write!(f, "D-Bus error: {} ({})", self.message().unwrap_or(""),
self.name().unwrap_or(""))
}
}
impl std::error::Error for Error {
fn description(&self) -> &str { "D-Bus error" }
}
impl std::fmt::Display for Error {
fn fmt(&self, f: &mut std::fmt::Formatter) -> Result<(),std::fmt::Error> {
if let Some(x) = self.message() {
write!(f, "{:?}", x.to_string())
} else { Ok(()) }
}
}
/// When listening for incoming events on the D-Bus, this enum will tell you what type
/// of incoming event has happened.
#[derive(Debug)]
pub enum ConnectionItem {
Nothing,
MethodCall(Message),
Signal(Message),
}
/// ConnectionItem iterator
pub struct ConnectionItems<'a> {
c: &'a Connection,
timeout_ms: i32,
}
impl<'a> Iterator for ConnectionItems<'a> {
type Item = ConnectionItem;
fn next(&mut self) -> Option<ConnectionItem> {
loop {
let i = self.c.i.pending_items.borrow_mut().pop_front();
if i.is_some() { return i; }
let r = unsafe { ffi::dbus_connection_read_write_dispatch(self.c.conn(), self.timeout_ms as libc::c_int) };
if !self.c.i.pending_items.borrow().is_empty() { continue };
if r == 0 { return None; }
return Some(ConnectionItem::Nothing);
}
}
}
/* Since we register callbacks with userdata pointers,
we need to make sure the connection pointer does not move around.
Hence this extra indirection. */
struct | {
conn: Cell<*mut ffi::DBusConnection>,
pending_items: RefCell<LinkedList<ConnectionItem>>,
}
/// A D-Bus connection. Start here if you want to get on the D-Bus!
pub struct Connection {
i: Box<IConnection>,
}
extern "C" fn filter_message_cb(conn: *mut ffi::DBusConnection, msg: *mut ffi::DBusMessage,
user_data: *mut libc::c_void) -> ffi::DBusHandlerResult {
let m = message::message_from_ptr(msg, true);
let i: &IConnection = unsafe { std::mem::transmute(user_data) };
assert!(i.conn.get() == conn);
let mtype: ffi::DBusMessageType = unsafe { std::mem::transmute(ffi::dbus_message_get_type(msg)) };
let r = match mtype {
ffi::DBusMessageType::Signal => {
i.pending_items.borrow_mut().push_back(ConnectionItem::Signal(m));
ffi::DBusHandlerResult::Handled
}
_ => ffi::DBusHandlerResult::NotYetHandled,
};
r
}
extern "C" fn object_path_message_cb(conn: *mut ffi::DBusConnection, msg: *mut ffi::DBusMessage,
user_data: *mut libc::c_void) -> ffi::DBusHandlerResult {
let m = message::message_from_ptr(msg, true);
let i: &IConnection = unsafe { std::mem::transmute(user_data) };
assert!(i.conn.get() == conn);
i.pending_items.borrow_mut().push_back(ConnectionItem::MethodCall(m));
ffi::DBusHandlerResult::Handled
}
impl Connection {
#[inline(always)]
fn conn(&self) -> *mut ffi::DBusConnection {
self.i.conn.get()
}
/// Creates a new D-Bus connection.
pub fn get_private(bus: BusType) -> Result<Connection, Error> {
let mut e = Error::empty();
let conn = unsafe { ffi::dbus_bus_get_private(bus, e.get_mut()) };
if conn == ptr::null_mut() {
return Err(e)
}
let c = Connection { i: Box::new(IConnection { conn: Cell::new(conn), pending_items: RefCell::new(LinkedList::new()) })};
/* No, we don't want our app to suddenly quit if dbus goes down */
unsafe { ffi::dbus_connection_set_exit_on_disconnect(conn, 0) };
assert!(unsafe {
ffi::dbus_connection_add_filter(c.conn(), Some(filter_message_cb as ffi::DBusCallback), std::mem::transmute(&*c.i), None)
} != 0);
Ok(c)
}
/// Sends a message over the D-Bus and waits for a reply.
/// This is usually used for method calls.
pub fn send_with_reply_and_block(&self, msg: Message, timeout_ms: i32) -> Result<Message, Error> {
let mut e = Error::empty();
let response = unsafe {
ffi::dbus_connection_send_with_reply_and_block(self.conn(), message::get_message_ptr(&msg),
timeout_ms as libc::c_int, e.get_mut())
};
if response == ptr::null_mut() {
return Err(e);
}
Ok(message::message_from_ptr(response, false))
}
/// Sends a message over the D-Bus without waiting. Useful for sending signals and method call replies.
pub fn send(&self, msg: Message) -> Result<u32,()> {
let mut serial = 0u32;
let r = unsafe { ffi::dbus_connection_send(self.conn(), message::get_message_ptr(&msg), &mut serial) };
if r == 0 { return Err(()); }
unsafe { ffi::dbus_connection_flush(self.conn()) };
Ok(serial)
}
pub fn unique_name(&self) -> String {
let c = unsafe { ffi::dbus_bus_get_unique_name(self.conn()) };
c_str_to_slice(&c).unwrap_or("").to_string()
}
// Check if there are new incoming events
pub fn iter(&self, timeout_ms: i32) -> ConnectionItems {
ConnectionItems {
c: self,
timeout_ms: timeout_ms,
}
}
pub fn register_object_path(&self, path: &str) -> Result<(), Error> {
let mut e = Error::empty();
let p = to_c_str(path);
let vtable = ffi::DBusObjectPathVTable {
unregister_function: None,
message_function: Some(object_path_message_cb as ffi::DBusCallback),
dbus_internal_pad1: None,
dbus_internal_pad2: None,
dbus_internal_pad3: None,
dbus_internal_pad4: None,
};
let r = unsafe {
let user_data: *mut libc::c_void = std::mem::transmute(&*self.i);
ffi::dbus_connection_try_register_object_path(self.conn(), p.as_ptr(), &vtable, user_data, e.get_mut())
};
if r == 0 { Err(e) } else { Ok(()) }
}
pub fn unregister_object_path(&self, path: &str) {
let p = to_c_str(path);
let r = unsafe { ffi::dbus_connection_unregister_object_path(self.conn(), p.as_ptr()) };
if r == 0 { panic!("Out of memory"); }
}
pub fn list_registered_object_paths(&self, path: &str) -> Vec<String> {
let p = to_c_str(path);
let mut clist: *mut *mut libc::c_char = ptr::null_mut();
let r = unsafe { ffi::dbus_connection_list_registered(self.conn(), p.as_ptr(), &mut clist) };
if r == 0 { panic!("Out of memory"); }
let mut v = Vec::new();
let mut i = 0;
loop {
let s = unsafe {
let citer = clist.offset(i);
if *citer == ptr::null_mut() { break };
std::mem::transmute(citer)
};
v.push(format!("{}", c_str_to_slice(s).unwrap()));
i += 1;
}
unsafe { ffi::dbus_free_string_array(clist) };
v
}
pub fn register_name(&self, name: &str, flags: u32) -> Result<RequestNameReply, Error> {
let mut e = Error::empty();
let n = to_c_str(name);
let r = unsafe { ffi::dbus_bus_request_name(self.conn(), n.as_ptr(), flags, e.get_mut()) };
if r == -1 { Err(e) } else { Ok(unsafe { std::mem::transmute(r) }) }
}
pub fn release_name(&self, name: &str) -> Result<ReleaseNameReply, Error> {
let mut e = Error::empty();
let n = to_c_str(name);
let r = unsafe { ffi::dbus_bus_release_name(self.conn(), n.as_ptr(), e.get_mut()) };
if r == -1 { Err(e) } else { Ok(unsafe { std::mem::transmute(r) }) }
}
pub fn add_match(&self, rule: &str) -> Result<(), Error> {
let mut e = Error::empty();
let n = to_c_str(rule);
unsafe { ffi::dbus_bus_add_match(self.conn(), n.as_ptr(), e.get_mut()) };
if e.name().is_some() { Err(e) } else { Ok(()) }
}
pub fn remove_match(&self, rule: &str) -> Result<(), Error> {
let mut e = Error::empty();
let n = to_c_str(rule);
unsafe { ffi::dbus_bus_remove_match(self.conn(), n.as_ptr(), e.get_mut()) };
if e.name().is_some() { Err(e) } else { Ok(()) }
}
}
impl Drop for Connection {
fn drop(&mut self) {
unsafe {
ffi::dbus_connection_close(self.conn());
ffi::dbus_connection_unref(self.conn());
}
}
}
impl std::fmt::Debug for Connection {
fn fmt(&self, f: &mut std::fmt::Formatter) -> Result<(), std::fmt::Error> {
write!(f, "D-Bus Connection({})", self.unique_name())
}
}
#[cfg(test)]
mod test {
use super::{Connection, Message, BusType, MessageItem, ConnectionItem, NameFlag,
RequestNameReply, ReleaseNameReply};
#[test]
fn connection() {
let c = Connection::get_private(BusType::Session).unwrap();
let n = c.unique_name();
assert!(n.starts_with(":1."));
println!("Connected to DBus, unique name: {}", n);
}
#[test]
fn invalid_message() {
let c = Connection::get_private(BusType::Session).unwrap();
let m = Message::new_method_call("foo.bar", "/", "foo.bar", "FooBar").unwrap();
let e = c.send_with_reply_and_block(m, 2000).err().unwrap();
assert!(e.name().unwrap() == "org.freedesktop.DBus.Error.ServiceUnknown");
}
#[test]
fn message_listnames() {
let c = Connection::get_private(BusType::Session).unwrap();
let m = Message::new_method_call("org.freedesktop.DBus", "/", "org.freedesktop.DBus", "ListNames").unwrap();
let r = c.send_with_reply_and_block(m, 2000).unwrap();
let reply = r.get_items();
println!("{:?}", reply);
}
#[test]
fn message_namehasowner() {
let c = Connection::get_private(BusType::Session).unwrap();
let mut m = Message::new_method_call("org.freedesktop.DBus", "/", "org.freedesktop.DBus", "NameHasOwner").unwrap();
m.append_items(&[MessageItem::Str("org.freedesktop.DBus".to_string())]);
let r = c.send_with_reply_and_block(m, 2000).unwrap();
let reply = r.get_items();
println!("{:?}", reply);
assert_eq!(reply, vec!(MessageItem::Bool(true)));
}
#[test]
fn object_path() {
use std::sync::mpsc;
let (tx, rx) = mpsc::channel();
let thread = ::std::thread::spawn(move || {
let c = Connection::get_private(BusType::Session).unwrap();
c.register_object_path("/hello").unwrap();
// println!("Waiting...");
tx.send(c.unique_name()).unwrap();
for n in c.iter(1000) {
// println!("Found message... ({})", n);
match n {
ConnectionItem::MethodCall(ref m) => {
let reply = Message::new_method_return(m).unwrap();
c.send(reply).unwrap();
break;
}
_ => {}
}
}
c.unregister_object_path("/hello");
});
let c = Connection::get_private(BusType::Session).unwrap();
let n = rx.recv().unwrap();
let m = Message::new_method_call(&n, "/hello", "com.example.hello", "Hello").unwrap();
println!("Sending...");
let r = c.send_with_reply_and_block(m, 8000).unwrap();
let reply = r.get_items();
println!("{:?}", reply);
thread.join().unwrap();
}
#[test]
fn register_name() {
let c = Connection::get_private(BusType::Session).unwrap();
let n = format!("com.example.hello.test.register_name");
assert_eq!(c.register_name(&n, NameFlag::ReplaceExisting as u32).unwrap(), RequestNameReply::PrimaryOwner);
assert_eq!(c.release_name(&n).unwrap(), ReleaseNameReply::Released);
}
#[test]
fn signal() {
let c = Connection::get_private(BusType::Session).unwrap();
let iface = "com.example.signaltest";
let mstr = format!("interface='{}',member='ThisIsASignal'", iface);
c.add_match(&mstr).unwrap();
let m = Message::new_signal("/mysignal", iface, "ThisIsASignal").unwrap();
let uname = c.unique_name();
c.send(m).unwrap();
for n in c.iter(1000) {
match n {
ConnectionItem::Signal(s) => {
let (_, p, i, m) = s.headers();
match (&*p.unwrap(), &*i.unwrap(), &*m.unwrap()) {
("/mysignal", "com.example.signaltest", "ThisIsASignal") => {
assert_eq!(s.sender().unwrap(), uname);
break;
},
(_, _, _) => println!("Other signal: {:?}", s.headers()),
}
}
_ => {},
}
}
c.remove_match(&mstr).unwrap();
}
}
| IConnection | identifier_name |
lib.rs | //! D-Bus bindings for Rust
//!
//! [D-Bus](http://dbus.freedesktop.org/) is a message bus, and is mainly used in Linux
//! for communication between processes. It is present by default on almost every
//! Linux distribution out there, and runs in two instances - one per session, and one
//! system-wide.
//!
//! See the examples directory for some examples to get you started.
extern crate libc;
pub use ffi::DBusBusType as BusType;
pub use ffi::DBusNameFlag as NameFlag;
pub use ffi::DBusRequestNameReply as RequestNameReply;
pub use ffi::DBusReleaseNameReply as ReleaseNameReply;
pub use ffi::DBusMessageType as MessageType;
pub use message::{Message, MessageItem, FromMessageItem, OwnedFd, OPath, ArrayError};
pub use prop::PropHandler;
pub use prop::Props;
/// A TypeSig describes the type of a MessageItem.
pub type TypeSig<'a> = std::borrow::Cow<'a, str>;
use std::ffi::{CString, CStr};
use std::ptr::{self};
use std::collections::LinkedList;
use std::cell::{Cell, RefCell};
mod ffi;
mod message;
mod prop;
mod objpath;
/// Contains functionality for the "server" of a D-Bus object. A remote application can
/// introspect this object and call methods on it.
pub mod obj {
pub use objpath::{ObjectPath, Interface, Property, Signal, Argument};
pub use objpath::{Method, MethodHandler, MethodResult};
pub use objpath::{PropertyROHandler, PropertyRWHandler, PropertyWOHandler, PropertyGetResult, PropertySetResult};
}
static INITDBUS: std::sync::Once = std::sync::ONCE_INIT;
fn init_dbus() {
INITDBUS.call_once(|| {
if unsafe { ffi::dbus_threads_init_default() } == 0 {
panic!("Out of memory when trying to initialize D-Bus library!");
}
});
}
/// D-Bus Error wrapper
pub struct Error {
e: ffi::DBusError,
}
unsafe impl Send for Error {}
fn c_str_to_slice(c: & *const libc::c_char) -> Option<&str> {
if *c == ptr::null() { None }
else { std::str::from_utf8( unsafe { CStr::from_ptr(*c).to_bytes() }).ok() }
}
fn to_c_str(n: &str) -> CString { CString::new(n.as_bytes()).unwrap() }
impl Error {
pub fn new_custom(name: &str, message: &str) -> Error {
let n = to_c_str(name);
let m = to_c_str(&message.replace("%","%%"));
let mut e = Error::empty();
unsafe { ffi::dbus_set_error(e.get_mut(), n.as_ptr(), m.as_ptr()) };
e
}
fn empty() -> Error {
init_dbus();
let mut e = ffi::DBusError {
name: ptr::null(),
message: ptr::null(),
dummy: 0,
padding1: ptr::null()
};
unsafe { ffi::dbus_error_init(&mut e); }
Error{ e: e }
}
/// Error name/type, e g 'org.freedesktop.DBus.Error.Failed'
pub fn name(&self) -> Option<&str> {
c_str_to_slice(&self.e.name)
}
/// Custom message, e g 'Could not find a matching object path'
pub fn message(&self) -> Option<&str> {
c_str_to_slice(&self.e.message)
}
fn get_mut(&mut self) -> &mut ffi::DBusError { &mut self.e }
}
impl Drop for Error {
fn drop(&mut self) {
unsafe { ffi::dbus_error_free(&mut self.e); }
}
}
impl std::fmt::Debug for Error {
fn fmt(&self, f: &mut std::fmt::Formatter) -> Result<(), std::fmt::Error> {
write!(f, "D-Bus error: {} ({})", self.message().unwrap_or(""),
self.name().unwrap_or(""))
}
}
impl std::error::Error for Error {
fn description(&self) -> &str { "D-Bus error" }
}
impl std::fmt::Display for Error {
fn fmt(&self, f: &mut std::fmt::Formatter) -> Result<(),std::fmt::Error> {
if let Some(x) = self.message() {
write!(f, "{:?}", x.to_string())
} else { Ok(()) }
}
}
/// When listening for incoming events on the D-Bus, this enum will tell you what type
/// of incoming event has happened.
#[derive(Debug)]
pub enum ConnectionItem {
Nothing,
MethodCall(Message),
Signal(Message),
}
/// ConnectionItem iterator
pub struct ConnectionItems<'a> {
c: &'a Connection,
timeout_ms: i32,
}
impl<'a> Iterator for ConnectionItems<'a> {
type Item = ConnectionItem;
fn next(&mut self) -> Option<ConnectionItem> {
loop {
let i = self.c.i.pending_items.borrow_mut().pop_front();
if i.is_some() { return i; }
let r = unsafe { ffi::dbus_connection_read_write_dispatch(self.c.conn(), self.timeout_ms as libc::c_int) };
if !self.c.i.pending_items.borrow().is_empty() { continue };
if r == 0 { return None; }
return Some(ConnectionItem::Nothing);
}
}
}
/* Since we register callbacks with userdata pointers,
we need to make sure the connection pointer does not move around.
Hence this extra indirection. */
struct IConnection {
conn: Cell<*mut ffi::DBusConnection>,
pending_items: RefCell<LinkedList<ConnectionItem>>,
}
/// A D-Bus connection. Start here if you want to get on the D-Bus!
pub struct Connection {
i: Box<IConnection>,
}
extern "C" fn filter_message_cb(conn: *mut ffi::DBusConnection, msg: *mut ffi::DBusMessage,
user_data: *mut libc::c_void) -> ffi::DBusHandlerResult {
let m = message::message_from_ptr(msg, true);
let i: &IConnection = unsafe { std::mem::transmute(user_data) };
assert!(i.conn.get() == conn);
let mtype: ffi::DBusMessageType = unsafe { std::mem::transmute(ffi::dbus_message_get_type(msg)) };
let r = match mtype {
ffi::DBusMessageType::Signal => {
i.pending_items.borrow_mut().push_back(ConnectionItem::Signal(m));
ffi::DBusHandlerResult::Handled
}
_ => ffi::DBusHandlerResult::NotYetHandled,
};
r
}
extern "C" fn object_path_message_cb(conn: *mut ffi::DBusConnection, msg: *mut ffi::DBusMessage,
user_data: *mut libc::c_void) -> ffi::DBusHandlerResult {
let m = message::message_from_ptr(msg, true);
let i: &IConnection = unsafe { std::mem::transmute(user_data) };
assert!(i.conn.get() == conn);
i.pending_items.borrow_mut().push_back(ConnectionItem::MethodCall(m));
ffi::DBusHandlerResult::Handled
}
impl Connection {
#[inline(always)]
fn conn(&self) -> *mut ffi::DBusConnection {
self.i.conn.get()
}
/// Creates a new D-Bus connection.
pub fn get_private(bus: BusType) -> Result<Connection, Error> {
let mut e = Error::empty();
let conn = unsafe { ffi::dbus_bus_get_private(bus, e.get_mut()) };
if conn == ptr::null_mut() {
return Err(e)
}
let c = Connection { i: Box::new(IConnection { conn: Cell::new(conn), pending_items: RefCell::new(LinkedList::new()) })};
/* No, we don't want our app to suddenly quit if dbus goes down */
unsafe { ffi::dbus_connection_set_exit_on_disconnect(conn, 0) };
assert!(unsafe {
ffi::dbus_connection_add_filter(c.conn(), Some(filter_message_cb as ffi::DBusCallback), std::mem::transmute(&*c.i), None)
} != 0);
Ok(c)
}
/// Sends a message over the D-Bus and waits for a reply.
/// This is usually used for method calls.
pub fn send_with_reply_and_block(&self, msg: Message, timeout_ms: i32) -> Result<Message, Error> {
let mut e = Error::empty();
let response = unsafe {
ffi::dbus_connection_send_with_reply_and_block(self.conn(), message::get_message_ptr(&msg),
timeout_ms as libc::c_int, e.get_mut())
};
if response == ptr::null_mut() {
return Err(e);
}
Ok(message::message_from_ptr(response, false))
}
/// Sends a message over the D-Bus without waiting. Useful for sending signals and method call replies.
pub fn send(&self, msg: Message) -> Result<u32,()> {
let mut serial = 0u32;
let r = unsafe { ffi::dbus_connection_send(self.conn(), message::get_message_ptr(&msg), &mut serial) };
if r == 0 { return Err(()); }
unsafe { ffi::dbus_connection_flush(self.conn()) };
Ok(serial)
}
pub fn unique_name(&self) -> String {
let c = unsafe { ffi::dbus_bus_get_unique_name(self.conn()) };
c_str_to_slice(&c).unwrap_or("").to_string()
}
// Check if there are new incoming events
pub fn iter(&self, timeout_ms: i32) -> ConnectionItems {
ConnectionItems {
c: self,
timeout_ms: timeout_ms,
}
}
pub fn register_object_path(&self, path: &str) -> Result<(), Error> {
let mut e = Error::empty();
let p = to_c_str(path);
let vtable = ffi::DBusObjectPathVTable {
unregister_function: None,
message_function: Some(object_path_message_cb as ffi::DBusCallback),
dbus_internal_pad1: None,
dbus_internal_pad2: None,
dbus_internal_pad3: None,
dbus_internal_pad4: None,
};
let r = unsafe {
let user_data: *mut libc::c_void = std::mem::transmute(&*self.i);
ffi::dbus_connection_try_register_object_path(self.conn(), p.as_ptr(), &vtable, user_data, e.get_mut())
};
if r == 0 { Err(e) } else { Ok(()) }
}
pub fn unregister_object_path(&self, path: &str) {
let p = to_c_str(path);
let r = unsafe { ffi::dbus_connection_unregister_object_path(self.conn(), p.as_ptr()) };
if r == 0 { panic!("Out of memory"); }
}
pub fn list_registered_object_paths(&self, path: &str) -> Vec<String> {
let p = to_c_str(path);
let mut clist: *mut *mut libc::c_char = ptr::null_mut();
let r = unsafe { ffi::dbus_connection_list_registered(self.conn(), p.as_ptr(), &mut clist) };
if r == 0 { panic!("Out of memory"); }
let mut v = Vec::new();
let mut i = 0;
loop {
let s = unsafe {
let citer = clist.offset(i);
if *citer == ptr::null_mut() { break };
std::mem::transmute(citer)
};
v.push(format!("{}", c_str_to_slice(s).unwrap()));
i += 1;
}
unsafe { ffi::dbus_free_string_array(clist) };
v
}
pub fn register_name(&self, name: &str, flags: u32) -> Result<RequestNameReply, Error> {
let mut e = Error::empty();
let n = to_c_str(name);
let r = unsafe { ffi::dbus_bus_request_name(self.conn(), n.as_ptr(), flags, e.get_mut()) };
if r == -1 { Err(e) } else { Ok(unsafe { std::mem::transmute(r) }) }
}
pub fn release_name(&self, name: &str) -> Result<ReleaseNameReply, Error> {
let mut e = Error::empty();
let n = to_c_str(name);
let r = unsafe { ffi::dbus_bus_release_name(self.conn(), n.as_ptr(), e.get_mut()) };
if r == -1 { Err(e) } else { Ok(unsafe { std::mem::transmute(r) }) }
}
pub fn add_match(&self, rule: &str) -> Result<(), Error> {
let mut e = Error::empty();
let n = to_c_str(rule);
unsafe { ffi::dbus_bus_add_match(self.conn(), n.as_ptr(), e.get_mut()) };
if e.name().is_some() { Err(e) } else { Ok(()) }
}
pub fn remove_match(&self, rule: &str) -> Result<(), Error> {
let mut e = Error::empty();
let n = to_c_str(rule);
unsafe { ffi::dbus_bus_remove_match(self.conn(), n.as_ptr(), e.get_mut()) };
if e.name().is_some() { Err(e) } else { Ok(()) }
}
}
impl Drop for Connection {
fn drop(&mut self) {
unsafe {
ffi::dbus_connection_close(self.conn());
ffi::dbus_connection_unref(self.conn());
}
}
}
impl std::fmt::Debug for Connection {
fn fmt(&self, f: &mut std::fmt::Formatter) -> Result<(), std::fmt::Error> {
write!(f, "D-Bus Connection({})", self.unique_name())
}
}
#[cfg(test)]
mod test {
use super::{Connection, Message, BusType, MessageItem, ConnectionItem, NameFlag,
RequestNameReply, ReleaseNameReply};
#[test]
fn connection() {
let c = Connection::get_private(BusType::Session).unwrap();
let n = c.unique_name();
assert!(n.starts_with(":1."));
println!("Connected to DBus, unique name: {}", n);
}
#[test]
fn invalid_message() {
let c = Connection::get_private(BusType::Session).unwrap();
let m = Message::new_method_call("foo.bar", "/", "foo.bar", "FooBar").unwrap();
let e = c.send_with_reply_and_block(m, 2000).err().unwrap();
assert!(e.name().unwrap() == "org.freedesktop.DBus.Error.ServiceUnknown");
}
#[test]
fn message_listnames() {
let c = Connection::get_private(BusType::Session).unwrap();
let m = Message::new_method_call("org.freedesktop.DBus", "/", "org.freedesktop.DBus", "ListNames").unwrap();
let r = c.send_with_reply_and_block(m, 2000).unwrap();
let reply = r.get_items();
println!("{:?}", reply);
}
#[test]
fn message_namehasowner() {
let c = Connection::get_private(BusType::Session).unwrap();
let mut m = Message::new_method_call("org.freedesktop.DBus", "/", "org.freedesktop.DBus", "NameHasOwner").unwrap();
m.append_items(&[MessageItem::Str("org.freedesktop.DBus".to_string())]);
let r = c.send_with_reply_and_block(m, 2000).unwrap();
let reply = r.get_items();
println!("{:?}", reply); |
#[test]
fn object_path() {
use std::sync::mpsc;
let (tx, rx) = mpsc::channel();
let thread = ::std::thread::spawn(move || {
let c = Connection::get_private(BusType::Session).unwrap();
c.register_object_path("/hello").unwrap();
// println!("Waiting...");
tx.send(c.unique_name()).unwrap();
for n in c.iter(1000) {
// println!("Found message... ({})", n);
match n {
ConnectionItem::MethodCall(ref m) => {
let reply = Message::new_method_return(m).unwrap();
c.send(reply).unwrap();
break;
}
_ => {}
}
}
c.unregister_object_path("/hello");
});
let c = Connection::get_private(BusType::Session).unwrap();
let n = rx.recv().unwrap();
let m = Message::new_method_call(&n, "/hello", "com.example.hello", "Hello").unwrap();
println!("Sending...");
let r = c.send_with_reply_and_block(m, 8000).unwrap();
let reply = r.get_items();
println!("{:?}", reply);
thread.join().unwrap();
}
#[test]
fn register_name() {
let c = Connection::get_private(BusType::Session).unwrap();
let n = format!("com.example.hello.test.register_name");
assert_eq!(c.register_name(&n, NameFlag::ReplaceExisting as u32).unwrap(), RequestNameReply::PrimaryOwner);
assert_eq!(c.release_name(&n).unwrap(), ReleaseNameReply::Released);
}
#[test]
fn signal() {
let c = Connection::get_private(BusType::Session).unwrap();
let iface = "com.example.signaltest";
let mstr = format!("interface='{}',member='ThisIsASignal'", iface);
c.add_match(&mstr).unwrap();
let m = Message::new_signal("/mysignal", iface, "ThisIsASignal").unwrap();
let uname = c.unique_name();
c.send(m).unwrap();
for n in c.iter(1000) {
match n {
ConnectionItem::Signal(s) => {
let (_, p, i, m) = s.headers();
match (&*p.unwrap(), &*i.unwrap(), &*m.unwrap()) {
("/mysignal", "com.example.signaltest", "ThisIsASignal") => {
assert_eq!(s.sender().unwrap(), uname);
break;
},
(_, _, _) => println!("Other signal: {:?}", s.headers()),
}
}
_ => {},
}
}
c.remove_match(&mstr).unwrap();
}
} | assert_eq!(reply, vec!(MessageItem::Bool(true)));
} | random_line_split |
app.js | angular.module('MEANcraftApp', ['ngRoute', 'MEANcraftApp.login', 'MEANcraftApp.overview', 'btford.socket-io'/*,'socket-io', 'flow'*/])
.config(function ($httpProvider, $routeProvider) {
$httpProvider.interceptors.push('TokenInterceptor');
$routeProvider
.when('/login', {
templateUrl: 'app/login/login',
controller: 'loginCtrl',
protect: false
})
.when('/overview', {
templateUrl: 'app/overview/overview',
//controller: 'overviewCtrl',
protect: true,
resolve: {
initialData: function (ServerSocket, FetchData, $q) {
return $q(function (resolve, reject) {
ServerSocket.emit('info');
ServerSocket.once('info', function (data) {
console.log(data);
FetchData = angular.extend(FetchData, data);
resolve();
});
});
}
}
})
.otherwise({
redirectTo: '/overview'
});
})
.run(function ($rootScope, $location, $window, $routeParams, UserAuth) {
if (!UserAuth.isLogged) {
$location.path('/login');
}
$rootScope.$on('$routeChangeStart', function (event, nextRoute, prevRoute) {
console.groupCollapsed('%cAPP.RUN -> ROUTE CHANGE START', 'background: #222; color: #bada55;');
console.log('%cTOKEN -> %c' + $window.sessionStorage.token, 'font-weight: bold', '');
console.log('%cLOGGIN STATUS -> %c' + UserAuth.isLogged, 'font-weight: bold', UserAuth.isLogged ? 'color: green;' : 'color: red;');
console.groupEnd('APP.RUN -> ROUTE CHANGE START');
if (nextRoute.protect && UserAuth.isLogged === false && !$window.sessionStorage.token) | else if (!nextRoute.protect && UserAuth.isLogged) {
$location.path('/overview');
}
});
}); | {
$location.path('/login');
console.error('Route protected, user not logged in');
} | conditional_block |
app.js | angular.module('MEANcraftApp', ['ngRoute', 'MEANcraftApp.login', 'MEANcraftApp.overview', 'btford.socket-io'/*,'socket-io', 'flow'*/])
.config(function ($httpProvider, $routeProvider) {
$httpProvider.interceptors.push('TokenInterceptor');
$routeProvider
.when('/login', {
templateUrl: 'app/login/login',
controller: 'loginCtrl',
protect: false
})
.when('/overview', {
templateUrl: 'app/overview/overview',
//controller: 'overviewCtrl',
protect: true,
resolve: {
initialData: function (ServerSocket, FetchData, $q) {
return $q(function (resolve, reject) {
ServerSocket.emit('info');
ServerSocket.once('info', function (data) {
console.log(data);
FetchData = angular.extend(FetchData, data);
resolve();
});
});
}
}
})
.otherwise({
redirectTo: '/overview'
});
})
.run(function ($rootScope, $location, $window, $routeParams, UserAuth) {
if (!UserAuth.isLogged) {
$location.path('/login');
}
$rootScope.$on('$routeChangeStart', function (event, nextRoute, prevRoute) {
console.groupCollapsed('%cAPP.RUN -> ROUTE CHANGE START', 'background: #222; color: #bada55;');
console.log('%cTOKEN -> %c' + $window.sessionStorage.token, 'font-weight: bold', '');
console.log('%cLOGGIN STATUS -> %c' + UserAuth.isLogged, 'font-weight: bold', UserAuth.isLogged ? 'color: green;' : 'color: red;');
console.groupEnd('APP.RUN -> ROUTE CHANGE START');
if (nextRoute.protect && UserAuth.isLogged === false && !$window.sessionStorage.token) {
$location.path('/login');
console.error('Route protected, user not logged in');
} else if (!nextRoute.protect && UserAuth.isLogged) {
$location.path('/overview'); | }); | }
}); | random_line_split |
projects.py | # Copyright 2017, Fabien Boucher
# Copyright 2017, Red Hat
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
from collections import OrderedDict
from pecan import abort
from pecan import expose
from repoxplorer import version
from repoxplorer.index.projects import Projects
rx_version = version.get_version()
class ProjectsController(object):
@expose('json')
def projects(self, pid=None):
projects_index = Projects()
if pid:
project = projects_index.get(pid)
if not project:
abort(404, detail="Project ID has not been found")
return {pid: projects_index.get(pid)}
else:
projects = projects_index.get_projects(
source=['name', 'description', 'logo', 'refs'])
_projects = OrderedDict(
sorted(list(projects.items()), key=lambda t: t[0]))
return {'projects': _projects,
'tags': projects_index.get_tags()}
@expose('json')
def | (self, pid=None, tid=None):
projects_index = Projects()
if not pid and not tid:
abort(404,
detail="A tag ID or project ID must be passed as parameter")
if pid:
project = projects_index.get(pid)
else:
if tid in projects_index.get_tags():
refs = projects_index.get_references_from_tags(tid)
project = {'refs': refs}
else:
project = None
if not project:
abort(404,
detail='Project ID or Tag ID has not been found')
return project['refs']
| repos | identifier_name |
projects.py | # Copyright 2017, Fabien Boucher
# Copyright 2017, Red Hat
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
from collections import OrderedDict
from pecan import abort
from pecan import expose
from repoxplorer import version
from repoxplorer.index.projects import Projects
rx_version = version.get_version()
class ProjectsController(object):
@expose('json')
def projects(self, pid=None):
projects_index = Projects()
if pid:
project = projects_index.get(pid)
if not project:
abort(404, detail="Project ID has not been found")
return {pid: projects_index.get(pid)}
else:
projects = projects_index.get_projects(
source=['name', 'description', 'logo', 'refs'])
_projects = OrderedDict(
sorted(list(projects.items()), key=lambda t: t[0]))
return {'projects': _projects,
'tags': projects_index.get_tags()}
@expose('json')
def repos(self, pid=None, tid=None):
projects_index = Projects()
if not pid and not tid:
|
if pid:
project = projects_index.get(pid)
else:
if tid in projects_index.get_tags():
refs = projects_index.get_references_from_tags(tid)
project = {'refs': refs}
else:
project = None
if not project:
abort(404,
detail='Project ID or Tag ID has not been found')
return project['refs']
| abort(404,
detail="A tag ID or project ID must be passed as parameter") | conditional_block |
projects.py | # Copyright 2017, Fabien Boucher
# Copyright 2017, Red Hat
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
|
from repoxplorer import version
from repoxplorer.index.projects import Projects
rx_version = version.get_version()
class ProjectsController(object):
@expose('json')
def projects(self, pid=None):
projects_index = Projects()
if pid:
project = projects_index.get(pid)
if not project:
abort(404, detail="Project ID has not been found")
return {pid: projects_index.get(pid)}
else:
projects = projects_index.get_projects(
source=['name', 'description', 'logo', 'refs'])
_projects = OrderedDict(
sorted(list(projects.items()), key=lambda t: t[0]))
return {'projects': _projects,
'tags': projects_index.get_tags()}
@expose('json')
def repos(self, pid=None, tid=None):
projects_index = Projects()
if not pid and not tid:
abort(404,
detail="A tag ID or project ID must be passed as parameter")
if pid:
project = projects_index.get(pid)
else:
if tid in projects_index.get_tags():
refs = projects_index.get_references_from_tags(tid)
project = {'refs': refs}
else:
project = None
if not project:
abort(404,
detail='Project ID or Tag ID has not been found')
return project['refs'] | from collections import OrderedDict
from pecan import abort
from pecan import expose | random_line_split |
projects.py | # Copyright 2017, Fabien Boucher
# Copyright 2017, Red Hat
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
from collections import OrderedDict
from pecan import abort
from pecan import expose
from repoxplorer import version
from repoxplorer.index.projects import Projects
rx_version = version.get_version()
class ProjectsController(object):
@expose('json')
def projects(self, pid=None):
|
@expose('json')
def repos(self, pid=None, tid=None):
projects_index = Projects()
if not pid and not tid:
abort(404,
detail="A tag ID or project ID must be passed as parameter")
if pid:
project = projects_index.get(pid)
else:
if tid in projects_index.get_tags():
refs = projects_index.get_references_from_tags(tid)
project = {'refs': refs}
else:
project = None
if not project:
abort(404,
detail='Project ID or Tag ID has not been found')
return project['refs']
| projects_index = Projects()
if pid:
project = projects_index.get(pid)
if not project:
abort(404, detail="Project ID has not been found")
return {pid: projects_index.get(pid)}
else:
projects = projects_index.get_projects(
source=['name', 'description', 'logo', 'refs'])
_projects = OrderedDict(
sorted(list(projects.items()), key=lambda t: t[0]))
return {'projects': _projects,
'tags': projects_index.get_tags()} | identifier_body |
to_str.rs | // Copyright 2012-2013 The Rust Project Developers. See the COPYRIGHT
// file at the top-level directory of this distribution and at
// http://rust-lang.org/COPYRIGHT.
//
// Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or
// http://www.apache.org/licenses/LICENSE-2.0> or the MIT license
// <LICENSE-MIT or http://opensource.org/licenses/MIT>, at your
// option. This file may not be copied, modified, or distributed
// except according to those terms.
use ast;
use ast::{meta_item, item, expr};
use codemap::span;
use ext::base::ExtCtxt;
use ext::build::AstBuilder;
use ext::deriving::generic::*;
pub fn expand_deriving_to_str(cx: @ExtCtxt,
span: span,
mitem: @meta_item,
in_items: ~[@item])
-> ~[@item] {
let trait_def = TraitDef {
path: Path::new(~["std", "to_str", "ToStr"]),
additional_bounds: ~[],
generics: LifetimeBounds::empty(),
methods: ~[
MethodDef {
name: "to_str",
generics: LifetimeBounds::empty(),
explicit_self: borrowed_explicit_self(),
args: ~[],
ret_ty: Ptr(~Literal(Path::new_local("str")), Send),
const_nonmatching: false,
combine_substructure: to_str_substructure
}
]
};
trait_def.expand(cx, span, mitem, in_items)
}
// It used to be the case that this deriving implementation invoked
// std::sys::log_str, but this isn't sufficient because it doesn't invoke the
// to_str() method on each field. Hence we mirror the logic of the log_str()
// method, but with tweaks to call to_str() on sub-fields.
fn to_str_substructure(cx: @ExtCtxt, span: span,
substr: &Substructure) -> @expr {
let to_str = cx.ident_of("to_str");
let doit = |start: &str, end: @str, name: ast::ident,
fields: &[(Option<ast::ident>, @expr, ~[@expr])]| {
if fields.len() == 0 {
cx.expr_str_uniq(span, cx.str_of(name))
} else {
let buf = cx.ident_of("buf");
let start = cx.str_of(name) + start;
let init = cx.expr_str_uniq(span, start.to_managed());
let mut stmts = ~[cx.stmt_let(span, true, buf, init)];
let push_str = cx.ident_of("push_str");
let push = |s: @expr| {
let ebuf = cx.expr_ident(span, buf);
let call = cx.expr_method_call(span, ebuf, push_str, ~[s]);
stmts.push(cx.stmt_expr(call));
};
for fields.iter().enumerate().advance |(i, &(name, e, _))| {
if i > 0 {
push(cx.expr_str(span, @", "));
}
match name {
None => {}
Some(id) => {
let name = cx.str_of(id) + ": ";
push(cx.expr_str(span, name.to_managed()));
}
}
push(cx.expr_method_call(span, e, to_str, ~[]));
}
push(cx.expr_str(span, end));
cx.expr_blk(cx.blk(span, stmts, Some(cx.expr_ident(span, buf))))
}
};
return match *substr.fields {
Struct(ref fields) => {
if fields.len() == 0 || fields[0].n0_ref().is_none() {
doit("(", @")", substr.type_ident, *fields)
} else {
doit("{", @"}", substr.type_ident, *fields)
}
}
EnumMatching(_, variant, ref fields) => {
match variant.node.kind {
ast::tuple_variant_kind(*) =>
doit("(", @")", variant.node.name, *fields),
ast::struct_variant_kind(*) =>
doit("{", @"}", variant.node.name, *fields), | }
_ => cx.bug("expected Struct or EnumMatching in deriving(ToStr)")
};
} | } | random_line_split |
lemkelcp.py | import numpy as np
class lemketableau:
def __init__(self,M,q,maxIter = 100):
n = len(q)
self.T = np.hstack((np.eye(n),-M,-np.ones((n,1)),q.reshape((n,1))))
self.n = n
self.wPos = np.arange(n)
self.zPos = np.arange(n,2*n)
self.W = 0
self.Z = 1
self.Y = 2
self.Q = 3
TbInd = np.vstack((self.W*np.ones(n,dtype=int),
np.arange(n,dtype=int)))
TnbInd = np.vstack((self.Z*np.ones(n,dtype=int),
np.arange(n,dtype=int)))
DriveInd = np.array([[self.Y],[0]])
QInd = np.array([[self.Q],[0]])
self.Tind = np.hstack((TbInd,TnbInd,DriveInd,QInd))
self.maxIter = maxIter
def lemkeAlgorithm(self):
initVal = self.initialize()
if not initVal:
return np.zeros(self.n),0,'Solution Found'
for k in range(self.maxIter):
stepVal = self.step()
if self.Tind[0,-2] == self.Y:
# Solution Found
z = self.extractSolution()
return z,0,'Solution Found'
elif not stepVal:
return None,1,'Secondary ray found'
return None,2,'Max Iterations Exceeded'
def initialize(self):
q = self.T[:,-1]
minQ = np.min(q)
if minQ < 0:
ind = np.argmin(q)
self.clearDriverColumn(ind)
self.pivot(ind)
return True
else:
return False
def step(self):
q = self.T[:,-1]
a = self.T[:,-2]
ind = np.nan
minRatio = np.inf
for i in range(self.n):
if a[i] > 0:
newRatio = q[i] / a[i]
if newRatio < minRatio:
ind = i
minRatio = newRatio
if minRatio < np.inf:
self.clearDriverColumn(ind)
self.pivot(ind)
return True
else:
return False
def extractSolution(self):
z = np.zeros(self.n)
q = self.T[:,-1]
for i in range(self.n):
if self.Tind[0,i] == self.Z:
z[self.Tind[1,i]] = q[i]
return z
def partnerPos(self,pos):
v,ind = self.Tind[:,pos]
if v == self.W:
ppos = self.zPos[ind]
elif v == self.Z:
ppos = self.wPos[ind]
else:
ppos = None
return ppos
def pivot(self,pos):
ppos = self.partnerPos(pos)
if ppos is not None:
self.swapColumns(pos,ppos)
self.swapColumns(pos,-2)
return True
else:
self.swapColumns(pos,-2)
return False
def swapMatColumns(self,M,i,j):
|
def swapPos(self,v,ind,newPos):
if v == self.W:
self.wPos[ind] = newPos % (2*self.n+2)
elif v == self.Z:
self.zPos[ind] = newPos % (2*self.n+2)
def swapColumns(self,i,j):
iInd = self.Tind[:,i]
jInd = self.Tind[:,j]
v,ind = iInd
self.swapPos(v,ind,j)
v,ind = jInd
self.swapPos(v,ind,i)
self.Tind = self.swapMatColumns(self.Tind,i,j)
self.T = self.swapMatColumns(self.T,i,j)
def clearDriverColumn(self,ind):
a = self.T[ind,-2]
self.T[ind] /= a
for i in range(self.n):
if i != ind:
b = self.T[i,-2]
self.T[i] -= b * self.T[ind]
def ind2str(self,indvec):
v,pos = indvec
if v == self.W:
s = 'w%d' % pos
elif v == self.Z:
s = 'z%d' % pos
elif v == self.Y:
s = 'y'
else:
s = 'q'
return s
def indexStringArray(self):
indstr = np.array([self.ind2str(indvec) for indvec in self.Tind.T],dtype=object)
return indstr
def indexedTableau(self):
indstr = self.indexStringArray()
return np.vstack((indstr,self.T))
def __repr__(self):
IT = self.indexedTableau()
return IT.__repr__()
def __str__(self):
IT = self.indexedTableau()
return IT.__str__()
def lemkelcp(M,q,maxIter=100):
"""
sol = lemkelcp(M,q,maxIter)
Uses Lemke's algorithm to copute a solution to the
linear complementarity problem:
Mz + q >= 0
z >= 0
z'(Mz+q) = 0
The inputs are given by:
M - an nxn numpy array
q - a length n numpy array
maxIter - an optional number of pivot iterations. Set to 100 by default
The solution is a tuple of the form:
z,exit_code,exit_string = sol
The entries are summaries in the table below:
|z | exit_code | exit_string |
-----------------------------------------------------------
| solution to LCP | 0 | 'Solution Found' |
| None | 1 | 'Secondary ray found' |
| None | 2 | 'Max Iterations Exceeded' |
"""
tableau = lemketableau(M,q,maxIter)
return tableau.lemkeAlgorithm()
| Mi = np.array(M[:,i],copy=True)
Mj = np.array(M[:,j],copy=True)
M[:,i] = Mj
M[:,j] = Mi
return M | identifier_body |
lemkelcp.py | import numpy as np
class lemketableau:
def __init__(self,M,q,maxIter = 100):
n = len(q)
self.T = np.hstack((np.eye(n),-M,-np.ones((n,1)),q.reshape((n,1))))
self.n = n
self.wPos = np.arange(n)
self.zPos = np.arange(n,2*n)
self.W = 0
self.Z = 1
self.Y = 2
self.Q = 3
TbInd = np.vstack((self.W*np.ones(n,dtype=int),
np.arange(n,dtype=int)))
TnbInd = np.vstack((self.Z*np.ones(n,dtype=int),
np.arange(n,dtype=int)))
DriveInd = np.array([[self.Y],[0]])
QInd = np.array([[self.Q],[0]])
self.Tind = np.hstack((TbInd,TnbInd,DriveInd,QInd))
self.maxIter = maxIter
def lemkeAlgorithm(self):
initVal = self.initialize()
if not initVal:
return np.zeros(self.n),0,'Solution Found'
for k in range(self.maxIter):
stepVal = self.step()
if self.Tind[0,-2] == self.Y:
# Solution Found
z = self.extractSolution()
return z,0,'Solution Found'
elif not stepVal:
return None,1,'Secondary ray found'
return None,2,'Max Iterations Exceeded'
def initialize(self):
q = self.T[:,-1]
minQ = np.min(q)
if minQ < 0:
|
else:
return False
def step(self):
q = self.T[:,-1]
a = self.T[:,-2]
ind = np.nan
minRatio = np.inf
for i in range(self.n):
if a[i] > 0:
newRatio = q[i] / a[i]
if newRatio < minRatio:
ind = i
minRatio = newRatio
if minRatio < np.inf:
self.clearDriverColumn(ind)
self.pivot(ind)
return True
else:
return False
def extractSolution(self):
z = np.zeros(self.n)
q = self.T[:,-1]
for i in range(self.n):
if self.Tind[0,i] == self.Z:
z[self.Tind[1,i]] = q[i]
return z
def partnerPos(self,pos):
v,ind = self.Tind[:,pos]
if v == self.W:
ppos = self.zPos[ind]
elif v == self.Z:
ppos = self.wPos[ind]
else:
ppos = None
return ppos
def pivot(self,pos):
ppos = self.partnerPos(pos)
if ppos is not None:
self.swapColumns(pos,ppos)
self.swapColumns(pos,-2)
return True
else:
self.swapColumns(pos,-2)
return False
def swapMatColumns(self,M,i,j):
Mi = np.array(M[:,i],copy=True)
Mj = np.array(M[:,j],copy=True)
M[:,i] = Mj
M[:,j] = Mi
return M
def swapPos(self,v,ind,newPos):
if v == self.W:
self.wPos[ind] = newPos % (2*self.n+2)
elif v == self.Z:
self.zPos[ind] = newPos % (2*self.n+2)
def swapColumns(self,i,j):
iInd = self.Tind[:,i]
jInd = self.Tind[:,j]
v,ind = iInd
self.swapPos(v,ind,j)
v,ind = jInd
self.swapPos(v,ind,i)
self.Tind = self.swapMatColumns(self.Tind,i,j)
self.T = self.swapMatColumns(self.T,i,j)
def clearDriverColumn(self,ind):
a = self.T[ind,-2]
self.T[ind] /= a
for i in range(self.n):
if i != ind:
b = self.T[i,-2]
self.T[i] -= b * self.T[ind]
def ind2str(self,indvec):
v,pos = indvec
if v == self.W:
s = 'w%d' % pos
elif v == self.Z:
s = 'z%d' % pos
elif v == self.Y:
s = 'y'
else:
s = 'q'
return s
def indexStringArray(self):
indstr = np.array([self.ind2str(indvec) for indvec in self.Tind.T],dtype=object)
return indstr
def indexedTableau(self):
indstr = self.indexStringArray()
return np.vstack((indstr,self.T))
def __repr__(self):
IT = self.indexedTableau()
return IT.__repr__()
def __str__(self):
IT = self.indexedTableau()
return IT.__str__()
def lemkelcp(M,q,maxIter=100):
"""
sol = lemkelcp(M,q,maxIter)
Uses Lemke's algorithm to copute a solution to the
linear complementarity problem:
Mz + q >= 0
z >= 0
z'(Mz+q) = 0
The inputs are given by:
M - an nxn numpy array
q - a length n numpy array
maxIter - an optional number of pivot iterations. Set to 100 by default
The solution is a tuple of the form:
z,exit_code,exit_string = sol
The entries are summaries in the table below:
|z | exit_code | exit_string |
-----------------------------------------------------------
| solution to LCP | 0 | 'Solution Found' |
| None | 1 | 'Secondary ray found' |
| None | 2 | 'Max Iterations Exceeded' |
"""
tableau = lemketableau(M,q,maxIter)
return tableau.lemkeAlgorithm()
| ind = np.argmin(q)
self.clearDriverColumn(ind)
self.pivot(ind)
return True | conditional_block |
lemkelcp.py | import numpy as np
class lemketableau:
def __init__(self,M,q,maxIter = 100):
n = len(q)
self.T = np.hstack((np.eye(n),-M,-np.ones((n,1)),q.reshape((n,1))))
self.n = n
self.wPos = np.arange(n)
self.zPos = np.arange(n,2*n)
self.W = 0
self.Z = 1
self.Y = 2
self.Q = 3
TbInd = np.vstack((self.W*np.ones(n,dtype=int),
np.arange(n,dtype=int)))
TnbInd = np.vstack((self.Z*np.ones(n,dtype=int),
np.arange(n,dtype=int)))
DriveInd = np.array([[self.Y],[0]])
QInd = np.array([[self.Q],[0]])
self.Tind = np.hstack((TbInd,TnbInd,DriveInd,QInd))
self.maxIter = maxIter
def lemkeAlgorithm(self):
initVal = self.initialize()
if not initVal:
return np.zeros(self.n),0,'Solution Found'
for k in range(self.maxIter):
stepVal = self.step()
if self.Tind[0,-2] == self.Y:
# Solution Found
z = self.extractSolution()
return z,0,'Solution Found'
elif not stepVal:
return None,1,'Secondary ray found'
return None,2,'Max Iterations Exceeded'
def initialize(self):
q = self.T[:,-1]
minQ = np.min(q)
if minQ < 0:
ind = np.argmin(q)
self.clearDriverColumn(ind)
self.pivot(ind)
return True
else:
return False
def | (self):
q = self.T[:,-1]
a = self.T[:,-2]
ind = np.nan
minRatio = np.inf
for i in range(self.n):
if a[i] > 0:
newRatio = q[i] / a[i]
if newRatio < minRatio:
ind = i
minRatio = newRatio
if minRatio < np.inf:
self.clearDriverColumn(ind)
self.pivot(ind)
return True
else:
return False
def extractSolution(self):
z = np.zeros(self.n)
q = self.T[:,-1]
for i in range(self.n):
if self.Tind[0,i] == self.Z:
z[self.Tind[1,i]] = q[i]
return z
def partnerPos(self,pos):
v,ind = self.Tind[:,pos]
if v == self.W:
ppos = self.zPos[ind]
elif v == self.Z:
ppos = self.wPos[ind]
else:
ppos = None
return ppos
def pivot(self,pos):
ppos = self.partnerPos(pos)
if ppos is not None:
self.swapColumns(pos,ppos)
self.swapColumns(pos,-2)
return True
else:
self.swapColumns(pos,-2)
return False
def swapMatColumns(self,M,i,j):
Mi = np.array(M[:,i],copy=True)
Mj = np.array(M[:,j],copy=True)
M[:,i] = Mj
M[:,j] = Mi
return M
def swapPos(self,v,ind,newPos):
if v == self.W:
self.wPos[ind] = newPos % (2*self.n+2)
elif v == self.Z:
self.zPos[ind] = newPos % (2*self.n+2)
def swapColumns(self,i,j):
iInd = self.Tind[:,i]
jInd = self.Tind[:,j]
v,ind = iInd
self.swapPos(v,ind,j)
v,ind = jInd
self.swapPos(v,ind,i)
self.Tind = self.swapMatColumns(self.Tind,i,j)
self.T = self.swapMatColumns(self.T,i,j)
def clearDriverColumn(self,ind):
a = self.T[ind,-2]
self.T[ind] /= a
for i in range(self.n):
if i != ind:
b = self.T[i,-2]
self.T[i] -= b * self.T[ind]
def ind2str(self,indvec):
v,pos = indvec
if v == self.W:
s = 'w%d' % pos
elif v == self.Z:
s = 'z%d' % pos
elif v == self.Y:
s = 'y'
else:
s = 'q'
return s
def indexStringArray(self):
indstr = np.array([self.ind2str(indvec) for indvec in self.Tind.T],dtype=object)
return indstr
def indexedTableau(self):
indstr = self.indexStringArray()
return np.vstack((indstr,self.T))
def __repr__(self):
IT = self.indexedTableau()
return IT.__repr__()
def __str__(self):
IT = self.indexedTableau()
return IT.__str__()
def lemkelcp(M,q,maxIter=100):
"""
sol = lemkelcp(M,q,maxIter)
Uses Lemke's algorithm to copute a solution to the
linear complementarity problem:
Mz + q >= 0
z >= 0
z'(Mz+q) = 0
The inputs are given by:
M - an nxn numpy array
q - a length n numpy array
maxIter - an optional number of pivot iterations. Set to 100 by default
The solution is a tuple of the form:
z,exit_code,exit_string = sol
The entries are summaries in the table below:
|z | exit_code | exit_string |
-----------------------------------------------------------
| solution to LCP | 0 | 'Solution Found' |
| None | 1 | 'Secondary ray found' |
| None | 2 | 'Max Iterations Exceeded' |
"""
tableau = lemketableau(M,q,maxIter)
return tableau.lemkeAlgorithm()
| step | identifier_name |
lemkelcp.py | import numpy as np
class lemketableau:
def __init__(self,M,q,maxIter = 100):
n = len(q)
self.T = np.hstack((np.eye(n),-M,-np.ones((n,1)),q.reshape((n,1))))
self.n = n
self.wPos = np.arange(n)
self.zPos = np.arange(n,2*n)
self.W = 0
self.Z = 1
self.Y = 2
self.Q = 3
TbInd = np.vstack((self.W*np.ones(n,dtype=int),
np.arange(n,dtype=int)))
TnbInd = np.vstack((self.Z*np.ones(n,dtype=int),
np.arange(n,dtype=int)))
DriveInd = np.array([[self.Y],[0]])
QInd = np.array([[self.Q],[0]])
self.Tind = np.hstack((TbInd,TnbInd,DriveInd,QInd))
self.maxIter = maxIter
def lemkeAlgorithm(self):
initVal = self.initialize()
if not initVal:
return np.zeros(self.n),0,'Solution Found'
| # Solution Found
z = self.extractSolution()
return z,0,'Solution Found'
elif not stepVal:
return None,1,'Secondary ray found'
return None,2,'Max Iterations Exceeded'
def initialize(self):
q = self.T[:,-1]
minQ = np.min(q)
if minQ < 0:
ind = np.argmin(q)
self.clearDriverColumn(ind)
self.pivot(ind)
return True
else:
return False
def step(self):
q = self.T[:,-1]
a = self.T[:,-2]
ind = np.nan
minRatio = np.inf
for i in range(self.n):
if a[i] > 0:
newRatio = q[i] / a[i]
if newRatio < minRatio:
ind = i
minRatio = newRatio
if minRatio < np.inf:
self.clearDriverColumn(ind)
self.pivot(ind)
return True
else:
return False
def extractSolution(self):
z = np.zeros(self.n)
q = self.T[:,-1]
for i in range(self.n):
if self.Tind[0,i] == self.Z:
z[self.Tind[1,i]] = q[i]
return z
def partnerPos(self,pos):
v,ind = self.Tind[:,pos]
if v == self.W:
ppos = self.zPos[ind]
elif v == self.Z:
ppos = self.wPos[ind]
else:
ppos = None
return ppos
def pivot(self,pos):
ppos = self.partnerPos(pos)
if ppos is not None:
self.swapColumns(pos,ppos)
self.swapColumns(pos,-2)
return True
else:
self.swapColumns(pos,-2)
return False
def swapMatColumns(self,M,i,j):
Mi = np.array(M[:,i],copy=True)
Mj = np.array(M[:,j],copy=True)
M[:,i] = Mj
M[:,j] = Mi
return M
def swapPos(self,v,ind,newPos):
if v == self.W:
self.wPos[ind] = newPos % (2*self.n+2)
elif v == self.Z:
self.zPos[ind] = newPos % (2*self.n+2)
def swapColumns(self,i,j):
iInd = self.Tind[:,i]
jInd = self.Tind[:,j]
v,ind = iInd
self.swapPos(v,ind,j)
v,ind = jInd
self.swapPos(v,ind,i)
self.Tind = self.swapMatColumns(self.Tind,i,j)
self.T = self.swapMatColumns(self.T,i,j)
def clearDriverColumn(self,ind):
a = self.T[ind,-2]
self.T[ind] /= a
for i in range(self.n):
if i != ind:
b = self.T[i,-2]
self.T[i] -= b * self.T[ind]
def ind2str(self,indvec):
v,pos = indvec
if v == self.W:
s = 'w%d' % pos
elif v == self.Z:
s = 'z%d' % pos
elif v == self.Y:
s = 'y'
else:
s = 'q'
return s
def indexStringArray(self):
indstr = np.array([self.ind2str(indvec) for indvec in self.Tind.T],dtype=object)
return indstr
def indexedTableau(self):
indstr = self.indexStringArray()
return np.vstack((indstr,self.T))
def __repr__(self):
IT = self.indexedTableau()
return IT.__repr__()
def __str__(self):
IT = self.indexedTableau()
return IT.__str__()
def lemkelcp(M,q,maxIter=100):
"""
sol = lemkelcp(M,q,maxIter)
Uses Lemke's algorithm to copute a solution to the
linear complementarity problem:
Mz + q >= 0
z >= 0
z'(Mz+q) = 0
The inputs are given by:
M - an nxn numpy array
q - a length n numpy array
maxIter - an optional number of pivot iterations. Set to 100 by default
The solution is a tuple of the form:
z,exit_code,exit_string = sol
The entries are summaries in the table below:
|z | exit_code | exit_string |
-----------------------------------------------------------
| solution to LCP | 0 | 'Solution Found' |
| None | 1 | 'Secondary ray found' |
| None | 2 | 'Max Iterations Exceeded' |
"""
tableau = lemketableau(M,q,maxIter)
return tableau.lemkeAlgorithm() | for k in range(self.maxIter):
stepVal = self.step()
if self.Tind[0,-2] == self.Y: | random_line_split |
mod.rs | use alloc::boxed::{Box, FnBox};
use super::stack::Stack;
#[cfg(target_arch = "x86")]
mod i686;
#[cfg(target_arch = "x86_64")]
mod x86_64;
mod imp {
#[cfg(target_arch = "x86")]
pub use super::i686::*;
#[cfg(target_arch = "x86_64")]
pub use super::x86_64::*;
}
/// A thread has to be wrapped by a calling function. This function
/// is responsible to setup/cleanup for the actual closure that the user wants
/// to call. This closure is passed as first parameter to the wrapping function
/// and is named 'f' here. This pointer *IS* extracted from a Box via a call
/// to Box::into_raw. The wrapper function is now responsible for its proper
/// deallocation when the thread is terminated
pub type WrapperFn = extern "C" fn(f: *mut u8) -> !;
#[derive(Debug)]
pub struct Context {
regs: imp::Registers,
}
impl Context {
pub unsafe fn new<F>(wrapper: WrapperFn, mut f: F, stack: &mut Stack) -> Self
where F: FnMut() -> (), F: Send + 'static {
let fun = move || {
f();
};
let boxed_fun: Box<FnBox()> = Box::new(fun);
let fun_ptr = Box::into_raw(Box::new(boxed_fun)) as *mut u8;
Context {
regs: imp::Registers::new(wrapper, fun_ptr, stack.top().unwrap()),
}
}
/// Load the current context to the CPU
pub fn load(&self) -> ! |
#[inline(always)]
#[cfg_attr(feature = "clippy", allow(inline_always))]
/// Save the current context. This function will actually return twice.
/// The first return is just after saving the context and will return false
/// The second time is when the saved context gets restored and will return
/// true
///
/// This function is always inlined because otherwise the stack frame gets
/// corrupted as this will return twice. The second time the function
/// returns the stack frame will most likely be corrupted. To avoid that
/// inline the function to merge the stack frame of this function with
/// the caller's.
pub fn save(&mut self) -> bool {
unsafe {
imp::registers_save(&mut self.regs)
}
}
}
| {
unsafe {
imp::registers_load(&self.regs);
}
} | identifier_body |
mod.rs | use alloc::boxed::{Box, FnBox};
use super::stack::Stack;
#[cfg(target_arch = "x86")]
mod i686;
#[cfg(target_arch = "x86_64")]
mod x86_64;
mod imp {
#[cfg(target_arch = "x86")]
pub use super::i686::*;
#[cfg(target_arch = "x86_64")]
pub use super::x86_64::*;
}
/// A thread has to be wrapped by a calling function. This function
/// is responsible to setup/cleanup for the actual closure that the user wants
/// to call. This closure is passed as first parameter to the wrapping function
/// and is named 'f' here. This pointer *IS* extracted from a Box via a call
/// to Box::into_raw. The wrapper function is now responsible for its proper
/// deallocation when the thread is terminated
pub type WrapperFn = extern "C" fn(f: *mut u8) -> !;
#[derive(Debug)]
pub struct Context {
regs: imp::Registers,
}
impl Context {
pub unsafe fn | <F>(wrapper: WrapperFn, mut f: F, stack: &mut Stack) -> Self
where F: FnMut() -> (), F: Send + 'static {
let fun = move || {
f();
};
let boxed_fun: Box<FnBox()> = Box::new(fun);
let fun_ptr = Box::into_raw(Box::new(boxed_fun)) as *mut u8;
Context {
regs: imp::Registers::new(wrapper, fun_ptr, stack.top().unwrap()),
}
}
/// Load the current context to the CPU
pub fn load(&self) -> ! {
unsafe {
imp::registers_load(&self.regs);
}
}
#[inline(always)]
#[cfg_attr(feature = "clippy", allow(inline_always))]
/// Save the current context. This function will actually return twice.
/// The first return is just after saving the context and will return false
/// The second time is when the saved context gets restored and will return
/// true
///
/// This function is always inlined because otherwise the stack frame gets
/// corrupted as this will return twice. The second time the function
/// returns the stack frame will most likely be corrupted. To avoid that
/// inline the function to merge the stack frame of this function with
/// the caller's.
pub fn save(&mut self) -> bool {
unsafe {
imp::registers_save(&mut self.regs)
}
}
}
| new | identifier_name |
mod.rs | use alloc::boxed::{Box, FnBox};
use super::stack::Stack;
#[cfg(target_arch = "x86")]
mod i686;
#[cfg(target_arch = "x86_64")]
mod x86_64;
mod imp {
#[cfg(target_arch = "x86")]
pub use super::i686::*;
#[cfg(target_arch = "x86_64")]
pub use super::x86_64::*;
}
/// A thread has to be wrapped by a calling function. This function
/// is responsible to setup/cleanup for the actual closure that the user wants
/// to call. This closure is passed as first parameter to the wrapping function
/// and is named 'f' here. This pointer *IS* extracted from a Box via a call
/// to Box::into_raw. The wrapper function is now responsible for its proper
/// deallocation when the thread is terminated
pub type WrapperFn = extern "C" fn(f: *mut u8) -> !;
#[derive(Debug)]
pub struct Context {
regs: imp::Registers,
}
impl Context {
pub unsafe fn new<F>(wrapper: WrapperFn, mut f: F, stack: &mut Stack) -> Self
where F: FnMut() -> (), F: Send + 'static {
let fun = move || {
f();
};
let boxed_fun: Box<FnBox()> = Box::new(fun);
let fun_ptr = Box::into_raw(Box::new(boxed_fun)) as *mut u8;
Context {
regs: imp::Registers::new(wrapper, fun_ptr, stack.top().unwrap()),
}
} | pub fn load(&self) -> ! {
unsafe {
imp::registers_load(&self.regs);
}
}
#[inline(always)]
#[cfg_attr(feature = "clippy", allow(inline_always))]
/// Save the current context. This function will actually return twice.
/// The first return is just after saving the context and will return false
/// The second time is when the saved context gets restored and will return
/// true
///
/// This function is always inlined because otherwise the stack frame gets
/// corrupted as this will return twice. The second time the function
/// returns the stack frame will most likely be corrupted. To avoid that
/// inline the function to merge the stack frame of this function with
/// the caller's.
pub fn save(&mut self) -> bool {
unsafe {
imp::registers_save(&mut self.regs)
}
}
} |
/// Load the current context to the CPU | random_line_split |
borrowck-preserve-box-in-pat.rs | // Copyright 2012 The Rust Project Developers. See the COPYRIGHT
// file at the top-level directory of this distribution and at
// http://rust-lang.org/COPYRIGHT.
//
// Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or
// http://www.apache.org/licenses/LICENSE-2.0> or the MIT license
// <LICENSE-MIT or http://opensource.org/licenses/MIT>, at your | // exec-env:RUST_POISON_ON_FREE=1
use std::ptr;
struct F { f: ~int }
pub fn main() {
let x = @mut @F {f: ~3};
match x {
@@F{f: ref b_x} => {
assert_eq!(**b_x, 3);
assert_eq!(ptr::to_unsafe_ptr(&(x.f)), ptr::to_unsafe_ptr(b_x));
*x = @F {f: ~4};
info!("ptr::to_unsafe_ptr(*b_x) = {:x}",
ptr::to_unsafe_ptr(&(**b_x)) as uint);
assert_eq!(**b_x, 3);
assert!(ptr::to_unsafe_ptr(&(*x.f)) != ptr::to_unsafe_ptr(&(**b_x)));
}
}
} | // option. This file may not be copied, modified, or distributed
// except according to those terms.
| random_line_split |
borrowck-preserve-box-in-pat.rs | // Copyright 2012 The Rust Project Developers. See the COPYRIGHT
// file at the top-level directory of this distribution and at
// http://rust-lang.org/COPYRIGHT.
//
// Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or
// http://www.apache.org/licenses/LICENSE-2.0> or the MIT license
// <LICENSE-MIT or http://opensource.org/licenses/MIT>, at your
// option. This file may not be copied, modified, or distributed
// except according to those terms.
// exec-env:RUST_POISON_ON_FREE=1
use std::ptr;
struct F { f: ~int }
pub fn main() | {
let x = @mut @F {f: ~3};
match x {
@@F{f: ref b_x} => {
assert_eq!(**b_x, 3);
assert_eq!(ptr::to_unsafe_ptr(&(x.f)), ptr::to_unsafe_ptr(b_x));
*x = @F {f: ~4};
info!("ptr::to_unsafe_ptr(*b_x) = {:x}",
ptr::to_unsafe_ptr(&(**b_x)) as uint);
assert_eq!(**b_x, 3);
assert!(ptr::to_unsafe_ptr(&(*x.f)) != ptr::to_unsafe_ptr(&(**b_x)));
}
}
} | identifier_body | |
borrowck-preserve-box-in-pat.rs | // Copyright 2012 The Rust Project Developers. See the COPYRIGHT
// file at the top-level directory of this distribution and at
// http://rust-lang.org/COPYRIGHT.
//
// Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or
// http://www.apache.org/licenses/LICENSE-2.0> or the MIT license
// <LICENSE-MIT or http://opensource.org/licenses/MIT>, at your
// option. This file may not be copied, modified, or distributed
// except according to those terms.
// exec-env:RUST_POISON_ON_FREE=1
use std::ptr;
struct F { f: ~int }
pub fn | () {
let x = @mut @F {f: ~3};
match x {
@@F{f: ref b_x} => {
assert_eq!(**b_x, 3);
assert_eq!(ptr::to_unsafe_ptr(&(x.f)), ptr::to_unsafe_ptr(b_x));
*x = @F {f: ~4};
info!("ptr::to_unsafe_ptr(*b_x) = {:x}",
ptr::to_unsafe_ptr(&(**b_x)) as uint);
assert_eq!(**b_x, 3);
assert!(ptr::to_unsafe_ptr(&(*x.f)) != ptr::to_unsafe_ptr(&(**b_x)));
}
}
}
| main | identifier_name |
mdata_info.rs | // Copyright 2018 MaidSafe.net limited.
//
// This SAFE Network Software is licensed to you under The General Public License (GPL), version 3.
// Unless required by applicable law or agreed to in writing, the SAFE Network Software distributed
// under the GPL Licence is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
// KIND, either express or implied. Please review the Licences for the specific language governing
// permissions and limitations relating to use of the SAFE Network Software.
use crate::crypto::shared_secretbox;
use crate::errors::CoreError;
use crate::ffi::arrays::{SymNonce, SymSecretKey};
use crate::ffi::MDataInfo as FfiMDataInfo;
use crate::ipc::IpcError;
use crate::utils::{symmetric_decrypt, symmetric_encrypt};
use ffi_utils::ReprC;
use rand::{OsRng, Rng};
use routing::{EntryAction, Value, XorName};
use rust_sodium::crypto::secretbox;
use std::collections::{BTreeMap, BTreeSet};
use tiny_keccak::sha3_256;
/// Information allowing to locate and access mutable data on the network.
#[derive(Clone, Debug, Eq, PartialEq, Deserialize, Serialize)]
pub struct MDataInfo {
/// Name of the data where the directory is stored.
pub name: XorName,
/// Type tag of the data where the directory is stored.
pub type_tag: u64,
/// Key to encrypt/decrypt the directory content and the nonce to be used for keys
pub enc_info: Option<(shared_secretbox::Key, secretbox::Nonce)>,
/// Future encryption info, used for two-phase data reencryption.
pub new_enc_info: Option<(shared_secretbox::Key, secretbox::Nonce)>,
}
impl MDataInfo {
/// Construct `MDataInfo` for private (encrypted) data with a provided private key.
pub fn new_private(
name: XorName,
type_tag: u64,
enc_info: (shared_secretbox::Key, secretbox::Nonce),
) -> Self {
MDataInfo {
name,
type_tag,
enc_info: Some(enc_info),
new_enc_info: None,
}
}
/// Construct `MDataInfo` for public data.
pub fn new_public(name: XorName, type_tag: u64) -> Self {
MDataInfo {
name,
type_tag,
enc_info: None,
new_enc_info: None,
}
}
/// Generate random `MDataInfo` for private (encrypted) mutable data.
pub fn random_private(type_tag: u64) -> Result<Self, CoreError> {
let mut rng = os_rng()?;
let enc_info = (shared_secretbox::gen_key(), secretbox::gen_nonce());
Ok(Self::new_private(rng.gen(), type_tag, enc_info))
}
/// Generate random `MDataInfo` for public mutable data.
pub fn random_public(type_tag: u64) -> Result<Self, CoreError> {
let mut rng = os_rng()?;
Ok(Self::new_public(rng.gen(), type_tag))
}
/// Returns the encryption key, if any.
pub fn enc_key(&self) -> Option<&shared_secretbox::Key> {
self.enc_info.as_ref().map(|&(ref key, _)| key)
}
/// Returns the nonce, if any.
pub fn nonce(&self) -> Option<&secretbox::Nonce> {
self.enc_info.as_ref().map(|&(_, ref nonce)| nonce)
}
/// Encrypt the key for the mdata entry accordingly.
pub fn enc_entry_key(&self, plain_text: &[u8]) -> Result<Vec<u8>, CoreError> {
if let Some((ref key, seed)) = self.new_enc_info {
enc_entry_key(plain_text, key, seed)
} else if let Some((ref key, seed)) = self.enc_info {
enc_entry_key(plain_text, key, seed)
} else {
Ok(plain_text.to_vec())
}
}
/// Encrypt the value for this mdata entry accordingly.
pub fn enc_entry_value(&self, plain_text: &[u8]) -> Result<Vec<u8>, CoreError> {
if let Some((ref key, _)) = self.new_enc_info {
symmetric_encrypt(plain_text, key, None)
} else if let Some((ref key, _)) = self.enc_info {
symmetric_encrypt(plain_text, key, None)
} else {
Ok(plain_text.to_vec())
}
}
/// Decrypt key or value of this mdata entry.
pub fn decrypt(&self, cipher: &[u8]) -> Result<Vec<u8>, CoreError> {
if let Some((ref key, _)) = self.new_enc_info {
if let Ok(plain) = symmetric_decrypt(cipher, key) {
return Ok(plain);
}
}
if let Some((ref key, _)) = self.enc_info {
symmetric_decrypt(cipher, key)
} else {
Ok(cipher.to_vec())
}
}
/// Start the encryption info re-generation by populating the `new_enc_info`
/// field with random keys, unless it's already populated.
pub fn start_new_enc_info(&mut self) {
if self.enc_info.is_some() && self.new_enc_info.is_none() {
self.new_enc_info = Some((shared_secretbox::gen_key(), secretbox::gen_nonce()));
}
}
/// Commit the encryption info re-generation by replacing the current encryption info
/// with `new_enc_info` (if any).
pub fn commit_new_enc_info(&mut self) {
if let Some(new_enc_info) = self.new_enc_info.take() {
self.enc_info = Some(new_enc_info);
}
}
/// Construct FFI wrapper for the native Rust object, consuming self.
pub fn into_repr_c(self) -> FfiMDataInfo {
let (has_enc_info, enc_key, enc_nonce) = enc_info_into_repr_c(self.enc_info);
let (has_new_enc_info, new_enc_key, new_enc_nonce) =
enc_info_into_repr_c(self.new_enc_info);
FfiMDataInfo {
name: self.name.0,
type_tag: self.type_tag,
has_enc_info,
enc_key,
enc_nonce,
has_new_enc_info,
new_enc_key,
new_enc_nonce,
}
}
}
fn os_rng() -> Result<OsRng, CoreError> {
OsRng::new().map_err(|_| CoreError::RandomDataGenerationFailure)
}
/// Encrypt the entries (both keys and values) using the `MDataInfo`.
pub fn encrypt_entries(
info: &MDataInfo,
entries: &BTreeMap<Vec<u8>, Value>,
) -> Result<BTreeMap<Vec<u8>, Value>, CoreError> {
let mut output = BTreeMap::new();
for (key, value) in entries {
let encrypted_key = info.enc_entry_key(key)?;
let encrypted_value = encrypt_value(info, value)?;
let _ = output.insert(encrypted_key, encrypted_value);
}
Ok(output)
}
/// Encrypt entry actions using the `MDataInfo`. The effect of this is that the entries
/// mutated by the encrypted actions will end up encrypted using the `MDataInfo`.
pub fn encrypt_entry_actions(
info: &MDataInfo,
actions: &BTreeMap<Vec<u8>, EntryAction>,
) -> Result<BTreeMap<Vec<u8>, EntryAction>, CoreError> {
let mut output = BTreeMap::new();
for (key, action) in actions {
let encrypted_key = info.enc_entry_key(key)?;
let encrypted_action = match *action {
EntryAction::Ins(ref value) => EntryAction::Ins(encrypt_value(info, value)?),
EntryAction::Update(ref value) => EntryAction::Update(encrypt_value(info, value)?),
EntryAction::Del(version) => EntryAction::Del(version),
};
let _ = output.insert(encrypted_key, encrypted_action);
}
Ok(output)
}
/// Decrypt entries using the `MDataInfo`.
pub fn decrypt_entries(
info: &MDataInfo,
entries: &BTreeMap<Vec<u8>, Value>,
) -> Result<BTreeMap<Vec<u8>, Value>, CoreError> {
let mut output = BTreeMap::new();
for (key, value) in entries {
let decrypted_key = info.decrypt(key)?;
let decrypted_value = decrypt_value(info, value)?;
let _ = output.insert(decrypted_key, decrypted_value);
}
Ok(output)
}
/// Decrypt all keys using the `MDataInfo`.
pub fn decrypt_keys(
info: &MDataInfo,
keys: &BTreeSet<Vec<u8>>,
) -> Result<BTreeSet<Vec<u8>>, CoreError> {
let mut output = BTreeSet::new();
for key in keys {
let _ = output.insert(info.decrypt(key)?);
}
Ok(output)
}
/// Decrypt all values using the `MDataInfo`.
pub fn decrypt_values(info: &MDataInfo, values: &[Value]) -> Result<Vec<Value>, CoreError> {
let mut output = Vec::with_capacity(values.len());
for value in values {
output.push(decrypt_value(info, value)?);
}
Ok(output)
}
fn encrypt_value(info: &MDataInfo, value: &Value) -> Result<Value, CoreError> {
Ok(Value {
content: info.enc_entry_value(&value.content)?,
entry_version: value.entry_version,
})
}
fn decrypt_value(info: &MDataInfo, value: &Value) -> Result<Value, CoreError> {
Ok(Value {
content: info.decrypt(&value.content)?,
entry_version: value.entry_version,
})
}
fn enc_entry_key(
plain_text: &[u8],
key: &secretbox::Key,
seed: secretbox::Nonce,
) -> Result<Vec<u8>, CoreError> {
let nonce = {
let secretbox::Nonce(ref nonce) = seed;
let mut pt = plain_text.to_vec();
pt.extend_from_slice(&nonce[..]);
unwrap!(secretbox::Nonce::from_slice(
&sha3_256(&pt)[..secretbox::NONCEBYTES],
))
};
symmetric_encrypt(plain_text, key, Some(&nonce))
}
impl ReprC for MDataInfo {
type C = *const FfiMDataInfo;
type Error = IpcError;
#[allow(unsafe_code)]
unsafe fn clone_from_repr_c(repr_c: Self::C) -> Result<Self, Self::Error> {
let FfiMDataInfo {
name,
type_tag,
has_enc_info,
enc_key,
enc_nonce,
has_new_enc_info,
new_enc_key,
new_enc_nonce,
} = *repr_c;
Ok(Self {
name: XorName(name),
type_tag,
enc_info: enc_info_from_repr_c(has_enc_info, enc_key, enc_nonce),
new_enc_info: enc_info_from_repr_c(has_new_enc_info, new_enc_key, new_enc_nonce),
})
}
}
fn enc_info_into_repr_c(
info: Option<(shared_secretbox::Key, secretbox::Nonce)>,
) -> (bool, SymSecretKey, SymNonce) {
if let Some((key, nonce)) = info | else {
(false, Default::default(), Default::default())
}
}
fn enc_info_from_repr_c(
is_set: bool,
key: SymSecretKey,
nonce: SymNonce,
) -> Option<(shared_secretbox::Key, secretbox::Nonce)> {
if is_set {
Some((
shared_secretbox::Key::from_raw(&key),
secretbox::Nonce(nonce),
))
} else {
None
}
}
#[cfg(test)]
mod tests {
use super::*;
// Ensure that a private mdata info is encrypted.
#[test]
fn private_mdata_info_encrypts() {
let info = unwrap!(MDataInfo::random_private(0));
let key = Vec::from("str of key");
let val = Vec::from("other is value");
let enc_key = unwrap!(info.enc_entry_key(&key));
let enc_val = unwrap!(info.enc_entry_value(&val));
assert_ne!(enc_key, key);
assert_ne!(enc_val, val);
assert_eq!(unwrap!(info.decrypt(&enc_key)), key);
assert_eq!(unwrap!(info.decrypt(&enc_val)), val);
}
// Ensure that a public mdata info is not encrypted.
#[test]
fn public_mdata_info_doesnt_encrypt() {
let info = unwrap!(MDataInfo::random_public(0));
let key = Vec::from("str of key");
let val = Vec::from("other is value");
assert_eq!(unwrap!(info.enc_entry_key(&key)), key);
assert_eq!(unwrap!(info.enc_entry_value(&val)), val);
assert_eq!(unwrap!(info.decrypt(&val)), val);
}
// Test creating and committing new encryption info.
#[test]
fn decrypt() {
let mut info = unwrap!(MDataInfo::random_private(0));
let plain = Vec::from("plaintext");
let old_cipher = unwrap!(info.enc_entry_value(&plain));
info.start_new_enc_info();
let new_cipher = unwrap!(info.enc_entry_value(&plain));
// After start, both encryption infos work.
assert_eq!(unwrap!(info.decrypt(&old_cipher)), plain);
assert_eq!(unwrap!(info.decrypt(&new_cipher)), plain);
// After commit, only the new encryption info works.
info.commit_new_enc_info();
match info.decrypt(&old_cipher) {
Err(CoreError::SymmetricDecipherFailure) => (),
x => panic!("Unexpected {:?}", x),
}
assert_eq!(unwrap!(info.decrypt(&new_cipher)), plain);
}
}
| {
(true, key.0, nonce.0)
} | conditional_block |
mdata_info.rs | // Copyright 2018 MaidSafe.net limited.
//
// This SAFE Network Software is licensed to you under The General Public License (GPL), version 3.
// Unless required by applicable law or agreed to in writing, the SAFE Network Software distributed
// under the GPL Licence is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
// KIND, either express or implied. Please review the Licences for the specific language governing
// permissions and limitations relating to use of the SAFE Network Software.
use crate::crypto::shared_secretbox;
use crate::errors::CoreError;
use crate::ffi::arrays::{SymNonce, SymSecretKey};
use crate::ffi::MDataInfo as FfiMDataInfo;
use crate::ipc::IpcError;
use crate::utils::{symmetric_decrypt, symmetric_encrypt};
use ffi_utils::ReprC;
use rand::{OsRng, Rng};
use routing::{EntryAction, Value, XorName};
use rust_sodium::crypto::secretbox;
use std::collections::{BTreeMap, BTreeSet};
use tiny_keccak::sha3_256;
/// Information allowing to locate and access mutable data on the network.
#[derive(Clone, Debug, Eq, PartialEq, Deserialize, Serialize)]
pub struct MDataInfo {
/// Name of the data where the directory is stored.
pub name: XorName,
/// Type tag of the data where the directory is stored.
pub type_tag: u64,
/// Key to encrypt/decrypt the directory content and the nonce to be used for keys
pub enc_info: Option<(shared_secretbox::Key, secretbox::Nonce)>,
/// Future encryption info, used for two-phase data reencryption.
pub new_enc_info: Option<(shared_secretbox::Key, secretbox::Nonce)>,
}
impl MDataInfo {
/// Construct `MDataInfo` for private (encrypted) data with a provided private key.
pub fn new_private(
name: XorName,
type_tag: u64,
enc_info: (shared_secretbox::Key, secretbox::Nonce),
) -> Self {
MDataInfo {
name,
type_tag,
enc_info: Some(enc_info),
new_enc_info: None,
}
}
/// Construct `MDataInfo` for public data.
pub fn new_public(name: XorName, type_tag: u64) -> Self {
MDataInfo {
name,
type_tag,
enc_info: None,
new_enc_info: None,
}
}
/// Generate random `MDataInfo` for private (encrypted) mutable data.
pub fn random_private(type_tag: u64) -> Result<Self, CoreError> {
let mut rng = os_rng()?;
let enc_info = (shared_secretbox::gen_key(), secretbox::gen_nonce());
Ok(Self::new_private(rng.gen(), type_tag, enc_info))
}
/// Generate random `MDataInfo` for public mutable data.
pub fn random_public(type_tag: u64) -> Result<Self, CoreError> {
let mut rng = os_rng()?;
Ok(Self::new_public(rng.gen(), type_tag))
}
/// Returns the encryption key, if any.
pub fn enc_key(&self) -> Option<&shared_secretbox::Key> {
self.enc_info.as_ref().map(|&(ref key, _)| key)
}
/// Returns the nonce, if any.
pub fn nonce(&self) -> Option<&secretbox::Nonce> {
self.enc_info.as_ref().map(|&(_, ref nonce)| nonce)
}
/// Encrypt the key for the mdata entry accordingly.
pub fn enc_entry_key(&self, plain_text: &[u8]) -> Result<Vec<u8>, CoreError> {
if let Some((ref key, seed)) = self.new_enc_info {
enc_entry_key(plain_text, key, seed)
} else if let Some((ref key, seed)) = self.enc_info {
enc_entry_key(plain_text, key, seed)
} else {
Ok(plain_text.to_vec())
}
}
/// Encrypt the value for this mdata entry accordingly.
pub fn enc_entry_value(&self, plain_text: &[u8]) -> Result<Vec<u8>, CoreError> {
if let Some((ref key, _)) = self.new_enc_info {
symmetric_encrypt(plain_text, key, None)
} else if let Some((ref key, _)) = self.enc_info {
symmetric_encrypt(plain_text, key, None)
} else {
Ok(plain_text.to_vec())
}
}
/// Decrypt key or value of this mdata entry.
pub fn decrypt(&self, cipher: &[u8]) -> Result<Vec<u8>, CoreError> {
if let Some((ref key, _)) = self.new_enc_info {
if let Ok(plain) = symmetric_decrypt(cipher, key) {
return Ok(plain);
}
}
if let Some((ref key, _)) = self.enc_info {
symmetric_decrypt(cipher, key)
} else {
Ok(cipher.to_vec())
}
}
/// Start the encryption info re-generation by populating the `new_enc_info`
/// field with random keys, unless it's already populated.
pub fn start_new_enc_info(&mut self) {
if self.enc_info.is_some() && self.new_enc_info.is_none() {
self.new_enc_info = Some((shared_secretbox::gen_key(), secretbox::gen_nonce()));
}
}
/// Commit the encryption info re-generation by replacing the current encryption info
/// with `new_enc_info` (if any).
pub fn | (&mut self) {
if let Some(new_enc_info) = self.new_enc_info.take() {
self.enc_info = Some(new_enc_info);
}
}
/// Construct FFI wrapper for the native Rust object, consuming self.
pub fn into_repr_c(self) -> FfiMDataInfo {
let (has_enc_info, enc_key, enc_nonce) = enc_info_into_repr_c(self.enc_info);
let (has_new_enc_info, new_enc_key, new_enc_nonce) =
enc_info_into_repr_c(self.new_enc_info);
FfiMDataInfo {
name: self.name.0,
type_tag: self.type_tag,
has_enc_info,
enc_key,
enc_nonce,
has_new_enc_info,
new_enc_key,
new_enc_nonce,
}
}
}
fn os_rng() -> Result<OsRng, CoreError> {
OsRng::new().map_err(|_| CoreError::RandomDataGenerationFailure)
}
/// Encrypt the entries (both keys and values) using the `MDataInfo`.
pub fn encrypt_entries(
info: &MDataInfo,
entries: &BTreeMap<Vec<u8>, Value>,
) -> Result<BTreeMap<Vec<u8>, Value>, CoreError> {
let mut output = BTreeMap::new();
for (key, value) in entries {
let encrypted_key = info.enc_entry_key(key)?;
let encrypted_value = encrypt_value(info, value)?;
let _ = output.insert(encrypted_key, encrypted_value);
}
Ok(output)
}
/// Encrypt entry actions using the `MDataInfo`. The effect of this is that the entries
/// mutated by the encrypted actions will end up encrypted using the `MDataInfo`.
pub fn encrypt_entry_actions(
info: &MDataInfo,
actions: &BTreeMap<Vec<u8>, EntryAction>,
) -> Result<BTreeMap<Vec<u8>, EntryAction>, CoreError> {
let mut output = BTreeMap::new();
for (key, action) in actions {
let encrypted_key = info.enc_entry_key(key)?;
let encrypted_action = match *action {
EntryAction::Ins(ref value) => EntryAction::Ins(encrypt_value(info, value)?),
EntryAction::Update(ref value) => EntryAction::Update(encrypt_value(info, value)?),
EntryAction::Del(version) => EntryAction::Del(version),
};
let _ = output.insert(encrypted_key, encrypted_action);
}
Ok(output)
}
/// Decrypt entries using the `MDataInfo`.
pub fn decrypt_entries(
info: &MDataInfo,
entries: &BTreeMap<Vec<u8>, Value>,
) -> Result<BTreeMap<Vec<u8>, Value>, CoreError> {
let mut output = BTreeMap::new();
for (key, value) in entries {
let decrypted_key = info.decrypt(key)?;
let decrypted_value = decrypt_value(info, value)?;
let _ = output.insert(decrypted_key, decrypted_value);
}
Ok(output)
}
/// Decrypt all keys using the `MDataInfo`.
pub fn decrypt_keys(
info: &MDataInfo,
keys: &BTreeSet<Vec<u8>>,
) -> Result<BTreeSet<Vec<u8>>, CoreError> {
let mut output = BTreeSet::new();
for key in keys {
let _ = output.insert(info.decrypt(key)?);
}
Ok(output)
}
/// Decrypt all values using the `MDataInfo`.
pub fn decrypt_values(info: &MDataInfo, values: &[Value]) -> Result<Vec<Value>, CoreError> {
let mut output = Vec::with_capacity(values.len());
for value in values {
output.push(decrypt_value(info, value)?);
}
Ok(output)
}
fn encrypt_value(info: &MDataInfo, value: &Value) -> Result<Value, CoreError> {
Ok(Value {
content: info.enc_entry_value(&value.content)?,
entry_version: value.entry_version,
})
}
fn decrypt_value(info: &MDataInfo, value: &Value) -> Result<Value, CoreError> {
Ok(Value {
content: info.decrypt(&value.content)?,
entry_version: value.entry_version,
})
}
fn enc_entry_key(
plain_text: &[u8],
key: &secretbox::Key,
seed: secretbox::Nonce,
) -> Result<Vec<u8>, CoreError> {
let nonce = {
let secretbox::Nonce(ref nonce) = seed;
let mut pt = plain_text.to_vec();
pt.extend_from_slice(&nonce[..]);
unwrap!(secretbox::Nonce::from_slice(
&sha3_256(&pt)[..secretbox::NONCEBYTES],
))
};
symmetric_encrypt(plain_text, key, Some(&nonce))
}
impl ReprC for MDataInfo {
type C = *const FfiMDataInfo;
type Error = IpcError;
#[allow(unsafe_code)]
unsafe fn clone_from_repr_c(repr_c: Self::C) -> Result<Self, Self::Error> {
let FfiMDataInfo {
name,
type_tag,
has_enc_info,
enc_key,
enc_nonce,
has_new_enc_info,
new_enc_key,
new_enc_nonce,
} = *repr_c;
Ok(Self {
name: XorName(name),
type_tag,
enc_info: enc_info_from_repr_c(has_enc_info, enc_key, enc_nonce),
new_enc_info: enc_info_from_repr_c(has_new_enc_info, new_enc_key, new_enc_nonce),
})
}
}
fn enc_info_into_repr_c(
info: Option<(shared_secretbox::Key, secretbox::Nonce)>,
) -> (bool, SymSecretKey, SymNonce) {
if let Some((key, nonce)) = info {
(true, key.0, nonce.0)
} else {
(false, Default::default(), Default::default())
}
}
fn enc_info_from_repr_c(
is_set: bool,
key: SymSecretKey,
nonce: SymNonce,
) -> Option<(shared_secretbox::Key, secretbox::Nonce)> {
if is_set {
Some((
shared_secretbox::Key::from_raw(&key),
secretbox::Nonce(nonce),
))
} else {
None
}
}
#[cfg(test)]
mod tests {
use super::*;
// Ensure that a private mdata info is encrypted.
#[test]
fn private_mdata_info_encrypts() {
let info = unwrap!(MDataInfo::random_private(0));
let key = Vec::from("str of key");
let val = Vec::from("other is value");
let enc_key = unwrap!(info.enc_entry_key(&key));
let enc_val = unwrap!(info.enc_entry_value(&val));
assert_ne!(enc_key, key);
assert_ne!(enc_val, val);
assert_eq!(unwrap!(info.decrypt(&enc_key)), key);
assert_eq!(unwrap!(info.decrypt(&enc_val)), val);
}
// Ensure that a public mdata info is not encrypted.
#[test]
fn public_mdata_info_doesnt_encrypt() {
let info = unwrap!(MDataInfo::random_public(0));
let key = Vec::from("str of key");
let val = Vec::from("other is value");
assert_eq!(unwrap!(info.enc_entry_key(&key)), key);
assert_eq!(unwrap!(info.enc_entry_value(&val)), val);
assert_eq!(unwrap!(info.decrypt(&val)), val);
}
// Test creating and committing new encryption info.
#[test]
fn decrypt() {
let mut info = unwrap!(MDataInfo::random_private(0));
let plain = Vec::from("plaintext");
let old_cipher = unwrap!(info.enc_entry_value(&plain));
info.start_new_enc_info();
let new_cipher = unwrap!(info.enc_entry_value(&plain));
// After start, both encryption infos work.
assert_eq!(unwrap!(info.decrypt(&old_cipher)), plain);
assert_eq!(unwrap!(info.decrypt(&new_cipher)), plain);
// After commit, only the new encryption info works.
info.commit_new_enc_info();
match info.decrypt(&old_cipher) {
Err(CoreError::SymmetricDecipherFailure) => (),
x => panic!("Unexpected {:?}", x),
}
assert_eq!(unwrap!(info.decrypt(&new_cipher)), plain);
}
}
| commit_new_enc_info | identifier_name |
mdata_info.rs | // Copyright 2018 MaidSafe.net limited.
//
// This SAFE Network Software is licensed to you under The General Public License (GPL), version 3.
// Unless required by applicable law or agreed to in writing, the SAFE Network Software distributed
// under the GPL Licence is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
// KIND, either express or implied. Please review the Licences for the specific language governing
// permissions and limitations relating to use of the SAFE Network Software.
use crate::crypto::shared_secretbox;
use crate::errors::CoreError;
use crate::ffi::arrays::{SymNonce, SymSecretKey};
use crate::ffi::MDataInfo as FfiMDataInfo;
use crate::ipc::IpcError;
use crate::utils::{symmetric_decrypt, symmetric_encrypt};
use ffi_utils::ReprC;
use rand::{OsRng, Rng};
use routing::{EntryAction, Value, XorName};
use rust_sodium::crypto::secretbox;
use std::collections::{BTreeMap, BTreeSet};
use tiny_keccak::sha3_256;
/// Information allowing to locate and access mutable data on the network.
#[derive(Clone, Debug, Eq, PartialEq, Deserialize, Serialize)]
pub struct MDataInfo {
/// Name of the data where the directory is stored.
pub name: XorName,
/// Type tag of the data where the directory is stored.
pub type_tag: u64,
/// Key to encrypt/decrypt the directory content and the nonce to be used for keys
pub enc_info: Option<(shared_secretbox::Key, secretbox::Nonce)>,
/// Future encryption info, used for two-phase data reencryption.
pub new_enc_info: Option<(shared_secretbox::Key, secretbox::Nonce)>,
}
impl MDataInfo {
/// Construct `MDataInfo` for private (encrypted) data with a provided private key.
pub fn new_private(
name: XorName,
type_tag: u64,
enc_info: (shared_secretbox::Key, secretbox::Nonce),
) -> Self {
MDataInfo {
name,
type_tag,
enc_info: Some(enc_info),
new_enc_info: None,
}
}
/// Construct `MDataInfo` for public data.
pub fn new_public(name: XorName, type_tag: u64) -> Self {
MDataInfo {
name,
type_tag,
enc_info: None,
new_enc_info: None,
}
}
/// Generate random `MDataInfo` for private (encrypted) mutable data.
pub fn random_private(type_tag: u64) -> Result<Self, CoreError> {
let mut rng = os_rng()?;
let enc_info = (shared_secretbox::gen_key(), secretbox::gen_nonce());
Ok(Self::new_private(rng.gen(), type_tag, enc_info))
}
/// Generate random `MDataInfo` for public mutable data.
pub fn random_public(type_tag: u64) -> Result<Self, CoreError> {
let mut rng = os_rng()?;
Ok(Self::new_public(rng.gen(), type_tag))
}
/// Returns the encryption key, if any.
pub fn enc_key(&self) -> Option<&shared_secretbox::Key> {
self.enc_info.as_ref().map(|&(ref key, _)| key)
}
/// Returns the nonce, if any.
pub fn nonce(&self) -> Option<&secretbox::Nonce> {
self.enc_info.as_ref().map(|&(_, ref nonce)| nonce)
}
/// Encrypt the key for the mdata entry accordingly.
pub fn enc_entry_key(&self, plain_text: &[u8]) -> Result<Vec<u8>, CoreError> {
if let Some((ref key, seed)) = self.new_enc_info {
enc_entry_key(plain_text, key, seed)
} else if let Some((ref key, seed)) = self.enc_info {
enc_entry_key(plain_text, key, seed)
} else {
Ok(plain_text.to_vec())
}
}
/// Encrypt the value for this mdata entry accordingly.
pub fn enc_entry_value(&self, plain_text: &[u8]) -> Result<Vec<u8>, CoreError> {
if let Some((ref key, _)) = self.new_enc_info {
symmetric_encrypt(plain_text, key, None)
} else if let Some((ref key, _)) = self.enc_info {
symmetric_encrypt(plain_text, key, None)
} else {
Ok(plain_text.to_vec())
}
}
/// Decrypt key or value of this mdata entry.
pub fn decrypt(&self, cipher: &[u8]) -> Result<Vec<u8>, CoreError> {
if let Some((ref key, _)) = self.new_enc_info {
if let Ok(plain) = symmetric_decrypt(cipher, key) {
return Ok(plain);
}
}
if let Some((ref key, _)) = self.enc_info {
symmetric_decrypt(cipher, key)
} else {
Ok(cipher.to_vec())
}
}
/// Start the encryption info re-generation by populating the `new_enc_info`
/// field with random keys, unless it's already populated.
pub fn start_new_enc_info(&mut self) {
if self.enc_info.is_some() && self.new_enc_info.is_none() {
self.new_enc_info = Some((shared_secretbox::gen_key(), secretbox::gen_nonce()));
}
}
/// Commit the encryption info re-generation by replacing the current encryption info
/// with `new_enc_info` (if any).
pub fn commit_new_enc_info(&mut self) {
if let Some(new_enc_info) = self.new_enc_info.take() {
self.enc_info = Some(new_enc_info);
}
}
/// Construct FFI wrapper for the native Rust object, consuming self.
pub fn into_repr_c(self) -> FfiMDataInfo {
let (has_enc_info, enc_key, enc_nonce) = enc_info_into_repr_c(self.enc_info);
let (has_new_enc_info, new_enc_key, new_enc_nonce) =
enc_info_into_repr_c(self.new_enc_info);
FfiMDataInfo {
name: self.name.0,
type_tag: self.type_tag,
has_enc_info,
enc_key,
enc_nonce,
has_new_enc_info,
new_enc_key,
new_enc_nonce,
}
}
}
fn os_rng() -> Result<OsRng, CoreError> {
OsRng::new().map_err(|_| CoreError::RandomDataGenerationFailure)
}
/// Encrypt the entries (both keys and values) using the `MDataInfo`.
pub fn encrypt_entries(
info: &MDataInfo,
entries: &BTreeMap<Vec<u8>, Value>,
) -> Result<BTreeMap<Vec<u8>, Value>, CoreError> {
let mut output = BTreeMap::new();
for (key, value) in entries {
let encrypted_key = info.enc_entry_key(key)?;
let encrypted_value = encrypt_value(info, value)?;
let _ = output.insert(encrypted_key, encrypted_value);
}
Ok(output)
}
/// Encrypt entry actions using the `MDataInfo`. The effect of this is that the entries
/// mutated by the encrypted actions will end up encrypted using the `MDataInfo`.
pub fn encrypt_entry_actions(
info: &MDataInfo,
actions: &BTreeMap<Vec<u8>, EntryAction>,
) -> Result<BTreeMap<Vec<u8>, EntryAction>, CoreError> {
let mut output = BTreeMap::new();
for (key, action) in actions {
let encrypted_key = info.enc_entry_key(key)?;
let encrypted_action = match *action {
EntryAction::Ins(ref value) => EntryAction::Ins(encrypt_value(info, value)?),
EntryAction::Update(ref value) => EntryAction::Update(encrypt_value(info, value)?),
EntryAction::Del(version) => EntryAction::Del(version),
};
let _ = output.insert(encrypted_key, encrypted_action);
}
Ok(output)
}
/// Decrypt entries using the `MDataInfo`.
pub fn decrypt_entries(
info: &MDataInfo,
entries: &BTreeMap<Vec<u8>, Value>,
) -> Result<BTreeMap<Vec<u8>, Value>, CoreError> {
let mut output = BTreeMap::new();
for (key, value) in entries {
let decrypted_key = info.decrypt(key)?;
let decrypted_value = decrypt_value(info, value)?;
let _ = output.insert(decrypted_key, decrypted_value);
}
Ok(output)
}
/// Decrypt all keys using the `MDataInfo`.
pub fn decrypt_keys(
info: &MDataInfo,
keys: &BTreeSet<Vec<u8>>,
) -> Result<BTreeSet<Vec<u8>>, CoreError> {
let mut output = BTreeSet::new();
for key in keys {
let _ = output.insert(info.decrypt(key)?);
}
Ok(output)
}
/// Decrypt all values using the `MDataInfo`.
pub fn decrypt_values(info: &MDataInfo, values: &[Value]) -> Result<Vec<Value>, CoreError> {
let mut output = Vec::with_capacity(values.len());
for value in values {
output.push(decrypt_value(info, value)?);
} |
Ok(output)
}
fn encrypt_value(info: &MDataInfo, value: &Value) -> Result<Value, CoreError> {
Ok(Value {
content: info.enc_entry_value(&value.content)?,
entry_version: value.entry_version,
})
}
fn decrypt_value(info: &MDataInfo, value: &Value) -> Result<Value, CoreError> {
Ok(Value {
content: info.decrypt(&value.content)?,
entry_version: value.entry_version,
})
}
fn enc_entry_key(
plain_text: &[u8],
key: &secretbox::Key,
seed: secretbox::Nonce,
) -> Result<Vec<u8>, CoreError> {
let nonce = {
let secretbox::Nonce(ref nonce) = seed;
let mut pt = plain_text.to_vec();
pt.extend_from_slice(&nonce[..]);
unwrap!(secretbox::Nonce::from_slice(
&sha3_256(&pt)[..secretbox::NONCEBYTES],
))
};
symmetric_encrypt(plain_text, key, Some(&nonce))
}
impl ReprC for MDataInfo {
type C = *const FfiMDataInfo;
type Error = IpcError;
#[allow(unsafe_code)]
unsafe fn clone_from_repr_c(repr_c: Self::C) -> Result<Self, Self::Error> {
let FfiMDataInfo {
name,
type_tag,
has_enc_info,
enc_key,
enc_nonce,
has_new_enc_info,
new_enc_key,
new_enc_nonce,
} = *repr_c;
Ok(Self {
name: XorName(name),
type_tag,
enc_info: enc_info_from_repr_c(has_enc_info, enc_key, enc_nonce),
new_enc_info: enc_info_from_repr_c(has_new_enc_info, new_enc_key, new_enc_nonce),
})
}
}
fn enc_info_into_repr_c(
info: Option<(shared_secretbox::Key, secretbox::Nonce)>,
) -> (bool, SymSecretKey, SymNonce) {
if let Some((key, nonce)) = info {
(true, key.0, nonce.0)
} else {
(false, Default::default(), Default::default())
}
}
fn enc_info_from_repr_c(
is_set: bool,
key: SymSecretKey,
nonce: SymNonce,
) -> Option<(shared_secretbox::Key, secretbox::Nonce)> {
if is_set {
Some((
shared_secretbox::Key::from_raw(&key),
secretbox::Nonce(nonce),
))
} else {
None
}
}
#[cfg(test)]
mod tests {
use super::*;
// Ensure that a private mdata info is encrypted.
#[test]
fn private_mdata_info_encrypts() {
let info = unwrap!(MDataInfo::random_private(0));
let key = Vec::from("str of key");
let val = Vec::from("other is value");
let enc_key = unwrap!(info.enc_entry_key(&key));
let enc_val = unwrap!(info.enc_entry_value(&val));
assert_ne!(enc_key, key);
assert_ne!(enc_val, val);
assert_eq!(unwrap!(info.decrypt(&enc_key)), key);
assert_eq!(unwrap!(info.decrypt(&enc_val)), val);
}
// Ensure that a public mdata info is not encrypted.
#[test]
fn public_mdata_info_doesnt_encrypt() {
let info = unwrap!(MDataInfo::random_public(0));
let key = Vec::from("str of key");
let val = Vec::from("other is value");
assert_eq!(unwrap!(info.enc_entry_key(&key)), key);
assert_eq!(unwrap!(info.enc_entry_value(&val)), val);
assert_eq!(unwrap!(info.decrypt(&val)), val);
}
// Test creating and committing new encryption info.
#[test]
fn decrypt() {
let mut info = unwrap!(MDataInfo::random_private(0));
let plain = Vec::from("plaintext");
let old_cipher = unwrap!(info.enc_entry_value(&plain));
info.start_new_enc_info();
let new_cipher = unwrap!(info.enc_entry_value(&plain));
// After start, both encryption infos work.
assert_eq!(unwrap!(info.decrypt(&old_cipher)), plain);
assert_eq!(unwrap!(info.decrypt(&new_cipher)), plain);
// After commit, only the new encryption info works.
info.commit_new_enc_info();
match info.decrypt(&old_cipher) {
Err(CoreError::SymmetricDecipherFailure) => (),
x => panic!("Unexpected {:?}", x),
}
assert_eq!(unwrap!(info.decrypt(&new_cipher)), plain);
}
} | random_line_split | |
mdata_info.rs | // Copyright 2018 MaidSafe.net limited.
//
// This SAFE Network Software is licensed to you under The General Public License (GPL), version 3.
// Unless required by applicable law or agreed to in writing, the SAFE Network Software distributed
// under the GPL Licence is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
// KIND, either express or implied. Please review the Licences for the specific language governing
// permissions and limitations relating to use of the SAFE Network Software.
use crate::crypto::shared_secretbox;
use crate::errors::CoreError;
use crate::ffi::arrays::{SymNonce, SymSecretKey};
use crate::ffi::MDataInfo as FfiMDataInfo;
use crate::ipc::IpcError;
use crate::utils::{symmetric_decrypt, symmetric_encrypt};
use ffi_utils::ReprC;
use rand::{OsRng, Rng};
use routing::{EntryAction, Value, XorName};
use rust_sodium::crypto::secretbox;
use std::collections::{BTreeMap, BTreeSet};
use tiny_keccak::sha3_256;
/// Information allowing to locate and access mutable data on the network.
#[derive(Clone, Debug, Eq, PartialEq, Deserialize, Serialize)]
pub struct MDataInfo {
/// Name of the data where the directory is stored.
pub name: XorName,
/// Type tag of the data where the directory is stored.
pub type_tag: u64,
/// Key to encrypt/decrypt the directory content and the nonce to be used for keys
pub enc_info: Option<(shared_secretbox::Key, secretbox::Nonce)>,
/// Future encryption info, used for two-phase data reencryption.
pub new_enc_info: Option<(shared_secretbox::Key, secretbox::Nonce)>,
}
impl MDataInfo {
/// Construct `MDataInfo` for private (encrypted) data with a provided private key.
pub fn new_private(
name: XorName,
type_tag: u64,
enc_info: (shared_secretbox::Key, secretbox::Nonce),
) -> Self {
MDataInfo {
name,
type_tag,
enc_info: Some(enc_info),
new_enc_info: None,
}
}
/// Construct `MDataInfo` for public data.
pub fn new_public(name: XorName, type_tag: u64) -> Self {
MDataInfo {
name,
type_tag,
enc_info: None,
new_enc_info: None,
}
}
/// Generate random `MDataInfo` for private (encrypted) mutable data.
pub fn random_private(type_tag: u64) -> Result<Self, CoreError> {
let mut rng = os_rng()?;
let enc_info = (shared_secretbox::gen_key(), secretbox::gen_nonce());
Ok(Self::new_private(rng.gen(), type_tag, enc_info))
}
/// Generate random `MDataInfo` for public mutable data.
pub fn random_public(type_tag: u64) -> Result<Self, CoreError> {
let mut rng = os_rng()?;
Ok(Self::new_public(rng.gen(), type_tag))
}
/// Returns the encryption key, if any.
pub fn enc_key(&self) -> Option<&shared_secretbox::Key> {
self.enc_info.as_ref().map(|&(ref key, _)| key)
}
/// Returns the nonce, if any.
pub fn nonce(&self) -> Option<&secretbox::Nonce> {
self.enc_info.as_ref().map(|&(_, ref nonce)| nonce)
}
/// Encrypt the key for the mdata entry accordingly.
pub fn enc_entry_key(&self, plain_text: &[u8]) -> Result<Vec<u8>, CoreError> {
if let Some((ref key, seed)) = self.new_enc_info {
enc_entry_key(plain_text, key, seed)
} else if let Some((ref key, seed)) = self.enc_info {
enc_entry_key(plain_text, key, seed)
} else {
Ok(plain_text.to_vec())
}
}
/// Encrypt the value for this mdata entry accordingly.
pub fn enc_entry_value(&self, plain_text: &[u8]) -> Result<Vec<u8>, CoreError> {
if let Some((ref key, _)) = self.new_enc_info {
symmetric_encrypt(plain_text, key, None)
} else if let Some((ref key, _)) = self.enc_info {
symmetric_encrypt(plain_text, key, None)
} else {
Ok(plain_text.to_vec())
}
}
/// Decrypt key or value of this mdata entry.
pub fn decrypt(&self, cipher: &[u8]) -> Result<Vec<u8>, CoreError> {
if let Some((ref key, _)) = self.new_enc_info {
if let Ok(plain) = symmetric_decrypt(cipher, key) {
return Ok(plain);
}
}
if let Some((ref key, _)) = self.enc_info {
symmetric_decrypt(cipher, key)
} else {
Ok(cipher.to_vec())
}
}
/// Start the encryption info re-generation by populating the `new_enc_info`
/// field with random keys, unless it's already populated.
pub fn start_new_enc_info(&mut self) {
if self.enc_info.is_some() && self.new_enc_info.is_none() {
self.new_enc_info = Some((shared_secretbox::gen_key(), secretbox::gen_nonce()));
}
}
/// Commit the encryption info re-generation by replacing the current encryption info
/// with `new_enc_info` (if any).
pub fn commit_new_enc_info(&mut self) {
if let Some(new_enc_info) = self.new_enc_info.take() {
self.enc_info = Some(new_enc_info);
}
}
/// Construct FFI wrapper for the native Rust object, consuming self.
pub fn into_repr_c(self) -> FfiMDataInfo {
let (has_enc_info, enc_key, enc_nonce) = enc_info_into_repr_c(self.enc_info);
let (has_new_enc_info, new_enc_key, new_enc_nonce) =
enc_info_into_repr_c(self.new_enc_info);
FfiMDataInfo {
name: self.name.0,
type_tag: self.type_tag,
has_enc_info,
enc_key,
enc_nonce,
has_new_enc_info,
new_enc_key,
new_enc_nonce,
}
}
}
fn os_rng() -> Result<OsRng, CoreError> {
OsRng::new().map_err(|_| CoreError::RandomDataGenerationFailure)
}
/// Encrypt the entries (both keys and values) using the `MDataInfo`.
pub fn encrypt_entries(
info: &MDataInfo,
entries: &BTreeMap<Vec<u8>, Value>,
) -> Result<BTreeMap<Vec<u8>, Value>, CoreError> {
let mut output = BTreeMap::new();
for (key, value) in entries {
let encrypted_key = info.enc_entry_key(key)?;
let encrypted_value = encrypt_value(info, value)?;
let _ = output.insert(encrypted_key, encrypted_value);
}
Ok(output)
}
/// Encrypt entry actions using the `MDataInfo`. The effect of this is that the entries
/// mutated by the encrypted actions will end up encrypted using the `MDataInfo`.
pub fn encrypt_entry_actions(
info: &MDataInfo,
actions: &BTreeMap<Vec<u8>, EntryAction>,
) -> Result<BTreeMap<Vec<u8>, EntryAction>, CoreError> {
let mut output = BTreeMap::new();
for (key, action) in actions {
let encrypted_key = info.enc_entry_key(key)?;
let encrypted_action = match *action {
EntryAction::Ins(ref value) => EntryAction::Ins(encrypt_value(info, value)?),
EntryAction::Update(ref value) => EntryAction::Update(encrypt_value(info, value)?),
EntryAction::Del(version) => EntryAction::Del(version),
};
let _ = output.insert(encrypted_key, encrypted_action);
}
Ok(output)
}
/// Decrypt entries using the `MDataInfo`.
pub fn decrypt_entries(
info: &MDataInfo,
entries: &BTreeMap<Vec<u8>, Value>,
) -> Result<BTreeMap<Vec<u8>, Value>, CoreError> {
let mut output = BTreeMap::new();
for (key, value) in entries {
let decrypted_key = info.decrypt(key)?;
let decrypted_value = decrypt_value(info, value)?;
let _ = output.insert(decrypted_key, decrypted_value);
}
Ok(output)
}
/// Decrypt all keys using the `MDataInfo`.
pub fn decrypt_keys(
info: &MDataInfo,
keys: &BTreeSet<Vec<u8>>,
) -> Result<BTreeSet<Vec<u8>>, CoreError> {
let mut output = BTreeSet::new();
for key in keys {
let _ = output.insert(info.decrypt(key)?);
}
Ok(output)
}
/// Decrypt all values using the `MDataInfo`.
pub fn decrypt_values(info: &MDataInfo, values: &[Value]) -> Result<Vec<Value>, CoreError> |
fn encrypt_value(info: &MDataInfo, value: &Value) -> Result<Value, CoreError> {
Ok(Value {
content: info.enc_entry_value(&value.content)?,
entry_version: value.entry_version,
})
}
fn decrypt_value(info: &MDataInfo, value: &Value) -> Result<Value, CoreError> {
Ok(Value {
content: info.decrypt(&value.content)?,
entry_version: value.entry_version,
})
}
fn enc_entry_key(
plain_text: &[u8],
key: &secretbox::Key,
seed: secretbox::Nonce,
) -> Result<Vec<u8>, CoreError> {
let nonce = {
let secretbox::Nonce(ref nonce) = seed;
let mut pt = plain_text.to_vec();
pt.extend_from_slice(&nonce[..]);
unwrap!(secretbox::Nonce::from_slice(
&sha3_256(&pt)[..secretbox::NONCEBYTES],
))
};
symmetric_encrypt(plain_text, key, Some(&nonce))
}
impl ReprC for MDataInfo {
type C = *const FfiMDataInfo;
type Error = IpcError;
#[allow(unsafe_code)]
unsafe fn clone_from_repr_c(repr_c: Self::C) -> Result<Self, Self::Error> {
let FfiMDataInfo {
name,
type_tag,
has_enc_info,
enc_key,
enc_nonce,
has_new_enc_info,
new_enc_key,
new_enc_nonce,
} = *repr_c;
Ok(Self {
name: XorName(name),
type_tag,
enc_info: enc_info_from_repr_c(has_enc_info, enc_key, enc_nonce),
new_enc_info: enc_info_from_repr_c(has_new_enc_info, new_enc_key, new_enc_nonce),
})
}
}
fn enc_info_into_repr_c(
info: Option<(shared_secretbox::Key, secretbox::Nonce)>,
) -> (bool, SymSecretKey, SymNonce) {
if let Some((key, nonce)) = info {
(true, key.0, nonce.0)
} else {
(false, Default::default(), Default::default())
}
}
fn enc_info_from_repr_c(
is_set: bool,
key: SymSecretKey,
nonce: SymNonce,
) -> Option<(shared_secretbox::Key, secretbox::Nonce)> {
if is_set {
Some((
shared_secretbox::Key::from_raw(&key),
secretbox::Nonce(nonce),
))
} else {
None
}
}
#[cfg(test)]
mod tests {
use super::*;
// Ensure that a private mdata info is encrypted.
#[test]
fn private_mdata_info_encrypts() {
let info = unwrap!(MDataInfo::random_private(0));
let key = Vec::from("str of key");
let val = Vec::from("other is value");
let enc_key = unwrap!(info.enc_entry_key(&key));
let enc_val = unwrap!(info.enc_entry_value(&val));
assert_ne!(enc_key, key);
assert_ne!(enc_val, val);
assert_eq!(unwrap!(info.decrypt(&enc_key)), key);
assert_eq!(unwrap!(info.decrypt(&enc_val)), val);
}
// Ensure that a public mdata info is not encrypted.
#[test]
fn public_mdata_info_doesnt_encrypt() {
let info = unwrap!(MDataInfo::random_public(0));
let key = Vec::from("str of key");
let val = Vec::from("other is value");
assert_eq!(unwrap!(info.enc_entry_key(&key)), key);
assert_eq!(unwrap!(info.enc_entry_value(&val)), val);
assert_eq!(unwrap!(info.decrypt(&val)), val);
}
// Test creating and committing new encryption info.
#[test]
fn decrypt() {
let mut info = unwrap!(MDataInfo::random_private(0));
let plain = Vec::from("plaintext");
let old_cipher = unwrap!(info.enc_entry_value(&plain));
info.start_new_enc_info();
let new_cipher = unwrap!(info.enc_entry_value(&plain));
// After start, both encryption infos work.
assert_eq!(unwrap!(info.decrypt(&old_cipher)), plain);
assert_eq!(unwrap!(info.decrypt(&new_cipher)), plain);
// After commit, only the new encryption info works.
info.commit_new_enc_info();
match info.decrypt(&old_cipher) {
Err(CoreError::SymmetricDecipherFailure) => (),
x => panic!("Unexpected {:?}", x),
}
assert_eq!(unwrap!(info.decrypt(&new_cipher)), plain);
}
}
| {
let mut output = Vec::with_capacity(values.len());
for value in values {
output.push(decrypt_value(info, value)?);
}
Ok(output)
} | identifier_body |
sqlalchemy_utils.py | from typing import Any, Optional
import sqlalchemy
from django.db import connection
from zerver.lib.db import TimeTrackingConnection
# This is a Pool that doesn't close connections. Therefore it can be used with
# existing Django database connections.
class NonClosingPool(sqlalchemy.pool.NullPool):
def status(self) -> str:
return "NonClosingPool"
def _do_return_conn(self, conn: sqlalchemy.engine.base.Connection) -> None:
pass
def recreate(self) -> 'NonClosingPool':
return self.__class__(creator=self._creator,
recycle=self._recycle,
use_threadlocal=self._use_threadlocal,
reset_on_return=self._reset_on_return,
echo=self.echo,
logging_name=self._orig_logging_name,
_dispatch=self.dispatch)
sqlalchemy_engine: Optional[Any] = None
def get_sqlalchemy_connection() -> sqlalchemy.engine.base.Connection:
| global sqlalchemy_engine
if sqlalchemy_engine is None:
def get_dj_conn() -> TimeTrackingConnection:
connection.ensure_connection()
return connection.connection
sqlalchemy_engine = sqlalchemy.create_engine('postgresql://',
creator=get_dj_conn,
poolclass=NonClosingPool,
pool_reset_on_return=False)
sa_connection = sqlalchemy_engine.connect()
sa_connection.execution_options(autocommit=False)
return sa_connection | identifier_body | |
sqlalchemy_utils.py | from typing import Any, Optional
import sqlalchemy
from django.db import connection
from zerver.lib.db import TimeTrackingConnection
# This is a Pool that doesn't close connections. Therefore it can be used with
# existing Django database connections.
class NonClosingPool(sqlalchemy.pool.NullPool):
def status(self) -> str:
return "NonClosingPool"
def _do_return_conn(self, conn: sqlalchemy.engine.base.Connection) -> None:
pass
def | (self) -> 'NonClosingPool':
return self.__class__(creator=self._creator,
recycle=self._recycle,
use_threadlocal=self._use_threadlocal,
reset_on_return=self._reset_on_return,
echo=self.echo,
logging_name=self._orig_logging_name,
_dispatch=self.dispatch)
sqlalchemy_engine: Optional[Any] = None
def get_sqlalchemy_connection() -> sqlalchemy.engine.base.Connection:
global sqlalchemy_engine
if sqlalchemy_engine is None:
def get_dj_conn() -> TimeTrackingConnection:
connection.ensure_connection()
return connection.connection
sqlalchemy_engine = sqlalchemy.create_engine('postgresql://',
creator=get_dj_conn,
poolclass=NonClosingPool,
pool_reset_on_return=False)
sa_connection = sqlalchemy_engine.connect()
sa_connection.execution_options(autocommit=False)
return sa_connection
| recreate | identifier_name |
sqlalchemy_utils.py | from typing import Any, Optional
import sqlalchemy
from django.db import connection
from zerver.lib.db import TimeTrackingConnection
# This is a Pool that doesn't close connections. Therefore it can be used with
# existing Django database connections.
class NonClosingPool(sqlalchemy.pool.NullPool):
def status(self) -> str:
return "NonClosingPool"
def _do_return_conn(self, conn: sqlalchemy.engine.base.Connection) -> None:
pass
def recreate(self) -> 'NonClosingPool':
return self.__class__(creator=self._creator,
recycle=self._recycle,
use_threadlocal=self._use_threadlocal,
reset_on_return=self._reset_on_return,
echo=self.echo,
logging_name=self._orig_logging_name,
_dispatch=self.dispatch)
sqlalchemy_engine: Optional[Any] = None
def get_sqlalchemy_connection() -> sqlalchemy.engine.base.Connection:
global sqlalchemy_engine
if sqlalchemy_engine is None:
|
sa_connection = sqlalchemy_engine.connect()
sa_connection.execution_options(autocommit=False)
return sa_connection
| def get_dj_conn() -> TimeTrackingConnection:
connection.ensure_connection()
return connection.connection
sqlalchemy_engine = sqlalchemy.create_engine('postgresql://',
creator=get_dj_conn,
poolclass=NonClosingPool,
pool_reset_on_return=False) | conditional_block |
sqlalchemy_utils.py | from typing import Any, Optional
import sqlalchemy
from django.db import connection
from zerver.lib.db import TimeTrackingConnection
# This is a Pool that doesn't close connections. Therefore it can be used with
# existing Django database connections.
class NonClosingPool(sqlalchemy.pool.NullPool):
def status(self) -> str:
return "NonClosingPool"
def _do_return_conn(self, conn: sqlalchemy.engine.base.Connection) -> None:
pass
def recreate(self) -> 'NonClosingPool':
return self.__class__(creator=self._creator,
recycle=self._recycle,
use_threadlocal=self._use_threadlocal,
reset_on_return=self._reset_on_return, | sqlalchemy_engine: Optional[Any] = None
def get_sqlalchemy_connection() -> sqlalchemy.engine.base.Connection:
global sqlalchemy_engine
if sqlalchemy_engine is None:
def get_dj_conn() -> TimeTrackingConnection:
connection.ensure_connection()
return connection.connection
sqlalchemy_engine = sqlalchemy.create_engine('postgresql://',
creator=get_dj_conn,
poolclass=NonClosingPool,
pool_reset_on_return=False)
sa_connection = sqlalchemy_engine.connect()
sa_connection.execution_options(autocommit=False)
return sa_connection | echo=self.echo,
logging_name=self._orig_logging_name,
_dispatch=self.dispatch)
| random_line_split |
random_trees.py | # -*- coding: utf-8 -*-
from __future__ import print_function
from __future__ import unicode_literals
from __future__ import division
from optparse import make_option
import random
import math
from django.contrib.gis.geos import Point
from treemap.models import Plot, Tree, Species
from treemap.management.util import InstanceDataCommand
class Command(InstanceDataCommand):
option_list = InstanceDataCommand.option_list + (
make_option('-r', '--radius',
action='store',
type='int',
dest='radius',
default=5000,
help='Number of meters from the center'),
make_option('-n', '--number-of-trees',
action='store',
type='int',
dest='n',
default=100000,
help='Number of trees to create'),
make_option('-p', '--prob-of-tree',
action='store',
type='int',
dest='ptree',
default=50,
help=('Probability that a given plot will '
'have a tree (0-100)')),
make_option('-s', '--prob-of-species',
action='store',
type='int',
dest='pspecies',
default=50,
help=('Probability that a given tree will '
'have a species (0-100)')),
make_option('-D', '--prob-of-diameter',
action='store',
type='int',
dest='pdiameter',
default=10,
help=('Probability that a given tree will '
'have a diameter (0-100)')))
def | (self, *args, **options):
""" Create some seed data """
instance, user = self.setup_env(*args, **options)
species_qs = instance.scope_model(Species)
n = options['n']
self.stdout.write("Will create %s plots" % n)
get_prob = lambda option: float(min(100, max(0, option))) / 100.0
tree_prob = get_prob(options['ptree'])
species_prob = get_prob(options['pspecies'])
diameter_prob = get_prob(options['pdiameter'])
max_radius = options['radius']
center_x = instance.center.x
center_y = instance.center.y
ct = 0
cp = 0
for i in xrange(0, n):
mktree = random.random() < tree_prob
radius = random.gauss(0.0, max_radius)
theta = random.random() * 2.0 * math.pi
x = math.cos(theta) * radius + center_x
y = math.sin(theta) * radius + center_y
plot = Plot(instance=instance,
geom=Point(x, y))
plot.save_with_user(user)
cp += 1
if mktree:
add_species = random.random() < species_prob
if add_species:
species = random.choice(species_qs)
else:
species = None
add_diameter = random.random() < diameter_prob
if add_diameter:
diameter = 2 + random.random() * 18
else:
diameter = None
tree = Tree(plot=plot,
species=species,
diameter=diameter,
instance=instance)
tree.save_with_user(user)
ct += 1
self.stdout.write("Created %s trees and %s plots" % (ct, cp))
| handle | identifier_name |
random_trees.py | # -*- coding: utf-8 -*-
from __future__ import print_function
from __future__ import unicode_literals
from __future__ import division
from optparse import make_option
import random
import math
from django.contrib.gis.geos import Point
from treemap.models import Plot, Tree, Species
from treemap.management.util import InstanceDataCommand
class Command(InstanceDataCommand):
| option_list = InstanceDataCommand.option_list + (
make_option('-r', '--radius',
action='store',
type='int',
dest='radius',
default=5000,
help='Number of meters from the center'),
make_option('-n', '--number-of-trees',
action='store',
type='int',
dest='n',
default=100000,
help='Number of trees to create'),
make_option('-p', '--prob-of-tree',
action='store',
type='int',
dest='ptree',
default=50,
help=('Probability that a given plot will '
'have a tree (0-100)')),
make_option('-s', '--prob-of-species',
action='store',
type='int',
dest='pspecies',
default=50,
help=('Probability that a given tree will '
'have a species (0-100)')),
make_option('-D', '--prob-of-diameter',
action='store',
type='int',
dest='pdiameter',
default=10,
help=('Probability that a given tree will '
'have a diameter (0-100)')))
def handle(self, *args, **options):
""" Create some seed data """
instance, user = self.setup_env(*args, **options)
species_qs = instance.scope_model(Species)
n = options['n']
self.stdout.write("Will create %s plots" % n)
get_prob = lambda option: float(min(100, max(0, option))) / 100.0
tree_prob = get_prob(options['ptree'])
species_prob = get_prob(options['pspecies'])
diameter_prob = get_prob(options['pdiameter'])
max_radius = options['radius']
center_x = instance.center.x
center_y = instance.center.y
ct = 0
cp = 0
for i in xrange(0, n):
mktree = random.random() < tree_prob
radius = random.gauss(0.0, max_radius)
theta = random.random() * 2.0 * math.pi
x = math.cos(theta) * radius + center_x
y = math.sin(theta) * radius + center_y
plot = Plot(instance=instance,
geom=Point(x, y))
plot.save_with_user(user)
cp += 1
if mktree:
add_species = random.random() < species_prob
if add_species:
species = random.choice(species_qs)
else:
species = None
add_diameter = random.random() < diameter_prob
if add_diameter:
diameter = 2 + random.random() * 18
else:
diameter = None
tree = Tree(plot=plot,
species=species,
diameter=diameter,
instance=instance)
tree.save_with_user(user)
ct += 1
self.stdout.write("Created %s trees and %s plots" % (ct, cp)) | identifier_body | |
random_trees.py | # -*- coding: utf-8 -*-
from __future__ import print_function
from __future__ import unicode_literals
from __future__ import division
from optparse import make_option
import random
import math
from django.contrib.gis.geos import Point
from treemap.models import Plot, Tree, Species
from treemap.management.util import InstanceDataCommand
class Command(InstanceDataCommand):
option_list = InstanceDataCommand.option_list + (
make_option('-r', '--radius',
action='store',
type='int',
dest='radius',
default=5000,
help='Number of meters from the center'),
make_option('-n', '--number-of-trees',
action='store',
type='int',
dest='n',
default=100000,
help='Number of trees to create'),
make_option('-p', '--prob-of-tree',
action='store',
type='int',
dest='ptree',
default=50,
help=('Probability that a given plot will '
'have a tree (0-100)')),
make_option('-s', '--prob-of-species',
action='store',
type='int',
dest='pspecies',
default=50,
help=('Probability that a given tree will '
'have a species (0-100)')),
make_option('-D', '--prob-of-diameter',
action='store',
type='int',
dest='pdiameter',
default=10,
help=('Probability that a given tree will '
'have a diameter (0-100)')))
def handle(self, *args, **options):
""" Create some seed data """
instance, user = self.setup_env(*args, **options)
species_qs = instance.scope_model(Species)
n = options['n']
self.stdout.write("Will create %s plots" % n)
get_prob = lambda option: float(min(100, max(0, option))) / 100.0
tree_prob = get_prob(options['ptree'])
species_prob = get_prob(options['pspecies'])
diameter_prob = get_prob(options['pdiameter'])
max_radius = options['radius']
center_x = instance.center.x
center_y = instance.center.y
ct = 0
cp = 0
for i in xrange(0, n):
mktree = random.random() < tree_prob
radius = random.gauss(0.0, max_radius)
theta = random.random() * 2.0 * math.pi
x = math.cos(theta) * radius + center_x
y = math.sin(theta) * radius + center_y
plot = Plot(instance=instance,
geom=Point(x, y))
plot.save_with_user(user)
cp += 1
if mktree:
|
self.stdout.write("Created %s trees and %s plots" % (ct, cp))
| add_species = random.random() < species_prob
if add_species:
species = random.choice(species_qs)
else:
species = None
add_diameter = random.random() < diameter_prob
if add_diameter:
diameter = 2 + random.random() * 18
else:
diameter = None
tree = Tree(plot=plot,
species=species,
diameter=diameter,
instance=instance)
tree.save_with_user(user)
ct += 1 | conditional_block |
random_trees.py | # -*- coding: utf-8 -*-
from __future__ import print_function
from __future__ import unicode_literals
from __future__ import division
from optparse import make_option
import random
import math
from django.contrib.gis.geos import Point
from treemap.models import Plot, Tree, Species
from treemap.management.util import InstanceDataCommand
class Command(InstanceDataCommand):
option_list = InstanceDataCommand.option_list + (
make_option('-r', '--radius',
action='store',
type='int',
dest='radius',
default=5000,
help='Number of meters from the center'),
make_option('-n', '--number-of-trees',
action='store',
type='int',
dest='n',
default=100000,
help='Number of trees to create'),
make_option('-p', '--prob-of-tree',
action='store',
type='int',
dest='ptree',
default=50,
help=('Probability that a given plot will '
'have a tree (0-100)')),
make_option('-s', '--prob-of-species',
action='store',
type='int',
dest='pspecies',
default=50,
help=('Probability that a given tree will '
'have a species (0-100)')),
make_option('-D', '--prob-of-diameter',
action='store',
type='int',
dest='pdiameter',
default=10,
help=('Probability that a given tree will '
'have a diameter (0-100)')))
def handle(self, *args, **options):
""" Create some seed data """ | self.stdout.write("Will create %s plots" % n)
get_prob = lambda option: float(min(100, max(0, option))) / 100.0
tree_prob = get_prob(options['ptree'])
species_prob = get_prob(options['pspecies'])
diameter_prob = get_prob(options['pdiameter'])
max_radius = options['radius']
center_x = instance.center.x
center_y = instance.center.y
ct = 0
cp = 0
for i in xrange(0, n):
mktree = random.random() < tree_prob
radius = random.gauss(0.0, max_radius)
theta = random.random() * 2.0 * math.pi
x = math.cos(theta) * radius + center_x
y = math.sin(theta) * radius + center_y
plot = Plot(instance=instance,
geom=Point(x, y))
plot.save_with_user(user)
cp += 1
if mktree:
add_species = random.random() < species_prob
if add_species:
species = random.choice(species_qs)
else:
species = None
add_diameter = random.random() < diameter_prob
if add_diameter:
diameter = 2 + random.random() * 18
else:
diameter = None
tree = Tree(plot=plot,
species=species,
diameter=diameter,
instance=instance)
tree.save_with_user(user)
ct += 1
self.stdout.write("Created %s trees and %s plots" % (ct, cp)) | instance, user = self.setup_env(*args, **options)
species_qs = instance.scope_model(Species)
n = options['n'] | random_line_split |
translation_simba.rs | use simba::simd::SimdValue;
use crate::base::allocator::Allocator;
use crate::base::dimension::DimName;
use crate::base::{DefaultAllocator, VectorN};
use crate::Scalar;
use crate::geometry::Translation;
impl<N: Scalar + SimdValue, D: DimName> SimdValue for Translation<N, D>
where
N::Element: Scalar,
DefaultAllocator: Allocator<N, D> + Allocator<N::Element, D>,
{
type Element = Translation<N::Element, D>;
type SimdBool = N::SimdBool;
#[inline]
fn lanes() -> usize {
N::lanes()
}
#[inline]
fn splat(val: Self::Element) -> Self {
VectorN::splat(val.vector).into()
}
#[inline]
fn extract(&self, i: usize) -> Self::Element {
self.vector.extract(i).into()
}
#[inline]
unsafe fn extract_unchecked(&self, i: usize) -> Self::Element {
self.vector.extract_unchecked(i).into()
}
#[inline]
fn replace(&mut self, i: usize, val: Self::Element) |
#[inline]
unsafe fn replace_unchecked(&mut self, i: usize, val: Self::Element) {
self.vector.replace_unchecked(i, val.vector)
}
#[inline]
fn select(self, cond: Self::SimdBool, other: Self) -> Self {
self.vector.select(cond, other.vector).into()
}
}
| {
self.vector.replace(i, val.vector)
} | identifier_body |
translation_simba.rs | use simba::simd::SimdValue;
use crate::base::allocator::Allocator;
use crate::base::dimension::DimName;
use crate::base::{DefaultAllocator, VectorN};
use crate::Scalar;
use crate::geometry::Translation;
impl<N: Scalar + SimdValue, D: DimName> SimdValue for Translation<N, D>
where
N::Element: Scalar,
DefaultAllocator: Allocator<N, D> + Allocator<N::Element, D>,
{
type Element = Translation<N::Element, D>;
type SimdBool = N::SimdBool;
#[inline]
fn lanes() -> usize {
N::lanes()
}
#[inline]
fn splat(val: Self::Element) -> Self { | self.vector.extract(i).into()
}
#[inline]
unsafe fn extract_unchecked(&self, i: usize) -> Self::Element {
self.vector.extract_unchecked(i).into()
}
#[inline]
fn replace(&mut self, i: usize, val: Self::Element) {
self.vector.replace(i, val.vector)
}
#[inline]
unsafe fn replace_unchecked(&mut self, i: usize, val: Self::Element) {
self.vector.replace_unchecked(i, val.vector)
}
#[inline]
fn select(self, cond: Self::SimdBool, other: Self) -> Self {
self.vector.select(cond, other.vector).into()
}
} | VectorN::splat(val.vector).into()
}
#[inline]
fn extract(&self, i: usize) -> Self::Element { | random_line_split |
translation_simba.rs | use simba::simd::SimdValue;
use crate::base::allocator::Allocator;
use crate::base::dimension::DimName;
use crate::base::{DefaultAllocator, VectorN};
use crate::Scalar;
use crate::geometry::Translation;
impl<N: Scalar + SimdValue, D: DimName> SimdValue for Translation<N, D>
where
N::Element: Scalar,
DefaultAllocator: Allocator<N, D> + Allocator<N::Element, D>,
{
type Element = Translation<N::Element, D>;
type SimdBool = N::SimdBool;
#[inline]
fn lanes() -> usize {
N::lanes()
}
#[inline]
fn splat(val: Self::Element) -> Self {
VectorN::splat(val.vector).into()
}
#[inline]
fn extract(&self, i: usize) -> Self::Element {
self.vector.extract(i).into()
}
#[inline]
unsafe fn extract_unchecked(&self, i: usize) -> Self::Element {
self.vector.extract_unchecked(i).into()
}
#[inline]
fn | (&mut self, i: usize, val: Self::Element) {
self.vector.replace(i, val.vector)
}
#[inline]
unsafe fn replace_unchecked(&mut self, i: usize, val: Self::Element) {
self.vector.replace_unchecked(i, val.vector)
}
#[inline]
fn select(self, cond: Self::SimdBool, other: Self) -> Self {
self.vector.select(cond, other.vector).into()
}
}
| replace | identifier_name |
main.rs | #![cfg_attr(feature = "clippy", feature(plugin))]
#![cfg_attr(feature = "clippy", plugin(clippy))]
#[macro_use]
extern crate clap;
extern crate reqwest;
#[macro_use]
extern crate serde_derive;
extern crate toml;
extern crate indicatif;
#[macro_use]
extern crate lazy_static;
#[cfg(test)]
extern crate hyper;
use clap::App;
use reqwest::header::{AUTHORIZATION, USER_AGENT};
use indicatif::{ProgressBar, ProgressStyle};
use std::env;
use std::fs::File;
use std::io::prelude::*;
use std::path::Path;
mod github;
static GITHUB_TOKEN: &'static str = "RP_GITHUBTOKEN";
static USERAGENT: &'static str = "release-party-br";
lazy_static! {
static ref RP_VERSION: String = {
let yaml = load_yaml!("release-party.yml");
let app = App::from_yaml(yaml);
version_string(&app)
};
}
fn main() {
let yaml = load_yaml!("release-party.yml");
let matches = App::from_yaml(yaml).get_matches();
let org_url = make_org_url(&matches);
let token = match env::var(GITHUB_TOKEN) {
Ok(env_var) => env_var,
Err(_) => {
print_message_and_exit(
&format!("{} environment variable should be set", GITHUB_TOKEN),
-1,
);
unreachable!();
}
};
let reqwest_client = get_reqwest_client(&token);
let links = get_pr_links(
&get_repos_we_care_about(&org_url, &reqwest_client),
&reqwest_client,
is_dryrun(&matches),
);
print_party_links(links);
}
fn version_string(app: &App) -> String {
let mut version: Vec<u8> = Vec::new();
app.write_version(&mut version)
.expect("Should write to version vec.");
String::from_utf8(version).expect("Version text should be utf8 text")
}
fn is_dryrun(matches: &clap::ArgMatches) -> bool {
matches.is_present("DRYRUN")
}
fn org_is_just_org(org: &str) -> bool {
if org.contains("https://api.github.com") {
return false;
}
true
}
fn suggest_org_arg(org: &str) -> Result<String, String> {
if org.starts_with("https://api.github.com/orgs/") && org.ends_with("/repos") {
let suggestion = org
.replace("https://api.github.com/orgs/", "")
.replace("/repos", "");
return Ok(suggestion.to_string());
}
Err("Can't make a suggestion".to_owned())
}
fn make_org_url(matches: &clap::ArgMatches) -> String {
let org = matches
.value_of("ORG")
.expect("Please specify a github org");
if !org_is_just_org(&org) {
match suggest_org_arg(&org) {
Ok(suggestion) => {
print_message_and_exit(&format!("Try this for the org value: {}", suggestion), -1)
}
Err(_) => {
print_message_and_exit(&"Please make org just the organization name.".to_string(), -1)
}
}
}
format!("https://api.github.com/orgs/{}/repos", org)
}
fn get_pr_links(
repos: &Vec<github::GithubRepo>,
reqwest_client: &reqwest::Client,
dryrun: bool,
) -> Vec<Option<String>> {
let pbar = ProgressBar::new(repos.len() as u64);
pbar.set_style(ProgressStyle::default_bar().template("[{elapsed_precise}] {bar:50.cyan/blue} {pos:>7}/{len:7} {msg}"));
let mut pr_links: Vec<Option<String>> = repos
.iter()
.map(|repo| {
pbar.inc(1);
let i = match get_release_pr_for(&repo, reqwest_client, dryrun) {
Some(pr_url) => Some(pr_url),
None => None,
};
// update the PR body
// pr_url will look like https://github.com/matthewkmayer/release-party-BR/pull/39
// split by '/' and grab last chunk.
if let Some(ref pr_url) = i {
let pr_split = pr_url.split('/').collect::<Vec<&str>>();
let pr_num = pr_split.last().expect("PR link malformed?");
github::update_pr_body(repo, pr_num, reqwest_client, &RP_VERSION);
}
i
})
.collect();
pbar.finish();
// only keep the Some(PR_URL) items:
pr_links.retain(|maybe_pr_link| maybe_pr_link.is_some());
pr_links
}
fn get_reqwest_client(token: &str) -> reqwest::Client {
let mut headers = reqwest::header::HeaderMap::new();
headers.insert(
USER_AGENT,
USERAGENT.parse().expect("useragent should be a string"),
);
headers.insert(
AUTHORIZATION,
format!("token {}", token)
.parse()
.expect("token should be a string"),
);
match reqwest::Client::builder().default_headers(headers).build() {
Ok(new_client) => new_client,
Err(e) => panic!("Couldn't create new reqwest client: {}", e),
}
}
fn get_repos_we_care_about(
github_org_url: &str,
reqwest_client: &reqwest::Client,
) -> Vec<github::GithubRepo> {
let mut repos = match github::get_repos_at(github_org_url, reqwest_client) {
Ok(repos) => repos,
Err(e) => panic!(format!("Couldn't get repos from github: {}", e)),
};
let repos_to_ignore = ignored_repos();
// remove repos we don't care about:
repos.retain(|repo| !repos_to_ignore.contains(&repo.name));
repos
}
fn get_release_pr_for(
repo: &github::GithubRepo,
client: &reqwest::Client,
dryrun: bool,
) -> Option<String> {
match github::existing_release_pr_location(repo, client) {
Some(url) => Some(url),
None => {
if !github::is_release_up_to_date_with_master(&repo.url, client) {
if dryrun {
Some(format!("Dry run: {} would get a release PR.", repo.url))
} else {
match github::create_release_pull_request(repo, client) {
Ok(pr_url) => Some(pr_url),
Err(_) => None,
}
}
} else {
None
}
}
}
}
fn print_party_links(pr_links: Vec<Option<String>>) {
if !pr_links.is_empty() {
println!("\nIt's a release party! PRs to review and approve:");
for link in pr_links {
match link {
Some(pr_link) => println!("{}", pr_link),
None => println!("Party link is None: this shouldn't happen."),
}
}
} else {
println!("\nNo party today, all releases are done.");
}
}
#[derive(Deserialize, Debug)]
struct IgnoredRepo {
ignore: Option<Vec<String>>,
}
fn ignored_repos() -> Vec<String> {
let hfi = match dirs::home_dir() {
Some(path) => {
if Path::new(&path).join(".ignoredrepos.toml").exists() {
Some(Path::new(&path).join(".ignoredrepos.toml"))
} else {
None
}
},
None => None,
};
let lfi = match Path::new("ignoredrepos.toml").exists() {
true => Some(Path::new("ignoredrepos.toml").to_path_buf()),
false => None,
};
let fi = match (lfi, hfi) {
(Some(a), _) => a,
(None, Some(b)) => b,
(_, _) => {println!("The ignoredrepos.toml file not found"); return Vec::new()},
};
let mut f = match File::open(&fi) {
Ok(file) => file,
Err(e) => {
println!(
"Couldn't load ignoredrepos.toml, not ignoring any repos. Reason: {}",
e
);
return Vec::new();
}
};
println!(
"Found ignoredrepos.toml file at {:#?}",
fi
);
let mut buffer = String::new();
match f.read_to_string(&mut buffer) {
Ok(_) => (),
Err(e) => {
println!(
"Couldn't read from ignoredrepos.toml, not ignoring any repos. Reason: {}",
e
);
return Vec::new();
}
} | let ignored: IgnoredRepo = match toml::from_str(&buffer) {
Ok(ignored_repos) => ignored_repos,
Err(e) => {
println!(
"Couldn't parse toml from ignoredrepos.toml, not ignoring any repos. Reason: {}",
e
);
return Vec::new();
}
};
match ignored.ignore {
Some(repos_to_ignore) => repos_to_ignore,
None => Vec::new(),
}
}
fn print_message_and_exit(message: &str, exit_code: i32) {
println!("{}", message);
::std::process::exit(exit_code);
}
#[cfg(test)]
mod tests {
use super::*;
#[test]
fn get_ignored_repos_happy_path() {
let ignored_repositories = vec!["calagator".to_owned(), "moe".to_owned()];
assert_eq!(ignored_repositories, ignored_repos());
}
#[test]
fn handle_malformed_org() {
assert_eq!(
false,
org_is_just_org("https://api.github.com/orgs/ORG-HERE/repos")
);
}
#[test]
fn handle_okay_org() {
assert_eq!(true, org_is_just_org("ORG-HERE"));
}
#[test]
fn suggestion_for_org_happy() {
assert_eq!(
"ORG-HERE",
suggest_org_arg("https://api.github.com/orgs/ORG-HERE/repos").unwrap()
);
}
#[test]
fn suggestion_for_org_sad() {
assert_eq!(
true,
suggest_org_arg("https://api.github.com/orgs/ORG-HERE/").is_err()
);
assert_eq!(
true,
suggest_org_arg("http://api.github.com/orgs/ORG-HERE/").is_err()
);
assert_eq!(
true,
suggest_org_arg("api.github.com/orgs/ORG-HERE/repos").is_err()
);
}
} | random_line_split | |
main.rs | #![cfg_attr(feature = "clippy", feature(plugin))]
#![cfg_attr(feature = "clippy", plugin(clippy))]
#[macro_use]
extern crate clap;
extern crate reqwest;
#[macro_use]
extern crate serde_derive;
extern crate toml;
extern crate indicatif;
#[macro_use]
extern crate lazy_static;
#[cfg(test)]
extern crate hyper;
use clap::App;
use reqwest::header::{AUTHORIZATION, USER_AGENT};
use indicatif::{ProgressBar, ProgressStyle};
use std::env;
use std::fs::File;
use std::io::prelude::*;
use std::path::Path;
mod github;
static GITHUB_TOKEN: &'static str = "RP_GITHUBTOKEN";
static USERAGENT: &'static str = "release-party-br";
lazy_static! {
static ref RP_VERSION: String = {
let yaml = load_yaml!("release-party.yml");
let app = App::from_yaml(yaml);
version_string(&app)
};
}
fn main() {
let yaml = load_yaml!("release-party.yml");
let matches = App::from_yaml(yaml).get_matches();
let org_url = make_org_url(&matches);
let token = match env::var(GITHUB_TOKEN) {
Ok(env_var) => env_var,
Err(_) => {
print_message_and_exit(
&format!("{} environment variable should be set", GITHUB_TOKEN),
-1,
);
unreachable!();
}
};
let reqwest_client = get_reqwest_client(&token);
let links = get_pr_links(
&get_repos_we_care_about(&org_url, &reqwest_client),
&reqwest_client,
is_dryrun(&matches),
);
print_party_links(links);
}
fn version_string(app: &App) -> String {
let mut version: Vec<u8> = Vec::new();
app.write_version(&mut version)
.expect("Should write to version vec.");
String::from_utf8(version).expect("Version text should be utf8 text")
}
fn is_dryrun(matches: &clap::ArgMatches) -> bool {
matches.is_present("DRYRUN")
}
fn org_is_just_org(org: &str) -> bool {
if org.contains("https://api.github.com") {
return false;
}
true
}
fn suggest_org_arg(org: &str) -> Result<String, String> {
if org.starts_with("https://api.github.com/orgs/") && org.ends_with("/repos") {
let suggestion = org
.replace("https://api.github.com/orgs/", "")
.replace("/repos", "");
return Ok(suggestion.to_string());
}
Err("Can't make a suggestion".to_owned())
}
fn make_org_url(matches: &clap::ArgMatches) -> String {
let org = matches
.value_of("ORG")
.expect("Please specify a github org");
if !org_is_just_org(&org) {
match suggest_org_arg(&org) {
Ok(suggestion) => {
print_message_and_exit(&format!("Try this for the org value: {}", suggestion), -1)
}
Err(_) => {
print_message_and_exit(&"Please make org just the organization name.".to_string(), -1)
}
}
}
format!("https://api.github.com/orgs/{}/repos", org)
}
fn get_pr_links(
repos: &Vec<github::GithubRepo>,
reqwest_client: &reqwest::Client,
dryrun: bool,
) -> Vec<Option<String>> {
let pbar = ProgressBar::new(repos.len() as u64);
pbar.set_style(ProgressStyle::default_bar().template("[{elapsed_precise}] {bar:50.cyan/blue} {pos:>7}/{len:7} {msg}"));
let mut pr_links: Vec<Option<String>> = repos
.iter()
.map(|repo| {
pbar.inc(1);
let i = match get_release_pr_for(&repo, reqwest_client, dryrun) {
Some(pr_url) => Some(pr_url),
None => None,
};
// update the PR body
// pr_url will look like https://github.com/matthewkmayer/release-party-BR/pull/39
// split by '/' and grab last chunk.
if let Some(ref pr_url) = i {
let pr_split = pr_url.split('/').collect::<Vec<&str>>();
let pr_num = pr_split.last().expect("PR link malformed?");
github::update_pr_body(repo, pr_num, reqwest_client, &RP_VERSION);
}
i
})
.collect();
pbar.finish();
// only keep the Some(PR_URL) items:
pr_links.retain(|maybe_pr_link| maybe_pr_link.is_some());
pr_links
}
fn get_reqwest_client(token: &str) -> reqwest::Client {
let mut headers = reqwest::header::HeaderMap::new();
headers.insert(
USER_AGENT,
USERAGENT.parse().expect("useragent should be a string"),
);
headers.insert(
AUTHORIZATION,
format!("token {}", token)
.parse()
.expect("token should be a string"),
);
match reqwest::Client::builder().default_headers(headers).build() {
Ok(new_client) => new_client,
Err(e) => panic!("Couldn't create new reqwest client: {}", e),
}
}
fn get_repos_we_care_about(
github_org_url: &str,
reqwest_client: &reqwest::Client,
) -> Vec<github::GithubRepo> {
let mut repos = match github::get_repos_at(github_org_url, reqwest_client) {
Ok(repos) => repos,
Err(e) => panic!(format!("Couldn't get repos from github: {}", e)),
};
let repos_to_ignore = ignored_repos();
// remove repos we don't care about:
repos.retain(|repo| !repos_to_ignore.contains(&repo.name));
repos
}
fn get_release_pr_for(
repo: &github::GithubRepo,
client: &reqwest::Client,
dryrun: bool,
) -> Option<String> {
match github::existing_release_pr_location(repo, client) {
Some(url) => Some(url),
None => {
if !github::is_release_up_to_date_with_master(&repo.url, client) {
if dryrun {
Some(format!("Dry run: {} would get a release PR.", repo.url))
} else {
match github::create_release_pull_request(repo, client) {
Ok(pr_url) => Some(pr_url),
Err(_) => None,
}
}
} else {
None
}
}
}
}
fn print_party_links(pr_links: Vec<Option<String>>) {
if !pr_links.is_empty() {
println!("\nIt's a release party! PRs to review and approve:");
for link in pr_links {
match link {
Some(pr_link) => println!("{}", pr_link),
None => println!("Party link is None: this shouldn't happen."),
}
}
} else {
println!("\nNo party today, all releases are done.");
}
}
#[derive(Deserialize, Debug)]
struct IgnoredRepo {
ignore: Option<Vec<String>>,
}
fn ignored_repos() -> Vec<String> {
let hfi = match dirs::home_dir() {
Some(path) => {
if Path::new(&path).join(".ignoredrepos.toml").exists() {
Some(Path::new(&path).join(".ignoredrepos.toml"))
} else {
None
}
},
None => None,
};
let lfi = match Path::new("ignoredrepos.toml").exists() {
true => Some(Path::new("ignoredrepos.toml").to_path_buf()),
false => None,
};
let fi = match (lfi, hfi) {
(Some(a), _) => a,
(None, Some(b)) => b,
(_, _) => {println!("The ignoredrepos.toml file not found"); return Vec::new()},
};
let mut f = match File::open(&fi) {
Ok(file) => file,
Err(e) => {
println!(
"Couldn't load ignoredrepos.toml, not ignoring any repos. Reason: {}",
e
);
return Vec::new();
}
};
println!(
"Found ignoredrepos.toml file at {:#?}",
fi
);
let mut buffer = String::new();
match f.read_to_string(&mut buffer) {
Ok(_) => (),
Err(e) => {
println!(
"Couldn't read from ignoredrepos.toml, not ignoring any repos. Reason: {}",
e
);
return Vec::new();
}
}
let ignored: IgnoredRepo = match toml::from_str(&buffer) {
Ok(ignored_repos) => ignored_repos,
Err(e) => {
println!(
"Couldn't parse toml from ignoredrepos.toml, not ignoring any repos. Reason: {}",
e
);
return Vec::new();
}
};
match ignored.ignore {
Some(repos_to_ignore) => repos_to_ignore,
None => Vec::new(),
}
}
fn print_message_and_exit(message: &str, exit_code: i32) {
println!("{}", message);
::std::process::exit(exit_code);
}
#[cfg(test)]
mod tests {
use super::*;
#[test]
fn get_ignored_repos_happy_path() {
let ignored_repositories = vec!["calagator".to_owned(), "moe".to_owned()];
assert_eq!(ignored_repositories, ignored_repos());
}
#[test]
fn handle_malformed_org() {
assert_eq!(
false,
org_is_just_org("https://api.github.com/orgs/ORG-HERE/repos")
);
}
#[test]
fn handle_okay_org() {
assert_eq!(true, org_is_just_org("ORG-HERE"));
}
#[test]
fn suggestion_for_org_happy() {
assert_eq!(
"ORG-HERE",
suggest_org_arg("https://api.github.com/orgs/ORG-HERE/repos").unwrap()
);
}
#[test]
fn | () {
assert_eq!(
true,
suggest_org_arg("https://api.github.com/orgs/ORG-HERE/").is_err()
);
assert_eq!(
true,
suggest_org_arg("http://api.github.com/orgs/ORG-HERE/").is_err()
);
assert_eq!(
true,
suggest_org_arg("api.github.com/orgs/ORG-HERE/repos").is_err()
);
}
}
| suggestion_for_org_sad | identifier_name |
main.rs | #![cfg_attr(feature = "clippy", feature(plugin))]
#![cfg_attr(feature = "clippy", plugin(clippy))]
#[macro_use]
extern crate clap;
extern crate reqwest;
#[macro_use]
extern crate serde_derive;
extern crate toml;
extern crate indicatif;
#[macro_use]
extern crate lazy_static;
#[cfg(test)]
extern crate hyper;
use clap::App;
use reqwest::header::{AUTHORIZATION, USER_AGENT};
use indicatif::{ProgressBar, ProgressStyle};
use std::env;
use std::fs::File;
use std::io::prelude::*;
use std::path::Path;
mod github;
static GITHUB_TOKEN: &'static str = "RP_GITHUBTOKEN";
static USERAGENT: &'static str = "release-party-br";
lazy_static! {
static ref RP_VERSION: String = {
let yaml = load_yaml!("release-party.yml");
let app = App::from_yaml(yaml);
version_string(&app)
};
}
fn main() {
let yaml = load_yaml!("release-party.yml");
let matches = App::from_yaml(yaml).get_matches();
let org_url = make_org_url(&matches);
let token = match env::var(GITHUB_TOKEN) {
Ok(env_var) => env_var,
Err(_) => {
print_message_and_exit(
&format!("{} environment variable should be set", GITHUB_TOKEN),
-1,
);
unreachable!();
}
};
let reqwest_client = get_reqwest_client(&token);
let links = get_pr_links(
&get_repos_we_care_about(&org_url, &reqwest_client),
&reqwest_client,
is_dryrun(&matches),
);
print_party_links(links);
}
fn version_string(app: &App) -> String {
let mut version: Vec<u8> = Vec::new();
app.write_version(&mut version)
.expect("Should write to version vec.");
String::from_utf8(version).expect("Version text should be utf8 text")
}
fn is_dryrun(matches: &clap::ArgMatches) -> bool {
matches.is_present("DRYRUN")
}
fn org_is_just_org(org: &str) -> bool {
if org.contains("https://api.github.com") {
return false;
}
true
}
fn suggest_org_arg(org: &str) -> Result<String, String> {
if org.starts_with("https://api.github.com/orgs/") && org.ends_with("/repos") {
let suggestion = org
.replace("https://api.github.com/orgs/", "")
.replace("/repos", "");
return Ok(suggestion.to_string());
}
Err("Can't make a suggestion".to_owned())
}
fn make_org_url(matches: &clap::ArgMatches) -> String {
let org = matches
.value_of("ORG")
.expect("Please specify a github org");
if !org_is_just_org(&org) {
match suggest_org_arg(&org) {
Ok(suggestion) => {
print_message_and_exit(&format!("Try this for the org value: {}", suggestion), -1)
}
Err(_) => {
print_message_and_exit(&"Please make org just the organization name.".to_string(), -1)
}
}
}
format!("https://api.github.com/orgs/{}/repos", org)
}
fn get_pr_links(
repos: &Vec<github::GithubRepo>,
reqwest_client: &reqwest::Client,
dryrun: bool,
) -> Vec<Option<String>> {
let pbar = ProgressBar::new(repos.len() as u64);
pbar.set_style(ProgressStyle::default_bar().template("[{elapsed_precise}] {bar:50.cyan/blue} {pos:>7}/{len:7} {msg}"));
let mut pr_links: Vec<Option<String>> = repos
.iter()
.map(|repo| {
pbar.inc(1);
let i = match get_release_pr_for(&repo, reqwest_client, dryrun) {
Some(pr_url) => Some(pr_url),
None => None,
};
// update the PR body
// pr_url will look like https://github.com/matthewkmayer/release-party-BR/pull/39
// split by '/' and grab last chunk.
if let Some(ref pr_url) = i {
let pr_split = pr_url.split('/').collect::<Vec<&str>>();
let pr_num = pr_split.last().expect("PR link malformed?");
github::update_pr_body(repo, pr_num, reqwest_client, &RP_VERSION);
}
i
})
.collect();
pbar.finish();
// only keep the Some(PR_URL) items:
pr_links.retain(|maybe_pr_link| maybe_pr_link.is_some());
pr_links
}
fn get_reqwest_client(token: &str) -> reqwest::Client {
let mut headers = reqwest::header::HeaderMap::new();
headers.insert(
USER_AGENT,
USERAGENT.parse().expect("useragent should be a string"),
);
headers.insert(
AUTHORIZATION,
format!("token {}", token)
.parse()
.expect("token should be a string"),
);
match reqwest::Client::builder().default_headers(headers).build() {
Ok(new_client) => new_client,
Err(e) => panic!("Couldn't create new reqwest client: {}", e),
}
}
fn get_repos_we_care_about(
github_org_url: &str,
reqwest_client: &reqwest::Client,
) -> Vec<github::GithubRepo> {
let mut repos = match github::get_repos_at(github_org_url, reqwest_client) {
Ok(repos) => repos,
Err(e) => panic!(format!("Couldn't get repos from github: {}", e)),
};
let repos_to_ignore = ignored_repos();
// remove repos we don't care about:
repos.retain(|repo| !repos_to_ignore.contains(&repo.name));
repos
}
fn get_release_pr_for(
repo: &github::GithubRepo,
client: &reqwest::Client,
dryrun: bool,
) -> Option<String> {
match github::existing_release_pr_location(repo, client) {
Some(url) => Some(url),
None => {
if !github::is_release_up_to_date_with_master(&repo.url, client) {
if dryrun {
Some(format!("Dry run: {} would get a release PR.", repo.url))
} else {
match github::create_release_pull_request(repo, client) {
Ok(pr_url) => Some(pr_url),
Err(_) => None,
}
}
} else {
None
}
}
}
}
fn print_party_links(pr_links: Vec<Option<String>>) {
if !pr_links.is_empty() {
println!("\nIt's a release party! PRs to review and approve:");
for link in pr_links {
match link {
Some(pr_link) => println!("{}", pr_link),
None => println!("Party link is None: this shouldn't happen."),
}
}
} else {
println!("\nNo party today, all releases are done.");
}
}
#[derive(Deserialize, Debug)]
struct IgnoredRepo {
ignore: Option<Vec<String>>,
}
fn ignored_repos() -> Vec<String> {
let hfi = match dirs::home_dir() {
Some(path) => {
if Path::new(&path).join(".ignoredrepos.toml").exists() {
Some(Path::new(&path).join(".ignoredrepos.toml"))
} else {
None
}
},
None => None,
};
let lfi = match Path::new("ignoredrepos.toml").exists() {
true => Some(Path::new("ignoredrepos.toml").to_path_buf()),
false => None,
};
let fi = match (lfi, hfi) {
(Some(a), _) => a,
(None, Some(b)) => b,
(_, _) => {println!("The ignoredrepos.toml file not found"); return Vec::new()},
};
let mut f = match File::open(&fi) {
Ok(file) => file,
Err(e) => {
println!(
"Couldn't load ignoredrepos.toml, not ignoring any repos. Reason: {}",
e
);
return Vec::new();
}
};
println!(
"Found ignoredrepos.toml file at {:#?}",
fi
);
let mut buffer = String::new();
match f.read_to_string(&mut buffer) {
Ok(_) => (),
Err(e) => {
println!(
"Couldn't read from ignoredrepos.toml, not ignoring any repos. Reason: {}",
e
);
return Vec::new();
}
}
let ignored: IgnoredRepo = match toml::from_str(&buffer) {
Ok(ignored_repos) => ignored_repos,
Err(e) => {
println!(
"Couldn't parse toml from ignoredrepos.toml, not ignoring any repos. Reason: {}",
e
);
return Vec::new();
}
};
match ignored.ignore {
Some(repos_to_ignore) => repos_to_ignore,
None => Vec::new(),
}
}
fn print_message_and_exit(message: &str, exit_code: i32) |
#[cfg(test)]
mod tests {
use super::*;
#[test]
fn get_ignored_repos_happy_path() {
let ignored_repositories = vec!["calagator".to_owned(), "moe".to_owned()];
assert_eq!(ignored_repositories, ignored_repos());
}
#[test]
fn handle_malformed_org() {
assert_eq!(
false,
org_is_just_org("https://api.github.com/orgs/ORG-HERE/repos")
);
}
#[test]
fn handle_okay_org() {
assert_eq!(true, org_is_just_org("ORG-HERE"));
}
#[test]
fn suggestion_for_org_happy() {
assert_eq!(
"ORG-HERE",
suggest_org_arg("https://api.github.com/orgs/ORG-HERE/repos").unwrap()
);
}
#[test]
fn suggestion_for_org_sad() {
assert_eq!(
true,
suggest_org_arg("https://api.github.com/orgs/ORG-HERE/").is_err()
);
assert_eq!(
true,
suggest_org_arg("http://api.github.com/orgs/ORG-HERE/").is_err()
);
assert_eq!(
true,
suggest_org_arg("api.github.com/orgs/ORG-HERE/repos").is_err()
);
}
}
| {
println!("{}", message);
::std::process::exit(exit_code);
} | identifier_body |
speaksfor_util.py | #----------------------------------------------------------------------
# Copyright (c) 2014 Raytheon BBN Technologies
#
# Permission is hereby granted, free of charge, to any person obtaining
# a copy of this software and/or hardware specification (the "Work") to
# deal in the Work without restriction, including without limitation the
# rights to use, copy, modify, merge, publish, distribute, sublicense,
# and/or sell copies of the Work, and to permit persons to whom the Work
# is furnished to do so, subject to the following conditions:
#
# The above copyright notice and this permission notice shall be
# included in all copies or substantial portions of the Work.
#
# THE WORK IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS
# OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
# MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
# NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT
# HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY,
# WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
# OUT OF OR IN CONNECTION WITH THE WORK OR THE USE OR OTHER DEALINGS
# IN THE WORK.
#----------------------------------------------------------------------
from __future__ import absolute_import
import datetime
from dateutil import parser as du_parser, tz as du_tz
import optparse
import os
import subprocess
import sys
import tempfile
from xml.dom.minidom import *
from StringIO import StringIO
from extensions.sfa.trust.abac_credential import ABACCredential, ABACElement
from extensions.sfa.trust.certificate import Certificate
from extensions.sfa.trust.credential import Credential, signature_template, HAVELXML
from extensions.sfa.trust.credential_factory import CredentialFactory
from extensions.sfa.trust.gid import GID
# Routine to validate that a speaks-for credential
# says what it claims to say:
# It is a signed credential wherein the signer S is attesting to the
# ABAC statement:
# S.speaks_for(S)<-T Or "S says that T speaks for S"
# Requires that openssl be installed and in the path
# create_speaks_for requires that xmlsec1 be on the path
# Simple XML helper functions
# Find the text associated with first child text node
def findTextChildValue(root):
child = findChildNamed(root, '#text')
if child: return str(child.nodeValue)
return None
# Find first child with given name
def | (root, name):
for child in root.childNodes:
if child.nodeName == name:
return child
return None
# Write a string to a tempfile, returning name of tempfile
def write_to_tempfile(str):
str_fd, str_file = tempfile.mkstemp()
if str:
os.write(str_fd, str)
os.close(str_fd)
return str_file
# Run a subprocess and return output
def run_subprocess(cmd, stdout, stderr):
try:
proc = subprocess.Popen(cmd, stdout=stdout, stderr=stderr)
proc.wait()
if stdout:
output = proc.stdout.read()
else:
output = proc.returncode
return output
except Exception as e:
raise Exception("Failed call to subprocess '%s': %s" % (" ".join(cmd), e))
def get_cert_keyid(gid):
"""Extract the subject key identifier from the given certificate.
Return they key id as lowercase string with no colon separators
between pairs. The key id as shown in the text output of a
certificate are in uppercase with colon separators.
"""
raw_key_id = gid.get_extension('subjectKeyIdentifier')
# Raw has colons separating pairs, and all characters are upper case.
# Remove the colons and convert to lower case.
keyid = raw_key_id.replace(':', '').lower()
return keyid
# Pull the cert out of a list of certs in a PEM formatted cert string
def grab_toplevel_cert(cert):
start_label = '-----BEGIN CERTIFICATE-----'
if cert.find(start_label) > -1:
start_index = cert.find(start_label) + len(start_label)
else:
start_index = 0
end_label = '-----END CERTIFICATE-----'
end_index = cert.find(end_label)
first_cert = cert[start_index:end_index]
pieces = first_cert.split('\n')
first_cert = "".join(pieces)
return first_cert
# Validate that the given speaks-for credential represents the
# statement User.speaks_for(User)<-Tool for the given user and tool certs
# and was signed by the user
# Return:
# Boolean indicating whether the given credential
# is not expired
# is an ABAC credential
# was signed by the user associated with the speaking_for_urn
# is verified by xmlsec1
# asserts U.speaks_for(U)<-T ("user says that T may speak for user")
# If schema provided, validate against schema
# is trusted by given set of trusted roots (both user cert and tool cert)
# String user certificate of speaking_for user if the above tests succeed
# (None otherwise)
# Error message indicating why the speaks_for call failed ("" otherwise)
def verify_speaks_for(cred, tool_gid, speaking_for_urn, \
trusted_roots, schema=None, logger=None):
# Credential has not expired
if cred.expiration and cred.expiration < datetime.datetime.utcnow():
return False, None, "ABAC Credential expired at %s (%s)" % (cred.expiration.isoformat(), cred.get_summary_tostring())
# Must be ABAC
if cred.get_cred_type() != ABACCredential.ABAC_CREDENTIAL_TYPE:
return False, None, "Credential not of type ABAC but %s" % cred.get_cred_type
if cred.signature is None or cred.signature.gid is None:
return False, None, "Credential malformed: missing signature or signer cert. Cred: %s" % cred.get_summary_tostring()
user_gid = cred.signature.gid
user_urn = user_gid.get_urn()
# URN of signer from cert must match URN of 'speaking-for' argument
if user_urn != speaking_for_urn:
return False, None, "User URN from cred doesn't match speaking_for URN: %s != %s (cred %s)" % \
(user_urn, speaking_for_urn, cred.get_summary_tostring())
tails = cred.get_tails()
if len(tails) != 1:
return False, None, "Invalid ABAC-SF credential: Need exactly 1 tail element, got %d (%s)" % \
(len(tails), cred.get_summary_tostring())
user_keyid = get_cert_keyid(user_gid)
tool_keyid = get_cert_keyid(tool_gid)
subject_keyid = tails[0].get_principal_keyid()
head = cred.get_head()
principal_keyid = head.get_principal_keyid()
role = head.get_role()
# Credential must pass xmlsec1 verify
cred_file = write_to_tempfile(cred.save_to_string())
cert_args = []
if trusted_roots:
for x in trusted_roots:
cert_args += ['--trusted-pem', x.filename]
# FIXME: Why do we not need to specify the --node-id option as credential.py does?
xmlsec1_args = [cred.xmlsec_path, '--verify'] + cert_args + [ cred_file]
output = run_subprocess(xmlsec1_args, stdout=None, stderr=subprocess.PIPE)
os.unlink(cred_file)
if output != 0:
# FIXME
# xmlsec errors have a msg= which is the interesting bit.
# But does this go to stderr or stdout? Do we have it here?
verified = ""
mstart = verified.find("msg=")
msg = ""
if mstart > -1 and len(verified) > 4:
mstart = mstart + 4
mend = verified.find('\\', mstart)
msg = verified[mstart:mend]
if msg == "":
msg = output
return False, None, "ABAC credential failed to xmlsec1 verify: %s" % msg
# Must say U.speaks_for(U)<-T
if user_keyid != principal_keyid or \
tool_keyid != subject_keyid or \
role != ('speaks_for_%s' % user_keyid):
return False, None, "ABAC statement doesn't assert U.speaks_for(U)<-T (%s)" % cred.get_summary_tostring()
# If schema provided, validate against schema
if HAVELXML and schema and os.path.exists(schema):
from lxml import etree
tree = etree.parse(StringIO(cred.xml))
schema_doc = etree.parse(schema)
xmlschema = etree.XMLSchema(schema_doc)
if not xmlschema.validate(tree):
error = xmlschema.error_log.last_error
message = "%s: %s (line %s)" % (cred.get_summary_tostring(), error.message, error.line)
return False, None, ("XML Credential schema invalid: %s" % message)
if trusted_roots:
# User certificate must validate against trusted roots
try:
user_gid.verify_chain(trusted_roots)
except Exception, e:
return False, None, \
"Cred signer (user) cert not trusted: %s" % e
# Tool certificate must validate against trusted roots
try:
tool_gid.verify_chain(trusted_roots)
except Exception, e:
return False, None, \
"Tool cert not trusted: %s" % e
return True, user_gid, ""
# Determine if this is a speaks-for context. If so, validate
# And return either the tool_cert (not speaks-for or not validated)
# or the user cert (validated speaks-for)
#
# credentials is a list of GENI-style credentials:
# Either a cred string xml string, or Credential object of a tuple
# [{'geni_type' : geni_type, 'geni_value : cred_value,
# 'geni_version' : version}]
# caller_gid is the raw X509 cert gid
# options is the dictionary of API-provided options
# trusted_roots is a list of Certificate objects from the system
# trusted_root directory
# Optionally, provide an XML schema against which to validate the credential
def determine_speaks_for(logger, credentials, caller_gid, options, \
trusted_roots, schema=None):
if options and 'geni_speaking_for' in options:
speaking_for_urn = options['geni_speaking_for'].strip()
for cred in credentials:
# Skip things that aren't ABAC credentials
if type(cred) == dict:
if cred['geni_type'] != ABACCredential.ABAC_CREDENTIAL_TYPE: continue
cred_value = cred['geni_value']
elif isinstance(cred, Credential):
if not isinstance(cred, ABACCredential):
continue
else:
cred_value = cred
else:
if CredentialFactory.getType(cred) != ABACCredential.ABAC_CREDENTIAL_TYPE: continue
cred_value = cred
# If the cred_value is xml, create the object
if not isinstance(cred_value, ABACCredential):
cred = CredentialFactory.createCred(cred_value)
# print "Got a cred to check speaksfor for: %s" % cred.get_summary_tostring()
# #cred.dump(True, True)
# print "Caller: %s" % caller_gid.dump_string(2, True)
# See if this is a valid speaks_for
is_valid_speaks_for, user_gid, msg = \
verify_speaks_for(cred,
caller_gid, speaking_for_urn, \
trusted_roots, schema, logger)
if is_valid_speaks_for:
return user_gid # speaks-for
else:
if logger:
logger.info("Got speaks-for option but not a valid speaks_for with this credential: %s" % msg)
else:
print "Got a speaks-for option but not a valid speaks_for with this credential: " + msg
return caller_gid # Not speaks-for
# Create an ABAC Speaks For credential using the ABACCredential object and it's encode&sign methods
def create_sign_abaccred(tool_gid, user_gid, ma_gid, user_key_file, cred_filename, dur_days=365):
print "Creating ABAC SpeaksFor using ABACCredential...\n"
# Write out the user cert
from tempfile import mkstemp
ma_str = ma_gid.save_to_string()
user_cert_str = user_gid.save_to_string()
if not user_cert_str.endswith(ma_str):
user_cert_str += ma_str
fp, user_cert_filename = mkstemp(suffix='cred', text=True)
fp = os.fdopen(fp, "w")
fp.write(user_cert_str)
fp.close()
# Create the cred
cred = ABACCredential()
cred.set_issuer_keys(user_key_file, user_cert_filename)
tool_urn = tool_gid.get_urn()
user_urn = user_gid.get_urn()
user_keyid = get_cert_keyid(user_gid)
tool_keyid = get_cert_keyid(tool_gid)
cred.head = ABACElement(user_keyid, user_urn, "speaks_for_%s" % user_keyid)
cred.tails.append(ABACElement(tool_keyid, tool_urn))
cred.set_expiration(datetime.datetime.utcnow() + datetime.timedelta(days=dur_days))
cred.expiration = cred.expiration.replace(microsecond=0)
# Produce the cred XML
cred.encode()
# Sign it
cred.sign()
# Save it
cred.save_to_file(cred_filename)
print "Created ABAC credential: '%s' in file %s" % \
(cred.get_summary_tostring(), cred_filename)
# FIXME: Assumes xmlsec1 is on path
# FIXME: Assumes signer is itself signed by an 'ma_gid' that can be trusted
def create_speaks_for(tool_gid, user_gid, ma_gid, \
user_key_file, cred_filename, dur_days=365):
tool_urn = tool_gid.get_urn()
user_urn = user_gid.get_urn()
header = '<?xml version="1.0" encoding="UTF-8"?>'
reference = "ref0"
signature_block = \
'<signatures>\n' + \
signature_template + \
'</signatures>'
template = header + '\n' + \
'<signed-credential '
template += 'xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:noNamespaceSchemaLocation="http://www.geni.net/resources/credential/2/credential.xsd" xsi:schemaLocation="http://www.protogeni.net/resources/credential/ext/policy/1 http://www.protogeni.net/resources/credential/ext/policy/1/policy.xsd"'
template += '>\n' + \
'<credential xml:id="%s">\n' + \
'<type>abac</type>\n' + \
'<serial/>\n' +\
'<owner_gid/>\n' + \
'<owner_urn/>\n' + \
'<target_gid/>\n' + \
'<target_urn/>\n' + \
'<uuid/>\n' + \
'<expires>%s</expires>' +\
'<abac>\n' + \
'<rt0>\n' + \
'<version>%s</version>\n' + \
'<head>\n' + \
'<ABACprincipal><keyid>%s</keyid><mnemonic>%s</mnemonic></ABACprincipal>\n' +\
'<role>speaks_for_%s</role>\n' + \
'</head>\n' + \
'<tail>\n' +\
'<ABACprincipal><keyid>%s</keyid><mnemonic>%s</mnemonic></ABACprincipal>\n' +\
'</tail>\n' +\
'</rt0>\n' + \
'</abac>\n' + \
'</credential>\n' + \
signature_block + \
'</signed-credential>\n'
credential_duration = datetime.timedelta(days=dur_days)
expiration = datetime.datetime.now(du_tz.tzutc()) + credential_duration
expiration_str = expiration.strftime('%Y-%m-%dT%H:%M:%SZ') # FIXME: libabac can't handle .isoformat()
version = "1.1"
user_keyid = get_cert_keyid(user_gid)
tool_keyid = get_cert_keyid(tool_gid)
unsigned_cred = template % (reference, expiration_str, version, \
user_keyid, user_urn, user_keyid, tool_keyid, tool_urn, \
reference, reference)
unsigned_cred_filename = write_to_tempfile(unsigned_cred)
# Now sign the file with xmlsec1
# xmlsec1 --sign --privkey-pem privkey.pem,cert.pem
# --output signed.xml tosign.xml
pems = "%s,%s,%s" % (user_key_file, user_gid.get_filename(),
ma_gid.get_filename())
# FIXME: assumes xmlsec1 is on path
cmd = ['xmlsec1', '--sign', '--privkey-pem', pems,
'--output', cred_filename, unsigned_cred_filename]
# print " ".join(cmd)
sign_proc_output = run_subprocess(cmd, stdout=subprocess.PIPE, stderr=None)
if sign_proc_output == None:
print "OUTPUT = %s" % sign_proc_output
else:
print "Created ABAC credential: '%s speaks_for %s' in file %s" % \
(tool_urn, user_urn, cred_filename)
os.unlink(unsigned_cred_filename)
# Test procedure
if __name__ == "__main__":
parser = optparse.OptionParser()
parser.add_option('--cred_file',
help='Name of credential file')
parser.add_option('--tool_cert_file',
help='Name of file containing tool certificate')
parser.add_option('--user_urn',
help='URN of speaks-for user')
parser.add_option('--user_cert_file',
help="filename of x509 certificate of signing user")
parser.add_option('--ma_cert_file',
help="filename of x509 cert of MA that signed user cert")
parser.add_option('--user_key_file',
help="filename of private key of signing user")
parser.add_option('--trusted_roots_directory',
help='Directory of trusted root certs')
parser.add_option('--create',
help="name of file of ABAC speaksfor cred to create")
parser.add_option('--useObject', action='store_true', default=False,
help='Use the ABACCredential object to create the credential (default False)')
options, args = parser.parse_args(sys.argv)
tool_gid = GID(filename=options.tool_cert_file)
if options.create:
if options.user_cert_file and options.user_key_file \
and options.ma_cert_file:
user_gid = GID(filename=options.user_cert_file)
ma_gid = GID(filename=options.ma_cert_file)
if options.useObject:
create_sign_abaccred(tool_gid, user_gid, ma_gid, \
options.user_key_file, \
options.create)
else:
create_speaks_for(tool_gid, user_gid, ma_gid, \
options.user_key_file, \
options.create)
else:
print "Usage: --create cred_file " + \
"--user_cert_file user_cert_file" + \
" --user_key_file user_key_file --ma_cert_file ma_cert_file"
sys.exit()
user_urn = options.user_urn
# Get list of trusted rootcerts
if options.cred_file and not options.trusted_roots_directory:
sys.exit("Must supply --trusted_roots_directory to validate a credential")
trusted_roots_directory = options.trusted_roots_directory
trusted_roots = \
[Certificate(filename=os.path.join(trusted_roots_directory, file)) \
for file in os.listdir(trusted_roots_directory) \
if file.endswith('.pem') and file != 'CATedCACerts.pem']
cred = open(options.cred_file).read()
creds = [{'geni_type' : ABACCredential.ABAC_CREDENTIAL_TYPE, 'geni_value' : cred,
'geni_version' : '1'}]
gid = determine_speaks_for(None, creds, tool_gid, \
{'geni_speaking_for' : user_urn}, \
trusted_roots)
print 'SPEAKS_FOR = %s' % (gid != tool_gid)
print "CERT URN = %s" % gid.get_urn()
| findChildNamed | identifier_name |
speaksfor_util.py | #----------------------------------------------------------------------
# Copyright (c) 2014 Raytheon BBN Technologies
#
# Permission is hereby granted, free of charge, to any person obtaining
# a copy of this software and/or hardware specification (the "Work") to
# deal in the Work without restriction, including without limitation the
# rights to use, copy, modify, merge, publish, distribute, sublicense,
# and/or sell copies of the Work, and to permit persons to whom the Work
# is furnished to do so, subject to the following conditions:
#
# The above copyright notice and this permission notice shall be
# included in all copies or substantial portions of the Work.
#
# THE WORK IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS
# OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
# MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
# NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT
# HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY,
# WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
# OUT OF OR IN CONNECTION WITH THE WORK OR THE USE OR OTHER DEALINGS
# IN THE WORK.
#----------------------------------------------------------------------
from __future__ import absolute_import
import datetime
from dateutil import parser as du_parser, tz as du_tz
import optparse
import os
import subprocess
import sys
import tempfile
from xml.dom.minidom import *
from StringIO import StringIO
from extensions.sfa.trust.abac_credential import ABACCredential, ABACElement
from extensions.sfa.trust.certificate import Certificate
from extensions.sfa.trust.credential import Credential, signature_template, HAVELXML
from extensions.sfa.trust.credential_factory import CredentialFactory
from extensions.sfa.trust.gid import GID
# Routine to validate that a speaks-for credential
# says what it claims to say:
# It is a signed credential wherein the signer S is attesting to the
# ABAC statement:
# S.speaks_for(S)<-T Or "S says that T speaks for S"
# Requires that openssl be installed and in the path
# create_speaks_for requires that xmlsec1 be on the path
# Simple XML helper functions
# Find the text associated with first child text node
def findTextChildValue(root):
child = findChildNamed(root, '#text')
if child: return str(child.nodeValue)
return None
# Find first child with given name
def findChildNamed(root, name):
for child in root.childNodes:
if child.nodeName == name:
return child
return None
# Write a string to a tempfile, returning name of tempfile
def write_to_tempfile(str):
str_fd, str_file = tempfile.mkstemp()
if str:
os.write(str_fd, str)
os.close(str_fd)
return str_file
# Run a subprocess and return output
def run_subprocess(cmd, stdout, stderr):
try:
proc = subprocess.Popen(cmd, stdout=stdout, stderr=stderr)
proc.wait()
if stdout:
output = proc.stdout.read()
else:
output = proc.returncode
return output
except Exception as e:
raise Exception("Failed call to subprocess '%s': %s" % (" ".join(cmd), e))
def get_cert_keyid(gid):
"""Extract the subject key identifier from the given certificate.
Return they key id as lowercase string with no colon separators
between pairs. The key id as shown in the text output of a
certificate are in uppercase with colon separators.
"""
raw_key_id = gid.get_extension('subjectKeyIdentifier')
# Raw has colons separating pairs, and all characters are upper case.
# Remove the colons and convert to lower case.
keyid = raw_key_id.replace(':', '').lower()
return keyid
# Pull the cert out of a list of certs in a PEM formatted cert string
def grab_toplevel_cert(cert):
start_label = '-----BEGIN CERTIFICATE-----'
if cert.find(start_label) > -1:
start_index = cert.find(start_label) + len(start_label)
else:
start_index = 0
end_label = '-----END CERTIFICATE-----'
end_index = cert.find(end_label)
first_cert = cert[start_index:end_index]
pieces = first_cert.split('\n')
first_cert = "".join(pieces)
return first_cert
# Validate that the given speaks-for credential represents the
# statement User.speaks_for(User)<-Tool for the given user and tool certs
# and was signed by the user
# Return:
# Boolean indicating whether the given credential
# is not expired
# is an ABAC credential
# was signed by the user associated with the speaking_for_urn
# is verified by xmlsec1
# asserts U.speaks_for(U)<-T ("user says that T may speak for user")
# If schema provided, validate against schema
# is trusted by given set of trusted roots (both user cert and tool cert)
# String user certificate of speaking_for user if the above tests succeed
# (None otherwise)
# Error message indicating why the speaks_for call failed ("" otherwise)
def verify_speaks_for(cred, tool_gid, speaking_for_urn, \
trusted_roots, schema=None, logger=None):
# Credential has not expired
if cred.expiration and cred.expiration < datetime.datetime.utcnow():
return False, None, "ABAC Credential expired at %s (%s)" % (cred.expiration.isoformat(), cred.get_summary_tostring())
# Must be ABAC
if cred.get_cred_type() != ABACCredential.ABAC_CREDENTIAL_TYPE:
return False, None, "Credential not of type ABAC but %s" % cred.get_cred_type
if cred.signature is None or cred.signature.gid is None:
return False, None, "Credential malformed: missing signature or signer cert. Cred: %s" % cred.get_summary_tostring()
user_gid = cred.signature.gid
user_urn = user_gid.get_urn()
# URN of signer from cert must match URN of 'speaking-for' argument
if user_urn != speaking_for_urn:
return False, None, "User URN from cred doesn't match speaking_for URN: %s != %s (cred %s)" % \
(user_urn, speaking_for_urn, cred.get_summary_tostring())
tails = cred.get_tails()
if len(tails) != 1:
return False, None, "Invalid ABAC-SF credential: Need exactly 1 tail element, got %d (%s)" % \
(len(tails), cred.get_summary_tostring())
user_keyid = get_cert_keyid(user_gid)
tool_keyid = get_cert_keyid(tool_gid)
subject_keyid = tails[0].get_principal_keyid()
head = cred.get_head()
principal_keyid = head.get_principal_keyid()
role = head.get_role()
# Credential must pass xmlsec1 verify
cred_file = write_to_tempfile(cred.save_to_string())
cert_args = []
if trusted_roots:
for x in trusted_roots:
cert_args += ['--trusted-pem', x.filename]
# FIXME: Why do we not need to specify the --node-id option as credential.py does?
xmlsec1_args = [cred.xmlsec_path, '--verify'] + cert_args + [ cred_file]
output = run_subprocess(xmlsec1_args, stdout=None, stderr=subprocess.PIPE)
os.unlink(cred_file)
if output != 0:
# FIXME
# xmlsec errors have a msg= which is the interesting bit.
# But does this go to stderr or stdout? Do we have it here?
verified = ""
mstart = verified.find("msg=")
msg = ""
if mstart > -1 and len(verified) > 4:
mstart = mstart + 4
mend = verified.find('\\', mstart)
msg = verified[mstart:mend]
if msg == "":
msg = output
return False, None, "ABAC credential failed to xmlsec1 verify: %s" % msg
# Must say U.speaks_for(U)<-T
if user_keyid != principal_keyid or \
tool_keyid != subject_keyid or \
role != ('speaks_for_%s' % user_keyid):
return False, None, "ABAC statement doesn't assert U.speaks_for(U)<-T (%s)" % cred.get_summary_tostring()
# If schema provided, validate against schema
if HAVELXML and schema and os.path.exists(schema):
from lxml import etree
tree = etree.parse(StringIO(cred.xml))
schema_doc = etree.parse(schema)
xmlschema = etree.XMLSchema(schema_doc)
if not xmlschema.validate(tree):
error = xmlschema.error_log.last_error
message = "%s: %s (line %s)" % (cred.get_summary_tostring(), error.message, error.line)
return False, None, ("XML Credential schema invalid: %s" % message)
if trusted_roots:
# User certificate must validate against trusted roots
try:
user_gid.verify_chain(trusted_roots)
except Exception, e:
return False, None, \
"Cred signer (user) cert not trusted: %s" % e
# Tool certificate must validate against trusted roots
try:
tool_gid.verify_chain(trusted_roots)
except Exception, e:
return False, None, \
"Tool cert not trusted: %s" % e
return True, user_gid, ""
# Determine if this is a speaks-for context. If so, validate
# And return either the tool_cert (not speaks-for or not validated)
# or the user cert (validated speaks-for)
#
# credentials is a list of GENI-style credentials:
# Either a cred string xml string, or Credential object of a tuple
# [{'geni_type' : geni_type, 'geni_value : cred_value,
# 'geni_version' : version}]
# caller_gid is the raw X509 cert gid
# options is the dictionary of API-provided options
# trusted_roots is a list of Certificate objects from the system
# trusted_root directory
# Optionally, provide an XML schema against which to validate the credential
def determine_speaks_for(logger, credentials, caller_gid, options, \
trusted_roots, schema=None):
if options and 'geni_speaking_for' in options:
speaking_for_urn = options['geni_speaking_for'].strip()
for cred in credentials:
# Skip things that aren't ABAC credentials
if type(cred) == dict:
if cred['geni_type'] != ABACCredential.ABAC_CREDENTIAL_TYPE: continue
cred_value = cred['geni_value']
elif isinstance(cred, Credential):
if not isinstance(cred, ABACCredential):
continue
else:
cred_value = cred
else:
if CredentialFactory.getType(cred) != ABACCredential.ABAC_CREDENTIAL_TYPE: continue
cred_value = cred
# If the cred_value is xml, create the object
if not isinstance(cred_value, ABACCredential):
cred = CredentialFactory.createCred(cred_value)
# print "Got a cred to check speaksfor for: %s" % cred.get_summary_tostring()
# #cred.dump(True, True)
# print "Caller: %s" % caller_gid.dump_string(2, True)
# See if this is a valid speaks_for
is_valid_speaks_for, user_gid, msg = \
verify_speaks_for(cred,
caller_gid, speaking_for_urn, \
trusted_roots, schema, logger)
if is_valid_speaks_for:
return user_gid # speaks-for
else:
if logger:
logger.info("Got speaks-for option but not a valid speaks_for with this credential: %s" % msg)
else:
print "Got a speaks-for option but not a valid speaks_for with this credential: " + msg
return caller_gid # Not speaks-for
# Create an ABAC Speaks For credential using the ABACCredential object and it's encode&sign methods
def create_sign_abaccred(tool_gid, user_gid, ma_gid, user_key_file, cred_filename, dur_days=365):
|
# FIXME: Assumes xmlsec1 is on path
# FIXME: Assumes signer is itself signed by an 'ma_gid' that can be trusted
def create_speaks_for(tool_gid, user_gid, ma_gid, \
user_key_file, cred_filename, dur_days=365):
tool_urn = tool_gid.get_urn()
user_urn = user_gid.get_urn()
header = '<?xml version="1.0" encoding="UTF-8"?>'
reference = "ref0"
signature_block = \
'<signatures>\n' + \
signature_template + \
'</signatures>'
template = header + '\n' + \
'<signed-credential '
template += 'xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:noNamespaceSchemaLocation="http://www.geni.net/resources/credential/2/credential.xsd" xsi:schemaLocation="http://www.protogeni.net/resources/credential/ext/policy/1 http://www.protogeni.net/resources/credential/ext/policy/1/policy.xsd"'
template += '>\n' + \
'<credential xml:id="%s">\n' + \
'<type>abac</type>\n' + \
'<serial/>\n' +\
'<owner_gid/>\n' + \
'<owner_urn/>\n' + \
'<target_gid/>\n' + \
'<target_urn/>\n' + \
'<uuid/>\n' + \
'<expires>%s</expires>' +\
'<abac>\n' + \
'<rt0>\n' + \
'<version>%s</version>\n' + \
'<head>\n' + \
'<ABACprincipal><keyid>%s</keyid><mnemonic>%s</mnemonic></ABACprincipal>\n' +\
'<role>speaks_for_%s</role>\n' + \
'</head>\n' + \
'<tail>\n' +\
'<ABACprincipal><keyid>%s</keyid><mnemonic>%s</mnemonic></ABACprincipal>\n' +\
'</tail>\n' +\
'</rt0>\n' + \
'</abac>\n' + \
'</credential>\n' + \
signature_block + \
'</signed-credential>\n'
credential_duration = datetime.timedelta(days=dur_days)
expiration = datetime.datetime.now(du_tz.tzutc()) + credential_duration
expiration_str = expiration.strftime('%Y-%m-%dT%H:%M:%SZ') # FIXME: libabac can't handle .isoformat()
version = "1.1"
user_keyid = get_cert_keyid(user_gid)
tool_keyid = get_cert_keyid(tool_gid)
unsigned_cred = template % (reference, expiration_str, version, \
user_keyid, user_urn, user_keyid, tool_keyid, tool_urn, \
reference, reference)
unsigned_cred_filename = write_to_tempfile(unsigned_cred)
# Now sign the file with xmlsec1
# xmlsec1 --sign --privkey-pem privkey.pem,cert.pem
# --output signed.xml tosign.xml
pems = "%s,%s,%s" % (user_key_file, user_gid.get_filename(),
ma_gid.get_filename())
# FIXME: assumes xmlsec1 is on path
cmd = ['xmlsec1', '--sign', '--privkey-pem', pems,
'--output', cred_filename, unsigned_cred_filename]
# print " ".join(cmd)
sign_proc_output = run_subprocess(cmd, stdout=subprocess.PIPE, stderr=None)
if sign_proc_output == None:
print "OUTPUT = %s" % sign_proc_output
else:
print "Created ABAC credential: '%s speaks_for %s' in file %s" % \
(tool_urn, user_urn, cred_filename)
os.unlink(unsigned_cred_filename)
# Test procedure
if __name__ == "__main__":
parser = optparse.OptionParser()
parser.add_option('--cred_file',
help='Name of credential file')
parser.add_option('--tool_cert_file',
help='Name of file containing tool certificate')
parser.add_option('--user_urn',
help='URN of speaks-for user')
parser.add_option('--user_cert_file',
help="filename of x509 certificate of signing user")
parser.add_option('--ma_cert_file',
help="filename of x509 cert of MA that signed user cert")
parser.add_option('--user_key_file',
help="filename of private key of signing user")
parser.add_option('--trusted_roots_directory',
help='Directory of trusted root certs')
parser.add_option('--create',
help="name of file of ABAC speaksfor cred to create")
parser.add_option('--useObject', action='store_true', default=False,
help='Use the ABACCredential object to create the credential (default False)')
options, args = parser.parse_args(sys.argv)
tool_gid = GID(filename=options.tool_cert_file)
if options.create:
if options.user_cert_file and options.user_key_file \
and options.ma_cert_file:
user_gid = GID(filename=options.user_cert_file)
ma_gid = GID(filename=options.ma_cert_file)
if options.useObject:
create_sign_abaccred(tool_gid, user_gid, ma_gid, \
options.user_key_file, \
options.create)
else:
create_speaks_for(tool_gid, user_gid, ma_gid, \
options.user_key_file, \
options.create)
else:
print "Usage: --create cred_file " + \
"--user_cert_file user_cert_file" + \
" --user_key_file user_key_file --ma_cert_file ma_cert_file"
sys.exit()
user_urn = options.user_urn
# Get list of trusted rootcerts
if options.cred_file and not options.trusted_roots_directory:
sys.exit("Must supply --trusted_roots_directory to validate a credential")
trusted_roots_directory = options.trusted_roots_directory
trusted_roots = \
[Certificate(filename=os.path.join(trusted_roots_directory, file)) \
for file in os.listdir(trusted_roots_directory) \
if file.endswith('.pem') and file != 'CATedCACerts.pem']
cred = open(options.cred_file).read()
creds = [{'geni_type' : ABACCredential.ABAC_CREDENTIAL_TYPE, 'geni_value' : cred,
'geni_version' : '1'}]
gid = determine_speaks_for(None, creds, tool_gid, \
{'geni_speaking_for' : user_urn}, \
trusted_roots)
print 'SPEAKS_FOR = %s' % (gid != tool_gid)
print "CERT URN = %s" % gid.get_urn()
| print "Creating ABAC SpeaksFor using ABACCredential...\n"
# Write out the user cert
from tempfile import mkstemp
ma_str = ma_gid.save_to_string()
user_cert_str = user_gid.save_to_string()
if not user_cert_str.endswith(ma_str):
user_cert_str += ma_str
fp, user_cert_filename = mkstemp(suffix='cred', text=True)
fp = os.fdopen(fp, "w")
fp.write(user_cert_str)
fp.close()
# Create the cred
cred = ABACCredential()
cred.set_issuer_keys(user_key_file, user_cert_filename)
tool_urn = tool_gid.get_urn()
user_urn = user_gid.get_urn()
user_keyid = get_cert_keyid(user_gid)
tool_keyid = get_cert_keyid(tool_gid)
cred.head = ABACElement(user_keyid, user_urn, "speaks_for_%s" % user_keyid)
cred.tails.append(ABACElement(tool_keyid, tool_urn))
cred.set_expiration(datetime.datetime.utcnow() + datetime.timedelta(days=dur_days))
cred.expiration = cred.expiration.replace(microsecond=0)
# Produce the cred XML
cred.encode()
# Sign it
cred.sign()
# Save it
cred.save_to_file(cred_filename)
print "Created ABAC credential: '%s' in file %s" % \
(cred.get_summary_tostring(), cred_filename) | identifier_body |
speaksfor_util.py | #----------------------------------------------------------------------
# Copyright (c) 2014 Raytheon BBN Technologies
#
# Permission is hereby granted, free of charge, to any person obtaining
# a copy of this software and/or hardware specification (the "Work") to
# deal in the Work without restriction, including without limitation the
# rights to use, copy, modify, merge, publish, distribute, sublicense,
# and/or sell copies of the Work, and to permit persons to whom the Work
# is furnished to do so, subject to the following conditions:
#
# The above copyright notice and this permission notice shall be
# included in all copies or substantial portions of the Work.
#
# THE WORK IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS
# OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
# MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
# NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT
# HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY,
# WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
# OUT OF OR IN CONNECTION WITH THE WORK OR THE USE OR OTHER DEALINGS
# IN THE WORK.
#----------------------------------------------------------------------
from __future__ import absolute_import
import datetime
from dateutil import parser as du_parser, tz as du_tz
import optparse
import os
import subprocess
import sys
import tempfile
from xml.dom.minidom import *
from StringIO import StringIO
from extensions.sfa.trust.abac_credential import ABACCredential, ABACElement
from extensions.sfa.trust.certificate import Certificate
from extensions.sfa.trust.credential import Credential, signature_template, HAVELXML
from extensions.sfa.trust.credential_factory import CredentialFactory
from extensions.sfa.trust.gid import GID
# Routine to validate that a speaks-for credential
# says what it claims to say:
# It is a signed credential wherein the signer S is attesting to the
# ABAC statement:
# S.speaks_for(S)<-T Or "S says that T speaks for S"
# Requires that openssl be installed and in the path
# create_speaks_for requires that xmlsec1 be on the path
# Simple XML helper functions
# Find the text associated with first child text node
def findTextChildValue(root):
child = findChildNamed(root, '#text')
if child: return str(child.nodeValue)
return None
# Find first child with given name
def findChildNamed(root, name):
for child in root.childNodes:
if child.nodeName == name:
return child
return None
# Write a string to a tempfile, returning name of tempfile
def write_to_tempfile(str):
str_fd, str_file = tempfile.mkstemp()
if str:
os.write(str_fd, str)
os.close(str_fd)
return str_file
# Run a subprocess and return output
def run_subprocess(cmd, stdout, stderr):
try:
proc = subprocess.Popen(cmd, stdout=stdout, stderr=stderr)
proc.wait()
if stdout:
output = proc.stdout.read()
else:
output = proc.returncode
return output
except Exception as e:
raise Exception("Failed call to subprocess '%s': %s" % (" ".join(cmd), e))
def get_cert_keyid(gid):
"""Extract the subject key identifier from the given certificate.
Return they key id as lowercase string with no colon separators
between pairs. The key id as shown in the text output of a
certificate are in uppercase with colon separators.
"""
raw_key_id = gid.get_extension('subjectKeyIdentifier')
# Raw has colons separating pairs, and all characters are upper case.
# Remove the colons and convert to lower case.
keyid = raw_key_id.replace(':', '').lower()
return keyid
# Pull the cert out of a list of certs in a PEM formatted cert string
def grab_toplevel_cert(cert):
start_label = '-----BEGIN CERTIFICATE-----'
if cert.find(start_label) > -1:
start_index = cert.find(start_label) + len(start_label)
else:
start_index = 0
end_label = '-----END CERTIFICATE-----'
end_index = cert.find(end_label)
first_cert = cert[start_index:end_index]
pieces = first_cert.split('\n')
first_cert = "".join(pieces)
return first_cert
# Validate that the given speaks-for credential represents the
# statement User.speaks_for(User)<-Tool for the given user and tool certs
# and was signed by the user
# Return:
# Boolean indicating whether the given credential
# is not expired
# is an ABAC credential
# was signed by the user associated with the speaking_for_urn
# is verified by xmlsec1
# asserts U.speaks_for(U)<-T ("user says that T may speak for user")
# If schema provided, validate against schema
# is trusted by given set of trusted roots (both user cert and tool cert)
# String user certificate of speaking_for user if the above tests succeed
# (None otherwise)
# Error message indicating why the speaks_for call failed ("" otherwise)
def verify_speaks_for(cred, tool_gid, speaking_for_urn, \
trusted_roots, schema=None, logger=None):
# Credential has not expired
if cred.expiration and cred.expiration < datetime.datetime.utcnow():
return False, None, "ABAC Credential expired at %s (%s)" % (cred.expiration.isoformat(), cred.get_summary_tostring())
# Must be ABAC
if cred.get_cred_type() != ABACCredential.ABAC_CREDENTIAL_TYPE:
return False, None, "Credential not of type ABAC but %s" % cred.get_cred_type
if cred.signature is None or cred.signature.gid is None:
return False, None, "Credential malformed: missing signature or signer cert. Cred: %s" % cred.get_summary_tostring()
user_gid = cred.signature.gid
user_urn = user_gid.get_urn()
# URN of signer from cert must match URN of 'speaking-for' argument
if user_urn != speaking_for_urn:
return False, None, "User URN from cred doesn't match speaking_for URN: %s != %s (cred %s)" % \
(user_urn, speaking_for_urn, cred.get_summary_tostring())
tails = cred.get_tails()
if len(tails) != 1:
|
user_keyid = get_cert_keyid(user_gid)
tool_keyid = get_cert_keyid(tool_gid)
subject_keyid = tails[0].get_principal_keyid()
head = cred.get_head()
principal_keyid = head.get_principal_keyid()
role = head.get_role()
# Credential must pass xmlsec1 verify
cred_file = write_to_tempfile(cred.save_to_string())
cert_args = []
if trusted_roots:
for x in trusted_roots:
cert_args += ['--trusted-pem', x.filename]
# FIXME: Why do we not need to specify the --node-id option as credential.py does?
xmlsec1_args = [cred.xmlsec_path, '--verify'] + cert_args + [ cred_file]
output = run_subprocess(xmlsec1_args, stdout=None, stderr=subprocess.PIPE)
os.unlink(cred_file)
if output != 0:
# FIXME
# xmlsec errors have a msg= which is the interesting bit.
# But does this go to stderr or stdout? Do we have it here?
verified = ""
mstart = verified.find("msg=")
msg = ""
if mstart > -1 and len(verified) > 4:
mstart = mstart + 4
mend = verified.find('\\', mstart)
msg = verified[mstart:mend]
if msg == "":
msg = output
return False, None, "ABAC credential failed to xmlsec1 verify: %s" % msg
# Must say U.speaks_for(U)<-T
if user_keyid != principal_keyid or \
tool_keyid != subject_keyid or \
role != ('speaks_for_%s' % user_keyid):
return False, None, "ABAC statement doesn't assert U.speaks_for(U)<-T (%s)" % cred.get_summary_tostring()
# If schema provided, validate against schema
if HAVELXML and schema and os.path.exists(schema):
from lxml import etree
tree = etree.parse(StringIO(cred.xml))
schema_doc = etree.parse(schema)
xmlschema = etree.XMLSchema(schema_doc)
if not xmlschema.validate(tree):
error = xmlschema.error_log.last_error
message = "%s: %s (line %s)" % (cred.get_summary_tostring(), error.message, error.line)
return False, None, ("XML Credential schema invalid: %s" % message)
if trusted_roots:
# User certificate must validate against trusted roots
try:
user_gid.verify_chain(trusted_roots)
except Exception, e:
return False, None, \
"Cred signer (user) cert not trusted: %s" % e
# Tool certificate must validate against trusted roots
try:
tool_gid.verify_chain(trusted_roots)
except Exception, e:
return False, None, \
"Tool cert not trusted: %s" % e
return True, user_gid, ""
# Determine if this is a speaks-for context. If so, validate
# And return either the tool_cert (not speaks-for or not validated)
# or the user cert (validated speaks-for)
#
# credentials is a list of GENI-style credentials:
# Either a cred string xml string, or Credential object of a tuple
# [{'geni_type' : geni_type, 'geni_value : cred_value,
# 'geni_version' : version}]
# caller_gid is the raw X509 cert gid
# options is the dictionary of API-provided options
# trusted_roots is a list of Certificate objects from the system
# trusted_root directory
# Optionally, provide an XML schema against which to validate the credential
def determine_speaks_for(logger, credentials, caller_gid, options, \
trusted_roots, schema=None):
if options and 'geni_speaking_for' in options:
speaking_for_urn = options['geni_speaking_for'].strip()
for cred in credentials:
# Skip things that aren't ABAC credentials
if type(cred) == dict:
if cred['geni_type'] != ABACCredential.ABAC_CREDENTIAL_TYPE: continue
cred_value = cred['geni_value']
elif isinstance(cred, Credential):
if not isinstance(cred, ABACCredential):
continue
else:
cred_value = cred
else:
if CredentialFactory.getType(cred) != ABACCredential.ABAC_CREDENTIAL_TYPE: continue
cred_value = cred
# If the cred_value is xml, create the object
if not isinstance(cred_value, ABACCredential):
cred = CredentialFactory.createCred(cred_value)
# print "Got a cred to check speaksfor for: %s" % cred.get_summary_tostring()
# #cred.dump(True, True)
# print "Caller: %s" % caller_gid.dump_string(2, True)
# See if this is a valid speaks_for
is_valid_speaks_for, user_gid, msg = \
verify_speaks_for(cred,
caller_gid, speaking_for_urn, \
trusted_roots, schema, logger)
if is_valid_speaks_for:
return user_gid # speaks-for
else:
if logger:
logger.info("Got speaks-for option but not a valid speaks_for with this credential: %s" % msg)
else:
print "Got a speaks-for option but not a valid speaks_for with this credential: " + msg
return caller_gid # Not speaks-for
# Create an ABAC Speaks For credential using the ABACCredential object and it's encode&sign methods
def create_sign_abaccred(tool_gid, user_gid, ma_gid, user_key_file, cred_filename, dur_days=365):
print "Creating ABAC SpeaksFor using ABACCredential...\n"
# Write out the user cert
from tempfile import mkstemp
ma_str = ma_gid.save_to_string()
user_cert_str = user_gid.save_to_string()
if not user_cert_str.endswith(ma_str):
user_cert_str += ma_str
fp, user_cert_filename = mkstemp(suffix='cred', text=True)
fp = os.fdopen(fp, "w")
fp.write(user_cert_str)
fp.close()
# Create the cred
cred = ABACCredential()
cred.set_issuer_keys(user_key_file, user_cert_filename)
tool_urn = tool_gid.get_urn()
user_urn = user_gid.get_urn()
user_keyid = get_cert_keyid(user_gid)
tool_keyid = get_cert_keyid(tool_gid)
cred.head = ABACElement(user_keyid, user_urn, "speaks_for_%s" % user_keyid)
cred.tails.append(ABACElement(tool_keyid, tool_urn))
cred.set_expiration(datetime.datetime.utcnow() + datetime.timedelta(days=dur_days))
cred.expiration = cred.expiration.replace(microsecond=0)
# Produce the cred XML
cred.encode()
# Sign it
cred.sign()
# Save it
cred.save_to_file(cred_filename)
print "Created ABAC credential: '%s' in file %s" % \
(cred.get_summary_tostring(), cred_filename)
# FIXME: Assumes xmlsec1 is on path
# FIXME: Assumes signer is itself signed by an 'ma_gid' that can be trusted
def create_speaks_for(tool_gid, user_gid, ma_gid, \
user_key_file, cred_filename, dur_days=365):
tool_urn = tool_gid.get_urn()
user_urn = user_gid.get_urn()
header = '<?xml version="1.0" encoding="UTF-8"?>'
reference = "ref0"
signature_block = \
'<signatures>\n' + \
signature_template + \
'</signatures>'
template = header + '\n' + \
'<signed-credential '
template += 'xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:noNamespaceSchemaLocation="http://www.geni.net/resources/credential/2/credential.xsd" xsi:schemaLocation="http://www.protogeni.net/resources/credential/ext/policy/1 http://www.protogeni.net/resources/credential/ext/policy/1/policy.xsd"'
template += '>\n' + \
'<credential xml:id="%s">\n' + \
'<type>abac</type>\n' + \
'<serial/>\n' +\
'<owner_gid/>\n' + \
'<owner_urn/>\n' + \
'<target_gid/>\n' + \
'<target_urn/>\n' + \
'<uuid/>\n' + \
'<expires>%s</expires>' +\
'<abac>\n' + \
'<rt0>\n' + \
'<version>%s</version>\n' + \
'<head>\n' + \
'<ABACprincipal><keyid>%s</keyid><mnemonic>%s</mnemonic></ABACprincipal>\n' +\
'<role>speaks_for_%s</role>\n' + \
'</head>\n' + \
'<tail>\n' +\
'<ABACprincipal><keyid>%s</keyid><mnemonic>%s</mnemonic></ABACprincipal>\n' +\
'</tail>\n' +\
'</rt0>\n' + \
'</abac>\n' + \
'</credential>\n' + \
signature_block + \
'</signed-credential>\n'
credential_duration = datetime.timedelta(days=dur_days)
expiration = datetime.datetime.now(du_tz.tzutc()) + credential_duration
expiration_str = expiration.strftime('%Y-%m-%dT%H:%M:%SZ') # FIXME: libabac can't handle .isoformat()
version = "1.1"
user_keyid = get_cert_keyid(user_gid)
tool_keyid = get_cert_keyid(tool_gid)
unsigned_cred = template % (reference, expiration_str, version, \
user_keyid, user_urn, user_keyid, tool_keyid, tool_urn, \
reference, reference)
unsigned_cred_filename = write_to_tempfile(unsigned_cred)
# Now sign the file with xmlsec1
# xmlsec1 --sign --privkey-pem privkey.pem,cert.pem
# --output signed.xml tosign.xml
pems = "%s,%s,%s" % (user_key_file, user_gid.get_filename(),
ma_gid.get_filename())
# FIXME: assumes xmlsec1 is on path
cmd = ['xmlsec1', '--sign', '--privkey-pem', pems,
'--output', cred_filename, unsigned_cred_filename]
# print " ".join(cmd)
sign_proc_output = run_subprocess(cmd, stdout=subprocess.PIPE, stderr=None)
if sign_proc_output == None:
print "OUTPUT = %s" % sign_proc_output
else:
print "Created ABAC credential: '%s speaks_for %s' in file %s" % \
(tool_urn, user_urn, cred_filename)
os.unlink(unsigned_cred_filename)
# Test procedure
if __name__ == "__main__":
parser = optparse.OptionParser()
parser.add_option('--cred_file',
help='Name of credential file')
parser.add_option('--tool_cert_file',
help='Name of file containing tool certificate')
parser.add_option('--user_urn',
help='URN of speaks-for user')
parser.add_option('--user_cert_file',
help="filename of x509 certificate of signing user")
parser.add_option('--ma_cert_file',
help="filename of x509 cert of MA that signed user cert")
parser.add_option('--user_key_file',
help="filename of private key of signing user")
parser.add_option('--trusted_roots_directory',
help='Directory of trusted root certs')
parser.add_option('--create',
help="name of file of ABAC speaksfor cred to create")
parser.add_option('--useObject', action='store_true', default=False,
help='Use the ABACCredential object to create the credential (default False)')
options, args = parser.parse_args(sys.argv)
tool_gid = GID(filename=options.tool_cert_file)
if options.create:
if options.user_cert_file and options.user_key_file \
and options.ma_cert_file:
user_gid = GID(filename=options.user_cert_file)
ma_gid = GID(filename=options.ma_cert_file)
if options.useObject:
create_sign_abaccred(tool_gid, user_gid, ma_gid, \
options.user_key_file, \
options.create)
else:
create_speaks_for(tool_gid, user_gid, ma_gid, \
options.user_key_file, \
options.create)
else:
print "Usage: --create cred_file " + \
"--user_cert_file user_cert_file" + \
" --user_key_file user_key_file --ma_cert_file ma_cert_file"
sys.exit()
user_urn = options.user_urn
# Get list of trusted rootcerts
if options.cred_file and not options.trusted_roots_directory:
sys.exit("Must supply --trusted_roots_directory to validate a credential")
trusted_roots_directory = options.trusted_roots_directory
trusted_roots = \
[Certificate(filename=os.path.join(trusted_roots_directory, file)) \
for file in os.listdir(trusted_roots_directory) \
if file.endswith('.pem') and file != 'CATedCACerts.pem']
cred = open(options.cred_file).read()
creds = [{'geni_type' : ABACCredential.ABAC_CREDENTIAL_TYPE, 'geni_value' : cred,
'geni_version' : '1'}]
gid = determine_speaks_for(None, creds, tool_gid, \
{'geni_speaking_for' : user_urn}, \
trusted_roots)
print 'SPEAKS_FOR = %s' % (gid != tool_gid)
print "CERT URN = %s" % gid.get_urn()
| return False, None, "Invalid ABAC-SF credential: Need exactly 1 tail element, got %d (%s)" % \
(len(tails), cred.get_summary_tostring()) | conditional_block |
speaksfor_util.py | #----------------------------------------------------------------------
# Copyright (c) 2014 Raytheon BBN Technologies
#
# Permission is hereby granted, free of charge, to any person obtaining
# a copy of this software and/or hardware specification (the "Work") to
# deal in the Work without restriction, including without limitation the
# rights to use, copy, modify, merge, publish, distribute, sublicense,
# and/or sell copies of the Work, and to permit persons to whom the Work
# is furnished to do so, subject to the following conditions:
#
# The above copyright notice and this permission notice shall be
# included in all copies or substantial portions of the Work.
#
# THE WORK IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS
# OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
# MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
# NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT
# HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY,
# WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
# OUT OF OR IN CONNECTION WITH THE WORK OR THE USE OR OTHER DEALINGS
# IN THE WORK.
#----------------------------------------------------------------------
from __future__ import absolute_import
import datetime
from dateutil import parser as du_parser, tz as du_tz
import optparse
import os
import subprocess
import sys
import tempfile
from xml.dom.minidom import *
from StringIO import StringIO
from extensions.sfa.trust.abac_credential import ABACCredential, ABACElement
from extensions.sfa.trust.certificate import Certificate
from extensions.sfa.trust.credential import Credential, signature_template, HAVELXML
from extensions.sfa.trust.credential_factory import CredentialFactory
from extensions.sfa.trust.gid import GID
# Routine to validate that a speaks-for credential
# says what it claims to say:
# It is a signed credential wherein the signer S is attesting to the
# ABAC statement:
# S.speaks_for(S)<-T Or "S says that T speaks for S"
# Requires that openssl be installed and in the path
# create_speaks_for requires that xmlsec1 be on the path
# Simple XML helper functions
# Find the text associated with first child text node
def findTextChildValue(root):
child = findChildNamed(root, '#text')
if child: return str(child.nodeValue)
return None
# Find first child with given name
def findChildNamed(root, name):
for child in root.childNodes:
if child.nodeName == name:
return child
return None
# Write a string to a tempfile, returning name of tempfile
def write_to_tempfile(str):
str_fd, str_file = tempfile.mkstemp()
if str: | def run_subprocess(cmd, stdout, stderr):
try:
proc = subprocess.Popen(cmd, stdout=stdout, stderr=stderr)
proc.wait()
if stdout:
output = proc.stdout.read()
else:
output = proc.returncode
return output
except Exception as e:
raise Exception("Failed call to subprocess '%s': %s" % (" ".join(cmd), e))
def get_cert_keyid(gid):
"""Extract the subject key identifier from the given certificate.
Return they key id as lowercase string with no colon separators
between pairs. The key id as shown in the text output of a
certificate are in uppercase with colon separators.
"""
raw_key_id = gid.get_extension('subjectKeyIdentifier')
# Raw has colons separating pairs, and all characters are upper case.
# Remove the colons and convert to lower case.
keyid = raw_key_id.replace(':', '').lower()
return keyid
# Pull the cert out of a list of certs in a PEM formatted cert string
def grab_toplevel_cert(cert):
start_label = '-----BEGIN CERTIFICATE-----'
if cert.find(start_label) > -1:
start_index = cert.find(start_label) + len(start_label)
else:
start_index = 0
end_label = '-----END CERTIFICATE-----'
end_index = cert.find(end_label)
first_cert = cert[start_index:end_index]
pieces = first_cert.split('\n')
first_cert = "".join(pieces)
return first_cert
# Validate that the given speaks-for credential represents the
# statement User.speaks_for(User)<-Tool for the given user and tool certs
# and was signed by the user
# Return:
# Boolean indicating whether the given credential
# is not expired
# is an ABAC credential
# was signed by the user associated with the speaking_for_urn
# is verified by xmlsec1
# asserts U.speaks_for(U)<-T ("user says that T may speak for user")
# If schema provided, validate against schema
# is trusted by given set of trusted roots (both user cert and tool cert)
# String user certificate of speaking_for user if the above tests succeed
# (None otherwise)
# Error message indicating why the speaks_for call failed ("" otherwise)
def verify_speaks_for(cred, tool_gid, speaking_for_urn, \
trusted_roots, schema=None, logger=None):
# Credential has not expired
if cred.expiration and cred.expiration < datetime.datetime.utcnow():
return False, None, "ABAC Credential expired at %s (%s)" % (cred.expiration.isoformat(), cred.get_summary_tostring())
# Must be ABAC
if cred.get_cred_type() != ABACCredential.ABAC_CREDENTIAL_TYPE:
return False, None, "Credential not of type ABAC but %s" % cred.get_cred_type
if cred.signature is None or cred.signature.gid is None:
return False, None, "Credential malformed: missing signature or signer cert. Cred: %s" % cred.get_summary_tostring()
user_gid = cred.signature.gid
user_urn = user_gid.get_urn()
# URN of signer from cert must match URN of 'speaking-for' argument
if user_urn != speaking_for_urn:
return False, None, "User URN from cred doesn't match speaking_for URN: %s != %s (cred %s)" % \
(user_urn, speaking_for_urn, cred.get_summary_tostring())
tails = cred.get_tails()
if len(tails) != 1:
return False, None, "Invalid ABAC-SF credential: Need exactly 1 tail element, got %d (%s)" % \
(len(tails), cred.get_summary_tostring())
user_keyid = get_cert_keyid(user_gid)
tool_keyid = get_cert_keyid(tool_gid)
subject_keyid = tails[0].get_principal_keyid()
head = cred.get_head()
principal_keyid = head.get_principal_keyid()
role = head.get_role()
# Credential must pass xmlsec1 verify
cred_file = write_to_tempfile(cred.save_to_string())
cert_args = []
if trusted_roots:
for x in trusted_roots:
cert_args += ['--trusted-pem', x.filename]
# FIXME: Why do we not need to specify the --node-id option as credential.py does?
xmlsec1_args = [cred.xmlsec_path, '--verify'] + cert_args + [ cred_file]
output = run_subprocess(xmlsec1_args, stdout=None, stderr=subprocess.PIPE)
os.unlink(cred_file)
if output != 0:
# FIXME
# xmlsec errors have a msg= which is the interesting bit.
# But does this go to stderr or stdout? Do we have it here?
verified = ""
mstart = verified.find("msg=")
msg = ""
if mstart > -1 and len(verified) > 4:
mstart = mstart + 4
mend = verified.find('\\', mstart)
msg = verified[mstart:mend]
if msg == "":
msg = output
return False, None, "ABAC credential failed to xmlsec1 verify: %s" % msg
# Must say U.speaks_for(U)<-T
if user_keyid != principal_keyid or \
tool_keyid != subject_keyid or \
role != ('speaks_for_%s' % user_keyid):
return False, None, "ABAC statement doesn't assert U.speaks_for(U)<-T (%s)" % cred.get_summary_tostring()
# If schema provided, validate against schema
if HAVELXML and schema and os.path.exists(schema):
from lxml import etree
tree = etree.parse(StringIO(cred.xml))
schema_doc = etree.parse(schema)
xmlschema = etree.XMLSchema(schema_doc)
if not xmlschema.validate(tree):
error = xmlschema.error_log.last_error
message = "%s: %s (line %s)" % (cred.get_summary_tostring(), error.message, error.line)
return False, None, ("XML Credential schema invalid: %s" % message)
if trusted_roots:
# User certificate must validate against trusted roots
try:
user_gid.verify_chain(trusted_roots)
except Exception, e:
return False, None, \
"Cred signer (user) cert not trusted: %s" % e
# Tool certificate must validate against trusted roots
try:
tool_gid.verify_chain(trusted_roots)
except Exception, e:
return False, None, \
"Tool cert not trusted: %s" % e
return True, user_gid, ""
# Determine if this is a speaks-for context. If so, validate
# And return either the tool_cert (not speaks-for or not validated)
# or the user cert (validated speaks-for)
#
# credentials is a list of GENI-style credentials:
# Either a cred string xml string, or Credential object of a tuple
# [{'geni_type' : geni_type, 'geni_value : cred_value,
# 'geni_version' : version}]
# caller_gid is the raw X509 cert gid
# options is the dictionary of API-provided options
# trusted_roots is a list of Certificate objects from the system
# trusted_root directory
# Optionally, provide an XML schema against which to validate the credential
def determine_speaks_for(logger, credentials, caller_gid, options, \
trusted_roots, schema=None):
if options and 'geni_speaking_for' in options:
speaking_for_urn = options['geni_speaking_for'].strip()
for cred in credentials:
# Skip things that aren't ABAC credentials
if type(cred) == dict:
if cred['geni_type'] != ABACCredential.ABAC_CREDENTIAL_TYPE: continue
cred_value = cred['geni_value']
elif isinstance(cred, Credential):
if not isinstance(cred, ABACCredential):
continue
else:
cred_value = cred
else:
if CredentialFactory.getType(cred) != ABACCredential.ABAC_CREDENTIAL_TYPE: continue
cred_value = cred
# If the cred_value is xml, create the object
if not isinstance(cred_value, ABACCredential):
cred = CredentialFactory.createCred(cred_value)
# print "Got a cred to check speaksfor for: %s" % cred.get_summary_tostring()
# #cred.dump(True, True)
# print "Caller: %s" % caller_gid.dump_string(2, True)
# See if this is a valid speaks_for
is_valid_speaks_for, user_gid, msg = \
verify_speaks_for(cred,
caller_gid, speaking_for_urn, \
trusted_roots, schema, logger)
if is_valid_speaks_for:
return user_gid # speaks-for
else:
if logger:
logger.info("Got speaks-for option but not a valid speaks_for with this credential: %s" % msg)
else:
print "Got a speaks-for option but not a valid speaks_for with this credential: " + msg
return caller_gid # Not speaks-for
# Create an ABAC Speaks For credential using the ABACCredential object and it's encode&sign methods
def create_sign_abaccred(tool_gid, user_gid, ma_gid, user_key_file, cred_filename, dur_days=365):
print "Creating ABAC SpeaksFor using ABACCredential...\n"
# Write out the user cert
from tempfile import mkstemp
ma_str = ma_gid.save_to_string()
user_cert_str = user_gid.save_to_string()
if not user_cert_str.endswith(ma_str):
user_cert_str += ma_str
fp, user_cert_filename = mkstemp(suffix='cred', text=True)
fp = os.fdopen(fp, "w")
fp.write(user_cert_str)
fp.close()
# Create the cred
cred = ABACCredential()
cred.set_issuer_keys(user_key_file, user_cert_filename)
tool_urn = tool_gid.get_urn()
user_urn = user_gid.get_urn()
user_keyid = get_cert_keyid(user_gid)
tool_keyid = get_cert_keyid(tool_gid)
cred.head = ABACElement(user_keyid, user_urn, "speaks_for_%s" % user_keyid)
cred.tails.append(ABACElement(tool_keyid, tool_urn))
cred.set_expiration(datetime.datetime.utcnow() + datetime.timedelta(days=dur_days))
cred.expiration = cred.expiration.replace(microsecond=0)
# Produce the cred XML
cred.encode()
# Sign it
cred.sign()
# Save it
cred.save_to_file(cred_filename)
print "Created ABAC credential: '%s' in file %s" % \
(cred.get_summary_tostring(), cred_filename)
# FIXME: Assumes xmlsec1 is on path
# FIXME: Assumes signer is itself signed by an 'ma_gid' that can be trusted
def create_speaks_for(tool_gid, user_gid, ma_gid, \
user_key_file, cred_filename, dur_days=365):
tool_urn = tool_gid.get_urn()
user_urn = user_gid.get_urn()
header = '<?xml version="1.0" encoding="UTF-8"?>'
reference = "ref0"
signature_block = \
'<signatures>\n' + \
signature_template + \
'</signatures>'
template = header + '\n' + \
'<signed-credential '
template += 'xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:noNamespaceSchemaLocation="http://www.geni.net/resources/credential/2/credential.xsd" xsi:schemaLocation="http://www.protogeni.net/resources/credential/ext/policy/1 http://www.protogeni.net/resources/credential/ext/policy/1/policy.xsd"'
template += '>\n' + \
'<credential xml:id="%s">\n' + \
'<type>abac</type>\n' + \
'<serial/>\n' +\
'<owner_gid/>\n' + \
'<owner_urn/>\n' + \
'<target_gid/>\n' + \
'<target_urn/>\n' + \
'<uuid/>\n' + \
'<expires>%s</expires>' +\
'<abac>\n' + \
'<rt0>\n' + \
'<version>%s</version>\n' + \
'<head>\n' + \
'<ABACprincipal><keyid>%s</keyid><mnemonic>%s</mnemonic></ABACprincipal>\n' +\
'<role>speaks_for_%s</role>\n' + \
'</head>\n' + \
'<tail>\n' +\
'<ABACprincipal><keyid>%s</keyid><mnemonic>%s</mnemonic></ABACprincipal>\n' +\
'</tail>\n' +\
'</rt0>\n' + \
'</abac>\n' + \
'</credential>\n' + \
signature_block + \
'</signed-credential>\n'
credential_duration = datetime.timedelta(days=dur_days)
expiration = datetime.datetime.now(du_tz.tzutc()) + credential_duration
expiration_str = expiration.strftime('%Y-%m-%dT%H:%M:%SZ') # FIXME: libabac can't handle .isoformat()
version = "1.1"
user_keyid = get_cert_keyid(user_gid)
tool_keyid = get_cert_keyid(tool_gid)
unsigned_cred = template % (reference, expiration_str, version, \
user_keyid, user_urn, user_keyid, tool_keyid, tool_urn, \
reference, reference)
unsigned_cred_filename = write_to_tempfile(unsigned_cred)
# Now sign the file with xmlsec1
# xmlsec1 --sign --privkey-pem privkey.pem,cert.pem
# --output signed.xml tosign.xml
pems = "%s,%s,%s" % (user_key_file, user_gid.get_filename(),
ma_gid.get_filename())
# FIXME: assumes xmlsec1 is on path
cmd = ['xmlsec1', '--sign', '--privkey-pem', pems,
'--output', cred_filename, unsigned_cred_filename]
# print " ".join(cmd)
sign_proc_output = run_subprocess(cmd, stdout=subprocess.PIPE, stderr=None)
if sign_proc_output == None:
print "OUTPUT = %s" % sign_proc_output
else:
print "Created ABAC credential: '%s speaks_for %s' in file %s" % \
(tool_urn, user_urn, cred_filename)
os.unlink(unsigned_cred_filename)
# Test procedure
if __name__ == "__main__":
parser = optparse.OptionParser()
parser.add_option('--cred_file',
help='Name of credential file')
parser.add_option('--tool_cert_file',
help='Name of file containing tool certificate')
parser.add_option('--user_urn',
help='URN of speaks-for user')
parser.add_option('--user_cert_file',
help="filename of x509 certificate of signing user")
parser.add_option('--ma_cert_file',
help="filename of x509 cert of MA that signed user cert")
parser.add_option('--user_key_file',
help="filename of private key of signing user")
parser.add_option('--trusted_roots_directory',
help='Directory of trusted root certs')
parser.add_option('--create',
help="name of file of ABAC speaksfor cred to create")
parser.add_option('--useObject', action='store_true', default=False,
help='Use the ABACCredential object to create the credential (default False)')
options, args = parser.parse_args(sys.argv)
tool_gid = GID(filename=options.tool_cert_file)
if options.create:
if options.user_cert_file and options.user_key_file \
and options.ma_cert_file:
user_gid = GID(filename=options.user_cert_file)
ma_gid = GID(filename=options.ma_cert_file)
if options.useObject:
create_sign_abaccred(tool_gid, user_gid, ma_gid, \
options.user_key_file, \
options.create)
else:
create_speaks_for(tool_gid, user_gid, ma_gid, \
options.user_key_file, \
options.create)
else:
print "Usage: --create cred_file " + \
"--user_cert_file user_cert_file" + \
" --user_key_file user_key_file --ma_cert_file ma_cert_file"
sys.exit()
user_urn = options.user_urn
# Get list of trusted rootcerts
if options.cred_file and not options.trusted_roots_directory:
sys.exit("Must supply --trusted_roots_directory to validate a credential")
trusted_roots_directory = options.trusted_roots_directory
trusted_roots = \
[Certificate(filename=os.path.join(trusted_roots_directory, file)) \
for file in os.listdir(trusted_roots_directory) \
if file.endswith('.pem') and file != 'CATedCACerts.pem']
cred = open(options.cred_file).read()
creds = [{'geni_type' : ABACCredential.ABAC_CREDENTIAL_TYPE, 'geni_value' : cred,
'geni_version' : '1'}]
gid = determine_speaks_for(None, creds, tool_gid, \
{'geni_speaking_for' : user_urn}, \
trusted_roots)
print 'SPEAKS_FOR = %s' % (gid != tool_gid)
print "CERT URN = %s" % gid.get_urn() | os.write(str_fd, str)
os.close(str_fd)
return str_file
# Run a subprocess and return output | random_line_split |
view.py | # Webhooks for external integrations.
from __future__ import absolute_import
from typing import Any, Dict, List, Optional, Text, Tuple
from django.utils.translation import ugettext as _
from django.db.models import Q
from django.conf import settings
from django.http import HttpRequest, HttpResponse
from zerver.models import UserProfile, get_user_profile_by_email, Realm
from zerver.lib.actions import check_send_message
from zerver.lib.response import json_success, json_error
from zerver.decorator import api_key_only_webhook_view, has_request_variables, REQ
import logging
import re
import ujson
IGNORED_EVENTS = [ | def guess_zulip_user_from_jira(jira_username, realm):
# type: (Text, Realm) -> Optional[UserProfile]
try:
# Try to find a matching user in Zulip
# We search a user's full name, short name,
# and beginning of email address
user = UserProfile.objects.filter(
Q(full_name__iexact=jira_username) |
Q(short_name__iexact=jira_username) |
Q(email__istartswith=jira_username),
is_active=True,
realm=realm).order_by("id")[0]
return user
except IndexError:
return None
def convert_jira_markup(content, realm):
# type: (Text, Realm) -> Text
# Attempt to do some simplistic conversion of JIRA
# formatting to Markdown, for consumption in Zulip
# Jira uses *word* for bold, we use **word**
content = re.sub(r'\*([^\*]+)\*', r'**\1**', content)
# Jira uses {{word}} for monospacing, we use `word`
content = re.sub(r'{{([^\*]+?)}}', r'`\1`', content)
# Starting a line with bq. block quotes that line
content = re.sub(r'bq\. (.*)', r'> \1', content)
# Wrapping a block of code in {quote}stuff{quote} also block-quotes it
quote_re = re.compile(r'{quote}(.*?){quote}', re.DOTALL)
content = re.sub(quote_re, r'~~~ quote\n\1\n~~~', content)
# {noformat}stuff{noformat} blocks are just code blocks with no
# syntax highlighting
noformat_re = re.compile(r'{noformat}(.*?){noformat}', re.DOTALL)
content = re.sub(noformat_re, r'~~~\n\1\n~~~', content)
# Code blocks are delineated by {code[: lang]} {code}
code_re = re.compile(r'{code[^\n]*}(.*?){code}', re.DOTALL)
content = re.sub(code_re, r'~~~\n\1\n~~~', content)
# Links are of form: [https://www.google.com] or [Link Title|https://www.google.com]
# In order to support both forms, we don't match a | in bare links
content = re.sub(r'\[([^\|~]+?)\]', r'[\1](\1)', content)
# Full links which have a | are converted into a better markdown link
full_link_re = re.compile(r'\[(?:(?P<title>[^|~]+)\|)(?P<url>.*)\]')
content = re.sub(full_link_re, r'[\g<title>](\g<url>)', content)
# Try to convert a JIRA user mention of format [~username] into a
# Zulip user mention. We don't know the email, just the JIRA username,
# so we naively guess at their Zulip account using this
if realm:
mention_re = re.compile(u'\[~(.*?)\]')
for username in mention_re.findall(content):
# Try to look up username
user_profile = guess_zulip_user_from_jira(username, realm)
if user_profile:
replacement = u"**{}**".format(user_profile.full_name)
else:
replacement = u"**{}**".format(username)
content = content.replace("[~{}]".format(username,), replacement)
return content
def get_in(payload, keys, default=''):
# type: (Dict[str, Any], List[str], Text) -> Any
try:
for key in keys:
payload = payload[key]
except (AttributeError, KeyError, TypeError):
return default
return payload
def get_issue_string(payload, issue_id=None):
# type: (Dict[str, Any], Text) -> Text
# Guess the URL as it is not specified in the payload
# We assume that there is a /browse/BUG-### page
# from the REST url of the issue itself
if issue_id is None:
issue_id = get_issue_id(payload)
base_url = re.match("(.*)\/rest\/api/.*", get_in(payload, ['issue', 'self']))
if base_url and len(base_url.groups()):
return u"[{}]({}/browse/{})".format(issue_id, base_url.group(1), issue_id)
else:
return issue_id
def get_assignee_mention(assignee_email):
# type: (Text) -> Text
if assignee_email != '':
try:
assignee_name = get_user_profile_by_email(assignee_email).full_name
except UserProfile.DoesNotExist:
assignee_name = assignee_email
return u"**{}**".format(assignee_name)
return ''
def get_issue_author(payload):
# type: (Dict[str, Any]) -> Text
return get_in(payload, ['user', 'displayName'])
def get_issue_id(payload):
# type: (Dict[str, Any]) -> Text
return get_in(payload, ['issue', 'key'])
def get_issue_title(payload):
# type: (Dict[str, Any]) -> Text
return get_in(payload, ['issue', 'fields', 'summary'])
def get_issue_subject(payload):
# type: (Dict[str, Any]) -> Text
return u"{}: {}".format(get_issue_id(payload), get_issue_title(payload))
def get_sub_event_for_update_issue(payload):
# type: (Dict[str, Any]) -> Text
sub_event = payload.get('issue_event_type_name', '')
if sub_event == '':
if payload.get('comment'):
return 'issue_commented'
elif payload.get('transition'):
return 'issue_transited'
return sub_event
def get_event_type(payload):
# type: (Dict[str, Any]) -> Optional[Text]
event = payload.get('webhookEvent')
if event is None and payload.get('transition'):
event = 'jira:issue_updated'
return event
def add_change_info(content, field, from_field, to_field):
# type: (Text, Text, Text, Text) -> Text
content += u"* Changed {}".format(field)
if from_field:
content += u" from **{}**".format(from_field)
if to_field:
content += u" to {}\n".format(to_field)
return content
def handle_updated_issue_event(payload, user_profile):
# Reassigned, commented, reopened, and resolved events are all bundled
# into this one 'updated' event type, so we try to extract the meaningful
# event that happened
# type: (Dict[str, Any], UserProfile) -> Text
issue_id = get_in(payload, ['issue', 'key'])
issue = get_issue_string(payload, issue_id)
assignee_email = get_in(payload, ['issue', 'fields', 'assignee', 'emailAddress'], '')
assignee_mention = get_assignee_mention(assignee_email)
if assignee_mention != '':
assignee_blurb = u" (assigned to {})".format(assignee_mention)
else:
assignee_blurb = ''
sub_event = get_sub_event_for_update_issue(payload)
if 'comment' in sub_event:
if sub_event == 'issue_commented':
verb = 'added comment to'
elif sub_event == 'issue_comment_edited':
verb = 'edited comment on'
else:
verb = 'deleted comment from'
content = u"{} **{}** {}{}".format(get_issue_author(payload), verb, issue, assignee_blurb)
comment = get_in(payload, ['comment', 'body'])
if comment:
comment = convert_jira_markup(comment, user_profile.realm)
content = u"{}:\n\n\n{}\n".format(content, comment)
else:
content = u"{} **updated** {}{}:\n\n".format(get_issue_author(payload), issue, assignee_blurb)
changelog = get_in(payload, ['changelog'])
if changelog != '':
# Use the changelog to display the changes, whitelist types we accept
items = changelog.get('items')
for item in items:
field = item.get('field')
if field == 'assignee' and assignee_mention != '':
target_field_string = assignee_mention
else:
# Convert a user's target to a @-mention if possible
target_field_string = u"**{}**".format(item.get('toString'))
from_field_string = item.get('fromString')
if target_field_string or from_field_string:
content = add_change_info(content, field, from_field_string, target_field_string)
elif sub_event == 'issue_transited':
from_field_string = get_in(payload, ['transition', 'from_status'])
target_field_string = u'**{}**'.format(get_in(payload, ['transition', 'to_status']))
if target_field_string or from_field_string:
content = add_change_info(content, 'status', from_field_string, target_field_string)
return content
def handle_created_issue_event(payload):
# type: (Dict[str, Any]) -> Text
return u"{} **created** {} priority {}, assigned to **{}**:\n\n> {}".format(
get_issue_author(payload),
get_issue_string(payload),
get_in(payload, ['issue', 'fields', 'priority', 'name']),
get_in(payload, ['issue', 'fields', 'assignee', 'displayName'], 'no one'),
get_issue_title(payload)
)
def handle_deleted_issue_event(payload):
# type: (Dict[str, Any]) -> Text
return u"{} **deleted** {}!".format(get_issue_author(payload), get_issue_string(payload))
@api_key_only_webhook_view("JIRA")
@has_request_variables
def api_jira_webhook(request, user_profile,
payload=REQ(argument_type='body'),
stream=REQ(default='jira')):
# type: (HttpRequest, UserProfile, Dict[str, Any], Text) -> HttpResponse
event = get_event_type(payload)
if event == 'jira:issue_created':
subject = get_issue_subject(payload)
content = handle_created_issue_event(payload)
elif event == 'jira:issue_deleted':
subject = get_issue_subject(payload)
content = handle_deleted_issue_event(payload)
elif event == 'jira:issue_updated':
subject = get_issue_subject(payload)
content = handle_updated_issue_event(payload, user_profile)
elif event in IGNORED_EVENTS:
return json_success()
else:
if event is None:
if not settings.TEST_SUITE:
message = u"Got JIRA event with None event type: {}".format(payload)
logging.warning(message)
return json_error(_("Event is not given by JIRA"))
else:
if not settings.TEST_SUITE:
logging.warning("Got JIRA event type we don't support: {}".format(event))
return json_success()
check_send_message(user_profile, request.client, "stream", [stream], subject, content)
return json_success() | 'comment_created', # we handle issue_update event instead
'comment_updated', # we handle issue_update event instead
'comment_deleted', # we handle issue_update event instead
]
| random_line_split |
view.py | # Webhooks for external integrations.
from __future__ import absolute_import
from typing import Any, Dict, List, Optional, Text, Tuple
from django.utils.translation import ugettext as _
from django.db.models import Q
from django.conf import settings
from django.http import HttpRequest, HttpResponse
from zerver.models import UserProfile, get_user_profile_by_email, Realm
from zerver.lib.actions import check_send_message
from zerver.lib.response import json_success, json_error
from zerver.decorator import api_key_only_webhook_view, has_request_variables, REQ
import logging
import re
import ujson
IGNORED_EVENTS = [
'comment_created', # we handle issue_update event instead
'comment_updated', # we handle issue_update event instead
'comment_deleted', # we handle issue_update event instead
]
def guess_zulip_user_from_jira(jira_username, realm):
# type: (Text, Realm) -> Optional[UserProfile]
try:
# Try to find a matching user in Zulip
# We search a user's full name, short name,
# and beginning of email address
user = UserProfile.objects.filter(
Q(full_name__iexact=jira_username) |
Q(short_name__iexact=jira_username) |
Q(email__istartswith=jira_username),
is_active=True,
realm=realm).order_by("id")[0]
return user
except IndexError:
return None
def convert_jira_markup(content, realm):
# type: (Text, Realm) -> Text
# Attempt to do some simplistic conversion of JIRA
# formatting to Markdown, for consumption in Zulip
# Jira uses *word* for bold, we use **word**
content = re.sub(r'\*([^\*]+)\*', r'**\1**', content)
# Jira uses {{word}} for monospacing, we use `word`
content = re.sub(r'{{([^\*]+?)}}', r'`\1`', content)
# Starting a line with bq. block quotes that line
content = re.sub(r'bq\. (.*)', r'> \1', content)
# Wrapping a block of code in {quote}stuff{quote} also block-quotes it
quote_re = re.compile(r'{quote}(.*?){quote}', re.DOTALL)
content = re.sub(quote_re, r'~~~ quote\n\1\n~~~', content)
# {noformat}stuff{noformat} blocks are just code blocks with no
# syntax highlighting
noformat_re = re.compile(r'{noformat}(.*?){noformat}', re.DOTALL)
content = re.sub(noformat_re, r'~~~\n\1\n~~~', content)
# Code blocks are delineated by {code[: lang]} {code}
code_re = re.compile(r'{code[^\n]*}(.*?){code}', re.DOTALL)
content = re.sub(code_re, r'~~~\n\1\n~~~', content)
# Links are of form: [https://www.google.com] or [Link Title|https://www.google.com]
# In order to support both forms, we don't match a | in bare links
content = re.sub(r'\[([^\|~]+?)\]', r'[\1](\1)', content)
# Full links which have a | are converted into a better markdown link
full_link_re = re.compile(r'\[(?:(?P<title>[^|~]+)\|)(?P<url>.*)\]')
content = re.sub(full_link_re, r'[\g<title>](\g<url>)', content)
# Try to convert a JIRA user mention of format [~username] into a
# Zulip user mention. We don't know the email, just the JIRA username,
# so we naively guess at their Zulip account using this
if realm:
mention_re = re.compile(u'\[~(.*?)\]')
for username in mention_re.findall(content):
# Try to look up username
user_profile = guess_zulip_user_from_jira(username, realm)
if user_profile:
replacement = u"**{}**".format(user_profile.full_name)
else:
replacement = u"**{}**".format(username)
content = content.replace("[~{}]".format(username,), replacement)
return content
def get_in(payload, keys, default=''):
# type: (Dict[str, Any], List[str], Text) -> Any
try:
for key in keys:
payload = payload[key]
except (AttributeError, KeyError, TypeError):
return default
return payload
def | (payload, issue_id=None):
# type: (Dict[str, Any], Text) -> Text
# Guess the URL as it is not specified in the payload
# We assume that there is a /browse/BUG-### page
# from the REST url of the issue itself
if issue_id is None:
issue_id = get_issue_id(payload)
base_url = re.match("(.*)\/rest\/api/.*", get_in(payload, ['issue', 'self']))
if base_url and len(base_url.groups()):
return u"[{}]({}/browse/{})".format(issue_id, base_url.group(1), issue_id)
else:
return issue_id
def get_assignee_mention(assignee_email):
# type: (Text) -> Text
if assignee_email != '':
try:
assignee_name = get_user_profile_by_email(assignee_email).full_name
except UserProfile.DoesNotExist:
assignee_name = assignee_email
return u"**{}**".format(assignee_name)
return ''
def get_issue_author(payload):
# type: (Dict[str, Any]) -> Text
return get_in(payload, ['user', 'displayName'])
def get_issue_id(payload):
# type: (Dict[str, Any]) -> Text
return get_in(payload, ['issue', 'key'])
def get_issue_title(payload):
# type: (Dict[str, Any]) -> Text
return get_in(payload, ['issue', 'fields', 'summary'])
def get_issue_subject(payload):
# type: (Dict[str, Any]) -> Text
return u"{}: {}".format(get_issue_id(payload), get_issue_title(payload))
def get_sub_event_for_update_issue(payload):
# type: (Dict[str, Any]) -> Text
sub_event = payload.get('issue_event_type_name', '')
if sub_event == '':
if payload.get('comment'):
return 'issue_commented'
elif payload.get('transition'):
return 'issue_transited'
return sub_event
def get_event_type(payload):
# type: (Dict[str, Any]) -> Optional[Text]
event = payload.get('webhookEvent')
if event is None and payload.get('transition'):
event = 'jira:issue_updated'
return event
def add_change_info(content, field, from_field, to_field):
# type: (Text, Text, Text, Text) -> Text
content += u"* Changed {}".format(field)
if from_field:
content += u" from **{}**".format(from_field)
if to_field:
content += u" to {}\n".format(to_field)
return content
def handle_updated_issue_event(payload, user_profile):
# Reassigned, commented, reopened, and resolved events are all bundled
# into this one 'updated' event type, so we try to extract the meaningful
# event that happened
# type: (Dict[str, Any], UserProfile) -> Text
issue_id = get_in(payload, ['issue', 'key'])
issue = get_issue_string(payload, issue_id)
assignee_email = get_in(payload, ['issue', 'fields', 'assignee', 'emailAddress'], '')
assignee_mention = get_assignee_mention(assignee_email)
if assignee_mention != '':
assignee_blurb = u" (assigned to {})".format(assignee_mention)
else:
assignee_blurb = ''
sub_event = get_sub_event_for_update_issue(payload)
if 'comment' in sub_event:
if sub_event == 'issue_commented':
verb = 'added comment to'
elif sub_event == 'issue_comment_edited':
verb = 'edited comment on'
else:
verb = 'deleted comment from'
content = u"{} **{}** {}{}".format(get_issue_author(payload), verb, issue, assignee_blurb)
comment = get_in(payload, ['comment', 'body'])
if comment:
comment = convert_jira_markup(comment, user_profile.realm)
content = u"{}:\n\n\n{}\n".format(content, comment)
else:
content = u"{} **updated** {}{}:\n\n".format(get_issue_author(payload), issue, assignee_blurb)
changelog = get_in(payload, ['changelog'])
if changelog != '':
# Use the changelog to display the changes, whitelist types we accept
items = changelog.get('items')
for item in items:
field = item.get('field')
if field == 'assignee' and assignee_mention != '':
target_field_string = assignee_mention
else:
# Convert a user's target to a @-mention if possible
target_field_string = u"**{}**".format(item.get('toString'))
from_field_string = item.get('fromString')
if target_field_string or from_field_string:
content = add_change_info(content, field, from_field_string, target_field_string)
elif sub_event == 'issue_transited':
from_field_string = get_in(payload, ['transition', 'from_status'])
target_field_string = u'**{}**'.format(get_in(payload, ['transition', 'to_status']))
if target_field_string or from_field_string:
content = add_change_info(content, 'status', from_field_string, target_field_string)
return content
def handle_created_issue_event(payload):
# type: (Dict[str, Any]) -> Text
return u"{} **created** {} priority {}, assigned to **{}**:\n\n> {}".format(
get_issue_author(payload),
get_issue_string(payload),
get_in(payload, ['issue', 'fields', 'priority', 'name']),
get_in(payload, ['issue', 'fields', 'assignee', 'displayName'], 'no one'),
get_issue_title(payload)
)
def handle_deleted_issue_event(payload):
# type: (Dict[str, Any]) -> Text
return u"{} **deleted** {}!".format(get_issue_author(payload), get_issue_string(payload))
@api_key_only_webhook_view("JIRA")
@has_request_variables
def api_jira_webhook(request, user_profile,
payload=REQ(argument_type='body'),
stream=REQ(default='jira')):
# type: (HttpRequest, UserProfile, Dict[str, Any], Text) -> HttpResponse
event = get_event_type(payload)
if event == 'jira:issue_created':
subject = get_issue_subject(payload)
content = handle_created_issue_event(payload)
elif event == 'jira:issue_deleted':
subject = get_issue_subject(payload)
content = handle_deleted_issue_event(payload)
elif event == 'jira:issue_updated':
subject = get_issue_subject(payload)
content = handle_updated_issue_event(payload, user_profile)
elif event in IGNORED_EVENTS:
return json_success()
else:
if event is None:
if not settings.TEST_SUITE:
message = u"Got JIRA event with None event type: {}".format(payload)
logging.warning(message)
return json_error(_("Event is not given by JIRA"))
else:
if not settings.TEST_SUITE:
logging.warning("Got JIRA event type we don't support: {}".format(event))
return json_success()
check_send_message(user_profile, request.client, "stream", [stream], subject, content)
return json_success()
| get_issue_string | identifier_name |
view.py | # Webhooks for external integrations.
from __future__ import absolute_import
from typing import Any, Dict, List, Optional, Text, Tuple
from django.utils.translation import ugettext as _
from django.db.models import Q
from django.conf import settings
from django.http import HttpRequest, HttpResponse
from zerver.models import UserProfile, get_user_profile_by_email, Realm
from zerver.lib.actions import check_send_message
from zerver.lib.response import json_success, json_error
from zerver.decorator import api_key_only_webhook_view, has_request_variables, REQ
import logging
import re
import ujson
IGNORED_EVENTS = [
'comment_created', # we handle issue_update event instead
'comment_updated', # we handle issue_update event instead
'comment_deleted', # we handle issue_update event instead
]
def guess_zulip_user_from_jira(jira_username, realm):
# type: (Text, Realm) -> Optional[UserProfile]
try:
# Try to find a matching user in Zulip
# We search a user's full name, short name,
# and beginning of email address
user = UserProfile.objects.filter(
Q(full_name__iexact=jira_username) |
Q(short_name__iexact=jira_username) |
Q(email__istartswith=jira_username),
is_active=True,
realm=realm).order_by("id")[0]
return user
except IndexError:
return None
def convert_jira_markup(content, realm):
# type: (Text, Realm) -> Text
# Attempt to do some simplistic conversion of JIRA
# formatting to Markdown, for consumption in Zulip
# Jira uses *word* for bold, we use **word**
content = re.sub(r'\*([^\*]+)\*', r'**\1**', content)
# Jira uses {{word}} for monospacing, we use `word`
content = re.sub(r'{{([^\*]+?)}}', r'`\1`', content)
# Starting a line with bq. block quotes that line
content = re.sub(r'bq\. (.*)', r'> \1', content)
# Wrapping a block of code in {quote}stuff{quote} also block-quotes it
quote_re = re.compile(r'{quote}(.*?){quote}', re.DOTALL)
content = re.sub(quote_re, r'~~~ quote\n\1\n~~~', content)
# {noformat}stuff{noformat} blocks are just code blocks with no
# syntax highlighting
noformat_re = re.compile(r'{noformat}(.*?){noformat}', re.DOTALL)
content = re.sub(noformat_re, r'~~~\n\1\n~~~', content)
# Code blocks are delineated by {code[: lang]} {code}
code_re = re.compile(r'{code[^\n]*}(.*?){code}', re.DOTALL)
content = re.sub(code_re, r'~~~\n\1\n~~~', content)
# Links are of form: [https://www.google.com] or [Link Title|https://www.google.com]
# In order to support both forms, we don't match a | in bare links
content = re.sub(r'\[([^\|~]+?)\]', r'[\1](\1)', content)
# Full links which have a | are converted into a better markdown link
full_link_re = re.compile(r'\[(?:(?P<title>[^|~]+)\|)(?P<url>.*)\]')
content = re.sub(full_link_re, r'[\g<title>](\g<url>)', content)
# Try to convert a JIRA user mention of format [~username] into a
# Zulip user mention. We don't know the email, just the JIRA username,
# so we naively guess at their Zulip account using this
if realm:
mention_re = re.compile(u'\[~(.*?)\]')
for username in mention_re.findall(content):
# Try to look up username
user_profile = guess_zulip_user_from_jira(username, realm)
if user_profile:
replacement = u"**{}**".format(user_profile.full_name)
else:
replacement = u"**{}**".format(username)
content = content.replace("[~{}]".format(username,), replacement)
return content
def get_in(payload, keys, default=''):
# type: (Dict[str, Any], List[str], Text) -> Any
try:
for key in keys:
payload = payload[key]
except (AttributeError, KeyError, TypeError):
return default
return payload
def get_issue_string(payload, issue_id=None):
# type: (Dict[str, Any], Text) -> Text
# Guess the URL as it is not specified in the payload
# We assume that there is a /browse/BUG-### page
# from the REST url of the issue itself
if issue_id is None:
issue_id = get_issue_id(payload)
base_url = re.match("(.*)\/rest\/api/.*", get_in(payload, ['issue', 'self']))
if base_url and len(base_url.groups()):
return u"[{}]({}/browse/{})".format(issue_id, base_url.group(1), issue_id)
else:
return issue_id
def get_assignee_mention(assignee_email):
# type: (Text) -> Text
if assignee_email != '':
try:
assignee_name = get_user_profile_by_email(assignee_email).full_name
except UserProfile.DoesNotExist:
assignee_name = assignee_email
return u"**{}**".format(assignee_name)
return ''
def get_issue_author(payload):
# type: (Dict[str, Any]) -> Text
return get_in(payload, ['user', 'displayName'])
def get_issue_id(payload):
# type: (Dict[str, Any]) -> Text
return get_in(payload, ['issue', 'key'])
def get_issue_title(payload):
# type: (Dict[str, Any]) -> Text
|
def get_issue_subject(payload):
# type: (Dict[str, Any]) -> Text
return u"{}: {}".format(get_issue_id(payload), get_issue_title(payload))
def get_sub_event_for_update_issue(payload):
# type: (Dict[str, Any]) -> Text
sub_event = payload.get('issue_event_type_name', '')
if sub_event == '':
if payload.get('comment'):
return 'issue_commented'
elif payload.get('transition'):
return 'issue_transited'
return sub_event
def get_event_type(payload):
# type: (Dict[str, Any]) -> Optional[Text]
event = payload.get('webhookEvent')
if event is None and payload.get('transition'):
event = 'jira:issue_updated'
return event
def add_change_info(content, field, from_field, to_field):
# type: (Text, Text, Text, Text) -> Text
content += u"* Changed {}".format(field)
if from_field:
content += u" from **{}**".format(from_field)
if to_field:
content += u" to {}\n".format(to_field)
return content
def handle_updated_issue_event(payload, user_profile):
# Reassigned, commented, reopened, and resolved events are all bundled
# into this one 'updated' event type, so we try to extract the meaningful
# event that happened
# type: (Dict[str, Any], UserProfile) -> Text
issue_id = get_in(payload, ['issue', 'key'])
issue = get_issue_string(payload, issue_id)
assignee_email = get_in(payload, ['issue', 'fields', 'assignee', 'emailAddress'], '')
assignee_mention = get_assignee_mention(assignee_email)
if assignee_mention != '':
assignee_blurb = u" (assigned to {})".format(assignee_mention)
else:
assignee_blurb = ''
sub_event = get_sub_event_for_update_issue(payload)
if 'comment' in sub_event:
if sub_event == 'issue_commented':
verb = 'added comment to'
elif sub_event == 'issue_comment_edited':
verb = 'edited comment on'
else:
verb = 'deleted comment from'
content = u"{} **{}** {}{}".format(get_issue_author(payload), verb, issue, assignee_blurb)
comment = get_in(payload, ['comment', 'body'])
if comment:
comment = convert_jira_markup(comment, user_profile.realm)
content = u"{}:\n\n\n{}\n".format(content, comment)
else:
content = u"{} **updated** {}{}:\n\n".format(get_issue_author(payload), issue, assignee_blurb)
changelog = get_in(payload, ['changelog'])
if changelog != '':
# Use the changelog to display the changes, whitelist types we accept
items = changelog.get('items')
for item in items:
field = item.get('field')
if field == 'assignee' and assignee_mention != '':
target_field_string = assignee_mention
else:
# Convert a user's target to a @-mention if possible
target_field_string = u"**{}**".format(item.get('toString'))
from_field_string = item.get('fromString')
if target_field_string or from_field_string:
content = add_change_info(content, field, from_field_string, target_field_string)
elif sub_event == 'issue_transited':
from_field_string = get_in(payload, ['transition', 'from_status'])
target_field_string = u'**{}**'.format(get_in(payload, ['transition', 'to_status']))
if target_field_string or from_field_string:
content = add_change_info(content, 'status', from_field_string, target_field_string)
return content
def handle_created_issue_event(payload):
# type: (Dict[str, Any]) -> Text
return u"{} **created** {} priority {}, assigned to **{}**:\n\n> {}".format(
get_issue_author(payload),
get_issue_string(payload),
get_in(payload, ['issue', 'fields', 'priority', 'name']),
get_in(payload, ['issue', 'fields', 'assignee', 'displayName'], 'no one'),
get_issue_title(payload)
)
def handle_deleted_issue_event(payload):
# type: (Dict[str, Any]) -> Text
return u"{} **deleted** {}!".format(get_issue_author(payload), get_issue_string(payload))
@api_key_only_webhook_view("JIRA")
@has_request_variables
def api_jira_webhook(request, user_profile,
payload=REQ(argument_type='body'),
stream=REQ(default='jira')):
# type: (HttpRequest, UserProfile, Dict[str, Any], Text) -> HttpResponse
event = get_event_type(payload)
if event == 'jira:issue_created':
subject = get_issue_subject(payload)
content = handle_created_issue_event(payload)
elif event == 'jira:issue_deleted':
subject = get_issue_subject(payload)
content = handle_deleted_issue_event(payload)
elif event == 'jira:issue_updated':
subject = get_issue_subject(payload)
content = handle_updated_issue_event(payload, user_profile)
elif event in IGNORED_EVENTS:
return json_success()
else:
if event is None:
if not settings.TEST_SUITE:
message = u"Got JIRA event with None event type: {}".format(payload)
logging.warning(message)
return json_error(_("Event is not given by JIRA"))
else:
if not settings.TEST_SUITE:
logging.warning("Got JIRA event type we don't support: {}".format(event))
return json_success()
check_send_message(user_profile, request.client, "stream", [stream], subject, content)
return json_success()
| return get_in(payload, ['issue', 'fields', 'summary']) | identifier_body |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.