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 |
|---|---|---|---|---|
virtual_interface.py | # Copyright (C) 2014, Red Hat, Inc.
#
# Licensed under the Apache License, Version 2.0 (the "License"); you may
# not use this file except in compliance with the License. You may obtain
# a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS, WITHOUT
# WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the
# License for the specific language governing permissions and limitations
# under the License.
from nova import db
from nova import exception
from nova import objects
from nova.objects import base
from nova.objects import fields
# TODO(berrange): Remove NovaObjectDictCompat
class VirtualInterface(base.NovaPersistentObject, base.NovaObject,
base.NovaObjectDictCompat):
# Version 1.0: Initial version
VERSION = '1.0'
fields = {
'id': fields.IntegerField(),
'address': fields.StringField(nullable=True),
'network_id': fields.IntegerField(),
'instance_uuid': fields.UUIDField(),
'uuid': fields.UUIDField(),
}
@staticmethod
def _from_db_object(context, vif, db_vif):
for field in vif.fields:
vif[field] = db_vif[field]
vif._context = context
vif.obj_reset_changes()
return vif
@base.remotable_classmethod
def get_by_id(cls, context, vif_id):
db_vif = db.virtual_interface_get(context, vif_id)
if db_vif:
return cls._from_db_object(context, cls(), db_vif)
@base.remotable_classmethod
def get_by_uuid(cls, context, vif_uuid):
db_vif = db.virtual_interface_get_by_uuid(context, vif_uuid)
if db_vif:
return cls._from_db_object(context, cls(), db_vif)
@base.remotable_classmethod
def get_by_address(cls, context, address):
db_vif = db.virtual_interface_get_by_address(context, address)
if db_vif:
return cls._from_db_object(context, cls(), db_vif)
@base.remotable_classmethod
def get_by_instance_and_network(cls, context, instance_uuid, network_id):
db_vif = db.virtual_interface_get_by_instance_and_network(context,
instance_uuid, network_id)
if db_vif:
return cls._from_db_object(context, cls(), db_vif)
@base.remotable
def create(self):
if self.obj_attr_is_set('id'):
raise exception.ObjectActionError(action='create',
reason='already created')
updates = self.obj_get_changes()
db_vif = db.virtual_interface_create(self._context, updates) | @base.remotable_classmethod
def delete_by_instance_uuid(cls, context, instance_uuid):
db.virtual_interface_delete_by_instance(context, instance_uuid)
class VirtualInterfaceList(base.ObjectListBase, base.NovaObject):
# Version 1.0: Initial version
VERSION = '1.0'
fields = {
'objects': fields.ListOfObjectsField('VirtualInterface'),
}
child_versions = {
'1.0': '1.0',
}
@base.remotable_classmethod
def get_all(cls, context):
db_vifs = db.virtual_interface_get_all(context)
return base.obj_make_list(context, cls(context),
objects.VirtualInterface, db_vifs)
@base.remotable_classmethod
def get_by_instance_uuid(cls, context, instance_uuid, use_slave=False):
db_vifs = db.virtual_interface_get_by_instance(context, instance_uuid,
use_slave=use_slave)
return base.obj_make_list(context, cls(context),
objects.VirtualInterface, db_vifs) | self._from_db_object(self._context, self, db_vif)
| random_line_split |
virtual_interface.py | # Copyright (C) 2014, Red Hat, Inc.
#
# Licensed under the Apache License, Version 2.0 (the "License"); you may
# not use this file except in compliance with the License. You may obtain
# a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS, WITHOUT
# WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the
# License for the specific language governing permissions and limitations
# under the License.
from nova import db
from nova import exception
from nova import objects
from nova.objects import base
from nova.objects import fields
# TODO(berrange): Remove NovaObjectDictCompat
class VirtualInterface(base.NovaPersistentObject, base.NovaObject,
base.NovaObjectDictCompat):
# Version 1.0: Initial version
VERSION = '1.0'
fields = {
'id': fields.IntegerField(),
'address': fields.StringField(nullable=True),
'network_id': fields.IntegerField(),
'instance_uuid': fields.UUIDField(),
'uuid': fields.UUIDField(),
}
@staticmethod
def _from_db_object(context, vif, db_vif):
for field in vif.fields:
vif[field] = db_vif[field]
vif._context = context
vif.obj_reset_changes()
return vif
@base.remotable_classmethod
def get_by_id(cls, context, vif_id):
db_vif = db.virtual_interface_get(context, vif_id)
if db_vif:
return cls._from_db_object(context, cls(), db_vif)
@base.remotable_classmethod
def get_by_uuid(cls, context, vif_uuid):
db_vif = db.virtual_interface_get_by_uuid(context, vif_uuid)
if db_vif:
return cls._from_db_object(context, cls(), db_vif)
@base.remotable_classmethod
def get_by_address(cls, context, address):
db_vif = db.virtual_interface_get_by_address(context, address)
if db_vif:
return cls._from_db_object(context, cls(), db_vif)
@base.remotable_classmethod
def get_by_instance_and_network(cls, context, instance_uuid, network_id):
db_vif = db.virtual_interface_get_by_instance_and_network(context,
instance_uuid, network_id)
if db_vif:
return cls._from_db_object(context, cls(), db_vif)
@base.remotable
def create(self):
if self.obj_attr_is_set('id'):
raise exception.ObjectActionError(action='create',
reason='already created')
updates = self.obj_get_changes()
db_vif = db.virtual_interface_create(self._context, updates)
self._from_db_object(self._context, self, db_vif)
@base.remotable_classmethod
def delete_by_instance_uuid(cls, context, instance_uuid):
db.virtual_interface_delete_by_instance(context, instance_uuid)
class VirtualInterfaceList(base.ObjectListBase, base.NovaObject):
# Version 1.0: Initial version
VERSION = '1.0'
fields = {
'objects': fields.ListOfObjectsField('VirtualInterface'),
}
child_versions = {
'1.0': '1.0',
}
@base.remotable_classmethod
def get_all(cls, context):
db_vifs = db.virtual_interface_get_all(context)
return base.obj_make_list(context, cls(context),
objects.VirtualInterface, db_vifs)
@base.remotable_classmethod
def | (cls, context, instance_uuid, use_slave=False):
db_vifs = db.virtual_interface_get_by_instance(context, instance_uuid,
use_slave=use_slave)
return base.obj_make_list(context, cls(context),
objects.VirtualInterface, db_vifs)
| get_by_instance_uuid | identifier_name |
virtual_interface.py | # Copyright (C) 2014, Red Hat, Inc.
#
# Licensed under the Apache License, Version 2.0 (the "License"); you may
# not use this file except in compliance with the License. You may obtain
# a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS, WITHOUT
# WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the
# License for the specific language governing permissions and limitations
# under the License.
from nova import db
from nova import exception
from nova import objects
from nova.objects import base
from nova.objects import fields
# TODO(berrange): Remove NovaObjectDictCompat
class VirtualInterface(base.NovaPersistentObject, base.NovaObject,
base.NovaObjectDictCompat):
# Version 1.0: Initial version
VERSION = '1.0'
fields = {
'id': fields.IntegerField(),
'address': fields.StringField(nullable=True),
'network_id': fields.IntegerField(),
'instance_uuid': fields.UUIDField(),
'uuid': fields.UUIDField(),
}
@staticmethod
def _from_db_object(context, vif, db_vif):
for field in vif.fields:
vif[field] = db_vif[field]
vif._context = context
vif.obj_reset_changes()
return vif
@base.remotable_classmethod
def get_by_id(cls, context, vif_id):
db_vif = db.virtual_interface_get(context, vif_id)
if db_vif:
return cls._from_db_object(context, cls(), db_vif)
@base.remotable_classmethod
def get_by_uuid(cls, context, vif_uuid):
db_vif = db.virtual_interface_get_by_uuid(context, vif_uuid)
if db_vif:
return cls._from_db_object(context, cls(), db_vif)
@base.remotable_classmethod
def get_by_address(cls, context, address):
db_vif = db.virtual_interface_get_by_address(context, address)
if db_vif:
|
@base.remotable_classmethod
def get_by_instance_and_network(cls, context, instance_uuid, network_id):
db_vif = db.virtual_interface_get_by_instance_and_network(context,
instance_uuid, network_id)
if db_vif:
return cls._from_db_object(context, cls(), db_vif)
@base.remotable
def create(self):
if self.obj_attr_is_set('id'):
raise exception.ObjectActionError(action='create',
reason='already created')
updates = self.obj_get_changes()
db_vif = db.virtual_interface_create(self._context, updates)
self._from_db_object(self._context, self, db_vif)
@base.remotable_classmethod
def delete_by_instance_uuid(cls, context, instance_uuid):
db.virtual_interface_delete_by_instance(context, instance_uuid)
class VirtualInterfaceList(base.ObjectListBase, base.NovaObject):
# Version 1.0: Initial version
VERSION = '1.0'
fields = {
'objects': fields.ListOfObjectsField('VirtualInterface'),
}
child_versions = {
'1.0': '1.0',
}
@base.remotable_classmethod
def get_all(cls, context):
db_vifs = db.virtual_interface_get_all(context)
return base.obj_make_list(context, cls(context),
objects.VirtualInterface, db_vifs)
@base.remotable_classmethod
def get_by_instance_uuid(cls, context, instance_uuid, use_slave=False):
db_vifs = db.virtual_interface_get_by_instance(context, instance_uuid,
use_slave=use_slave)
return base.obj_make_list(context, cls(context),
objects.VirtualInterface, db_vifs)
| return cls._from_db_object(context, cls(), db_vif) | conditional_block |
mem.rs | use std::num::SignedInt;
use syntax::{Dir, Left, Right};
// size of allocated memory in bytes
const MEM_SIZE: usize = 65_536; // 64kB!
pub struct Mem {
cells: Box<[u8]>, // address space
ptr: usize // pointer in address space
}
impl Mem {
/// Create a new `Mem` stuct.
#[inline]
pub fn new() -> Mem |
/// Return the value of cell at the current pointer.
#[inline]
pub fn get(&self) -> u8 {
self.cells[self.ptr]
}
/// Set the value at the current pointer.
#[inline]
pub fn set(&mut self, value: u8) {
self.cells[self.ptr] = value;
}
/// Adds `value` to the current cell.
#[inline]
pub fn add(&mut self, value: u8) {
self.cells[self.ptr] += value;
}
/// Subtracts `value` from the current cell.
#[inline]
pub fn subtract(&mut self, value: u8) {
self.cells[self.ptr] -= value;
}
/// Shifts the current pointer to the left or right by a number of steps.
#[inline]
pub fn shift(&mut self, dir: Dir, steps: usize) {
match dir {
Left => self.ptr -= steps,
Right => self.ptr += steps,
}
}
// optimizations
/// Clears the current cell.
#[inline]
pub fn clear(&mut self) {
self.cells[self.ptr] = 0;
}
/// Scans left or right for a zero cell. This fuction will panic! if there
/// is no zero cell before it scans past the beginning of the address space.
#[inline]
pub fn scan(&mut self, dir: Dir) {
while self.cells[self.ptr] != 0 {
self.shift(dir, 1);
}
}
/// Copys the value of the current cell into the cell left or right a
/// number of steps.
#[inline]
pub fn copy(&mut self, dir: Dir, steps: usize) {
let index = match dir {
Left => self.ptr - steps,
Right => self.ptr + steps,
};
self.cells[index] += self.cells[self.ptr];
}
/// Multiplys the value of the current cell by a factor and inserts the
/// product into the cell left or right a number of steps.
pub fn multiply(&mut self, dir: Dir, steps: usize, factor: i8) {
let index = match dir {
Left => self.ptr - steps,
Right => self.ptr + steps,
};
// safely cast factor to u8
let u8_factor = SignedInt::abs(factor) as u8;
// when factor is 1 it acts like a copy
if factor == 1 {
self.cells[index] += self.cells[self.ptr];
}
// when factor is -1 it acts like the inverse of copy
else if factor == -1 {
self.cells[index] -= self.cells[self.ptr];
}
// when factor is >= 2 it adds the product of the current cell and the
// absolute value of factor to the cell at index
else if factor >= 2 {
self.cells[index] += self.cells[self.ptr] * u8_factor;
}
// when factor is <= -2 it subtracts the product of the current cell and the
// absolute value of factor to the cell at index
else if factor <= -2 {
self.cells[index] -= self.cells[self.ptr] * u8_factor;
}
// when factor is 0 it is ignored, as it would do nothing
else {}
}
}
| {
Mem {
cells: box [0u8; MEM_SIZE],
ptr: 0
}
} | identifier_body |
mem.rs | use std::num::SignedInt;
use syntax::{Dir, Left, Right};
// size of allocated memory in bytes
const MEM_SIZE: usize = 65_536; // 64kB!
pub struct Mem {
cells: Box<[u8]>, // address space
ptr: usize // pointer in address space
}
impl Mem {
/// Create a new `Mem` stuct.
#[inline]
pub fn new() -> Mem {
Mem {
cells: box [0u8; MEM_SIZE],
ptr: 0
}
}
/// Return the value of cell at the current pointer.
#[inline]
pub fn get(&self) -> u8 {
self.cells[self.ptr]
}
/// Set the value at the current pointer.
#[inline]
pub fn set(&mut self, value: u8) {
self.cells[self.ptr] = value;
}
/// Adds `value` to the current cell.
#[inline]
pub fn add(&mut self, value: u8) {
self.cells[self.ptr] += value;
}
/// Subtracts `value` from the current cell.
#[inline]
pub fn subtract(&mut self, value: u8) {
self.cells[self.ptr] -= value;
}
/// Shifts the current pointer to the left or right by a number of steps.
#[inline]
pub fn shift(&mut self, dir: Dir, steps: usize) {
match dir {
Left => self.ptr -= steps,
Right => self.ptr += steps,
}
}
// optimizations
/// Clears the current cell.
#[inline]
pub fn clear(&mut self) {
self.cells[self.ptr] = 0;
}
/// Scans left or right for a zero cell. This fuction will panic! if there
/// is no zero cell before it scans past the beginning of the address space.
#[inline]
pub fn scan(&mut self, dir: Dir) {
while self.cells[self.ptr] != 0 {
self.shift(dir, 1);
}
}
/// Copys the value of the current cell into the cell left or right a
/// number of steps.
#[inline] | };
self.cells[index] += self.cells[self.ptr];
}
/// Multiplys the value of the current cell by a factor and inserts the
/// product into the cell left or right a number of steps.
pub fn multiply(&mut self, dir: Dir, steps: usize, factor: i8) {
let index = match dir {
Left => self.ptr - steps,
Right => self.ptr + steps,
};
// safely cast factor to u8
let u8_factor = SignedInt::abs(factor) as u8;
// when factor is 1 it acts like a copy
if factor == 1 {
self.cells[index] += self.cells[self.ptr];
}
// when factor is -1 it acts like the inverse of copy
else if factor == -1 {
self.cells[index] -= self.cells[self.ptr];
}
// when factor is >= 2 it adds the product of the current cell and the
// absolute value of factor to the cell at index
else if factor >= 2 {
self.cells[index] += self.cells[self.ptr] * u8_factor;
}
// when factor is <= -2 it subtracts the product of the current cell and the
// absolute value of factor to the cell at index
else if factor <= -2 {
self.cells[index] -= self.cells[self.ptr] * u8_factor;
}
// when factor is 0 it is ignored, as it would do nothing
else {}
}
} | pub fn copy(&mut self, dir: Dir, steps: usize) {
let index = match dir {
Left => self.ptr - steps,
Right => self.ptr + steps, | random_line_split |
mem.rs | use std::num::SignedInt;
use syntax::{Dir, Left, Right};
// size of allocated memory in bytes
const MEM_SIZE: usize = 65_536; // 64kB!
pub struct Mem {
cells: Box<[u8]>, // address space
ptr: usize // pointer in address space
}
impl Mem {
/// Create a new `Mem` stuct.
#[inline]
pub fn new() -> Mem {
Mem {
cells: box [0u8; MEM_SIZE],
ptr: 0
}
}
/// Return the value of cell at the current pointer.
#[inline]
pub fn get(&self) -> u8 {
self.cells[self.ptr]
}
/// Set the value at the current pointer.
#[inline]
pub fn set(&mut self, value: u8) {
self.cells[self.ptr] = value;
}
/// Adds `value` to the current cell.
#[inline]
pub fn add(&mut self, value: u8) {
self.cells[self.ptr] += value;
}
/// Subtracts `value` from the current cell.
#[inline]
pub fn subtract(&mut self, value: u8) {
self.cells[self.ptr] -= value;
}
/// Shifts the current pointer to the left or right by a number of steps.
#[inline]
pub fn shift(&mut self, dir: Dir, steps: usize) {
match dir {
Left => self.ptr -= steps,
Right => self.ptr += steps,
}
}
// optimizations
/// Clears the current cell.
#[inline]
pub fn clear(&mut self) {
self.cells[self.ptr] = 0;
}
/// Scans left or right for a zero cell. This fuction will panic! if there
/// is no zero cell before it scans past the beginning of the address space.
#[inline]
pub fn | (&mut self, dir: Dir) {
while self.cells[self.ptr] != 0 {
self.shift(dir, 1);
}
}
/// Copys the value of the current cell into the cell left or right a
/// number of steps.
#[inline]
pub fn copy(&mut self, dir: Dir, steps: usize) {
let index = match dir {
Left => self.ptr - steps,
Right => self.ptr + steps,
};
self.cells[index] += self.cells[self.ptr];
}
/// Multiplys the value of the current cell by a factor and inserts the
/// product into the cell left or right a number of steps.
pub fn multiply(&mut self, dir: Dir, steps: usize, factor: i8) {
let index = match dir {
Left => self.ptr - steps,
Right => self.ptr + steps,
};
// safely cast factor to u8
let u8_factor = SignedInt::abs(factor) as u8;
// when factor is 1 it acts like a copy
if factor == 1 {
self.cells[index] += self.cells[self.ptr];
}
// when factor is -1 it acts like the inverse of copy
else if factor == -1 {
self.cells[index] -= self.cells[self.ptr];
}
// when factor is >= 2 it adds the product of the current cell and the
// absolute value of factor to the cell at index
else if factor >= 2 {
self.cells[index] += self.cells[self.ptr] * u8_factor;
}
// when factor is <= -2 it subtracts the product of the current cell and the
// absolute value of factor to the cell at index
else if factor <= -2 {
self.cells[index] -= self.cells[self.ptr] * u8_factor;
}
// when factor is 0 it is ignored, as it would do nothing
else {}
}
}
| scan | identifier_name |
package.py | ##############################################################################
# Copyright (c) 2013-2017, Lawrence Livermore National Security, LLC.
# Produced at the Lawrence Livermore National Laboratory.
#
# This file is part of Spack.
# Created by Todd Gamblin, tgamblin@llnl.gov, All rights reserved.
# LLNL-CODE-647188
#
# For details, see https://github.com/llnl/spack
# Please also see the NOTICE and LICENSE files for our notice and the LGPL.
#
# This program is free software; you can redistribute it and/or modify
# it under the terms of the GNU Lesser General Public License (as
# published by the Free Software Foundation) version 2.1, February 1999.
#
# This program is distributed in the hope that it will be useful, but
# WITHOUT ANY WARRANTY; without even the IMPLIED WARRANTY OF
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the terms and
# conditions of the GNU Lesser General Public License for more details.
#
# You should have received a copy of the GNU Lesser General Public
# License along with this program; if not, write to the Free Software
# Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
##############################################################################
from spack import *
class | (AutotoolsPackage):
"""The Scientific Application Web server (SAWs) turns any C or C++
scientific or engineering application code into a webserver,
allowing one to examine (and even modify) the state of the
simulation with any browser from anywhere."""
homepage = "https://bitbucket.org/saws/saws/wiki/Home"
version('develop', git='https://bitbucket.org/saws/saws.git', tag='master')
version('0.1.0', git='https://bitbucket.org/saws/saws.git', tag='v0.1.0')
| Saws | identifier_name |
package.py | ##############################################################################
# Copyright (c) 2013-2017, Lawrence Livermore National Security, LLC.
# Produced at the Lawrence Livermore National Laboratory.
#
# This file is part of Spack.
# Created by Todd Gamblin, tgamblin@llnl.gov, All rights reserved.
# LLNL-CODE-647188
#
# For details, see https://github.com/llnl/spack
# Please also see the NOTICE and LICENSE files for our notice and the LGPL.
#
# This program is free software; you can redistribute it and/or modify
# it under the terms of the GNU Lesser General Public License (as
# published by the Free Software Foundation) version 2.1, February 1999.
#
# This program is distributed in the hope that it will be useful, but
# WITHOUT ANY WARRANTY; without even the IMPLIED WARRANTY OF
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the terms and
# conditions of the GNU Lesser General Public License for more details.
#
# You should have received a copy of the GNU Lesser General Public
# License along with this program; if not, write to the Free Software
# Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
##############################################################################
from spack import *
class Saws(AutotoolsPackage):
| """The Scientific Application Web server (SAWs) turns any C or C++
scientific or engineering application code into a webserver,
allowing one to examine (and even modify) the state of the
simulation with any browser from anywhere."""
homepage = "https://bitbucket.org/saws/saws/wiki/Home"
version('develop', git='https://bitbucket.org/saws/saws.git', tag='master')
version('0.1.0', git='https://bitbucket.org/saws/saws.git', tag='v0.1.0') | identifier_body | |
package.py | ##############################################################################
# Copyright (c) 2013-2017, Lawrence Livermore National Security, LLC.
# Produced at the Lawrence Livermore National Laboratory.
#
# This file is part of Spack.
# Created by Todd Gamblin, tgamblin@llnl.gov, All rights reserved.
# LLNL-CODE-647188
#
# For details, see https://github.com/llnl/spack
# Please also see the NOTICE and LICENSE files for our notice and the LGPL.
#
# This program is free software; you can redistribute it and/or modify
# it under the terms of the GNU Lesser General Public License (as
# published by the Free Software Foundation) version 2.1, February 1999.
#
# This program is distributed in the hope that it will be useful, but
# WITHOUT ANY WARRANTY; without even the IMPLIED WARRANTY OF
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the terms and
# conditions of the GNU Lesser General Public License for more details.
# |
class Saws(AutotoolsPackage):
"""The Scientific Application Web server (SAWs) turns any C or C++
scientific or engineering application code into a webserver,
allowing one to examine (and even modify) the state of the
simulation with any browser from anywhere."""
homepage = "https://bitbucket.org/saws/saws/wiki/Home"
version('develop', git='https://bitbucket.org/saws/saws.git', tag='master')
version('0.1.0', git='https://bitbucket.org/saws/saws.git', tag='v0.1.0') | # You should have received a copy of the GNU Lesser General Public
# License along with this program; if not, write to the Free Software
# Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
##############################################################################
from spack import * | random_line_split |
CustomStyles.tsx | import * as React from 'react';
import Checkbox from '@material-ui/core/Checkbox';
import {
createMuiTheme,
ThemeProvider,
experimentalStyled as styled,
} from '@material-ui/core/styles';
import { orange } from '@material-ui/core/colors';
declare module '@material-ui/core/styles' {
interface Theme {
status: {
danger: string;
};
}
// allow configuration using `createMuiTheme`
interface ThemeOptions {
status?: {
danger?: string;
};
}
}
const CustomCheckbox = styled(Checkbox)(({ theme }) => ({
color: theme.status.danger,
'&.Mui-checked': {
color: theme.status.danger,
},
}));
const theme = createMuiTheme({
status: {
danger: orange[500],
}, | <ThemeProvider theme={theme}>
<CustomCheckbox defaultChecked />
</ThemeProvider>
);
} | });
export default function CustomStyles() {
return ( | random_line_split |
CustomStyles.tsx | import * as React from 'react';
import Checkbox from '@material-ui/core/Checkbox';
import {
createMuiTheme,
ThemeProvider,
experimentalStyled as styled,
} from '@material-ui/core/styles';
import { orange } from '@material-ui/core/colors';
declare module '@material-ui/core/styles' {
interface Theme {
status: {
danger: string;
};
}
// allow configuration using `createMuiTheme`
interface ThemeOptions {
status?: {
danger?: string;
};
}
}
const CustomCheckbox = styled(Checkbox)(({ theme }) => ({
color: theme.status.danger,
'&.Mui-checked': {
color: theme.status.danger,
},
}));
const theme = createMuiTheme({
status: {
danger: orange[500],
},
});
export default function | () {
return (
<ThemeProvider theme={theme}>
<CustomCheckbox defaultChecked />
</ThemeProvider>
);
}
| CustomStyles | identifier_name |
CustomStyles.tsx | import * as React from 'react';
import Checkbox from '@material-ui/core/Checkbox';
import {
createMuiTheme,
ThemeProvider,
experimentalStyled as styled,
} from '@material-ui/core/styles';
import { orange } from '@material-ui/core/colors';
declare module '@material-ui/core/styles' {
interface Theme {
status: {
danger: string;
};
}
// allow configuration using `createMuiTheme`
interface ThemeOptions {
status?: {
danger?: string;
};
}
}
const CustomCheckbox = styled(Checkbox)(({ theme }) => ({
color: theme.status.danger,
'&.Mui-checked': {
color: theme.status.danger,
},
}));
const theme = createMuiTheme({
status: {
danger: orange[500],
},
});
export default function CustomStyles() | {
return (
<ThemeProvider theme={theme}>
<CustomCheckbox defaultChecked />
</ThemeProvider>
);
} | identifier_body | |
indexedlogauxstore.rs | /*
* Copyright (c) Meta Platforms, Inc. and affiliates.
*
* This software may be used and distributed according to the terms of the
* GNU General Public License version 2.
*/
use std::io::Cursor;
use std::io::Read;
use std::io::Write;
use std::path::Path;
use anyhow::bail;
use anyhow::Result;
use byteorder::ReadBytesExt;
use byteorder::WriteBytesExt;
use configparser::config::ConfigSet;
use configparser::convert::ByteCount;
use edenapi_types::ContentId;
use edenapi_types::FileAuxData;
use edenapi_types::Sha1;
use edenapi_types::Sha256;
use indexedlog::log::IndexOutput;
use minibytes::Bytes;
use parking_lot::RwLock;
use types::hgid::ReadHgIdExt;
use types::HgId;
use vlqencoding::VLQDecode;
use vlqencoding::VLQEncode;
use crate::indexedlogutil::Store;
use crate::indexedlogutil::StoreOpenOptions;
use crate::indexedlogutil::StoreType;
/// See edenapi_types::FileAuxData and mononoke_types::ContentMetadata
#[derive(Copy, Clone, Debug, Default, Eq, PartialEq)]
pub struct Entry {
pub(crate) total_size: u64,
pub(crate) content_id: ContentId,
pub(crate) content_sha1: Sha1,
pub(crate) content_sha256: Sha256,
}
impl From<FileAuxData> for Entry {
fn from(v: FileAuxData) -> Self {
Entry {
total_size: v.total_size,
content_id: v.content_id,
content_sha1: v.sha1,
content_sha256: v.sha256,
}
}
}
impl Entry {
pub fn total_size(&self) -> u64 {
self.total_size
}
pub fn content_id(&self) -> ContentId {
self.content_id
}
pub fn content_sha1(&self) -> Sha1 {
self.content_sha1
}
pub fn content_sha256(&self) -> Sha256 {
self.content_sha256
}
/// Serialize the Entry to Bytes.
///
/// The serialization format is as follows:
/// - HgId <20 bytes>
/// - Version <1 byte> (for compatibility)
/// - content_id <32 bytes>
/// - content sha1 <20 bytes>
/// - content sha256 <32 bytes>
/// - total_size <u64 VLQ, 1-9 bytes>
fn serialize(&self, hgid: HgId) -> Result<Bytes> {
let mut buf = Vec::new();
buf.write_all(hgid.as_ref())?;
buf.write_u8(0)?; // write version
buf.write_all(self.content_id.as_ref())?;
buf.write_all(self.content_sha1.as_ref())?;
buf.write_all(self.content_sha256.as_ref())?;
buf.write_vlq(self.total_size)?;
Ok(buf.into())
}
fn deserialize(bytes: Bytes) -> Result<(HgId, Self)> {
let data: &[u8] = bytes.as_ref();
let mut cur = Cursor::new(data);
let hgid = cur.read_hgid()?;
let version = cur.read_u8()?;
if version != 0 {
bail!("unsupported auxstore entry version {}", version);
}
let mut content_id = [0u8; 32];
cur.read_exact(&mut content_id)?;
let mut content_sha1 = [0u8; 20];
cur.read_exact(&mut content_sha1)?;
let mut content_sha256 = [0u8; 32];
cur.read_exact(&mut content_sha256)?;
let total_size: u64 = cur.read_vlq()?;
Ok((
hgid,
Entry {
content_id: content_id.into(),
content_sha1: content_sha1.into(),
content_sha256: content_sha256.into(),
total_size,
},
))
}
}
pub struct AuxStore(RwLock<Store>);
impl AuxStore {
pub fn new(path: impl AsRef<Path>, config: &ConfigSet, store_type: StoreType) -> Result<Self> {
// TODO(meyer): Eliminate "local" AuxStore - always treat it as shared / cache?
let open_options = AuxStore::open_options(config)?;
let log = match store_type {
StoreType::Local => open_options.local(&path),
StoreType::Shared => open_options.shared(&path),
}?;
Ok(AuxStore(RwLock::new(log)))
}
fn open_options(config: &ConfigSet) -> Result<StoreOpenOptions> {
// TODO(meyer): Decide exactly how we want to configure this store. This is all copied from indexedlogdatastore
// Default configuration: 4 x 2.5GB.
let mut open_options = StoreOpenOptions::new()
.max_log_count(4)
.max_bytes_per_log(2500 * 1000 * 1000)
.auto_sync_threshold(10 * 1024 * 1024)
.create(true)
.index("node", |_| {
vec![IndexOutput::Reference(0..HgId::len() as u64)]
});
if let Some(max_log_count) = config.get_opt::<u8>("indexedlog", "data.max-log-count")? {
open_options = open_options.max_log_count(max_log_count);
}
if let Some(max_bytes_per_log) =
config.get_opt::<ByteCount>("indexedlog", "data.max-bytes-per-log")?
{
open_options = open_options.max_bytes_per_log(max_bytes_per_log.value());
} else if let Some(max_bytes_per_log) =
config.get_opt::<ByteCount>("remotefilelog", "cachelimit")?
|
Ok(open_options)
}
pub fn get(&self, hgid: HgId) -> Result<Option<Entry>> {
let log = self.0.read();
let mut entries = log.lookup(0, &hgid)?;
let slice = match entries.next() {
None => return Ok(None),
Some(slice) => slice?,
};
let bytes = log.slice_to_bytes(slice);
drop(log);
Entry::deserialize(bytes).map(|(_hgid, entry)| Some(entry))
}
pub fn put(&self, hgid: HgId, entry: &Entry) -> Result<()> {
let serialized = entry.serialize(hgid)?;
self.0.write().append(&serialized)
}
pub fn flush(&self) -> Result<()> {
self.0.write().flush()
}
#[cfg(test)]
pub(crate) fn hgids(&self) -> Result<Vec<HgId>> {
let log = self.0.read();
log.iter()
.map(|slice| {
let bytes = log.slice_to_bytes(slice?);
Entry::deserialize(bytes).map(|(hgid, _entry)| hgid)
})
.collect()
}
}
#[cfg(test)]
mod tests {
use std::fs::remove_file;
use std::str::FromStr;
use std::sync::Arc;
use tempfile::TempDir;
use types::testutil::*;
use super::*;
use crate::scmstore::FileAttributes;
use crate::scmstore::FileStore;
use crate::testutil::*;
use crate::ExtStoredPolicy;
use crate::HgIdMutableDeltaStore;
use crate::IndexedLogHgIdDataStore;
fn single_byte_sha1(fst: u8) -> Sha1 {
let mut x: [u8; Sha1::len()] = Default::default();
x[0] = fst;
Sha1::from(x)
}
#[test]
fn test_empty() -> Result<()> {
let tempdir = TempDir::new()?;
let store = AuxStore::new(&tempdir, &ConfigSet::new(), StoreType::Shared)?;
store.flush()?;
Ok(())
}
#[test]
fn test_add_get() -> Result<()> {
let tempdir = TempDir::new().unwrap();
let store = AuxStore::new(&tempdir, &ConfigSet::new(), StoreType::Shared)?;
let mut entry = Entry::default();
entry.total_size = 1;
entry.content_sha1 = single_byte_sha1(1);
let k = key("a", "1");
store.put(k.hgid, &entry)?;
store.flush()?;
let found = store.get(k.hgid)?;
assert_eq!(Some(entry), found);
Ok(())
}
#[test]
fn test_lookup_failure() -> Result<()> {
let tempdir = TempDir::new().unwrap();
let store = AuxStore::new(&tempdir, &ConfigSet::new(), StoreType::Shared)?;
let mut entry = Entry::default();
entry.total_size = 1;
entry.content_sha1 = single_byte_sha1(1);
let k = key("a", "1");
store.put(k.hgid, &entry)?;
store.flush()?;
let k2 = key("b", "2");
let found = store.get(k2.hgid)?;
assert_eq!(None, found);
Ok(())
}
#[test]
fn test_corrupted() -> Result<()> {
let tempdir = TempDir::new()?;
let store = AuxStore::new(&tempdir, &ConfigSet::new(), StoreType::Shared)?;
let k = key("a", "2");
let mut entry = Entry::default();
entry.total_size = 2;
entry.content_sha1 = single_byte_sha1(2);
store.put(k.hgid, &entry)?;
store.flush()?;
drop(store);
// Corrupt the log by removing the "log" file.
let mut rotate_log_path = tempdir.path().to_path_buf();
rotate_log_path.push("0");
rotate_log_path.push("log");
remove_file(rotate_log_path)?;
let store = AuxStore::new(&tempdir, &ConfigSet::new(), StoreType::Shared)?;
let k = key("a", "3");
let mut entry = Entry::default();
entry.total_size = 3;
entry.content_sha1 = single_byte_sha1(3);
store.put(k.hgid, &entry)?;
store.flush()?;
// There should be only one key in the store.
assert_eq!(store.hgids().into_iter().count(), 1);
Ok(())
}
#[test]
fn test_scmstore_read() -> Result<()> {
let tmp = TempDir::new()?;
let aux = Arc::new(AuxStore::new(&tmp, &ConfigSet::new(), StoreType::Shared)?);
let mut entry = Entry::default();
entry.total_size = 1;
entry.content_sha1 = single_byte_sha1(1);
let k = key("a", "1");
aux.put(k.hgid, &entry)?;
aux.flush()?;
// Set up local-only FileStore
let mut store = FileStore::empty();
store.aux_local = Some(aux.clone());
// Attempt fetch.
let fetched = store
.fetch(std::iter::once(k.clone()), FileAttributes::AUX)
.single()?
.expect("key not found");
assert_eq!(entry, fetched.aux_data().expect("no aux data found").into());
Ok(())
}
#[test]
fn test_scmstore_compute_read() -> Result<()> {
let k = key("a", "def6f29d7b61f9cb70b2f14f79cd5c43c38e21b2");
let d = delta("1234", None, k.clone());
let meta = Default::default();
// Setup local indexedlog
let tmp = TempDir::new()?;
let content = Arc::new(IndexedLogHgIdDataStore::new(
&tmp,
ExtStoredPolicy::Ignore,
&ConfigSet::new(),
StoreType::Shared,
)?);
content.add(&d, &meta).unwrap();
content.flush().unwrap();
let tmp = TempDir::new()?;
let aux = Arc::new(AuxStore::new(&tmp, &ConfigSet::new(), StoreType::Shared)?);
// Set up local-only FileStore
let mut store = FileStore::empty();
store.cache_to_local_cache = true;
store.indexedlog_local = Some(content.clone());
store.aux_local = Some(aux.clone());
let mut expected = Entry::default();
expected.total_size = 4;
expected.content_id = ContentId::from_str(
"aa6ab85da77ca480b7624172fe44aa9906b6c3f00f06ff23c3e5f60bfd0c414e",
)?;
expected.content_sha1 = Sha1::from_str("7110eda4d09e062aa5e4a390b0a572ac0d2c0220")?;
expected.content_sha256 =
Sha256::from_str("03ac674216f3e15c761ee1a5e255f067953623c8b388b4459e13f978d7c846f4")?;
// Attempt fetch.
let fetched = store
.fetch(std::iter::once(k.clone()), FileAttributes::AUX)
.single()?
.expect("key not found");
assert_eq!(
expected,
fetched.aux_data().expect("no aux data found").into()
);
// Verify we can read it directly too
let found = aux.get(k.hgid)?;
assert_eq!(Some(expected), found);
Ok(())
}
}
| {
let log_count: u64 = open_options.max_log_count.unwrap_or(1).max(1).into();
open_options =
open_options.max_bytes_per_log((max_bytes_per_log.value() / log_count).max(1));
} | conditional_block |
indexedlogauxstore.rs | /*
* Copyright (c) Meta Platforms, Inc. and affiliates.
*
* This software may be used and distributed according to the terms of the
* GNU General Public License version 2.
*/
use std::io::Cursor;
use std::io::Read;
use std::io::Write;
use std::path::Path;
use anyhow::bail;
use anyhow::Result;
use byteorder::ReadBytesExt;
use byteorder::WriteBytesExt;
use configparser::config::ConfigSet;
use configparser::convert::ByteCount;
use edenapi_types::ContentId;
use edenapi_types::FileAuxData;
use edenapi_types::Sha1;
use edenapi_types::Sha256;
use indexedlog::log::IndexOutput;
use minibytes::Bytes;
use parking_lot::RwLock;
use types::hgid::ReadHgIdExt;
use types::HgId;
use vlqencoding::VLQDecode;
use vlqencoding::VLQEncode;
use crate::indexedlogutil::Store;
use crate::indexedlogutil::StoreOpenOptions;
use crate::indexedlogutil::StoreType;
/// See edenapi_types::FileAuxData and mononoke_types::ContentMetadata
#[derive(Copy, Clone, Debug, Default, Eq, PartialEq)]
pub struct Entry {
pub(crate) total_size: u64,
pub(crate) content_id: ContentId,
pub(crate) content_sha1: Sha1,
pub(crate) content_sha256: Sha256,
}
impl From<FileAuxData> for Entry {
fn from(v: FileAuxData) -> Self {
Entry {
total_size: v.total_size,
content_id: v.content_id,
content_sha1: v.sha1,
content_sha256: v.sha256,
}
}
}
impl Entry {
pub fn total_size(&self) -> u64 {
self.total_size
}
pub fn content_id(&self) -> ContentId {
self.content_id
}
pub fn content_sha1(&self) -> Sha1 {
self.content_sha1
}
pub fn content_sha256(&self) -> Sha256 {
self.content_sha256
}
/// Serialize the Entry to Bytes.
///
/// The serialization format is as follows:
/// - HgId <20 bytes>
/// - Version <1 byte> (for compatibility)
/// - content_id <32 bytes>
/// - content sha1 <20 bytes>
/// - content sha256 <32 bytes>
/// - total_size <u64 VLQ, 1-9 bytes>
fn serialize(&self, hgid: HgId) -> Result<Bytes> {
let mut buf = Vec::new();
buf.write_all(hgid.as_ref())?;
buf.write_u8(0)?; // write version
buf.write_all(self.content_id.as_ref())?;
buf.write_all(self.content_sha1.as_ref())?;
buf.write_all(self.content_sha256.as_ref())?;
buf.write_vlq(self.total_size)?;
Ok(buf.into())
}
fn deserialize(bytes: Bytes) -> Result<(HgId, Self)> {
let data: &[u8] = bytes.as_ref();
let mut cur = Cursor::new(data);
let hgid = cur.read_hgid()?;
let version = cur.read_u8()?;
if version != 0 {
bail!("unsupported auxstore entry version {}", version);
}
let mut content_id = [0u8; 32];
cur.read_exact(&mut content_id)?;
let mut content_sha1 = [0u8; 20];
cur.read_exact(&mut content_sha1)?;
let mut content_sha256 = [0u8; 32];
cur.read_exact(&mut content_sha256)?;
let total_size: u64 = cur.read_vlq()?;
Ok((
hgid,
Entry {
content_id: content_id.into(),
content_sha1: content_sha1.into(),
content_sha256: content_sha256.into(),
total_size,
},
))
}
}
pub struct AuxStore(RwLock<Store>);
impl AuxStore {
pub fn new(path: impl AsRef<Path>, config: &ConfigSet, store_type: StoreType) -> Result<Self> {
// TODO(meyer): Eliminate "local" AuxStore - always treat it as shared / cache?
let open_options = AuxStore::open_options(config)?;
let log = match store_type {
StoreType::Local => open_options.local(&path),
StoreType::Shared => open_options.shared(&path),
}?;
Ok(AuxStore(RwLock::new(log)))
}
fn open_options(config: &ConfigSet) -> Result<StoreOpenOptions> {
// TODO(meyer): Decide exactly how we want to configure this store. This is all copied from indexedlogdatastore
// Default configuration: 4 x 2.5GB.
let mut open_options = StoreOpenOptions::new()
.max_log_count(4)
.max_bytes_per_log(2500 * 1000 * 1000)
.auto_sync_threshold(10 * 1024 * 1024)
.create(true)
.index("node", |_| {
vec![IndexOutput::Reference(0..HgId::len() as u64)]
});
if let Some(max_log_count) = config.get_opt::<u8>("indexedlog", "data.max-log-count")? {
open_options = open_options.max_log_count(max_log_count);
}
if let Some(max_bytes_per_log) =
config.get_opt::<ByteCount>("indexedlog", "data.max-bytes-per-log")?
{
open_options = open_options.max_bytes_per_log(max_bytes_per_log.value());
} else if let Some(max_bytes_per_log) =
config.get_opt::<ByteCount>("remotefilelog", "cachelimit")?
{
let log_count: u64 = open_options.max_log_count.unwrap_or(1).max(1).into();
open_options =
open_options.max_bytes_per_log((max_bytes_per_log.value() / log_count).max(1));
}
Ok(open_options)
}
pub fn get(&self, hgid: HgId) -> Result<Option<Entry>> {
let log = self.0.read();
let mut entries = log.lookup(0, &hgid)?;
let slice = match entries.next() {
None => return Ok(None),
Some(slice) => slice?,
};
let bytes = log.slice_to_bytes(slice);
drop(log);
Entry::deserialize(bytes).map(|(_hgid, entry)| Some(entry))
}
pub fn put(&self, hgid: HgId, entry: &Entry) -> Result<()> {
let serialized = entry.serialize(hgid)?;
self.0.write().append(&serialized)
}
pub fn flush(&self) -> Result<()> {
self.0.write().flush()
}
#[cfg(test)]
pub(crate) fn hgids(&self) -> Result<Vec<HgId>> {
let log = self.0.read();
log.iter()
.map(|slice| {
let bytes = log.slice_to_bytes(slice?);
Entry::deserialize(bytes).map(|(hgid, _entry)| hgid)
})
.collect()
}
}
#[cfg(test)]
mod tests {
use std::fs::remove_file;
use std::str::FromStr;
use std::sync::Arc;
use tempfile::TempDir;
use types::testutil::*;
use super::*;
use crate::scmstore::FileAttributes;
use crate::scmstore::FileStore;
use crate::testutil::*;
use crate::ExtStoredPolicy;
use crate::HgIdMutableDeltaStore;
use crate::IndexedLogHgIdDataStore;
fn single_byte_sha1(fst: u8) -> Sha1 {
let mut x: [u8; Sha1::len()] = Default::default();
x[0] = fst;
Sha1::from(x)
}
#[test]
fn | () -> Result<()> {
let tempdir = TempDir::new()?;
let store = AuxStore::new(&tempdir, &ConfigSet::new(), StoreType::Shared)?;
store.flush()?;
Ok(())
}
#[test]
fn test_add_get() -> Result<()> {
let tempdir = TempDir::new().unwrap();
let store = AuxStore::new(&tempdir, &ConfigSet::new(), StoreType::Shared)?;
let mut entry = Entry::default();
entry.total_size = 1;
entry.content_sha1 = single_byte_sha1(1);
let k = key("a", "1");
store.put(k.hgid, &entry)?;
store.flush()?;
let found = store.get(k.hgid)?;
assert_eq!(Some(entry), found);
Ok(())
}
#[test]
fn test_lookup_failure() -> Result<()> {
let tempdir = TempDir::new().unwrap();
let store = AuxStore::new(&tempdir, &ConfigSet::new(), StoreType::Shared)?;
let mut entry = Entry::default();
entry.total_size = 1;
entry.content_sha1 = single_byte_sha1(1);
let k = key("a", "1");
store.put(k.hgid, &entry)?;
store.flush()?;
let k2 = key("b", "2");
let found = store.get(k2.hgid)?;
assert_eq!(None, found);
Ok(())
}
#[test]
fn test_corrupted() -> Result<()> {
let tempdir = TempDir::new()?;
let store = AuxStore::new(&tempdir, &ConfigSet::new(), StoreType::Shared)?;
let k = key("a", "2");
let mut entry = Entry::default();
entry.total_size = 2;
entry.content_sha1 = single_byte_sha1(2);
store.put(k.hgid, &entry)?;
store.flush()?;
drop(store);
// Corrupt the log by removing the "log" file.
let mut rotate_log_path = tempdir.path().to_path_buf();
rotate_log_path.push("0");
rotate_log_path.push("log");
remove_file(rotate_log_path)?;
let store = AuxStore::new(&tempdir, &ConfigSet::new(), StoreType::Shared)?;
let k = key("a", "3");
let mut entry = Entry::default();
entry.total_size = 3;
entry.content_sha1 = single_byte_sha1(3);
store.put(k.hgid, &entry)?;
store.flush()?;
// There should be only one key in the store.
assert_eq!(store.hgids().into_iter().count(), 1);
Ok(())
}
#[test]
fn test_scmstore_read() -> Result<()> {
let tmp = TempDir::new()?;
let aux = Arc::new(AuxStore::new(&tmp, &ConfigSet::new(), StoreType::Shared)?);
let mut entry = Entry::default();
entry.total_size = 1;
entry.content_sha1 = single_byte_sha1(1);
let k = key("a", "1");
aux.put(k.hgid, &entry)?;
aux.flush()?;
// Set up local-only FileStore
let mut store = FileStore::empty();
store.aux_local = Some(aux.clone());
// Attempt fetch.
let fetched = store
.fetch(std::iter::once(k.clone()), FileAttributes::AUX)
.single()?
.expect("key not found");
assert_eq!(entry, fetched.aux_data().expect("no aux data found").into());
Ok(())
}
#[test]
fn test_scmstore_compute_read() -> Result<()> {
let k = key("a", "def6f29d7b61f9cb70b2f14f79cd5c43c38e21b2");
let d = delta("1234", None, k.clone());
let meta = Default::default();
// Setup local indexedlog
let tmp = TempDir::new()?;
let content = Arc::new(IndexedLogHgIdDataStore::new(
&tmp,
ExtStoredPolicy::Ignore,
&ConfigSet::new(),
StoreType::Shared,
)?);
content.add(&d, &meta).unwrap();
content.flush().unwrap();
let tmp = TempDir::new()?;
let aux = Arc::new(AuxStore::new(&tmp, &ConfigSet::new(), StoreType::Shared)?);
// Set up local-only FileStore
let mut store = FileStore::empty();
store.cache_to_local_cache = true;
store.indexedlog_local = Some(content.clone());
store.aux_local = Some(aux.clone());
let mut expected = Entry::default();
expected.total_size = 4;
expected.content_id = ContentId::from_str(
"aa6ab85da77ca480b7624172fe44aa9906b6c3f00f06ff23c3e5f60bfd0c414e",
)?;
expected.content_sha1 = Sha1::from_str("7110eda4d09e062aa5e4a390b0a572ac0d2c0220")?;
expected.content_sha256 =
Sha256::from_str("03ac674216f3e15c761ee1a5e255f067953623c8b388b4459e13f978d7c846f4")?;
// Attempt fetch.
let fetched = store
.fetch(std::iter::once(k.clone()), FileAttributes::AUX)
.single()?
.expect("key not found");
assert_eq!(
expected,
fetched.aux_data().expect("no aux data found").into()
);
// Verify we can read it directly too
let found = aux.get(k.hgid)?;
assert_eq!(Some(expected), found);
Ok(())
}
}
| test_empty | identifier_name |
indexedlogauxstore.rs | /*
* Copyright (c) Meta Platforms, Inc. and affiliates.
*
* This software may be used and distributed according to the terms of the
* GNU General Public License version 2.
*/
use std::io::Cursor;
use std::io::Read;
use std::io::Write;
use std::path::Path;
use anyhow::bail;
use anyhow::Result;
use byteorder::ReadBytesExt;
use byteorder::WriteBytesExt;
use configparser::config::ConfigSet;
use configparser::convert::ByteCount;
use edenapi_types::ContentId;
use edenapi_types::FileAuxData;
use edenapi_types::Sha1;
use edenapi_types::Sha256;
use indexedlog::log::IndexOutput;
use minibytes::Bytes;
use parking_lot::RwLock;
use types::hgid::ReadHgIdExt;
use types::HgId;
use vlqencoding::VLQDecode;
use vlqencoding::VLQEncode;
use crate::indexedlogutil::Store;
use crate::indexedlogutil::StoreOpenOptions;
use crate::indexedlogutil::StoreType;
/// See edenapi_types::FileAuxData and mononoke_types::ContentMetadata
#[derive(Copy, Clone, Debug, Default, Eq, PartialEq)]
pub struct Entry {
pub(crate) total_size: u64,
pub(crate) content_id: ContentId,
pub(crate) content_sha1: Sha1,
pub(crate) content_sha256: Sha256,
}
impl From<FileAuxData> for Entry {
fn from(v: FileAuxData) -> Self {
Entry {
total_size: v.total_size,
content_id: v.content_id,
content_sha1: v.sha1,
content_sha256: v.sha256,
}
}
}
impl Entry {
pub fn total_size(&self) -> u64 {
self.total_size
}
pub fn content_id(&self) -> ContentId {
self.content_id
}
pub fn content_sha1(&self) -> Sha1 {
self.content_sha1
}
pub fn content_sha256(&self) -> Sha256 {
self.content_sha256
}
/// Serialize the Entry to Bytes.
///
/// The serialization format is as follows:
/// - HgId <20 bytes>
/// - Version <1 byte> (for compatibility)
/// - content_id <32 bytes>
/// - content sha1 <20 bytes>
/// - content sha256 <32 bytes>
/// - total_size <u64 VLQ, 1-9 bytes>
fn serialize(&self, hgid: HgId) -> Result<Bytes> |
fn deserialize(bytes: Bytes) -> Result<(HgId, Self)> {
let data: &[u8] = bytes.as_ref();
let mut cur = Cursor::new(data);
let hgid = cur.read_hgid()?;
let version = cur.read_u8()?;
if version != 0 {
bail!("unsupported auxstore entry version {}", version);
}
let mut content_id = [0u8; 32];
cur.read_exact(&mut content_id)?;
let mut content_sha1 = [0u8; 20];
cur.read_exact(&mut content_sha1)?;
let mut content_sha256 = [0u8; 32];
cur.read_exact(&mut content_sha256)?;
let total_size: u64 = cur.read_vlq()?;
Ok((
hgid,
Entry {
content_id: content_id.into(),
content_sha1: content_sha1.into(),
content_sha256: content_sha256.into(),
total_size,
},
))
}
}
pub struct AuxStore(RwLock<Store>);
impl AuxStore {
pub fn new(path: impl AsRef<Path>, config: &ConfigSet, store_type: StoreType) -> Result<Self> {
// TODO(meyer): Eliminate "local" AuxStore - always treat it as shared / cache?
let open_options = AuxStore::open_options(config)?;
let log = match store_type {
StoreType::Local => open_options.local(&path),
StoreType::Shared => open_options.shared(&path),
}?;
Ok(AuxStore(RwLock::new(log)))
}
fn open_options(config: &ConfigSet) -> Result<StoreOpenOptions> {
// TODO(meyer): Decide exactly how we want to configure this store. This is all copied from indexedlogdatastore
// Default configuration: 4 x 2.5GB.
let mut open_options = StoreOpenOptions::new()
.max_log_count(4)
.max_bytes_per_log(2500 * 1000 * 1000)
.auto_sync_threshold(10 * 1024 * 1024)
.create(true)
.index("node", |_| {
vec![IndexOutput::Reference(0..HgId::len() as u64)]
});
if let Some(max_log_count) = config.get_opt::<u8>("indexedlog", "data.max-log-count")? {
open_options = open_options.max_log_count(max_log_count);
}
if let Some(max_bytes_per_log) =
config.get_opt::<ByteCount>("indexedlog", "data.max-bytes-per-log")?
{
open_options = open_options.max_bytes_per_log(max_bytes_per_log.value());
} else if let Some(max_bytes_per_log) =
config.get_opt::<ByteCount>("remotefilelog", "cachelimit")?
{
let log_count: u64 = open_options.max_log_count.unwrap_or(1).max(1).into();
open_options =
open_options.max_bytes_per_log((max_bytes_per_log.value() / log_count).max(1));
}
Ok(open_options)
}
pub fn get(&self, hgid: HgId) -> Result<Option<Entry>> {
let log = self.0.read();
let mut entries = log.lookup(0, &hgid)?;
let slice = match entries.next() {
None => return Ok(None),
Some(slice) => slice?,
};
let bytes = log.slice_to_bytes(slice);
drop(log);
Entry::deserialize(bytes).map(|(_hgid, entry)| Some(entry))
}
pub fn put(&self, hgid: HgId, entry: &Entry) -> Result<()> {
let serialized = entry.serialize(hgid)?;
self.0.write().append(&serialized)
}
pub fn flush(&self) -> Result<()> {
self.0.write().flush()
}
#[cfg(test)]
pub(crate) fn hgids(&self) -> Result<Vec<HgId>> {
let log = self.0.read();
log.iter()
.map(|slice| {
let bytes = log.slice_to_bytes(slice?);
Entry::deserialize(bytes).map(|(hgid, _entry)| hgid)
})
.collect()
}
}
#[cfg(test)]
mod tests {
use std::fs::remove_file;
use std::str::FromStr;
use std::sync::Arc;
use tempfile::TempDir;
use types::testutil::*;
use super::*;
use crate::scmstore::FileAttributes;
use crate::scmstore::FileStore;
use crate::testutil::*;
use crate::ExtStoredPolicy;
use crate::HgIdMutableDeltaStore;
use crate::IndexedLogHgIdDataStore;
fn single_byte_sha1(fst: u8) -> Sha1 {
let mut x: [u8; Sha1::len()] = Default::default();
x[0] = fst;
Sha1::from(x)
}
#[test]
fn test_empty() -> Result<()> {
let tempdir = TempDir::new()?;
let store = AuxStore::new(&tempdir, &ConfigSet::new(), StoreType::Shared)?;
store.flush()?;
Ok(())
}
#[test]
fn test_add_get() -> Result<()> {
let tempdir = TempDir::new().unwrap();
let store = AuxStore::new(&tempdir, &ConfigSet::new(), StoreType::Shared)?;
let mut entry = Entry::default();
entry.total_size = 1;
entry.content_sha1 = single_byte_sha1(1);
let k = key("a", "1");
store.put(k.hgid, &entry)?;
store.flush()?;
let found = store.get(k.hgid)?;
assert_eq!(Some(entry), found);
Ok(())
}
#[test]
fn test_lookup_failure() -> Result<()> {
let tempdir = TempDir::new().unwrap();
let store = AuxStore::new(&tempdir, &ConfigSet::new(), StoreType::Shared)?;
let mut entry = Entry::default();
entry.total_size = 1;
entry.content_sha1 = single_byte_sha1(1);
let k = key("a", "1");
store.put(k.hgid, &entry)?;
store.flush()?;
let k2 = key("b", "2");
let found = store.get(k2.hgid)?;
assert_eq!(None, found);
Ok(())
}
#[test]
fn test_corrupted() -> Result<()> {
let tempdir = TempDir::new()?;
let store = AuxStore::new(&tempdir, &ConfigSet::new(), StoreType::Shared)?;
let k = key("a", "2");
let mut entry = Entry::default();
entry.total_size = 2;
entry.content_sha1 = single_byte_sha1(2);
store.put(k.hgid, &entry)?;
store.flush()?;
drop(store);
// Corrupt the log by removing the "log" file.
let mut rotate_log_path = tempdir.path().to_path_buf();
rotate_log_path.push("0");
rotate_log_path.push("log");
remove_file(rotate_log_path)?;
let store = AuxStore::new(&tempdir, &ConfigSet::new(), StoreType::Shared)?;
let k = key("a", "3");
let mut entry = Entry::default();
entry.total_size = 3;
entry.content_sha1 = single_byte_sha1(3);
store.put(k.hgid, &entry)?;
store.flush()?;
// There should be only one key in the store.
assert_eq!(store.hgids().into_iter().count(), 1);
Ok(())
}
#[test]
fn test_scmstore_read() -> Result<()> {
let tmp = TempDir::new()?;
let aux = Arc::new(AuxStore::new(&tmp, &ConfigSet::new(), StoreType::Shared)?);
let mut entry = Entry::default();
entry.total_size = 1;
entry.content_sha1 = single_byte_sha1(1);
let k = key("a", "1");
aux.put(k.hgid, &entry)?;
aux.flush()?;
// Set up local-only FileStore
let mut store = FileStore::empty();
store.aux_local = Some(aux.clone());
// Attempt fetch.
let fetched = store
.fetch(std::iter::once(k.clone()), FileAttributes::AUX)
.single()?
.expect("key not found");
assert_eq!(entry, fetched.aux_data().expect("no aux data found").into());
Ok(())
}
#[test]
fn test_scmstore_compute_read() -> Result<()> {
let k = key("a", "def6f29d7b61f9cb70b2f14f79cd5c43c38e21b2");
let d = delta("1234", None, k.clone());
let meta = Default::default();
// Setup local indexedlog
let tmp = TempDir::new()?;
let content = Arc::new(IndexedLogHgIdDataStore::new(
&tmp,
ExtStoredPolicy::Ignore,
&ConfigSet::new(),
StoreType::Shared,
)?);
content.add(&d, &meta).unwrap();
content.flush().unwrap();
let tmp = TempDir::new()?;
let aux = Arc::new(AuxStore::new(&tmp, &ConfigSet::new(), StoreType::Shared)?);
// Set up local-only FileStore
let mut store = FileStore::empty();
store.cache_to_local_cache = true;
store.indexedlog_local = Some(content.clone());
store.aux_local = Some(aux.clone());
let mut expected = Entry::default();
expected.total_size = 4;
expected.content_id = ContentId::from_str(
"aa6ab85da77ca480b7624172fe44aa9906b6c3f00f06ff23c3e5f60bfd0c414e",
)?;
expected.content_sha1 = Sha1::from_str("7110eda4d09e062aa5e4a390b0a572ac0d2c0220")?;
expected.content_sha256 =
Sha256::from_str("03ac674216f3e15c761ee1a5e255f067953623c8b388b4459e13f978d7c846f4")?;
// Attempt fetch.
let fetched = store
.fetch(std::iter::once(k.clone()), FileAttributes::AUX)
.single()?
.expect("key not found");
assert_eq!(
expected,
fetched.aux_data().expect("no aux data found").into()
);
// Verify we can read it directly too
let found = aux.get(k.hgid)?;
assert_eq!(Some(expected), found);
Ok(())
}
}
| {
let mut buf = Vec::new();
buf.write_all(hgid.as_ref())?;
buf.write_u8(0)?; // write version
buf.write_all(self.content_id.as_ref())?;
buf.write_all(self.content_sha1.as_ref())?;
buf.write_all(self.content_sha256.as_ref())?;
buf.write_vlq(self.total_size)?;
Ok(buf.into())
} | identifier_body |
indexedlogauxstore.rs | /*
* Copyright (c) Meta Platforms, Inc. and affiliates.
*
* This software may be used and distributed according to the terms of the
* GNU General Public License version 2.
*/
use std::io::Cursor;
use std::io::Read;
use std::io::Write;
use std::path::Path;
use anyhow::bail;
use anyhow::Result;
use byteorder::ReadBytesExt;
use byteorder::WriteBytesExt;
use configparser::config::ConfigSet;
use configparser::convert::ByteCount;
use edenapi_types::ContentId;
use edenapi_types::FileAuxData;
use edenapi_types::Sha1;
use edenapi_types::Sha256;
use indexedlog::log::IndexOutput;
use minibytes::Bytes;
use parking_lot::RwLock;
use types::hgid::ReadHgIdExt;
use types::HgId;
use vlqencoding::VLQDecode;
use vlqencoding::VLQEncode;
use crate::indexedlogutil::Store;
use crate::indexedlogutil::StoreOpenOptions;
use crate::indexedlogutil::StoreType;
/// See edenapi_types::FileAuxData and mononoke_types::ContentMetadata
#[derive(Copy, Clone, Debug, Default, Eq, PartialEq)]
pub struct Entry {
pub(crate) total_size: u64,
pub(crate) content_id: ContentId,
pub(crate) content_sha1: Sha1,
pub(crate) content_sha256: Sha256,
}
impl From<FileAuxData> for Entry {
fn from(v: FileAuxData) -> Self {
Entry {
total_size: v.total_size,
content_id: v.content_id,
content_sha1: v.sha1,
content_sha256: v.sha256,
}
}
}
impl Entry {
pub fn total_size(&self) -> u64 {
self.total_size
}
pub fn content_id(&self) -> ContentId {
self.content_id
}
pub fn content_sha1(&self) -> Sha1 {
self.content_sha1
}
pub fn content_sha256(&self) -> Sha256 {
self.content_sha256
}
/// Serialize the Entry to Bytes.
///
/// The serialization format is as follows:
/// - HgId <20 bytes>
/// - Version <1 byte> (for compatibility)
/// - content_id <32 bytes>
/// - content sha1 <20 bytes>
/// - content sha256 <32 bytes>
/// - total_size <u64 VLQ, 1-9 bytes>
fn serialize(&self, hgid: HgId) -> Result<Bytes> {
let mut buf = Vec::new();
buf.write_all(hgid.as_ref())?;
buf.write_u8(0)?; // write version
buf.write_all(self.content_id.as_ref())?;
buf.write_all(self.content_sha1.as_ref())?;
buf.write_all(self.content_sha256.as_ref())?;
buf.write_vlq(self.total_size)?;
Ok(buf.into())
}
fn deserialize(bytes: Bytes) -> Result<(HgId, Self)> {
let data: &[u8] = bytes.as_ref();
let mut cur = Cursor::new(data);
let hgid = cur.read_hgid()?;
let version = cur.read_u8()?;
if version != 0 {
bail!("unsupported auxstore entry version {}", version);
}
let mut content_id = [0u8; 32];
cur.read_exact(&mut content_id)?;
let mut content_sha1 = [0u8; 20];
cur.read_exact(&mut content_sha1)?;
let mut content_sha256 = [0u8; 32];
cur.read_exact(&mut content_sha256)?;
let total_size: u64 = cur.read_vlq()?;
Ok((
hgid,
Entry {
content_id: content_id.into(),
content_sha1: content_sha1.into(),
content_sha256: content_sha256.into(),
total_size,
},
))
}
}
pub struct AuxStore(RwLock<Store>);
impl AuxStore {
pub fn new(path: impl AsRef<Path>, config: &ConfigSet, store_type: StoreType) -> Result<Self> {
// TODO(meyer): Eliminate "local" AuxStore - always treat it as shared / cache?
let open_options = AuxStore::open_options(config)?;
let log = match store_type {
StoreType::Local => open_options.local(&path),
StoreType::Shared => open_options.shared(&path),
}?;
Ok(AuxStore(RwLock::new(log)))
}
fn open_options(config: &ConfigSet) -> Result<StoreOpenOptions> {
// TODO(meyer): Decide exactly how we want to configure this store. This is all copied from indexedlogdatastore
// Default configuration: 4 x 2.5GB.
let mut open_options = StoreOpenOptions::new()
.max_log_count(4)
.max_bytes_per_log(2500 * 1000 * 1000)
.auto_sync_threshold(10 * 1024 * 1024)
.create(true)
.index("node", |_| {
vec![IndexOutput::Reference(0..HgId::len() as u64)]
});
if let Some(max_log_count) = config.get_opt::<u8>("indexedlog", "data.max-log-count")? {
open_options = open_options.max_log_count(max_log_count);
}
if let Some(max_bytes_per_log) =
config.get_opt::<ByteCount>("indexedlog", "data.max-bytes-per-log")?
{
open_options = open_options.max_bytes_per_log(max_bytes_per_log.value());
} else if let Some(max_bytes_per_log) =
config.get_opt::<ByteCount>("remotefilelog", "cachelimit")?
{
let log_count: u64 = open_options.max_log_count.unwrap_or(1).max(1).into();
open_options =
open_options.max_bytes_per_log((max_bytes_per_log.value() / log_count).max(1));
}
Ok(open_options)
}
pub fn get(&self, hgid: HgId) -> Result<Option<Entry>> {
let log = self.0.read();
let mut entries = log.lookup(0, &hgid)?;
let slice = match entries.next() {
None => return Ok(None),
Some(slice) => slice?,
};
let bytes = log.slice_to_bytes(slice);
drop(log);
Entry::deserialize(bytes).map(|(_hgid, entry)| Some(entry))
}
pub fn put(&self, hgid: HgId, entry: &Entry) -> Result<()> {
let serialized = entry.serialize(hgid)?;
self.0.write().append(&serialized)
}
pub fn flush(&self) -> Result<()> {
self.0.write().flush()
}
#[cfg(test)]
pub(crate) fn hgids(&self) -> Result<Vec<HgId>> {
let log = self.0.read();
log.iter()
.map(|slice| {
let bytes = log.slice_to_bytes(slice?);
Entry::deserialize(bytes).map(|(hgid, _entry)| hgid)
})
.collect()
}
}
#[cfg(test)]
mod tests {
use std::fs::remove_file;
use std::str::FromStr;
use std::sync::Arc;
use tempfile::TempDir; | use types::testutil::*;
use super::*;
use crate::scmstore::FileAttributes;
use crate::scmstore::FileStore;
use crate::testutil::*;
use crate::ExtStoredPolicy;
use crate::HgIdMutableDeltaStore;
use crate::IndexedLogHgIdDataStore;
fn single_byte_sha1(fst: u8) -> Sha1 {
let mut x: [u8; Sha1::len()] = Default::default();
x[0] = fst;
Sha1::from(x)
}
#[test]
fn test_empty() -> Result<()> {
let tempdir = TempDir::new()?;
let store = AuxStore::new(&tempdir, &ConfigSet::new(), StoreType::Shared)?;
store.flush()?;
Ok(())
}
#[test]
fn test_add_get() -> Result<()> {
let tempdir = TempDir::new().unwrap();
let store = AuxStore::new(&tempdir, &ConfigSet::new(), StoreType::Shared)?;
let mut entry = Entry::default();
entry.total_size = 1;
entry.content_sha1 = single_byte_sha1(1);
let k = key("a", "1");
store.put(k.hgid, &entry)?;
store.flush()?;
let found = store.get(k.hgid)?;
assert_eq!(Some(entry), found);
Ok(())
}
#[test]
fn test_lookup_failure() -> Result<()> {
let tempdir = TempDir::new().unwrap();
let store = AuxStore::new(&tempdir, &ConfigSet::new(), StoreType::Shared)?;
let mut entry = Entry::default();
entry.total_size = 1;
entry.content_sha1 = single_byte_sha1(1);
let k = key("a", "1");
store.put(k.hgid, &entry)?;
store.flush()?;
let k2 = key("b", "2");
let found = store.get(k2.hgid)?;
assert_eq!(None, found);
Ok(())
}
#[test]
fn test_corrupted() -> Result<()> {
let tempdir = TempDir::new()?;
let store = AuxStore::new(&tempdir, &ConfigSet::new(), StoreType::Shared)?;
let k = key("a", "2");
let mut entry = Entry::default();
entry.total_size = 2;
entry.content_sha1 = single_byte_sha1(2);
store.put(k.hgid, &entry)?;
store.flush()?;
drop(store);
// Corrupt the log by removing the "log" file.
let mut rotate_log_path = tempdir.path().to_path_buf();
rotate_log_path.push("0");
rotate_log_path.push("log");
remove_file(rotate_log_path)?;
let store = AuxStore::new(&tempdir, &ConfigSet::new(), StoreType::Shared)?;
let k = key("a", "3");
let mut entry = Entry::default();
entry.total_size = 3;
entry.content_sha1 = single_byte_sha1(3);
store.put(k.hgid, &entry)?;
store.flush()?;
// There should be only one key in the store.
assert_eq!(store.hgids().into_iter().count(), 1);
Ok(())
}
#[test]
fn test_scmstore_read() -> Result<()> {
let tmp = TempDir::new()?;
let aux = Arc::new(AuxStore::new(&tmp, &ConfigSet::new(), StoreType::Shared)?);
let mut entry = Entry::default();
entry.total_size = 1;
entry.content_sha1 = single_byte_sha1(1);
let k = key("a", "1");
aux.put(k.hgid, &entry)?;
aux.flush()?;
// Set up local-only FileStore
let mut store = FileStore::empty();
store.aux_local = Some(aux.clone());
// Attempt fetch.
let fetched = store
.fetch(std::iter::once(k.clone()), FileAttributes::AUX)
.single()?
.expect("key not found");
assert_eq!(entry, fetched.aux_data().expect("no aux data found").into());
Ok(())
}
#[test]
fn test_scmstore_compute_read() -> Result<()> {
let k = key("a", "def6f29d7b61f9cb70b2f14f79cd5c43c38e21b2");
let d = delta("1234", None, k.clone());
let meta = Default::default();
// Setup local indexedlog
let tmp = TempDir::new()?;
let content = Arc::new(IndexedLogHgIdDataStore::new(
&tmp,
ExtStoredPolicy::Ignore,
&ConfigSet::new(),
StoreType::Shared,
)?);
content.add(&d, &meta).unwrap();
content.flush().unwrap();
let tmp = TempDir::new()?;
let aux = Arc::new(AuxStore::new(&tmp, &ConfigSet::new(), StoreType::Shared)?);
// Set up local-only FileStore
let mut store = FileStore::empty();
store.cache_to_local_cache = true;
store.indexedlog_local = Some(content.clone());
store.aux_local = Some(aux.clone());
let mut expected = Entry::default();
expected.total_size = 4;
expected.content_id = ContentId::from_str(
"aa6ab85da77ca480b7624172fe44aa9906b6c3f00f06ff23c3e5f60bfd0c414e",
)?;
expected.content_sha1 = Sha1::from_str("7110eda4d09e062aa5e4a390b0a572ac0d2c0220")?;
expected.content_sha256 =
Sha256::from_str("03ac674216f3e15c761ee1a5e255f067953623c8b388b4459e13f978d7c846f4")?;
// Attempt fetch.
let fetched = store
.fetch(std::iter::once(k.clone()), FileAttributes::AUX)
.single()?
.expect("key not found");
assert_eq!(
expected,
fetched.aux_data().expect("no aux data found").into()
);
// Verify we can read it directly too
let found = aux.get(k.hgid)?;
assert_eq!(Some(expected), found);
Ok(())
}
} | random_line_split | |
index.tsx | /// <reference path="../node_modules/protobufjs/stub-node.d.ts" />
/**
* UI/NEXT TODO LIST
*
* ! = Potentially difficult to implement
*
* - All Pages / Shared Components
* - "Last Updated"
* - Dropdowns
* - Fix 1px offset bug
* - Tables
* - CSS Match to design
* - Management of column widths
* - Cluster Page
* - Alert notifications
* - Mismatched/Out-of-date Version
* - Help us
* - Right-side Summary Section
* - Link to Nodes page
* - Events?
* - Graphs
* - Tooltip when hover over title
* - Code block syntax highlighting
* - Choose keywords correctly
* - Fix bug on direct page load
* - Databases Page
* - Last Updated Column
* - Retrieve/Filter events
* - Single database page
* - Table component row limit
* - Route to single database
* - Schema Change
* - Retrieve information from backend
* - Display in table list column
* - Display alert on table details page
* - Table details page
* - Schema Change notification
* - Fill out summary stats
* - Back Button
* - Column widths for grants table
* - Nodes page
* - Table Style
* - Add Summary Section
* - Remove Link from Navigation Bar
* - Helpus Page
* - New Navigation Bar Icon
* - Header links
* - New form field Appearance
*
* NICE TO HAVE:
* - Create a "NodeStatusProvider" similar to "MetricsDataProvider", allowing
* different components to access nodes data.
*
* - Commonize code between different graph types (LineGraph and
* StackedAreaGraph). This can likely be done by converting them into stateless
* functions, that return an underlying "Common" graph component. The props of
* the Common graph component would include the part of `initGraph` and
* `drawGraph` that are different for these two chart types.
*
*/
import "nvd3/build/nv.d3.min.css";
import "react-select/dist/react-select.css";
import "../styl/app.styl";
import "./js/sim/style.css";
import * as protobuf from "protobufjs/minimal";
import Long from "long";
protobuf.util.Long = Long as any;
protobuf.configure();
import * as React from "react";
import * as ReactDOM from "react-dom";
import { Provider } from "react-redux";
import { Router, Route, IndexRoute, IndexRedirect } from "react-router";
import {
tableNameAttr, databaseNameAttr, nodeIDAttr, dashboardNameAttr,
} from "./util/constants";
import { store, history } from "./redux/state";
import Layout from "./containers/layout";
import { DatabaseTablesList, DatabaseGrantsList } from "./containers/databases/databases";
import TableDetails from "./containers/databases/tableDetails";
import Nodes from "./containers/nodes";
import NodesOverview from "./containers/nodesOverview";
import NodeOverview from "./containers/nodeOverview";
import NodeGraphs from "./containers/nodeGraphs";
import NodeLogs from "./containers/nodeLogs";
import { EventPage } from "./containers/events";
import Raft from "./containers/raft";
import RaftRanges from "./containers/raftRanges";
import ClusterViz from "./containers/clusterViz";
import { alertDataSync } from "./redux/alerts";
ReactDOM.render(
<Provider store={store}>
<Router history={history}>
<Route path="/" component={Layout}>
<IndexRedirect to="cluster" />
<Route path="cluster" component={ Nodes }>
<IndexRedirect to="all/overview" />
<Route path={`all/:${dashboardNameAttr}`} component={NodeGraphs} />
<Route path={ `node/:${nodeIDAttr}/:${dashboardNameAttr}` } component={NodeGraphs} />
</Route>
<Route path="cluster">
<Route path="nodes">
<IndexRoute component={NodesOverview} />
<Route path={`:${nodeIDAttr}`}>
<IndexRoute component={NodeOverview} />
<Route path="logs" component={ NodeLogs } />
</Route>
</Route>
<Route path="events" component={ EventPage } />
</Route>
<Route path="databases">
<IndexRedirect to="tables" /> | <Route path="raft" component={ Raft }>
<IndexRedirect to="ranges" />
<Route path="ranges" component={ RaftRanges } />
</Route>
<Route path="clusterviz" component={ ClusterViz } />
</Route>
</Router>
</Provider>,
document.getElementById("react-layout"),
);
store.subscribe(alertDataSync(store)); | <Route path="tables" component={ DatabaseTablesList } />
<Route path="grants" component={ DatabaseGrantsList } />
<Route path={ `database/:${databaseNameAttr}/table/:${tableNameAttr}` } component={ TableDetails } />
</Route> | random_line_split |
test_sys_call.py | # Copyright 2016: Mirantis Inc.
# All Rights Reserved.
#
# 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.
import subprocess
import jsonschema
import mock
from rally import consts
from rally.plugins.common.hook import sys_call
from rally.task import hook
from tests.unit import fakes
from tests.unit import test
class SysCallHookTestCase(test.TestCase):
def test_validate(self):
|
def test_validate_error(self):
conf = {
"name": "sys_call",
"description": "list folder",
"args": {
"cmd": 50,
},
"trigger": {
"name": "event",
"args": {
"unit": "iteration",
"at": [10]
}
}
}
self.assertRaises(
jsonschema.ValidationError, hook.Hook.validate, conf)
@mock.patch("rally.common.utils.Timer", side_effect=fakes.FakeTimer)
@mock.patch("subprocess.Popen")
def test_run(self, mock_popen, mock_timer):
popen_instance = mock_popen.return_value
popen_instance.returncode = 0
task = mock.MagicMock()
sys_call_hook = sys_call.SysCallHook(task, "/bin/bash -c 'ls'",
{"iteration": 1}, "dummy_action")
sys_call_hook.run_sync()
sys_call_hook.validate_result_schema()
self.assertEqual(
{
"hook": "sys_call",
"description": "dummy_action",
"triggered_by": {"iteration": 1},
"started_at": fakes.FakeTimer().timestamp(),
"finished_at": fakes.FakeTimer().finish_timestamp(),
"status": consts.HookStatus.SUCCESS,
}, sys_call_hook.result())
mock_popen.assert_called_once_with(
["/bin/bash", "-c", "ls"],
stdout=subprocess.PIPE,
stderr=subprocess.STDOUT)
@mock.patch("rally.common.utils.Timer", side_effect=fakes.FakeTimer)
@mock.patch("subprocess.Popen")
def test_run_error(self, mock_popen, mock_timer):
popen_instance = mock_popen.return_value
popen_instance.returncode = 1
popen_instance.stdout.read.return_value = b"No such file or directory"
task = mock.MagicMock()
sys_call_hook = sys_call.SysCallHook(task, "/bin/bash -c 'ls'",
{"iteration": 1}, "dummy_action")
sys_call_hook.run_sync()
sys_call_hook.validate_result_schema()
self.assertEqual(
{
"hook": "sys_call",
"description": "dummy_action",
"triggered_by": {"iteration": 1},
"started_at": fakes.FakeTimer().timestamp(),
"finished_at": fakes.FakeTimer().finish_timestamp(),
"status": consts.HookStatus.FAILED,
"error": [
"n/a",
"Subprocess returned 1",
"No such file or directory",
]
}, sys_call_hook.result())
mock_popen.assert_called_once_with(
["/bin/bash", "-c", "ls"],
stdout=subprocess.PIPE,
stderr=subprocess.STDOUT)
| hook.Hook.validate(
{
"name": "sys_call",
"description": "list folder",
"args": "ls",
"trigger": {
"name": "event",
"args": {
"unit": "iteration",
"at": [10]
}
}
}
) | identifier_body |
test_sys_call.py | # Copyright 2016: Mirantis Inc.
# All Rights Reserved.
#
# 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.
import subprocess
import jsonschema
import mock
from rally import consts
from rally.plugins.common.hook import sys_call
from rally.task import hook
from tests.unit import fakes
from tests.unit import test
class | (test.TestCase):
def test_validate(self):
hook.Hook.validate(
{
"name": "sys_call",
"description": "list folder",
"args": "ls",
"trigger": {
"name": "event",
"args": {
"unit": "iteration",
"at": [10]
}
}
}
)
def test_validate_error(self):
conf = {
"name": "sys_call",
"description": "list folder",
"args": {
"cmd": 50,
},
"trigger": {
"name": "event",
"args": {
"unit": "iteration",
"at": [10]
}
}
}
self.assertRaises(
jsonschema.ValidationError, hook.Hook.validate, conf)
@mock.patch("rally.common.utils.Timer", side_effect=fakes.FakeTimer)
@mock.patch("subprocess.Popen")
def test_run(self, mock_popen, mock_timer):
popen_instance = mock_popen.return_value
popen_instance.returncode = 0
task = mock.MagicMock()
sys_call_hook = sys_call.SysCallHook(task, "/bin/bash -c 'ls'",
{"iteration": 1}, "dummy_action")
sys_call_hook.run_sync()
sys_call_hook.validate_result_schema()
self.assertEqual(
{
"hook": "sys_call",
"description": "dummy_action",
"triggered_by": {"iteration": 1},
"started_at": fakes.FakeTimer().timestamp(),
"finished_at": fakes.FakeTimer().finish_timestamp(),
"status": consts.HookStatus.SUCCESS,
}, sys_call_hook.result())
mock_popen.assert_called_once_with(
["/bin/bash", "-c", "ls"],
stdout=subprocess.PIPE,
stderr=subprocess.STDOUT)
@mock.patch("rally.common.utils.Timer", side_effect=fakes.FakeTimer)
@mock.patch("subprocess.Popen")
def test_run_error(self, mock_popen, mock_timer):
popen_instance = mock_popen.return_value
popen_instance.returncode = 1
popen_instance.stdout.read.return_value = b"No such file or directory"
task = mock.MagicMock()
sys_call_hook = sys_call.SysCallHook(task, "/bin/bash -c 'ls'",
{"iteration": 1}, "dummy_action")
sys_call_hook.run_sync()
sys_call_hook.validate_result_schema()
self.assertEqual(
{
"hook": "sys_call",
"description": "dummy_action",
"triggered_by": {"iteration": 1},
"started_at": fakes.FakeTimer().timestamp(),
"finished_at": fakes.FakeTimer().finish_timestamp(),
"status": consts.HookStatus.FAILED,
"error": [
"n/a",
"Subprocess returned 1",
"No such file or directory",
]
}, sys_call_hook.result())
mock_popen.assert_called_once_with(
["/bin/bash", "-c", "ls"],
stdout=subprocess.PIPE,
stderr=subprocess.STDOUT)
| SysCallHookTestCase | identifier_name |
test_sys_call.py | # Copyright 2016: Mirantis Inc.
# All Rights Reserved.
#
# 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.
import subprocess
import jsonschema
import mock
from rally import consts
from rally.plugins.common.hook import sys_call
from rally.task import hook
from tests.unit import fakes
from tests.unit import test
class SysCallHookTestCase(test.TestCase):
def test_validate(self):
hook.Hook.validate(
{
"name": "sys_call",
"description": "list folder",
"args": "ls",
"trigger": {
"name": "event",
"args": {
"unit": "iteration",
"at": [10]
}
}
}
)
def test_validate_error(self):
conf = {
"name": "sys_call", | "cmd": 50,
},
"trigger": {
"name": "event",
"args": {
"unit": "iteration",
"at": [10]
}
}
}
self.assertRaises(
jsonschema.ValidationError, hook.Hook.validate, conf)
@mock.patch("rally.common.utils.Timer", side_effect=fakes.FakeTimer)
@mock.patch("subprocess.Popen")
def test_run(self, mock_popen, mock_timer):
popen_instance = mock_popen.return_value
popen_instance.returncode = 0
task = mock.MagicMock()
sys_call_hook = sys_call.SysCallHook(task, "/bin/bash -c 'ls'",
{"iteration": 1}, "dummy_action")
sys_call_hook.run_sync()
sys_call_hook.validate_result_schema()
self.assertEqual(
{
"hook": "sys_call",
"description": "dummy_action",
"triggered_by": {"iteration": 1},
"started_at": fakes.FakeTimer().timestamp(),
"finished_at": fakes.FakeTimer().finish_timestamp(),
"status": consts.HookStatus.SUCCESS,
}, sys_call_hook.result())
mock_popen.assert_called_once_with(
["/bin/bash", "-c", "ls"],
stdout=subprocess.PIPE,
stderr=subprocess.STDOUT)
@mock.patch("rally.common.utils.Timer", side_effect=fakes.FakeTimer)
@mock.patch("subprocess.Popen")
def test_run_error(self, mock_popen, mock_timer):
popen_instance = mock_popen.return_value
popen_instance.returncode = 1
popen_instance.stdout.read.return_value = b"No such file or directory"
task = mock.MagicMock()
sys_call_hook = sys_call.SysCallHook(task, "/bin/bash -c 'ls'",
{"iteration": 1}, "dummy_action")
sys_call_hook.run_sync()
sys_call_hook.validate_result_schema()
self.assertEqual(
{
"hook": "sys_call",
"description": "dummy_action",
"triggered_by": {"iteration": 1},
"started_at": fakes.FakeTimer().timestamp(),
"finished_at": fakes.FakeTimer().finish_timestamp(),
"status": consts.HookStatus.FAILED,
"error": [
"n/a",
"Subprocess returned 1",
"No such file or directory",
]
}, sys_call_hook.result())
mock_popen.assert_called_once_with(
["/bin/bash", "-c", "ls"],
stdout=subprocess.PIPE,
stderr=subprocess.STDOUT) | "description": "list folder",
"args": { | random_line_split |
lib.rs | /* This Source Code Form is subject to the terms of the Mozilla Public
* License, v. 2.0. If a copy of the MPL was not distributed with this
* file, You can obtain one at http://mozilla.org/MPL/2.0/. */
#![feature(box_syntax)]
#![feature(custom_derive)]
#![feature(plugin)]
#![feature(mpsc_select)]
#![feature(plugin)]
#![plugin(plugins)]
#![deny(unsafe_code)]
#![plugin(serde_macros)]
extern crate app_units;
extern crate azure;
extern crate canvas;
extern crate canvas_traits;
extern crate clipboard;
#[cfg(target_os = "macos")]
extern crate core_graphics;
#[cfg(target_os = "macos")]
extern crate core_text;
extern crate devtools_traits;
extern crate euclid;
#[cfg(not(target_os = "windows"))]
extern crate gaol;
extern crate gfx;
extern crate gfx_traits;
extern crate gleam;
extern crate image;
extern crate ipc_channel;
extern crate layers;
extern crate layout_traits;
#[macro_use]
extern crate log;
extern crate msg;
extern crate net_traits;
extern crate num;
extern crate offscreen_gl_context;
#[macro_use]
extern crate profile_traits;
extern crate rand;
extern crate script_traits;
extern crate serde;
extern crate style_traits;
extern crate time;
extern crate url;
#[macro_use]
extern crate util;
extern crate webrender;
extern crate webrender_traits;
pub use compositor_thread::{CompositorEventListener, CompositorProxy, CompositorThread};
pub use constellation::Constellation;
use euclid::size::{Size2D};
use gfx_traits::Epoch;
use ipc_channel::ipc::{IpcSender};
use msg::constellation_msg::{FrameId, Key, KeyState, KeyModifiers, LoadData};
use msg::constellation_msg::{NavigationDirection, PipelineId, SubpageId};
use msg::constellation_msg::{WebDriverCommandMsg, WindowSizeData};
use std::collections::HashMap;
use url::Url;
mod compositor;
mod compositor_layer;
pub mod compositor_thread;
pub mod constellation;
mod delayed_composition;
pub mod pipeline;
#[cfg(not(target_os = "windows"))]
pub mod sandboxing;
mod surface_map;
mod timer_scheduler;
mod touch;
pub mod windowing;
/// Specifies whether the script or layout thread needs to be ticked for animation.
#[derive(Deserialize, Serialize)]
pub enum | {
Script,
Layout,
}
/// Messages from the compositor to the constellation.
#[derive(Deserialize, Serialize)]
pub enum CompositorMsg {
Exit,
FrameSize(PipelineId, Size2D<f32>),
/// Request that the constellation send the FrameId corresponding to the document
/// with the provided pipeline id
GetFrame(PipelineId, IpcSender<Option<FrameId>>),
/// Request that the constellation send the current pipeline id for the provided frame
/// id, or for the root frame if this is None, over a provided channel
GetPipeline(Option<FrameId>, IpcSender<Option<PipelineId>>),
/// Requests that the constellation inform the compositor of the title of the pipeline
/// immediately.
GetPipelineTitle(PipelineId),
InitLoadUrl(Url),
/// Query the constellation to see if the current compositor output is stable
IsReadyToSaveImage(HashMap<PipelineId, Epoch>),
KeyEvent(Key, KeyState, KeyModifiers),
LoadUrl(PipelineId, LoadData),
Navigate(Option<(PipelineId, SubpageId)>, NavigationDirection),
ResizedWindow(WindowSizeData),
/// Requests that the constellation instruct layout to begin a new tick of the animation.
TickAnimation(PipelineId, AnimationTickType),
/// Dispatch a webdriver command
WebDriverCommand(WebDriverCommandMsg),
}
| AnimationTickType | identifier_name |
lib.rs | /* This Source Code Form is subject to the terms of the Mozilla Public
* License, v. 2.0. If a copy of the MPL was not distributed with this
* file, You can obtain one at http://mozilla.org/MPL/2.0/. */
#![feature(box_syntax)]
#![feature(custom_derive)]
#![feature(plugin)]
#![feature(mpsc_select)]
#![feature(plugin)]
#![plugin(plugins)]
#![deny(unsafe_code)]
#![plugin(serde_macros)]
extern crate app_units;
extern crate azure;
extern crate canvas;
extern crate canvas_traits;
extern crate clipboard;
#[cfg(target_os = "macos")]
extern crate core_graphics;
#[cfg(target_os = "macos")]
extern crate core_text;
extern crate devtools_traits;
extern crate euclid;
#[cfg(not(target_os = "windows"))]
extern crate gaol;
extern crate gfx;
extern crate gfx_traits;
extern crate gleam;
extern crate image; | extern crate layout_traits;
#[macro_use]
extern crate log;
extern crate msg;
extern crate net_traits;
extern crate num;
extern crate offscreen_gl_context;
#[macro_use]
extern crate profile_traits;
extern crate rand;
extern crate script_traits;
extern crate serde;
extern crate style_traits;
extern crate time;
extern crate url;
#[macro_use]
extern crate util;
extern crate webrender;
extern crate webrender_traits;
pub use compositor_thread::{CompositorEventListener, CompositorProxy, CompositorThread};
pub use constellation::Constellation;
use euclid::size::{Size2D};
use gfx_traits::Epoch;
use ipc_channel::ipc::{IpcSender};
use msg::constellation_msg::{FrameId, Key, KeyState, KeyModifiers, LoadData};
use msg::constellation_msg::{NavigationDirection, PipelineId, SubpageId};
use msg::constellation_msg::{WebDriverCommandMsg, WindowSizeData};
use std::collections::HashMap;
use url::Url;
mod compositor;
mod compositor_layer;
pub mod compositor_thread;
pub mod constellation;
mod delayed_composition;
pub mod pipeline;
#[cfg(not(target_os = "windows"))]
pub mod sandboxing;
mod surface_map;
mod timer_scheduler;
mod touch;
pub mod windowing;
/// Specifies whether the script or layout thread needs to be ticked for animation.
#[derive(Deserialize, Serialize)]
pub enum AnimationTickType {
Script,
Layout,
}
/// Messages from the compositor to the constellation.
#[derive(Deserialize, Serialize)]
pub enum CompositorMsg {
Exit,
FrameSize(PipelineId, Size2D<f32>),
/// Request that the constellation send the FrameId corresponding to the document
/// with the provided pipeline id
GetFrame(PipelineId, IpcSender<Option<FrameId>>),
/// Request that the constellation send the current pipeline id for the provided frame
/// id, or for the root frame if this is None, over a provided channel
GetPipeline(Option<FrameId>, IpcSender<Option<PipelineId>>),
/// Requests that the constellation inform the compositor of the title of the pipeline
/// immediately.
GetPipelineTitle(PipelineId),
InitLoadUrl(Url),
/// Query the constellation to see if the current compositor output is stable
IsReadyToSaveImage(HashMap<PipelineId, Epoch>),
KeyEvent(Key, KeyState, KeyModifiers),
LoadUrl(PipelineId, LoadData),
Navigate(Option<(PipelineId, SubpageId)>, NavigationDirection),
ResizedWindow(WindowSizeData),
/// Requests that the constellation instruct layout to begin a new tick of the animation.
TickAnimation(PipelineId, AnimationTickType),
/// Dispatch a webdriver command
WebDriverCommand(WebDriverCommandMsg),
} | extern crate ipc_channel;
extern crate layers; | random_line_split |
save-action-service.js | (function() {
'use strict';
angular
.module('otusjs.player.core.phase')
.service('otusjs.player.core.phase.SaveActionService', Service);
Service.$inject = [
'otusjs.player.core.phase.ActionPipeService',
'otusjs.player.core.phase.PreSaveActionService',
'otusjs.player.core.phase.ExecutionSaveActionService',
'otusjs.player.core.phase.PostSaveActionService'
];
function Service(ActionPipeService, PreSaveActionService, ExecutionSaveActionService, PostSaveActionService) |
})();
| {
var self = this;
/* Public methods */
self.PreSaveActionService = PreSaveActionService;
self.ExecutionSaveActionService = ExecutionSaveActionService;
self.PostSaveActionService = PostSaveActionService;
self.execute = execute;
function execute() {
var phaseData = PreSaveActionService.execute(ActionPipeService.flowData);
phaseData = ExecutionSaveActionService.execute(phaseData);
phaseData = PostSaveActionService.execute(phaseData);
}
} | identifier_body |
save-action-service.js | (function() {
'use strict';
angular
.module('otusjs.player.core.phase')
.service('otusjs.player.core.phase.SaveActionService', Service);
Service.$inject = [
'otusjs.player.core.phase.ActionPipeService',
'otusjs.player.core.phase.PreSaveActionService',
'otusjs.player.core.phase.ExecutionSaveActionService',
'otusjs.player.core.phase.PostSaveActionService' |
/* Public methods */
self.PreSaveActionService = PreSaveActionService;
self.ExecutionSaveActionService = ExecutionSaveActionService;
self.PostSaveActionService = PostSaveActionService;
self.execute = execute;
function execute() {
var phaseData = PreSaveActionService.execute(ActionPipeService.flowData);
phaseData = ExecutionSaveActionService.execute(phaseData);
phaseData = PostSaveActionService.execute(phaseData);
}
}
})(); | ];
function Service(ActionPipeService, PreSaveActionService, ExecutionSaveActionService, PostSaveActionService) {
var self = this; | random_line_split |
save-action-service.js | (function() {
'use strict';
angular
.module('otusjs.player.core.phase')
.service('otusjs.player.core.phase.SaveActionService', Service);
Service.$inject = [
'otusjs.player.core.phase.ActionPipeService',
'otusjs.player.core.phase.PreSaveActionService',
'otusjs.player.core.phase.ExecutionSaveActionService',
'otusjs.player.core.phase.PostSaveActionService'
];
function Service(ActionPipeService, PreSaveActionService, ExecutionSaveActionService, PostSaveActionService) {
var self = this;
/* Public methods */
self.PreSaveActionService = PreSaveActionService;
self.ExecutionSaveActionService = ExecutionSaveActionService;
self.PostSaveActionService = PostSaveActionService;
self.execute = execute;
function | () {
var phaseData = PreSaveActionService.execute(ActionPipeService.flowData);
phaseData = ExecutionSaveActionService.execute(phaseData);
phaseData = PostSaveActionService.execute(phaseData);
}
}
})();
| execute | identifier_name |
main.rs | /*
Full Monkey.
Generic preprocessor tool.
Copyright 2016 Sam Saint-Pettersen.
Released under the MIT/X11 License.
*/
extern crate clioptions;
extern crate regex;
use clioptions::CliOptions;
use regex::Regex;
use std::io::{BufRead, BufReader, Write};
use std::fs::File;
use std::process::exit;
fn preprocess(input: &str, output: &str, conditions: &str, verbose: bool) {
let mut loc: Vec<String> = Vec::new();
let mut preprocessed: Vec<String> = Vec::new();
let mut cond = String::new();
let mut set_conds: Vec<String> = Vec::new();
let mut prefixed: Vec<String> = Vec::new();
let mut prefixes: Vec<String> = Vec::new();
let mut in_pp = false;
let conditions = conditions.split(",");
for sc in conditions {
set_conds.push(sc.to_string());
}
let f = File::open(input).unwrap();
let file = BufReader::new(&f);
for l in file.lines() {
let l = l.unwrap();
// Process prefix...
let mut p = Regex::new("#prefix (.*) with (.*)").unwrap();
if p.is_match(&l) {
for cap in p.captures_iter(&l) {
prefixed.push(cap.at(1).unwrap().to_string());
prefixes.push(cap.at(2).unwrap().to_string());
}
continue;
}
// Process conditional (if/else/elseif)...
p = Regex::new("#[else]*[if]* (.*)").unwrap();
if p.is_match(&l) {
for cap in p.captures_iter(&l) {
cond = cap.at(1).unwrap().to_string();
in_pp = true;
}
continue;
}
// Process end block...
p = Regex::new("#[fi|endif]").unwrap();
if p.is_match(&l) {
in_pp = false;
continue;
}
// Push relevant LoC to vector...
for sc in set_conds.clone() {
if in_pp && cond == sc {
preprocessed.push(l.to_string());
}
}
if !in_pp {
preprocessed.push(l.to_string());
continue;
}
}
// Do any alterations:
for line in preprocessed {
let mut fl = line;
for (i, p) in prefixed.iter().enumerate() {
let r = Regex::new(®ex::quote(&p)).unwrap();
let repl = format!("{}{}", &prefixes[i], &p);
fl = r.replace_all(&fl, &repl[..]);
}
loc.push(fl);
}
loc.push(String::new());
if verbose {
println!("Preprocessing {} --> {}", input, output);
}
let mut w = File::create(output).unwrap();
let _ = w.write_all(loc.join("\n").as_bytes());
}
fn display_version() {
println!("Full Monkey v. 0.1");
println!(r" __");
println!(r"w c(..)o (");
println!(r" \__(-) __)");
println!(r" /\ (");
println!(r" /(_)___)");
println!(r" w /|");
println!(r" | \");
println!(r" m m");
println!("\nMonkey appears courtesy of ejm97:");
println!("http://www.ascii-art.de/ascii/mno/monkey.txt");
exit(0);
}
fn display_error(program: &str, error: &str) {
println!("Error: {}.", error);
display_usage(&program, -1);
}
fn | (program: &str, exit_code: i32) {
println!("\nFull Monkey.");
println!("Generic preprocessor tool.");
println!("\nCopyright 2016 Sam Saint-Pettersen.");
println!("Released under the MIT/X11 License.");
println!("\n{} -f|--file <input> [-c|--condition <condition(s)>] -o|--out <output>", program);
println!("[-l|--verbose][-h|--help | -v|--version]");
println!("\n-f|--file: File to run preprocessing on.");
println!("-c|--conditon: Comma delimited list of conditon(s) to apply.");
println!("-o|--out: File to output preprocessed LoC to.");
println!("-l|--verbose: Display message to console on process.");
println!("-h|--help: Display this help information and exit.");
println!("-v|--version: Display program version and exit.");
exit(exit_code);
}
fn main() {
let cli = CliOptions::new("fm");
let program = cli.get_program();
let mut input = String::new();
let mut output = String::new();
let mut conditions = String::new();
let mut verbose = false;
if cli.get_num() > 1 {
for (i, a) in cli.get_args().iter().enumerate() {
match a.trim() {
"-h" | "--help" => display_usage(&program, 0),
"-v" | "--version" => display_version(),
"-f" | "--file" => input = cli.next_argument(i),
"-c" | "--condition" => conditions = cli.next_argument(i),
"-o" | "--out" => output = cli.next_argument(i),
"-l" | "--verbose" => verbose = true,
_ => continue,
}
}
if input.is_empty() {
display_error(&program, "No input specified");
}
if output.is_empty() {
display_error(&program, "No output specified");
}
preprocess(&input, &output, &conditions, verbose);
}
else {
display_error(&program, "No options specified");
}
}
| display_usage | identifier_name |
main.rs | /*
Full Monkey.
Generic preprocessor tool.
Copyright 2016 Sam Saint-Pettersen.
Released under the MIT/X11 License.
*/
extern crate clioptions;
extern crate regex;
use clioptions::CliOptions;
use regex::Regex;
use std::io::{BufRead, BufReader, Write};
use std::fs::File;
use std::process::exit;
fn preprocess(input: &str, output: &str, conditions: &str, verbose: bool) |
fn display_version() {
println!("Full Monkey v. 0.1");
println!(r" __");
println!(r"w c(..)o (");
println!(r" \__(-) __)");
println!(r" /\ (");
println!(r" /(_)___)");
println!(r" w /|");
println!(r" | \");
println!(r" m m");
println!("\nMonkey appears courtesy of ejm97:");
println!("http://www.ascii-art.de/ascii/mno/monkey.txt");
exit(0);
}
fn display_error(program: &str, error: &str) {
println!("Error: {}.", error);
display_usage(&program, -1);
}
fn display_usage(program: &str, exit_code: i32) {
println!("\nFull Monkey.");
println!("Generic preprocessor tool.");
println!("\nCopyright 2016 Sam Saint-Pettersen.");
println!("Released under the MIT/X11 License.");
println!("\n{} -f|--file <input> [-c|--condition <condition(s)>] -o|--out <output>", program);
println!("[-l|--verbose][-h|--help | -v|--version]");
println!("\n-f|--file: File to run preprocessing on.");
println!("-c|--conditon: Comma delimited list of conditon(s) to apply.");
println!("-o|--out: File to output preprocessed LoC to.");
println!("-l|--verbose: Display message to console on process.");
println!("-h|--help: Display this help information and exit.");
println!("-v|--version: Display program version and exit.");
exit(exit_code);
}
fn main() {
let cli = CliOptions::new("fm");
let program = cli.get_program();
let mut input = String::new();
let mut output = String::new();
let mut conditions = String::new();
let mut verbose = false;
if cli.get_num() > 1 {
for (i, a) in cli.get_args().iter().enumerate() {
match a.trim() {
"-h" | "--help" => display_usage(&program, 0),
"-v" | "--version" => display_version(),
"-f" | "--file" => input = cli.next_argument(i),
"-c" | "--condition" => conditions = cli.next_argument(i),
"-o" | "--out" => output = cli.next_argument(i),
"-l" | "--verbose" => verbose = true,
_ => continue,
}
}
if input.is_empty() {
display_error(&program, "No input specified");
}
if output.is_empty() {
display_error(&program, "No output specified");
}
preprocess(&input, &output, &conditions, verbose);
}
else {
display_error(&program, "No options specified");
}
}
| {
let mut loc: Vec<String> = Vec::new();
let mut preprocessed: Vec<String> = Vec::new();
let mut cond = String::new();
let mut set_conds: Vec<String> = Vec::new();
let mut prefixed: Vec<String> = Vec::new();
let mut prefixes: Vec<String> = Vec::new();
let mut in_pp = false;
let conditions = conditions.split(",");
for sc in conditions {
set_conds.push(sc.to_string());
}
let f = File::open(input).unwrap();
let file = BufReader::new(&f);
for l in file.lines() {
let l = l.unwrap();
// Process prefix...
let mut p = Regex::new("#prefix (.*) with (.*)").unwrap();
if p.is_match(&l) {
for cap in p.captures_iter(&l) {
prefixed.push(cap.at(1).unwrap().to_string());
prefixes.push(cap.at(2).unwrap().to_string());
}
continue;
}
// Process conditional (if/else/elseif)...
p = Regex::new("#[else]*[if]* (.*)").unwrap();
if p.is_match(&l) {
for cap in p.captures_iter(&l) {
cond = cap.at(1).unwrap().to_string();
in_pp = true;
}
continue;
}
// Process end block...
p = Regex::new("#[fi|endif]").unwrap();
if p.is_match(&l) {
in_pp = false;
continue;
}
// Push relevant LoC to vector...
for sc in set_conds.clone() {
if in_pp && cond == sc {
preprocessed.push(l.to_string());
}
}
if !in_pp {
preprocessed.push(l.to_string());
continue;
}
}
// Do any alterations:
for line in preprocessed {
let mut fl = line;
for (i, p) in prefixed.iter().enumerate() {
let r = Regex::new(®ex::quote(&p)).unwrap();
let repl = format!("{}{}", &prefixes[i], &p);
fl = r.replace_all(&fl, &repl[..]);
}
loc.push(fl);
}
loc.push(String::new());
if verbose {
println!("Preprocessing {} --> {}", input, output);
}
let mut w = File::create(output).unwrap();
let _ = w.write_all(loc.join("\n").as_bytes());
} | identifier_body |
main.rs | /*
Full Monkey.
Generic preprocessor tool.
Copyright 2016 Sam Saint-Pettersen.
Released under the MIT/X11 License.
*/
extern crate clioptions;
extern crate regex;
use clioptions::CliOptions;
use regex::Regex;
use std::io::{BufRead, BufReader, Write};
use std::fs::File;
use std::process::exit;
fn preprocess(input: &str, output: &str, conditions: &str, verbose: bool) {
let mut loc: Vec<String> = Vec::new();
let mut preprocessed: Vec<String> = Vec::new();
let mut cond = String::new();
let mut set_conds: Vec<String> = Vec::new();
let mut prefixed: Vec<String> = Vec::new();
let mut prefixes: Vec<String> = Vec::new();
let mut in_pp = false;
let conditions = conditions.split(",");
for sc in conditions {
set_conds.push(sc.to_string());
}
let f = File::open(input).unwrap();
let file = BufReader::new(&f);
for l in file.lines() {
let l = l.unwrap();
// Process prefix...
let mut p = Regex::new("#prefix (.*) with (.*)").unwrap();
if p.is_match(&l) {
for cap in p.captures_iter(&l) {
prefixed.push(cap.at(1).unwrap().to_string());
prefixes.push(cap.at(2).unwrap().to_string());
}
continue;
}
// Process conditional (if/else/elseif)...
p = Regex::new("#[else]*[if]* (.*)").unwrap();
if p.is_match(&l) {
for cap in p.captures_iter(&l) {
cond = cap.at(1).unwrap().to_string();
in_pp = true;
}
continue;
}
// Process end block...
p = Regex::new("#[fi|endif]").unwrap();
if p.is_match(&l) {
in_pp = false;
continue;
}
// Push relevant LoC to vector...
for sc in set_conds.clone() {
if in_pp && cond == sc {
preprocessed.push(l.to_string());
} | preprocessed.push(l.to_string());
continue;
}
}
// Do any alterations:
for line in preprocessed {
let mut fl = line;
for (i, p) in prefixed.iter().enumerate() {
let r = Regex::new(®ex::quote(&p)).unwrap();
let repl = format!("{}{}", &prefixes[i], &p);
fl = r.replace_all(&fl, &repl[..]);
}
loc.push(fl);
}
loc.push(String::new());
if verbose {
println!("Preprocessing {} --> {}", input, output);
}
let mut w = File::create(output).unwrap();
let _ = w.write_all(loc.join("\n").as_bytes());
}
fn display_version() {
println!("Full Monkey v. 0.1");
println!(r" __");
println!(r"w c(..)o (");
println!(r" \__(-) __)");
println!(r" /\ (");
println!(r" /(_)___)");
println!(r" w /|");
println!(r" | \");
println!(r" m m");
println!("\nMonkey appears courtesy of ejm97:");
println!("http://www.ascii-art.de/ascii/mno/monkey.txt");
exit(0);
}
fn display_error(program: &str, error: &str) {
println!("Error: {}.", error);
display_usage(&program, -1);
}
fn display_usage(program: &str, exit_code: i32) {
println!("\nFull Monkey.");
println!("Generic preprocessor tool.");
println!("\nCopyright 2016 Sam Saint-Pettersen.");
println!("Released under the MIT/X11 License.");
println!("\n{} -f|--file <input> [-c|--condition <condition(s)>] -o|--out <output>", program);
println!("[-l|--verbose][-h|--help | -v|--version]");
println!("\n-f|--file: File to run preprocessing on.");
println!("-c|--conditon: Comma delimited list of conditon(s) to apply.");
println!("-o|--out: File to output preprocessed LoC to.");
println!("-l|--verbose: Display message to console on process.");
println!("-h|--help: Display this help information and exit.");
println!("-v|--version: Display program version and exit.");
exit(exit_code);
}
fn main() {
let cli = CliOptions::new("fm");
let program = cli.get_program();
let mut input = String::new();
let mut output = String::new();
let mut conditions = String::new();
let mut verbose = false;
if cli.get_num() > 1 {
for (i, a) in cli.get_args().iter().enumerate() {
match a.trim() {
"-h" | "--help" => display_usage(&program, 0),
"-v" | "--version" => display_version(),
"-f" | "--file" => input = cli.next_argument(i),
"-c" | "--condition" => conditions = cli.next_argument(i),
"-o" | "--out" => output = cli.next_argument(i),
"-l" | "--verbose" => verbose = true,
_ => continue,
}
}
if input.is_empty() {
display_error(&program, "No input specified");
}
if output.is_empty() {
display_error(&program, "No output specified");
}
preprocess(&input, &output, &conditions, verbose);
}
else {
display_error(&program, "No options specified");
}
} | }
if !in_pp { | random_line_split |
main.rs | /*
Full Monkey.
Generic preprocessor tool.
Copyright 2016 Sam Saint-Pettersen.
Released under the MIT/X11 License.
*/
extern crate clioptions;
extern crate regex;
use clioptions::CliOptions;
use regex::Regex;
use std::io::{BufRead, BufReader, Write};
use std::fs::File;
use std::process::exit;
fn preprocess(input: &str, output: &str, conditions: &str, verbose: bool) {
let mut loc: Vec<String> = Vec::new();
let mut preprocessed: Vec<String> = Vec::new();
let mut cond = String::new();
let mut set_conds: Vec<String> = Vec::new();
let mut prefixed: Vec<String> = Vec::new();
let mut prefixes: Vec<String> = Vec::new();
let mut in_pp = false;
let conditions = conditions.split(",");
for sc in conditions {
set_conds.push(sc.to_string());
}
let f = File::open(input).unwrap();
let file = BufReader::new(&f);
for l in file.lines() {
let l = l.unwrap();
// Process prefix...
let mut p = Regex::new("#prefix (.*) with (.*)").unwrap();
if p.is_match(&l) {
for cap in p.captures_iter(&l) {
prefixed.push(cap.at(1).unwrap().to_string());
prefixes.push(cap.at(2).unwrap().to_string());
}
continue;
}
// Process conditional (if/else/elseif)...
p = Regex::new("#[else]*[if]* (.*)").unwrap();
if p.is_match(&l) |
// Process end block...
p = Regex::new("#[fi|endif]").unwrap();
if p.is_match(&l) {
in_pp = false;
continue;
}
// Push relevant LoC to vector...
for sc in set_conds.clone() {
if in_pp && cond == sc {
preprocessed.push(l.to_string());
}
}
if !in_pp {
preprocessed.push(l.to_string());
continue;
}
}
// Do any alterations:
for line in preprocessed {
let mut fl = line;
for (i, p) in prefixed.iter().enumerate() {
let r = Regex::new(®ex::quote(&p)).unwrap();
let repl = format!("{}{}", &prefixes[i], &p);
fl = r.replace_all(&fl, &repl[..]);
}
loc.push(fl);
}
loc.push(String::new());
if verbose {
println!("Preprocessing {} --> {}", input, output);
}
let mut w = File::create(output).unwrap();
let _ = w.write_all(loc.join("\n").as_bytes());
}
fn display_version() {
println!("Full Monkey v. 0.1");
println!(r" __");
println!(r"w c(..)o (");
println!(r" \__(-) __)");
println!(r" /\ (");
println!(r" /(_)___)");
println!(r" w /|");
println!(r" | \");
println!(r" m m");
println!("\nMonkey appears courtesy of ejm97:");
println!("http://www.ascii-art.de/ascii/mno/monkey.txt");
exit(0);
}
fn display_error(program: &str, error: &str) {
println!("Error: {}.", error);
display_usage(&program, -1);
}
fn display_usage(program: &str, exit_code: i32) {
println!("\nFull Monkey.");
println!("Generic preprocessor tool.");
println!("\nCopyright 2016 Sam Saint-Pettersen.");
println!("Released under the MIT/X11 License.");
println!("\n{} -f|--file <input> [-c|--condition <condition(s)>] -o|--out <output>", program);
println!("[-l|--verbose][-h|--help | -v|--version]");
println!("\n-f|--file: File to run preprocessing on.");
println!("-c|--conditon: Comma delimited list of conditon(s) to apply.");
println!("-o|--out: File to output preprocessed LoC to.");
println!("-l|--verbose: Display message to console on process.");
println!("-h|--help: Display this help information and exit.");
println!("-v|--version: Display program version and exit.");
exit(exit_code);
}
fn main() {
let cli = CliOptions::new("fm");
let program = cli.get_program();
let mut input = String::new();
let mut output = String::new();
let mut conditions = String::new();
let mut verbose = false;
if cli.get_num() > 1 {
for (i, a) in cli.get_args().iter().enumerate() {
match a.trim() {
"-h" | "--help" => display_usage(&program, 0),
"-v" | "--version" => display_version(),
"-f" | "--file" => input = cli.next_argument(i),
"-c" | "--condition" => conditions = cli.next_argument(i),
"-o" | "--out" => output = cli.next_argument(i),
"-l" | "--verbose" => verbose = true,
_ => continue,
}
}
if input.is_empty() {
display_error(&program, "No input specified");
}
if output.is_empty() {
display_error(&program, "No output specified");
}
preprocess(&input, &output, &conditions, verbose);
}
else {
display_error(&program, "No options specified");
}
}
| {
for cap in p.captures_iter(&l) {
cond = cap.at(1).unwrap().to_string();
in_pp = true;
}
continue;
} | conditional_block |
get_room_information.rs | //! `GET /_matrix/federation/*/query/directory`
//!
//! Endpoint to query room information with a room alias.
pub mod v1 {
//! `/v1/` ([spec])
//!
//! [spec]: https://spec.matrix.org/v1.2/server-server-api/#get_matrixfederationv1querydirectory
use ruma_common::{api::ruma_api, RoomAliasId, RoomId, ServerName};
ruma_api! {
metadata: {
description: "Get mapped room ID and resident homeservers for a given room alias.",
name: "get_room_information",
method: GET,
stable_path: "/_matrix/federation/v1/query/directory",
rate_limited: false,
authentication: ServerSignatures,
added: 1.0,
}
request: {
/// Room alias to query.
#[ruma_api(query)]
pub room_alias: &'a RoomAliasId,
}
response: {
/// Room ID mapped to queried alias.
pub room_id: Box<RoomId>,
/// An array of server names that are likely to hold the given room.
pub servers: Vec<Box<ServerName>>,
}
}
impl<'a> Request<'a> {
/// Creates a new `Request` with the given room alias ID.
pub fn new(room_alias: &'a RoomAliasId) -> Self {
Self { room_alias }
}
}
impl Response {
/// Creates a new `Response` with the given room IDs and servers.
pub fn new(room_id: Box<RoomId>, servers: Vec<Box<ServerName>>) -> Self |
}
}
| {
Self { room_id, servers }
} | identifier_body |
get_room_information.rs | //! `GET /_matrix/federation/*/query/directory`
//!
//! Endpoint to query room information with a room alias.
pub mod v1 {
//! `/v1/` ([spec])
//!
//! [spec]: https://spec.matrix.org/v1.2/server-server-api/#get_matrixfederationv1querydirectory
use ruma_common::{api::ruma_api, RoomAliasId, RoomId, ServerName};
ruma_api! {
metadata: {
description: "Get mapped room ID and resident homeservers for a given room alias.",
name: "get_room_information",
method: GET,
stable_path: "/_matrix/federation/v1/query/directory",
rate_limited: false,
authentication: ServerSignatures,
added: 1.0,
}
request: {
/// Room alias to query.
#[ruma_api(query)]
pub room_alias: &'a RoomAliasId,
}
response: {
/// Room ID mapped to queried alias.
pub room_id: Box<RoomId>,
/// An array of server names that are likely to hold the given room.
pub servers: Vec<Box<ServerName>>,
}
}
impl<'a> Request<'a> {
/// Creates a new `Request` with the given room alias ID.
pub fn new(room_alias: &'a RoomAliasId) -> Self {
Self { room_alias }
}
}
impl Response {
/// Creates a new `Response` with the given room IDs and servers.
pub fn | (room_id: Box<RoomId>, servers: Vec<Box<ServerName>>) -> Self {
Self { room_id, servers }
}
}
}
| new | identifier_name |
get_room_information.rs | //! `GET /_matrix/federation/*/query/directory`
//!
//! Endpoint to query room information with a room alias.
pub mod v1 {
//! `/v1/` ([spec])
//!
//! [spec]: https://spec.matrix.org/v1.2/server-server-api/#get_matrixfederationv1querydirectory
use ruma_common::{api::ruma_api, RoomAliasId, RoomId, ServerName};
ruma_api! {
metadata: {
description: "Get mapped room ID and resident homeservers for a given room alias.",
name: "get_room_information",
method: GET,
stable_path: "/_matrix/federation/v1/query/directory",
rate_limited: false,
authentication: ServerSignatures,
added: 1.0,
}
request: {
/// Room alias to query.
#[ruma_api(query)]
pub room_alias: &'a RoomAliasId,
}
response: {
/// Room ID mapped to queried alias.
pub room_id: Box<RoomId>,
/// An array of server names that are likely to hold the given room. | impl<'a> Request<'a> {
/// Creates a new `Request` with the given room alias ID.
pub fn new(room_alias: &'a RoomAliasId) -> Self {
Self { room_alias }
}
}
impl Response {
/// Creates a new `Response` with the given room IDs and servers.
pub fn new(room_id: Box<RoomId>, servers: Vec<Box<ServerName>>) -> Self {
Self { room_id, servers }
}
}
} | pub servers: Vec<Box<ServerName>>,
}
}
| random_line_split |
lzw.py | #!/usr/bin/env python
import sys
stderr = sys.stderr
## LZWDecoder
##
class LZWDecoder(object):
debug = 0
def __init__(self, fp):
self.fp = fp
self.buff = 0
self.bpos = 8
self.nbits = 9
self.table = None
self.prevbuf = None
return
def readbits(self, bits):
v = 0
while 1:
# the number of remaining bits we can get from the current buffer.
r = 8-self.bpos
if bits <= r:
# |-----8-bits-----|
# |-bpos-|-bits-| |
# | |----r----|
v = (v<<bits) | ((self.buff>>(r-bits)) & ((1<<bits)-1))
self.bpos += bits
break
else:
# |-----8-bits-----|
# |-bpos-|---bits----...
# | |----r----|
v = (v<<r) | (self.buff & ((1<<r)-1))
bits -= r
x = self.fp.read(1)
if not x: raise EOFError
self.buff = ord(x)
self.bpos = 0
return v
def feed(self, code):
x = ''
if code == 256:
self.table = [ chr(c) for c in xrange(256) ] # 0-255
self.table.append(None) # 256
self.table.append(None) # 257
self.prevbuf = ''
self.nbits = 9
elif code == 257:
pass
elif not self.prevbuf:
x = self.prevbuf = self.table[code]
else:
if code < len(self.table):
x = self.table[code]
self.table.append(self.prevbuf+x[0])
else:
self.table.append(self.prevbuf+self.prevbuf[0])
x = self.table[code]
l = len(self.table)
if l == 511:
self.nbits = 10
elif l == 1023:
self.nbits = 11
elif l == 2047:
self.nbits = 12
self.prevbuf = x
return x
def | (self):
while 1:
try:
code = self.readbits(self.nbits)
except EOFError:
break
x = self.feed(code)
yield x
if self.debug:
print >>stderr, ('nbits=%d, code=%d, output=%r, table=%r' %
(self.nbits, code, x, self.table[258:]))
return
def main(argv):
import StringIO
input = '\x80\x0b\x60\x50\x22\x0c\x0c\x85\x01'
fp = StringIO.StringIO(input)
expected = '\x2d\x2d\x2d\x2d\x2d\x41\x2d\x2d\x2d\x42'
LZWDecoder.debug = 1
output = ''.join(LZWDecoder(fp).run())
print (input, expected, output)
print output == expected
return 0
if __name__ == '__main__': sys.exit(main(sys.argv))
| run | identifier_name |
lzw.py | #!/usr/bin/env python
import sys
stderr = sys.stderr
## LZWDecoder
##
class LZWDecoder(object):
debug = 0
def __init__(self, fp):
self.fp = fp
self.buff = 0
self.bpos = 8
self.nbits = 9
self.table = None
self.prevbuf = None
return
def readbits(self, bits):
v = 0
while 1:
# the number of remaining bits we can get from the current buffer.
r = 8-self.bpos
if bits <= r:
# |-----8-bits-----|
# |-bpos-|-bits-| |
# | |----r----|
v = (v<<bits) | ((self.buff>>(r-bits)) & ((1<<bits)-1))
self.bpos += bits
break
else:
# |-----8-bits-----|
# |-bpos-|---bits----...
# | |----r----|
v = (v<<r) | (self.buff & ((1<<r)-1))
bits -= r
x = self.fp.read(1)
if not x: raise EOFError
self.buff = ord(x)
self.bpos = 0
return v
def feed(self, code):
x = ''
if code == 256:
self.table = [ chr(c) for c in xrange(256) ] # 0-255
self.table.append(None) # 256
self.table.append(None) # 257
self.prevbuf = ''
self.nbits = 9
elif code == 257:
pass
elif not self.prevbuf:
x = self.prevbuf = self.table[code]
else:
if code < len(self.table):
x = self.table[code]
self.table.append(self.prevbuf+x[0])
else:
self.table.append(self.prevbuf+self.prevbuf[0])
x = self.table[code]
l = len(self.table)
if l == 511:
self.nbits = 10
elif l == 1023:
self.nbits = 11
elif l == 2047:
self.nbits = 12
self.prevbuf = x
return x
def run(self):
|
def main(argv):
import StringIO
input = '\x80\x0b\x60\x50\x22\x0c\x0c\x85\x01'
fp = StringIO.StringIO(input)
expected = '\x2d\x2d\x2d\x2d\x2d\x41\x2d\x2d\x2d\x42'
LZWDecoder.debug = 1
output = ''.join(LZWDecoder(fp).run())
print (input, expected, output)
print output == expected
return 0
if __name__ == '__main__': sys.exit(main(sys.argv))
| while 1:
try:
code = self.readbits(self.nbits)
except EOFError:
break
x = self.feed(code)
yield x
if self.debug:
print >>stderr, ('nbits=%d, code=%d, output=%r, table=%r' %
(self.nbits, code, x, self.table[258:]))
return | identifier_body |
lzw.py | #!/usr/bin/env python
import sys
stderr = sys.stderr
## LZWDecoder
##
class LZWDecoder(object):
debug = 0
def __init__(self, fp):
self.fp = fp
self.buff = 0
self.bpos = 8
self.nbits = 9
self.table = None
self.prevbuf = None
return
def readbits(self, bits):
v = 0
while 1:
# the number of remaining bits we can get from the current buffer.
r = 8-self.bpos
if bits <= r:
# |-----8-bits-----|
# |-bpos-|-bits-| |
# | |----r----|
v = (v<<bits) | ((self.buff>>(r-bits)) & ((1<<bits)-1))
self.bpos += bits
break
else:
# |-----8-bits-----|
# |-bpos-|---bits----...
# | |----r----|
v = (v<<r) | (self.buff & ((1<<r)-1))
bits -= r
x = self.fp.read(1)
if not x: raise EOFError
self.buff = ord(x)
self.bpos = 0
return v
def feed(self, code):
x = ''
if code == 256:
self.table = [ chr(c) for c in xrange(256) ] # 0-255
self.table.append(None) # 256
self.table.append(None) # 257
self.prevbuf = ''
self.nbits = 9
elif code == 257:
pass | elif not self.prevbuf:
x = self.prevbuf = self.table[code]
else:
if code < len(self.table):
x = self.table[code]
self.table.append(self.prevbuf+x[0])
else:
self.table.append(self.prevbuf+self.prevbuf[0])
x = self.table[code]
l = len(self.table)
if l == 511:
self.nbits = 10
elif l == 1023:
self.nbits = 11
elif l == 2047:
self.nbits = 12
self.prevbuf = x
return x
def run(self):
while 1:
try:
code = self.readbits(self.nbits)
except EOFError:
break
x = self.feed(code)
yield x
if self.debug:
print >>stderr, ('nbits=%d, code=%d, output=%r, table=%r' %
(self.nbits, code, x, self.table[258:]))
return
def main(argv):
import StringIO
input = '\x80\x0b\x60\x50\x22\x0c\x0c\x85\x01'
fp = StringIO.StringIO(input)
expected = '\x2d\x2d\x2d\x2d\x2d\x41\x2d\x2d\x2d\x42'
LZWDecoder.debug = 1
output = ''.join(LZWDecoder(fp).run())
print (input, expected, output)
print output == expected
return 0
if __name__ == '__main__': sys.exit(main(sys.argv)) | random_line_split | |
lzw.py | #!/usr/bin/env python
import sys
stderr = sys.stderr
## LZWDecoder
##
class LZWDecoder(object):
debug = 0
def __init__(self, fp):
self.fp = fp
self.buff = 0
self.bpos = 8
self.nbits = 9
self.table = None
self.prevbuf = None
return
def readbits(self, bits):
v = 0
while 1:
# the number of remaining bits we can get from the current buffer.
r = 8-self.bpos
if bits <= r:
# |-----8-bits-----|
# |-bpos-|-bits-| |
# | |----r----|
v = (v<<bits) | ((self.buff>>(r-bits)) & ((1<<bits)-1))
self.bpos += bits
break
else:
# |-----8-bits-----|
# |-bpos-|---bits----...
# | |----r----|
v = (v<<r) | (self.buff & ((1<<r)-1))
bits -= r
x = self.fp.read(1)
if not x: raise EOFError
self.buff = ord(x)
self.bpos = 0
return v
def feed(self, code):
x = ''
if code == 256:
self.table = [ chr(c) for c in xrange(256) ] # 0-255
self.table.append(None) # 256
self.table.append(None) # 257
self.prevbuf = ''
self.nbits = 9
elif code == 257:
pass
elif not self.prevbuf:
x = self.prevbuf = self.table[code]
else:
if code < len(self.table):
x = self.table[code]
self.table.append(self.prevbuf+x[0])
else:
self.table.append(self.prevbuf+self.prevbuf[0])
x = self.table[code]
l = len(self.table)
if l == 511:
self.nbits = 10
elif l == 1023:
self.nbits = 11
elif l == 2047:
self.nbits = 12
self.prevbuf = x
return x
def run(self):
while 1:
try:
code = self.readbits(self.nbits)
except EOFError:
break
x = self.feed(code)
yield x
if self.debug:
|
return
def main(argv):
import StringIO
input = '\x80\x0b\x60\x50\x22\x0c\x0c\x85\x01'
fp = StringIO.StringIO(input)
expected = '\x2d\x2d\x2d\x2d\x2d\x41\x2d\x2d\x2d\x42'
LZWDecoder.debug = 1
output = ''.join(LZWDecoder(fp).run())
print (input, expected, output)
print output == expected
return 0
if __name__ == '__main__': sys.exit(main(sys.argv))
| print >>stderr, ('nbits=%d, code=%d, output=%r, table=%r' %
(self.nbits, code, x, self.table[258:])) | conditional_block |
code_from_book.py | # Python Code From Book
# This file consists of code snippets only
# It is not intended to be run as a script
raise SystemExit
####################################################################
# 3. Thinking in Binary
####################################################################
import magic
print magic.from_file("my_image.jpg")
# JPEG image data, Exif standard: [TIFF image data, big-endian,
# direntries=16, height=3264, bps=0, PhotometricIntepretation=RGB],
# baseline, precision 8, 2378x2379, frames 3
if magic.from_file("upload.jpg", mime=True) == "image/jpeg":
continue_uploading("upload.jpg")
else:
alert("Sorry! This file type is not allowed")
import imghdr
print imghdr.what("path/to/my/file.ext")
import binascii
ย
def spoof_file(file, magic_number):
magic_number = binascii.unhexlify(magic_number)
with open(file, "r+b") as f:
old = f.read()
f.seek(0)
f.write(magic_number + old)
ย
def to_ascii_bytes(string):
return " ".join(format(ord(char), '08b') for char in string)
string = "my ascii string"
"".join(hex(ord(char))[2:] for char in string)
# '6d7920617363696920737472696e67'
hex_string = "6d7920617363696920737472696e67"
hex_string.decode("hex")
# 'my ascii string'
"".join(chr(int(hex_string[i:i+2], 16)) for i in range(0, len(hex_string), 2))
# 'my ascii string'
# adapted from https://code.activestate.com/recipes/142812-hex-dumper/
def hexdump(string, length=8):
result = []
digits = 4 if isinstance(string, unicode) else 2
for i in xrange(0, len(string), length):
s | return '\n'.join(result)
with open("/path/to/my_file.ext", "r") as f:
print hexdump(f.read())
import struct
num = 0x103e4
struct.pack("I", 0x103e4)
# '\xe4\x03\x01\x00'
string = '\xe4\x03\x01\x00'
struct.unpack("i", string)
# (66532,)
bytes = '\x01\xc2'
struct.pack("<h", struct.unpack(">h", bytes)[0])
# '\xc2\x01'
import base64
base64.b64encode('encodings are fun...')
# 'ZW5jb2RpbmdzIGFyZSBmdW4uLi4='
base64.b64decode(_)
# 'encodings are fun...'
string = "hello\x00"
binary_string = ' '.join('{:08b}'.format(ord(char)) for char in string)
" ".join(binary_string[i:i+6] for i in range(0, len(binary_string), 6))
# '011010 000110 010101 101100 011011 000110 111100 000000'
bin_string = '011010 000110 010101 101100 011011 000110 111100 000000'
[int(b, 2) for b in bin_string.split()]
# [26, 6, 21, 44, 27, 6, 60, 0]
u'โ \u2020'.encode('utf8')
# '\xe2\x97\x91 \xe2\x80\xa0'
'\xe2\x97\x91 \xe2\x80\xa0'.decode('utf8')
# u'\u25d1 \u2020'
unicode('\xe2\x97\x91 \xe2\x80\xa0', encoding='utf8')
# u'\u25d1 \u2020'
utf8_string = 'ร
รชรญรฒรผ'
utf8_string
# '\xc3\x85\xc3\xaa\xc3\xad\xc3\xb2\xc3\xbc'
unicode_string = utf8_string.decode('utf8')
unicode_string
# u'\xc5\xea\xed\xf2\xfc'
unicode_string.encode('mac roman')
# '\x81\x90\x92\x98\x9f'
'ร
รชรญรฒรผ'.decode('utf8').encode('ascii')
# Traceback (most recent call last):
# ย File "<stdin>", line 1, in <module>
# UnicodeEncodeError: 'ascii' codec can't encode characters in position 0-4: ordinal not in range(128)
file = """ๆฝๆฅชๆ
ขๆซๆค โณๆกดโฅๆ
งๆฒๆฌโคๆด็ธ็ ๆ
จโด็ฉ็ ๆจ็ ็ฅๆฑตโดๆฏ็ ็กฅโดๆขๆนฉโงๆคๆฝฃๆคโค็ตๆนฉโงๆนก็ ๆฅฎ็ฎๆนฅๆคโคๆกฃ
็กๆกๆดโฒๆนฅๆฝฃๆฅคๆฎๆฅทๆกดๆ ๆตฏๆฑฐ็ฅๆฑฅโนๆนตๆฒๆ
ฌๆดโคๆนฏ็ฅๆฏๆดโฎ็ฆๆตฏๆ ๆ ๆฉๆฆๆฒ็ฎ็ ๆฅฒๆฅดๆฎ็ ็นๆดโนญโงโ ๆ
ๆซโฎ
็ฆๆตฏๆ โนฎๆฅทๆฅซๆฐๆฅคโนก็ฏโฅง"""
print file.decode('utf8').encode('utf16')
# ??Mojibake is the garbled text that is the result of text being decoded using an
# unintended character encoding with completely unrelated ones, often from a
# different writing system.' (Taken from en.wikipedia.org)
import ftfy
ftfy.fix_text(u"รขโฌลMojibakeรขโฌล can be fixed.")
# u'"Mojibake" can be fixed.'
bin(0b1010 & 0b1111110111)
# '0b10'
bin(0b1010 | 0b0110)
# '0b1110'
bin(0b10111 | 0b01000)
# '0b11111'
bin(0b100 ^ 0b110)
# '0b10'
bin(-0b1010 >> 0b10)
# '-0b11'
x = 0b1111
y = 0b1010
bin(int("{:b}{:b}".format(x, y), 2))
# '0b11111010'
bin(x << 4 | y)
# '0b11111010'
####################################################################
# 4. Cryptography
####################################################################
import random
import string
ย
r = random.SystemRandom()
# Get a random integer between 0 and 20
r.randint(0, 20)
# 5
ย
# Get a random number between 0 and 1
r.random()
# 0.8282475835972263
ย
# Generate a random 40-bit number
r.getrandbits(40)
# 595477188771L
# Choose a random item from a string or list
chars = string.printable
r.choice(chars)
# 'e'
ย # Randomize the order of a sequence
seq = ['a', 'b', 'c', 'd', 'e']
r.shuffle(seq)
print seq
# ['c','d', 'a', 'e', 'b']
"ALLIGATOR".encode('rot13')
# 'NYYVTNGBE'
"NYYVTNGBE".encode('rot13')
# 'ALLIGATOR'
plaintext = "A secret-ish message!"
"".join(chr((ord(c) + 20) % 256) for c in plaintext)
# 'U4\x87yw\x86y\x88A}\x87|4\x81y\x87\x87u{y5'
ciphertext = 'U4\x87yw\x86y\x88A}\x87|4\x81y\x87\x87u{y5'
"".join(chr((ord(c) - 20) % 256) for c in ciphertext)
# 'A secret-ish message!'
plaintext = 0b110100001101001
one_time_pad = 0b110000011100001
bin(plaintext ^ one_time_pad)
# '0b100010001000'
decrypted = 0b100010001000 ^ one_time_pad
format(decrypted, 'x').decode('hex')
# 'hi'
import os
import binascii
# ASCII-encoded plaintext
plaintext = "this is a secret message"
plaintext_bits = int(binascii.hexlify(plaintext), 16)
print "plaintext (ascii):", plaintext
print "plaintext (hex):", plaintext_bits
# Generate the one-time pad
onetime_pad = int(binascii.hexlify(os.urandom(len(plaintext))), 16)
print "one-time pad: (hex):", onetime_pad
# Encrypt plaintext using XOR operation with one-time pad
ciphertext_bits = plaintext_bits ^ onetime_pad
print "encrypted text (hex):", ciphertext_bits
# Decrypt using XOR operation with one-time pad
decrypted_text = ciphertext_bits ^ onetime_pad
decrypted_text = binascii.unhexlify(hex(decrypted_text)[2:-1])
print "decrypted text (ascii):", decrypted_text
import random
import binascii
p1 = "this is the part where you run away"
p2 = "from bad cryptography practices."
# pad plaintexts with spaces to ensure equal length
p1 = p1.ljust(len(p2))
p2 = p2.ljust(len(p1))
p1 = int(binascii.hexlify(p1), 16)
p2 = int(binascii.hexlify(p2), 16)
# get random one-time pad
otp = random.SystemRandom().getrandbits(p1.bit_length())
# encrypt
c1 = p1 ^ otp
c2 = p2 ^ otp # otp reuse...not good!
print "c1 ^ c2 == p1 ^ p2 ?", c1 ^ c2 == p1 ^ p2
print "c1 ^ c2 =", hex(c1 ^ c2)
# the crib
crib = " the "
crib = int(binascii.hexlify(crib), 16)
xored = c1 ^ c2
print "crib =", hex(crib)
cbl = crib.bit_length()
xbl = xored.bit_length()
print
mask = (2**(cbl + 1) - 1)
fill = len(str(xbl / 8))
# crib dragging
for s in range(0, xbl - cbl + 8, 8):
xor = (xored ^ (crib << s)) & (mask << s)
out = binascii.unhexlify(hex(xor)[2:-1])
print "{:>{}} {}".format(s/8, fill, out)
from cryptography.fernet import Fernet
key = Fernet.generate_key()
f = Fernet(key)
ciphertext = f.encrypt("this is my plaintext")
decrypted = f.decrypt(ciphertext)
print decrypted
# this is my plaintext
import os
from cryptography.hazmat.primitives import padding
from cryptography.hazmat.primitives.ciphers import Cipher, algorithms, modes
from cryptography.hazmat.backends import default_backend
pt = "my plaintext"
backend = default_backend()
key = os.urandom(32)
iv = os.urandom(16)
padder = padding.PKCS7(128).padder()
pt = padder.update(pt) + padder.finalize()
cipher = Cipher(algorithms.AES(key), modes.CBC(iv), backend=backend)
encryptor = cipher.encryptor()
ct = encryptor.update(pt) + encryptor.finalize()
decryptor = cipher.decryptor()
out = decryptor.update(ct) + decryptor.finalize()
unpadder = padding.PKCS7(128).unpadder()
out = unpadder.update(out) + unpadder.finalize()
print out
import hashlib
hashlib.md5("hash me please").hexdigest()
# '760d92b6a6f974ae11904cd0a6fc2e90'
hashlib.sha1("hash me please").hexdigest()
# '1a58c9b3d138a45519518ee42e634600d1b52153'
import os
from cryptography.hazmat.primitives.kdf.scrypt import Scrypt
from cryptography.hazmat.backends import default_backend
backend = default_backend()
salt = os.urandom(16)
kdf = Scrypt(salt=salt, length=64, n=2**14, r=8, p=1, backend=backend)
key = kdf.derive("your favorite password")
key
import hmac
import hashlib
secret_key = "my secret key"
ciphertext = "my ciphertext"
# generate HMAC
h = hmac.new(key=secret_key, msg=ciphertext, digestmod=hashlib.sha256)
print h.hexdigest()
# verify HMAC
hmac.compare_digest(h.hexdigest(), h.hexdigest())
p = 9576890767
q = 1299827
n = p * q
print n
# 12448301194997309
e = 65537
phi = (p - 1) * (q - 1)
phi % e != 0
# True
import sympy
d = sympy.numbers.igcdex(e, phi)[0]
print d
# 1409376745910033
m = 12345
c = pow(m, e, n)
print c
# 3599057382134015
pow(c, d, n)
# 12345
m = 0
while pow(m, e, n) != c:
ย ย ย m += 1
print m
from cryptography.hazmat.backends import default_backend
from cryptography.hazmat.primitives.asymmetric import rsa
from cryptography.hazmat.primitives import serialization
private_key = rsa.generate_private_key(public_exponent=65537, key_size=2048, b
ackend=default_backend())
public_key = private_key.public_key()
private_pem = private_key.private_bytes(encoding=serialization.Encoding.PEM,
format=serialization.PrivateFormat.PKCS8,
encryption_algorithm=serialization.BestAvailableEncryption('your password here'))
public_pem = public_key.public_bytes(encoding=serialization.Encoding.PEM,
format=serialization.PublicFormat.SubjectPublicKeyInfo)
print public_pem
print private_pem
from cryptography.hazmat.primitives import hashes
from cryptography.hazmat.primitives.asymmetric import padding
import base64
with open("path/to/public_key.pem", "rb") as key_file:
public_key = serialization.load_pem_public_key(key_file.read(),
backend=default_backend())
message = "your secret message"
ciphertext = public_key.encrypt(message,
padding.OAEP(mgf=padding.MGF1(algorithm=hashes.SHA256()),
algorithm=hashes.SHA256(),
label=None))
b64_ciphertext = base64.urlsafe_b64encode(ciphertext)
print b64_ciphertext
plaintext = private_key.decrypt(ciphertext,
padding.OAEP(mgf=padding.MGF1(algorithm=hashes.SHA256()),
algorithm=hashes.SHA256(),
label=None))
print plaintext
from cryptography.hazmat.primitives import hashes
from cryptography.hazmat.primitives.asymmetric import padding
signer = private_key.signer(padding.PSS(mgf=padding.MGF1(hashes.SHA256()), salt_length=padding.PSS.MAX_LENGTH), hashes.SHA256())
message = "A message of arbitrary length"
signer.update(message)
signature = signer.finalize()
public_key = private_key.public_key()
verifier = public_key.verifier(signature, padding.PSS(mgf=padding.MGF1(hashes.SHA256()), salt_length=padding.PSS.MAX_LENGTH), hashes.SHA256())
verifier.update(message)
verifier.verify()
####################################################################
# 5. Networking
####################################################################
import requests
r = requests.get('https://www.google.com/imghp')
r.content[:200]
# View status code
r.status_code
# 200
ย
# View response header fields
r.headers
# {'Alt-Svc': 'quic=":443"; ma=2592000; v="36,35,34"',
# ย 'Cache-Control': 'private, max-age=0',
# ย 'Content-Encoding': 'gzip',
# ย 'Content-Type': 'text/html; charset=ISO-8859-1',
# 'Expires': '-1',
# ย 'P3P': 'CP="This is not a P3P policy! See https://www.google.com/support/accounts/answer/151657?hl=en for more info."',
# ย 'Server': 'gws',
# path=/; domain=.google.com; HttpOnly',
# ย 'Transfer-Encoding': 'chunked',
# ย 'X-Frame-Options': 'SAMEORIGIN',
# ย 'X-XSS-Protection': '1; mode=block'}
# Get content length in bytes
len(r.content)
# 10971
# Encoding
r.apparent_encoding
# 'ISO-8859-2'
# Time elapsed during request
r.elapsed
# datetime.timedelta(0, 0, 454447)
r.request.headers
# {'Accept': '*/*',
# ย 'Accept-Encoding': 'gzip, deflate',
# ย 'Connection': 'keep-alive',
# ย 'User-Agent': 'python-requests/2.12.4'}
custom_headers = {"user-agent": "Mozilla/5.0 (Macintosh; Intel Mac OS X 10_11_6) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/56.0.2924.87 Safari/537.36"}
r = requests.get("https://www.google.com/imghp", headers=custom_headers)
r.request.headers
# {'Accept': '*/*',
# ย 'Accept-Encoding': 'gzip, deflate',
# ย 'Connection': 'keep-alive',
# ย 'user-agent': 'Mozilla/5.0 (Macintosh; Intel Mac OS X 10_11_6) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/56.0.2924.87 Safari/537.36'}
import requests
import logging
import http.client as http_client
http_client.HTTPConnection.debuglevel = 1
logging.basicConfig()
logging.getLogger().setLevel(logging.DEBUG)
requests_log = logging.getLogger("requests.packages.urllib3")
requests_log.setLevel(logging.DEBUG)
requests_log.propagate = True
r = requests.get('https://www.google.com/')
# send: 'GET / HTTP/1.1\r\nHost: www.google.com\r\nConnection: keep-alive\r\nAccept-Encoding: gzip, deflate\r\nAccept: */*\r\nUser-Agent: python-requests/2.12.4\r\n\r\n'
# reply: 'HTTP/1.1 200 OK\r\n'
# header: Expires: -1
# header: Cache-Control: private, max-age=0
# header: Content-Type: text/html; charset=ISO-8859-1
# header: P3P: CP="This is not a P3P policy! See https://www.google.com/support/accounts/answer/151657?hl=en for more info."
# header: Content-Encoding: gzip
# header: Server: gws
# header: X-XSS-Protection: 1; mode=block
# header: X-Frame-Options: SAMEORIGIN
import urlparse
simple_url = "http://www.example.com/path/to/my/page"
parsed = urlparse.urlparse(simple_url)
parsed.scheme
parsed.hostname
parsed.path
url_with_query = "http://www.example.com/?page=1&key=Anvn4mo24"
query = urlparse.urlparse(url_with_query).query
urlparse.parse_qs(query)
# {'key': ['Anvn4mo24'], 'page': ['1']}
import urllib
url = 'https://www.example.com/%5EA-url-with-%-and-%5E?page=page+with%20spaces'
urllib.unquote(url)
# 'https://www.example.com/^A-url-with-%-and-^?page=page+with spaces'
chars = '!@#$%^%$#)'
urllib.quote(chars)
# '%21%40%23%24%25%5E%25%24%23%29'
urllib.unquote_plus(url)
# 'https://www.example.com/^A-url-with-%-and-^?page=page with spaces'
urllib.quote_plus('one two')
'one+two'
import requests
from bs4 import BeautifulSoup
r = requests.get("http://www.google.com")
soup = BeautifulSoup(r.content, "lxml")
soup.find_all('p')
soup.find_all('a')
# [<a class="gb1" href="http://www.google.com/imghp?hl=en&tab=wi">Images</a>,
# <a class="gb1" href="http://maps.google.com/maps?hl=en&tab=wl">Maps</a>,
# <a class="gb1" href="https://play.google.com/?hl=en&tab=w8">Play</a>,
# <a class="gb1" href="http://www.youtube.com/?tab=w1">YouTube</a>,
# <a class="gb1" href="http://news.google.com/nwshp?hl=en&tab=wn">News</a>,
# โฆ]
for link in soup.find_all('a'):
print link.text, link["href"]
# Images http://www.google.com/imghp?hl=en&tab=wi
# Maps http://maps.google.com/maps?hl=en&tab=wl
# Play https://play.google.com/?hl=en&tab=w8
# YouTube http://www.youtube.com/?tab=w1
import dryscrape
from bs4 import BeautifulSoup
session = dryscrape.Session()
session.visit("http://www.google.com")
r = session.body()
soup = BeautifulSoup(r, "lxml")
from selenium import webdriver
driver = webdriver.Chrome("/path/to/chromedriver")
driver.get("http://www.google.com")
html = driver.page_source
driver.save_screenshot("screenshot.png")
driver.quit()
import smtplib
server = smtplib.SMTP('localhost', port=1025)
server.set_debuglevel(True)
server.sendmail("me@localhost", "you@localhost", "This is an email message")
server.quit()
| = string[i:i + length]
hexa = "".join("{:0{}X}".format(ord(x), digits) for x in s)
text = "".join(x if 0x20 <= ord(x) < 0x7F else '.' for x in s)
result.append("{:04X}ย ย {:{}}ย ย {}".format(i, hexa, length * (digits + 1), text))
| conditional_block |
code_from_book.py | # Python Code From Book
# This file consists of code snippets only
# It is not intended to be run as a script
raise SystemExit
####################################################################
# 3. Thinking in Binary
####################################################################
import magic
print magic.from_file("my_image.jpg")
# JPEG image data, Exif standard: [TIFF image data, big-endian,
# direntries=16, height=3264, bps=0, PhotometricIntepretation=RGB],
# baseline, precision 8, 2378x2379, frames 3
if magic.from_file("upload.jpg", mime=True) == "image/jpeg":
continue_uploading("upload.jpg")
else:
alert("Sorry! This file type is not allowed")
import imghdr
print imghdr.what("path/to/my/file.ext")
import binascii
ย
def spoof_file(file, magic_number):
magic_number = binascii.unhexlify(magic_number)
with open(file, "r+b") as f:
old = f.read()
f.seek(0)
f.write(magic_number + old)
ย
def to_ascii_bytes(string):
return " ".join(format(ord(char), '08b') for char in string)
string = "my ascii string"
"".join(hex(ord(char))[2:] for char in string)
# '6d7920617363696920737472696e67'
hex_string = "6d7920617363696920737472696e67"
hex_string.decode("hex")
# 'my ascii string'
"".join(chr(int(hex_string[i:i+2], 16)) for i in range(0, len(hex_string), 2))
# 'my ascii string'
# adapted from https://code.activestate.com/recipes/142812-hex-dumper/
def hexdump(string, length=8):
re | th open("/path/to/my_file.ext", "r") as f:
print hexdump(f.read())
import struct
num = 0x103e4
struct.pack("I", 0x103e4)
# '\xe4\x03\x01\x00'
string = '\xe4\x03\x01\x00'
struct.unpack("i", string)
# (66532,)
bytes = '\x01\xc2'
struct.pack("<h", struct.unpack(">h", bytes)[0])
# '\xc2\x01'
import base64
base64.b64encode('encodings are fun...')
# 'ZW5jb2RpbmdzIGFyZSBmdW4uLi4='
base64.b64decode(_)
# 'encodings are fun...'
string = "hello\x00"
binary_string = ' '.join('{:08b}'.format(ord(char)) for char in string)
" ".join(binary_string[i:i+6] for i in range(0, len(binary_string), 6))
# '011010 000110 010101 101100 011011 000110 111100 000000'
bin_string = '011010 000110 010101 101100 011011 000110 111100 000000'
[int(b, 2) for b in bin_string.split()]
# [26, 6, 21, 44, 27, 6, 60, 0]
u'โ \u2020'.encode('utf8')
# '\xe2\x97\x91 \xe2\x80\xa0'
'\xe2\x97\x91 \xe2\x80\xa0'.decode('utf8')
# u'\u25d1 \u2020'
unicode('\xe2\x97\x91 \xe2\x80\xa0', encoding='utf8')
# u'\u25d1 \u2020'
utf8_string = 'ร
รชรญรฒรผ'
utf8_string
# '\xc3\x85\xc3\xaa\xc3\xad\xc3\xb2\xc3\xbc'
unicode_string = utf8_string.decode('utf8')
unicode_string
# u'\xc5\xea\xed\xf2\xfc'
unicode_string.encode('mac roman')
# '\x81\x90\x92\x98\x9f'
'ร
รชรญรฒรผ'.decode('utf8').encode('ascii')
# Traceback (most recent call last):
# ย File "<stdin>", line 1, in <module>
# UnicodeEncodeError: 'ascii' codec can't encode characters in position 0-4: ordinal not in range(128)
file = """ๆฝๆฅชๆ
ขๆซๆค โณๆกดโฅๆ
งๆฒๆฌโคๆด็ธ็ ๆ
จโด็ฉ็ ๆจ็ ็ฅๆฑตโดๆฏ็ ็กฅโดๆขๆนฉโงๆคๆฝฃๆคโค็ตๆนฉโงๆนก็ ๆฅฎ็ฎๆนฅๆคโคๆกฃ
็กๆกๆดโฒๆนฅๆฝฃๆฅคๆฎๆฅทๆกดๆ ๆตฏๆฑฐ็ฅๆฑฅโนๆนตๆฒๆ
ฌๆดโคๆนฏ็ฅๆฏๆดโฎ็ฆๆตฏๆ ๆ ๆฉๆฆๆฒ็ฎ็ ๆฅฒๆฅดๆฎ็ ็นๆดโนญโงโ ๆ
ๆซโฎ
็ฆๆตฏๆ โนฎๆฅทๆฅซๆฐๆฅคโนก็ฏโฅง"""
print file.decode('utf8').encode('utf16')
# ??Mojibake is the garbled text that is the result of text being decoded using an
# unintended character encoding with completely unrelated ones, often from a
# different writing system.' (Taken from en.wikipedia.org)
import ftfy
ftfy.fix_text(u"รขโฌลMojibakeรขโฌล can be fixed.")
# u'"Mojibake" can be fixed.'
bin(0b1010 & 0b1111110111)
# '0b10'
bin(0b1010 | 0b0110)
# '0b1110'
bin(0b10111 | 0b01000)
# '0b11111'
bin(0b100 ^ 0b110)
# '0b10'
bin(-0b1010 >> 0b10)
# '-0b11'
x = 0b1111
y = 0b1010
bin(int("{:b}{:b}".format(x, y), 2))
# '0b11111010'
bin(x << 4 | y)
# '0b11111010'
####################################################################
# 4. Cryptography
####################################################################
import random
import string
ย
r = random.SystemRandom()
# Get a random integer between 0 and 20
r.randint(0, 20)
# 5
ย
# Get a random number between 0 and 1
r.random()
# 0.8282475835972263
ย
# Generate a random 40-bit number
r.getrandbits(40)
# 595477188771L
# Choose a random item from a string or list
chars = string.printable
r.choice(chars)
# 'e'
ย # Randomize the order of a sequence
seq = ['a', 'b', 'c', 'd', 'e']
r.shuffle(seq)
print seq
# ['c','d', 'a', 'e', 'b']
"ALLIGATOR".encode('rot13')
# 'NYYVTNGBE'
"NYYVTNGBE".encode('rot13')
# 'ALLIGATOR'
plaintext = "A secret-ish message!"
"".join(chr((ord(c) + 20) % 256) for c in plaintext)
# 'U4\x87yw\x86y\x88A}\x87|4\x81y\x87\x87u{y5'
ciphertext = 'U4\x87yw\x86y\x88A}\x87|4\x81y\x87\x87u{y5'
"".join(chr((ord(c) - 20) % 256) for c in ciphertext)
# 'A secret-ish message!'
plaintext = 0b110100001101001
one_time_pad = 0b110000011100001
bin(plaintext ^ one_time_pad)
# '0b100010001000'
decrypted = 0b100010001000 ^ one_time_pad
format(decrypted, 'x').decode('hex')
# 'hi'
import os
import binascii
# ASCII-encoded plaintext
plaintext = "this is a secret message"
plaintext_bits = int(binascii.hexlify(plaintext), 16)
print "plaintext (ascii):", plaintext
print "plaintext (hex):", plaintext_bits
# Generate the one-time pad
onetime_pad = int(binascii.hexlify(os.urandom(len(plaintext))), 16)
print "one-time pad: (hex):", onetime_pad
# Encrypt plaintext using XOR operation with one-time pad
ciphertext_bits = plaintext_bits ^ onetime_pad
print "encrypted text (hex):", ciphertext_bits
# Decrypt using XOR operation with one-time pad
decrypted_text = ciphertext_bits ^ onetime_pad
decrypted_text = binascii.unhexlify(hex(decrypted_text)[2:-1])
print "decrypted text (ascii):", decrypted_text
import random
import binascii
p1 = "this is the part where you run away"
p2 = "from bad cryptography practices."
# pad plaintexts with spaces to ensure equal length
p1 = p1.ljust(len(p2))
p2 = p2.ljust(len(p1))
p1 = int(binascii.hexlify(p1), 16)
p2 = int(binascii.hexlify(p2), 16)
# get random one-time pad
otp = random.SystemRandom().getrandbits(p1.bit_length())
# encrypt
c1 = p1 ^ otp
c2 = p2 ^ otp # otp reuse...not good!
print "c1 ^ c2 == p1 ^ p2 ?", c1 ^ c2 == p1 ^ p2
print "c1 ^ c2 =", hex(c1 ^ c2)
# the crib
crib = " the "
crib = int(binascii.hexlify(crib), 16)
xored = c1 ^ c2
print "crib =", hex(crib)
cbl = crib.bit_length()
xbl = xored.bit_length()
print
mask = (2**(cbl + 1) - 1)
fill = len(str(xbl / 8))
# crib dragging
for s in range(0, xbl - cbl + 8, 8):
xor = (xored ^ (crib << s)) & (mask << s)
out = binascii.unhexlify(hex(xor)[2:-1])
print "{:>{}} {}".format(s/8, fill, out)
from cryptography.fernet import Fernet
key = Fernet.generate_key()
f = Fernet(key)
ciphertext = f.encrypt("this is my plaintext")
decrypted = f.decrypt(ciphertext)
print decrypted
# this is my plaintext
import os
from cryptography.hazmat.primitives import padding
from cryptography.hazmat.primitives.ciphers import Cipher, algorithms, modes
from cryptography.hazmat.backends import default_backend
pt = "my plaintext"
backend = default_backend()
key = os.urandom(32)
iv = os.urandom(16)
padder = padding.PKCS7(128).padder()
pt = padder.update(pt) + padder.finalize()
cipher = Cipher(algorithms.AES(key), modes.CBC(iv), backend=backend)
encryptor = cipher.encryptor()
ct = encryptor.update(pt) + encryptor.finalize()
decryptor = cipher.decryptor()
out = decryptor.update(ct) + decryptor.finalize()
unpadder = padding.PKCS7(128).unpadder()
out = unpadder.update(out) + unpadder.finalize()
print out
import hashlib
hashlib.md5("hash me please").hexdigest()
# '760d92b6a6f974ae11904cd0a6fc2e90'
hashlib.sha1("hash me please").hexdigest()
# '1a58c9b3d138a45519518ee42e634600d1b52153'
import os
from cryptography.hazmat.primitives.kdf.scrypt import Scrypt
from cryptography.hazmat.backends import default_backend
backend = default_backend()
salt = os.urandom(16)
kdf = Scrypt(salt=salt, length=64, n=2**14, r=8, p=1, backend=backend)
key = kdf.derive("your favorite password")
key
import hmac
import hashlib
secret_key = "my secret key"
ciphertext = "my ciphertext"
# generate HMAC
h = hmac.new(key=secret_key, msg=ciphertext, digestmod=hashlib.sha256)
print h.hexdigest()
# verify HMAC
hmac.compare_digest(h.hexdigest(), h.hexdigest())
p = 9576890767
q = 1299827
n = p * q
print n
# 12448301194997309
e = 65537
phi = (p - 1) * (q - 1)
phi % e != 0
# True
import sympy
d = sympy.numbers.igcdex(e, phi)[0]
print d
# 1409376745910033
m = 12345
c = pow(m, e, n)
print c
# 3599057382134015
pow(c, d, n)
# 12345
m = 0
while pow(m, e, n) != c:
ย ย ย m += 1
print m
from cryptography.hazmat.backends import default_backend
from cryptography.hazmat.primitives.asymmetric import rsa
from cryptography.hazmat.primitives import serialization
private_key = rsa.generate_private_key(public_exponent=65537, key_size=2048, b
ackend=default_backend())
public_key = private_key.public_key()
private_pem = private_key.private_bytes(encoding=serialization.Encoding.PEM,
format=serialization.PrivateFormat.PKCS8,
encryption_algorithm=serialization.BestAvailableEncryption('your password here'))
public_pem = public_key.public_bytes(encoding=serialization.Encoding.PEM,
format=serialization.PublicFormat.SubjectPublicKeyInfo)
print public_pem
print private_pem
from cryptography.hazmat.primitives import hashes
from cryptography.hazmat.primitives.asymmetric import padding
import base64
with open("path/to/public_key.pem", "rb") as key_file:
public_key = serialization.load_pem_public_key(key_file.read(),
backend=default_backend())
message = "your secret message"
ciphertext = public_key.encrypt(message,
padding.OAEP(mgf=padding.MGF1(algorithm=hashes.SHA256()),
algorithm=hashes.SHA256(),
label=None))
b64_ciphertext = base64.urlsafe_b64encode(ciphertext)
print b64_ciphertext
plaintext = private_key.decrypt(ciphertext,
padding.OAEP(mgf=padding.MGF1(algorithm=hashes.SHA256()),
algorithm=hashes.SHA256(),
label=None))
print plaintext
from cryptography.hazmat.primitives import hashes
from cryptography.hazmat.primitives.asymmetric import padding
signer = private_key.signer(padding.PSS(mgf=padding.MGF1(hashes.SHA256()), salt_length=padding.PSS.MAX_LENGTH), hashes.SHA256())
message = "A message of arbitrary length"
signer.update(message)
signature = signer.finalize()
public_key = private_key.public_key()
verifier = public_key.verifier(signature, padding.PSS(mgf=padding.MGF1(hashes.SHA256()), salt_length=padding.PSS.MAX_LENGTH), hashes.SHA256())
verifier.update(message)
verifier.verify()
####################################################################
# 5. Networking
####################################################################
import requests
r = requests.get('https://www.google.com/imghp')
r.content[:200]
# View status code
r.status_code
# 200
ย
# View response header fields
r.headers
# {'Alt-Svc': 'quic=":443"; ma=2592000; v="36,35,34"',
# ย 'Cache-Control': 'private, max-age=0',
# ย 'Content-Encoding': 'gzip',
# ย 'Content-Type': 'text/html; charset=ISO-8859-1',
# 'Expires': '-1',
# ย 'P3P': 'CP="This is not a P3P policy! See https://www.google.com/support/accounts/answer/151657?hl=en for more info."',
# ย 'Server': 'gws',
# path=/; domain=.google.com; HttpOnly',
# ย 'Transfer-Encoding': 'chunked',
# ย 'X-Frame-Options': 'SAMEORIGIN',
# ย 'X-XSS-Protection': '1; mode=block'}
# Get content length in bytes
len(r.content)
# 10971
# Encoding
r.apparent_encoding
# 'ISO-8859-2'
# Time elapsed during request
r.elapsed
# datetime.timedelta(0, 0, 454447)
r.request.headers
# {'Accept': '*/*',
# ย 'Accept-Encoding': 'gzip, deflate',
# ย 'Connection': 'keep-alive',
# ย 'User-Agent': 'python-requests/2.12.4'}
custom_headers = {"user-agent": "Mozilla/5.0 (Macintosh; Intel Mac OS X 10_11_6) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/56.0.2924.87 Safari/537.36"}
r = requests.get("https://www.google.com/imghp", headers=custom_headers)
r.request.headers
# {'Accept': '*/*',
# ย 'Accept-Encoding': 'gzip, deflate',
# ย 'Connection': 'keep-alive',
# ย 'user-agent': 'Mozilla/5.0 (Macintosh; Intel Mac OS X 10_11_6) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/56.0.2924.87 Safari/537.36'}
import requests
import logging
import http.client as http_client
http_client.HTTPConnection.debuglevel = 1
logging.basicConfig()
logging.getLogger().setLevel(logging.DEBUG)
requests_log = logging.getLogger("requests.packages.urllib3")
requests_log.setLevel(logging.DEBUG)
requests_log.propagate = True
r = requests.get('https://www.google.com/')
# send: 'GET / HTTP/1.1\r\nHost: www.google.com\r\nConnection: keep-alive\r\nAccept-Encoding: gzip, deflate\r\nAccept: */*\r\nUser-Agent: python-requests/2.12.4\r\n\r\n'
# reply: 'HTTP/1.1 200 OK\r\n'
# header: Expires: -1
# header: Cache-Control: private, max-age=0
# header: Content-Type: text/html; charset=ISO-8859-1
# header: P3P: CP="This is not a P3P policy! See https://www.google.com/support/accounts/answer/151657?hl=en for more info."
# header: Content-Encoding: gzip
# header: Server: gws
# header: X-XSS-Protection: 1; mode=block
# header: X-Frame-Options: SAMEORIGIN
import urlparse
simple_url = "http://www.example.com/path/to/my/page"
parsed = urlparse.urlparse(simple_url)
parsed.scheme
parsed.hostname
parsed.path
url_with_query = "http://www.example.com/?page=1&key=Anvn4mo24"
query = urlparse.urlparse(url_with_query).query
urlparse.parse_qs(query)
# {'key': ['Anvn4mo24'], 'page': ['1']}
import urllib
url = 'https://www.example.com/%5EA-url-with-%-and-%5E?page=page+with%20spaces'
urllib.unquote(url)
# 'https://www.example.com/^A-url-with-%-and-^?page=page+with spaces'
chars = '!@#$%^%$#)'
urllib.quote(chars)
# '%21%40%23%24%25%5E%25%24%23%29'
urllib.unquote_plus(url)
# 'https://www.example.com/^A-url-with-%-and-^?page=page with spaces'
urllib.quote_plus('one two')
'one+two'
import requests
from bs4 import BeautifulSoup
r = requests.get("http://www.google.com")
soup = BeautifulSoup(r.content, "lxml")
soup.find_all('p')
soup.find_all('a')
# [<a class="gb1" href="http://www.google.com/imghp?hl=en&tab=wi">Images</a>,
# <a class="gb1" href="http://maps.google.com/maps?hl=en&tab=wl">Maps</a>,
# <a class="gb1" href="https://play.google.com/?hl=en&tab=w8">Play</a>,
# <a class="gb1" href="http://www.youtube.com/?tab=w1">YouTube</a>,
# <a class="gb1" href="http://news.google.com/nwshp?hl=en&tab=wn">News</a>,
# โฆ]
for link in soup.find_all('a'):
print link.text, link["href"]
# Images http://www.google.com/imghp?hl=en&tab=wi
# Maps http://maps.google.com/maps?hl=en&tab=wl
# Play https://play.google.com/?hl=en&tab=w8
# YouTube http://www.youtube.com/?tab=w1
import dryscrape
from bs4 import BeautifulSoup
session = dryscrape.Session()
session.visit("http://www.google.com")
r = session.body()
soup = BeautifulSoup(r, "lxml")
from selenium import webdriver
driver = webdriver.Chrome("/path/to/chromedriver")
driver.get("http://www.google.com")
html = driver.page_source
driver.save_screenshot("screenshot.png")
driver.quit()
import smtplib
server = smtplib.SMTP('localhost', port=1025)
server.set_debuglevel(True)
server.sendmail("me@localhost", "you@localhost", "This is an email message")
server.quit()
| sult = []
digits = 4 if isinstance(string, unicode) else 2
for i in xrange(0, len(string), length):
s = string[i:i + length]
hexa = "".join("{:0{}X}".format(ord(x), digits) for x in s)
text = "".join(x if 0x20 <= ord(x) < 0x7F else '.' for x in s)
result.append("{:04X}ย ย {:{}}ย ย {}".format(i, hexa, length * (digits + 1), text))
return '\n'.join(result)
wi | identifier_body |
code_from_book.py | # Python Code From Book
# This file consists of code snippets only
# It is not intended to be run as a script
raise SystemExit
####################################################################
# 3. Thinking in Binary
####################################################################
import magic
print magic.from_file("my_image.jpg")
# JPEG image data, Exif standard: [TIFF image data, big-endian,
# direntries=16, height=3264, bps=0, PhotometricIntepretation=RGB],
# baseline, precision 8, 2378x2379, frames 3
if magic.from_file("upload.jpg", mime=True) == "image/jpeg":
continue_uploading("upload.jpg")
else:
alert("Sorry! This file type is not allowed")
import imghdr
print imghdr.what("path/to/my/file.ext")
import binascii
ย
def spoof_file(file, magic_number):
magic_number = binascii.unhexlify(magic_number)
with open(file, "r+b") as f:
old = f.read()
f.seek(0)
f.write(magic_number + old)
ย
def to_ascii_bytes(string):
return " ".join(format(ord(char), '08b') for char in string)
string = "my ascii string"
"".join(hex(ord(char))[2:] for char in string)
# '6d7920617363696920737472696e67'
hex_string = "6d7920617363696920737472696e67"
hex_string.decode("hex")
# 'my ascii string'
"".join(chr(int(hex_string[i:i+2], 16)) for i in range(0, len(hex_string), 2))
# 'my ascii string'
# adapted from https://code.activestate.com/recipes/142812-hex-dumper/
def hexdump(string, length=8):
result = []
digits = 4 if isinstance(string, unicode) else 2
for i in xrange(0, len(string), length):
s = string[i:i + length]
hexa = "".join("{:0{}X}".format(ord(x), digits) for x in s)
text = "".join(x if 0x20 <= ord(x) < 0x7F else '.' for x in s)
result.append("{:04X}ย ย {:{}}ย ย {}".format(i, hexa, length * (digits + 1), text))
return '\n'.join(result)
with open("/path/to/my_file.ext", "r") as f:
print hexdump(f.read())
import struct
num = 0x103e4
struct.pack("I", 0x103e4)
# '\xe4\x03\x01\x00'
string = '\xe4\x03\x01\x00'
struct.unpack("i", string)
# (66532,)
bytes = '\x01\xc2'
struct.pack("<h", struct.unpack(">h", bytes)[0])
# '\xc2\x01'
import base64
base64.b64encode('encodings are fun...')
# 'ZW5jb2RpbmdzIGFyZSBmdW4uLi4='
base64.b64decode(_)
# 'encodings are fun...'
string = "hello\x00"
binary_string = ' '.join('{:08b}'.format(ord(char)) for char in string)
" ".join(binary_string[i:i+6] for i in range(0, len(binary_string), 6))
# '011010 000110 010101 101100 011011 000110 111100 000000'
bin_string = '011010 000110 010101 101100 011011 000110 111100 000000'
[int(b, 2) for b in bin_string.split()]
# [26, 6, 21, 44, 27, 6, 60, 0]
u'โ \u2020'.encode('utf8')
# '\xe2\x97\x91 \xe2\x80\xa0'
'\xe2\x97\x91 \xe2\x80\xa0'.decode('utf8')
# u'\u25d1 \u2020'
unicode('\xe2\x97\x91 \xe2\x80\xa0', encoding='utf8')
# u'\u25d1 \u2020'
utf8_string = 'ร
รชรญรฒรผ'
utf8_string
# '\xc3\x85\xc3\xaa\xc3\xad\xc3\xb2\xc3\xbc'
unicode_string = utf8_string.decode('utf8')
unicode_string
# u'\xc5\xea\xed\xf2\xfc'
unicode_string.encode('mac roman')
# '\x81\x90\x92\x98\x9f'
'ร
รชรญรฒรผ'.decode('utf8').encode('ascii')
# Traceback (most recent call last):
# ย File "<stdin>", line 1, in <module>
# UnicodeEncodeError: 'ascii' codec can't encode characters in position 0-4: ordinal not in range(128)
file = """ๆฝๆฅชๆ
ขๆซๆค โณๆกดโฅๆ
งๆฒๆฌโคๆด็ธ็ ๆ
จโด็ฉ็ ๆจ็ ็ฅๆฑตโดๆฏ็ ็กฅโดๆขๆนฉโงๆคๆฝฃๆคโค็ตๆนฉโงๆนก็ ๆฅฎ็ฎๆนฅๆคโคๆกฃ
็กๆกๆดโฒๆนฅๆฝฃๆฅคๆฎๆฅทๆกดๆ ๆตฏๆฑฐ็ฅๆฑฅโนๆนตๆฒๆ
ฌๆดโคๆนฏ็ฅๆฏๆดโฎ็ฆๆตฏๆ ๆ ๆฉๆฆๆฒ็ฎ็ ๆฅฒๆฅดๆฎ็ ็นๆดโนญโงโ ๆ
ๆซโฎ
็ฆๆตฏๆ โนฎๆฅทๆฅซๆฐๆฅคโนก็ฏโฅง"""
print file.decode('utf8').encode('utf16')
# ??Mojibake is the garbled text that is the result of text being decoded using an
# unintended character encoding with completely unrelated ones, often from a
# different writing system.' (Taken from en.wikipedia.org)
import ftfy
ftfy.fix_text(u"รขโฌลMojibakeรขโฌล can be fixed.")
# u'"Mojibake" can be fixed.'
bin(0b1010 & 0b1111110111)
# '0b10'
bin(0b1010 | 0b0110)
# '0b1110'
bin(0b10111 | 0b01000)
# '0b11111'
bin(0b100 ^ 0b110)
# '0b10'
bin(-0b1010 >> 0b10)
# '-0b11'
x = 0b1111
y = 0b1010
bin(int("{:b}{:b}".format(x, y), 2))
# '0b11111010'
bin(x << 4 | y)
# '0b11111010'
####################################################################
# 4. Cryptography
####################################################################
import random
import string
ย
r = random.SystemRandom()
# Get a random integer between 0 and 20
r.randint(0, 20)
# 5
ย
# Get a random number between 0 and 1
r.random()
# 0.8282475835972263
ย
# Generate a random 40-bit number
r.getrandbits(40)
# 595477188771L
# Choose a random item from a string or list
chars = string.printable
r.choice(chars)
# 'e'
ย # Randomize the order of a sequence
seq = ['a', 'b', 'c', 'd', 'e']
r.shuffle(seq)
print seq
# ['c','d', 'a', 'e', 'b']
"ALLIGATOR".encode('rot13')
# 'NYYVTNGBE'
"NYYVTNGBE".encode('rot13')
# 'ALLIGATOR'
plaintext = "A secret-ish message!"
"".join(chr((ord(c) + 20) % 256) for c in plaintext)
# 'U4\x87yw\x86y\x88A}\x87|4\x81y\x87\x87u{y5'
ciphertext = 'U4\x87yw\x86y\x88A}\x87|4\x81y\x87\x87u{y5'
"".join(chr((ord(c) - 20) % 256) for c in ciphertext)
# 'A secret-ish message!'
plaintext = 0b110100001101001
one_time_pad = 0b110000011100001
bin(plaintext ^ one_time_pad)
# '0b100010001000'
decrypted = 0b100010001000 ^ one_time_pad
format(decrypted, 'x').decode('hex')
# 'hi'
import os
import binascii
# ASCII-encoded plaintext
plaintext = "this is a secret message"
plaintext_bits = int(binascii.hexlify(plaintext), 16)
print "plaintext (ascii):", plaintext
print "plaintext (hex):", plaintext_bits
# Generate the one-time pad
onetime_pad = int(binascii.hexlify(os.urandom(len(plaintext))), 16)
print "one-time pad: (hex):", onetime_pad
# Encrypt plaintext using XOR operation with one-time pad
ciphertext_bits = plaintext_bits ^ onetime_pad
print "encrypted text (hex):", ciphertext_bits
# Decrypt using XOR operation with one-time pad
decrypted_text = ciphertext_bits ^ onetime_pad
decrypted_text = binascii.unhexlify(hex(decrypted_text)[2:-1])
print "decrypted text (ascii):", decrypted_text
import random
import binascii
p1 = "this is the part where you run away"
p2 = "from bad cryptography practices."
# pad plaintexts with spaces to ensure equal length
p1 = p1.ljust(len(p2))
p2 = p2.ljust(len(p1))
p1 = int(binascii.hexlify(p1), 16)
p2 = int(binascii.hexlify(p2), 16)
# get random one-time pad
otp = random.SystemRandom().getrandbits(p1.bit_length())
# encrypt
c1 = p1 ^ otp
c2 = p2 ^ otp # otp reuse...not good!
print "c1 ^ c2 == p1 ^ p2 ?", c1 ^ c2 == p1 ^ p2
print "c1 ^ c2 =", hex(c1 ^ c2)
# the crib
crib = " the "
crib = int(binascii.hexlify(crib), 16)
xored = c1 ^ c2
print "crib =", hex(crib)
cbl = crib.bit_length()
xbl = xored.bit_length()
print
mask = (2**(cbl + 1) - 1)
fill = len(str(xbl / 8))
# crib dragging
for s in range(0, xbl - cbl + 8, 8):
xor = (xored ^ (crib << s)) & (mask << s)
out = binascii.unhexlify(hex(xor)[2:-1])
print "{:>{}} {}".format(s/8, fill, out)
from cryptography.fernet import Fernet
key = Fernet.generate_key()
f = Fernet(key)
ciphertext = f.encrypt("this is my plaintext")
decrypted = f.decrypt(ciphertext)
print decrypted
# this is my plaintext
import os
from cryptography.hazmat.primitives import padding
from cryptography.hazmat.primitives.ciphers import Cipher, algorithms, modes
from cryptography.hazmat.backends import default_backend
pt = "my plaintext"
backend = default_backend()
key = os.urandom(32)
iv = os.urandom(16)
| pt = padder.update(pt) + padder.finalize()
cipher = Cipher(algorithms.AES(key), modes.CBC(iv), backend=backend)
encryptor = cipher.encryptor()
ct = encryptor.update(pt) + encryptor.finalize()
decryptor = cipher.decryptor()
out = decryptor.update(ct) + decryptor.finalize()
unpadder = padding.PKCS7(128).unpadder()
out = unpadder.update(out) + unpadder.finalize()
print out
import hashlib
hashlib.md5("hash me please").hexdigest()
# '760d92b6a6f974ae11904cd0a6fc2e90'
hashlib.sha1("hash me please").hexdigest()
# '1a58c9b3d138a45519518ee42e634600d1b52153'
import os
from cryptography.hazmat.primitives.kdf.scrypt import Scrypt
from cryptography.hazmat.backends import default_backend
backend = default_backend()
salt = os.urandom(16)
kdf = Scrypt(salt=salt, length=64, n=2**14, r=8, p=1, backend=backend)
key = kdf.derive("your favorite password")
key
import hmac
import hashlib
secret_key = "my secret key"
ciphertext = "my ciphertext"
# generate HMAC
h = hmac.new(key=secret_key, msg=ciphertext, digestmod=hashlib.sha256)
print h.hexdigest()
# verify HMAC
hmac.compare_digest(h.hexdigest(), h.hexdigest())
p = 9576890767
q = 1299827
n = p * q
print n
# 12448301194997309
e = 65537
phi = (p - 1) * (q - 1)
phi % e != 0
# True
import sympy
d = sympy.numbers.igcdex(e, phi)[0]
print d
# 1409376745910033
m = 12345
c = pow(m, e, n)
print c
# 3599057382134015
pow(c, d, n)
# 12345
m = 0
while pow(m, e, n) != c:
ย ย ย m += 1
print m
from cryptography.hazmat.backends import default_backend
from cryptography.hazmat.primitives.asymmetric import rsa
from cryptography.hazmat.primitives import serialization
private_key = rsa.generate_private_key(public_exponent=65537, key_size=2048, b
ackend=default_backend())
public_key = private_key.public_key()
private_pem = private_key.private_bytes(encoding=serialization.Encoding.PEM,
format=serialization.PrivateFormat.PKCS8,
encryption_algorithm=serialization.BestAvailableEncryption('your password here'))
public_pem = public_key.public_bytes(encoding=serialization.Encoding.PEM,
format=serialization.PublicFormat.SubjectPublicKeyInfo)
print public_pem
print private_pem
from cryptography.hazmat.primitives import hashes
from cryptography.hazmat.primitives.asymmetric import padding
import base64
with open("path/to/public_key.pem", "rb") as key_file:
public_key = serialization.load_pem_public_key(key_file.read(),
backend=default_backend())
message = "your secret message"
ciphertext = public_key.encrypt(message,
padding.OAEP(mgf=padding.MGF1(algorithm=hashes.SHA256()),
algorithm=hashes.SHA256(),
label=None))
b64_ciphertext = base64.urlsafe_b64encode(ciphertext)
print b64_ciphertext
plaintext = private_key.decrypt(ciphertext,
padding.OAEP(mgf=padding.MGF1(algorithm=hashes.SHA256()),
algorithm=hashes.SHA256(),
label=None))
print plaintext
from cryptography.hazmat.primitives import hashes
from cryptography.hazmat.primitives.asymmetric import padding
signer = private_key.signer(padding.PSS(mgf=padding.MGF1(hashes.SHA256()), salt_length=padding.PSS.MAX_LENGTH), hashes.SHA256())
message = "A message of arbitrary length"
signer.update(message)
signature = signer.finalize()
public_key = private_key.public_key()
verifier = public_key.verifier(signature, padding.PSS(mgf=padding.MGF1(hashes.SHA256()), salt_length=padding.PSS.MAX_LENGTH), hashes.SHA256())
verifier.update(message)
verifier.verify()
####################################################################
# 5. Networking
####################################################################
import requests
r = requests.get('https://www.google.com/imghp')
r.content[:200]
# View status code
r.status_code
# 200
ย
# View response header fields
r.headers
# {'Alt-Svc': 'quic=":443"; ma=2592000; v="36,35,34"',
# ย 'Cache-Control': 'private, max-age=0',
# ย 'Content-Encoding': 'gzip',
# ย 'Content-Type': 'text/html; charset=ISO-8859-1',
# 'Expires': '-1',
# ย 'P3P': 'CP="This is not a P3P policy! See https://www.google.com/support/accounts/answer/151657?hl=en for more info."',
# ย 'Server': 'gws',
# path=/; domain=.google.com; HttpOnly',
# ย 'Transfer-Encoding': 'chunked',
# ย 'X-Frame-Options': 'SAMEORIGIN',
# ย 'X-XSS-Protection': '1; mode=block'}
# Get content length in bytes
len(r.content)
# 10971
# Encoding
r.apparent_encoding
# 'ISO-8859-2'
# Time elapsed during request
r.elapsed
# datetime.timedelta(0, 0, 454447)
r.request.headers
# {'Accept': '*/*',
# ย 'Accept-Encoding': 'gzip, deflate',
# ย 'Connection': 'keep-alive',
# ย 'User-Agent': 'python-requests/2.12.4'}
custom_headers = {"user-agent": "Mozilla/5.0 (Macintosh; Intel Mac OS X 10_11_6) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/56.0.2924.87 Safari/537.36"}
r = requests.get("https://www.google.com/imghp", headers=custom_headers)
r.request.headers
# {'Accept': '*/*',
# ย 'Accept-Encoding': 'gzip, deflate',
# ย 'Connection': 'keep-alive',
# ย 'user-agent': 'Mozilla/5.0 (Macintosh; Intel Mac OS X 10_11_6) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/56.0.2924.87 Safari/537.36'}
import requests
import logging
import http.client as http_client
http_client.HTTPConnection.debuglevel = 1
logging.basicConfig()
logging.getLogger().setLevel(logging.DEBUG)
requests_log = logging.getLogger("requests.packages.urllib3")
requests_log.setLevel(logging.DEBUG)
requests_log.propagate = True
r = requests.get('https://www.google.com/')
# send: 'GET / HTTP/1.1\r\nHost: www.google.com\r\nConnection: keep-alive\r\nAccept-Encoding: gzip, deflate\r\nAccept: */*\r\nUser-Agent: python-requests/2.12.4\r\n\r\n'
# reply: 'HTTP/1.1 200 OK\r\n'
# header: Expires: -1
# header: Cache-Control: private, max-age=0
# header: Content-Type: text/html; charset=ISO-8859-1
# header: P3P: CP="This is not a P3P policy! See https://www.google.com/support/accounts/answer/151657?hl=en for more info."
# header: Content-Encoding: gzip
# header: Server: gws
# header: X-XSS-Protection: 1; mode=block
# header: X-Frame-Options: SAMEORIGIN
import urlparse
simple_url = "http://www.example.com/path/to/my/page"
parsed = urlparse.urlparse(simple_url)
parsed.scheme
parsed.hostname
parsed.path
url_with_query = "http://www.example.com/?page=1&key=Anvn4mo24"
query = urlparse.urlparse(url_with_query).query
urlparse.parse_qs(query)
# {'key': ['Anvn4mo24'], 'page': ['1']}
import urllib
url = 'https://www.example.com/%5EA-url-with-%-and-%5E?page=page+with%20spaces'
urllib.unquote(url)
# 'https://www.example.com/^A-url-with-%-and-^?page=page+with spaces'
chars = '!@#$%^%$#)'
urllib.quote(chars)
# '%21%40%23%24%25%5E%25%24%23%29'
urllib.unquote_plus(url)
# 'https://www.example.com/^A-url-with-%-and-^?page=page with spaces'
urllib.quote_plus('one two')
'one+two'
import requests
from bs4 import BeautifulSoup
r = requests.get("http://www.google.com")
soup = BeautifulSoup(r.content, "lxml")
soup.find_all('p')
soup.find_all('a')
# [<a class="gb1" href="http://www.google.com/imghp?hl=en&tab=wi">Images</a>,
# <a class="gb1" href="http://maps.google.com/maps?hl=en&tab=wl">Maps</a>,
# <a class="gb1" href="https://play.google.com/?hl=en&tab=w8">Play</a>,
# <a class="gb1" href="http://www.youtube.com/?tab=w1">YouTube</a>,
# <a class="gb1" href="http://news.google.com/nwshp?hl=en&tab=wn">News</a>,
# โฆ]
for link in soup.find_all('a'):
print link.text, link["href"]
# Images http://www.google.com/imghp?hl=en&tab=wi
# Maps http://maps.google.com/maps?hl=en&tab=wl
# Play https://play.google.com/?hl=en&tab=w8
# YouTube http://www.youtube.com/?tab=w1
import dryscrape
from bs4 import BeautifulSoup
session = dryscrape.Session()
session.visit("http://www.google.com")
r = session.body()
soup = BeautifulSoup(r, "lxml")
from selenium import webdriver
driver = webdriver.Chrome("/path/to/chromedriver")
driver.get("http://www.google.com")
html = driver.page_source
driver.save_screenshot("screenshot.png")
driver.quit()
import smtplib
server = smtplib.SMTP('localhost', port=1025)
server.set_debuglevel(True)
server.sendmail("me@localhost", "you@localhost", "This is an email message")
server.quit() | padder = padding.PKCS7(128).padder() | random_line_split |
code_from_book.py | # Python Code From Book
# This file consists of code snippets only
# It is not intended to be run as a script
raise SystemExit
####################################################################
# 3. Thinking in Binary
####################################################################
import magic
print magic.from_file("my_image.jpg")
# JPEG image data, Exif standard: [TIFF image data, big-endian,
# direntries=16, height=3264, bps=0, PhotometricIntepretation=RGB],
# baseline, precision 8, 2378x2379, frames 3
if magic.from_file("upload.jpg", mime=True) == "image/jpeg":
continue_uploading("upload.jpg")
else:
alert("Sorry! This file type is not allowed")
import imghdr
print imghdr.what("path/to/my/file.ext")
import binascii
ย
def spoof_file(file, magic_number):
magic_number = binascii.unhexlify(magic_number)
with open(file, "r+b") as f:
old = f.read()
f.seek(0)
f.write(magic_number + old)
ย
def to | tring):
return " ".join(format(ord(char), '08b') for char in string)
string = "my ascii string"
"".join(hex(ord(char))[2:] for char in string)
# '6d7920617363696920737472696e67'
hex_string = "6d7920617363696920737472696e67"
hex_string.decode("hex")
# 'my ascii string'
"".join(chr(int(hex_string[i:i+2], 16)) for i in range(0, len(hex_string), 2))
# 'my ascii string'
# adapted from https://code.activestate.com/recipes/142812-hex-dumper/
def hexdump(string, length=8):
result = []
digits = 4 if isinstance(string, unicode) else 2
for i in xrange(0, len(string), length):
s = string[i:i + length]
hexa = "".join("{:0{}X}".format(ord(x), digits) for x in s)
text = "".join(x if 0x20 <= ord(x) < 0x7F else '.' for x in s)
result.append("{:04X}ย ย {:{}}ย ย {}".format(i, hexa, length * (digits + 1), text))
return '\n'.join(result)
with open("/path/to/my_file.ext", "r") as f:
print hexdump(f.read())
import struct
num = 0x103e4
struct.pack("I", 0x103e4)
# '\xe4\x03\x01\x00'
string = '\xe4\x03\x01\x00'
struct.unpack("i", string)
# (66532,)
bytes = '\x01\xc2'
struct.pack("<h", struct.unpack(">h", bytes)[0])
# '\xc2\x01'
import base64
base64.b64encode('encodings are fun...')
# 'ZW5jb2RpbmdzIGFyZSBmdW4uLi4='
base64.b64decode(_)
# 'encodings are fun...'
string = "hello\x00"
binary_string = ' '.join('{:08b}'.format(ord(char)) for char in string)
" ".join(binary_string[i:i+6] for i in range(0, len(binary_string), 6))
# '011010 000110 010101 101100 011011 000110 111100 000000'
bin_string = '011010 000110 010101 101100 011011 000110 111100 000000'
[int(b, 2) for b in bin_string.split()]
# [26, 6, 21, 44, 27, 6, 60, 0]
u'โ \u2020'.encode('utf8')
# '\xe2\x97\x91 \xe2\x80\xa0'
'\xe2\x97\x91 \xe2\x80\xa0'.decode('utf8')
# u'\u25d1 \u2020'
unicode('\xe2\x97\x91 \xe2\x80\xa0', encoding='utf8')
# u'\u25d1 \u2020'
utf8_string = 'ร
รชรญรฒรผ'
utf8_string
# '\xc3\x85\xc3\xaa\xc3\xad\xc3\xb2\xc3\xbc'
unicode_string = utf8_string.decode('utf8')
unicode_string
# u'\xc5\xea\xed\xf2\xfc'
unicode_string.encode('mac roman')
# '\x81\x90\x92\x98\x9f'
'ร
รชรญรฒรผ'.decode('utf8').encode('ascii')
# Traceback (most recent call last):
# ย File "<stdin>", line 1, in <module>
# UnicodeEncodeError: 'ascii' codec can't encode characters in position 0-4: ordinal not in range(128)
file = """ๆฝๆฅชๆ
ขๆซๆค โณๆกดโฅๆ
งๆฒๆฌโคๆด็ธ็ ๆ
จโด็ฉ็ ๆจ็ ็ฅๆฑตโดๆฏ็ ็กฅโดๆขๆนฉโงๆคๆฝฃๆคโค็ตๆนฉโงๆนก็ ๆฅฎ็ฎๆนฅๆคโคๆกฃ
็กๆกๆดโฒๆนฅๆฝฃๆฅคๆฎๆฅทๆกดๆ ๆตฏๆฑฐ็ฅๆฑฅโนๆนตๆฒๆ
ฌๆดโคๆนฏ็ฅๆฏๆดโฎ็ฆๆตฏๆ ๆ ๆฉๆฆๆฒ็ฎ็ ๆฅฒๆฅดๆฎ็ ็นๆดโนญโงโ ๆ
ๆซโฎ
็ฆๆตฏๆ โนฎๆฅทๆฅซๆฐๆฅคโนก็ฏโฅง"""
print file.decode('utf8').encode('utf16')
# ??Mojibake is the garbled text that is the result of text being decoded using an
# unintended character encoding with completely unrelated ones, often from a
# different writing system.' (Taken from en.wikipedia.org)
import ftfy
ftfy.fix_text(u"รขโฌลMojibakeรขโฌล can be fixed.")
# u'"Mojibake" can be fixed.'
bin(0b1010 & 0b1111110111)
# '0b10'
bin(0b1010 | 0b0110)
# '0b1110'
bin(0b10111 | 0b01000)
# '0b11111'
bin(0b100 ^ 0b110)
# '0b10'
bin(-0b1010 >> 0b10)
# '-0b11'
x = 0b1111
y = 0b1010
bin(int("{:b}{:b}".format(x, y), 2))
# '0b11111010'
bin(x << 4 | y)
# '0b11111010'
####################################################################
# 4. Cryptography
####################################################################
import random
import string
ย
r = random.SystemRandom()
# Get a random integer between 0 and 20
r.randint(0, 20)
# 5
ย
# Get a random number between 0 and 1
r.random()
# 0.8282475835972263
ย
# Generate a random 40-bit number
r.getrandbits(40)
# 595477188771L
# Choose a random item from a string or list
chars = string.printable
r.choice(chars)
# 'e'
ย # Randomize the order of a sequence
seq = ['a', 'b', 'c', 'd', 'e']
r.shuffle(seq)
print seq
# ['c','d', 'a', 'e', 'b']
"ALLIGATOR".encode('rot13')
# 'NYYVTNGBE'
"NYYVTNGBE".encode('rot13')
# 'ALLIGATOR'
plaintext = "A secret-ish message!"
"".join(chr((ord(c) + 20) % 256) for c in plaintext)
# 'U4\x87yw\x86y\x88A}\x87|4\x81y\x87\x87u{y5'
ciphertext = 'U4\x87yw\x86y\x88A}\x87|4\x81y\x87\x87u{y5'
"".join(chr((ord(c) - 20) % 256) for c in ciphertext)
# 'A secret-ish message!'
plaintext = 0b110100001101001
one_time_pad = 0b110000011100001
bin(plaintext ^ one_time_pad)
# '0b100010001000'
decrypted = 0b100010001000 ^ one_time_pad
format(decrypted, 'x').decode('hex')
# 'hi'
import os
import binascii
# ASCII-encoded plaintext
plaintext = "this is a secret message"
plaintext_bits = int(binascii.hexlify(plaintext), 16)
print "plaintext (ascii):", plaintext
print "plaintext (hex):", plaintext_bits
# Generate the one-time pad
onetime_pad = int(binascii.hexlify(os.urandom(len(plaintext))), 16)
print "one-time pad: (hex):", onetime_pad
# Encrypt plaintext using XOR operation with one-time pad
ciphertext_bits = plaintext_bits ^ onetime_pad
print "encrypted text (hex):", ciphertext_bits
# Decrypt using XOR operation with one-time pad
decrypted_text = ciphertext_bits ^ onetime_pad
decrypted_text = binascii.unhexlify(hex(decrypted_text)[2:-1])
print "decrypted text (ascii):", decrypted_text
import random
import binascii
p1 = "this is the part where you run away"
p2 = "from bad cryptography practices."
# pad plaintexts with spaces to ensure equal length
p1 = p1.ljust(len(p2))
p2 = p2.ljust(len(p1))
p1 = int(binascii.hexlify(p1), 16)
p2 = int(binascii.hexlify(p2), 16)
# get random one-time pad
otp = random.SystemRandom().getrandbits(p1.bit_length())
# encrypt
c1 = p1 ^ otp
c2 = p2 ^ otp # otp reuse...not good!
print "c1 ^ c2 == p1 ^ p2 ?", c1 ^ c2 == p1 ^ p2
print "c1 ^ c2 =", hex(c1 ^ c2)
# the crib
crib = " the "
crib = int(binascii.hexlify(crib), 16)
xored = c1 ^ c2
print "crib =", hex(crib)
cbl = crib.bit_length()
xbl = xored.bit_length()
print
mask = (2**(cbl + 1) - 1)
fill = len(str(xbl / 8))
# crib dragging
for s in range(0, xbl - cbl + 8, 8):
xor = (xored ^ (crib << s)) & (mask << s)
out = binascii.unhexlify(hex(xor)[2:-1])
print "{:>{}} {}".format(s/8, fill, out)
from cryptography.fernet import Fernet
key = Fernet.generate_key()
f = Fernet(key)
ciphertext = f.encrypt("this is my plaintext")
decrypted = f.decrypt(ciphertext)
print decrypted
# this is my plaintext
import os
from cryptography.hazmat.primitives import padding
from cryptography.hazmat.primitives.ciphers import Cipher, algorithms, modes
from cryptography.hazmat.backends import default_backend
pt = "my plaintext"
backend = default_backend()
key = os.urandom(32)
iv = os.urandom(16)
padder = padding.PKCS7(128).padder()
pt = padder.update(pt) + padder.finalize()
cipher = Cipher(algorithms.AES(key), modes.CBC(iv), backend=backend)
encryptor = cipher.encryptor()
ct = encryptor.update(pt) + encryptor.finalize()
decryptor = cipher.decryptor()
out = decryptor.update(ct) + decryptor.finalize()
unpadder = padding.PKCS7(128).unpadder()
out = unpadder.update(out) + unpadder.finalize()
print out
import hashlib
hashlib.md5("hash me please").hexdigest()
# '760d92b6a6f974ae11904cd0a6fc2e90'
hashlib.sha1("hash me please").hexdigest()
# '1a58c9b3d138a45519518ee42e634600d1b52153'
import os
from cryptography.hazmat.primitives.kdf.scrypt import Scrypt
from cryptography.hazmat.backends import default_backend
backend = default_backend()
salt = os.urandom(16)
kdf = Scrypt(salt=salt, length=64, n=2**14, r=8, p=1, backend=backend)
key = kdf.derive("your favorite password")
key
import hmac
import hashlib
secret_key = "my secret key"
ciphertext = "my ciphertext"
# generate HMAC
h = hmac.new(key=secret_key, msg=ciphertext, digestmod=hashlib.sha256)
print h.hexdigest()
# verify HMAC
hmac.compare_digest(h.hexdigest(), h.hexdigest())
p = 9576890767
q = 1299827
n = p * q
print n
# 12448301194997309
e = 65537
phi = (p - 1) * (q - 1)
phi % e != 0
# True
import sympy
d = sympy.numbers.igcdex(e, phi)[0]
print d
# 1409376745910033
m = 12345
c = pow(m, e, n)
print c
# 3599057382134015
pow(c, d, n)
# 12345
m = 0
while pow(m, e, n) != c:
ย ย ย m += 1
print m
from cryptography.hazmat.backends import default_backend
from cryptography.hazmat.primitives.asymmetric import rsa
from cryptography.hazmat.primitives import serialization
private_key = rsa.generate_private_key(public_exponent=65537, key_size=2048, b
ackend=default_backend())
public_key = private_key.public_key()
private_pem = private_key.private_bytes(encoding=serialization.Encoding.PEM,
format=serialization.PrivateFormat.PKCS8,
encryption_algorithm=serialization.BestAvailableEncryption('your password here'))
public_pem = public_key.public_bytes(encoding=serialization.Encoding.PEM,
format=serialization.PublicFormat.SubjectPublicKeyInfo)
print public_pem
print private_pem
from cryptography.hazmat.primitives import hashes
from cryptography.hazmat.primitives.asymmetric import padding
import base64
with open("path/to/public_key.pem", "rb") as key_file:
public_key = serialization.load_pem_public_key(key_file.read(),
backend=default_backend())
message = "your secret message"
ciphertext = public_key.encrypt(message,
padding.OAEP(mgf=padding.MGF1(algorithm=hashes.SHA256()),
algorithm=hashes.SHA256(),
label=None))
b64_ciphertext = base64.urlsafe_b64encode(ciphertext)
print b64_ciphertext
plaintext = private_key.decrypt(ciphertext,
padding.OAEP(mgf=padding.MGF1(algorithm=hashes.SHA256()),
algorithm=hashes.SHA256(),
label=None))
print plaintext
from cryptography.hazmat.primitives import hashes
from cryptography.hazmat.primitives.asymmetric import padding
signer = private_key.signer(padding.PSS(mgf=padding.MGF1(hashes.SHA256()), salt_length=padding.PSS.MAX_LENGTH), hashes.SHA256())
message = "A message of arbitrary length"
signer.update(message)
signature = signer.finalize()
public_key = private_key.public_key()
verifier = public_key.verifier(signature, padding.PSS(mgf=padding.MGF1(hashes.SHA256()), salt_length=padding.PSS.MAX_LENGTH), hashes.SHA256())
verifier.update(message)
verifier.verify()
####################################################################
# 5. Networking
####################################################################
import requests
r = requests.get('https://www.google.com/imghp')
r.content[:200]
# View status code
r.status_code
# 200
ย
# View response header fields
r.headers
# {'Alt-Svc': 'quic=":443"; ma=2592000; v="36,35,34"',
# ย 'Cache-Control': 'private, max-age=0',
# ย 'Content-Encoding': 'gzip',
# ย 'Content-Type': 'text/html; charset=ISO-8859-1',
# 'Expires': '-1',
# ย 'P3P': 'CP="This is not a P3P policy! See https://www.google.com/support/accounts/answer/151657?hl=en for more info."',
# ย 'Server': 'gws',
# path=/; domain=.google.com; HttpOnly',
# ย 'Transfer-Encoding': 'chunked',
# ย 'X-Frame-Options': 'SAMEORIGIN',
# ย 'X-XSS-Protection': '1; mode=block'}
# Get content length in bytes
len(r.content)
# 10971
# Encoding
r.apparent_encoding
# 'ISO-8859-2'
# Time elapsed during request
r.elapsed
# datetime.timedelta(0, 0, 454447)
r.request.headers
# {'Accept': '*/*',
# ย 'Accept-Encoding': 'gzip, deflate',
# ย 'Connection': 'keep-alive',
# ย 'User-Agent': 'python-requests/2.12.4'}
custom_headers = {"user-agent": "Mozilla/5.0 (Macintosh; Intel Mac OS X 10_11_6) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/56.0.2924.87 Safari/537.36"}
r = requests.get("https://www.google.com/imghp", headers=custom_headers)
r.request.headers
# {'Accept': '*/*',
# ย 'Accept-Encoding': 'gzip, deflate',
# ย 'Connection': 'keep-alive',
# ย 'user-agent': 'Mozilla/5.0 (Macintosh; Intel Mac OS X 10_11_6) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/56.0.2924.87 Safari/537.36'}
import requests
import logging
import http.client as http_client
http_client.HTTPConnection.debuglevel = 1
logging.basicConfig()
logging.getLogger().setLevel(logging.DEBUG)
requests_log = logging.getLogger("requests.packages.urllib3")
requests_log.setLevel(logging.DEBUG)
requests_log.propagate = True
r = requests.get('https://www.google.com/')
# send: 'GET / HTTP/1.1\r\nHost: www.google.com\r\nConnection: keep-alive\r\nAccept-Encoding: gzip, deflate\r\nAccept: */*\r\nUser-Agent: python-requests/2.12.4\r\n\r\n'
# reply: 'HTTP/1.1 200 OK\r\n'
# header: Expires: -1
# header: Cache-Control: private, max-age=0
# header: Content-Type: text/html; charset=ISO-8859-1
# header: P3P: CP="This is not a P3P policy! See https://www.google.com/support/accounts/answer/151657?hl=en for more info."
# header: Content-Encoding: gzip
# header: Server: gws
# header: X-XSS-Protection: 1; mode=block
# header: X-Frame-Options: SAMEORIGIN
import urlparse
simple_url = "http://www.example.com/path/to/my/page"
parsed = urlparse.urlparse(simple_url)
parsed.scheme
parsed.hostname
parsed.path
url_with_query = "http://www.example.com/?page=1&key=Anvn4mo24"
query = urlparse.urlparse(url_with_query).query
urlparse.parse_qs(query)
# {'key': ['Anvn4mo24'], 'page': ['1']}
import urllib
url = 'https://www.example.com/%5EA-url-with-%-and-%5E?page=page+with%20spaces'
urllib.unquote(url)
# 'https://www.example.com/^A-url-with-%-and-^?page=page+with spaces'
chars = '!@#$%^%$#)'
urllib.quote(chars)
# '%21%40%23%24%25%5E%25%24%23%29'
urllib.unquote_plus(url)
# 'https://www.example.com/^A-url-with-%-and-^?page=page with spaces'
urllib.quote_plus('one two')
'one+two'
import requests
from bs4 import BeautifulSoup
r = requests.get("http://www.google.com")
soup = BeautifulSoup(r.content, "lxml")
soup.find_all('p')
soup.find_all('a')
# [<a class="gb1" href="http://www.google.com/imghp?hl=en&tab=wi">Images</a>,
# <a class="gb1" href="http://maps.google.com/maps?hl=en&tab=wl">Maps</a>,
# <a class="gb1" href="https://play.google.com/?hl=en&tab=w8">Play</a>,
# <a class="gb1" href="http://www.youtube.com/?tab=w1">YouTube</a>,
# <a class="gb1" href="http://news.google.com/nwshp?hl=en&tab=wn">News</a>,
# โฆ]
for link in soup.find_all('a'):
print link.text, link["href"]
# Images http://www.google.com/imghp?hl=en&tab=wi
# Maps http://maps.google.com/maps?hl=en&tab=wl
# Play https://play.google.com/?hl=en&tab=w8
# YouTube http://www.youtube.com/?tab=w1
import dryscrape
from bs4 import BeautifulSoup
session = dryscrape.Session()
session.visit("http://www.google.com")
r = session.body()
soup = BeautifulSoup(r, "lxml")
from selenium import webdriver
driver = webdriver.Chrome("/path/to/chromedriver")
driver.get("http://www.google.com")
html = driver.page_source
driver.save_screenshot("screenshot.png")
driver.quit()
import smtplib
server = smtplib.SMTP('localhost', port=1025)
server.set_debuglevel(True)
server.sendmail("me@localhost", "you@localhost", "This is an email message")
server.quit()
| _ascii_bytes(s | identifier_name |
device_id.rs | #[cfg(feature = "rand")]
use super::generate_localpart;
/// A Matrix key ID.
///
/// Device identifiers in Matrix are completely opaque character sequences. This type is provided
/// simply for its semantic value.
///
/// # Example
///
/// ```
/// use ruma_common::{device_id, DeviceId};
///
/// let random_id = DeviceId::new();
/// assert_eq!(random_id.as_str().len(), 8);
///
/// let static_id = device_id!("01234567");
/// assert_eq!(static_id.as_str(), "01234567");
///
/// let ref_id: &DeviceId = "abcdefghi".into();
/// assert_eq!(ref_id.as_str(), "abcdefghi");
///
/// let owned_id: Box<DeviceId> = "ijklmnop".into();
/// assert_eq!(owned_id.as_str(), "ijklmnop");
/// ```
#[repr(transparent)]
#[derive(PartialEq, Eq, PartialOrd, Ord, Hash)]
pub struct DeviceId(str);
| opaque_identifier!(DeviceId);
impl DeviceId {
/// Generates a random `DeviceId`, suitable for assignment to a new device.
#[cfg(feature = "rand")]
pub fn new() -> Box<Self> {
Self::from_owned(generate_localpart(8))
}
}
#[cfg(all(test, feature = "rand"))]
mod tests {
use super::DeviceId;
#[test]
fn generate_device_id() {
assert_eq!(DeviceId::new().as_str().len(), 8);
}
#[test]
fn create_device_id_from_str() {
let ref_id: &DeviceId = "abcdefgh".into();
assert_eq!(ref_id.as_str(), "abcdefgh");
}
#[test]
fn create_boxed_device_id_from_str() {
let box_id: Box<DeviceId> = "12345678".into();
assert_eq!(box_id.as_str(), "12345678");
}
#[test]
fn create_device_id_from_box() {
let box_str: Box<str> = "ijklmnop".into();
let device_id: Box<DeviceId> = DeviceId::from_owned(box_str);
assert_eq!(device_id.as_str(), "ijklmnop");
}
} | random_line_split | |
device_id.rs | #[cfg(feature = "rand")]
use super::generate_localpart;
/// A Matrix key ID.
///
/// Device identifiers in Matrix are completely opaque character sequences. This type is provided
/// simply for its semantic value.
///
/// # Example
///
/// ```
/// use ruma_common::{device_id, DeviceId};
///
/// let random_id = DeviceId::new();
/// assert_eq!(random_id.as_str().len(), 8);
///
/// let static_id = device_id!("01234567");
/// assert_eq!(static_id.as_str(), "01234567");
///
/// let ref_id: &DeviceId = "abcdefghi".into();
/// assert_eq!(ref_id.as_str(), "abcdefghi");
///
/// let owned_id: Box<DeviceId> = "ijklmnop".into();
/// assert_eq!(owned_id.as_str(), "ijklmnop");
/// ```
#[repr(transparent)]
#[derive(PartialEq, Eq, PartialOrd, Ord, Hash)]
pub struct DeviceId(str);
opaque_identifier!(DeviceId);
impl DeviceId {
/// Generates a random `DeviceId`, suitable for assignment to a new device.
#[cfg(feature = "rand")]
pub fn | () -> Box<Self> {
Self::from_owned(generate_localpart(8))
}
}
#[cfg(all(test, feature = "rand"))]
mod tests {
use super::DeviceId;
#[test]
fn generate_device_id() {
assert_eq!(DeviceId::new().as_str().len(), 8);
}
#[test]
fn create_device_id_from_str() {
let ref_id: &DeviceId = "abcdefgh".into();
assert_eq!(ref_id.as_str(), "abcdefgh");
}
#[test]
fn create_boxed_device_id_from_str() {
let box_id: Box<DeviceId> = "12345678".into();
assert_eq!(box_id.as_str(), "12345678");
}
#[test]
fn create_device_id_from_box() {
let box_str: Box<str> = "ijklmnop".into();
let device_id: Box<DeviceId> = DeviceId::from_owned(box_str);
assert_eq!(device_id.as_str(), "ijklmnop");
}
}
| new | identifier_name |
globals.ts | import * as path from 'path';
export const UPDATE_INTERVALL = 2 * 60 * 60 * 1000;
export const GITHUB_RELEASES_URL = "https://api.github.com/repos/kumpelblase2/proxtop/releases";
export const UPDATER_FEED_URL = "https://proxtop.eternalwings.de/update/";
export const APP_NAME = "proxtop";
export const PROXER_BASE_URL = "https://proxer.me";
export const PROXER_API_BASE_URL = "https://proxer.me/api/v1";
export const INDEX_LOCATION = __dirname + "/index.html";
export const LOGO_RELATIVE_PATH = "static/assets/proxtop_logo_256.png";
export const LOGO_LOCATION = path.join(__dirname, "../", LOGO_RELATIVE_PATH);
let appDir: string;
try {
appDir = path.join(require("electron").app.getPath("appData"), APP_NAME);
} catch (e) {
appDir = path.join(__dirname, '..', '..', APP_NAME);
}
export const APP_DIR = appDir;
export const PROXER_PATHS = {
ROOT: '/',
LOGIN: '/component/user/?task=user.login',
API_LOGIN: '/login?format=json&action=login',
WATCHLIST: '/ucp?s=reminder',
OWN_PROFILE: '/user',
NEWS: '/news',
NEWS_API: '/notifications?format=json&s=news&p=1',
CONVERSATIONS_API: '/messages/?format=json&json=conferences',
CONVERSATION_PAGE: '/messages/?id=',
CONVERSATION_FAVORITES: '/messages/favourite',
CONVERSATION_MARK_FAVORITE: '/messages/?format=json&json=favour&id=',
CONVERSATION_UNMARK_FAVORITE: '/messages/?format=json&json=unfavour&id=',
CONVERSATION_MARK_BLOCKED: '/messages/?format=json&json=block&id=',
CONVERSATION_UNMARK_BLOCKED: '/messages/?format=json&json=unblock&id=',
CONVERSATION_REPORT: '/messages/?s=report&format=raw&id=',
CONVERSATION_NEW_CONFERENCE: "/messages/?format=json&json=newConference",
CONVERSATION_NEW: "/messages/?format=json&json=new",
MESSAGE_API: '/messages/?format=json&json=messages&id=',
MESSAGE_NEW_API: '/messages/?format=json&json=newmessages&id=',
MESSAGE_WRITE_API: '/messages/?format=json&json=answer&id=',
MESSAGE_NOTIFICATIONS: '/messages?format=raw&s=notification',
WATCH_ANIME: '/watch/%d/%d/%s',
VIEW_MANGA: '/chapter/%d/%d/%s',
LOGOUT: '/component/users/?task=user.logout',
DELETE_WATCHLIST: '/ucp?format=json&type=deleteReminder&id='
};
export const API_PATHS = {
USER: {
LOGIN: "/user/login",
LOGOUT: "/user/logout",
PROFILE: "/user/userinfo"
},
WATCHLIST: {
GET: "/ucp/reminder",
REMOVE: "/ucp/deletereminder",
SET: "/ucp/setreminder",
SET_EPISODE: "/ucp/setcommentstate"
},
ANIME: {
UPDATE_STATUS: "/info/setuserinfo"
},
QUERY: {
USERS: "/user/list",
SEARCH: "/list/entrysearch",
},
MESSAGES: {
CONSTANTS: "/messenger/constants",
CONFERENCES: "/messenger/conferences",
CONFERENCE_INFO: "/messenger/conferenceinfo",
MESSAGES: "/messenger/messages",
WRITE_MESSAGE: "/messenger/setmessage",
NEW_CONVERSATION: "/messenger/newconference",
NEW_CONFERENCE: "/messenger/newconferencegroup",
REPORT: "/messenger/report",
MARK_READ: "/messenger/setread",
MARK_UNREAD: "/messenger/setunread",
BLOCK: "/messenger/setblock",
UNBLOCK: "/messenger/setunblock",
FAVORITE: "/messenger/setfavour",
UNFAVORITE: "/messenger/setunfavour"
},
NOTIFICATIONS: {
NEWS: "/notifications/news",
AMOUNT: "/notifications/count",
CLEAR: "/notifications/delete"
},
UCP: {
ANIME_MANGA_LIST: "/ucp/list",
SET_COMMENT_STATE: "/ucp/setcommentstate" | }
};
export const Errors = {
CONNECTION: {
NO_NETWORK: 'ERROR.CONNECTION_NO_NETWORK',
UNABLE_TO_RESOLVE: 'ERROR.CONNECTION_NO_RESOLVE',
TIMEOUT: 'ERROR.CONNECTION_TIMEOUT',
NOT_FOUND: 'ERROR.CONNECTION_NOT_FOUND',
NO_CACHE: 'ERROR.CONNECTION_NO_CACHE_AVAILABLE',
NETWORK_RECONNECT: 'ERROR.CONNECTION_RECONNECT'
},
PROXER: {
OFFLINE: 'ERROR.PROXER_OFFLINE',
INVALID_CREDENTIALS: 'ERROR.PROXER_INVALID_CREDENTIALS',
NO_DETAILS_PROVIDED: 'ERROR.PROXER_NO_DETAILS',
MYSQL_DOWN: 'ERROR.PROXER_MYSQL_ERROR',
CLOUDFLARE: 'ERROR.PROXER_CLOUDFLARE_PROTECTION',
API_LIMIT_REACHED: 'ERROR.PROXER_API_LIMIT'
},
STREAMS: {
CANNOT_PARSE: 'ERROR.STREAM_NO_PARSER'
},
OTHER: {
UNKNOWN: 'ERROR.UNKNOWN_ERROR',
CACHE_CLEAR: 'ERROR.CACHE_CLEAR'
},
SEVERITY: {
SEVERE: 'ERROR_SEVERITY.severe',
WARNING: 'ERROR_SEVERITY.warn',
INFO: 'ERROR_SEVERITY.info'
}
}; | random_line_split | |
fault.service.ts | import { TimeAndDateService,Date } from './../time_and_date/time-and-date.service';
import { Injectable } from '@angular/core';
@Injectable()
export class FaultService { //this service used to get, update and delete faults
constructor() { }
getFaults(){
let list:Fault[]=[]; //for testing generate static 10 faultes
for(var i=1;i<6;i++)
{
list.push( new Fault(i,4,101,"ื ืืกืื",false,new Date(2018,2,14),new Date(2018,2,14),"ืจืื","ืืืืงื"));
}
for(var i=6;i<11;i++)
{
list.push( new Fault(i,6,69,"ืืืฆืขืืช",true,new Date(2018,2,20),new Date(2018,2,20),"ืื ื","ืืืืงื"));
}
return list;
}
}
export class Fault{
//this class describe how fault neet to seems
constructor(
private _id:number,
private _base:number,
private _site:number,
private _system:string,
private _state:boolean, //ืื ืืชืงืื ืืฉืืืชื ืื ืืืจืืื ืืฉืจืืืืช TRUE=ืืฉืืืช FALSE=ืฉืจืืืืช
private _startTime:Date,
private _endTime:Date,
private _contact:string,
private _remarks:string){}
get id(){return this._id;}
get base(){return this._base;}
get site(){return this._site;}
get system(){return this._system;}
get state(){return this._state;}
get startTime(){return this._startTime;}
get endTime(){return this._endTime;}
get contact(){return this._contact;}
| this._remarks;}
}
class Base { //class for base include the number of the base and its name and sites. for example base 6 Hatzerim
constructor(
private _id: number,
private _name: string,
private _sites: string[]) { }
get id(){return this._id;}
get name(){return this._name;}
get sites(){return this._sites;}
}
| get remarks(){return | identifier_body |
fault.service.ts | import { TimeAndDateService,Date } from './../time_and_date/time-and-date.service';
import { Injectable } from '@angular/core';
@Injectable()
export class FaultService { //this service used to get, update and delete faults
constructor() { }
getFaults(){
let list:Fault[]=[]; //for testing generate static 10 faultes
for(var i=1;i<6;i++)
{
list.push( new Fault(i,4,101,"ื ืืกืื",false,new Date(2018,2,14),new Date(2018,2,14),"ืจืื","ืืืืงื"));
}
for(var i=6;i<11;i++)
{
list.push( new Fault(i,6,69,"ืืืฆืขืืช",true,new Date(2018,2,20),new Date(2018,2,20),"ืื ื","ืืืืงื"));
}
return list;
}
}
export class Fault{
//this class describe how fault neet to seems
constructor(
private _id:number,
private _base:number,
private _site:number,
private _system:string,
private _state:boolean, //ืื ืืชืงืื ืืฉืืืชื ืื ืืืจืืื ืืฉืจืืืืช TRUE=ืืฉืืืช FALSE=ืฉืจืืืืช
private _startTime:Date,
private _endTime:Date,
private _contact:string,
private _remarks:string){}
get id(){return this._id;}
get base(){return this._base;}
get site(){return this._site;}
get system(){return this._system;}
get state(){return this._state;}
get startTime(){return this._startTime;}
get endTime(){return this._endTime;}
get contact(){return this._contact;}
get remarks(){return this._remarks;}
}
class Base { //class for base include the number of the base and its name and sites. for example base 6 Hatzerim
constructor(
private _id: number,
private _name: string,
private _sites: string[]) { }
get id(){return this._id;}
get name(){return this._name;}
get | tes(){return this._sites;}
}
| si | identifier_name |
fault.service.ts | import { TimeAndDateService,Date } from './../time_and_date/time-and-date.service';
import { Injectable } from '@angular/core';
@Injectable()
export class FaultService { //this service used to get, update and delete faults
constructor() { }
getFaults(){
let list:Fault[]=[]; //for testing generate static 10 faultes
for(var i=1;i<6;i++)
{
list.push( new Fault(i,4,101,"ื ืืกืื",false,new Date(2018,2,14),new Date(2018,2,14),"ืจืื","ืืืืงื"));
}
for(var i=6;i<11;i++)
{
list.push( new Fault(i,6,69,"ืืืฆืขืืช",true,new Date(2018,2,20),new Date(2018,2,20),"ืื ื","ืืืืงื"));
}
return list;
}
}
export class Fault{
//this class describe how fault neet to seems
constructor(
private _id:number,
private _base:number,
private _site:number,
private _system:string,
private _state:boolean, //ืื ืืชืงืื ืืฉืืืชื ืื ืืืจืืื ืืฉืจืืืืช TRUE=ืืฉืืืช FALSE=ืฉืจืืืืช
private _startTime:Date,
private _endTime:Date,
private _contact:string,
private _remarks:string){}
get id(){return this._id;}
get base(){return this._base;}
get site(){return this._site;}
get system(){return this._system;}
get state(){return this._state;} |
class Base { //class for base include the number of the base and its name and sites. for example base 6 Hatzerim
constructor(
private _id: number,
private _name: string,
private _sites: string[]) { }
get id(){return this._id;}
get name(){return this._name;}
get sites(){return this._sites;}
} | get startTime(){return this._startTime;}
get endTime(){return this._endTime;}
get contact(){return this._contact;}
get remarks(){return this._remarks;}
} | random_line_split |
fault.service.ts | import { TimeAndDateService,Date } from './../time_and_date/time-and-date.service';
import { Injectable } from '@angular/core';
@Injectable()
export class FaultService { //this service used to get, update and delete faults
constructor() { }
getFaults(){
let list:Fault[]=[]; //for testing generate static 10 faultes
for(var i=1;i<6;i++)
| i=6;i<11;i++)
{
list.push( new Fault(i,6,69,"ืืืฆืขืืช",true,new Date(2018,2,20),new Date(2018,2,20),"ืื ื","ืืืืงื"));
}
return list;
}
}
export class Fault{
//this class describe how fault neet to seems
constructor(
private _id:number,
private _base:number,
private _site:number,
private _system:string,
private _state:boolean, //ืื ืืชืงืื ืืฉืืืชื ืื ืืืจืืื ืืฉืจืืืืช TRUE=ืืฉืืืช FALSE=ืฉืจืืืืช
private _startTime:Date,
private _endTime:Date,
private _contact:string,
private _remarks:string){}
get id(){return this._id;}
get base(){return this._base;}
get site(){return this._site;}
get system(){return this._system;}
get state(){return this._state;}
get startTime(){return this._startTime;}
get endTime(){return this._endTime;}
get contact(){return this._contact;}
get remarks(){return this._remarks;}
}
class Base { //class for base include the number of the base and its name and sites. for example base 6 Hatzerim
constructor(
private _id: number,
private _name: string,
private _sites: string[]) { }
get id(){return this._id;}
get name(){return this._name;}
get sites(){return this._sites;}
}
| {
list.push( new Fault(i,4,101,"ื ืืกืื",false,new Date(2018,2,14),new Date(2018,2,14),"ืจืื","ืืืืงื"));
}
for(var | conditional_block |
hud.rs | use super::wad_system::WadSystem;
use engine::{
ControlFlow, DependenciesFrom, Gesture, InfallibleSystem, Input, Scancode, TextId,
TextRenderer, Window,
};
use math::prelude::*;
use math::Pnt2f;
pub struct Bindings {
pub quit: Gesture,
pub next_level: Gesture,
pub previous_level: Gesture,
pub toggle_mouse: Gesture,
pub toggle_help: Gesture,
}
impl Default for Bindings {
fn default() -> Self {
Bindings {
quit: Gesture::AnyOf(vec![
Gesture::QuitTrigger,
Gesture::KeyTrigger(Scancode::Escape),
]),
next_level: Gesture::AllOf(vec![
Gesture::KeyHold(Scancode::LControl),
Gesture::KeyTrigger(Scancode::N),
]),
previous_level: Gesture::AllOf(vec![
Gesture::KeyHold(Scancode::LControl),
Gesture::KeyTrigger(Scancode::P),
]),
toggle_mouse: Gesture::KeyTrigger(Scancode::Grave),
toggle_help: Gesture::KeyTrigger(Scancode::H),
}
}
}
#[derive(DependenciesFrom)]
pub struct Dependencies<'context> {
bindings: &'context Bindings,
window: &'context Window,
input: &'context mut Input,
text: &'context mut TextRenderer,
control_flow: &'context mut ControlFlow,
wad: &'context mut WadSystem,
}
pub struct Hud {
mouse_grabbed: bool,
current_help: HelpState,
prompt_text: TextId,
help_text: TextId,
}
impl<'context> InfallibleSystem<'context> for Hud {
type Dependencies = Dependencies<'context>;
fn debug_name() -> &'static str {
"hud"
}
fn create(deps: Dependencies) -> Self {
deps.input.set_mouse_enabled(true);
deps.input.set_cursor_grabbed(true);
let prompt_text = deps
.text
.insert(deps.window, PROMPT_TEXT, Pnt2f::origin(), HELP_PADDING);
let help_text = deps
.text
.insert(deps.window, HELP_TEXT, Pnt2f::origin(), HELP_PADDING);
deps.text[help_text].set_visible(false);
Hud {
prompt_text,
help_text,
mouse_grabbed: true,
current_help: HelpState::Prompt,
}
}
fn update(&mut self, deps: Dependencies) {
let Dependencies {
input,
text,
control_flow,
bindings,
..
} = deps;
if input.poll_gesture(&bindings.quit) {
control_flow.quit_requested = true
}
if input.poll_gesture(&bindings.toggle_mouse) {
self.mouse_grabbed = !self.mouse_grabbed;
input.set_mouse_enabled(self.mouse_grabbed);
input.set_cursor_grabbed(self.mouse_grabbed);
}
if input.poll_gesture(&bindings.toggle_help) {
self.current_help = match self.current_help {
HelpState::Prompt => {
text[self.prompt_text].set_visible(false);
text[self.help_text].set_visible(true);
HelpState::Shown
}
HelpState::Shown => {
text[self.help_text].set_visible(false);
HelpState::Hidden
}
HelpState::Hidden => {
text[self.help_text].set_visible(true);
HelpState::Shown
}
};
}
if input.poll_gesture(&bindings.next_level) {
let index = deps.wad.level_index();
deps.wad.change_level(index + 1);
} else if input.poll_gesture(&bindings.previous_level) {
let index = deps.wad.level_index();
if index > 0 |
}
}
fn teardown(&mut self, deps: Dependencies) {
deps.text.remove(self.help_text);
deps.text.remove(self.prompt_text);
}
}
enum HelpState {
Prompt,
Shown,
Hidden,
}
const HELP_PADDING: u32 = 6;
const PROMPT_TEXT: &str = "WASD and mouse, 'E' to push/use, LB to shoot or 'h' for help.";
const HELP_TEXT: &str = r"Use WASD to move and the mouse or arrow keys to aim.
Other keys:
ESC - to quit
SPACEBAR - jump
E - push/interact/use
Left Click - shoot (only effect is to trigger gun-activated things)
` - to toggle mouse grab (backtick)
f - to toggle fly mode
c - to toggle clipping (wall collisions)
Ctrl-N - to change to next level (though using the exit will also do this!)
Ctrl-P - to change to previous level
h - toggle this help message";
| {
deps.wad.change_level(index - 1);
} | conditional_block |
hud.rs | use super::wad_system::WadSystem;
use engine::{
ControlFlow, DependenciesFrom, Gesture, InfallibleSystem, Input, Scancode, TextId,
TextRenderer, Window,
};
use math::prelude::*;
use math::Pnt2f;
pub struct Bindings {
pub quit: Gesture,
pub next_level: Gesture,
pub previous_level: Gesture,
pub toggle_mouse: Gesture,
pub toggle_help: Gesture,
}
impl Default for Bindings {
fn default() -> Self {
Bindings {
quit: Gesture::AnyOf(vec![
Gesture::QuitTrigger,
Gesture::KeyTrigger(Scancode::Escape),
]),
next_level: Gesture::AllOf(vec![
Gesture::KeyHold(Scancode::LControl),
Gesture::KeyTrigger(Scancode::N),
]),
previous_level: Gesture::AllOf(vec![
Gesture::KeyHold(Scancode::LControl),
Gesture::KeyTrigger(Scancode::P),
]),
toggle_mouse: Gesture::KeyTrigger(Scancode::Grave),
toggle_help: Gesture::KeyTrigger(Scancode::H),
}
}
}
#[derive(DependenciesFrom)]
pub struct Dependencies<'context> {
bindings: &'context Bindings,
window: &'context Window,
input: &'context mut Input,
text: &'context mut TextRenderer,
control_flow: &'context mut ControlFlow,
wad: &'context mut WadSystem,
}
pub struct Hud {
mouse_grabbed: bool,
current_help: HelpState,
prompt_text: TextId,
help_text: TextId,
}
impl<'context> InfallibleSystem<'context> for Hud {
type Dependencies = Dependencies<'context>;
fn debug_name() -> &'static str {
"hud"
}
fn create(deps: Dependencies) -> Self {
deps.input.set_mouse_enabled(true);
deps.input.set_cursor_grabbed(true);
let prompt_text = deps
.text
.insert(deps.window, PROMPT_TEXT, Pnt2f::origin(), HELP_PADDING);
let help_text = deps
.text
.insert(deps.window, HELP_TEXT, Pnt2f::origin(), HELP_PADDING);
deps.text[help_text].set_visible(false);
Hud {
prompt_text,
help_text,
mouse_grabbed: true,
current_help: HelpState::Prompt,
}
}
fn update(&mut self, deps: Dependencies) {
let Dependencies {
input,
text,
control_flow,
bindings,
..
} = deps;
if input.poll_gesture(&bindings.quit) {
control_flow.quit_requested = true
}
if input.poll_gesture(&bindings.toggle_mouse) {
self.mouse_grabbed = !self.mouse_grabbed;
input.set_mouse_enabled(self.mouse_grabbed);
input.set_cursor_grabbed(self.mouse_grabbed);
}
if input.poll_gesture(&bindings.toggle_help) {
self.current_help = match self.current_help {
HelpState::Prompt => {
text[self.prompt_text].set_visible(false);
text[self.help_text].set_visible(true);
HelpState::Shown
}
HelpState::Shown => {
text[self.help_text].set_visible(false);
HelpState::Hidden
}
HelpState::Hidden => {
text[self.help_text].set_visible(true);
HelpState::Shown
}
};
}
if input.poll_gesture(&bindings.next_level) {
let index = deps.wad.level_index();
deps.wad.change_level(index + 1);
} else if input.poll_gesture(&bindings.previous_level) {
let index = deps.wad.level_index();
if index > 0 {
deps.wad.change_level(index - 1);
}
}
}
fn | (&mut self, deps: Dependencies) {
deps.text.remove(self.help_text);
deps.text.remove(self.prompt_text);
}
}
enum HelpState {
Prompt,
Shown,
Hidden,
}
const HELP_PADDING: u32 = 6;
const PROMPT_TEXT: &str = "WASD and mouse, 'E' to push/use, LB to shoot or 'h' for help.";
const HELP_TEXT: &str = r"Use WASD to move and the mouse or arrow keys to aim.
Other keys:
ESC - to quit
SPACEBAR - jump
E - push/interact/use
Left Click - shoot (only effect is to trigger gun-activated things)
` - to toggle mouse grab (backtick)
f - to toggle fly mode
c - to toggle clipping (wall collisions)
Ctrl-N - to change to next level (though using the exit will also do this!)
Ctrl-P - to change to previous level
h - toggle this help message";
| teardown | identifier_name |
hud.rs | use super::wad_system::WadSystem;
use engine::{
ControlFlow, DependenciesFrom, Gesture, InfallibleSystem, Input, Scancode, TextId,
TextRenderer, Window,
};
use math::prelude::*;
use math::Pnt2f;
pub struct Bindings {
pub quit: Gesture,
pub next_level: Gesture,
pub previous_level: Gesture,
pub toggle_mouse: Gesture,
pub toggle_help: Gesture,
}
impl Default for Bindings {
fn default() -> Self {
Bindings {
quit: Gesture::AnyOf(vec![
Gesture::QuitTrigger,
Gesture::KeyTrigger(Scancode::Escape),
]),
next_level: Gesture::AllOf(vec![
Gesture::KeyHold(Scancode::LControl),
Gesture::KeyTrigger(Scancode::N),
]),
previous_level: Gesture::AllOf(vec![
Gesture::KeyHold(Scancode::LControl),
Gesture::KeyTrigger(Scancode::P),
]),
toggle_mouse: Gesture::KeyTrigger(Scancode::Grave),
toggle_help: Gesture::KeyTrigger(Scancode::H),
}
}
}
#[derive(DependenciesFrom)]
pub struct Dependencies<'context> {
bindings: &'context Bindings,
window: &'context Window,
input: &'context mut Input,
text: &'context mut TextRenderer,
control_flow: &'context mut ControlFlow,
wad: &'context mut WadSystem,
}
pub struct Hud {
mouse_grabbed: bool,
current_help: HelpState,
prompt_text: TextId,
help_text: TextId,
}
impl<'context> InfallibleSystem<'context> for Hud {
type Dependencies = Dependencies<'context>;
fn debug_name() -> &'static str {
"hud"
}
fn create(deps: Dependencies) -> Self {
deps.input.set_mouse_enabled(true);
deps.input.set_cursor_grabbed(true);
let prompt_text = deps
.text
.insert(deps.window, PROMPT_TEXT, Pnt2f::origin(), HELP_PADDING);
let help_text = deps
.text
.insert(deps.window, HELP_TEXT, Pnt2f::origin(), HELP_PADDING);
deps.text[help_text].set_visible(false);
Hud {
prompt_text,
help_text,
mouse_grabbed: true,
current_help: HelpState::Prompt,
}
}
fn update(&mut self, deps: Dependencies) {
let Dependencies {
input,
text,
control_flow,
bindings,
..
} = deps;
if input.poll_gesture(&bindings.quit) {
control_flow.quit_requested = true
}
if input.poll_gesture(&bindings.toggle_mouse) {
self.mouse_grabbed = !self.mouse_grabbed;
input.set_mouse_enabled(self.mouse_grabbed);
input.set_cursor_grabbed(self.mouse_grabbed);
}
if input.poll_gesture(&bindings.toggle_help) {
self.current_help = match self.current_help {
HelpState::Prompt => { | text[self.prompt_text].set_visible(false);
text[self.help_text].set_visible(true);
HelpState::Shown
}
HelpState::Shown => {
text[self.help_text].set_visible(false);
HelpState::Hidden
}
HelpState::Hidden => {
text[self.help_text].set_visible(true);
HelpState::Shown
}
};
}
if input.poll_gesture(&bindings.next_level) {
let index = deps.wad.level_index();
deps.wad.change_level(index + 1);
} else if input.poll_gesture(&bindings.previous_level) {
let index = deps.wad.level_index();
if index > 0 {
deps.wad.change_level(index - 1);
}
}
}
fn teardown(&mut self, deps: Dependencies) {
deps.text.remove(self.help_text);
deps.text.remove(self.prompt_text);
}
}
enum HelpState {
Prompt,
Shown,
Hidden,
}
const HELP_PADDING: u32 = 6;
const PROMPT_TEXT: &str = "WASD and mouse, 'E' to push/use, LB to shoot or 'h' for help.";
const HELP_TEXT: &str = r"Use WASD to move and the mouse or arrow keys to aim.
Other keys:
ESC - to quit
SPACEBAR - jump
E - push/interact/use
Left Click - shoot (only effect is to trigger gun-activated things)
` - to toggle mouse grab (backtick)
f - to toggle fly mode
c - to toggle clipping (wall collisions)
Ctrl-N - to change to next level (though using the exit will also do this!)
Ctrl-P - to change to previous level
h - toggle this help message"; | random_line_split | |
custom_tests.rs | extern crate rusoto_mock;
use crate::generated::{LexRuntime, LexRuntimeClient, PostTextRequest, PostTextResponse}; | #[tokio::test]
async fn test_post_text_resposnse_serialization() {
let mock_resp_body = r#"{
"dialogState": "ElicitSlot",
"intentName": "BookCar",
"message": "In what city do you need to rent a car?",
"messageFormat": "PlainText",
"responseCard": null,
"sessionAttributes": {},
"slotToElicit": "PickUpCity",
"slots": {
"CarType": null,
"PickUpCity": "Boston"
}
}"#;
let mock_request = MockRequestDispatcher::with_status(200).with_body(mock_resp_body);
let lex_client =
LexRuntimeClient::new_with(mock_request, MockCredentialsProvider, Region::UsEast1);
let post_text_req = PostTextRequest {
input_text: "Book a car".to_owned(),
user_id: "rs".to_owned(),
..Default::default()
};
let mut slots = HashMap::new();
slots.insert("CarType".to_owned(), None);
slots.insert("PickUpCity".to_owned(), Some("Boston".to_owned()));
let expected = PostTextResponse {
active_contexts: None,
alternative_intents: None,
bot_version: None,
dialog_state: Some("ElicitSlot".to_owned()),
intent_name: Some("BookCar".to_owned()),
message: Some("In what city do you need to rent a car?".to_owned()),
message_format: Some("PlainText".to_owned()),
nlu_intent_confidence: None,
slot_to_elicit: Some("PickUpCity".to_owned()),
slots: Some(slots),
response_card: None,
session_attributes: Some(HashMap::new()),
sentiment_response: None,
session_id: None,
};
let result: PostTextResponse = lex_client.post_text(post_text_req).await.unwrap();
assert_eq!(result, expected);
} | use rusoto_core::Region;
use std::collections::HashMap;
use self::rusoto_mock::*;
| random_line_split |
custom_tests.rs | extern crate rusoto_mock;
use crate::generated::{LexRuntime, LexRuntimeClient, PostTextRequest, PostTextResponse};
use rusoto_core::Region;
use std::collections::HashMap;
use self::rusoto_mock::*;
#[tokio::test]
async fn | () {
let mock_resp_body = r#"{
"dialogState": "ElicitSlot",
"intentName": "BookCar",
"message": "In what city do you need to rent a car?",
"messageFormat": "PlainText",
"responseCard": null,
"sessionAttributes": {},
"slotToElicit": "PickUpCity",
"slots": {
"CarType": null,
"PickUpCity": "Boston"
}
}"#;
let mock_request = MockRequestDispatcher::with_status(200).with_body(mock_resp_body);
let lex_client =
LexRuntimeClient::new_with(mock_request, MockCredentialsProvider, Region::UsEast1);
let post_text_req = PostTextRequest {
input_text: "Book a car".to_owned(),
user_id: "rs".to_owned(),
..Default::default()
};
let mut slots = HashMap::new();
slots.insert("CarType".to_owned(), None);
slots.insert("PickUpCity".to_owned(), Some("Boston".to_owned()));
let expected = PostTextResponse {
active_contexts: None,
alternative_intents: None,
bot_version: None,
dialog_state: Some("ElicitSlot".to_owned()),
intent_name: Some("BookCar".to_owned()),
message: Some("In what city do you need to rent a car?".to_owned()),
message_format: Some("PlainText".to_owned()),
nlu_intent_confidence: None,
slot_to_elicit: Some("PickUpCity".to_owned()),
slots: Some(slots),
response_card: None,
session_attributes: Some(HashMap::new()),
sentiment_response: None,
session_id: None,
};
let result: PostTextResponse = lex_client.post_text(post_text_req).await.unwrap();
assert_eq!(result, expected);
}
| test_post_text_resposnse_serialization | identifier_name |
custom_tests.rs | extern crate rusoto_mock;
use crate::generated::{LexRuntime, LexRuntimeClient, PostTextRequest, PostTextResponse};
use rusoto_core::Region;
use std::collections::HashMap;
use self::rusoto_mock::*;
#[tokio::test]
async fn test_post_text_resposnse_serialization() | {
let mock_resp_body = r#"{
"dialogState": "ElicitSlot",
"intentName": "BookCar",
"message": "In what city do you need to rent a car?",
"messageFormat": "PlainText",
"responseCard": null,
"sessionAttributes": {},
"slotToElicit": "PickUpCity",
"slots": {
"CarType": null,
"PickUpCity": "Boston"
}
}"#;
let mock_request = MockRequestDispatcher::with_status(200).with_body(mock_resp_body);
let lex_client =
LexRuntimeClient::new_with(mock_request, MockCredentialsProvider, Region::UsEast1);
let post_text_req = PostTextRequest {
input_text: "Book a car".to_owned(),
user_id: "rs".to_owned(),
..Default::default()
};
let mut slots = HashMap::new();
slots.insert("CarType".to_owned(), None);
slots.insert("PickUpCity".to_owned(), Some("Boston".to_owned()));
let expected = PostTextResponse {
active_contexts: None,
alternative_intents: None,
bot_version: None,
dialog_state: Some("ElicitSlot".to_owned()),
intent_name: Some("BookCar".to_owned()),
message: Some("In what city do you need to rent a car?".to_owned()),
message_format: Some("PlainText".to_owned()),
nlu_intent_confidence: None,
slot_to_elicit: Some("PickUpCity".to_owned()),
slots: Some(slots),
response_card: None,
session_attributes: Some(HashMap::new()),
sentiment_response: None,
session_id: None,
};
let result: PostTextResponse = lex_client.post_text(post_text_req).await.unwrap();
assert_eq!(result, expected);
} | identifier_body | |
removeformatting.js | // Copyright 2008 The Closure Library Authors. All Rights Reserved.
//
// 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.
// All Rights Reserved.
/**
* @fileoverview Plugin to handle Remove Formatting.
*
*/
goog.provide('goog.editor.plugins.RemoveFormatting');
goog.require('goog.dom');
goog.require('goog.dom.NodeType');
goog.require('goog.dom.Range');
goog.require('goog.dom.TagName');
goog.require('goog.editor.BrowserFeature');
goog.require('goog.editor.Plugin');
goog.require('goog.editor.node');
goog.require('goog.editor.range');
goog.require('goog.string');
goog.require('goog.userAgent');
/**
* A plugin to handle removing formatting from selected text.
* @constructor
* @extends {goog.editor.Plugin}
* @final
*/
goog.editor.plugins.RemoveFormatting = function() {
goog.editor.Plugin.call(this);
/**
* Optional function to perform remove formatting in place of the
* provided removeFormattingWorker_.
* @type {?function(string): string}
* @private
*/
this.optRemoveFormattingFunc_ = null;
};
goog.inherits(goog.editor.plugins.RemoveFormatting, goog.editor.Plugin);
/**
* The editor command this plugin in handling.
* @type {string}
*/
goog.editor.plugins.RemoveFormatting.REMOVE_FORMATTING_COMMAND =
'+removeFormat';
/**
* Regular expression that matches a block tag name.
* @type {RegExp}
* @private
*/
goog.editor.plugins.RemoveFormatting.BLOCK_RE_ =
/^(DIV|TR|LI|BLOCKQUOTE|H\d|PRE|XMP)/;
/**
* Appends a new line to a string buffer.
* @param {Array.<string>} sb The string buffer to add to.
* @private
*/
goog.editor.plugins.RemoveFormatting.appendNewline_ = function(sb) {
sb.push('<br>');
};
/**
* Create a new range delimited by the start point of the first range and
* the end point of the second range.
* @param {goog.dom.AbstractRange} startRange Use the start point of this
* range as the beginning of the new range.
* @param {goog.dom.AbstractRange} endRange Use the end point of this
* range as the end of the new range.
* @return {!goog.dom.AbstractRange} The new range.
* @private
*/
goog.editor.plugins.RemoveFormatting.createRangeDelimitedByRanges_ = function(
startRange, endRange) {
return goog.dom.Range.createFromNodes(
startRange.getStartNode(), startRange.getStartOffset(),
endRange.getEndNode(), endRange.getEndOffset());
};
/** @override */
goog.editor.plugins.RemoveFormatting.prototype.getTrogClassId = function() {
return 'RemoveFormatting';
};
/** @override */
goog.editor.plugins.RemoveFormatting.prototype.isSupportedCommand = function(
command) {
return command ==
goog.editor.plugins.RemoveFormatting.REMOVE_FORMATTING_COMMAND;
};
/** @override */
goog.editor.plugins.RemoveFormatting.prototype.execCommandInternal =
function(command, var_args) {
if (command ==
goog.editor.plugins.RemoveFormatting.REMOVE_FORMATTING_COMMAND) {
this.removeFormatting_();
}
};
/** @override */
goog.editor.plugins.RemoveFormatting.prototype.handleKeyboardShortcut =
function(e, key, isModifierPressed) {
if (!isModifierPressed) {
return false;
}
if (key == ' ') {
this.getFieldObject().execCommand(
goog.editor.plugins.RemoveFormatting.REMOVE_FORMATTING_COMMAND);
return true;
}
return false;
};
/**
* Removes formatting from the current selection. Removes basic formatting
* (B/I/U) using the browser's execCommand. Then extracts the html from the
* selection to convert, calls either a client's specified removeFormattingFunc
* callback or trogedit's general built-in removeFormattingWorker_,
* and then replaces the current selection with the converted text.
* @private
*/
goog.editor.plugins.RemoveFormatting.prototype.removeFormatting_ = function() {
var range = this.getFieldObject().getRange();
if (range.isCollapsed()) {
return;
}
// Get the html to format and send it off for formatting. Built in
// removeFormat only strips some inline elements and some inline CSS styles
var convFunc = this.optRemoveFormattingFunc_ ||
goog.bind(this.removeFormattingWorker_, this);
this.convertSelectedHtmlText_(convFunc);
// Do the execCommand last as it needs block elements removed to work
// properly on background/fontColor in FF. There are, unfortunately, still
// cases where background/fontColor are not removed here.
var doc = this.getFieldDomHelper().getDocument();
doc.execCommand('RemoveFormat', false, undefined);
if (goog.editor.BrowserFeature.ADDS_NBSPS_IN_REMOVE_FORMAT) {
// WebKit converts spaces to non-breaking spaces when doing a RemoveFormat.
// See: https://bugs.webkit.org/show_bug.cgi?id=14062
this.convertSelectedHtmlText_(function(text) {
// This loses anything that might have legitimately been a non-breaking
// space, but that's better than the alternative of only having non-
// breaking spaces.
// Old versions of WebKit (Safari 3, Chrome 1) incorrectly match /u00A0
// and newer versions properly match .
var nbspRegExp =
goog.userAgent.isVersionOrHigher('528') ? / /g : /\u00A0/g;
return text.replace(nbspRegExp, ' ');
});
}
};
/**
* Finds the nearest ancestor of the node that is a table.
* @param {Node} nodeToCheck Node to search from.
* @return {Node} The table, or null if one was not found.
* @private
*/
goog.editor.plugins.RemoveFormatting.prototype.getTableAncestor_ = function(
nodeToCheck) {
var fieldElement = this.getFieldObject().getElement();
while (nodeToCheck && nodeToCheck != fieldElement) {
if (nodeToCheck.tagName == goog.dom.TagName.TABLE) {
return nodeToCheck;
}
nodeToCheck = nodeToCheck.parentNode;
}
return null;
};
/**
* Replaces the contents of the selection with html. Does its best to maintain
* the original selection. Also does its best to result in a valid DOM.
*
* TODO(user): See if there's any way to make this work on Ranges, and then
* move it into goog.editor.range. The Firefox implementation uses execCommand
* on the document, so must work on the actual selection.
*
* @param {string} html The html string to insert into the range.
* @private
*/
goog.editor.plugins.RemoveFormatting.prototype.pasteHtml_ = function(html) {
var range = this.getFieldObject().getRange();
var dh = this.getFieldDomHelper();
// Use markers to set the extent of the selection so that we can reselect it
// afterwards. This works better than builtin range manipulation in FF and IE
// because their implementations are so self-inconsistent and buggy.
var startSpanId = goog.string.createUniqueString();
var endSpanId = goog.string.createUniqueString();
html = '<span id="' + startSpanId + '"></span>' + html +
'<span id="' + endSpanId + '"></span>';
var dummyNodeId = goog.string.createUniqueString();
var dummySpanText = '<span id="' + dummyNodeId + '"></span>';
if (goog.editor.BrowserFeature.HAS_IE_RANGES) {
// IE's selection often doesn't include the outermost tags.
// We want to use pasteHTML to replace the range contents with the newly
// unformatted text, so we have to check to make sure we aren't just
// pasting into some stray tags. To do this, we first clear out the
// contents of the range and then delete all empty nodes parenting the now
// empty range. This way, the pasted contents are never re-embedded into
// formated nodes. Pasting purely empty html does not work, since IE moves
// the selection inside the next node, so we insert a dummy span.
var textRange = range.getTextRange(0).getBrowserRangeObject();
textRange.pasteHTML(dummySpanText);
var parent;
while ((parent = textRange.parentElement()) &&
goog.editor.node.isEmpty(parent) &&
!goog.editor.node.isEditableContainer(parent)) {
var tag = parent.nodeName;
// We can't remove these table tags as it will invalidate the table dom.
if (tag == goog.dom.TagName.TD ||
tag == goog.dom.TagName.TR ||
tag == goog.dom.TagName.TH) {
break;
}
goog.dom.removeNode(parent);
}
textRange.pasteHTML(html);
var dummySpan = dh.getElement(dummyNodeId);
// If we entered the while loop above, the node has already been removed
// since it was a child of parent and parent was removed.
if (dummySpan) {
goog.dom.removeNode(dummySpan);
}
} else if (goog.editor.BrowserFeature.HAS_W3C_RANGES) {
// insertHtml and range.insertNode don't merge blocks correctly.
// (e.g. if your selection spans two paragraphs)
dh.getDocument().execCommand('insertImage', false, dummyNodeId);
var dummyImageNodePattern = new RegExp('<[^<]*' + dummyNodeId + '[^>]*>');
var parent = this.getFieldObject().getRange().getContainerElement();
if (parent.nodeType == goog.dom.NodeType.TEXT) {
// Opera sometimes returns a text node here.
// TODO(user): perhaps we should modify getParentContainer?
parent = parent.parentNode;
}
// We have to search up the DOM because in some cases, notably when
// selecting li's within a list, execCommand('insertImage') actually splits
// tags in such a way that parent that used to contain the selection does
// not contain inserted image.
while (!dummyImageNodePattern.test(parent.innerHTML)) {
parent = parent.parentNode;
}
// Like the IE case above, sometimes the selection does not include the
// outermost tags. For Gecko, we have already expanded the range so that
// it does, so we can just replace the dummy image with the final html.
// For WebKit, we use the same approach as we do with IE - we
// inject a dummy span where we will eventually place the contents, and
// remove parentNodes of the span while they are empty.
if (goog.userAgent.GECKO) {
goog.editor.node.replaceInnerHtml(parent,
parent.innerHTML.replace(dummyImageNodePattern, html));
} else {
goog.editor.node.replaceInnerHtml(parent,
parent.innerHTML.replace(dummyImageNodePattern, dummySpanText));
var dummySpan = dh.getElement(dummyNodeId);
parent = dummySpan;
while ((parent = dummySpan.parentNode) &&
goog.editor.node.isEmpty(parent) &&
!goog.editor.node.isEditableContainer(parent)) {
var tag = parent.nodeName;
// We can't remove these table tags as it will invalidate the table dom.
if (tag == goog.dom.TagName.TD ||
tag == goog.dom.TagName.TR ||
tag == goog.dom.TagName.TH) {
break;
}
// We can't just remove parent since dummySpan is inside it, and we need
// to keep dummy span around for the replacement. So we move the
// dummySpan up as we go.
goog.dom.insertSiblingAfter(dummySpan, parent);
goog.dom.removeNode(parent);
}
goog.editor.node.replaceInnerHtml(parent,
parent.innerHTML.replace(new RegExp(dummySpanText, 'i'), html));
}
}
var startSpan = dh.getElement(startSpanId);
var endSpan = dh.getElement(endSpanId);
goog.dom.Range.createFromNodes(startSpan, 0, endSpan,
endSpan.childNodes.length).select();
goog.dom.removeNode(startSpan);
goog.dom.removeNode(endSpan);
};
/**
* Gets the html inside the selection to send off for further processing.
*
* TODO(user): Make this general so that it can be moved into
* goog.editor.range. The main reason it can't be moved is becuase we need to
* get the range before we do the execCommand and continue to operate on that
* same range (reasons are documented above).
*
* @param {goog.dom.AbstractRange} range The selection.
* @return {string} The html string to format.
* @private
*/
goog.editor.plugins.RemoveFormatting.prototype.getHtmlText_ = function(range) {
var div = this.getFieldDomHelper().createDom('div');
var textRange = range.getBrowserRangeObject();
if (goog.editor.BrowserFeature.HAS_W3C_RANGES) {
// Get the text to convert.
div.appendChild(textRange.cloneContents());
} else if (goog.editor.BrowserFeature.HAS_IE_RANGES) {
// Trim the whitespace on the ends of the range, so that it the container
// will be the container of only the text content that we are changing.
// This gets around issues in IE where the spaces are included in the
// selection, but ignored sometimes by execCommand, and left orphaned.
var rngText = range.getText();
// BRs get reported as \r\n, but only count as one character for moves.
// Adjust the string so our move counter is correct.
rngText = rngText.replace(/\r\n/g, '\r');
var rngTextLength = rngText.length;
var left = rngTextLength - goog.string.trimLeft(rngText).length;
var right = rngTextLength - goog.string.trimRight(rngText).length;
textRange.moveStart('character', left);
textRange.moveEnd('character', -right);
var htmlText = textRange.htmlText;
// Check if in pretag and fix up formatting so that new lines are preserved.
if (textRange.queryCommandValue('formatBlock') == 'Formatted') {
htmlText = goog.string.newLineToBr(textRange.htmlText);
}
div.innerHTML = htmlText;
}
// Get the innerHTML of the node instead of just returning the text above
// so that its properly html escaped.
return div.innerHTML;
};
/**
* Move the range so that it doesn't include any partially selected tables.
* @param {goog.dom.AbstractRange} range The range to adjust.
* @param {Node} startInTable Table node that the range starts in.
* @param {Node} endInTable Table node that the range ends in.
* @return {!goog.dom.SavedCaretRange} Range to use to restore the
* selection after we run our custom remove formatting.
* @private
*/
goog.editor.plugins.RemoveFormatting.prototype.adjustRangeForTables_ =
function(range, startInTable, endInTable) {
// Create placeholders for the current selection so we can restore it
// later.
var savedCaretRange = goog.editor.range.saveUsingNormalizedCarets(range);
var startNode = range.getStartNode();
var startOffset = range.getStartOffset();
var endNode = range.getEndNode();
var endOffset = range.getEndOffset();
var dh = this.getFieldDomHelper();
// Move start after the table.
if (startInTable) {
var textNode = dh.createTextNode('');
goog.dom.insertSiblingAfter(textNode, startInTable);
startNode = textNode;
startOffset = 0;
}
// Move end before the table.
if (endInTable) {
var textNode = dh.createTextNode('');
goog.dom.insertSiblingBefore(textNode, endInTable);
endNode = textNode;
endOffset = 0;
}
goog.dom.Range.createFromNodes(startNode, startOffset,
endNode, endOffset).select();
return savedCaretRange;
};
/**
* Remove a caret from the dom and hide it in a safe place, so it can
* be restored later via restoreCaretsFromCave.
* @param {goog.dom.SavedCaretRange} caretRange The caret range to
* get the carets from.
* @param {boolean} isStart Whether this is the start or end caret.
* @private
*/
goog.editor.plugins.RemoveFormatting.prototype.putCaretInCave_ = function(
caretRange, isStart) {
var cavedCaret = goog.dom.removeNode(caretRange.getCaret(isStart));
if (isStart) {
this.startCaretInCave_ = cavedCaret;
} else {
this.endCaretInCave_ = cavedCaret;
}
};
/**
* Restore carets that were hidden away by adding them back into the dom.
* Note: this does not restore to the original dom location, as that
* will likely have been modified with remove formatting. The only
* guarentees here are that start will still be before end, and that
* they will be in the editable region. This should only be used when
* you don't actually intend to USE the caret again.
* @private
*/
goog.editor.plugins.RemoveFormatting.prototype.restoreCaretsFromCave_ =
function() {
// To keep start before end, we put the end caret at the bottom of the field
// and the start caret at the start of the field.
var field = this.getFieldObject().getElement();
if (this.startCaretInCave_) {
field.insertBefore(this.startCaretInCave_, field.firstChild);
this.startCaretInCave_ = null;
}
if (this.endCaretInCave_) {
field.appendChild(this.endCaretInCave_);
this.endCaretInCave_ = null;
}
};
/**
* Gets the html inside the current selection, passes it through the given
* conversion function, and puts it back into the selection.
*
* @param {function(string): string} convertFunc A conversion function that
* transforms an html string to new html string.
* @private
*/
goog.editor.plugins.RemoveFormatting.prototype.convertSelectedHtmlText_ =
function(convertFunc) {
var range = this.getFieldObject().getRange();
// For multiple ranges, it is really hard to do our custom remove formatting
// without invalidating other ranges. So instead of always losing the
// content, this solution at least lets the browser do its own remove
// formatting which works correctly most of the time.
if (range.getTextRangeCount() > 1) {
return;
}
if (goog.userAgent.GECKO) {
// Determine if we need to handle tables, since they are special cases.
// If the selection is entirely within a table, there is no extra
// formatting removal we can do. If a table is fully selected, we will
// just blow it away. If a table is only partially selected, we can
// perform custom remove formatting only on the non table parts, since we
// we can't just remove the parts and paste back into it (eg. we can't
// inject html where a TR used to be).
// If the selection contains the table and more, this is automatically
// handled, but if just the table is selected, it can be tricky to figure
// this case out, because of the numerous ways selections can be formed -
// ex. if a table has a single tr with a single td with a single text node
// in it, and the selection is (textNode: 0), (textNode: nextNode.length)
// then the entire table is selected, even though the start and end aren't
// the table itself. We are truly inside a table if the expanded endpoints
// are still inside the table.
// Expand the selection to include any outermost tags that weren't included
// in the selection, but have the same visible selection. Stop expanding
// if we reach the top level field.
var expandedRange = goog.editor.range.expand(range,
this.getFieldObject().getElement());
var startInTable = this.getTableAncestor_(expandedRange.getStartNode());
var endInTable = this.getTableAncestor_(expandedRange.getEndNode());
if (startInTable || endInTable) {
if (startInTable == endInTable) {
// We are fully contained in the same table, there is no extra
// remove formatting that we can do, just return and run browser
// formatting only.
return;
}
// Adjust the range to not contain any partially selected tables, since
// we don't want to run our custom remove formatting on them.
var savedCaretRange = this.adjustRangeForTables_(range,
startInTable, endInTable);
// Hack alert!!
// If start is not in a table, then the saved caret will get sent out
// for uber remove formatting, and it will get blown away. This is
// fine, except that we need to be able to re-create a range from the
// savedCaretRange later on. So, we just remove it from the dom, and
// put it back later so we can create a range later (not exactly in the
// same spot, but don't worry we don't actually try to use it later)
// and then it will be removed when we dispose the range.
if (!startInTable) {
this.putCaretInCave_(savedCaretRange, true);
}
if (!endInTable) {
this.putCaretInCave_(savedCaretRange, false);
}
// Re-fetch the range, and re-expand it, since we just modified it.
range = this.getFieldObject().getRange();
expandedRange = goog.editor.range.expand(range,
this.getFieldObject().getElement());
}
expandedRange.select();
range = expandedRange;
}
// Convert the selected text to the format-less version, paste back into
// the selection.
var text = this.getHtmlText_(range);
this.pasteHtml_(convertFunc(text));
if (goog.userAgent.GECKO && savedCaretRange) {
// If we moved the selection, move it back so the user can't tell we did
// anything crazy and so the browser removeFormat that we call next
// will operate on the entire originally selected range.
range = this.getFieldObject().getRange();
this.restoreCaretsFromCave_();
var realSavedCaretRange = savedCaretRange.toAbstractRange();
var startRange = startInTable ? realSavedCaretRange : range;
var endRange = endInTable ? realSavedCaretRange : range;
var restoredRange =
goog.editor.plugins.RemoveFormatting.createRangeDelimitedByRanges_(
startRange, endRange);
restoredRange.select();
savedCaretRange.dispose();
}
};
/**
* Does a best-effort attempt at clobbering all formatting that the
* browser's execCommand couldn't clobber without being totally inefficient.
* Attempts to convert visual line breaks to BRs. Leaves anchors that contain an
* href and images.
* Adapted from Gmail's MessageUtil's htmlToPlainText. http://go/messageutil.js
* @param {string} html The original html of the message.
* @return {string} The unformatted html, which is just text, br's, anchors and
* images.
* @private
*/
goog.editor.plugins.RemoveFormatting.prototype.removeFormattingWorker_ =
function(html) {
var el = goog.dom.createElement('div');
el.innerHTML = html;
// Put everything into a string buffer to avoid lots of expensive string
// concatenation along the way.
var sb = [];
var stack = [el.childNodes, 0];
// Keep separate stacks for places where we need to keep track of
// how deeply embedded we are. These are analogous to the general stack.
var preTagStack = [];
var preTagLevel = 0; // Length of the prestack.
var tableStack = [];
var tableLevel = 0;
// sp = stack pointer, pointing to the stack array.
// decrement by 2 since the stack alternates node lists and
// processed node counts
for (var sp = 0; sp >= 0; sp -= 2) {
// Check if we should pop the table level.
var changedLevel = false;
while (tableLevel > 0 && sp <= tableStack[tableLevel - 1]) {
tableLevel--;
changedLevel = true;
}
if (changedLevel) {
goog.editor.plugins.RemoveFormatting.appendNewline_(sb);
}
// Check if we should pop the <pre>/<xmp> level.
changedLevel = false;
while (preTagLevel > 0 && sp <= preTagStack[preTagLevel - 1]) {
preTagLevel--;
changedLevel = true;
}
if (changedLevel) {
goog.editor.plugins.RemoveFormatting.appendNewline_(sb);
}
// The list of of nodes to process at the current stack level.
var nodeList = stack[sp];
// The number of nodes processed so far, stored in the stack immediately
// following the node list for that stack level.
var numNodesProcessed = stack[sp + 1];
while (numNodesProcessed < nodeList.length) {
var node = nodeList[numNodesProcessed++];
var nodeName = node.nodeName;
var formatted = this.getValueForNode(node);
if (goog.isDefAndNotNull(formatted)) {
sb.push(formatted);
continue;
}
// TODO(user): Handle case 'EMBED' and case 'OBJECT'.
switch (nodeName) {
case '#text':
// Note that IE does not preserve whitespace in the dom
// values, even in a pre tag, so this is useless for IE.
var nodeValue = preTagLevel > 0 ?
node.nodeValue :
goog.string.stripNewlines(node.nodeValue);
nodeValue = goog.string.htmlEscape(nodeValue);
sb.push(nodeValue);
continue;
case goog.dom.TagName.P:
goog.editor.plugins.RemoveFormatting.appendNewline_(sb);
goog.editor.plugins.RemoveFormatting.appendNewline_(sb);
break; // break (not continue) so that child nodes are processed.
case goog.dom.TagName.BR:
goog.editor.plugins.RemoveFormatting.appendNewline_(sb);
continue;
case goog.dom.TagName.TABLE:
goog.editor.plugins.RemoveFormatting.appendNewline_(sb);
tableStack[tableLevel++] = sp;
break;
case goog.dom.TagName.PRE:
case 'XMP':
// This doesn't fully handle xmp, since
// it doesn't actually ignore tags within the xmp tag.
preTagStack[preTagLevel++] = sp;
break;
case goog.dom.TagName.STYLE:
case goog.dom.TagName.SCRIPT:
case goog.dom.TagName.SELECT:
continue;
case goog.dom.TagName.A:
if (node.href && node.href != '') {
sb.push("<a href='");
sb.push(node.href);
sb.push("'>");
sb.push(this.removeFormattingWorker_(node.innerHTML));
sb.push('</a>');
continue; // Children taken care of.
} else {
break; // Take care of the children.
}
case goog.dom.TagName.IMG:
sb.push("<img src='");
sb.push(node.src);
sb.push("'");
// border=0 is a common way to not show a blue border around an image
// that is wrapped by a link. If we remove that, the blue border will
// show up, which to the user looks like adding format, not removing.
if (node.border == '0') {
sb.push(" border='0'");
}
sb.push('>');
continue;
case goog.dom.TagName.TD:
// Don't add a space for the first TD, we only want spaces to
// separate td's.
if (node.previousSibling) {
sb.push(' ');
}
break;
case goog.dom.TagName.TR:
// Don't add a newline for the first TR.
if (node.previousSibling) {
goog.editor.plugins.RemoveFormatting.appendNewline_(sb);
}
break;
case goog.dom.TagName.DIV:
var parent = node.parentNode;
if (parent.firstChild == node &&
goog.editor.plugins.RemoveFormatting.BLOCK_RE_.test(
parent.tagName)) {
// If a DIV is the first child of another element that itself is a
// block element, the DIV does not add a new line.
break;
}
// Otherwise, the DIV does add a new line. Fall through.
default:
if (goog.editor.plugins.RemoveFormatting.BLOCK_RE_.test(nodeName)) {
goog.editor.plugins.RemoveFormatting.appendNewline_(sb);
}
}
// Recurse down the node.
var children = node.childNodes;
if (children.length > 0) |
}
}
// Replace with white space.
return goog.string.normalizeSpaces(sb.join(''));
};
/**
* Handle per node special processing if neccessary. If this function returns
* null then standard cleanup is applied. Otherwise this node and all children
* are assumed to be cleaned.
* NOTE(user): If an alternate RemoveFormatting processor is provided
* (setRemoveFormattingFunc()), this will no longer work.
* @param {Element} node The node to clean.
* @return {?string} The HTML strig representation of the cleaned data.
*/
goog.editor.plugins.RemoveFormatting.prototype.getValueForNode = function(
node) {
return null;
};
/**
* Sets a function to be used for remove formatting.
* @param {function(string): string} removeFormattingFunc - A function that
* takes a string of html and returns a string of html that does any other
* formatting changes desired. Use this only if trogedit's behavior doesn't
* meet your needs.
*/
goog.editor.plugins.RemoveFormatting.prototype.setRemoveFormattingFunc =
function(removeFormattingFunc) {
this.optRemoveFormattingFunc_ = removeFormattingFunc;
};
| {
// Push the current state on the stack.
stack[sp++] = nodeList;
stack[sp++] = numNodesProcessed;
// Iterate through the children nodes.
nodeList = children;
numNodesProcessed = 0;
} | conditional_block |
removeformatting.js | // Copyright 2008 The Closure Library Authors. All Rights Reserved.
//
// 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.
// All Rights Reserved.
/**
* @fileoverview Plugin to handle Remove Formatting.
*
*/
goog.provide('goog.editor.plugins.RemoveFormatting');
goog.require('goog.dom');
goog.require('goog.dom.NodeType');
goog.require('goog.dom.Range');
goog.require('goog.dom.TagName');
goog.require('goog.editor.BrowserFeature');
goog.require('goog.editor.Plugin');
goog.require('goog.editor.node');
goog.require('goog.editor.range');
goog.require('goog.string');
goog.require('goog.userAgent');
/**
* A plugin to handle removing formatting from selected text.
* @constructor
* @extends {goog.editor.Plugin}
* @final
*/
goog.editor.plugins.RemoveFormatting = function() {
goog.editor.Plugin.call(this);
/**
* Optional function to perform remove formatting in place of the
* provided removeFormattingWorker_.
* @type {?function(string): string}
* @private
*/
this.optRemoveFormattingFunc_ = null;
};
goog.inherits(goog.editor.plugins.RemoveFormatting, goog.editor.Plugin);
/**
* The editor command this plugin in handling.
* @type {string}
*/
goog.editor.plugins.RemoveFormatting.REMOVE_FORMATTING_COMMAND =
'+removeFormat';
/**
* Regular expression that matches a block tag name.
* @type {RegExp}
* @private
*/
goog.editor.plugins.RemoveFormatting.BLOCK_RE_ =
/^(DIV|TR|LI|BLOCKQUOTE|H\d|PRE|XMP)/;
/**
* Appends a new line to a string buffer.
* @param {Array.<string>} sb The string buffer to add to.
* @private
*/
goog.editor.plugins.RemoveFormatting.appendNewline_ = function(sb) {
sb.push('<br>');
};
/**
* Create a new range delimited by the start point of the first range and
* the end point of the second range.
* @param {goog.dom.AbstractRange} startRange Use the start point of this
* range as the beginning of the new range.
* @param {goog.dom.AbstractRange} endRange Use the end point of this
* range as the end of the new range.
* @return {!goog.dom.AbstractRange} The new range.
* @private
*/
goog.editor.plugins.RemoveFormatting.createRangeDelimitedByRanges_ = function(
startRange, endRange) {
return goog.dom.Range.createFromNodes(
startRange.getStartNode(), startRange.getStartOffset(),
endRange.getEndNode(), endRange.getEndOffset());
};
/** @override */
goog.editor.plugins.RemoveFormatting.prototype.getTrogClassId = function() {
return 'RemoveFormatting';
};
/** @override */
goog.editor.plugins.RemoveFormatting.prototype.isSupportedCommand = function(
command) {
return command ==
goog.editor.plugins.RemoveFormatting.REMOVE_FORMATTING_COMMAND;
};
/** @override */
goog.editor.plugins.RemoveFormatting.prototype.execCommandInternal =
function(command, var_args) {
if (command ==
goog.editor.plugins.RemoveFormatting.REMOVE_FORMATTING_COMMAND) {
this.removeFormatting_();
}
};
/** @override */
goog.editor.plugins.RemoveFormatting.prototype.handleKeyboardShortcut =
function(e, key, isModifierPressed) {
if (!isModifierPressed) {
return false;
}
if (key == ' ') {
this.getFieldObject().execCommand(
goog.editor.plugins.RemoveFormatting.REMOVE_FORMATTING_COMMAND);
return true;
}
return false;
};
/**
* Removes formatting from the current selection. Removes basic formatting
* (B/I/U) using the browser's execCommand. Then extracts the html from the
* selection to convert, calls either a client's specified removeFormattingFunc
* callback or trogedit's general built-in removeFormattingWorker_,
* and then replaces the current selection with the converted text.
* @private
*/
goog.editor.plugins.RemoveFormatting.prototype.removeFormatting_ = function() {
var range = this.getFieldObject().getRange();
if (range.isCollapsed()) {
return;
}
// Get the html to format and send it off for formatting. Built in
// removeFormat only strips some inline elements and some inline CSS styles
var convFunc = this.optRemoveFormattingFunc_ ||
goog.bind(this.removeFormattingWorker_, this);
this.convertSelectedHtmlText_(convFunc);
// Do the execCommand last as it needs block elements removed to work
// properly on background/fontColor in FF. There are, unfortunately, still
// cases where background/fontColor are not removed here.
var doc = this.getFieldDomHelper().getDocument();
doc.execCommand('RemoveFormat', false, undefined);
if (goog.editor.BrowserFeature.ADDS_NBSPS_IN_REMOVE_FORMAT) {
// WebKit converts spaces to non-breaking spaces when doing a RemoveFormat.
// See: https://bugs.webkit.org/show_bug.cgi?id=14062
this.convertSelectedHtmlText_(function(text) {
// This loses anything that might have legitimately been a non-breaking
// space, but that's better than the alternative of only having non-
// breaking spaces.
// Old versions of WebKit (Safari 3, Chrome 1) incorrectly match /u00A0
// and newer versions properly match .
var nbspRegExp =
goog.userAgent.isVersionOrHigher('528') ? / /g : /\u00A0/g;
return text.replace(nbspRegExp, ' ');
});
}
};
/**
* Finds the nearest ancestor of the node that is a table.
* @param {Node} nodeToCheck Node to search from.
* @return {Node} The table, or null if one was not found.
* @private
*/
goog.editor.plugins.RemoveFormatting.prototype.getTableAncestor_ = function(
nodeToCheck) {
var fieldElement = this.getFieldObject().getElement();
while (nodeToCheck && nodeToCheck != fieldElement) {
if (nodeToCheck.tagName == goog.dom.TagName.TABLE) {
return nodeToCheck;
}
nodeToCheck = nodeToCheck.parentNode;
}
return null;
};
/**
* Replaces the contents of the selection with html. Does its best to maintain
* the original selection. Also does its best to result in a valid DOM.
*
* TODO(user): See if there's any way to make this work on Ranges, and then
* move it into goog.editor.range. The Firefox implementation uses execCommand
* on the document, so must work on the actual selection.
*
* @param {string} html The html string to insert into the range.
* @private
*/
goog.editor.plugins.RemoveFormatting.prototype.pasteHtml_ = function(html) {
var range = this.getFieldObject().getRange();
var dh = this.getFieldDomHelper();
// Use markers to set the extent of the selection so that we can reselect it
// afterwards. This works better than builtin range manipulation in FF and IE
// because their implementations are so self-inconsistent and buggy.
var startSpanId = goog.string.createUniqueString();
var endSpanId = goog.string.createUniqueString();
html = '<span id="' + startSpanId + '"></span>' + html +
'<span id="' + endSpanId + '"></span>';
var dummyNodeId = goog.string.createUniqueString();
var dummySpanText = '<span id="' + dummyNodeId + '"></span>';
if (goog.editor.BrowserFeature.HAS_IE_RANGES) {
// IE's selection often doesn't include the outermost tags.
// We want to use pasteHTML to replace the range contents with the newly
// unformatted text, so we have to check to make sure we aren't just
// pasting into some stray tags. To do this, we first clear out the
// contents of the range and then delete all empty nodes parenting the now
// empty range. This way, the pasted contents are never re-embedded into
// formated nodes. Pasting purely empty html does not work, since IE moves
// the selection inside the next node, so we insert a dummy span.
var textRange = range.getTextRange(0).getBrowserRangeObject();
textRange.pasteHTML(dummySpanText);
var parent;
while ((parent = textRange.parentElement()) &&
goog.editor.node.isEmpty(parent) &&
!goog.editor.node.isEditableContainer(parent)) {
var tag = parent.nodeName;
// We can't remove these table tags as it will invalidate the table dom.
if (tag == goog.dom.TagName.TD ||
tag == goog.dom.TagName.TR ||
tag == goog.dom.TagName.TH) {
break;
}
goog.dom.removeNode(parent);
}
textRange.pasteHTML(html);
var dummySpan = dh.getElement(dummyNodeId);
// If we entered the while loop above, the node has already been removed
// since it was a child of parent and parent was removed.
if (dummySpan) {
goog.dom.removeNode(dummySpan);
}
} else if (goog.editor.BrowserFeature.HAS_W3C_RANGES) {
// insertHtml and range.insertNode don't merge blocks correctly.
// (e.g. if your selection spans two paragraphs)
dh.getDocument().execCommand('insertImage', false, dummyNodeId);
var dummyImageNodePattern = new RegExp('<[^<]*' + dummyNodeId + '[^>]*>');
var parent = this.getFieldObject().getRange().getContainerElement();
if (parent.nodeType == goog.dom.NodeType.TEXT) {
// Opera sometimes returns a text node here.
// TODO(user): perhaps we should modify getParentContainer?
parent = parent.parentNode;
}
// We have to search up the DOM because in some cases, notably when
// selecting li's within a list, execCommand('insertImage') actually splits
// tags in such a way that parent that used to contain the selection does
// not contain inserted image.
while (!dummyImageNodePattern.test(parent.innerHTML)) {
parent = parent.parentNode;
}
// Like the IE case above, sometimes the selection does not include the
// outermost tags. For Gecko, we have already expanded the range so that
// it does, so we can just replace the dummy image with the final html.
// For WebKit, we use the same approach as we do with IE - we
// inject a dummy span where we will eventually place the contents, and
// remove parentNodes of the span while they are empty.
if (goog.userAgent.GECKO) {
goog.editor.node.replaceInnerHtml(parent,
parent.innerHTML.replace(dummyImageNodePattern, html));
} else {
goog.editor.node.replaceInnerHtml(parent,
parent.innerHTML.replace(dummyImageNodePattern, dummySpanText));
var dummySpan = dh.getElement(dummyNodeId);
parent = dummySpan;
while ((parent = dummySpan.parentNode) &&
goog.editor.node.isEmpty(parent) &&
!goog.editor.node.isEditableContainer(parent)) {
var tag = parent.nodeName;
// We can't remove these table tags as it will invalidate the table dom.
if (tag == goog.dom.TagName.TD ||
tag == goog.dom.TagName.TR ||
tag == goog.dom.TagName.TH) {
break;
}
// We can't just remove parent since dummySpan is inside it, and we need
// to keep dummy span around for the replacement. So we move the
// dummySpan up as we go.
goog.dom.insertSiblingAfter(dummySpan, parent);
goog.dom.removeNode(parent);
}
goog.editor.node.replaceInnerHtml(parent,
parent.innerHTML.replace(new RegExp(dummySpanText, 'i'), html));
}
}
var startSpan = dh.getElement(startSpanId);
var endSpan = dh.getElement(endSpanId);
goog.dom.Range.createFromNodes(startSpan, 0, endSpan,
endSpan.childNodes.length).select();
goog.dom.removeNode(startSpan);
goog.dom.removeNode(endSpan);
};
/**
* Gets the html inside the selection to send off for further processing.
*
* TODO(user): Make this general so that it can be moved into
* goog.editor.range. The main reason it can't be moved is becuase we need to
* get the range before we do the execCommand and continue to operate on that
* same range (reasons are documented above).
*
* @param {goog.dom.AbstractRange} range The selection.
* @return {string} The html string to format.
* @private
*/
goog.editor.plugins.RemoveFormatting.prototype.getHtmlText_ = function(range) {
var div = this.getFieldDomHelper().createDom('div');
var textRange = range.getBrowserRangeObject();
if (goog.editor.BrowserFeature.HAS_W3C_RANGES) {
// Get the text to convert.
div.appendChild(textRange.cloneContents());
} else if (goog.editor.BrowserFeature.HAS_IE_RANGES) {
// Trim the whitespace on the ends of the range, so that it the container
// will be the container of only the text content that we are changing.
// This gets around issues in IE where the spaces are included in the
// selection, but ignored sometimes by execCommand, and left orphaned.
var rngText = range.getText();
// BRs get reported as \r\n, but only count as one character for moves.
// Adjust the string so our move counter is correct.
rngText = rngText.replace(/\r\n/g, '\r');
var rngTextLength = rngText.length;
var left = rngTextLength - goog.string.trimLeft(rngText).length;
var right = rngTextLength - goog.string.trimRight(rngText).length;
textRange.moveStart('character', left);
textRange.moveEnd('character', -right);
var htmlText = textRange.htmlText;
// Check if in pretag and fix up formatting so that new lines are preserved.
if (textRange.queryCommandValue('formatBlock') == 'Formatted') {
htmlText = goog.string.newLineToBr(textRange.htmlText);
}
div.innerHTML = htmlText;
}
// Get the innerHTML of the node instead of just returning the text above
// so that its properly html escaped.
return div.innerHTML;
};
/**
* Move the range so that it doesn't include any partially selected tables.
* @param {goog.dom.AbstractRange} range The range to adjust.
* @param {Node} startInTable Table node that the range starts in.
* @param {Node} endInTable Table node that the range ends in.
* @return {!goog.dom.SavedCaretRange} Range to use to restore the
* selection after we run our custom remove formatting.
* @private
*/
goog.editor.plugins.RemoveFormatting.prototype.adjustRangeForTables_ =
function(range, startInTable, endInTable) {
// Create placeholders for the current selection so we can restore it
// later.
var savedCaretRange = goog.editor.range.saveUsingNormalizedCarets(range);
var startNode = range.getStartNode();
var startOffset = range.getStartOffset();
var endNode = range.getEndNode();
var endOffset = range.getEndOffset();
var dh = this.getFieldDomHelper();
// Move start after the table.
if (startInTable) {
var textNode = dh.createTextNode('');
goog.dom.insertSiblingAfter(textNode, startInTable);
startNode = textNode;
startOffset = 0;
}
// Move end before the table.
if (endInTable) {
var textNode = dh.createTextNode('');
goog.dom.insertSiblingBefore(textNode, endInTable);
endNode = textNode;
endOffset = 0;
}
goog.dom.Range.createFromNodes(startNode, startOffset,
endNode, endOffset).select();
return savedCaretRange;
};
/**
* Remove a caret from the dom and hide it in a safe place, so it can
* be restored later via restoreCaretsFromCave.
* @param {goog.dom.SavedCaretRange} caretRange The caret range to
* get the carets from.
* @param {boolean} isStart Whether this is the start or end caret.
* @private
*/
goog.editor.plugins.RemoveFormatting.prototype.putCaretInCave_ = function(
caretRange, isStart) {
var cavedCaret = goog.dom.removeNode(caretRange.getCaret(isStart));
if (isStart) {
this.startCaretInCave_ = cavedCaret;
} else {
this.endCaretInCave_ = cavedCaret;
}
};
/**
* Restore carets that were hidden away by adding them back into the dom.
* Note: this does not restore to the original dom location, as that
* will likely have been modified with remove formatting. The only
* guarentees here are that start will still be before end, and that
* they will be in the editable region. This should only be used when
* you don't actually intend to USE the caret again.
* @private
*/
goog.editor.plugins.RemoveFormatting.prototype.restoreCaretsFromCave_ =
function() {
// To keep start before end, we put the end caret at the bottom of the field
// and the start caret at the start of the field.
var field = this.getFieldObject().getElement();
if (this.startCaretInCave_) {
field.insertBefore(this.startCaretInCave_, field.firstChild);
this.startCaretInCave_ = null;
}
if (this.endCaretInCave_) {
field.appendChild(this.endCaretInCave_);
this.endCaretInCave_ = null;
}
};
/**
* Gets the html inside the current selection, passes it through the given
* conversion function, and puts it back into the selection.
*
* @param {function(string): string} convertFunc A conversion function that
* transforms an html string to new html string.
* @private
*/
goog.editor.plugins.RemoveFormatting.prototype.convertSelectedHtmlText_ =
function(convertFunc) {
var range = this.getFieldObject().getRange();
// For multiple ranges, it is really hard to do our custom remove formatting
// without invalidating other ranges. So instead of always losing the
// content, this solution at least lets the browser do its own remove
// formatting which works correctly most of the time.
if (range.getTextRangeCount() > 1) {
return;
}
if (goog.userAgent.GECKO) {
// Determine if we need to handle tables, since they are special cases.
// If the selection is entirely within a table, there is no extra
// formatting removal we can do. If a table is fully selected, we will
// just blow it away. If a table is only partially selected, we can
// perform custom remove formatting only on the non table parts, since we
// we can't just remove the parts and paste back into it (eg. we can't
// inject html where a TR used to be).
// If the selection contains the table and more, this is automatically
// handled, but if just the table is selected, it can be tricky to figure
// this case out, because of the numerous ways selections can be formed -
// ex. if a table has a single tr with a single td with a single text node
// in it, and the selection is (textNode: 0), (textNode: nextNode.length)
// then the entire table is selected, even though the start and end aren't
// the table itself. We are truly inside a table if the expanded endpoints
// are still inside the table.
// Expand the selection to include any outermost tags that weren't included
// in the selection, but have the same visible selection. Stop expanding
// if we reach the top level field.
var expandedRange = goog.editor.range.expand(range,
this.getFieldObject().getElement());
var startInTable = this.getTableAncestor_(expandedRange.getStartNode());
var endInTable = this.getTableAncestor_(expandedRange.getEndNode());
if (startInTable || endInTable) {
if (startInTable == endInTable) {
// We are fully contained in the same table, there is no extra
// remove formatting that we can do, just return and run browser
// formatting only.
return;
}
// Adjust the range to not contain any partially selected tables, since
// we don't want to run our custom remove formatting on them.
var savedCaretRange = this.adjustRangeForTables_(range,
startInTable, endInTable);
// Hack alert!!
// If start is not in a table, then the saved caret will get sent out | // savedCaretRange later on. So, we just remove it from the dom, and
// put it back later so we can create a range later (not exactly in the
// same spot, but don't worry we don't actually try to use it later)
// and then it will be removed when we dispose the range.
if (!startInTable) {
this.putCaretInCave_(savedCaretRange, true);
}
if (!endInTable) {
this.putCaretInCave_(savedCaretRange, false);
}
// Re-fetch the range, and re-expand it, since we just modified it.
range = this.getFieldObject().getRange();
expandedRange = goog.editor.range.expand(range,
this.getFieldObject().getElement());
}
expandedRange.select();
range = expandedRange;
}
// Convert the selected text to the format-less version, paste back into
// the selection.
var text = this.getHtmlText_(range);
this.pasteHtml_(convertFunc(text));
if (goog.userAgent.GECKO && savedCaretRange) {
// If we moved the selection, move it back so the user can't tell we did
// anything crazy and so the browser removeFormat that we call next
// will operate on the entire originally selected range.
range = this.getFieldObject().getRange();
this.restoreCaretsFromCave_();
var realSavedCaretRange = savedCaretRange.toAbstractRange();
var startRange = startInTable ? realSavedCaretRange : range;
var endRange = endInTable ? realSavedCaretRange : range;
var restoredRange =
goog.editor.plugins.RemoveFormatting.createRangeDelimitedByRanges_(
startRange, endRange);
restoredRange.select();
savedCaretRange.dispose();
}
};
/**
* Does a best-effort attempt at clobbering all formatting that the
* browser's execCommand couldn't clobber without being totally inefficient.
* Attempts to convert visual line breaks to BRs. Leaves anchors that contain an
* href and images.
* Adapted from Gmail's MessageUtil's htmlToPlainText. http://go/messageutil.js
* @param {string} html The original html of the message.
* @return {string} The unformatted html, which is just text, br's, anchors and
* images.
* @private
*/
goog.editor.plugins.RemoveFormatting.prototype.removeFormattingWorker_ =
function(html) {
var el = goog.dom.createElement('div');
el.innerHTML = html;
// Put everything into a string buffer to avoid lots of expensive string
// concatenation along the way.
var sb = [];
var stack = [el.childNodes, 0];
// Keep separate stacks for places where we need to keep track of
// how deeply embedded we are. These are analogous to the general stack.
var preTagStack = [];
var preTagLevel = 0; // Length of the prestack.
var tableStack = [];
var tableLevel = 0;
// sp = stack pointer, pointing to the stack array.
// decrement by 2 since the stack alternates node lists and
// processed node counts
for (var sp = 0; sp >= 0; sp -= 2) {
// Check if we should pop the table level.
var changedLevel = false;
while (tableLevel > 0 && sp <= tableStack[tableLevel - 1]) {
tableLevel--;
changedLevel = true;
}
if (changedLevel) {
goog.editor.plugins.RemoveFormatting.appendNewline_(sb);
}
// Check if we should pop the <pre>/<xmp> level.
changedLevel = false;
while (preTagLevel > 0 && sp <= preTagStack[preTagLevel - 1]) {
preTagLevel--;
changedLevel = true;
}
if (changedLevel) {
goog.editor.plugins.RemoveFormatting.appendNewline_(sb);
}
// The list of of nodes to process at the current stack level.
var nodeList = stack[sp];
// The number of nodes processed so far, stored in the stack immediately
// following the node list for that stack level.
var numNodesProcessed = stack[sp + 1];
while (numNodesProcessed < nodeList.length) {
var node = nodeList[numNodesProcessed++];
var nodeName = node.nodeName;
var formatted = this.getValueForNode(node);
if (goog.isDefAndNotNull(formatted)) {
sb.push(formatted);
continue;
}
// TODO(user): Handle case 'EMBED' and case 'OBJECT'.
switch (nodeName) {
case '#text':
// Note that IE does not preserve whitespace in the dom
// values, even in a pre tag, so this is useless for IE.
var nodeValue = preTagLevel > 0 ?
node.nodeValue :
goog.string.stripNewlines(node.nodeValue);
nodeValue = goog.string.htmlEscape(nodeValue);
sb.push(nodeValue);
continue;
case goog.dom.TagName.P:
goog.editor.plugins.RemoveFormatting.appendNewline_(sb);
goog.editor.plugins.RemoveFormatting.appendNewline_(sb);
break; // break (not continue) so that child nodes are processed.
case goog.dom.TagName.BR:
goog.editor.plugins.RemoveFormatting.appendNewline_(sb);
continue;
case goog.dom.TagName.TABLE:
goog.editor.plugins.RemoveFormatting.appendNewline_(sb);
tableStack[tableLevel++] = sp;
break;
case goog.dom.TagName.PRE:
case 'XMP':
// This doesn't fully handle xmp, since
// it doesn't actually ignore tags within the xmp tag.
preTagStack[preTagLevel++] = sp;
break;
case goog.dom.TagName.STYLE:
case goog.dom.TagName.SCRIPT:
case goog.dom.TagName.SELECT:
continue;
case goog.dom.TagName.A:
if (node.href && node.href != '') {
sb.push("<a href='");
sb.push(node.href);
sb.push("'>");
sb.push(this.removeFormattingWorker_(node.innerHTML));
sb.push('</a>');
continue; // Children taken care of.
} else {
break; // Take care of the children.
}
case goog.dom.TagName.IMG:
sb.push("<img src='");
sb.push(node.src);
sb.push("'");
// border=0 is a common way to not show a blue border around an image
// that is wrapped by a link. If we remove that, the blue border will
// show up, which to the user looks like adding format, not removing.
if (node.border == '0') {
sb.push(" border='0'");
}
sb.push('>');
continue;
case goog.dom.TagName.TD:
// Don't add a space for the first TD, we only want spaces to
// separate td's.
if (node.previousSibling) {
sb.push(' ');
}
break;
case goog.dom.TagName.TR:
// Don't add a newline for the first TR.
if (node.previousSibling) {
goog.editor.plugins.RemoveFormatting.appendNewline_(sb);
}
break;
case goog.dom.TagName.DIV:
var parent = node.parentNode;
if (parent.firstChild == node &&
goog.editor.plugins.RemoveFormatting.BLOCK_RE_.test(
parent.tagName)) {
// If a DIV is the first child of another element that itself is a
// block element, the DIV does not add a new line.
break;
}
// Otherwise, the DIV does add a new line. Fall through.
default:
if (goog.editor.plugins.RemoveFormatting.BLOCK_RE_.test(nodeName)) {
goog.editor.plugins.RemoveFormatting.appendNewline_(sb);
}
}
// Recurse down the node.
var children = node.childNodes;
if (children.length > 0) {
// Push the current state on the stack.
stack[sp++] = nodeList;
stack[sp++] = numNodesProcessed;
// Iterate through the children nodes.
nodeList = children;
numNodesProcessed = 0;
}
}
}
// Replace with white space.
return goog.string.normalizeSpaces(sb.join(''));
};
/**
* Handle per node special processing if neccessary. If this function returns
* null then standard cleanup is applied. Otherwise this node and all children
* are assumed to be cleaned.
* NOTE(user): If an alternate RemoveFormatting processor is provided
* (setRemoveFormattingFunc()), this will no longer work.
* @param {Element} node The node to clean.
* @return {?string} The HTML strig representation of the cleaned data.
*/
goog.editor.plugins.RemoveFormatting.prototype.getValueForNode = function(
node) {
return null;
};
/**
* Sets a function to be used for remove formatting.
* @param {function(string): string} removeFormattingFunc - A function that
* takes a string of html and returns a string of html that does any other
* formatting changes desired. Use this only if trogedit's behavior doesn't
* meet your needs.
*/
goog.editor.plugins.RemoveFormatting.prototype.setRemoveFormattingFunc =
function(removeFormattingFunc) {
this.optRemoveFormattingFunc_ = removeFormattingFunc;
}; | // for uber remove formatting, and it will get blown away. This is
// fine, except that we need to be able to re-create a range from the | random_line_split |
roundsd.rs | use ::{BroadcastMode, Instruction, MaskReg, MergeMode, Mnemonic, OperandSize, Reg, RoundingMode};
use ::RegType::*;
use ::instruction_def::*;
use ::Operand::*;
use ::Reg::*;
use ::RegScale::*;
fn roundsd_1() {
run_test(&Instruction { mnemonic: Mnemonic::ROUNDSD, operand1: Some(Direct(XMM0)), operand2: Some(Direct(XMM0)), operand3: Some(Literal8(73)), operand4: None, lock: false, rounding_mode: None, merge_mode: None, sae: false, mask: None, broadcast: None }, &[102, 15, 58, 11, 192, 73], OperandSize::Dword)
}
fn roundsd_2() {
run_test(&Instruction { mnemonic: Mnemonic::ROUNDSD, operand1: Some(Direct(XMM6)), operand2: Some(IndirectDisplaced(EAX, 455015242, Some(OperandSize::Qword), None)), operand3: Some(Literal8(66)), operand4: None, lock: false, rounding_mode: None, merge_mode: None, sae: false, mask: None, broadcast: None }, &[102, 15, 58, 11, 176, 74, 251, 30, 27, 66], OperandSize::Dword)
}
fn roundsd_3() {
run_test(&Instruction { mnemonic: Mnemonic::ROUNDSD, operand1: Some(Direct(XMM7)), operand2: Some(Direct(XMM1)), operand3: Some(Literal8(21)), operand4: None, lock: false, rounding_mode: None, merge_mode: None, sae: false, mask: None, broadcast: None }, &[102, 15, 58, 11, 249, 21], OperandSize::Qword)
} |
fn roundsd_4() {
run_test(&Instruction { mnemonic: Mnemonic::ROUNDSD, operand1: Some(Direct(XMM6)), operand2: Some(IndirectScaledIndexedDisplaced(RDX, RCX, Eight, 1515642711, Some(OperandSize::Qword), None)), operand3: Some(Literal8(102)), operand4: None, lock: false, rounding_mode: None, merge_mode: None, sae: false, mask: None, broadcast: None }, &[102, 15, 58, 11, 180, 202, 87, 223, 86, 90, 102], OperandSize::Qword)
} | random_line_split | |
roundsd.rs | use ::{BroadcastMode, Instruction, MaskReg, MergeMode, Mnemonic, OperandSize, Reg, RoundingMode};
use ::RegType::*;
use ::instruction_def::*;
use ::Operand::*;
use ::Reg::*;
use ::RegScale::*;
fn roundsd_1() {
run_test(&Instruction { mnemonic: Mnemonic::ROUNDSD, operand1: Some(Direct(XMM0)), operand2: Some(Direct(XMM0)), operand3: Some(Literal8(73)), operand4: None, lock: false, rounding_mode: None, merge_mode: None, sae: false, mask: None, broadcast: None }, &[102, 15, 58, 11, 192, 73], OperandSize::Dword)
}
fn | () {
run_test(&Instruction { mnemonic: Mnemonic::ROUNDSD, operand1: Some(Direct(XMM6)), operand2: Some(IndirectDisplaced(EAX, 455015242, Some(OperandSize::Qword), None)), operand3: Some(Literal8(66)), operand4: None, lock: false, rounding_mode: None, merge_mode: None, sae: false, mask: None, broadcast: None }, &[102, 15, 58, 11, 176, 74, 251, 30, 27, 66], OperandSize::Dword)
}
fn roundsd_3() {
run_test(&Instruction { mnemonic: Mnemonic::ROUNDSD, operand1: Some(Direct(XMM7)), operand2: Some(Direct(XMM1)), operand3: Some(Literal8(21)), operand4: None, lock: false, rounding_mode: None, merge_mode: None, sae: false, mask: None, broadcast: None }, &[102, 15, 58, 11, 249, 21], OperandSize::Qword)
}
fn roundsd_4() {
run_test(&Instruction { mnemonic: Mnemonic::ROUNDSD, operand1: Some(Direct(XMM6)), operand2: Some(IndirectScaledIndexedDisplaced(RDX, RCX, Eight, 1515642711, Some(OperandSize::Qword), None)), operand3: Some(Literal8(102)), operand4: None, lock: false, rounding_mode: None, merge_mode: None, sae: false, mask: None, broadcast: None }, &[102, 15, 58, 11, 180, 202, 87, 223, 86, 90, 102], OperandSize::Qword)
}
| roundsd_2 | identifier_name |
roundsd.rs | use ::{BroadcastMode, Instruction, MaskReg, MergeMode, Mnemonic, OperandSize, Reg, RoundingMode};
use ::RegType::*;
use ::instruction_def::*;
use ::Operand::*;
use ::Reg::*;
use ::RegScale::*;
fn roundsd_1() {
run_test(&Instruction { mnemonic: Mnemonic::ROUNDSD, operand1: Some(Direct(XMM0)), operand2: Some(Direct(XMM0)), operand3: Some(Literal8(73)), operand4: None, lock: false, rounding_mode: None, merge_mode: None, sae: false, mask: None, broadcast: None }, &[102, 15, 58, 11, 192, 73], OperandSize::Dword)
}
fn roundsd_2() {
run_test(&Instruction { mnemonic: Mnemonic::ROUNDSD, operand1: Some(Direct(XMM6)), operand2: Some(IndirectDisplaced(EAX, 455015242, Some(OperandSize::Qword), None)), operand3: Some(Literal8(66)), operand4: None, lock: false, rounding_mode: None, merge_mode: None, sae: false, mask: None, broadcast: None }, &[102, 15, 58, 11, 176, 74, 251, 30, 27, 66], OperandSize::Dword)
}
fn roundsd_3() {
run_test(&Instruction { mnemonic: Mnemonic::ROUNDSD, operand1: Some(Direct(XMM7)), operand2: Some(Direct(XMM1)), operand3: Some(Literal8(21)), operand4: None, lock: false, rounding_mode: None, merge_mode: None, sae: false, mask: None, broadcast: None }, &[102, 15, 58, 11, 249, 21], OperandSize::Qword)
}
fn roundsd_4() | {
run_test(&Instruction { mnemonic: Mnemonic::ROUNDSD, operand1: Some(Direct(XMM6)), operand2: Some(IndirectScaledIndexedDisplaced(RDX, RCX, Eight, 1515642711, Some(OperandSize::Qword), None)), operand3: Some(Literal8(102)), operand4: None, lock: false, rounding_mode: None, merge_mode: None, sae: false, mask: None, broadcast: None }, &[102, 15, 58, 11, 180, 202, 87, 223, 86, 90, 102], OperandSize::Qword)
} | identifier_body | |
process.rs | use std::io::process::{Command,ProcessOutput};
fn main() | {
// Initial command `rustc`
let mut cmd = Command::new("rustc");
// append the "--version" flag to the command
cmd.arg("--version");
// The `output` method will spawn `rustc --version`, wait until the process
// finishes and return the output of the process
match cmd.output() {
Err(why) => panic!("couldn't spawn rustc: {}", why.desc),
// Destructure `ProcessOutput`
Ok(ProcessOutput { error: err, output: out, status: exit }) => {
// Check if the process succeeded, i.e. the exit code was 0
if exit.success() {
// `out` has type `Vec<u8>`, convert it to a UTF-8 `$str`
let s = String::from_utf8_lossy(out.as_slice());
print!("rustc succeeded and stdout was:\n{}", s);
} else {
// `err` also has type `Vec<u8>`
let s = String::from_utf8_lossy(err.as_slice());
print!("rustc failed and stderr was:\n{}", s);
}
},
}
} | identifier_body | |
process.rs | use std::io::process::{Command,ProcessOutput};
fn main() {
// Initial command `rustc`
let mut cmd = Command::new("rustc");
// append the "--version" flag to the command
cmd.arg("--version");
| Ok(ProcessOutput { error: err, output: out, status: exit }) => {
// Check if the process succeeded, i.e. the exit code was 0
if exit.success() {
// `out` has type `Vec<u8>`, convert it to a UTF-8 `$str`
let s = String::from_utf8_lossy(out.as_slice());
print!("rustc succeeded and stdout was:\n{}", s);
} else {
// `err` also has type `Vec<u8>`
let s = String::from_utf8_lossy(err.as_slice());
print!("rustc failed and stderr was:\n{}", s);
}
},
}
} | // The `output` method will spawn `rustc --version`, wait until the process
// finishes and return the output of the process
match cmd.output() {
Err(why) => panic!("couldn't spawn rustc: {}", why.desc),
// Destructure `ProcessOutput` | random_line_split |
process.rs | use std::io::process::{Command,ProcessOutput};
fn | () {
// Initial command `rustc`
let mut cmd = Command::new("rustc");
// append the "--version" flag to the command
cmd.arg("--version");
// The `output` method will spawn `rustc --version`, wait until the process
// finishes and return the output of the process
match cmd.output() {
Err(why) => panic!("couldn't spawn rustc: {}", why.desc),
// Destructure `ProcessOutput`
Ok(ProcessOutput { error: err, output: out, status: exit }) => {
// Check if the process succeeded, i.e. the exit code was 0
if exit.success() {
// `out` has type `Vec<u8>`, convert it to a UTF-8 `$str`
let s = String::from_utf8_lossy(out.as_slice());
print!("rustc succeeded and stdout was:\n{}", s);
} else {
// `err` also has type `Vec<u8>`
let s = String::from_utf8_lossy(err.as_slice());
print!("rustc failed and stderr was:\n{}", s);
}
},
}
}
| main | identifier_name |
test_operations.py | import pytest
from diofant import Integer, SympifyError
from diofant.core.operations import AssocOp, LatticeOp
__all__ = ()
class MyMul(AssocOp):
identity = Integer(1)
def | ():
assert MyMul(2, MyMul(4, 3)) == MyMul(2, 4, 3)
class Join(LatticeOp):
"""Simplest possible Lattice class."""
zero = Integer(0)
identity = Integer(1)
def test_lattice_simple():
assert Join(Join(2, 3), 4) == Join(2, Join(3, 4))
assert Join(2, 3) == Join(3, 2)
assert Join(0, 2) == 0
assert Join(1, 2) == 2
assert Join(2, 2) == 2
assert Join(Join(2, 3), 4) == Join(2, 3, 4)
assert Join() == 1
assert Join(4) == 4
assert Join(1, 4, 2, 3, 1, 3, 2) == Join(2, 3, 4)
def test_lattice_shortcircuit():
pytest.raises(SympifyError, lambda: Join(object))
assert Join(0, object) == 0
def test_lattice_print():
assert str(Join(5, 4, 3, 2)) == 'Join(2, 3, 4, 5)'
def test_lattice_make_args():
assert Join.make_args(0) == {0}
assert Join.make_args(1) == {1}
assert Join.make_args(Join(2, 3, 4)) == {Integer(2), Integer(3), Integer(4)}
| test_flatten | identifier_name |
test_operations.py | import pytest
from diofant import Integer, SympifyError
from diofant.core.operations import AssocOp, LatticeOp
__all__ = ()
class MyMul(AssocOp):
identity = Integer(1) |
def test_flatten():
assert MyMul(2, MyMul(4, 3)) == MyMul(2, 4, 3)
class Join(LatticeOp):
"""Simplest possible Lattice class."""
zero = Integer(0)
identity = Integer(1)
def test_lattice_simple():
assert Join(Join(2, 3), 4) == Join(2, Join(3, 4))
assert Join(2, 3) == Join(3, 2)
assert Join(0, 2) == 0
assert Join(1, 2) == 2
assert Join(2, 2) == 2
assert Join(Join(2, 3), 4) == Join(2, 3, 4)
assert Join() == 1
assert Join(4) == 4
assert Join(1, 4, 2, 3, 1, 3, 2) == Join(2, 3, 4)
def test_lattice_shortcircuit():
pytest.raises(SympifyError, lambda: Join(object))
assert Join(0, object) == 0
def test_lattice_print():
assert str(Join(5, 4, 3, 2)) == 'Join(2, 3, 4, 5)'
def test_lattice_make_args():
assert Join.make_args(0) == {0}
assert Join.make_args(1) == {1}
assert Join.make_args(Join(2, 3, 4)) == {Integer(2), Integer(3), Integer(4)} | random_line_split | |
test_operations.py | import pytest
from diofant import Integer, SympifyError
from diofant.core.operations import AssocOp, LatticeOp
__all__ = ()
class MyMul(AssocOp):
identity = Integer(1)
def test_flatten():
assert MyMul(2, MyMul(4, 3)) == MyMul(2, 4, 3)
class Join(LatticeOp):
"""Simplest possible Lattice class."""
zero = Integer(0)
identity = Integer(1)
def test_lattice_simple():
|
def test_lattice_shortcircuit():
pytest.raises(SympifyError, lambda: Join(object))
assert Join(0, object) == 0
def test_lattice_print():
assert str(Join(5, 4, 3, 2)) == 'Join(2, 3, 4, 5)'
def test_lattice_make_args():
assert Join.make_args(0) == {0}
assert Join.make_args(1) == {1}
assert Join.make_args(Join(2, 3, 4)) == {Integer(2), Integer(3), Integer(4)}
| assert Join(Join(2, 3), 4) == Join(2, Join(3, 4))
assert Join(2, 3) == Join(3, 2)
assert Join(0, 2) == 0
assert Join(1, 2) == 2
assert Join(2, 2) == 2
assert Join(Join(2, 3), 4) == Join(2, 3, 4)
assert Join() == 1
assert Join(4) == 4
assert Join(1, 4, 2, 3, 1, 3, 2) == Join(2, 3, 4) | identifier_body |
Event.py | from django.db import models
from django.conf import settings
from django.utils import timezone
from django.core.validators import MinValueValidator
from django.urls import reverse
from django.core.exceptions import ValidationError
from django.utils.translation import ugettext as _
from .Committee import Committee
from .Registration import Registration
from lib.CommaSeparatedStringsField import CommaSeparatedStringsField
class Event(models.Model):
name = models.CharField(max_length=25)
description = models.TextField(max_length=255)
long_description = models.TextField(blank=True)
created_at = models.DateTimeField(auto_now_add=True)
updated_at = models.DateTimeField(auto_now=True)
published_at = models.DateTimeField(default=timezone.now, blank=True)
deadline_at = models.DateTimeField()
start_at = models.DateTimeField()
end_at = models.DateTimeField()
note_field = models.CharField(max_length=100, default='', blank=True)
note_field_options = CommaSeparatedStringsField(max_length=255, default='', blank=True)
note_field_required = models.BooleanField()
note_field_public = models.BooleanField()
location = models.CharField(max_length=25)
price = models.DecimalField(max_digits=5, decimal_places=2, default=0)
calendar_url = models.CharField(max_length=255, blank=True)
committee = models.ForeignKey(Committee, on_delete=models.PROTECT)
participants = models.ManyToManyField(settings.AUTH_USER_MODEL, through=Registration)
places = models.PositiveIntegerField(default=None, null=True, blank=True, validators=[MinValueValidator(1)])
def __str__(self):
return self.name
def get_absolute_url(self):
return reverse('event-detail', args=[self.pk])
def | (self):
"""
Return true if the event is published (past published date and not past end date)
"""
return self.published_at < timezone.now() < self.end_at
def is_expired(self):
"""
Return true if deadline is expired.
"""
return self.deadline_at is not None and self.deadline_at < timezone.now()
def is_full(self):
"""
Return true if there are no free places left.
"""
return self.get_free_places() is not None and self.get_free_places() <= 0
def get_free_places(self):
"""
Return the number of free places left.
"""
if self.places is None:
# If the event doesn't have a places limit, the value of this function is not defined
return None
else:
return self.places - Registration.objects.filter(event=self, withdrawn_at__isnull=True).count()
def get_active_registrations_count(self):
"""
Return the number of non-withdrawn registrations
"""
return self.registration_set.filter(withdrawn_at__isnull=True).count()
def is_almost_expired(self):
"""
Return true if the deadline is closer than a day.
"""
return self.deadline_at - timezone.now() < timezone.timedelta(days=1) and not self.is_expired()
def get_note_field_options(self):
"""
Return list of tuples from list of options
"""
return [('', self.note_field + ':')] + [(x, x) for x in self.note_field_options]
def clean(self):
if self.start_at > self.end_at:
raise ValidationError(_("Begindatum is later dan de einddatum!"))
if self.start_at < timezone.now():
raise ValidationError({'start_at': _("Startdatum is in het verleden!")})
if self.end_at < timezone.now():
raise ValidationError({'end_at': _("Einddatum is in het verleden!")})
if self.note_field_options and len(self.note_field_options) < 2:
raise ValidationError({'note_field_options': _("Geef minstens twee opties op.")})
class Meta:
ordering = ['created_at']
| is_published | identifier_name |
Event.py | from django.db import models
from django.conf import settings
from django.utils import timezone
from django.core.validators import MinValueValidator
from django.urls import reverse
from django.core.exceptions import ValidationError
from django.utils.translation import ugettext as _
from .Committee import Committee
from .Registration import Registration
from lib.CommaSeparatedStringsField import CommaSeparatedStringsField
class Event(models.Model):
| name = models.CharField(max_length=25)
description = models.TextField(max_length=255)
long_description = models.TextField(blank=True)
created_at = models.DateTimeField(auto_now_add=True)
updated_at = models.DateTimeField(auto_now=True)
published_at = models.DateTimeField(default=timezone.now, blank=True)
deadline_at = models.DateTimeField()
start_at = models.DateTimeField()
end_at = models.DateTimeField()
note_field = models.CharField(max_length=100, default='', blank=True)
note_field_options = CommaSeparatedStringsField(max_length=255, default='', blank=True)
note_field_required = models.BooleanField()
note_field_public = models.BooleanField()
location = models.CharField(max_length=25)
price = models.DecimalField(max_digits=5, decimal_places=2, default=0)
calendar_url = models.CharField(max_length=255, blank=True)
committee = models.ForeignKey(Committee, on_delete=models.PROTECT)
participants = models.ManyToManyField(settings.AUTH_USER_MODEL, through=Registration)
places = models.PositiveIntegerField(default=None, null=True, blank=True, validators=[MinValueValidator(1)])
def __str__(self):
return self.name
def get_absolute_url(self):
return reverse('event-detail', args=[self.pk])
def is_published(self):
"""
Return true if the event is published (past published date and not past end date)
"""
return self.published_at < timezone.now() < self.end_at
def is_expired(self):
"""
Return true if deadline is expired.
"""
return self.deadline_at is not None and self.deadline_at < timezone.now()
def is_full(self):
"""
Return true if there are no free places left.
"""
return self.get_free_places() is not None and self.get_free_places() <= 0
def get_free_places(self):
"""
Return the number of free places left.
"""
if self.places is None:
# If the event doesn't have a places limit, the value of this function is not defined
return None
else:
return self.places - Registration.objects.filter(event=self, withdrawn_at__isnull=True).count()
def get_active_registrations_count(self):
"""
Return the number of non-withdrawn registrations
"""
return self.registration_set.filter(withdrawn_at__isnull=True).count()
def is_almost_expired(self):
"""
Return true if the deadline is closer than a day.
"""
return self.deadline_at - timezone.now() < timezone.timedelta(days=1) and not self.is_expired()
def get_note_field_options(self):
"""
Return list of tuples from list of options
"""
return [('', self.note_field + ':')] + [(x, x) for x in self.note_field_options]
def clean(self):
if self.start_at > self.end_at:
raise ValidationError(_("Begindatum is later dan de einddatum!"))
if self.start_at < timezone.now():
raise ValidationError({'start_at': _("Startdatum is in het verleden!")})
if self.end_at < timezone.now():
raise ValidationError({'end_at': _("Einddatum is in het verleden!")})
if self.note_field_options and len(self.note_field_options) < 2:
raise ValidationError({'note_field_options': _("Geef minstens twee opties op.")})
class Meta:
ordering = ['created_at'] | identifier_body | |
Event.py | from django.db import models
from django.conf import settings
from django.utils import timezone
from django.core.validators import MinValueValidator
from django.urls import reverse
from django.core.exceptions import ValidationError
from django.utils.translation import ugettext as _
from .Committee import Committee
from .Registration import Registration
from lib.CommaSeparatedStringsField import CommaSeparatedStringsField
class Event(models.Model):
name = models.CharField(max_length=25)
description = models.TextField(max_length=255)
long_description = models.TextField(blank=True)
created_at = models.DateTimeField(auto_now_add=True)
updated_at = models.DateTimeField(auto_now=True)
published_at = models.DateTimeField(default=timezone.now, blank=True)
deadline_at = models.DateTimeField()
start_at = models.DateTimeField()
end_at = models.DateTimeField()
note_field = models.CharField(max_length=100, default='', blank=True)
note_field_options = CommaSeparatedStringsField(max_length=255, default='', blank=True)
note_field_required = models.BooleanField()
note_field_public = models.BooleanField()
location = models.CharField(max_length=25)
price = models.DecimalField(max_digits=5, decimal_places=2, default=0)
calendar_url = models.CharField(max_length=255, blank=True)
committee = models.ForeignKey(Committee, on_delete=models.PROTECT)
participants = models.ManyToManyField(settings.AUTH_USER_MODEL, through=Registration)
places = models.PositiveIntegerField(default=None, null=True, blank=True, validators=[MinValueValidator(1)])
def __str__(self):
return self.name
def get_absolute_url(self):
return reverse('event-detail', args=[self.pk])
def is_published(self):
"""
Return true if the event is published (past published date and not past end date)
"""
return self.published_at < timezone.now() < self.end_at
def is_expired(self):
"""
Return true if deadline is expired.
"""
return self.deadline_at is not None and self.deadline_at < timezone.now()
def is_full(self):
"""
Return true if there are no free places left.
"""
return self.get_free_places() is not None and self.get_free_places() <= 0
def get_free_places(self):
"""
Return the number of free places left.
"""
if self.places is None:
# If the event doesn't have a places limit, the value of this function is not defined
|
else:
return self.places - Registration.objects.filter(event=self, withdrawn_at__isnull=True).count()
def get_active_registrations_count(self):
"""
Return the number of non-withdrawn registrations
"""
return self.registration_set.filter(withdrawn_at__isnull=True).count()
def is_almost_expired(self):
"""
Return true if the deadline is closer than a day.
"""
return self.deadline_at - timezone.now() < timezone.timedelta(days=1) and not self.is_expired()
def get_note_field_options(self):
"""
Return list of tuples from list of options
"""
return [('', self.note_field + ':')] + [(x, x) for x in self.note_field_options]
def clean(self):
if self.start_at > self.end_at:
raise ValidationError(_("Begindatum is later dan de einddatum!"))
if self.start_at < timezone.now():
raise ValidationError({'start_at': _("Startdatum is in het verleden!")})
if self.end_at < timezone.now():
raise ValidationError({'end_at': _("Einddatum is in het verleden!")})
if self.note_field_options and len(self.note_field_options) < 2:
raise ValidationError({'note_field_options': _("Geef minstens twee opties op.")})
class Meta:
ordering = ['created_at']
| return None | conditional_block |
Event.py | from django.db import models
from django.conf import settings
from django.utils import timezone
from django.core.validators import MinValueValidator
from django.urls import reverse
from django.core.exceptions import ValidationError
from django.utils.translation import ugettext as _
from .Committee import Committee
from .Registration import Registration
from lib.CommaSeparatedStringsField import CommaSeparatedStringsField
class Event(models.Model):
name = models.CharField(max_length=25)
description = models.TextField(max_length=255)
long_description = models.TextField(blank=True)
created_at = models.DateTimeField(auto_now_add=True)
updated_at = models.DateTimeField(auto_now=True)
published_at = models.DateTimeField(default=timezone.now, blank=True)
deadline_at = models.DateTimeField()
start_at = models.DateTimeField()
end_at = models.DateTimeField()
note_field = models.CharField(max_length=100, default='', blank=True)
note_field_options = CommaSeparatedStringsField(max_length=255, default='', blank=True)
note_field_required = models.BooleanField()
note_field_public = models.BooleanField()
location = models.CharField(max_length=25)
price = models.DecimalField(max_digits=5, decimal_places=2, default=0)
calendar_url = models.CharField(max_length=255, blank=True)
committee = models.ForeignKey(Committee, on_delete=models.PROTECT)
participants = models.ManyToManyField(settings.AUTH_USER_MODEL, through=Registration)
places = models.PositiveIntegerField(default=None, null=True, blank=True, validators=[MinValueValidator(1)])
def __str__(self):
return self.name
def get_absolute_url(self):
return reverse('event-detail', args=[self.pk])
def is_published(self):
"""
Return true if the event is published (past published date and not past end date)
"""
return self.published_at < timezone.now() < self.end_at
def is_expired(self):
"""
Return true if deadline is expired.
"""
return self.deadline_at is not None and self.deadline_at < timezone.now()
def is_full(self):
"""
Return true if there are no free places left.
"""
return self.get_free_places() is not None and self.get_free_places() <= 0
def get_free_places(self):
"""
Return the number of free places left.
"""
if self.places is None:
# If the event doesn't have a places limit, the value of this function is not defined
return None
else:
return self.places - Registration.objects.filter(event=self, withdrawn_at__isnull=True).count()
def get_active_registrations_count(self):
"""
Return the number of non-withdrawn registrations | return self.registration_set.filter(withdrawn_at__isnull=True).count()
def is_almost_expired(self):
"""
Return true if the deadline is closer than a day.
"""
return self.deadline_at - timezone.now() < timezone.timedelta(days=1) and not self.is_expired()
def get_note_field_options(self):
"""
Return list of tuples from list of options
"""
return [('', self.note_field + ':')] + [(x, x) for x in self.note_field_options]
def clean(self):
if self.start_at > self.end_at:
raise ValidationError(_("Begindatum is later dan de einddatum!"))
if self.start_at < timezone.now():
raise ValidationError({'start_at': _("Startdatum is in het verleden!")})
if self.end_at < timezone.now():
raise ValidationError({'end_at': _("Einddatum is in het verleden!")})
if self.note_field_options and len(self.note_field_options) < 2:
raise ValidationError({'note_field_options': _("Geef minstens twee opties op.")})
class Meta:
ordering = ['created_at'] | """ | random_line_split |
lexer.py | # -*- coding: utf-8 -*-
"""
Collection of raw lexer test cases and class constructor.
"""
from __future__ import unicode_literals
import textwrap
swapquotes = {
39: 34, 34: 39,
# note the follow are interim error messages
96: 39,
}
# The structure and some test cases are taken
# from https://bitbucket.org/ned/jslex
es5_cases = [
(
# Identifiers
'identifiers_ascii',
('i my_variable_name c17 _dummy $str $ _ CamelCase class2type',
['ID i', 'ID my_variable_name', 'ID c17', 'ID _dummy',
'ID $str', 'ID $', 'ID _', 'ID CamelCase', 'ID class2type']
),
), (
'identifiers_unicode',
(u'\u03c0 \u03c0_tail var\ua67c',
[u'ID \u03c0', u'ID \u03c0_tail', u'ID var\ua67c']),
), (
# https://github.com/rspivak/slimit/issues/2
'slimit_issue_2',
('nullify truelie falsepositive',
['ID nullify', 'ID truelie', 'ID falsepositive']),
), (
'keywords_break',
('break Break BREAK', ['BREAK break', 'ID Break', 'ID BREAK']),
), (
# Literals
'literals',
('null true false Null True False',
['NULL null', 'TRUE true', 'FALSE false',
'ID Null', 'ID True', 'ID False']
),
), (
# Punctuators
'punctuators_simple',
('a /= b', ['ID a', 'DIVEQUAL /=', 'ID b']),
), (
'punctuators_various_equality',
(('= == != === !== < > <= >= || && ++ -- << >> '
'>>> += -= *= <<= >>= >>>= &= %= ^= |='),
['EQ =', 'EQEQ ==', 'NE !=', 'STREQ ===', 'STRNEQ !==', 'LT <',
'GT >', 'LE <=', 'GE >=', 'OR ||', 'AND &&', 'PLUSPLUS ++',
'MINUSMINUS --', 'LSHIFT <<', 'RSHIFT >>', 'URSHIFT >>>',
'PLUSEQUAL +=', 'MINUSEQUAL -=', 'MULTEQUAL *=', 'LSHIFTEQUAL <<=',
'RSHIFTEQUAL >>=', 'URSHIFTEQUAL >>>=', 'ANDEQUAL &=', 'MODEQUAL %=',
'XOREQUAL ^=', 'OREQUAL |=',
]
),
), (
'punctuators_various_others',
('. , ; : + - * % & | ^ ~ ? ! ( ) { } [ ]',
['PERIOD .', 'COMMA ,', 'SEMI ;', 'COLON :', 'PLUS +', 'MINUS -',
'MULT *', 'MOD %', 'BAND &', 'BOR |', 'BXOR ^', 'BNOT ~',
'CONDOP ?', 'NOT !', 'LPAREN (', 'RPAREN )', 'LBRACE {', 'RBRACE }',
'LBRACKET [', 'RBRACKET ]']
),
), (
'division_simple',
('a / b', ['ID a', 'DIV /', 'ID b']),
), (
'numbers',
(('3 3.3 0 0. 0.0 0.001 010 3.e2 3.e-2 3.e+2 3E2 3E+2 3E-2 '
'0.5e2 0.5e+2 0.5e-2 33 128.15 0x001 0X12ABCDEF 0xabcdef'),
['NUMBER 3', 'NUMBER 3.3', 'NUMBER 0', 'NUMBER 0.', 'NUMBER 0.0',
'NUMBER 0.001', 'NUMBER 010', 'NUMBER 3.e2', 'NUMBER 3.e-2',
'NUMBER 3.e+2', 'NUMBER 3E2', 'NUMBER 3E+2', 'NUMBER 3E-2',
'NUMBER 0.5e2', 'NUMBER 0.5e+2', 'NUMBER 0.5e-2', 'NUMBER 33',
'NUMBER 128.15', 'NUMBER 0x001', 'NUMBER 0X12ABCDEF',
'NUMBER 0xabcdef']
),
), (
'strings_simple_quote',
(""" '"' """, ["""STRING '"'"""]),
), (
'strings_escape_quote_tab',
(r'''"foo" 'foo' "x\";" 'x\';' "foo\tbar"''',
['STRING "foo"', """STRING 'foo'""", r'STRING "x\";"',
r"STRING 'x\';'", r'STRING "foo\tbar"']
),
), (
'strings_escape_ascii',
(r"""'\x55' "\x12ABCDEF" '!@#$%^&*()_+{}[]\";?'""",
[r"STRING '\x55'", r'STRING "\x12ABCDEF"',
r"STRING '!@#$%^&*()_+{}[]\";?'"]
),
), (
'strings_escape_unicode',
(r"""'\u0001' "\uFCEF" 'a\\\b\n'""",
[r"STRING '\u0001'", r'STRING "\uFCEF"', r"STRING 'a\\\b\n'"]
),
), (
'strings_unicode',
(u'"ัะตัั ัััะพะบะธ\\""', [u'STRING "ัะตัั ัััะพะบะธ\\""']),
), (
'strings_escape_octal',
(r"""'\251'""", [r"""STRING '\251'"""]),
), (
# Bug - https://github.com/rspivak/slimit/issues/5
'slimit_issue_5',
(r"var tagRegExp = new RegExp('<(\/*)(FooBar)', 'gi');",
['VAR var', 'ID tagRegExp', 'EQ =',
'NEW new', 'ID RegExp', 'LPAREN (',
r"STRING '<(\/*)(FooBar)'", 'COMMA ,', "STRING 'gi'",
'RPAREN )', 'SEMI ;']),
), (
# same as above but inside double quotes
'slimit_issue_5_double_quote',
(r'"<(\/*)(FooBar)"', [r'STRING "<(\/*)(FooBar)"']),
), (
# multiline string (string written across multiple lines
# of code) https://github.com/rspivak/slimit/issues/24
'slimit_issue_24_multi_line_code_double',
("var a = 'hello \\\n world'",
['VAR var', 'ID a', 'EQ =', "STRING 'hello \\\n world'"]),
), (
'slimit_issue_24_multi_line_code_single',
('var a = "hello \\\r world"',
['VAR var', 'ID a', 'EQ =', 'STRING "hello \\\r world"']),
), (
# regex
'regex_1',
(r'a=/a*/,1', ['ID a', 'EQ =', 'REGEX /a*/', 'COMMA ,', 'NUMBER 1']),
), (
'regex_2',
(r'a=/a*[^/]+/,1',
['ID a', 'EQ =', 'REGEX /a*[^/]+/', 'COMMA ,', 'NUMBER 1']
),
), (
'regex_3',
(r'a=/a*\[^/,1',
['ID a', 'EQ =', r'REGEX /a*\[^/', 'COMMA ,', 'NUMBER 1']
),
), (
'regex_4',
(r'a=/\//,1', ['ID a', 'EQ =', r'REGEX /\//', 'COMMA ,', 'NUMBER 1']),
), (
# not a regex, just a division
# https://github.com/rspivak/slimit/issues/6
'slimit_issue_6_not_regex_but_division',
(r'x = this / y;',
['ID x', 'EQ =', 'THIS this', r'DIV /', r'ID y', r'SEMI ;']),
), (
'regex_mozilla_example_1',
# next two are from
# http://www.mozilla.org/js/language/js20-2002-04/rationale/syntax.html#regular-expressions
('for (var x = a in foo && "</x>" || mot ? z:/x:3;x<5;y</g/i) '
'{xyz(x++);}',
["FOR for", "LPAREN (", "VAR var", "ID x", "EQ =", "ID a", "IN in",
"ID foo", "AND &&", 'STRING "</x>"', "OR ||", "ID mot", "CONDOP ?",
"ID z", "COLON :", "REGEX /x:3;x<5;y</g", "DIV /", "ID i",
"RPAREN )", "LBRACE {", "ID xyz", "LPAREN (", "ID x", "PLUSPLUS ++",
"RPAREN )", "SEMI ;", "RBRACE }"]
),
), (
'regex_mozilla_example_2',
('for (var x = a in foo && "</x>" || mot ? z/x:3;x<5;y</g/i) '
'{xyz(x++);}',
["FOR for", "LPAREN (", "VAR var", "ID x", "EQ =", "ID a", "IN in",
"ID foo", "AND &&", 'STRING "</x>"', "OR ||", "ID mot", "CONDOP ?",
"ID z", "DIV /", "ID x", "COLON :", "NUMBER 3", "SEMI ;", "ID x",
"LT <", "NUMBER 5", "SEMI ;", "ID y", "LT <", "REGEX /g/i",
"RPAREN )", "LBRACE {", "ID xyz", "LPAREN (", "ID x", "PLUSPLUS ++",
"RPAREN )", "SEMI ;", "RBRACE }"]
),
), (
'regex_illegal_1',
# Various "illegal" regexes that are valid according to the std.
(r"""/????/, /++++/, /[----]/ """,
['REGEX /????/', 'COMMA ,',
'REGEX /++++/', 'COMMA ,', 'REGEX /[----]/']
),
), (
'regex_stress_test_1',
# Stress cases from
# http://stackoverflow.com/questions/5533925/
# what-javascript-constructs-does-jslex-incorrectly-lex/5573409#5573409
(r"""/\[/""", [r"""REGEX /\[/"""]),
), (
'regex_stress_test_2',
(r"""/[i]/""", [r"""REGEX /[i]/"""]),
), (
'regex_stress_test_3',
(r"""/[\]]/""", [r"""REGEX /[\]]/"""]),
), (
'regex_stress_test_4',
(r"""/a[\]]/""", [r"""REGEX /a[\]]/"""]),
), (
'regex_stress_test_5',
(r"""/a[\]]b/""", [r"""REGEX /a[\]]b/"""]),
), (
'regex_stress_test_6',
(r"""/[\]/]/gi""", [r"""REGEX /[\]/]/gi"""]),
), (
'regex_stress_test_7',
(r"""/\[[^\]]+\]/gi""", [r"""REGEX /\[[^\]]+\]/gi"""]),
), (
'regex_stress_test_8',
(r"""
rexl.re = {
NAME: /^(?!\d)(?:\w)+|^"(?:[^"]|"")+"/,
UNQUOTED_LITERAL: /^@(?:(?!\d)(?:\w|\:)+|^"(?:[^"]|"")+")\[[^\]]+\]/,
QUOTED_LITERAL: /^'(?:[^']|'')*'/,
NUMERIC_LITERAL: /^[0-9]+(?:\.[0-9]*(?:[eE][-+][0-9]+)?)?/,
SYMBOL: /^(?:==|=|<>|<=|<|>=|>|!~~|!~|~~|~|!==|!=|!~=|!~|!|&|\||\.|\:|,|\(|\)|\[|\]|\{|\}|\?|\:|;|@|\^|\/\+|\/|\*|\+|-)/
};
""", [
"ID rexl", "PERIOD .", "ID re", "EQ =", "LBRACE {",
"ID NAME", "COLON :",
r"""REGEX /^(?!\d)(?:\w)+|^"(?:[^"]|"")+"/""", "COMMA ,",
"ID UNQUOTED_LITERAL", "COLON :",
r"""REGEX /^@(?:(?!\d)(?:\w|\:)+|^"(?:[^"]|"")+")\[[^\]]+\]/""",
"COMMA ,", "ID QUOTED_LITERAL", "COLON :",
r"""REGEX /^'(?:[^']|'')*'/""", "COMMA ,", "ID NUMERIC_LITERAL",
"COLON :",
r"""REGEX /^[0-9]+(?:\.[0-9]*(?:[eE][-+][0-9]+)?)?/""", "COMMA ,",
"ID SYMBOL", "COLON :",
r"""REGEX /^(?:==|=|<>|<=|<|>=|>|!~~|!~|~~|~|!==|!=|!~=|!~|!|&|\||\.|\:|,|\(|\)|\[|\]|\{|\}|\?|\:|;|@|\^|\/\+|\/|\*|\+|-)/""",
"RBRACE }", "SEMI ;"]),
), (
'regex_stress_test_9',
(r"""
rexl.re = {
NAME: /^(?!\d)(?:\w)+|^"(?:[^"]|"")+"/,
UNQUOTED_LITERAL: /^@(?:(?!\d)(?:\w|\:)+|^"(?:[^"]|"")+")\[[^\]]+\]/,
QUOTED_LITERAL: /^'(?:[^']|'')*'/,
NUMERIC_LITERAL: /^[0-9]+(?:\.[0-9]*(?:[eE][-+][0-9]+)?)?/,
SYMBOL: /^(?:==|=|<>|<=|<|>=|>|!~~|!~|~~|~|!==|!=|!~=|!~|!|&|\||\.|\:|,|\(|\)|\[|\]|\{|\}|\?|\:|;|@|\^|\/\+|\/|\*|\+|-)/
};
str = '"';
""", [
"ID rexl", "PERIOD .", "ID re", "EQ =", "LBRACE {",
"ID NAME", "COLON :", r"""REGEX /^(?!\d)(?:\w)+|^"(?:[^"]|"")+"/""",
"COMMA ,", "ID UNQUOTED_LITERAL", "COLON :",
r"""REGEX /^@(?:(?!\d)(?:\w|\:)+|^"(?:[^"]|"")+")\[[^\]]+\]/""",
"COMMA ,", "ID QUOTED_LITERAL", "COLON :",
r"""REGEX /^'(?:[^']|'')*'/""", "COMMA ,",
"ID NUMERIC_LITERAL", "COLON :",
r"""REGEX /^[0-9]+(?:\.[0-9]*(?:[eE][-+][0-9]+)?)?/""", "COMMA ,",
"ID SYMBOL", "COLON :",
r"""REGEX /^(?:==|=|<>|<=|<|>=|>|!~~|!~|~~|~|!==|!=|!~=|!~|!|&|\||\.|\:|,|\(|\)|\[|\]|\{|\}|\?|\:|;|@|\^|\/\+|\/|\*|\+|-)/""",
"RBRACE }", "SEMI ;",
"ID str", "EQ =", """STRING '"'""", "SEMI ;",
]),
), (
'regex_stress_test_10',
(r""" this._js = "e.str(\"" + this.value.replace(/\\/g, "\\\\").replace(/"/g, "\\\"") + "\")"; """,
["THIS this", "PERIOD .", "ID _js", "EQ =",
r'''STRING "e.str(\""''', "PLUS +", "THIS this", "PERIOD .",
"ID value", "PERIOD .", "ID replace", "LPAREN (", r"REGEX /\\/g",
"COMMA ,", r'STRING "\\\\"', "RPAREN )", "PERIOD .", "ID replace",
"LPAREN (", r'REGEX /"/g', "COMMA ,", r'STRING "\\\""', "RPAREN )",
"PLUS +", r'STRING "\")"', "SEMI ;"]),
), (
'regex_division_check',
('a = /a/ / /b/',
['ID a', 'EQ =', 'REGEX /a/', 'DIV /', 'REGEX /b/']),
), (
'regex_after_plus_brace',
('+{}/a/g',
['PLUS +', 'LBRACE {', 'RBRACE }', 'DIV /', 'ID a', 'DIV /', 'ID g']),
# The following pathological cases cannot be tested using the
# lexer alone, as the rules can only be addressed in conjunction
# with a parser
#
# 'regex_after_brace',
# ('{}/a/g',
# ['LBRACE {', 'RBRACE }', 'REGEX /a/g']),
# 'regex_after_if_brace',
# ('if (a) { } /a/.test(a)',
# ['IF if', 'LPAREN (', 'ID a', 'RPAREN )', 'LBRACE {', 'RBRACE }',
# 'REGEX /a/', "PERIOD .", "ID test", 'LPAREN (', 'ID a',
# 'RPAREN )']),
), (
'regex_case',
('switch(0){case /a/:}',
['SWITCH switch', 'LPAREN (', 'NUMBER 0', 'RPAREN )', 'LBRACE {',
'CASE case', 'REGEX /a/', 'COLON :', 'RBRACE }']),
), (
'div_after_valid_statement_function_call',
('if(){} f(a) / f(b)',
['IF if', 'LPAREN (', 'RPAREN )', 'LBRACE {', 'RBRACE }',
'ID f', 'LPAREN (', 'ID a', 'RPAREN )', 'DIV /',
'ID f', 'LPAREN (', 'ID b', 'RPAREN )']),
), (
'for_regex_slimit_issue_54',
('for (;;) /r/;',
['FOR for', 'LPAREN (', 'SEMI ;', 'SEMI ;', 'RPAREN )',
'REGEX /r/', 'SEMI ;']),
), (
'for_regex_slimit_issue_54_not_break_division',
('for (;;) { x / y }',
['FOR for', 'LPAREN (', 'SEMI ;', 'SEMI ;', 'RPAREN )',
'LBRACE {', 'ID x', 'DIV /', 'ID y', 'RBRACE }']),
), (
'for_regex_slimit_issue_54_bracket_accessor_check',
('s = {a:1} + s[2] / 1',
['ID s', 'EQ =', 'LBRACE {', 'ID a', 'COLON :', 'NUMBER 1',
'RBRACE }', 'PLUS +', 'ID s', 'LBRACKET [', 'NUMBER 2', 'RBRACKET ]',
'DIV /', 'NUMBER 1'])
), (
'for_regex_slimit_issue_54_function_parentheses_check',
('s = {a:1} + f(2) / 1',
['ID s', 'EQ =', 'LBRACE {', 'ID a', 'COLON :', 'NUMBER 1',
'RBRACE }', 'PLUS +', 'ID f', 'LPAREN (', 'NUMBER 2', 'RPAREN )',
'DIV /', 'NUMBER 1'])
), (
'for_regex_slimit_issue_54_math_parentheses_check',
('s = {a:1} + (2) / 1',
['ID s', 'EQ =', 'LBRACE {', 'ID a', 'COLON :', 'NUMBER 1',
'RBRACE }', 'PLUS +', 'LPAREN (', 'NUMBER 2', 'RPAREN )',
'DIV /', 'NUMBER 1'])
), (
'for_regex_slimit_issue_54_math_bracket_check',
('s = {a:1} + [2] / 1',
['ID s', 'EQ =', 'LBRACE {', 'ID a', 'COLON :', 'NUMBER 1',
'RBRACE }', 'PLUS +', 'LBRACKET [', 'NUMBER 2', 'RBRACKET ]',
'DIV /', 'NUMBER 1'])
), (
'for_regex_slimit_issue_54_math_braces_check',
('s = {a:2} / 166 / 9',
['ID s', 'EQ =', 'LBRACE {', 'ID a', 'COLON :', 'NUMBER 2',
'RBRACE }', 'DIV /', 'NUMBER 166', 'DIV /', 'NUMBER 9'])
), (
'do_while_regex',
('do {} while (0) /s/',
['DO do', 'LBRACE {', 'RBRACE }', 'WHILE while', 'LPAREN (',
'NUMBER 0', 'RPAREN )', 'REGEX /s/'])
), (
'if_regex',
('if (thing) /s/',
['IF if', 'LPAREN (', 'ID thing', 'RPAREN )', 'REGEX /s/'])
), (
'identifier_math',
('f (v) /s/g',
['ID f', 'LPAREN (', 'ID v', 'RPAREN )', 'DIV /', 'ID s', 'DIV /',
'ID g'])
), (
'section_7',
("a = b\n/hi/s",
['ID a', 'EQ =', 'ID b', 'DIV /', 'ID hi', 'DIV /', 'ID s'])
), (
'section_7_extras',
("a = b\n\n\n/hi/s",
['ID a', 'EQ =', 'ID b', 'DIV /', 'ID hi', 'DIV /', 'ID s'])
), (
'slimit_issue_39_and_57',
(r"f(a, 'hi\01').split('\1').split('\0');",
['ID f', 'LPAREN (', 'ID a', 'COMMA ,', r"STRING 'hi\01'", 'RPAREN )',
'PERIOD .', 'ID split', 'LPAREN (', r"STRING '\1'", 'RPAREN )',
'PERIOD .', 'ID split', 'LPAREN (', r"STRING '\0'", 'RPAREN )',
'SEMI ;'])
), (
'section_7_8_4_string_literal_with_7_3_conformance',
("'<LF>\\\n<CR>\\\r<LS>\\\u2028<PS>\\\u2029<CR><LF>\\\r\n'",
["STRING '<LF>\\\n<CR>\\\r<LS>\\\u2028<PS>\\\u2029<CR><LF>\\\r\n'"])
), (
# okay this is getting ridiculous how bad ECMA is.
'section_7_comments',
("a = b\n/** **/\n\n/hi/s",
['ID a', 'EQ =', 'ID b', 'DIV /', 'ID hi', 'DIV /', 'ID s'])
),
]
# various string related syntax errors
es5_error_cases_str = [
(
'unterminated_string_eof',
"var foo = 'test",
'Unterminated string literal "\'test" at 1:11',
), (
'naked_line_separator_in_string',
"vaf foo = 'test\u2028foo'",
'Unterminated string literal "\'test" at 1:11',
), (
'naked_line_feed_in_string',
"var foo = 'test\u2029foo'",
'Unterminated string literal "\'test" at 1:11',
), (
'naked_crnl_in_string',
"var foo = 'test\r\nfoo'",
'Unterminated string literal "\'test" at 1:11',
), (
'naked_cr_in_string',
"var foo = 'test\\\n\rfoo'",
# FIXME Note that the \\ is double escaped
'Unterminated string literal "\'test\\\\" at 1:11',
), (
'invalid_hex_sequence',
"var foo = 'fail\\x1'",
# backticks are converted to single quotes
"Invalid hexadecimal escape sequence `\\x1` at 1:16",
), (
'invalid_unicode_sequence',
"var foo = 'fail\\u12'",
"Invalid unicode escape sequence `\\u12` at 1:16",
), (
'invalid_hex_sequence_multiline',
"var foo = 'foobar\\\r\nfail\\x1'",
# backticks are converted to single quotes
"Invalid hexadecimal escape sequence `\\x1` at 2:5",
), (
'invalid_unicode_sequence_multiline',
"var foo = 'foobar\\\nfail\\u12'",
"Invalid unicode escape sequence `\\u12` at 2:5",
), (
'long_invalid_string_truncated',
"var foo = '1234567890abcdetruncated",
'Unterminated string literal "\'1234567890abcde..." at 1:11',
)
]
es5_comment_cases = [
(
'line_comment_whole',
('//comment\na = 5;\n',
['LINE_COMMENT //comment', 'ID a', 'EQ =', 'NUMBER 5', 'SEMI ;']),
), (
'line_comment_trail',
('a//comment', ['ID a', 'LINE_COMMENT //comment']),
), (
'block_comment_single',
('/***/b/=3//line',
['BLOCK_COMMENT /***/', 'ID b', 'DIVEQUAL /=',
'NUMBER 3', 'LINE_COMMENT //line']),
), (
'block_comment_multiline',
('/*\n * Copyright LGPL 2011 \n*/\na = 1;',
['BLOCK_COMMENT /*\n * Copyright LGPL 2011 \n*/',
'ID a', 'EQ =', 'NUMBER 1', 'SEMI ;']),
), (
# this will replace the standard test cases
'section_7_comments',
("a = b\n/** **/\n\n/hi/s",
['ID a', 'EQ =', 'ID b', 'BLOCK_COMMENT /** **/', 'DIV /', 'ID hi',
'DIV /', 'ID s'])
)
]
# replace the section_7_comments test case
es5_all_cases = es5_cases[:-1] + es5_comment_cases
# double quote version
es5_error_cases_str_dq = [
(n, arg.translate(swapquotes), msg.translate(swapquotes))
for n, arg, msg in es5_error_cases_str
]
# single quote version
es5_error_cases_str_sq = [
(n, arg, msg.translate({96: 39}))
for n, arg, msg in es5_error_cases_str
]
es5_pos_cases = [
(
'single_line',
"""
var foo = bar; // line 1
""", ([
'var 1:0', 'foo 1:4', '= 1:8', 'bar 1:10', '; 1:13'
], [
'var 1:1', 'foo 1:5', '= 1:9', 'bar 1:11', '; 1:14',
])
), (
'multi_line',
"""
var foo = bar; // line 1
var bar = baz; // line 4
""", ([
'var 1:0', 'foo 1:4', '= 1:8', 'bar 1:10', '; 1:13',
'var 4:28', 'bar 4:32', '= 4:36', 'baz 4:38', '; 4:41',
], [
'var 1:1', 'foo 1:5', '= 1:9', 'bar 1:11', '; 1:14',
'var 4:1', 'bar 4:5', '= 4:9', 'baz 4:11', '; 4:14',
])
), (
'inline_comment',
"""
// this is a comment // line 1
var foo = bar; // line 2
// another one // line 4
var bar = baz; // line 5
""", ([
'var 2:32', 'foo 2:36', '= 2:40', 'bar 2:42', '; 2:45',
'var 5:85', 'bar 5:89', '= 5:93', 'baz 5:95', '; 5:98',
], [
'var 2:1', 'foo 2:5', '= 2:9', 'bar 2:11', '; 2:14',
'var 5:1', 'bar 5:5', '= 5:9', 'baz 5:11', '; 5:14',
])
), (
'block_comment',
"""
/*
This is a block comment
*/
var foo = bar; // line 4
/* block single line */ // line 6
var bar = baz; // line 7
/* oops */bar(); // line 9
foo();
""", ([
'var 4:30', 'foo 4:34', '= 4:38', 'bar 4:40', '; 4:43',
'var 7:91', 'bar 7:95', '= 7:99', 'baz 7:101', '; 7:104',
'bar 9:128', '( 9:131', ') 9:132', '; 9:133',
'foo 11:149', '( 11:152', ') 11:153', '; 11:154',
], [
'var 4:1', 'foo 4:5', '= 4:9', 'bar 4:11', '; 4:14',
'var 7:1', 'bar 7:5', '= 7:9', 'baz 7:11', '; 7:14',
'bar 9:11', '( 9:14', ') 9:15', '; 9:16',
'foo 11:3', '( 11:6', ') 11:7', '; 11:8',
])
), (
'syntax_error_heading_comma',
"""
var a;
, b;
""", ([
'var 1:0', 'a 1:4', '; 1:5',
', 2:7', 'b 2:9', '; 2:10'
], [
'var 1:1', 'a 1:5', '; 1:6',
', 2:1', 'b 2:3', '; 2:4'
])
)
]
def run_lexer(value, lexer_cls):
lexer = lexer_cls()
lexer.input(value)
return ['%s %s' % (token.type, token.value) for token in lexer]
def run_lexer_pos(value, | lexer = lexer_cls()
lexer.input(textwrap.dedent(value).strip())
tokens = list(lexer)
return ([
'%s %d:%d' % (token.value, token.lineno, token.lexpos)
for token in tokens
], [
'%s %d:%d' % (token.value, token.lineno, token.colno)
for token in tokens
])
| lexer_cls):
| identifier_name |
lexer.py | # -*- coding: utf-8 -*-
"""
Collection of raw lexer test cases and class constructor.
"""
from __future__ import unicode_literals
import textwrap
swapquotes = {
39: 34, 34: 39,
# note the follow are interim error messages
96: 39,
}
# The structure and some test cases are taken
# from https://bitbucket.org/ned/jslex
es5_cases = [
(
# Identifiers
'identifiers_ascii',
('i my_variable_name c17 _dummy $str $ _ CamelCase class2type',
['ID i', 'ID my_variable_name', 'ID c17', 'ID _dummy',
'ID $str', 'ID $', 'ID _', 'ID CamelCase', 'ID class2type']
),
), (
'identifiers_unicode',
(u'\u03c0 \u03c0_tail var\ua67c',
[u'ID \u03c0', u'ID \u03c0_tail', u'ID var\ua67c']),
), (
# https://github.com/rspivak/slimit/issues/2
'slimit_issue_2',
('nullify truelie falsepositive',
['ID nullify', 'ID truelie', 'ID falsepositive']),
), (
'keywords_break',
('break Break BREAK', ['BREAK break', 'ID Break', 'ID BREAK']),
), (
# Literals
'literals',
('null true false Null True False',
['NULL null', 'TRUE true', 'FALSE false',
'ID Null', 'ID True', 'ID False']
),
), (
# Punctuators
'punctuators_simple',
('a /= b', ['ID a', 'DIVEQUAL /=', 'ID b']),
), (
'punctuators_various_equality',
(('= == != === !== < > <= >= || && ++ -- << >> '
'>>> += -= *= <<= >>= >>>= &= %= ^= |='),
['EQ =', 'EQEQ ==', 'NE !=', 'STREQ ===', 'STRNEQ !==', 'LT <',
'GT >', 'LE <=', 'GE >=', 'OR ||', 'AND &&', 'PLUSPLUS ++',
'MINUSMINUS --', 'LSHIFT <<', 'RSHIFT >>', 'URSHIFT >>>',
'PLUSEQUAL +=', 'MINUSEQUAL -=', 'MULTEQUAL *=', 'LSHIFTEQUAL <<=',
'RSHIFTEQUAL >>=', 'URSHIFTEQUAL >>>=', 'ANDEQUAL &=', 'MODEQUAL %=',
'XOREQUAL ^=', 'OREQUAL |=',
]
),
), (
'punctuators_various_others',
('. , ; : + - * % & | ^ ~ ? ! ( ) { } [ ]',
['PERIOD .', 'COMMA ,', 'SEMI ;', 'COLON :', 'PLUS +', 'MINUS -',
'MULT *', 'MOD %', 'BAND &', 'BOR |', 'BXOR ^', 'BNOT ~',
'CONDOP ?', 'NOT !', 'LPAREN (', 'RPAREN )', 'LBRACE {', 'RBRACE }',
'LBRACKET [', 'RBRACKET ]']
),
), (
'division_simple',
('a / b', ['ID a', 'DIV /', 'ID b']),
), (
'numbers',
(('3 3.3 0 0. 0.0 0.001 010 3.e2 3.e-2 3.e+2 3E2 3E+2 3E-2 '
'0.5e2 0.5e+2 0.5e-2 33 128.15 0x001 0X12ABCDEF 0xabcdef'),
['NUMBER 3', 'NUMBER 3.3', 'NUMBER 0', 'NUMBER 0.', 'NUMBER 0.0',
'NUMBER 0.001', 'NUMBER 010', 'NUMBER 3.e2', 'NUMBER 3.e-2',
'NUMBER 3.e+2', 'NUMBER 3E2', 'NUMBER 3E+2', 'NUMBER 3E-2',
'NUMBER 0.5e2', 'NUMBER 0.5e+2', 'NUMBER 0.5e-2', 'NUMBER 33',
'NUMBER 128.15', 'NUMBER 0x001', 'NUMBER 0X12ABCDEF',
'NUMBER 0xabcdef']
),
), (
'strings_simple_quote',
(""" '"' """, ["""STRING '"'"""]),
), (
'strings_escape_quote_tab',
(r'''"foo" 'foo' "x\";" 'x\';' "foo\tbar"''',
['STRING "foo"', """STRING 'foo'""", r'STRING "x\";"',
r"STRING 'x\';'", r'STRING "foo\tbar"']
),
), (
'strings_escape_ascii',
(r"""'\x55' "\x12ABCDEF" '!@#$%^&*()_+{}[]\";?'""",
[r"STRING '\x55'", r'STRING "\x12ABCDEF"',
r"STRING '!@#$%^&*()_+{}[]\";?'"]
),
), (
'strings_escape_unicode',
(r"""'\u0001' "\uFCEF" 'a\\\b\n'""",
[r"STRING '\u0001'", r'STRING "\uFCEF"', r"STRING 'a\\\b\n'"]
),
), (
'strings_unicode',
(u'"ัะตัั ัััะพะบะธ\\""', [u'STRING "ัะตัั ัััะพะบะธ\\""']),
), (
'strings_escape_octal',
(r"""'\251'""", [r"""STRING '\251'"""]),
), (
# Bug - https://github.com/rspivak/slimit/issues/5
'slimit_issue_5',
(r"var tagRegExp = new RegExp('<(\/*)(FooBar)', 'gi');",
['VAR var', 'ID tagRegExp', 'EQ =',
'NEW new', 'ID RegExp', 'LPAREN (',
r"STRING '<(\/*)(FooBar)'", 'COMMA ,', "STRING 'gi'",
'RPAREN )', 'SEMI ;']),
), (
# same as above but inside double quotes
'slimit_issue_5_double_quote',
(r'"<(\/*)(FooBar)"', [r'STRING "<(\/*)(FooBar)"']),
), (
# multiline string (string written across multiple lines
# of code) https://github.com/rspivak/slimit/issues/24
'slimit_issue_24_multi_line_code_double',
("var a = 'hello \\\n world'",
['VAR var', 'ID a', 'EQ =', "STRING 'hello \\\n world'"]),
), (
'slimit_issue_24_multi_line_code_single',
('var a = "hello \\\r world"',
['VAR var', 'ID a', 'EQ =', 'STRING "hello \\\r world"']),
), (
# regex
'regex_1',
(r'a=/a*/,1', ['ID a', 'EQ =', 'REGEX /a*/', 'COMMA ,', 'NUMBER 1']),
), (
'regex_2',
(r'a=/a*[^/]+/,1',
['ID a', 'EQ =', 'REGEX /a*[^/]+/', 'COMMA ,', 'NUMBER 1']
),
), (
'regex_3',
(r'a=/a*\[^/,1',
['ID a', 'EQ =', r'REGEX /a*\[^/', 'COMMA ,', 'NUMBER 1']
),
), (
'regex_4',
(r'a=/\//,1', ['ID a', 'EQ =', r'REGEX /\//', 'COMMA ,', 'NUMBER 1']),
), (
# not a regex, just a division
# https://github.com/rspivak/slimit/issues/6
'slimit_issue_6_not_regex_but_division',
(r'x = this / y;',
['ID x', 'EQ =', 'THIS this', r'DIV /', r'ID y', r'SEMI ;']),
), (
'regex_mozilla_example_1',
# next two are from
# http://www.mozilla.org/js/language/js20-2002-04/rationale/syntax.html#regular-expressions
('for (var x = a in foo && "</x>" || mot ? z:/x:3;x<5;y</g/i) '
'{xyz(x++);}',
["FOR for", "LPAREN (", "VAR var", "ID x", "EQ =", "ID a", "IN in",
"ID foo", "AND &&", 'STRING "</x>"', "OR ||", "ID mot", "CONDOP ?",
"ID z", "COLON :", "REGEX /x:3;x<5;y</g", "DIV /", "ID i",
"RPAREN )", "LBRACE {", "ID xyz", "LPAREN (", "ID x", "PLUSPLUS ++",
"RPAREN )", "SEMI ;", "RBRACE }"]
),
), (
'regex_mozilla_example_2',
('for (var x = a in foo && "</x>" || mot ? z/x:3;x<5;y</g/i) '
'{xyz(x++);}',
["FOR for", "LPAREN (", "VAR var", "ID x", "EQ =", "ID a", "IN in",
"ID foo", "AND &&", 'STRING "</x>"', "OR ||", "ID mot", "CONDOP ?",
"ID z", "DIV /", "ID x", "COLON :", "NUMBER 3", "SEMI ;", "ID x",
"LT <", "NUMBER 5", "SEMI ;", "ID y", "LT <", "REGEX /g/i",
"RPAREN )", "LBRACE {", "ID xyz", "LPAREN (", "ID x", "PLUSPLUS ++",
"RPAREN )", "SEMI ;", "RBRACE }"]
),
), (
'regex_illegal_1',
# Various "illegal" regexes that are valid according to the std.
(r"""/????/, /++++/, /[----]/ """,
['REGEX /????/', 'COMMA ,',
'REGEX /++++/', 'COMMA ,', 'REGEX /[----]/']
),
), (
'regex_stress_test_1',
# Stress cases from
# http://stackoverflow.com/questions/5533925/
# what-javascript-constructs-does-jslex-incorrectly-lex/5573409#5573409
(r"""/\[/""", [r"""REGEX /\[/"""]),
), (
'regex_stress_test_2',
(r"""/[i]/""", [r"""REGEX /[i]/"""]),
), (
'regex_stress_test_3',
(r"""/[\]]/""", [r"""REGEX /[\]]/"""]),
), (
'regex_stress_test_4',
(r"""/a[\]]/""", [r"""REGEX /a[\]]/"""]),
), (
'regex_stress_test_5',
(r"""/a[\]]b/""", [r"""REGEX /a[\]]b/"""]),
), (
'regex_stress_test_6',
(r"""/[\]/]/gi""", [r"""REGEX /[\]/]/gi"""]),
), (
'regex_stress_test_7',
(r"""/\[[^\]]+\]/gi""", [r"""REGEX /\[[^\]]+\]/gi"""]),
), (
'regex_stress_test_8',
(r"""
rexl.re = {
NAME: /^(?!\d)(?:\w)+|^"(?:[^"]|"")+"/,
UNQUOTED_LITERAL: /^@(?:(?!\d)(?:\w|\:)+|^"(?:[^"]|"")+")\[[^\]]+\]/,
QUOTED_LITERAL: /^'(?:[^']|'')*'/,
NUMERIC_LITERAL: /^[0-9]+(?:\.[0-9]*(?:[eE][-+][0-9]+)?)?/,
SYMBOL: /^(?:==|=|<>|<=|<|>=|>|!~~|!~|~~|~|!==|!=|!~=|!~|!|&|\||\.|\:|,|\(|\)|\[|\]|\{|\}|\?|\:|;|@|\^|\/\+|\/|\*|\+|-)/
};
""", [
"ID rexl", "PERIOD .", "ID re", "EQ =", "LBRACE {",
"ID NAME", "COLON :",
r"""REGEX /^(?!\d)(?:\w)+|^"(?:[^"]|"")+"/""", "COMMA ,",
"ID UNQUOTED_LITERAL", "COLON :",
r"""REGEX /^@(?:(?!\d)(?:\w|\:)+|^"(?:[^"]|"")+")\[[^\]]+\]/""",
"COMMA ,", "ID QUOTED_LITERAL", "COLON :",
r"""REGEX /^'(?:[^']|'')*'/""", "COMMA ,", "ID NUMERIC_LITERAL",
"COLON :",
r"""REGEX /^[0-9]+(?:\.[0-9]*(?:[eE][-+][0-9]+)?)?/""", "COMMA ,",
"ID SYMBOL", "COLON :",
r"""REGEX /^(?:==|=|<>|<=|<|>=|>|!~~|!~|~~|~|!==|!=|!~=|!~|!|&|\||\.|\:|,|\(|\)|\[|\]|\{|\}|\?|\:|;|@|\^|\/\+|\/|\*|\+|-)/""",
"RBRACE }", "SEMI ;"]),
), (
'regex_stress_test_9',
(r"""
rexl.re = {
NAME: /^(?!\d)(?:\w)+|^"(?:[^"]|"")+"/,
UNQUOTED_LITERAL: /^@(?:(?!\d)(?:\w|\:)+|^"(?:[^"]|"")+")\[[^\]]+\]/,
QUOTED_LITERAL: /^'(?:[^']|'')*'/,
NUMERIC_LITERAL: /^[0-9]+(?:\.[0-9]*(?:[eE][-+][0-9]+)?)?/,
SYMBOL: /^(?:==|=|<>|<=|<|>=|>|!~~|!~|~~|~|!==|!=|!~=|!~|!|&|\||\.|\:|,|\(|\)|\[|\]|\{|\}|\?|\:|;|@|\^|\/\+|\/|\*|\+|-)/
};
str = '"';
""", [
"ID rexl", "PERIOD .", "ID re", "EQ =", "LBRACE {",
"ID NAME", "COLON :", r"""REGEX /^(?!\d)(?:\w)+|^"(?:[^"]|"")+"/""",
"COMMA ,", "ID UNQUOTED_LITERAL", "COLON :",
r"""REGEX /^@(?:(?!\d)(?:\w|\:)+|^"(?:[^"]|"")+")\[[^\]]+\]/""",
"COMMA ,", "ID QUOTED_LITERAL", "COLON :",
r"""REGEX /^'(?:[^']|'')*'/""", "COMMA ,",
"ID NUMERIC_LITERAL", "COLON :",
r"""REGEX /^[0-9]+(?:\.[0-9]*(?:[eE][-+][0-9]+)?)?/""", "COMMA ,",
"ID SYMBOL", "COLON :",
r"""REGEX /^(?:==|=|<>|<=|<|>=|>|!~~|!~|~~|~|!==|!=|!~=|!~|!|&|\||\.|\:|,|\(|\)|\[|\]|\{|\}|\?|\:|;|@|\^|\/\+|\/|\*|\+|-)/""",
"RBRACE }", "SEMI ;",
"ID str", "EQ =", """STRING '"'""", "SEMI ;",
]),
), (
'regex_stress_test_10',
(r""" this._js = "e.str(\"" + this.value.replace(/\\/g, "\\\\").replace(/"/g, "\\\"") + "\")"; """,
["THIS this", "PERIOD .", "ID _js", "EQ =",
r'''STRING "e.str(\""''', "PLUS +", "THIS this", "PERIOD .",
"ID value", "PERIOD .", "ID replace", "LPAREN (", r"REGEX /\\/g",
"COMMA ,", r'STRING "\\\\"', "RPAREN )", "PERIOD .", "ID replace",
"LPAREN (", r'REGEX /"/g', "COMMA ,", r'STRING "\\\""', "RPAREN )",
"PLUS +", r'STRING "\")"', "SEMI ;"]),
), (
'regex_division_check',
('a = /a/ / /b/',
['ID a', 'EQ =', 'REGEX /a/', 'DIV /', 'REGEX /b/']),
), (
'regex_after_plus_brace',
('+{}/a/g',
['PLUS +', 'LBRACE {', 'RBRACE }', 'DIV /', 'ID a', 'DIV /', 'ID g']),
# The following pathological cases cannot be tested using the
# lexer alone, as the rules can only be addressed in conjunction
# with a parser
#
# 'regex_after_brace',
# ('{}/a/g',
# ['LBRACE {', 'RBRACE }', 'REGEX /a/g']),
# 'regex_after_if_brace',
# ('if (a) { } /a/.test(a)',
# ['IF if', 'LPAREN (', 'ID a', 'RPAREN )', 'LBRACE {', 'RBRACE }',
# 'REGEX /a/', "PERIOD .", "ID test", 'LPAREN (', 'ID a',
# 'RPAREN )']),
), (
'regex_case',
('switch(0){case /a/:}',
['SWITCH switch', 'LPAREN (', 'NUMBER 0', 'RPAREN )', 'LBRACE {',
'CASE case', 'REGEX /a/', 'COLON :', 'RBRACE }']),
), (
'div_after_valid_statement_function_call',
('if(){} f(a) / f(b)',
['IF if', 'LPAREN (', 'RPAREN )', 'LBRACE {', 'RBRACE }',
'ID f', 'LPAREN (', 'ID a', 'RPAREN )', 'DIV /',
'ID f', 'LPAREN (', 'ID b', 'RPAREN )']),
), (
'for_regex_slimit_issue_54',
('for (;;) /r/;',
['FOR for', 'LPAREN (', 'SEMI ;', 'SEMI ;', 'RPAREN )',
'REGEX /r/', 'SEMI ;']),
), (
'for_regex_slimit_issue_54_not_break_division',
('for (;;) { x / y }',
['FOR for', 'LPAREN (', 'SEMI ;', 'SEMI ;', 'RPAREN )',
'LBRACE {', 'ID x', 'DIV /', 'ID y', 'RBRACE }']),
), (
'for_regex_slimit_issue_54_bracket_accessor_check',
('s = {a:1} + s[2] / 1',
['ID s', 'EQ =', 'LBRACE {', 'ID a', 'COLON :', 'NUMBER 1',
'RBRACE }', 'PLUS +', 'ID s', 'LBRACKET [', 'NUMBER 2', 'RBRACKET ]',
'DIV /', 'NUMBER 1'])
), (
'for_regex_slimit_issue_54_function_parentheses_check',
('s = {a:1} + f(2) / 1',
['ID s', 'EQ =', 'LBRACE {', 'ID a', 'COLON :', 'NUMBER 1',
'RBRACE }', 'PLUS +', 'ID f', 'LPAREN (', 'NUMBER 2', 'RPAREN )',
'DIV /', 'NUMBER 1'])
), (
'for_regex_slimit_issue_54_math_parentheses_check',
('s = {a:1} + (2) / 1',
['ID s', 'EQ =', 'LBRACE {', 'ID a', 'COLON :', 'NUMBER 1',
'RBRACE }', 'PLUS +', 'LPAREN (', 'NUMBER 2', 'RPAREN )',
'DIV /', 'NUMBER 1'])
), (
'for_regex_slimit_issue_54_math_bracket_check',
('s = {a:1} + [2] / 1',
['ID s', 'EQ =', 'LBRACE {', 'ID a', 'COLON :', 'NUMBER 1',
'RBRACE }', 'PLUS +', 'LBRACKET [', 'NUMBER 2', 'RBRACKET ]',
'DIV /', 'NUMBER 1'])
), (
'for_regex_slimit_issue_54_math_braces_check',
('s = {a:2} / 166 / 9',
['ID s', 'EQ =', 'LBRACE {', 'ID a', 'COLON :', 'NUMBER 2',
'RBRACE }', 'DIV /', 'NUMBER 166', 'DIV /', 'NUMBER 9'])
), (
'do_while_regex',
('do {} while (0) /s/',
['DO do', 'LBRACE {', 'RBRACE }', 'WHILE while', 'LPAREN (',
'NUMBER 0', 'RPAREN )', 'REGEX /s/'])
), (
'if_regex',
('if (thing) /s/',
['IF if', 'LPAREN (', 'ID thing', 'RPAREN )', 'REGEX /s/'])
), (
'identifier_math',
('f (v) /s/g',
['ID f', 'LPAREN (', 'ID v', 'RPAREN )', 'DIV /', 'ID s', 'DIV /',
'ID g'])
), (
'section_7',
("a = b\n/hi/s",
['ID a', 'EQ =', 'ID b', 'DIV /', 'ID hi', 'DIV /', 'ID s'])
), (
'section_7_extras',
("a = b\n\n\n/hi/s",
['ID a', 'EQ =', 'ID b', 'DIV /', 'ID hi', 'DIV /', 'ID s'])
), (
'slimit_issue_39_and_57',
(r"f(a, 'hi\01').split('\1').split('\0');",
['ID f', 'LPAREN (', 'ID a', 'COMMA ,', r"STRING 'hi\01'", 'RPAREN )',
'PERIOD .', 'ID split', 'LPAREN (', r"STRING '\1'", 'RPAREN )',
'PERIOD .', 'ID split', 'LPAREN (', r"STRING '\0'", 'RPAREN )',
'SEMI ;'])
), (
'section_7_8_4_string_literal_with_7_3_conformance',
("'<LF>\\\n<CR>\\\r<LS>\\\u2028<PS>\\\u2029<CR><LF>\\\r\n'",
["STRING '<LF>\\\n<CR>\\\r<LS>\\\u2028<PS>\\\u2029<CR><LF>\\\r\n'"])
), (
# okay this is getting ridiculous how bad ECMA is.
'section_7_comments',
("a = b\n/** **/\n\n/hi/s",
['ID a', 'EQ =', 'ID b', 'DIV /', 'ID hi', 'DIV /', 'ID s'])
),
]
# various string related syntax errors
es5_error_cases_str = [
(
'unterminated_string_eof',
"var foo = 'test",
'Unterminated string literal "\'test" at 1:11',
), (
'naked_line_separator_in_string',
"vaf foo = 'test\u2028foo'",
'Unterminated string literal "\'test" at 1:11',
), (
'naked_line_feed_in_string',
"var foo = 'test\u2029foo'",
'Unterminated string literal "\'test" at 1:11',
), (
'naked_crnl_in_string',
"var foo = 'test\r\nfoo'",
'Unterminated string literal "\'test" at 1:11',
), (
'naked_cr_in_string',
"var foo = 'test\\\n\rfoo'",
# FIXME Note that the \\ is double escaped
'Unterminated string literal "\'test\\\\" at 1:11',
), (
'invalid_hex_sequence',
"var foo = 'fail\\x1'",
# backticks are converted to single quotes
"Invalid hexadecimal escape sequence `\\x1` at 1:16",
), (
'invalid_unicode_sequence',
"var foo = 'fail\\u12'",
"Invalid unicode escape sequence `\\u12` at 1:16",
), (
'invalid_hex_sequence_multiline',
"var foo = 'foobar\\\r\nfail\\x1'",
# backticks are converted to single quotes
"Invalid hexadecimal escape sequence `\\x1` at 2:5",
), (
'invalid_unicode_sequence_multiline',
"var foo = 'foobar\\\nfail\\u12'",
"Invalid unicode escape sequence `\\u12` at 2:5",
), (
'long_invalid_string_truncated',
"var foo = '1234567890abcdetruncated",
'Unterminated string literal "\'1234567890abcde..." at 1:11',
)
]
es5_comment_cases = [
(
'line_comment_whole',
('//comment\na = 5;\n',
['LINE_COMMENT //comment', 'ID a', 'EQ =', 'NUMBER 5', 'SEMI ;']),
), (
'line_comment_trail',
('a//comment', ['ID a', 'LINE_COMMENT //comment']),
), (
'block_comment_single',
('/***/b/=3//line',
['BLOCK_COMMENT /***/', 'ID b', 'DIVEQUAL /=',
'NUMBER 3', 'LINE_COMMENT //line']),
), (
'block_comment_multiline',
('/*\n * Copyright LGPL 2011 \n*/\na = 1;',
['BLOCK_COMMENT /*\n * Copyright LGPL 2011 \n*/',
'ID a', 'EQ =', 'NUMBER 1', 'SEMI ;']),
), (
# this will replace the standard test cases
'section_7_comments',
("a = b\n/** **/\n\n/hi/s",
['ID a', 'EQ =', 'ID b', 'BLOCK_COMMENT /** **/', 'DIV /', 'ID hi',
'DIV /', 'ID s'])
)
]
# replace the section_7_comments test case
es5_all_cases = es5_cases[:-1] + es5_comment_cases
# double quote version
es5_error_cases_str_dq = [
(n, arg.translate(swapquotes), msg.translate(swapquotes))
for n, arg, msg in es5_error_cases_str
]
# single quote version
es5_error_cases_str_sq = [
(n, arg, msg.translate({96: 39}))
for n, arg, msg in es5_error_cases_str
]
es5_pos_cases = [
(
'single_line',
"""
var foo = bar; // line 1
""", ([
'var 1:0', 'foo 1:4', '= 1:8', 'bar 1:10', '; 1:13'
], [
'var 1:1', 'foo 1:5', '= 1:9', 'bar 1:11', '; 1:14',
])
), (
'multi_line',
"""
var foo = bar; // line 1
var bar = baz; // line 4
""", ([
'var 1:0', 'foo 1:4', '= 1:8', 'bar 1:10', '; 1:13',
'var 4:28', 'bar 4:32', '= 4:36', 'baz 4:38', '; 4:41',
], [
'var 1:1', 'foo 1:5', '= 1:9', 'bar 1:11', '; 1:14',
'var 4:1', 'bar 4:5', '= 4:9', 'baz 4:11', '; 4:14',
])
), (
'inline_comment',
"""
// this is a comment // line 1
var foo = bar; // line 2
// another one // line 4
var bar = baz; // line 5
""", ([
'var 2:32', 'foo 2:36', '= 2:40', 'bar 2:42', '; 2:45',
'var 5:85', 'bar 5:89', '= 5:93', 'baz 5:95', '; 5:98',
], [
'var 2:1', 'foo 2:5', '= 2:9', 'bar 2:11', '; 2:14',
'var 5:1', 'bar 5:5', '= 5:9', 'baz 5:11', '; 5:14',
])
), (
'block_comment',
"""
/*
This is a block comment
*/
var foo = bar; // line 4
/* block single line */ // line 6
var bar = baz; // line 7
/* oops */bar(); // line 9
foo();
""", ([
'var 4:30', 'foo 4:34', '= 4:38', 'bar 4:40', '; 4:43',
'var 7:91', 'bar 7:95', '= 7:99', 'baz 7:101', '; 7:104',
'bar 9:128', '( 9:131', ') 9:132', '; 9:133',
'foo 11:149', '( 11:152', ') 11:153', '; 11:154',
], [
'var 4:1', 'foo 4:5', '= 4:9', 'bar 4:11', '; 4:14',
'var 7:1', 'bar 7:5', '= 7:9', 'baz 7:11', '; 7:14',
'bar 9:11', '( 9:14', ') 9:15', '; 9:16',
'foo 11:3', '( 11:6', ') 11:7', '; 11:8',
])
), (
'syntax_error_heading_comma',
"""
var a;
, b;
""", ([
'var 1:0', 'a 1:4', '; 1:5',
', 2:7', 'b 2:9', '; 2:10'
], [
'var 1:1', 'a 1:5', '; 1:6',
', 2:1', 'b 2:3', '; 2:4'
])
)
]
def run_lexer(value, lexer_cls):
lexer = lexer_cls()
lexer.input(value)
return ['%s %s' % (token.type, token.value) for token in lexer]
def run_lexer_pos(value, lexer_cls):
lexer = lexer_cls()
| lexer.input(textwrap.dedent(value).strip())
tokens = list(lexer)
return ([
'%s %d:%d' % (token.value, token.lineno, token.lexpos)
for token in tokens
], [
'%s %d:%d' % (token.value, token.lineno, token.colno)
for token in tokens
])
| identifier_body | |
lexer.py | # -*- coding: utf-8 -*-
"""
Collection of raw lexer test cases and class constructor.
"""
from __future__ import unicode_literals
import textwrap
swapquotes = {
39: 34, 34: 39,
# note the follow are interim error messages
96: 39,
}
# The structure and some test cases are taken
# from https://bitbucket.org/ned/jslex
es5_cases = [
(
# Identifiers
'identifiers_ascii',
('i my_variable_name c17 _dummy $str $ _ CamelCase class2type',
['ID i', 'ID my_variable_name', 'ID c17', 'ID _dummy',
'ID $str', 'ID $', 'ID _', 'ID CamelCase', 'ID class2type']
),
), (
'identifiers_unicode',
(u'\u03c0 \u03c0_tail var\ua67c',
[u'ID \u03c0', u'ID \u03c0_tail', u'ID var\ua67c']),
), (
# https://github.com/rspivak/slimit/issues/2
'slimit_issue_2',
('nullify truelie falsepositive',
['ID nullify', 'ID truelie', 'ID falsepositive']),
), (
'keywords_break',
('break Break BREAK', ['BREAK break', 'ID Break', 'ID BREAK']),
), (
# Literals
'literals',
('null true false Null True False',
['NULL null', 'TRUE true', 'FALSE false',
'ID Null', 'ID True', 'ID False']
),
), (
# Punctuators
'punctuators_simple',
('a /= b', ['ID a', 'DIVEQUAL /=', 'ID b']),
), (
'punctuators_various_equality',
(('= == != === !== < > <= >= || && ++ -- << >> '
'>>> += -= *= <<= >>= >>>= &= %= ^= |='),
['EQ =', 'EQEQ ==', 'NE !=', 'STREQ ===', 'STRNEQ !==', 'LT <',
'GT >', 'LE <=', 'GE >=', 'OR ||', 'AND &&', 'PLUSPLUS ++',
'MINUSMINUS --', 'LSHIFT <<', 'RSHIFT >>', 'URSHIFT >>>',
'PLUSEQUAL +=', 'MINUSEQUAL -=', 'MULTEQUAL *=', 'LSHIFTEQUAL <<=',
'RSHIFTEQUAL >>=', 'URSHIFTEQUAL >>>=', 'ANDEQUAL &=', 'MODEQUAL %=',
'XOREQUAL ^=', 'OREQUAL |=',
]
),
), (
'punctuators_various_others',
('. , ; : + - * % & | ^ ~ ? ! ( ) { } [ ]',
['PERIOD .', 'COMMA ,', 'SEMI ;', 'COLON :', 'PLUS +', 'MINUS -',
'MULT *', 'MOD %', 'BAND &', 'BOR |', 'BXOR ^', 'BNOT ~',
'CONDOP ?', 'NOT !', 'LPAREN (', 'RPAREN )', 'LBRACE {', 'RBRACE }',
'LBRACKET [', 'RBRACKET ]']
),
), (
'division_simple',
('a / b', ['ID a', 'DIV /', 'ID b']),
), (
'numbers',
(('3 3.3 0 0. 0.0 0.001 010 3.e2 3.e-2 3.e+2 3E2 3E+2 3E-2 '
'0.5e2 0.5e+2 0.5e-2 33 128.15 0x001 0X12ABCDEF 0xabcdef'),
['NUMBER 3', 'NUMBER 3.3', 'NUMBER 0', 'NUMBER 0.', 'NUMBER 0.0',
'NUMBER 0.001', 'NUMBER 010', 'NUMBER 3.e2', 'NUMBER 3.e-2',
'NUMBER 3.e+2', 'NUMBER 3E2', 'NUMBER 3E+2', 'NUMBER 3E-2',
'NUMBER 0.5e2', 'NUMBER 0.5e+2', 'NUMBER 0.5e-2', 'NUMBER 33',
'NUMBER 128.15', 'NUMBER 0x001', 'NUMBER 0X12ABCDEF',
'NUMBER 0xabcdef']
),
), (
'strings_simple_quote',
(""" '"' """, ["""STRING '"'"""]),
), (
'strings_escape_quote_tab',
(r'''"foo" 'foo' "x\";" 'x\';' "foo\tbar"''',
['STRING "foo"', """STRING 'foo'""", r'STRING "x\";"',
r"STRING 'x\';'", r'STRING "foo\tbar"']
),
), (
'strings_escape_ascii',
(r"""'\x55' "\x12ABCDEF" '!@#$%^&*()_+{}[]\";?'""",
[r"STRING '\x55'", r'STRING "\x12ABCDEF"',
r"STRING '!@#$%^&*()_+{}[]\";?'"]
),
), (
'strings_escape_unicode',
(r"""'\u0001' "\uFCEF" 'a\\\b\n'""",
[r"STRING '\u0001'", r'STRING "\uFCEF"', r"STRING 'a\\\b\n'"]
),
), (
'strings_unicode',
(u'"ัะตัั ัััะพะบะธ\\""', [u'STRING "ัะตัั ัััะพะบะธ\\""']),
), (
'strings_escape_octal',
(r"""'\251'""", [r"""STRING '\251'"""]),
), (
# Bug - https://github.com/rspivak/slimit/issues/5
'slimit_issue_5',
(r"var tagRegExp = new RegExp('<(\/*)(FooBar)', 'gi');",
['VAR var', 'ID tagRegExp', 'EQ =',
'NEW new', 'ID RegExp', 'LPAREN (',
r"STRING '<(\/*)(FooBar)'", 'COMMA ,', "STRING 'gi'",
'RPAREN )', 'SEMI ;']),
), (
# same as above but inside double quotes
'slimit_issue_5_double_quote',
(r'"<(\/*)(FooBar)"', [r'STRING "<(\/*)(FooBar)"']),
), (
# multiline string (string written across multiple lines
# of code) https://github.com/rspivak/slimit/issues/24
'slimit_issue_24_multi_line_code_double',
("var a = 'hello \\\n world'",
['VAR var', 'ID a', 'EQ =', "STRING 'hello \\\n world'"]),
), (
'slimit_issue_24_multi_line_code_single',
('var a = "hello \\\r world"',
['VAR var', 'ID a', 'EQ =', 'STRING "hello \\\r world"']),
), (
# regex
'regex_1', | (r'a=/a*/,1', ['ID a', 'EQ =', 'REGEX /a*/', 'COMMA ,', 'NUMBER 1']),
), (
'regex_2',
(r'a=/a*[^/]+/,1',
['ID a', 'EQ =', 'REGEX /a*[^/]+/', 'COMMA ,', 'NUMBER 1']
),
), (
'regex_3',
(r'a=/a*\[^/,1',
['ID a', 'EQ =', r'REGEX /a*\[^/', 'COMMA ,', 'NUMBER 1']
),
), (
'regex_4',
(r'a=/\//,1', ['ID a', 'EQ =', r'REGEX /\//', 'COMMA ,', 'NUMBER 1']),
), (
# not a regex, just a division
# https://github.com/rspivak/slimit/issues/6
'slimit_issue_6_not_regex_but_division',
(r'x = this / y;',
['ID x', 'EQ =', 'THIS this', r'DIV /', r'ID y', r'SEMI ;']),
), (
'regex_mozilla_example_1',
# next two are from
# http://www.mozilla.org/js/language/js20-2002-04/rationale/syntax.html#regular-expressions
('for (var x = a in foo && "</x>" || mot ? z:/x:3;x<5;y</g/i) '
'{xyz(x++);}',
["FOR for", "LPAREN (", "VAR var", "ID x", "EQ =", "ID a", "IN in",
"ID foo", "AND &&", 'STRING "</x>"', "OR ||", "ID mot", "CONDOP ?",
"ID z", "COLON :", "REGEX /x:3;x<5;y</g", "DIV /", "ID i",
"RPAREN )", "LBRACE {", "ID xyz", "LPAREN (", "ID x", "PLUSPLUS ++",
"RPAREN )", "SEMI ;", "RBRACE }"]
),
), (
'regex_mozilla_example_2',
('for (var x = a in foo && "</x>" || mot ? z/x:3;x<5;y</g/i) '
'{xyz(x++);}',
["FOR for", "LPAREN (", "VAR var", "ID x", "EQ =", "ID a", "IN in",
"ID foo", "AND &&", 'STRING "</x>"', "OR ||", "ID mot", "CONDOP ?",
"ID z", "DIV /", "ID x", "COLON :", "NUMBER 3", "SEMI ;", "ID x",
"LT <", "NUMBER 5", "SEMI ;", "ID y", "LT <", "REGEX /g/i",
"RPAREN )", "LBRACE {", "ID xyz", "LPAREN (", "ID x", "PLUSPLUS ++",
"RPAREN )", "SEMI ;", "RBRACE }"]
),
), (
'regex_illegal_1',
# Various "illegal" regexes that are valid according to the std.
(r"""/????/, /++++/, /[----]/ """,
['REGEX /????/', 'COMMA ,',
'REGEX /++++/', 'COMMA ,', 'REGEX /[----]/']
),
), (
'regex_stress_test_1',
# Stress cases from
# http://stackoverflow.com/questions/5533925/
# what-javascript-constructs-does-jslex-incorrectly-lex/5573409#5573409
(r"""/\[/""", [r"""REGEX /\[/"""]),
), (
'regex_stress_test_2',
(r"""/[i]/""", [r"""REGEX /[i]/"""]),
), (
'regex_stress_test_3',
(r"""/[\]]/""", [r"""REGEX /[\]]/"""]),
), (
'regex_stress_test_4',
(r"""/a[\]]/""", [r"""REGEX /a[\]]/"""]),
), (
'regex_stress_test_5',
(r"""/a[\]]b/""", [r"""REGEX /a[\]]b/"""]),
), (
'regex_stress_test_6',
(r"""/[\]/]/gi""", [r"""REGEX /[\]/]/gi"""]),
), (
'regex_stress_test_7',
(r"""/\[[^\]]+\]/gi""", [r"""REGEX /\[[^\]]+\]/gi"""]),
), (
'regex_stress_test_8',
(r"""
rexl.re = {
NAME: /^(?!\d)(?:\w)+|^"(?:[^"]|"")+"/,
UNQUOTED_LITERAL: /^@(?:(?!\d)(?:\w|\:)+|^"(?:[^"]|"")+")\[[^\]]+\]/,
QUOTED_LITERAL: /^'(?:[^']|'')*'/,
NUMERIC_LITERAL: /^[0-9]+(?:\.[0-9]*(?:[eE][-+][0-9]+)?)?/,
SYMBOL: /^(?:==|=|<>|<=|<|>=|>|!~~|!~|~~|~|!==|!=|!~=|!~|!|&|\||\.|\:|,|\(|\)|\[|\]|\{|\}|\?|\:|;|@|\^|\/\+|\/|\*|\+|-)/
};
""", [
"ID rexl", "PERIOD .", "ID re", "EQ =", "LBRACE {",
"ID NAME", "COLON :",
r"""REGEX /^(?!\d)(?:\w)+|^"(?:[^"]|"")+"/""", "COMMA ,",
"ID UNQUOTED_LITERAL", "COLON :",
r"""REGEX /^@(?:(?!\d)(?:\w|\:)+|^"(?:[^"]|"")+")\[[^\]]+\]/""",
"COMMA ,", "ID QUOTED_LITERAL", "COLON :",
r"""REGEX /^'(?:[^']|'')*'/""", "COMMA ,", "ID NUMERIC_LITERAL",
"COLON :",
r"""REGEX /^[0-9]+(?:\.[0-9]*(?:[eE][-+][0-9]+)?)?/""", "COMMA ,",
"ID SYMBOL", "COLON :",
r"""REGEX /^(?:==|=|<>|<=|<|>=|>|!~~|!~|~~|~|!==|!=|!~=|!~|!|&|\||\.|\:|,|\(|\)|\[|\]|\{|\}|\?|\:|;|@|\^|\/\+|\/|\*|\+|-)/""",
"RBRACE }", "SEMI ;"]),
), (
'regex_stress_test_9',
(r"""
rexl.re = {
NAME: /^(?!\d)(?:\w)+|^"(?:[^"]|"")+"/,
UNQUOTED_LITERAL: /^@(?:(?!\d)(?:\w|\:)+|^"(?:[^"]|"")+")\[[^\]]+\]/,
QUOTED_LITERAL: /^'(?:[^']|'')*'/,
NUMERIC_LITERAL: /^[0-9]+(?:\.[0-9]*(?:[eE][-+][0-9]+)?)?/,
SYMBOL: /^(?:==|=|<>|<=|<|>=|>|!~~|!~|~~|~|!==|!=|!~=|!~|!|&|\||\.|\:|,|\(|\)|\[|\]|\{|\}|\?|\:|;|@|\^|\/\+|\/|\*|\+|-)/
};
str = '"';
""", [
"ID rexl", "PERIOD .", "ID re", "EQ =", "LBRACE {",
"ID NAME", "COLON :", r"""REGEX /^(?!\d)(?:\w)+|^"(?:[^"]|"")+"/""",
"COMMA ,", "ID UNQUOTED_LITERAL", "COLON :",
r"""REGEX /^@(?:(?!\d)(?:\w|\:)+|^"(?:[^"]|"")+")\[[^\]]+\]/""",
"COMMA ,", "ID QUOTED_LITERAL", "COLON :",
r"""REGEX /^'(?:[^']|'')*'/""", "COMMA ,",
"ID NUMERIC_LITERAL", "COLON :",
r"""REGEX /^[0-9]+(?:\.[0-9]*(?:[eE][-+][0-9]+)?)?/""", "COMMA ,",
"ID SYMBOL", "COLON :",
r"""REGEX /^(?:==|=|<>|<=|<|>=|>|!~~|!~|~~|~|!==|!=|!~=|!~|!|&|\||\.|\:|,|\(|\)|\[|\]|\{|\}|\?|\:|;|@|\^|\/\+|\/|\*|\+|-)/""",
"RBRACE }", "SEMI ;",
"ID str", "EQ =", """STRING '"'""", "SEMI ;",
]),
), (
'regex_stress_test_10',
(r""" this._js = "e.str(\"" + this.value.replace(/\\/g, "\\\\").replace(/"/g, "\\\"") + "\")"; """,
["THIS this", "PERIOD .", "ID _js", "EQ =",
r'''STRING "e.str(\""''', "PLUS +", "THIS this", "PERIOD .",
"ID value", "PERIOD .", "ID replace", "LPAREN (", r"REGEX /\\/g",
"COMMA ,", r'STRING "\\\\"', "RPAREN )", "PERIOD .", "ID replace",
"LPAREN (", r'REGEX /"/g', "COMMA ,", r'STRING "\\\""', "RPAREN )",
"PLUS +", r'STRING "\")"', "SEMI ;"]),
), (
'regex_division_check',
('a = /a/ / /b/',
['ID a', 'EQ =', 'REGEX /a/', 'DIV /', 'REGEX /b/']),
), (
'regex_after_plus_brace',
('+{}/a/g',
['PLUS +', 'LBRACE {', 'RBRACE }', 'DIV /', 'ID a', 'DIV /', 'ID g']),
# The following pathological cases cannot be tested using the
# lexer alone, as the rules can only be addressed in conjunction
# with a parser
#
# 'regex_after_brace',
# ('{}/a/g',
# ['LBRACE {', 'RBRACE }', 'REGEX /a/g']),
# 'regex_after_if_brace',
# ('if (a) { } /a/.test(a)',
# ['IF if', 'LPAREN (', 'ID a', 'RPAREN )', 'LBRACE {', 'RBRACE }',
# 'REGEX /a/', "PERIOD .", "ID test", 'LPAREN (', 'ID a',
# 'RPAREN )']),
), (
'regex_case',
('switch(0){case /a/:}',
['SWITCH switch', 'LPAREN (', 'NUMBER 0', 'RPAREN )', 'LBRACE {',
'CASE case', 'REGEX /a/', 'COLON :', 'RBRACE }']),
), (
'div_after_valid_statement_function_call',
('if(){} f(a) / f(b)',
['IF if', 'LPAREN (', 'RPAREN )', 'LBRACE {', 'RBRACE }',
'ID f', 'LPAREN (', 'ID a', 'RPAREN )', 'DIV /',
'ID f', 'LPAREN (', 'ID b', 'RPAREN )']),
), (
'for_regex_slimit_issue_54',
('for (;;) /r/;',
['FOR for', 'LPAREN (', 'SEMI ;', 'SEMI ;', 'RPAREN )',
'REGEX /r/', 'SEMI ;']),
), (
'for_regex_slimit_issue_54_not_break_division',
('for (;;) { x / y }',
['FOR for', 'LPAREN (', 'SEMI ;', 'SEMI ;', 'RPAREN )',
'LBRACE {', 'ID x', 'DIV /', 'ID y', 'RBRACE }']),
), (
'for_regex_slimit_issue_54_bracket_accessor_check',
('s = {a:1} + s[2] / 1',
['ID s', 'EQ =', 'LBRACE {', 'ID a', 'COLON :', 'NUMBER 1',
'RBRACE }', 'PLUS +', 'ID s', 'LBRACKET [', 'NUMBER 2', 'RBRACKET ]',
'DIV /', 'NUMBER 1'])
), (
'for_regex_slimit_issue_54_function_parentheses_check',
('s = {a:1} + f(2) / 1',
['ID s', 'EQ =', 'LBRACE {', 'ID a', 'COLON :', 'NUMBER 1',
'RBRACE }', 'PLUS +', 'ID f', 'LPAREN (', 'NUMBER 2', 'RPAREN )',
'DIV /', 'NUMBER 1'])
), (
'for_regex_slimit_issue_54_math_parentheses_check',
('s = {a:1} + (2) / 1',
['ID s', 'EQ =', 'LBRACE {', 'ID a', 'COLON :', 'NUMBER 1',
'RBRACE }', 'PLUS +', 'LPAREN (', 'NUMBER 2', 'RPAREN )',
'DIV /', 'NUMBER 1'])
), (
'for_regex_slimit_issue_54_math_bracket_check',
('s = {a:1} + [2] / 1',
['ID s', 'EQ =', 'LBRACE {', 'ID a', 'COLON :', 'NUMBER 1',
'RBRACE }', 'PLUS +', 'LBRACKET [', 'NUMBER 2', 'RBRACKET ]',
'DIV /', 'NUMBER 1'])
), (
'for_regex_slimit_issue_54_math_braces_check',
('s = {a:2} / 166 / 9',
['ID s', 'EQ =', 'LBRACE {', 'ID a', 'COLON :', 'NUMBER 2',
'RBRACE }', 'DIV /', 'NUMBER 166', 'DIV /', 'NUMBER 9'])
), (
'do_while_regex',
('do {} while (0) /s/',
['DO do', 'LBRACE {', 'RBRACE }', 'WHILE while', 'LPAREN (',
'NUMBER 0', 'RPAREN )', 'REGEX /s/'])
), (
'if_regex',
('if (thing) /s/',
['IF if', 'LPAREN (', 'ID thing', 'RPAREN )', 'REGEX /s/'])
), (
'identifier_math',
('f (v) /s/g',
['ID f', 'LPAREN (', 'ID v', 'RPAREN )', 'DIV /', 'ID s', 'DIV /',
'ID g'])
), (
'section_7',
("a = b\n/hi/s",
['ID a', 'EQ =', 'ID b', 'DIV /', 'ID hi', 'DIV /', 'ID s'])
), (
'section_7_extras',
("a = b\n\n\n/hi/s",
['ID a', 'EQ =', 'ID b', 'DIV /', 'ID hi', 'DIV /', 'ID s'])
), (
'slimit_issue_39_and_57',
(r"f(a, 'hi\01').split('\1').split('\0');",
['ID f', 'LPAREN (', 'ID a', 'COMMA ,', r"STRING 'hi\01'", 'RPAREN )',
'PERIOD .', 'ID split', 'LPAREN (', r"STRING '\1'", 'RPAREN )',
'PERIOD .', 'ID split', 'LPAREN (', r"STRING '\0'", 'RPAREN )',
'SEMI ;'])
), (
'section_7_8_4_string_literal_with_7_3_conformance',
("'<LF>\\\n<CR>\\\r<LS>\\\u2028<PS>\\\u2029<CR><LF>\\\r\n'",
["STRING '<LF>\\\n<CR>\\\r<LS>\\\u2028<PS>\\\u2029<CR><LF>\\\r\n'"])
), (
# okay this is getting ridiculous how bad ECMA is.
'section_7_comments',
("a = b\n/** **/\n\n/hi/s",
['ID a', 'EQ =', 'ID b', 'DIV /', 'ID hi', 'DIV /', 'ID s'])
),
]
# various string related syntax errors
es5_error_cases_str = [
(
'unterminated_string_eof',
"var foo = 'test",
'Unterminated string literal "\'test" at 1:11',
), (
'naked_line_separator_in_string',
"vaf foo = 'test\u2028foo'",
'Unterminated string literal "\'test" at 1:11',
), (
'naked_line_feed_in_string',
"var foo = 'test\u2029foo'",
'Unterminated string literal "\'test" at 1:11',
), (
'naked_crnl_in_string',
"var foo = 'test\r\nfoo'",
'Unterminated string literal "\'test" at 1:11',
), (
'naked_cr_in_string',
"var foo = 'test\\\n\rfoo'",
# FIXME Note that the \\ is double escaped
'Unterminated string literal "\'test\\\\" at 1:11',
), (
'invalid_hex_sequence',
"var foo = 'fail\\x1'",
# backticks are converted to single quotes
"Invalid hexadecimal escape sequence `\\x1` at 1:16",
), (
'invalid_unicode_sequence',
"var foo = 'fail\\u12'",
"Invalid unicode escape sequence `\\u12` at 1:16",
), (
'invalid_hex_sequence_multiline',
"var foo = 'foobar\\\r\nfail\\x1'",
# backticks are converted to single quotes
"Invalid hexadecimal escape sequence `\\x1` at 2:5",
), (
'invalid_unicode_sequence_multiline',
"var foo = 'foobar\\\nfail\\u12'",
"Invalid unicode escape sequence `\\u12` at 2:5",
), (
'long_invalid_string_truncated',
"var foo = '1234567890abcdetruncated",
'Unterminated string literal "\'1234567890abcde..." at 1:11',
)
]
es5_comment_cases = [
(
'line_comment_whole',
('//comment\na = 5;\n',
['LINE_COMMENT //comment', 'ID a', 'EQ =', 'NUMBER 5', 'SEMI ;']),
), (
'line_comment_trail',
('a//comment', ['ID a', 'LINE_COMMENT //comment']),
), (
'block_comment_single',
('/***/b/=3//line',
['BLOCK_COMMENT /***/', 'ID b', 'DIVEQUAL /=',
'NUMBER 3', 'LINE_COMMENT //line']),
), (
'block_comment_multiline',
('/*\n * Copyright LGPL 2011 \n*/\na = 1;',
['BLOCK_COMMENT /*\n * Copyright LGPL 2011 \n*/',
'ID a', 'EQ =', 'NUMBER 1', 'SEMI ;']),
), (
# this will replace the standard test cases
'section_7_comments',
("a = b\n/** **/\n\n/hi/s",
['ID a', 'EQ =', 'ID b', 'BLOCK_COMMENT /** **/', 'DIV /', 'ID hi',
'DIV /', 'ID s'])
)
]
# replace the section_7_comments test case
es5_all_cases = es5_cases[:-1] + es5_comment_cases
# double quote version
es5_error_cases_str_dq = [
(n, arg.translate(swapquotes), msg.translate(swapquotes))
for n, arg, msg in es5_error_cases_str
]
# single quote version
es5_error_cases_str_sq = [
(n, arg, msg.translate({96: 39}))
for n, arg, msg in es5_error_cases_str
]
es5_pos_cases = [
(
'single_line',
"""
var foo = bar; // line 1
""", ([
'var 1:0', 'foo 1:4', '= 1:8', 'bar 1:10', '; 1:13'
], [
'var 1:1', 'foo 1:5', '= 1:9', 'bar 1:11', '; 1:14',
])
), (
'multi_line',
"""
var foo = bar; // line 1
var bar = baz; // line 4
""", ([
'var 1:0', 'foo 1:4', '= 1:8', 'bar 1:10', '; 1:13',
'var 4:28', 'bar 4:32', '= 4:36', 'baz 4:38', '; 4:41',
], [
'var 1:1', 'foo 1:5', '= 1:9', 'bar 1:11', '; 1:14',
'var 4:1', 'bar 4:5', '= 4:9', 'baz 4:11', '; 4:14',
])
), (
'inline_comment',
"""
// this is a comment // line 1
var foo = bar; // line 2
// another one // line 4
var bar = baz; // line 5
""", ([
'var 2:32', 'foo 2:36', '= 2:40', 'bar 2:42', '; 2:45',
'var 5:85', 'bar 5:89', '= 5:93', 'baz 5:95', '; 5:98',
], [
'var 2:1', 'foo 2:5', '= 2:9', 'bar 2:11', '; 2:14',
'var 5:1', 'bar 5:5', '= 5:9', 'baz 5:11', '; 5:14',
])
), (
'block_comment',
"""
/*
This is a block comment
*/
var foo = bar; // line 4
/* block single line */ // line 6
var bar = baz; // line 7
/* oops */bar(); // line 9
foo();
""", ([
'var 4:30', 'foo 4:34', '= 4:38', 'bar 4:40', '; 4:43',
'var 7:91', 'bar 7:95', '= 7:99', 'baz 7:101', '; 7:104',
'bar 9:128', '( 9:131', ') 9:132', '; 9:133',
'foo 11:149', '( 11:152', ') 11:153', '; 11:154',
], [
'var 4:1', 'foo 4:5', '= 4:9', 'bar 4:11', '; 4:14',
'var 7:1', 'bar 7:5', '= 7:9', 'baz 7:11', '; 7:14',
'bar 9:11', '( 9:14', ') 9:15', '; 9:16',
'foo 11:3', '( 11:6', ') 11:7', '; 11:8',
])
), (
'syntax_error_heading_comma',
"""
var a;
, b;
""", ([
'var 1:0', 'a 1:4', '; 1:5',
', 2:7', 'b 2:9', '; 2:10'
], [
'var 1:1', 'a 1:5', '; 1:6',
', 2:1', 'b 2:3', '; 2:4'
])
)
]
def run_lexer(value, lexer_cls):
lexer = lexer_cls()
lexer.input(value)
return ['%s %s' % (token.type, token.value) for token in lexer]
def run_lexer_pos(value, lexer_cls):
lexer = lexer_cls()
lexer.input(textwrap.dedent(value).strip())
tokens = list(lexer)
return ([
'%s %d:%d' % (token.value, token.lineno, token.lexpos)
for token in tokens
], [
'%s %d:%d' % (token.value, token.lineno, token.colno)
for token in tokens
]) | random_line_split | |
search.ts | /// <amd-dependency path="koExtends/persist">
import $ = require("jquery");
import ko = require("knockout");
import _ = require("underscore");
import koControl = require("./koControl");
class searchParams {
array: KnockoutObservableArray<any>;
}
function extract(term: string, regex: RegExp, results: string[]): string {
while (term.match(regex)) |
return term;
}
export class searchResult {
match: number;
antiMatch: number;
item: any;
}
export class SearchQuery {
matchTerms: string[] = [];
antiMatchTerms: string[] = [];
}
class search {
public searchQuery = ko.observable("").extend({persist: 'searchQuery'});
public titleOnly = ko.observable(false);
public results: KnockoutComputed<any[]>;
searchData: KnockoutObservableArray<any>;
public searchQueryObj: KnockoutComputed<SearchQuery>;
constructor(element: HTMLElement, params: searchParams) {
this.searchData = params.array;
this.setupSearchQuery();
this.setupResults();
}
setupSearchQuery() {
this.searchQueryObj = ko.computed(() => {
var searchQuery = this.searchQuery().toLowerCase();
//Need to get this so we auto-update
var titleOnly = this.titleOnly();
var verbatim = new RegExp("['\"][^'\"]+['\"]");
var terms: string[] = [];
searchQuery = extract(searchQuery, verbatim, terms);
terms = _.map(terms, term => term.substr(1, term.length - 2));
terms = terms.concat(searchQuery.split(new RegExp("\\s+")));
terms = _.filter(terms, term => term.length > 0);
var matchTerms = _.filter(terms, term => term.indexOf("-") !== 0);
var antiMatchTerms = _.filter(terms, term => term.indexOf("-") === 0);
antiMatchTerms = _.map(antiMatchTerms, term => term.substr(1));
var searchObj = new SearchQuery();
searchObj.matchTerms = matchTerms;
searchObj.antiMatchTerms = antiMatchTerms;
return searchObj;
});
}
setupResults() {
this.results = ko.computed(() => {
var searchObj = this.searchQueryObj();
var matchTerms = searchObj.matchTerms;
var antiMatchTerms = searchObj.antiMatchTerms;
var matches: searchResult[] = [];
//With a lookup table this could become much much faster...
_.forEach(this.searchData(), item => {
var itemToSearch = item;
if(this.titleOnly()) {
itemToSearch = item.jobTitle;
}
var match = 0;
var antiMatch = 0;
var rawText = JSON.stringify(itemToSearch).toLowerCase();
_.forEach(matchTerms, term => {
if (rawText.indexOf(term) >= 0) {
match++;
}
});
_.forEach(antiMatchTerms, term => {
if (rawText.indexOf(term) >= 0) {
antiMatch++;
}
});
if (match > 0) {
matches.push({ match: match, antiMatch: antiMatch, item: item });
}
});
matches.sort((a, b) => {
return (b.match - b.antiMatch) - (a.match - a.antiMatch);
});
return matches;
});
}
getResults(maxCount: number): KnockoutComputed<any[]> {
return ko.computed(() => {
var results = this.results();
var count = Math.min(results.length, maxCount);
var culledResults = [];
for (var ix = 0; ix < count; ix++) {
culledResults.push(results[ix]);
}
return culledResults;
});
}
}
koControl(search); | {
results.push(term.match(regex)[0]);
term = term.replace(regex, "");
} | conditional_block |
search.ts | /// <amd-dependency path="koExtends/persist">
import $ = require("jquery");
import ko = require("knockout");
import _ = require("underscore");
import koControl = require("./koControl");
class searchParams {
array: KnockoutObservableArray<any>;
}
function extract(term: string, regex: RegExp, results: string[]): string {
while (term.match(regex)) {
results.push(term.match(regex)[0]);
term = term.replace(regex, "");
}
return term;
}
export class searchResult {
match: number;
antiMatch: number;
item: any;
}
export class SearchQuery {
matchTerms: string[] = [];
antiMatchTerms: string[] = [];
}
class | {
public searchQuery = ko.observable("").extend({persist: 'searchQuery'});
public titleOnly = ko.observable(false);
public results: KnockoutComputed<any[]>;
searchData: KnockoutObservableArray<any>;
public searchQueryObj: KnockoutComputed<SearchQuery>;
constructor(element: HTMLElement, params: searchParams) {
this.searchData = params.array;
this.setupSearchQuery();
this.setupResults();
}
setupSearchQuery() {
this.searchQueryObj = ko.computed(() => {
var searchQuery = this.searchQuery().toLowerCase();
//Need to get this so we auto-update
var titleOnly = this.titleOnly();
var verbatim = new RegExp("['\"][^'\"]+['\"]");
var terms: string[] = [];
searchQuery = extract(searchQuery, verbatim, terms);
terms = _.map(terms, term => term.substr(1, term.length - 2));
terms = terms.concat(searchQuery.split(new RegExp("\\s+")));
terms = _.filter(terms, term => term.length > 0);
var matchTerms = _.filter(terms, term => term.indexOf("-") !== 0);
var antiMatchTerms = _.filter(terms, term => term.indexOf("-") === 0);
antiMatchTerms = _.map(antiMatchTerms, term => term.substr(1));
var searchObj = new SearchQuery();
searchObj.matchTerms = matchTerms;
searchObj.antiMatchTerms = antiMatchTerms;
return searchObj;
});
}
setupResults() {
this.results = ko.computed(() => {
var searchObj = this.searchQueryObj();
var matchTerms = searchObj.matchTerms;
var antiMatchTerms = searchObj.antiMatchTerms;
var matches: searchResult[] = [];
//With a lookup table this could become much much faster...
_.forEach(this.searchData(), item => {
var itemToSearch = item;
if(this.titleOnly()) {
itemToSearch = item.jobTitle;
}
var match = 0;
var antiMatch = 0;
var rawText = JSON.stringify(itemToSearch).toLowerCase();
_.forEach(matchTerms, term => {
if (rawText.indexOf(term) >= 0) {
match++;
}
});
_.forEach(antiMatchTerms, term => {
if (rawText.indexOf(term) >= 0) {
antiMatch++;
}
});
if (match > 0) {
matches.push({ match: match, antiMatch: antiMatch, item: item });
}
});
matches.sort((a, b) => {
return (b.match - b.antiMatch) - (a.match - a.antiMatch);
});
return matches;
});
}
getResults(maxCount: number): KnockoutComputed<any[]> {
return ko.computed(() => {
var results = this.results();
var count = Math.min(results.length, maxCount);
var culledResults = [];
for (var ix = 0; ix < count; ix++) {
culledResults.push(results[ix]);
}
return culledResults;
});
}
}
koControl(search); | search | identifier_name |
search.ts | /// <amd-dependency path="koExtends/persist">
import $ = require("jquery");
import ko = require("knockout");
import _ = require("underscore");
import koControl = require("./koControl");
class searchParams {
array: KnockoutObservableArray<any>;
}
function extract(term: string, regex: RegExp, results: string[]): string {
while (term.match(regex)) {
results.push(term.match(regex)[0]);
term = term.replace(regex, "");
}
return term;
}
export class searchResult {
match: number;
antiMatch: number;
item: any;
}
export class SearchQuery {
matchTerms: string[] = [];
antiMatchTerms: string[] = [];
}
class search {
public searchQuery = ko.observable("").extend({persist: 'searchQuery'});
public titleOnly = ko.observable(false);
| public searchQueryObj: KnockoutComputed<SearchQuery>;
constructor(element: HTMLElement, params: searchParams) {
this.searchData = params.array;
this.setupSearchQuery();
this.setupResults();
}
setupSearchQuery() {
this.searchQueryObj = ko.computed(() => {
var searchQuery = this.searchQuery().toLowerCase();
//Need to get this so we auto-update
var titleOnly = this.titleOnly();
var verbatim = new RegExp("['\"][^'\"]+['\"]");
var terms: string[] = [];
searchQuery = extract(searchQuery, verbatim, terms);
terms = _.map(terms, term => term.substr(1, term.length - 2));
terms = terms.concat(searchQuery.split(new RegExp("\\s+")));
terms = _.filter(terms, term => term.length > 0);
var matchTerms = _.filter(terms, term => term.indexOf("-") !== 0);
var antiMatchTerms = _.filter(terms, term => term.indexOf("-") === 0);
antiMatchTerms = _.map(antiMatchTerms, term => term.substr(1));
var searchObj = new SearchQuery();
searchObj.matchTerms = matchTerms;
searchObj.antiMatchTerms = antiMatchTerms;
return searchObj;
});
}
setupResults() {
this.results = ko.computed(() => {
var searchObj = this.searchQueryObj();
var matchTerms = searchObj.matchTerms;
var antiMatchTerms = searchObj.antiMatchTerms;
var matches: searchResult[] = [];
//With a lookup table this could become much much faster...
_.forEach(this.searchData(), item => {
var itemToSearch = item;
if(this.titleOnly()) {
itemToSearch = item.jobTitle;
}
var match = 0;
var antiMatch = 0;
var rawText = JSON.stringify(itemToSearch).toLowerCase();
_.forEach(matchTerms, term => {
if (rawText.indexOf(term) >= 0) {
match++;
}
});
_.forEach(antiMatchTerms, term => {
if (rawText.indexOf(term) >= 0) {
antiMatch++;
}
});
if (match > 0) {
matches.push({ match: match, antiMatch: antiMatch, item: item });
}
});
matches.sort((a, b) => {
return (b.match - b.antiMatch) - (a.match - a.antiMatch);
});
return matches;
});
}
getResults(maxCount: number): KnockoutComputed<any[]> {
return ko.computed(() => {
var results = this.results();
var count = Math.min(results.length, maxCount);
var culledResults = [];
for (var ix = 0; ix < count; ix++) {
culledResults.push(results[ix]);
}
return culledResults;
});
}
}
koControl(search); | public results: KnockoutComputed<any[]>;
searchData: KnockoutObservableArray<any>;
| random_line_split |
static.module.js | const ng = require('angular');
ng.module('porybox.static', ['ngRoute']).config(['$routeProvider', $routeProvider => {
[
'about',
'donate',
'extracting-pokemon-files',
'faq',
'how-to-pk6-1-bvs',
'how-to-pk6-2-homebrew',
'how-to-pk6-3-4-save-files',
'how-to-pk6-6-decrypted-powersaves',
'how-to-pk7-1-bvs',
'how-to-pk7-2-homebrew',
'how-to-pk7-3-digital-save-files',
'how-to-pk7-4-tea', | 'privacy-policy',
'tos'
].forEach(pageName => {
$routeProvider.when(`/${pageName}`, {templateUrl: `/static/${pageName}.html`});
});
$routeProvider.when('/extracting-pk6-files', {redirectTo: '/extracting-pokemon-files'});
}]); | 'markdown', | random_line_split |
events.d.ts | import { State, Ctx, PlayerID, Game } from '../../types';
export interface EventsAPI {
endGame?(...args: any[]): void;
endPhase?(...args: any[]): void;
endStage?(...args: any[]): void;
endTurn?(...args: any[]): void;
pass?(...args: any[]): void;
setActivePlayers?(...args: any[]): void;
setPhase?(...args: any[]): void;
setStage?(...args: any[]): void;
}
| update(state: State): State;
};
}
/**
* Events
*/
export declare class Events {
flow: Game['flow'];
playerID: PlayerID | undefined;
dispatch: Array<{
key: string;
args: any[];
phase: string;
turn: number;
}>;
constructor(flow: Game['flow'], playerID?: PlayerID);
/**
* Attaches the Events API to ctx.
* @param {object} ctx - The ctx object to attach to.
*/
api(ctx: Ctx): EventsAPI & PrivateEventsAPI;
isUsed(): boolean;
/**
* Updates ctx with the triggered events.
* @param {object} state - The state object { G, ctx }.
*/
update(state: State): State<any, Ctx>;
} | export interface PrivateEventsAPI {
_obj: {
isUsed(): boolean;
| random_line_split |
events.d.ts | import { State, Ctx, PlayerID, Game } from '../../types';
export interface EventsAPI {
endGame?(...args: any[]): void;
endPhase?(...args: any[]): void;
endStage?(...args: any[]): void;
endTurn?(...args: any[]): void;
pass?(...args: any[]): void;
setActivePlayers?(...args: any[]): void;
setPhase?(...args: any[]): void;
setStage?(...args: any[]): void;
}
export interface PrivateEventsAPI {
_obj: {
isUsed(): boolean;
update(state: State): State;
};
}
/**
* Events
*/
export declare class | {
flow: Game['flow'];
playerID: PlayerID | undefined;
dispatch: Array<{
key: string;
args: any[];
phase: string;
turn: number;
}>;
constructor(flow: Game['flow'], playerID?: PlayerID);
/**
* Attaches the Events API to ctx.
* @param {object} ctx - The ctx object to attach to.
*/
api(ctx: Ctx): EventsAPI & PrivateEventsAPI;
isUsed(): boolean;
/**
* Updates ctx with the triggered events.
* @param {object} state - The state object { G, ctx }.
*/
update(state: State): State<any, Ctx>;
}
| Events | identifier_name |
test_cli_config.py | import click
import mock
import pytest
from click.testing import CliRunner
from sigopt.cli import cli
class TestRunCli(object):
@pytest.mark.parametrize('opt_into_log_collection', [False, True])
@pytest.mark.parametrize('opt_into_cell_tracking', [False, True])
def test_config_command(self, opt_into_log_collection, opt_into_cell_tracking):
| runner = CliRunner()
log_collection_arg = '--enable-log-collection' if opt_into_log_collection else '--no-enable-log-collection'
cell_tracking_arg = '--enable-cell-tracking' if opt_into_cell_tracking else '--no-enable-cell-tracking'
with mock.patch('sigopt.cli.commands.config._config.persist_configuration_options') as persist_configuration_options:
result = runner.invoke(cli, [
'config',
'--api-token=some_test_token',
log_collection_arg,
cell_tracking_arg,
])
persist_configuration_options.assert_called_once_with({
'api_token': 'some_test_token',
'code_tracking_enabled': opt_into_cell_tracking,
'log_collection_enabled': opt_into_log_collection,
})
assert result.exit_code == 0
assert result.output == '' | identifier_body | |
test_cli_config.py | import click
import mock
import pytest
from click.testing import CliRunner
from sigopt.cli import cli
class | (object):
@pytest.mark.parametrize('opt_into_log_collection', [False, True])
@pytest.mark.parametrize('opt_into_cell_tracking', [False, True])
def test_config_command(self, opt_into_log_collection, opt_into_cell_tracking):
runner = CliRunner()
log_collection_arg = '--enable-log-collection' if opt_into_log_collection else '--no-enable-log-collection'
cell_tracking_arg = '--enable-cell-tracking' if opt_into_cell_tracking else '--no-enable-cell-tracking'
with mock.patch('sigopt.cli.commands.config._config.persist_configuration_options') as persist_configuration_options:
result = runner.invoke(cli, [
'config',
'--api-token=some_test_token',
log_collection_arg,
cell_tracking_arg,
])
persist_configuration_options.assert_called_once_with({
'api_token': 'some_test_token',
'code_tracking_enabled': opt_into_cell_tracking,
'log_collection_enabled': opt_into_log_collection,
})
assert result.exit_code == 0
assert result.output == ''
| TestRunCli | identifier_name |
test_cli_config.py |
from sigopt.cli import cli
class TestRunCli(object):
@pytest.mark.parametrize('opt_into_log_collection', [False, True])
@pytest.mark.parametrize('opt_into_cell_tracking', [False, True])
def test_config_command(self, opt_into_log_collection, opt_into_cell_tracking):
runner = CliRunner()
log_collection_arg = '--enable-log-collection' if opt_into_log_collection else '--no-enable-log-collection'
cell_tracking_arg = '--enable-cell-tracking' if opt_into_cell_tracking else '--no-enable-cell-tracking'
with mock.patch('sigopt.cli.commands.config._config.persist_configuration_options') as persist_configuration_options:
result = runner.invoke(cli, [
'config',
'--api-token=some_test_token',
log_collection_arg,
cell_tracking_arg,
])
persist_configuration_options.assert_called_once_with({
'api_token': 'some_test_token',
'code_tracking_enabled': opt_into_cell_tracking,
'log_collection_enabled': opt_into_log_collection,
})
assert result.exit_code == 0
assert result.output == '' | import click
import mock
import pytest
from click.testing import CliRunner | random_line_split | |
gcs.rs | // Copyright 2019 TiKV Project Authors. Licensed under Apache-2.0.
use std::{convert::TryInto, fmt::Display, io, sync::Arc};
use cloud::blob::{none_to_empty, BlobConfig, BlobStorage, BucketConf, StringNonEmpty};
use futures_util::{
future::TryFutureExt,
io::{AsyncRead, AsyncReadExt, Cursor},
stream::{StreamExt, TryStreamExt},
};
use hyper::{client::HttpConnector, Body, Client, Request, Response, StatusCode};
use hyper_tls::HttpsConnector;
pub use kvproto::brpb::{Bucket as InputBucket, CloudDynamic, Gcs as InputConfig};
use tame_gcs::{
common::{PredefinedAcl, StorageClass},
objects::{InsertObjectOptional, Metadata, Object},
types::{BucketName, ObjectId},
};
use tame_oauth::gcp::{ServiceAccountAccess, ServiceAccountInfo, TokenOrRequest};
use tikv_util::stream::{
block_on_external_io, error_stream, retry, AsyncReadAsSyncStreamOfBytes, RetryError,
};
const GOOGLE_APIS: &str = "https://www.googleapis.com";
const HARDCODED_ENDPOINTS_SUFFIX: &[&str] = &["upload/storage/v1/", "storage/v1/"];
#[derive(Clone, Debug)]
pub struct Config {
bucket: BucketConf,
predefined_acl: Option<PredefinedAcl>,
storage_class: Option<StorageClass>,
svc_info: Option<ServiceAccountInfo>,
}
impl Config {
#[cfg(test)]
pub fn default(bucket: BucketConf) -> Self {
Self {
bucket,
predefined_acl: None,
storage_class: None,
svc_info: None,
}
}
pub fn missing_credentials() -> io::Error {
io::Error::new(io::ErrorKind::InvalidInput, "missing credentials")
}
pub fn from_cloud_dynamic(cloud_dynamic: &CloudDynamic) -> io::Result<Config> {
let bucket = BucketConf::from_cloud_dynamic(cloud_dynamic)?;
let attrs = &cloud_dynamic.attrs;
let def = &String::new();
let predefined_acl = parse_predefined_acl(attrs.get("predefined_acl").unwrap_or(def))
.or_invalid_input("invalid predefined_acl")?;
let storage_class = parse_storage_class(&none_to_empty(bucket.storage_class.clone()))
.or_invalid_input("invalid storage_class")?;
let credentials_blob_opt = StringNonEmpty::opt(
attrs
.get("credentials_blob")
.unwrap_or(&"".to_string())
.to_string(),
);
let svc_info = if let Some(cred) = credentials_blob_opt {
Some(deserialize_service_account_info(cred)?)
} else {
None
};
Ok(Config {
bucket,
predefined_acl,
svc_info,
storage_class,
})
}
pub fn from_input(input: InputConfig) -> io::Result<Config> {
let endpoint = StringNonEmpty::opt(input.endpoint);
let bucket = BucketConf {
endpoint,
bucket: StringNonEmpty::required_field(input.bucket, "bucket")?,
prefix: StringNonEmpty::opt(input.prefix),
storage_class: StringNonEmpty::opt(input.storage_class),
region: None,
};
let predefined_acl = parse_predefined_acl(&input.predefined_acl)
.or_invalid_input("invalid predefined_acl")?;
let storage_class = parse_storage_class(&none_to_empty(bucket.storage_class.clone()))
.or_invalid_input("invalid storage_class")?;
let svc_info = if let Some(cred) = StringNonEmpty::opt(input.credentials_blob) {
Some(deserialize_service_account_info(cred)?)
} else {
None
};
Ok(Config {
bucket,
predefined_acl,
svc_info,
storage_class,
})
}
}
fn deserialize_service_account_info(
cred: StringNonEmpty,
) -> std::result::Result<ServiceAccountInfo, RequestError> {
ServiceAccountInfo::deserialize(cred.to_string())
.map_err(|e| RequestError::OAuth(e, "deserialize ServiceAccountInfo".to_string()))
}
impl BlobConfig for Config {
fn name(&self) -> &'static str {
STORAGE_NAME
}
fn url(&self) -> io::Result<url::Url> {
self.bucket.url("gcs").map_err(|s| {
io::Error::new(
io::ErrorKind::Other,
format!("error creating bucket url: {}", s),
)
})
}
}
// GCS compatible storage
#[derive(Clone)]
pub struct GCSStorage {
config: Config,
svc_access: Option<Arc<ServiceAccountAccess>>,
client: Client<HttpsConnector<HttpConnector>, Body>,
}
trait ResultExt {
type Ok;
// Maps the error of this result as an `std::io::Error` with `Other` error
// kind.
fn or_io_error<D: Display>(self, msg: D) -> io::Result<Self::Ok>;
// Maps the error of this result as an `std::io::Error` with `InvalidInput`
// error kind.
fn or_invalid_input<D: Display>(self, msg: D) -> io::Result<Self::Ok>;
}
impl<T, E: Display> ResultExt for Result<T, E> {
type Ok = T;
fn or_io_error<D: Display>(self, msg: D) -> io::Result<T> {
self.map_err(|e| io::Error::new(io::ErrorKind::Other, format!("{}: {}", msg, e)))
}
fn or_invalid_input<D: Display>(self, msg: D) -> io::Result<T> {
self.map_err(|e| io::Error::new(io::ErrorKind::InvalidInput, format!("{}: {}", msg, e)))
}
}
enum RequestError {
Hyper(hyper::Error, String),
OAuth(tame_oauth::Error, String),
Gcs(tame_gcs::Error),
InvalidEndpoint(http::uri::InvalidUri),
}
impl From<http::uri::InvalidUri> for RequestError {
fn from(err: http::uri::InvalidUri) -> Self {
Self::InvalidEndpoint(err)
}
}
fn status_code_error(code: StatusCode, msg: String) -> RequestError {
RequestError::OAuth(tame_oauth::Error::HttpStatus(code), msg)
}
impl From<RequestError> for io::Error {
fn from(err: RequestError) -> Self {
match err {
RequestError::Hyper(e, msg) => {
Self::new(io::ErrorKind::InvalidInput, format!("HTTP {}: {}", msg, e))
}
RequestError::OAuth(tame_oauth::Error::Io(e), _) => e,
RequestError::OAuth(tame_oauth::Error::HttpStatus(sc), msg) => {
let fmt = format!("GCS OAuth: {}: {}", msg, sc);
match sc.as_u16() {
401 | 403 => Self::new(io::ErrorKind::PermissionDenied, fmt),
404 => Self::new(io::ErrorKind::NotFound, fmt),
_ if sc.is_server_error() => Self::new(io::ErrorKind::Interrupted, fmt),
_ => Self::new(io::ErrorKind::InvalidInput, fmt),
}
}
RequestError::OAuth(tame_oauth::Error::AuthError(e), msg) => Self::new(
io::ErrorKind::PermissionDenied,
format!("authorization failed: {}: {}", msg, e),
),
RequestError::OAuth(e, msg) => Self::new(
io::ErrorKind::InvalidInput,
format!("oauth failed: {}: {}", msg, e),
),
RequestError::Gcs(e) => Self::new(
io::ErrorKind::InvalidInput,
format!("invalid GCS request: {}", e),
),
RequestError::InvalidEndpoint(e) => Self::new(
io::ErrorKind::InvalidInput,
format!("invalid GCS endpoint URI: {}", e),
),
}
}
}
impl RetryError for RequestError {
fn is_retryable(&self) -> bool {
match self {
// FIXME: Inspect the error source?
Self::Hyper(e, _) => {
e.is_closed()
|| e.is_connect()
|| e.is_incomplete_message()
|| e.is_body_write_aborted()
}
// See https://cloud.google.com/storage/docs/exponential-backoff.
Self::OAuth(tame_oauth::Error::HttpStatus(StatusCode::TOO_MANY_REQUESTS), _) => true,
Self::OAuth(tame_oauth::Error::HttpStatus(StatusCode::REQUEST_TIMEOUT), _) => true,
Self::OAuth(tame_oauth::Error::HttpStatus(status), _) => status.is_server_error(),
// Consider everything else not retryable.
_ => false,
}
}
}
impl GCSStorage {
pub fn from_input(input: InputConfig) -> io::Result<Self> {
Self::new(Config::from_input(input)?)
}
pub fn from_cloud_dynamic(cloud_dynamic: &CloudDynamic) -> io::Result<Self> {
Self::new(Config::from_cloud_dynamic(cloud_dynamic)?)
}
/// Create a new GCS storage for the given config.
pub fn new(config: Config) -> io::Result<GCSStorage> {
let svc_access = if let Some(si) = &config.svc_info {
Some(
ServiceAccountAccess::new(si.clone())
.or_invalid_input("invalid credentials_blob")?,
)
} else {
None
};
let client = Client::builder().build(HttpsConnector::new());
Ok(GCSStorage {
config,
svc_access: svc_access.map(Arc::new),
client,
})
}
fn maybe_prefix_key(&self, key: &str) -> String {
if let Some(prefix) = &self.config.bucket.prefix {
return format!("{}/{}", prefix, key);
}
key.to_owned()
}
async fn set_auth(
&self,
req: &mut Request<Body>,
scope: tame_gcs::Scopes,
svc_access: Arc<ServiceAccountAccess>,
) -> Result<(), RequestError> {
let token_or_request = svc_access
.get_token(&[scope])
.map_err(|e| RequestError::OAuth(e, "get_token".to_string()))?;
let token = match token_or_request {
TokenOrRequest::Token(token) => token,
TokenOrRequest::Request {
request,
scope_hash,
..
} => {
let res = self
.client
.request(request.map(From::from))
.await
.map_err(|e| RequestError::Hyper(e, "set auth request".to_owned()))?;
if !res.status().is_success() |
let (parts, body) = res.into_parts();
let body = hyper::body::to_bytes(body)
.await
.map_err(|e| RequestError::Hyper(e, "set auth body".to_owned()))?;
svc_access
.parse_token_response(scope_hash, Response::from_parts(parts, body))
.map_err(|e| RequestError::OAuth(e, "set auth parse token".to_string()))?
}
};
req.headers_mut().insert(
http::header::AUTHORIZATION,
token
.try_into()
.map_err(|e| RequestError::OAuth(e, "set auth add auth header".to_string()))?,
);
Ok(())
}
async fn make_request(
&self,
mut req: Request<Body>,
scope: tame_gcs::Scopes,
) -> Result<Response<Body>, RequestError> {
// replace the hard-coded GCS endpoint by the custom one.
if let Some(endpoint) = &self.config.bucket.endpoint {
let uri = req.uri().to_string();
let new_url_opt = change_host(endpoint, &uri);
if let Some(new_url) = new_url_opt {
*req.uri_mut() = new_url.parse()?;
}
}
if let Some(svc_access) = &self.svc_access {
self.set_auth(&mut req, scope, svc_access.clone()).await?;
}
let uri = req.uri().to_string();
let res = self
.client
.request(req)
.await
.map_err(|e| RequestError::Hyper(e, uri.clone()))?;
if !res.status().is_success() {
return Err(status_code_error(res.status(), uri));
}
Ok(res)
}
fn error_to_async_read<E>(kind: io::ErrorKind, e: E) -> Box<dyn AsyncRead + Unpin>
where
E: Into<Box<dyn std::error::Error + Send + Sync>>,
{
Box::new(error_stream(io::Error::new(kind, e)).into_async_read())
}
}
fn change_host(host: &StringNonEmpty, url: &str) -> Option<String> {
let new_host = (|| {
for hardcoded in HARDCODED_ENDPOINTS_SUFFIX {
if let Some(res) = host.strip_suffix(hardcoded) {
return StringNonEmpty::opt(res.to_owned()).unwrap();
}
}
host.to_owned()
})();
if let Some(res) = url.strip_prefix(GOOGLE_APIS) {
return Some([new_host.trim_end_matches('/'), res].concat());
}
None
}
// Convert manually since they don't implement FromStr.
fn parse_storage_class(sc: &str) -> Result<Option<StorageClass>, &str> {
Ok(Some(match sc {
"" => return Ok(None),
"STANDARD" => StorageClass::Standard,
"NEARLINE" => StorageClass::Nearline,
"COLDLINE" => StorageClass::Coldline,
"DURABLE_REDUCED_AVAILABILITY" => StorageClass::DurableReducedAvailability,
"REGIONAL" => StorageClass::Regional,
"MULTI_REGIONAL" => StorageClass::MultiRegional,
_ => return Err(sc),
}))
}
fn parse_predefined_acl(acl: &str) -> Result<Option<PredefinedAcl>, &str> {
Ok(Some(match acl {
"" => return Ok(None),
"authenticatedRead" => PredefinedAcl::AuthenticatedRead,
"bucketOwnerFullControl" => PredefinedAcl::BucketOwnerFullControl,
"bucketOwnerRead" => PredefinedAcl::BucketOwnerRead,
"private" => PredefinedAcl::Private,
"projectPrivate" => PredefinedAcl::ProjectPrivate,
"publicRead" => PredefinedAcl::PublicRead,
_ => return Err(acl),
}))
}
const STORAGE_NAME: &str = "gcs";
impl BlobStorage for GCSStorage {
fn config(&self) -> Box<dyn BlobConfig> {
Box::new(self.config.clone()) as Box<dyn BlobConfig>
}
fn put(
&self,
name: &str,
mut reader: Box<dyn AsyncRead + Send + Unpin>,
content_length: u64,
) -> io::Result<()> {
if content_length == 0 {
// It is probably better to just write the empty file
// However, currently going forward results in a body write aborted error
return Err(io::Error::new(
io::ErrorKind::InvalidInput,
"no content to write",
));
}
use std::convert::TryFrom;
let key = self.maybe_prefix_key(name);
debug!("save file to GCS storage"; "key" => %key);
let bucket = BucketName::try_from(self.config.bucket.bucket.to_string())
.or_invalid_input(format_args!("invalid bucket {}", self.config.bucket.bucket))?;
let metadata = Metadata {
name: Some(key),
storage_class: self.config.storage_class,
..Default::default()
};
block_on_external_io(async move {
// FIXME: Switch to upload() API so we don't need to read the entire data into memory
// in order to retry.
let mut data = Vec::with_capacity(content_length as usize);
reader.read_to_end(&mut data).await?;
retry(|| async {
let data = Cursor::new(data.clone());
let req = Object::insert_multipart(
&bucket,
data,
content_length,
&metadata,
Some(InsertObjectOptional {
predefined_acl: self.config.predefined_acl,
..Default::default()
}),
)
.map_err(RequestError::Gcs)?
.map(|reader| Body::wrap_stream(AsyncReadAsSyncStreamOfBytes::new(reader)));
self.make_request(req, tame_gcs::Scopes::ReadWrite).await
})
.await?;
Ok::<_, io::Error>(())
})?;
Ok(())
}
fn get(&self, name: &str) -> Box<dyn AsyncRead + Unpin + '_> {
let bucket = self.config.bucket.bucket.to_string();
let name = self.maybe_prefix_key(name);
debug!("read file from GCS storage"; "key" => %name);
let oid = match ObjectId::new(bucket, name) {
Ok(oid) => oid,
Err(e) => return GCSStorage::error_to_async_read(io::ErrorKind::InvalidInput, e),
};
let request = match Object::download(&oid, None /*optional*/) {
Ok(request) => request.map(|_: io::Empty| Body::empty()),
Err(e) => return GCSStorage::error_to_async_read(io::ErrorKind::Other, e),
};
Box::new(
self.make_request(request, tame_gcs::Scopes::ReadOnly)
.and_then(|response| async {
if response.status().is_success() {
Ok(response.into_body().map_err(|e| {
io::Error::new(
io::ErrorKind::Other,
format!("download from GCS error: {}", e),
)
}))
} else {
Err(status_code_error(
response.status(),
"bucket read".to_string(),
))
}
})
.err_into::<io::Error>()
.try_flatten_stream()
.boxed() // this `.boxed()` pin the stream.
.into_async_read(),
)
}
}
#[cfg(test)]
mod tests {
use super::*;
use matches::assert_matches;
const HARDCODED_ENDPOINTS: &[&str] = &[
"https://www.googleapis.com/upload/storage/v1",
"https://www.googleapis.com/storage/v1",
];
#[test]
fn test_change_host() {
let host = StringNonEmpty::static_str("http://localhost:4443");
assert_eq!(
&change_host(&host, &format!("{}/storage/v1/foo", GOOGLE_APIS)).unwrap(),
"http://localhost:4443/storage/v1/foo"
);
let h1 = url::Url::parse(HARDCODED_ENDPOINTS[0]).unwrap();
let h2 = url::Url::parse(HARDCODED_ENDPOINTS[1]).unwrap();
let endpoint = StringNonEmpty::static_str("http://example.com");
assert_eq!(
&change_host(&endpoint, h1.as_str()).unwrap(),
"http://example.com/upload/storage/v1"
);
assert_eq!(
&change_host(&endpoint, h2.as_str()).unwrap(),
"http://example.com/storage/v1"
);
assert_eq!(
&change_host(&endpoint, &format!("{}/foo", h2)).unwrap(),
"http://example.com/storage/v1/foo"
);
assert_matches!(&change_host(&endpoint, "foo"), None);
// if we get the endpoint with suffix "/storage/v1/"
let endpoint = StringNonEmpty::static_str("http://example.com/storage/v1/");
assert_eq!(
&change_host(&endpoint, &format!("{}/foo", h2)).unwrap(),
"http://example.com/storage/v1/foo"
);
let endpoint = StringNonEmpty::static_str("http://example.com/upload/storage/v1/");
assert_eq!(
&change_host(&endpoint, &format!("{}/foo", h2)).unwrap(),
"http://example.com/storage/v1/foo"
);
}
#[test]
fn test_parse_storage_class() {
assert_matches!(
parse_storage_class("STANDARD"),
Ok(Some(StorageClass::Standard))
);
assert_matches!(parse_storage_class(""), Ok(None));
assert_matches!(
parse_storage_class("NOT_A_STORAGE_CLASS"),
Err("NOT_A_STORAGE_CLASS")
);
}
#[test]
fn test_parse_acl() {
// can't use assert_matches!(), PredefinedAcl doesn't even implement Debug.
assert!(matches!(
parse_predefined_acl("private"),
Ok(Some(PredefinedAcl::Private))
));
assert!(matches!(parse_predefined_acl(""), Ok(None)));
assert!(matches!(parse_predefined_acl("notAnACL"), Err("notAnACL")));
}
#[test]
fn test_url_of_backend() {
let bucket_name = StringNonEmpty::static_str("bucket");
let mut bucket = BucketConf::default(bucket_name);
bucket.prefix = Some(StringNonEmpty::static_str("/backup 02/prefix/"));
let gcs = Config::default(bucket.clone());
// only 'bucket' and 'prefix' should be visible in url_of_backend()
assert_eq!(
gcs.url().unwrap().to_string(),
"gcs://bucket/backup%2002/prefix/"
);
bucket.endpoint = Some(StringNonEmpty::static_str("http://endpoint.com"));
assert_eq!(
&Config::default(bucket).url().unwrap().to_string(),
"http://endpoint.com/bucket/backup%2002/prefix/"
);
}
#[test]
fn test_config_round_trip() {
let mut input = InputConfig::default();
input.set_bucket("bucket".to_owned());
input.set_prefix("backup 02/prefix/".to_owned());
let c1 = Config::from_input(input.clone()).unwrap();
let c2 = Config::from_cloud_dynamic(&cloud_dynamic_from_input(input)).unwrap();
assert_eq!(c1.bucket.bucket, c2.bucket.bucket);
assert_eq!(c1.bucket.prefix, c2.bucket.prefix);
}
fn cloud_dynamic_from_input(mut gcs: InputConfig) -> CloudDynamic {
let mut bucket = InputBucket::default();
if !gcs.endpoint.is_empty() {
bucket.endpoint = gcs.take_endpoint();
}
if !gcs.prefix.is_empty() {
bucket.prefix = gcs.take_prefix();
}
if !gcs.storage_class.is_empty() {
bucket.storage_class = gcs.take_storage_class();
}
if !gcs.bucket.is_empty() {
bucket.bucket = gcs.take_bucket();
}
let mut attrs = std::collections::HashMap::new();
if !gcs.predefined_acl.is_empty() {
attrs.insert("predefined_acl".to_owned(), gcs.take_predefined_acl());
}
if !gcs.credentials_blob.is_empty() {
attrs.insert("credentials_blob".to_owned(), gcs.take_credentials_blob());
}
let mut cd = CloudDynamic::default();
cd.set_provider_name("gcp".to_owned());
cd.set_attrs(attrs);
cd.set_bucket(bucket);
cd
}
}
| {
return Err(status_code_error(
res.status(),
"set auth request".to_string(),
));
} | conditional_block |
gcs.rs | // Copyright 2019 TiKV Project Authors. Licensed under Apache-2.0.
use std::{convert::TryInto, fmt::Display, io, sync::Arc};
use cloud::blob::{none_to_empty, BlobConfig, BlobStorage, BucketConf, StringNonEmpty};
use futures_util::{
future::TryFutureExt,
io::{AsyncRead, AsyncReadExt, Cursor},
stream::{StreamExt, TryStreamExt},
};
use hyper::{client::HttpConnector, Body, Client, Request, Response, StatusCode};
use hyper_tls::HttpsConnector;
pub use kvproto::brpb::{Bucket as InputBucket, CloudDynamic, Gcs as InputConfig};
use tame_gcs::{
common::{PredefinedAcl, StorageClass},
objects::{InsertObjectOptional, Metadata, Object},
types::{BucketName, ObjectId},
};
use tame_oauth::gcp::{ServiceAccountAccess, ServiceAccountInfo, TokenOrRequest};
use tikv_util::stream::{
block_on_external_io, error_stream, retry, AsyncReadAsSyncStreamOfBytes, RetryError,
};
const GOOGLE_APIS: &str = "https://www.googleapis.com";
const HARDCODED_ENDPOINTS_SUFFIX: &[&str] = &["upload/storage/v1/", "storage/v1/"];
#[derive(Clone, Debug)]
pub struct Config {
bucket: BucketConf,
predefined_acl: Option<PredefinedAcl>,
storage_class: Option<StorageClass>,
svc_info: Option<ServiceAccountInfo>,
}
impl Config {
#[cfg(test)]
pub fn default(bucket: BucketConf) -> Self {
Self {
bucket,
predefined_acl: None,
storage_class: None,
svc_info: None,
}
}
pub fn missing_credentials() -> io::Error {
io::Error::new(io::ErrorKind::InvalidInput, "missing credentials")
}
pub fn from_cloud_dynamic(cloud_dynamic: &CloudDynamic) -> io::Result<Config> {
let bucket = BucketConf::from_cloud_dynamic(cloud_dynamic)?;
let attrs = &cloud_dynamic.attrs;
let def = &String::new();
let predefined_acl = parse_predefined_acl(attrs.get("predefined_acl").unwrap_or(def))
.or_invalid_input("invalid predefined_acl")?;
let storage_class = parse_storage_class(&none_to_empty(bucket.storage_class.clone()))
.or_invalid_input("invalid storage_class")?;
let credentials_blob_opt = StringNonEmpty::opt(
attrs
.get("credentials_blob")
.unwrap_or(&"".to_string())
.to_string(),
);
let svc_info = if let Some(cred) = credentials_blob_opt {
Some(deserialize_service_account_info(cred)?)
} else {
None
};
Ok(Config {
bucket,
predefined_acl,
svc_info,
storage_class,
})
}
pub fn from_input(input: InputConfig) -> io::Result<Config> {
let endpoint = StringNonEmpty::opt(input.endpoint);
let bucket = BucketConf {
endpoint,
bucket: StringNonEmpty::required_field(input.bucket, "bucket")?,
prefix: StringNonEmpty::opt(input.prefix),
storage_class: StringNonEmpty::opt(input.storage_class),
region: None,
};
let predefined_acl = parse_predefined_acl(&input.predefined_acl)
.or_invalid_input("invalid predefined_acl")?;
let storage_class = parse_storage_class(&none_to_empty(bucket.storage_class.clone()))
.or_invalid_input("invalid storage_class")?;
let svc_info = if let Some(cred) = StringNonEmpty::opt(input.credentials_blob) {
Some(deserialize_service_account_info(cred)?)
} else {
None
};
Ok(Config {
bucket,
predefined_acl,
svc_info,
storage_class,
})
}
}
fn deserialize_service_account_info(
cred: StringNonEmpty,
) -> std::result::Result<ServiceAccountInfo, RequestError> {
ServiceAccountInfo::deserialize(cred.to_string())
.map_err(|e| RequestError::OAuth(e, "deserialize ServiceAccountInfo".to_string()))
}
impl BlobConfig for Config {
fn name(&self) -> &'static str {
STORAGE_NAME
}
fn url(&self) -> io::Result<url::Url> {
self.bucket.url("gcs").map_err(|s| {
io::Error::new(
io::ErrorKind::Other,
format!("error creating bucket url: {}", s),
)
})
}
}
// GCS compatible storage
#[derive(Clone)]
pub struct GCSStorage {
config: Config,
svc_access: Option<Arc<ServiceAccountAccess>>,
client: Client<HttpsConnector<HttpConnector>, Body>,
}
trait ResultExt {
type Ok;
// Maps the error of this result as an `std::io::Error` with `Other` error
// kind.
fn or_io_error<D: Display>(self, msg: D) -> io::Result<Self::Ok>;
// Maps the error of this result as an `std::io::Error` with `InvalidInput`
// error kind.
fn or_invalid_input<D: Display>(self, msg: D) -> io::Result<Self::Ok>;
}
impl<T, E: Display> ResultExt for Result<T, E> {
type Ok = T;
fn or_io_error<D: Display>(self, msg: D) -> io::Result<T> {
self.map_err(|e| io::Error::new(io::ErrorKind::Other, format!("{}: {}", msg, e)))
}
fn or_invalid_input<D: Display>(self, msg: D) -> io::Result<T> {
self.map_err(|e| io::Error::new(io::ErrorKind::InvalidInput, format!("{}: {}", msg, e)))
}
}
enum RequestError {
Hyper(hyper::Error, String),
OAuth(tame_oauth::Error, String),
Gcs(tame_gcs::Error),
InvalidEndpoint(http::uri::InvalidUri),
}
impl From<http::uri::InvalidUri> for RequestError {
fn from(err: http::uri::InvalidUri) -> Self {
Self::InvalidEndpoint(err)
}
}
fn status_code_error(code: StatusCode, msg: String) -> RequestError {
RequestError::OAuth(tame_oauth::Error::HttpStatus(code), msg)
}
impl From<RequestError> for io::Error {
fn from(err: RequestError) -> Self {
match err {
RequestError::Hyper(e, msg) => {
Self::new(io::ErrorKind::InvalidInput, format!("HTTP {}: {}", msg, e))
}
RequestError::OAuth(tame_oauth::Error::Io(e), _) => e,
RequestError::OAuth(tame_oauth::Error::HttpStatus(sc), msg) => {
let fmt = format!("GCS OAuth: {}: {}", msg, sc);
match sc.as_u16() {
401 | 403 => Self::new(io::ErrorKind::PermissionDenied, fmt),
404 => Self::new(io::ErrorKind::NotFound, fmt),
_ if sc.is_server_error() => Self::new(io::ErrorKind::Interrupted, fmt),
_ => Self::new(io::ErrorKind::InvalidInput, fmt),
}
}
RequestError::OAuth(tame_oauth::Error::AuthError(e), msg) => Self::new(
io::ErrorKind::PermissionDenied,
format!("authorization failed: {}: {}", msg, e),
),
RequestError::OAuth(e, msg) => Self::new(
io::ErrorKind::InvalidInput,
format!("oauth failed: {}: {}", msg, e),
),
RequestError::Gcs(e) => Self::new(
io::ErrorKind::InvalidInput,
format!("invalid GCS request: {}", e),
),
RequestError::InvalidEndpoint(e) => Self::new(
io::ErrorKind::InvalidInput,
format!("invalid GCS endpoint URI: {}", e),
),
}
}
}
impl RetryError for RequestError {
fn is_retryable(&self) -> bool {
match self {
// FIXME: Inspect the error source?
Self::Hyper(e, _) => {
e.is_closed()
|| e.is_connect()
|| e.is_incomplete_message()
|| e.is_body_write_aborted()
}
// See https://cloud.google.com/storage/docs/exponential-backoff.
Self::OAuth(tame_oauth::Error::HttpStatus(StatusCode::TOO_MANY_REQUESTS), _) => true,
Self::OAuth(tame_oauth::Error::HttpStatus(StatusCode::REQUEST_TIMEOUT), _) => true,
Self::OAuth(tame_oauth::Error::HttpStatus(status), _) => status.is_server_error(),
// Consider everything else not retryable.
_ => false,
}
}
}
impl GCSStorage {
pub fn from_input(input: InputConfig) -> io::Result<Self> {
Self::new(Config::from_input(input)?)
}
pub fn from_cloud_dynamic(cloud_dynamic: &CloudDynamic) -> io::Result<Self> {
Self::new(Config::from_cloud_dynamic(cloud_dynamic)?)
}
/// Create a new GCS storage for the given config.
pub fn new(config: Config) -> io::Result<GCSStorage> {
let svc_access = if let Some(si) = &config.svc_info {
Some(
ServiceAccountAccess::new(si.clone())
.or_invalid_input("invalid credentials_blob")?,
)
} else {
None
};
let client = Client::builder().build(HttpsConnector::new());
Ok(GCSStorage {
config,
svc_access: svc_access.map(Arc::new),
client,
})
}
fn maybe_prefix_key(&self, key: &str) -> String {
if let Some(prefix) = &self.config.bucket.prefix {
return format!("{}/{}", prefix, key);
}
key.to_owned()
}
async fn set_auth(
&self,
req: &mut Request<Body>,
scope: tame_gcs::Scopes,
svc_access: Arc<ServiceAccountAccess>,
) -> Result<(), RequestError> {
let token_or_request = svc_access
.get_token(&[scope])
.map_err(|e| RequestError::OAuth(e, "get_token".to_string()))?;
let token = match token_or_request {
TokenOrRequest::Token(token) => token,
TokenOrRequest::Request {
request,
scope_hash,
..
} => {
let res = self
.client
.request(request.map(From::from))
.await
.map_err(|e| RequestError::Hyper(e, "set auth request".to_owned()))?;
if !res.status().is_success() {
return Err(status_code_error(
res.status(),
"set auth request".to_string(),
));
}
let (parts, body) = res.into_parts();
let body = hyper::body::to_bytes(body)
.await
.map_err(|e| RequestError::Hyper(e, "set auth body".to_owned()))?;
svc_access
.parse_token_response(scope_hash, Response::from_parts(parts, body))
.map_err(|e| RequestError::OAuth(e, "set auth parse token".to_string()))?
}
};
req.headers_mut().insert(
http::header::AUTHORIZATION,
token
.try_into()
.map_err(|e| RequestError::OAuth(e, "set auth add auth header".to_string()))?,
);
Ok(())
}
async fn make_request(
&self,
mut req: Request<Body>,
scope: tame_gcs::Scopes,
) -> Result<Response<Body>, RequestError> {
// replace the hard-coded GCS endpoint by the custom one.
if let Some(endpoint) = &self.config.bucket.endpoint {
let uri = req.uri().to_string();
let new_url_opt = change_host(endpoint, &uri);
if let Some(new_url) = new_url_opt {
*req.uri_mut() = new_url.parse()?;
}
}
if let Some(svc_access) = &self.svc_access {
self.set_auth(&mut req, scope, svc_access.clone()).await?;
}
let uri = req.uri().to_string();
let res = self
.client
.request(req)
.await
.map_err(|e| RequestError::Hyper(e, uri.clone()))?;
if !res.status().is_success() {
return Err(status_code_error(res.status(), uri));
}
Ok(res)
}
fn error_to_async_read<E>(kind: io::ErrorKind, e: E) -> Box<dyn AsyncRead + Unpin>
where
E: Into<Box<dyn std::error::Error + Send + Sync>>,
{
Box::new(error_stream(io::Error::new(kind, e)).into_async_read())
}
}
fn change_host(host: &StringNonEmpty, url: &str) -> Option<String> {
let new_host = (|| {
for hardcoded in HARDCODED_ENDPOINTS_SUFFIX {
if let Some(res) = host.strip_suffix(hardcoded) {
return StringNonEmpty::opt(res.to_owned()).unwrap();
}
}
host.to_owned()
})();
if let Some(res) = url.strip_prefix(GOOGLE_APIS) {
return Some([new_host.trim_end_matches('/'), res].concat());
}
None
}
// Convert manually since they don't implement FromStr.
fn parse_storage_class(sc: &str) -> Result<Option<StorageClass>, &str> {
Ok(Some(match sc {
"" => return Ok(None),
"STANDARD" => StorageClass::Standard,
"NEARLINE" => StorageClass::Nearline,
"COLDLINE" => StorageClass::Coldline,
"DURABLE_REDUCED_AVAILABILITY" => StorageClass::DurableReducedAvailability,
"REGIONAL" => StorageClass::Regional,
"MULTI_REGIONAL" => StorageClass::MultiRegional,
_ => return Err(sc),
}))
}
fn parse_predefined_acl(acl: &str) -> Result<Option<PredefinedAcl>, &str> {
Ok(Some(match acl {
"" => return Ok(None),
"authenticatedRead" => PredefinedAcl::AuthenticatedRead,
"bucketOwnerFullControl" => PredefinedAcl::BucketOwnerFullControl,
"bucketOwnerRead" => PredefinedAcl::BucketOwnerRead,
"private" => PredefinedAcl::Private,
"projectPrivate" => PredefinedAcl::ProjectPrivate,
"publicRead" => PredefinedAcl::PublicRead,
_ => return Err(acl),
}))
}
const STORAGE_NAME: &str = "gcs";
impl BlobStorage for GCSStorage {
fn config(&self) -> Box<dyn BlobConfig> {
Box::new(self.config.clone()) as Box<dyn BlobConfig>
}
fn put(
&self,
name: &str,
mut reader: Box<dyn AsyncRead + Send + Unpin>,
content_length: u64,
) -> io::Result<()> {
if content_length == 0 {
// It is probably better to just write the empty file
// However, currently going forward results in a body write aborted error
return Err(io::Error::new(
io::ErrorKind::InvalidInput,
"no content to write",
));
}
use std::convert::TryFrom;
let key = self.maybe_prefix_key(name);
debug!("save file to GCS storage"; "key" => %key);
let bucket = BucketName::try_from(self.config.bucket.bucket.to_string())
.or_invalid_input(format_args!("invalid bucket {}", self.config.bucket.bucket))?;
let metadata = Metadata {
name: Some(key),
storage_class: self.config.storage_class,
..Default::default()
};
block_on_external_io(async move {
// FIXME: Switch to upload() API so we don't need to read the entire data into memory
// in order to retry.
let mut data = Vec::with_capacity(content_length as usize);
reader.read_to_end(&mut data).await?;
retry(|| async {
let data = Cursor::new(data.clone());
let req = Object::insert_multipart(
&bucket,
data,
content_length,
&metadata,
Some(InsertObjectOptional {
predefined_acl: self.config.predefined_acl,
..Default::default()
}),
)
.map_err(RequestError::Gcs)?
.map(|reader| Body::wrap_stream(AsyncReadAsSyncStreamOfBytes::new(reader)));
self.make_request(req, tame_gcs::Scopes::ReadWrite).await
})
.await?;
Ok::<_, io::Error>(())
})?;
Ok(())
}
fn get(&self, name: &str) -> Box<dyn AsyncRead + Unpin + '_> {
let bucket = self.config.bucket.bucket.to_string();
let name = self.maybe_prefix_key(name);
debug!("read file from GCS storage"; "key" => %name);
let oid = match ObjectId::new(bucket, name) {
Ok(oid) => oid,
Err(e) => return GCSStorage::error_to_async_read(io::ErrorKind::InvalidInput, e),
};
let request = match Object::download(&oid, None /*optional*/) {
Ok(request) => request.map(|_: io::Empty| Body::empty()),
Err(e) => return GCSStorage::error_to_async_read(io::ErrorKind::Other, e),
};
Box::new(
self.make_request(request, tame_gcs::Scopes::ReadOnly)
.and_then(|response| async {
if response.status().is_success() {
Ok(response.into_body().map_err(|e| {
io::Error::new(
io::ErrorKind::Other,
format!("download from GCS error: {}", e),
)
}))
} else {
Err(status_code_error(
response.status(),
"bucket read".to_string(),
))
}
})
.err_into::<io::Error>()
.try_flatten_stream()
.boxed() // this `.boxed()` pin the stream.
.into_async_read(),
)
}
}
#[cfg(test)]
mod tests {
use super::*;
use matches::assert_matches;
const HARDCODED_ENDPOINTS: &[&str] = &[
"https://www.googleapis.com/upload/storage/v1",
"https://www.googleapis.com/storage/v1",
];
#[test]
fn test_change_host() {
let host = StringNonEmpty::static_str("http://localhost:4443");
assert_eq!(
&change_host(&host, &format!("{}/storage/v1/foo", GOOGLE_APIS)).unwrap(),
"http://localhost:4443/storage/v1/foo"
);
let h1 = url::Url::parse(HARDCODED_ENDPOINTS[0]).unwrap();
let h2 = url::Url::parse(HARDCODED_ENDPOINTS[1]).unwrap();
let endpoint = StringNonEmpty::static_str("http://example.com");
assert_eq!(
&change_host(&endpoint, h1.as_str()).unwrap(),
"http://example.com/upload/storage/v1"
);
assert_eq!(
&change_host(&endpoint, h2.as_str()).unwrap(),
"http://example.com/storage/v1"
);
assert_eq!(
&change_host(&endpoint, &format!("{}/foo", h2)).unwrap(),
"http://example.com/storage/v1/foo"
);
assert_matches!(&change_host(&endpoint, "foo"), None);
// if we get the endpoint with suffix "/storage/v1/"
let endpoint = StringNonEmpty::static_str("http://example.com/storage/v1/");
assert_eq!(
&change_host(&endpoint, &format!("{}/foo", h2)).unwrap(),
"http://example.com/storage/v1/foo"
);
let endpoint = StringNonEmpty::static_str("http://example.com/upload/storage/v1/");
assert_eq!(
&change_host(&endpoint, &format!("{}/foo", h2)).unwrap(),
"http://example.com/storage/v1/foo"
);
}
#[test]
fn test_parse_storage_class() {
assert_matches!(
parse_storage_class("STANDARD"),
Ok(Some(StorageClass::Standard))
);
assert_matches!(parse_storage_class(""), Ok(None));
assert_matches!(
parse_storage_class("NOT_A_STORAGE_CLASS"),
Err("NOT_A_STORAGE_CLASS")
);
}
#[test]
fn test_parse_acl() {
// can't use assert_matches!(), PredefinedAcl doesn't even implement Debug.
assert!(matches!(
parse_predefined_acl("private"),
Ok(Some(PredefinedAcl::Private))
));
assert!(matches!(parse_predefined_acl(""), Ok(None)));
assert!(matches!(parse_predefined_acl("notAnACL"), Err("notAnACL")));
}
#[test]
fn test_url_of_backend() {
let bucket_name = StringNonEmpty::static_str("bucket");
let mut bucket = BucketConf::default(bucket_name);
bucket.prefix = Some(StringNonEmpty::static_str("/backup 02/prefix/"));
let gcs = Config::default(bucket.clone());
// only 'bucket' and 'prefix' should be visible in url_of_backend()
assert_eq!(
gcs.url().unwrap().to_string(),
"gcs://bucket/backup%2002/prefix/"
);
bucket.endpoint = Some(StringNonEmpty::static_str("http://endpoint.com"));
assert_eq!(
&Config::default(bucket).url().unwrap().to_string(),
"http://endpoint.com/bucket/backup%2002/prefix/"
);
}
#[test]
fn | () {
let mut input = InputConfig::default();
input.set_bucket("bucket".to_owned());
input.set_prefix("backup 02/prefix/".to_owned());
let c1 = Config::from_input(input.clone()).unwrap();
let c2 = Config::from_cloud_dynamic(&cloud_dynamic_from_input(input)).unwrap();
assert_eq!(c1.bucket.bucket, c2.bucket.bucket);
assert_eq!(c1.bucket.prefix, c2.bucket.prefix);
}
fn cloud_dynamic_from_input(mut gcs: InputConfig) -> CloudDynamic {
let mut bucket = InputBucket::default();
if !gcs.endpoint.is_empty() {
bucket.endpoint = gcs.take_endpoint();
}
if !gcs.prefix.is_empty() {
bucket.prefix = gcs.take_prefix();
}
if !gcs.storage_class.is_empty() {
bucket.storage_class = gcs.take_storage_class();
}
if !gcs.bucket.is_empty() {
bucket.bucket = gcs.take_bucket();
}
let mut attrs = std::collections::HashMap::new();
if !gcs.predefined_acl.is_empty() {
attrs.insert("predefined_acl".to_owned(), gcs.take_predefined_acl());
}
if !gcs.credentials_blob.is_empty() {
attrs.insert("credentials_blob".to_owned(), gcs.take_credentials_blob());
}
let mut cd = CloudDynamic::default();
cd.set_provider_name("gcp".to_owned());
cd.set_attrs(attrs);
cd.set_bucket(bucket);
cd
}
}
| test_config_round_trip | identifier_name |
gcs.rs | // Copyright 2019 TiKV Project Authors. Licensed under Apache-2.0.
use std::{convert::TryInto, fmt::Display, io, sync::Arc};
use cloud::blob::{none_to_empty, BlobConfig, BlobStorage, BucketConf, StringNonEmpty};
use futures_util::{
future::TryFutureExt,
io::{AsyncRead, AsyncReadExt, Cursor},
stream::{StreamExt, TryStreamExt},
};
use hyper::{client::HttpConnector, Body, Client, Request, Response, StatusCode};
use hyper_tls::HttpsConnector;
pub use kvproto::brpb::{Bucket as InputBucket, CloudDynamic, Gcs as InputConfig};
use tame_gcs::{
common::{PredefinedAcl, StorageClass},
objects::{InsertObjectOptional, Metadata, Object},
types::{BucketName, ObjectId},
};
use tame_oauth::gcp::{ServiceAccountAccess, ServiceAccountInfo, TokenOrRequest};
use tikv_util::stream::{
block_on_external_io, error_stream, retry, AsyncReadAsSyncStreamOfBytes, RetryError,
};
const GOOGLE_APIS: &str = "https://www.googleapis.com";
const HARDCODED_ENDPOINTS_SUFFIX: &[&str] = &["upload/storage/v1/", "storage/v1/"];
#[derive(Clone, Debug)]
pub struct Config {
bucket: BucketConf,
predefined_acl: Option<PredefinedAcl>,
storage_class: Option<StorageClass>,
svc_info: Option<ServiceAccountInfo>,
}
impl Config {
#[cfg(test)]
pub fn default(bucket: BucketConf) -> Self {
Self {
bucket,
predefined_acl: None,
storage_class: None,
svc_info: None,
}
}
pub fn missing_credentials() -> io::Error {
io::Error::new(io::ErrorKind::InvalidInput, "missing credentials")
}
pub fn from_cloud_dynamic(cloud_dynamic: &CloudDynamic) -> io::Result<Config> {
let bucket = BucketConf::from_cloud_dynamic(cloud_dynamic)?;
let attrs = &cloud_dynamic.attrs;
let def = &String::new();
let predefined_acl = parse_predefined_acl(attrs.get("predefined_acl").unwrap_or(def))
.or_invalid_input("invalid predefined_acl")?;
let storage_class = parse_storage_class(&none_to_empty(bucket.storage_class.clone()))
.or_invalid_input("invalid storage_class")?;
let credentials_blob_opt = StringNonEmpty::opt(
attrs
.get("credentials_blob")
.unwrap_or(&"".to_string())
.to_string(),
);
let svc_info = if let Some(cred) = credentials_blob_opt {
Some(deserialize_service_account_info(cred)?)
} else {
None
};
Ok(Config {
bucket,
predefined_acl,
svc_info,
storage_class,
})
}
pub fn from_input(input: InputConfig) -> io::Result<Config> {
let endpoint = StringNonEmpty::opt(input.endpoint);
let bucket = BucketConf {
endpoint,
bucket: StringNonEmpty::required_field(input.bucket, "bucket")?,
prefix: StringNonEmpty::opt(input.prefix),
storage_class: StringNonEmpty::opt(input.storage_class),
region: None,
};
let predefined_acl = parse_predefined_acl(&input.predefined_acl)
.or_invalid_input("invalid predefined_acl")?;
let storage_class = parse_storage_class(&none_to_empty(bucket.storage_class.clone()))
.or_invalid_input("invalid storage_class")?;
let svc_info = if let Some(cred) = StringNonEmpty::opt(input.credentials_blob) {
Some(deserialize_service_account_info(cred)?)
} else {
None
};
Ok(Config {
bucket,
predefined_acl,
svc_info, |
fn deserialize_service_account_info(
cred: StringNonEmpty,
) -> std::result::Result<ServiceAccountInfo, RequestError> {
ServiceAccountInfo::deserialize(cred.to_string())
.map_err(|e| RequestError::OAuth(e, "deserialize ServiceAccountInfo".to_string()))
}
impl BlobConfig for Config {
fn name(&self) -> &'static str {
STORAGE_NAME
}
fn url(&self) -> io::Result<url::Url> {
self.bucket.url("gcs").map_err(|s| {
io::Error::new(
io::ErrorKind::Other,
format!("error creating bucket url: {}", s),
)
})
}
}
// GCS compatible storage
#[derive(Clone)]
pub struct GCSStorage {
config: Config,
svc_access: Option<Arc<ServiceAccountAccess>>,
client: Client<HttpsConnector<HttpConnector>, Body>,
}
trait ResultExt {
type Ok;
// Maps the error of this result as an `std::io::Error` with `Other` error
// kind.
fn or_io_error<D: Display>(self, msg: D) -> io::Result<Self::Ok>;
// Maps the error of this result as an `std::io::Error` with `InvalidInput`
// error kind.
fn or_invalid_input<D: Display>(self, msg: D) -> io::Result<Self::Ok>;
}
impl<T, E: Display> ResultExt for Result<T, E> {
type Ok = T;
fn or_io_error<D: Display>(self, msg: D) -> io::Result<T> {
self.map_err(|e| io::Error::new(io::ErrorKind::Other, format!("{}: {}", msg, e)))
}
fn or_invalid_input<D: Display>(self, msg: D) -> io::Result<T> {
self.map_err(|e| io::Error::new(io::ErrorKind::InvalidInput, format!("{}: {}", msg, e)))
}
}
enum RequestError {
Hyper(hyper::Error, String),
OAuth(tame_oauth::Error, String),
Gcs(tame_gcs::Error),
InvalidEndpoint(http::uri::InvalidUri),
}
impl From<http::uri::InvalidUri> for RequestError {
fn from(err: http::uri::InvalidUri) -> Self {
Self::InvalidEndpoint(err)
}
}
fn status_code_error(code: StatusCode, msg: String) -> RequestError {
RequestError::OAuth(tame_oauth::Error::HttpStatus(code), msg)
}
impl From<RequestError> for io::Error {
fn from(err: RequestError) -> Self {
match err {
RequestError::Hyper(e, msg) => {
Self::new(io::ErrorKind::InvalidInput, format!("HTTP {}: {}", msg, e))
}
RequestError::OAuth(tame_oauth::Error::Io(e), _) => e,
RequestError::OAuth(tame_oauth::Error::HttpStatus(sc), msg) => {
let fmt = format!("GCS OAuth: {}: {}", msg, sc);
match sc.as_u16() {
401 | 403 => Self::new(io::ErrorKind::PermissionDenied, fmt),
404 => Self::new(io::ErrorKind::NotFound, fmt),
_ if sc.is_server_error() => Self::new(io::ErrorKind::Interrupted, fmt),
_ => Self::new(io::ErrorKind::InvalidInput, fmt),
}
}
RequestError::OAuth(tame_oauth::Error::AuthError(e), msg) => Self::new(
io::ErrorKind::PermissionDenied,
format!("authorization failed: {}: {}", msg, e),
),
RequestError::OAuth(e, msg) => Self::new(
io::ErrorKind::InvalidInput,
format!("oauth failed: {}: {}", msg, e),
),
RequestError::Gcs(e) => Self::new(
io::ErrorKind::InvalidInput,
format!("invalid GCS request: {}", e),
),
RequestError::InvalidEndpoint(e) => Self::new(
io::ErrorKind::InvalidInput,
format!("invalid GCS endpoint URI: {}", e),
),
}
}
}
impl RetryError for RequestError {
fn is_retryable(&self) -> bool {
match self {
// FIXME: Inspect the error source?
Self::Hyper(e, _) => {
e.is_closed()
|| e.is_connect()
|| e.is_incomplete_message()
|| e.is_body_write_aborted()
}
// See https://cloud.google.com/storage/docs/exponential-backoff.
Self::OAuth(tame_oauth::Error::HttpStatus(StatusCode::TOO_MANY_REQUESTS), _) => true,
Self::OAuth(tame_oauth::Error::HttpStatus(StatusCode::REQUEST_TIMEOUT), _) => true,
Self::OAuth(tame_oauth::Error::HttpStatus(status), _) => status.is_server_error(),
// Consider everything else not retryable.
_ => false,
}
}
}
impl GCSStorage {
pub fn from_input(input: InputConfig) -> io::Result<Self> {
Self::new(Config::from_input(input)?)
}
pub fn from_cloud_dynamic(cloud_dynamic: &CloudDynamic) -> io::Result<Self> {
Self::new(Config::from_cloud_dynamic(cloud_dynamic)?)
}
/// Create a new GCS storage for the given config.
pub fn new(config: Config) -> io::Result<GCSStorage> {
let svc_access = if let Some(si) = &config.svc_info {
Some(
ServiceAccountAccess::new(si.clone())
.or_invalid_input("invalid credentials_blob")?,
)
} else {
None
};
let client = Client::builder().build(HttpsConnector::new());
Ok(GCSStorage {
config,
svc_access: svc_access.map(Arc::new),
client,
})
}
fn maybe_prefix_key(&self, key: &str) -> String {
if let Some(prefix) = &self.config.bucket.prefix {
return format!("{}/{}", prefix, key);
}
key.to_owned()
}
async fn set_auth(
&self,
req: &mut Request<Body>,
scope: tame_gcs::Scopes,
svc_access: Arc<ServiceAccountAccess>,
) -> Result<(), RequestError> {
let token_or_request = svc_access
.get_token(&[scope])
.map_err(|e| RequestError::OAuth(e, "get_token".to_string()))?;
let token = match token_or_request {
TokenOrRequest::Token(token) => token,
TokenOrRequest::Request {
request,
scope_hash,
..
} => {
let res = self
.client
.request(request.map(From::from))
.await
.map_err(|e| RequestError::Hyper(e, "set auth request".to_owned()))?;
if !res.status().is_success() {
return Err(status_code_error(
res.status(),
"set auth request".to_string(),
));
}
let (parts, body) = res.into_parts();
let body = hyper::body::to_bytes(body)
.await
.map_err(|e| RequestError::Hyper(e, "set auth body".to_owned()))?;
svc_access
.parse_token_response(scope_hash, Response::from_parts(parts, body))
.map_err(|e| RequestError::OAuth(e, "set auth parse token".to_string()))?
}
};
req.headers_mut().insert(
http::header::AUTHORIZATION,
token
.try_into()
.map_err(|e| RequestError::OAuth(e, "set auth add auth header".to_string()))?,
);
Ok(())
}
async fn make_request(
&self,
mut req: Request<Body>,
scope: tame_gcs::Scopes,
) -> Result<Response<Body>, RequestError> {
// replace the hard-coded GCS endpoint by the custom one.
if let Some(endpoint) = &self.config.bucket.endpoint {
let uri = req.uri().to_string();
let new_url_opt = change_host(endpoint, &uri);
if let Some(new_url) = new_url_opt {
*req.uri_mut() = new_url.parse()?;
}
}
if let Some(svc_access) = &self.svc_access {
self.set_auth(&mut req, scope, svc_access.clone()).await?;
}
let uri = req.uri().to_string();
let res = self
.client
.request(req)
.await
.map_err(|e| RequestError::Hyper(e, uri.clone()))?;
if !res.status().is_success() {
return Err(status_code_error(res.status(), uri));
}
Ok(res)
}
fn error_to_async_read<E>(kind: io::ErrorKind, e: E) -> Box<dyn AsyncRead + Unpin>
where
E: Into<Box<dyn std::error::Error + Send + Sync>>,
{
Box::new(error_stream(io::Error::new(kind, e)).into_async_read())
}
}
fn change_host(host: &StringNonEmpty, url: &str) -> Option<String> {
let new_host = (|| {
for hardcoded in HARDCODED_ENDPOINTS_SUFFIX {
if let Some(res) = host.strip_suffix(hardcoded) {
return StringNonEmpty::opt(res.to_owned()).unwrap();
}
}
host.to_owned()
})();
if let Some(res) = url.strip_prefix(GOOGLE_APIS) {
return Some([new_host.trim_end_matches('/'), res].concat());
}
None
}
// Convert manually since they don't implement FromStr.
fn parse_storage_class(sc: &str) -> Result<Option<StorageClass>, &str> {
Ok(Some(match sc {
"" => return Ok(None),
"STANDARD" => StorageClass::Standard,
"NEARLINE" => StorageClass::Nearline,
"COLDLINE" => StorageClass::Coldline,
"DURABLE_REDUCED_AVAILABILITY" => StorageClass::DurableReducedAvailability,
"REGIONAL" => StorageClass::Regional,
"MULTI_REGIONAL" => StorageClass::MultiRegional,
_ => return Err(sc),
}))
}
fn parse_predefined_acl(acl: &str) -> Result<Option<PredefinedAcl>, &str> {
Ok(Some(match acl {
"" => return Ok(None),
"authenticatedRead" => PredefinedAcl::AuthenticatedRead,
"bucketOwnerFullControl" => PredefinedAcl::BucketOwnerFullControl,
"bucketOwnerRead" => PredefinedAcl::BucketOwnerRead,
"private" => PredefinedAcl::Private,
"projectPrivate" => PredefinedAcl::ProjectPrivate,
"publicRead" => PredefinedAcl::PublicRead,
_ => return Err(acl),
}))
}
const STORAGE_NAME: &str = "gcs";
impl BlobStorage for GCSStorage {
fn config(&self) -> Box<dyn BlobConfig> {
Box::new(self.config.clone()) as Box<dyn BlobConfig>
}
fn put(
&self,
name: &str,
mut reader: Box<dyn AsyncRead + Send + Unpin>,
content_length: u64,
) -> io::Result<()> {
if content_length == 0 {
// It is probably better to just write the empty file
// However, currently going forward results in a body write aborted error
return Err(io::Error::new(
io::ErrorKind::InvalidInput,
"no content to write",
));
}
use std::convert::TryFrom;
let key = self.maybe_prefix_key(name);
debug!("save file to GCS storage"; "key" => %key);
let bucket = BucketName::try_from(self.config.bucket.bucket.to_string())
.or_invalid_input(format_args!("invalid bucket {}", self.config.bucket.bucket))?;
let metadata = Metadata {
name: Some(key),
storage_class: self.config.storage_class,
..Default::default()
};
block_on_external_io(async move {
// FIXME: Switch to upload() API so we don't need to read the entire data into memory
// in order to retry.
let mut data = Vec::with_capacity(content_length as usize);
reader.read_to_end(&mut data).await?;
retry(|| async {
let data = Cursor::new(data.clone());
let req = Object::insert_multipart(
&bucket,
data,
content_length,
&metadata,
Some(InsertObjectOptional {
predefined_acl: self.config.predefined_acl,
..Default::default()
}),
)
.map_err(RequestError::Gcs)?
.map(|reader| Body::wrap_stream(AsyncReadAsSyncStreamOfBytes::new(reader)));
self.make_request(req, tame_gcs::Scopes::ReadWrite).await
})
.await?;
Ok::<_, io::Error>(())
})?;
Ok(())
}
fn get(&self, name: &str) -> Box<dyn AsyncRead + Unpin + '_> {
let bucket = self.config.bucket.bucket.to_string();
let name = self.maybe_prefix_key(name);
debug!("read file from GCS storage"; "key" => %name);
let oid = match ObjectId::new(bucket, name) {
Ok(oid) => oid,
Err(e) => return GCSStorage::error_to_async_read(io::ErrorKind::InvalidInput, e),
};
let request = match Object::download(&oid, None /*optional*/) {
Ok(request) => request.map(|_: io::Empty| Body::empty()),
Err(e) => return GCSStorage::error_to_async_read(io::ErrorKind::Other, e),
};
Box::new(
self.make_request(request, tame_gcs::Scopes::ReadOnly)
.and_then(|response| async {
if response.status().is_success() {
Ok(response.into_body().map_err(|e| {
io::Error::new(
io::ErrorKind::Other,
format!("download from GCS error: {}", e),
)
}))
} else {
Err(status_code_error(
response.status(),
"bucket read".to_string(),
))
}
})
.err_into::<io::Error>()
.try_flatten_stream()
.boxed() // this `.boxed()` pin the stream.
.into_async_read(),
)
}
}
#[cfg(test)]
mod tests {
use super::*;
use matches::assert_matches;
const HARDCODED_ENDPOINTS: &[&str] = &[
"https://www.googleapis.com/upload/storage/v1",
"https://www.googleapis.com/storage/v1",
];
#[test]
fn test_change_host() {
let host = StringNonEmpty::static_str("http://localhost:4443");
assert_eq!(
&change_host(&host, &format!("{}/storage/v1/foo", GOOGLE_APIS)).unwrap(),
"http://localhost:4443/storage/v1/foo"
);
let h1 = url::Url::parse(HARDCODED_ENDPOINTS[0]).unwrap();
let h2 = url::Url::parse(HARDCODED_ENDPOINTS[1]).unwrap();
let endpoint = StringNonEmpty::static_str("http://example.com");
assert_eq!(
&change_host(&endpoint, h1.as_str()).unwrap(),
"http://example.com/upload/storage/v1"
);
assert_eq!(
&change_host(&endpoint, h2.as_str()).unwrap(),
"http://example.com/storage/v1"
);
assert_eq!(
&change_host(&endpoint, &format!("{}/foo", h2)).unwrap(),
"http://example.com/storage/v1/foo"
);
assert_matches!(&change_host(&endpoint, "foo"), None);
// if we get the endpoint with suffix "/storage/v1/"
let endpoint = StringNonEmpty::static_str("http://example.com/storage/v1/");
assert_eq!(
&change_host(&endpoint, &format!("{}/foo", h2)).unwrap(),
"http://example.com/storage/v1/foo"
);
let endpoint = StringNonEmpty::static_str("http://example.com/upload/storage/v1/");
assert_eq!(
&change_host(&endpoint, &format!("{}/foo", h2)).unwrap(),
"http://example.com/storage/v1/foo"
);
}
#[test]
fn test_parse_storage_class() {
assert_matches!(
parse_storage_class("STANDARD"),
Ok(Some(StorageClass::Standard))
);
assert_matches!(parse_storage_class(""), Ok(None));
assert_matches!(
parse_storage_class("NOT_A_STORAGE_CLASS"),
Err("NOT_A_STORAGE_CLASS")
);
}
#[test]
fn test_parse_acl() {
// can't use assert_matches!(), PredefinedAcl doesn't even implement Debug.
assert!(matches!(
parse_predefined_acl("private"),
Ok(Some(PredefinedAcl::Private))
));
assert!(matches!(parse_predefined_acl(""), Ok(None)));
assert!(matches!(parse_predefined_acl("notAnACL"), Err("notAnACL")));
}
#[test]
fn test_url_of_backend() {
let bucket_name = StringNonEmpty::static_str("bucket");
let mut bucket = BucketConf::default(bucket_name);
bucket.prefix = Some(StringNonEmpty::static_str("/backup 02/prefix/"));
let gcs = Config::default(bucket.clone());
// only 'bucket' and 'prefix' should be visible in url_of_backend()
assert_eq!(
gcs.url().unwrap().to_string(),
"gcs://bucket/backup%2002/prefix/"
);
bucket.endpoint = Some(StringNonEmpty::static_str("http://endpoint.com"));
assert_eq!(
&Config::default(bucket).url().unwrap().to_string(),
"http://endpoint.com/bucket/backup%2002/prefix/"
);
}
#[test]
fn test_config_round_trip() {
let mut input = InputConfig::default();
input.set_bucket("bucket".to_owned());
input.set_prefix("backup 02/prefix/".to_owned());
let c1 = Config::from_input(input.clone()).unwrap();
let c2 = Config::from_cloud_dynamic(&cloud_dynamic_from_input(input)).unwrap();
assert_eq!(c1.bucket.bucket, c2.bucket.bucket);
assert_eq!(c1.bucket.prefix, c2.bucket.prefix);
}
fn cloud_dynamic_from_input(mut gcs: InputConfig) -> CloudDynamic {
let mut bucket = InputBucket::default();
if !gcs.endpoint.is_empty() {
bucket.endpoint = gcs.take_endpoint();
}
if !gcs.prefix.is_empty() {
bucket.prefix = gcs.take_prefix();
}
if !gcs.storage_class.is_empty() {
bucket.storage_class = gcs.take_storage_class();
}
if !gcs.bucket.is_empty() {
bucket.bucket = gcs.take_bucket();
}
let mut attrs = std::collections::HashMap::new();
if !gcs.predefined_acl.is_empty() {
attrs.insert("predefined_acl".to_owned(), gcs.take_predefined_acl());
}
if !gcs.credentials_blob.is_empty() {
attrs.insert("credentials_blob".to_owned(), gcs.take_credentials_blob());
}
let mut cd = CloudDynamic::default();
cd.set_provider_name("gcp".to_owned());
cd.set_attrs(attrs);
cd.set_bucket(bucket);
cd
}
} | storage_class,
})
}
} | random_line_split |
gcs.rs | // Copyright 2019 TiKV Project Authors. Licensed under Apache-2.0.
use std::{convert::TryInto, fmt::Display, io, sync::Arc};
use cloud::blob::{none_to_empty, BlobConfig, BlobStorage, BucketConf, StringNonEmpty};
use futures_util::{
future::TryFutureExt,
io::{AsyncRead, AsyncReadExt, Cursor},
stream::{StreamExt, TryStreamExt},
};
use hyper::{client::HttpConnector, Body, Client, Request, Response, StatusCode};
use hyper_tls::HttpsConnector;
pub use kvproto::brpb::{Bucket as InputBucket, CloudDynamic, Gcs as InputConfig};
use tame_gcs::{
common::{PredefinedAcl, StorageClass},
objects::{InsertObjectOptional, Metadata, Object},
types::{BucketName, ObjectId},
};
use tame_oauth::gcp::{ServiceAccountAccess, ServiceAccountInfo, TokenOrRequest};
use tikv_util::stream::{
block_on_external_io, error_stream, retry, AsyncReadAsSyncStreamOfBytes, RetryError,
};
const GOOGLE_APIS: &str = "https://www.googleapis.com";
const HARDCODED_ENDPOINTS_SUFFIX: &[&str] = &["upload/storage/v1/", "storage/v1/"];
#[derive(Clone, Debug)]
pub struct Config {
bucket: BucketConf,
predefined_acl: Option<PredefinedAcl>,
storage_class: Option<StorageClass>,
svc_info: Option<ServiceAccountInfo>,
}
impl Config {
#[cfg(test)]
pub fn default(bucket: BucketConf) -> Self {
Self {
bucket,
predefined_acl: None,
storage_class: None,
svc_info: None,
}
}
pub fn missing_credentials() -> io::Error {
io::Error::new(io::ErrorKind::InvalidInput, "missing credentials")
}
pub fn from_cloud_dynamic(cloud_dynamic: &CloudDynamic) -> io::Result<Config> {
let bucket = BucketConf::from_cloud_dynamic(cloud_dynamic)?;
let attrs = &cloud_dynamic.attrs;
let def = &String::new();
let predefined_acl = parse_predefined_acl(attrs.get("predefined_acl").unwrap_or(def))
.or_invalid_input("invalid predefined_acl")?;
let storage_class = parse_storage_class(&none_to_empty(bucket.storage_class.clone()))
.or_invalid_input("invalid storage_class")?;
let credentials_blob_opt = StringNonEmpty::opt(
attrs
.get("credentials_blob")
.unwrap_or(&"".to_string())
.to_string(),
);
let svc_info = if let Some(cred) = credentials_blob_opt {
Some(deserialize_service_account_info(cred)?)
} else {
None
};
Ok(Config {
bucket,
predefined_acl,
svc_info,
storage_class,
})
}
pub fn from_input(input: InputConfig) -> io::Result<Config> {
let endpoint = StringNonEmpty::opt(input.endpoint);
let bucket = BucketConf {
endpoint,
bucket: StringNonEmpty::required_field(input.bucket, "bucket")?,
prefix: StringNonEmpty::opt(input.prefix),
storage_class: StringNonEmpty::opt(input.storage_class),
region: None,
};
let predefined_acl = parse_predefined_acl(&input.predefined_acl)
.or_invalid_input("invalid predefined_acl")?;
let storage_class = parse_storage_class(&none_to_empty(bucket.storage_class.clone()))
.or_invalid_input("invalid storage_class")?;
let svc_info = if let Some(cred) = StringNonEmpty::opt(input.credentials_blob) {
Some(deserialize_service_account_info(cred)?)
} else {
None
};
Ok(Config {
bucket,
predefined_acl,
svc_info,
storage_class,
})
}
}
fn deserialize_service_account_info(
cred: StringNonEmpty,
) -> std::result::Result<ServiceAccountInfo, RequestError> {
ServiceAccountInfo::deserialize(cred.to_string())
.map_err(|e| RequestError::OAuth(e, "deserialize ServiceAccountInfo".to_string()))
}
impl BlobConfig for Config {
fn name(&self) -> &'static str {
STORAGE_NAME
}
fn url(&self) -> io::Result<url::Url> {
self.bucket.url("gcs").map_err(|s| {
io::Error::new(
io::ErrorKind::Other,
format!("error creating bucket url: {}", s),
)
})
}
}
// GCS compatible storage
#[derive(Clone)]
pub struct GCSStorage {
config: Config,
svc_access: Option<Arc<ServiceAccountAccess>>,
client: Client<HttpsConnector<HttpConnector>, Body>,
}
trait ResultExt {
type Ok;
// Maps the error of this result as an `std::io::Error` with `Other` error
// kind.
fn or_io_error<D: Display>(self, msg: D) -> io::Result<Self::Ok>;
// Maps the error of this result as an `std::io::Error` with `InvalidInput`
// error kind.
fn or_invalid_input<D: Display>(self, msg: D) -> io::Result<Self::Ok>;
}
impl<T, E: Display> ResultExt for Result<T, E> {
type Ok = T;
fn or_io_error<D: Display>(self, msg: D) -> io::Result<T> {
self.map_err(|e| io::Error::new(io::ErrorKind::Other, format!("{}: {}", msg, e)))
}
fn or_invalid_input<D: Display>(self, msg: D) -> io::Result<T> {
self.map_err(|e| io::Error::new(io::ErrorKind::InvalidInput, format!("{}: {}", msg, e)))
}
}
enum RequestError {
Hyper(hyper::Error, String),
OAuth(tame_oauth::Error, String),
Gcs(tame_gcs::Error),
InvalidEndpoint(http::uri::InvalidUri),
}
impl From<http::uri::InvalidUri> for RequestError {
fn from(err: http::uri::InvalidUri) -> Self {
Self::InvalidEndpoint(err)
}
}
fn status_code_error(code: StatusCode, msg: String) -> RequestError {
RequestError::OAuth(tame_oauth::Error::HttpStatus(code), msg)
}
impl From<RequestError> for io::Error {
fn from(err: RequestError) -> Self {
match err {
RequestError::Hyper(e, msg) => {
Self::new(io::ErrorKind::InvalidInput, format!("HTTP {}: {}", msg, e))
}
RequestError::OAuth(tame_oauth::Error::Io(e), _) => e,
RequestError::OAuth(tame_oauth::Error::HttpStatus(sc), msg) => {
let fmt = format!("GCS OAuth: {}: {}", msg, sc);
match sc.as_u16() {
401 | 403 => Self::new(io::ErrorKind::PermissionDenied, fmt),
404 => Self::new(io::ErrorKind::NotFound, fmt),
_ if sc.is_server_error() => Self::new(io::ErrorKind::Interrupted, fmt),
_ => Self::new(io::ErrorKind::InvalidInput, fmt),
}
}
RequestError::OAuth(tame_oauth::Error::AuthError(e), msg) => Self::new(
io::ErrorKind::PermissionDenied,
format!("authorization failed: {}: {}", msg, e),
),
RequestError::OAuth(e, msg) => Self::new(
io::ErrorKind::InvalidInput,
format!("oauth failed: {}: {}", msg, e),
),
RequestError::Gcs(e) => Self::new(
io::ErrorKind::InvalidInput,
format!("invalid GCS request: {}", e),
),
RequestError::InvalidEndpoint(e) => Self::new(
io::ErrorKind::InvalidInput,
format!("invalid GCS endpoint URI: {}", e),
),
}
}
}
impl RetryError for RequestError {
fn is_retryable(&self) -> bool {
match self {
// FIXME: Inspect the error source?
Self::Hyper(e, _) => {
e.is_closed()
|| e.is_connect()
|| e.is_incomplete_message()
|| e.is_body_write_aborted()
}
// See https://cloud.google.com/storage/docs/exponential-backoff.
Self::OAuth(tame_oauth::Error::HttpStatus(StatusCode::TOO_MANY_REQUESTS), _) => true,
Self::OAuth(tame_oauth::Error::HttpStatus(StatusCode::REQUEST_TIMEOUT), _) => true,
Self::OAuth(tame_oauth::Error::HttpStatus(status), _) => status.is_server_error(),
// Consider everything else not retryable.
_ => false,
}
}
}
impl GCSStorage {
pub fn from_input(input: InputConfig) -> io::Result<Self> {
Self::new(Config::from_input(input)?)
}
pub fn from_cloud_dynamic(cloud_dynamic: &CloudDynamic) -> io::Result<Self> {
Self::new(Config::from_cloud_dynamic(cloud_dynamic)?)
}
/// Create a new GCS storage for the given config.
pub fn new(config: Config) -> io::Result<GCSStorage> {
let svc_access = if let Some(si) = &config.svc_info {
Some(
ServiceAccountAccess::new(si.clone())
.or_invalid_input("invalid credentials_blob")?,
)
} else {
None
};
let client = Client::builder().build(HttpsConnector::new());
Ok(GCSStorage {
config,
svc_access: svc_access.map(Arc::new),
client,
})
}
fn maybe_prefix_key(&self, key: &str) -> String {
if let Some(prefix) = &self.config.bucket.prefix {
return format!("{}/{}", prefix, key);
}
key.to_owned()
}
async fn set_auth(
&self,
req: &mut Request<Body>,
scope: tame_gcs::Scopes,
svc_access: Arc<ServiceAccountAccess>,
) -> Result<(), RequestError> |
async fn make_request(
&self,
mut req: Request<Body>,
scope: tame_gcs::Scopes,
) -> Result<Response<Body>, RequestError> {
// replace the hard-coded GCS endpoint by the custom one.
if let Some(endpoint) = &self.config.bucket.endpoint {
let uri = req.uri().to_string();
let new_url_opt = change_host(endpoint, &uri);
if let Some(new_url) = new_url_opt {
*req.uri_mut() = new_url.parse()?;
}
}
if let Some(svc_access) = &self.svc_access {
self.set_auth(&mut req, scope, svc_access.clone()).await?;
}
let uri = req.uri().to_string();
let res = self
.client
.request(req)
.await
.map_err(|e| RequestError::Hyper(e, uri.clone()))?;
if !res.status().is_success() {
return Err(status_code_error(res.status(), uri));
}
Ok(res)
}
fn error_to_async_read<E>(kind: io::ErrorKind, e: E) -> Box<dyn AsyncRead + Unpin>
where
E: Into<Box<dyn std::error::Error + Send + Sync>>,
{
Box::new(error_stream(io::Error::new(kind, e)).into_async_read())
}
}
fn change_host(host: &StringNonEmpty, url: &str) -> Option<String> {
let new_host = (|| {
for hardcoded in HARDCODED_ENDPOINTS_SUFFIX {
if let Some(res) = host.strip_suffix(hardcoded) {
return StringNonEmpty::opt(res.to_owned()).unwrap();
}
}
host.to_owned()
})();
if let Some(res) = url.strip_prefix(GOOGLE_APIS) {
return Some([new_host.trim_end_matches('/'), res].concat());
}
None
}
// Convert manually since they don't implement FromStr.
fn parse_storage_class(sc: &str) -> Result<Option<StorageClass>, &str> {
Ok(Some(match sc {
"" => return Ok(None),
"STANDARD" => StorageClass::Standard,
"NEARLINE" => StorageClass::Nearline,
"COLDLINE" => StorageClass::Coldline,
"DURABLE_REDUCED_AVAILABILITY" => StorageClass::DurableReducedAvailability,
"REGIONAL" => StorageClass::Regional,
"MULTI_REGIONAL" => StorageClass::MultiRegional,
_ => return Err(sc),
}))
}
fn parse_predefined_acl(acl: &str) -> Result<Option<PredefinedAcl>, &str> {
Ok(Some(match acl {
"" => return Ok(None),
"authenticatedRead" => PredefinedAcl::AuthenticatedRead,
"bucketOwnerFullControl" => PredefinedAcl::BucketOwnerFullControl,
"bucketOwnerRead" => PredefinedAcl::BucketOwnerRead,
"private" => PredefinedAcl::Private,
"projectPrivate" => PredefinedAcl::ProjectPrivate,
"publicRead" => PredefinedAcl::PublicRead,
_ => return Err(acl),
}))
}
const STORAGE_NAME: &str = "gcs";
impl BlobStorage for GCSStorage {
fn config(&self) -> Box<dyn BlobConfig> {
Box::new(self.config.clone()) as Box<dyn BlobConfig>
}
fn put(
&self,
name: &str,
mut reader: Box<dyn AsyncRead + Send + Unpin>,
content_length: u64,
) -> io::Result<()> {
if content_length == 0 {
// It is probably better to just write the empty file
// However, currently going forward results in a body write aborted error
return Err(io::Error::new(
io::ErrorKind::InvalidInput,
"no content to write",
));
}
use std::convert::TryFrom;
let key = self.maybe_prefix_key(name);
debug!("save file to GCS storage"; "key" => %key);
let bucket = BucketName::try_from(self.config.bucket.bucket.to_string())
.or_invalid_input(format_args!("invalid bucket {}", self.config.bucket.bucket))?;
let metadata = Metadata {
name: Some(key),
storage_class: self.config.storage_class,
..Default::default()
};
block_on_external_io(async move {
// FIXME: Switch to upload() API so we don't need to read the entire data into memory
// in order to retry.
let mut data = Vec::with_capacity(content_length as usize);
reader.read_to_end(&mut data).await?;
retry(|| async {
let data = Cursor::new(data.clone());
let req = Object::insert_multipart(
&bucket,
data,
content_length,
&metadata,
Some(InsertObjectOptional {
predefined_acl: self.config.predefined_acl,
..Default::default()
}),
)
.map_err(RequestError::Gcs)?
.map(|reader| Body::wrap_stream(AsyncReadAsSyncStreamOfBytes::new(reader)));
self.make_request(req, tame_gcs::Scopes::ReadWrite).await
})
.await?;
Ok::<_, io::Error>(())
})?;
Ok(())
}
fn get(&self, name: &str) -> Box<dyn AsyncRead + Unpin + '_> {
let bucket = self.config.bucket.bucket.to_string();
let name = self.maybe_prefix_key(name);
debug!("read file from GCS storage"; "key" => %name);
let oid = match ObjectId::new(bucket, name) {
Ok(oid) => oid,
Err(e) => return GCSStorage::error_to_async_read(io::ErrorKind::InvalidInput, e),
};
let request = match Object::download(&oid, None /*optional*/) {
Ok(request) => request.map(|_: io::Empty| Body::empty()),
Err(e) => return GCSStorage::error_to_async_read(io::ErrorKind::Other, e),
};
Box::new(
self.make_request(request, tame_gcs::Scopes::ReadOnly)
.and_then(|response| async {
if response.status().is_success() {
Ok(response.into_body().map_err(|e| {
io::Error::new(
io::ErrorKind::Other,
format!("download from GCS error: {}", e),
)
}))
} else {
Err(status_code_error(
response.status(),
"bucket read".to_string(),
))
}
})
.err_into::<io::Error>()
.try_flatten_stream()
.boxed() // this `.boxed()` pin the stream.
.into_async_read(),
)
}
}
#[cfg(test)]
mod tests {
use super::*;
use matches::assert_matches;
const HARDCODED_ENDPOINTS: &[&str] = &[
"https://www.googleapis.com/upload/storage/v1",
"https://www.googleapis.com/storage/v1",
];
#[test]
fn test_change_host() {
let host = StringNonEmpty::static_str("http://localhost:4443");
assert_eq!(
&change_host(&host, &format!("{}/storage/v1/foo", GOOGLE_APIS)).unwrap(),
"http://localhost:4443/storage/v1/foo"
);
let h1 = url::Url::parse(HARDCODED_ENDPOINTS[0]).unwrap();
let h2 = url::Url::parse(HARDCODED_ENDPOINTS[1]).unwrap();
let endpoint = StringNonEmpty::static_str("http://example.com");
assert_eq!(
&change_host(&endpoint, h1.as_str()).unwrap(),
"http://example.com/upload/storage/v1"
);
assert_eq!(
&change_host(&endpoint, h2.as_str()).unwrap(),
"http://example.com/storage/v1"
);
assert_eq!(
&change_host(&endpoint, &format!("{}/foo", h2)).unwrap(),
"http://example.com/storage/v1/foo"
);
assert_matches!(&change_host(&endpoint, "foo"), None);
// if we get the endpoint with suffix "/storage/v1/"
let endpoint = StringNonEmpty::static_str("http://example.com/storage/v1/");
assert_eq!(
&change_host(&endpoint, &format!("{}/foo", h2)).unwrap(),
"http://example.com/storage/v1/foo"
);
let endpoint = StringNonEmpty::static_str("http://example.com/upload/storage/v1/");
assert_eq!(
&change_host(&endpoint, &format!("{}/foo", h2)).unwrap(),
"http://example.com/storage/v1/foo"
);
}
#[test]
fn test_parse_storage_class() {
assert_matches!(
parse_storage_class("STANDARD"),
Ok(Some(StorageClass::Standard))
);
assert_matches!(parse_storage_class(""), Ok(None));
assert_matches!(
parse_storage_class("NOT_A_STORAGE_CLASS"),
Err("NOT_A_STORAGE_CLASS")
);
}
#[test]
fn test_parse_acl() {
// can't use assert_matches!(), PredefinedAcl doesn't even implement Debug.
assert!(matches!(
parse_predefined_acl("private"),
Ok(Some(PredefinedAcl::Private))
));
assert!(matches!(parse_predefined_acl(""), Ok(None)));
assert!(matches!(parse_predefined_acl("notAnACL"), Err("notAnACL")));
}
#[test]
fn test_url_of_backend() {
let bucket_name = StringNonEmpty::static_str("bucket");
let mut bucket = BucketConf::default(bucket_name);
bucket.prefix = Some(StringNonEmpty::static_str("/backup 02/prefix/"));
let gcs = Config::default(bucket.clone());
// only 'bucket' and 'prefix' should be visible in url_of_backend()
assert_eq!(
gcs.url().unwrap().to_string(),
"gcs://bucket/backup%2002/prefix/"
);
bucket.endpoint = Some(StringNonEmpty::static_str("http://endpoint.com"));
assert_eq!(
&Config::default(bucket).url().unwrap().to_string(),
"http://endpoint.com/bucket/backup%2002/prefix/"
);
}
#[test]
fn test_config_round_trip() {
let mut input = InputConfig::default();
input.set_bucket("bucket".to_owned());
input.set_prefix("backup 02/prefix/".to_owned());
let c1 = Config::from_input(input.clone()).unwrap();
let c2 = Config::from_cloud_dynamic(&cloud_dynamic_from_input(input)).unwrap();
assert_eq!(c1.bucket.bucket, c2.bucket.bucket);
assert_eq!(c1.bucket.prefix, c2.bucket.prefix);
}
fn cloud_dynamic_from_input(mut gcs: InputConfig) -> CloudDynamic {
let mut bucket = InputBucket::default();
if !gcs.endpoint.is_empty() {
bucket.endpoint = gcs.take_endpoint();
}
if !gcs.prefix.is_empty() {
bucket.prefix = gcs.take_prefix();
}
if !gcs.storage_class.is_empty() {
bucket.storage_class = gcs.take_storage_class();
}
if !gcs.bucket.is_empty() {
bucket.bucket = gcs.take_bucket();
}
let mut attrs = std::collections::HashMap::new();
if !gcs.predefined_acl.is_empty() {
attrs.insert("predefined_acl".to_owned(), gcs.take_predefined_acl());
}
if !gcs.credentials_blob.is_empty() {
attrs.insert("credentials_blob".to_owned(), gcs.take_credentials_blob());
}
let mut cd = CloudDynamic::default();
cd.set_provider_name("gcp".to_owned());
cd.set_attrs(attrs);
cd.set_bucket(bucket);
cd
}
}
| {
let token_or_request = svc_access
.get_token(&[scope])
.map_err(|e| RequestError::OAuth(e, "get_token".to_string()))?;
let token = match token_or_request {
TokenOrRequest::Token(token) => token,
TokenOrRequest::Request {
request,
scope_hash,
..
} => {
let res = self
.client
.request(request.map(From::from))
.await
.map_err(|e| RequestError::Hyper(e, "set auth request".to_owned()))?;
if !res.status().is_success() {
return Err(status_code_error(
res.status(),
"set auth request".to_string(),
));
}
let (parts, body) = res.into_parts();
let body = hyper::body::to_bytes(body)
.await
.map_err(|e| RequestError::Hyper(e, "set auth body".to_owned()))?;
svc_access
.parse_token_response(scope_hash, Response::from_parts(parts, body))
.map_err(|e| RequestError::OAuth(e, "set auth parse token".to_string()))?
}
};
req.headers_mut().insert(
http::header::AUTHORIZATION,
token
.try_into()
.map_err(|e| RequestError::OAuth(e, "set auth add auth header".to_string()))?,
);
Ok(())
} | identifier_body |
setup.py | from distutils.core import setup
import sys
import py2exe
try:
scriptName = sys.argv[3]
except IndexError:
print "Usage: python setup.py py2exe -i nombreApp"
| setup(
name=scriptName,
version="2.0",
description="Aplicacion Python creada con py2exe",
author="Pueyo Luciano",
author_email="PueyoLuciano.getMail()",
url="http://cafeidotica.blogspot.com.ar/",
license="Mozilla Public License 2.0",
scripts=[scriptName + ".py"],
console=[{"script":scriptName + ".py", "icon_resources": [(1, "pyc.ico")]}],
options={"py2exe": {"bundle_files": 1}},
zipfile=None,
# windows=[{"script":scriptName + ".py" , "icon_resources": [(1, "pyc.ico")] }] <<-- si configuras el windows, corre el .exe como un proceso.
) | sys.exit(2)
# Para crear el exe hay que ir al cmd y correr python setup.py py2exe
| random_line_split |
interaction-helper.ts |
import { find, values } from 'lodash';
import { Character } from '../../../shared/models/character';
import { SkillClassNames } from '../../../shared/interfaces/character';
export class InteractionHelper {
static tryToOpenDoor(player: Character, door, { gameState }): boolean {
door.properties = door.properties || {};
const { requireLockpick, skillRequired, requireHeld, requireEventToOpen, lockedIfAlive } = door.properties;
if(requireEventToOpen) return false;
if(!door.isOpen
&& (requireLockpick || requireHeld || lockedIfAlive)) {
let shouldOpen = false;
if(player.rightHand && player.rightHand.itemClass === 'Key') {
if(player.rightHand.isBroken()) |
if(requireHeld && player.hasHeldItem(requireHeld)) {
shouldOpen = true;
player.rightHand.condition -= 1000;
} else {
player.sendClientMessage('The key snapped off in the lock!');
player.rightHand.condition = 0;
return;
}
}
/** PERK:CLASS:THIEF:Thieves can pick locks. */
if(requireLockpick
&& skillRequired
&& player.baseClass === 'Thief'
&& player.hasHeldItem('Lockpick', 'right')) {
const playerSkill = player.calcSkillLevel(SkillClassNames.Thievery) + player.getTraitLevel('LockpickSpecialty');
if(playerSkill < skillRequired) {
player.sendClientMessage('You are not skilled enough to pick this lock.');
return false;
}
player.gainSkill(SkillClassNames.Thievery, skillRequired);
player.sendClientMessage('You successfully picked the lock!');
player.setRightHand(null);
shouldOpen = true;
}
if(lockedIfAlive) {
const isNPCAlive = find(values(player.$$room.state.mapNPCs), { npcId: lockedIfAlive });
if(!isNPCAlive || (isNPCAlive && isNPCAlive.isDead())) {
shouldOpen = true;
} else {
player.sendClientMessage('The door is sealed shut by a magical force.');
return false;
}
}
if(!shouldOpen) {
player.sendClientMessage('The door is locked.');
return false;
}
}
if(door.isOpen) {
const allInDoor = player.$$room.state.getAllInRangeRaw({ x: door.x / 64, y: (door.y / 64) - 1 }, 0);
if(allInDoor.length > 0) {
player.sendClientMessage('Something is blocking the door.');
return false;
}
}
player.sendClientMessage({ message: door.isOpen ? 'You close the door.' : 'You open the door.', sfx: door.isOpen ? 'env-door-close' : 'env-door-open' });
gameState.toggleDoor(door);
return true;
}
}
| {
player.sendClientMessage('That key is not currently usable!');
return;
} | conditional_block |
interaction-helper.ts |
import { find, values } from 'lodash';
import { Character } from '../../../shared/models/character';
import { SkillClassNames } from '../../../shared/interfaces/character';
export class InteractionHelper {
static | (player: Character, door, { gameState }): boolean {
door.properties = door.properties || {};
const { requireLockpick, skillRequired, requireHeld, requireEventToOpen, lockedIfAlive } = door.properties;
if(requireEventToOpen) return false;
if(!door.isOpen
&& (requireLockpick || requireHeld || lockedIfAlive)) {
let shouldOpen = false;
if(player.rightHand && player.rightHand.itemClass === 'Key') {
if(player.rightHand.isBroken()) {
player.sendClientMessage('That key is not currently usable!');
return;
}
if(requireHeld && player.hasHeldItem(requireHeld)) {
shouldOpen = true;
player.rightHand.condition -= 1000;
} else {
player.sendClientMessage('The key snapped off in the lock!');
player.rightHand.condition = 0;
return;
}
}
/** PERK:CLASS:THIEF:Thieves can pick locks. */
if(requireLockpick
&& skillRequired
&& player.baseClass === 'Thief'
&& player.hasHeldItem('Lockpick', 'right')) {
const playerSkill = player.calcSkillLevel(SkillClassNames.Thievery) + player.getTraitLevel('LockpickSpecialty');
if(playerSkill < skillRequired) {
player.sendClientMessage('You are not skilled enough to pick this lock.');
return false;
}
player.gainSkill(SkillClassNames.Thievery, skillRequired);
player.sendClientMessage('You successfully picked the lock!');
player.setRightHand(null);
shouldOpen = true;
}
if(lockedIfAlive) {
const isNPCAlive = find(values(player.$$room.state.mapNPCs), { npcId: lockedIfAlive });
if(!isNPCAlive || (isNPCAlive && isNPCAlive.isDead())) {
shouldOpen = true;
} else {
player.sendClientMessage('The door is sealed shut by a magical force.');
return false;
}
}
if(!shouldOpen) {
player.sendClientMessage('The door is locked.');
return false;
}
}
if(door.isOpen) {
const allInDoor = player.$$room.state.getAllInRangeRaw({ x: door.x / 64, y: (door.y / 64) - 1 }, 0);
if(allInDoor.length > 0) {
player.sendClientMessage('Something is blocking the door.');
return false;
}
}
player.sendClientMessage({ message: door.isOpen ? 'You close the door.' : 'You open the door.', sfx: door.isOpen ? 'env-door-close' : 'env-door-open' });
gameState.toggleDoor(door);
return true;
}
}
| tryToOpenDoor | identifier_name |
interaction-helper.ts | import { SkillClassNames } from '../../../shared/interfaces/character';
export class InteractionHelper {
static tryToOpenDoor(player: Character, door, { gameState }): boolean {
door.properties = door.properties || {};
const { requireLockpick, skillRequired, requireHeld, requireEventToOpen, lockedIfAlive } = door.properties;
if(requireEventToOpen) return false;
if(!door.isOpen
&& (requireLockpick || requireHeld || lockedIfAlive)) {
let shouldOpen = false;
if(player.rightHand && player.rightHand.itemClass === 'Key') {
if(player.rightHand.isBroken()) {
player.sendClientMessage('That key is not currently usable!');
return;
}
if(requireHeld && player.hasHeldItem(requireHeld)) {
shouldOpen = true;
player.rightHand.condition -= 1000;
} else {
player.sendClientMessage('The key snapped off in the lock!');
player.rightHand.condition = 0;
return;
}
}
/** PERK:CLASS:THIEF:Thieves can pick locks. */
if(requireLockpick
&& skillRequired
&& player.baseClass === 'Thief'
&& player.hasHeldItem('Lockpick', 'right')) {
const playerSkill = player.calcSkillLevel(SkillClassNames.Thievery) + player.getTraitLevel('LockpickSpecialty');
if(playerSkill < skillRequired) {
player.sendClientMessage('You are not skilled enough to pick this lock.');
return false;
}
player.gainSkill(SkillClassNames.Thievery, skillRequired);
player.sendClientMessage('You successfully picked the lock!');
player.setRightHand(null);
shouldOpen = true;
}
if(lockedIfAlive) {
const isNPCAlive = find(values(player.$$room.state.mapNPCs), { npcId: lockedIfAlive });
if(!isNPCAlive || (isNPCAlive && isNPCAlive.isDead())) {
shouldOpen = true;
} else {
player.sendClientMessage('The door is sealed shut by a magical force.');
return false;
}
}
if(!shouldOpen) {
player.sendClientMessage('The door is locked.');
return false;
}
}
if(door.isOpen) {
const allInDoor = player.$$room.state.getAllInRangeRaw({ x: door.x / 64, y: (door.y / 64) - 1 }, 0);
if(allInDoor.length > 0) {
player.sendClientMessage('Something is blocking the door.');
return false;
}
}
player.sendClientMessage({ message: door.isOpen ? 'You close the door.' : 'You open the door.', sfx: door.isOpen ? 'env-door-close' : 'env-door-open' });
gameState.toggleDoor(door);
return true;
}
} | import { find, values } from 'lodash';
import { Character } from '../../../shared/models/character'; | random_line_split | |
endpoint-schema-errors-continue.config.ts | import { WeavingConfig } from '../../../src/config/weaving-config';
import { GraphQLClient } from '../../../src/graphql-client/graphql-client';
import { ExecutionResult } from 'graphql';
import { defaultTestSchema } from '../../helpers/grapqhl-http-test/graphql-http-test-schema';
import { WeavingErrorHandlingMode } from '../../../src/config/error-handling';
import gql from 'graphql-tag';
import { makeExecutableSchema } from '@graphql-tools/schema';
const errorClient: GraphQLClient = {
| (query, vars, context, introspection): Promise<ExecutionResult> {
throw new Error(introspection ? 'Throwing introspection' : 'Throwing query');
}
};
const normalSchema = makeExecutableSchema({
// ZInner should be alphabeticaly after Query so that joining occurs before linking (to test another error case)
typeDefs: gql`type ZInner { field: String } type Query { inner: ZInner, inners: [ZInner] }`,
resolvers: {
Query: {
inner() {
return { field: 'hello' };
},
inners() {
return [ { field: 'hello' }, { field: 'world' } ];
}
}
}
});
export async function getConfig(): Promise<WeavingConfig> {
return {
endpoints: [
{
client: errorClient,
identifier: 'namespaceless-erroneous'
},
{
namespace: 'erroneous',
client: errorClient
},
{
namespace: 'erroneousPrefixed',
typePrefix: 'Erroneous',
client: errorClient
},
{
namespace: 'working',
typePrefix: 'Working',
schema: defaultTestSchema
},
{
namespace: 'linkConfigError',
typePrefix: 'LinkConfigError',
schema: normalSchema,
fieldMetadata: {
'ZInner.field': {
link: {
field: 'nonexisting',
argument: 'id',
batchMode: false
}
}
}
},
{
namespace: 'joinConfigError',
typePrefix: 'joinConfigError',
schema: normalSchema,
fieldMetadata: {
'ZInner.field': {
link: {
field: 'nonexisting',
argument: 'id',
batchMode: true,
keyField: 'key'
}
},
'Query.inners': {
join: {
linkField: 'field'
}
}
}
},
],
errorHandling: WeavingErrorHandlingMode.CONTINUE_AND_REPORT_IN_SCHEMA
};
}
| execute | identifier_name |
endpoint-schema-errors-continue.config.ts | import { WeavingConfig } from '../../../src/config/weaving-config';
import { GraphQLClient } from '../../../src/graphql-client/graphql-client';
import { ExecutionResult } from 'graphql';
import { defaultTestSchema } from '../../helpers/grapqhl-http-test/graphql-http-test-schema';
import { WeavingErrorHandlingMode } from '../../../src/config/error-handling';
import gql from 'graphql-tag';
import { makeExecutableSchema } from '@graphql-tools/schema';
const errorClient: GraphQLClient = {
execute(query, vars, context, introspection): Promise<ExecutionResult> {
throw new Error(introspection ? 'Throwing introspection' : 'Throwing query');
}
};
const normalSchema = makeExecutableSchema({
// ZInner should be alphabeticaly after Query so that joining occurs before linking (to test another error case)
typeDefs: gql`type ZInner { field: String } type Query { inner: ZInner, inners: [ZInner] }`,
resolvers: {
Query: {
inner() {
return { field: 'hello' };
},
inners() {
return [ { field: 'hello' }, { field: 'world' } ];
}
}
}
});
export async function getConfig(): Promise<WeavingConfig> {
return {
endpoints: [
{
client: errorClient,
identifier: 'namespaceless-erroneous'
},
{
namespace: 'erroneous',
client: errorClient
},
{
namespace: 'erroneousPrefixed',
typePrefix: 'Erroneous',
client: errorClient
},
{
namespace: 'working',
typePrefix: 'Working',
schema: defaultTestSchema | fieldMetadata: {
'ZInner.field': {
link: {
field: 'nonexisting',
argument: 'id',
batchMode: false
}
}
}
},
{
namespace: 'joinConfigError',
typePrefix: 'joinConfigError',
schema: normalSchema,
fieldMetadata: {
'ZInner.field': {
link: {
field: 'nonexisting',
argument: 'id',
batchMode: true,
keyField: 'key'
}
},
'Query.inners': {
join: {
linkField: 'field'
}
}
}
},
],
errorHandling: WeavingErrorHandlingMode.CONTINUE_AND_REPORT_IN_SCHEMA
};
} | },
{
namespace: 'linkConfigError',
typePrefix: 'LinkConfigError',
schema: normalSchema, | random_line_split |
endpoint-schema-errors-continue.config.ts | import { WeavingConfig } from '../../../src/config/weaving-config';
import { GraphQLClient } from '../../../src/graphql-client/graphql-client';
import { ExecutionResult } from 'graphql';
import { defaultTestSchema } from '../../helpers/grapqhl-http-test/graphql-http-test-schema';
import { WeavingErrorHandlingMode } from '../../../src/config/error-handling';
import gql from 'graphql-tag';
import { makeExecutableSchema } from '@graphql-tools/schema';
const errorClient: GraphQLClient = {
execute(query, vars, context, introspection): Promise<ExecutionResult> {
throw new Error(introspection ? 'Throwing introspection' : 'Throwing query');
}
};
const normalSchema = makeExecutableSchema({
// ZInner should be alphabeticaly after Query so that joining occurs before linking (to test another error case)
typeDefs: gql`type ZInner { field: String } type Query { inner: ZInner, inners: [ZInner] }`,
resolvers: {
Query: {
inner() {
return { field: 'hello' };
},
inners() {
return [ { field: 'hello' }, { field: 'world' } ];
}
}
}
});
export async function getConfig(): Promise<WeavingConfig> | {
return {
endpoints: [
{
client: errorClient,
identifier: 'namespaceless-erroneous'
},
{
namespace: 'erroneous',
client: errorClient
},
{
namespace: 'erroneousPrefixed',
typePrefix: 'Erroneous',
client: errorClient
},
{
namespace: 'working',
typePrefix: 'Working',
schema: defaultTestSchema
},
{
namespace: 'linkConfigError',
typePrefix: 'LinkConfigError',
schema: normalSchema,
fieldMetadata: {
'ZInner.field': {
link: {
field: 'nonexisting',
argument: 'id',
batchMode: false
}
}
}
},
{
namespace: 'joinConfigError',
typePrefix: 'joinConfigError',
schema: normalSchema,
fieldMetadata: {
'ZInner.field': {
link: {
field: 'nonexisting',
argument: 'id',
batchMode: true,
keyField: 'key'
}
},
'Query.inners': {
join: {
linkField: 'field'
}
}
}
},
],
errorHandling: WeavingErrorHandlingMode.CONTINUE_AND_REPORT_IN_SCHEMA
};
} | identifier_body | |
lib.rs | //! # nom, eating data byte by byte
//!
//! nom is a parser combinator library with a focus on safe parsing,
//! streaming patterns, and as much as possible zero copy.
//!
//! ## Example
//!
//! ```rust
//! use nom::{
//! IResult,
//! bytes::complete::{tag, take_while_m_n},
//! combinator::map_res,
//! sequence::tuple};
//!
//! #[derive(Debug,PartialEq)]
//! pub struct Color {
//! pub red: u8,
//! pub green: u8,
//! pub blue: u8,
//! }
//!
//! fn from_hex(input: &str) -> Result<u8, std::num::ParseIntError> {
//! u8::from_str_radix(input, 16)
//! }
//!
//! fn is_hex_digit(c: char) -> bool {
//! c.is_digit(16)
//! }
//!
//! fn hex_primary(input: &str) -> IResult<&str, u8> {
//! map_res(
//! take_while_m_n(2, 2, is_hex_digit),
//! from_hex
//! )(input)
//! }
//!
//! fn hex_color(input: &str) -> IResult<&str, Color> {
//! let (input, _) = tag("#")(input)?;
//! let (input, (red, green, blue)) = tuple((hex_primary, hex_primary, hex_primary))(input)?;
//!
//! Ok((input, Color { red, green, blue }))
//! }
//!
//! fn main() {
//! assert_eq!(hex_color("#2F14DF"), Ok(("", Color {
//! red: 47,
//! green: 20,
//! blue: 223,
//! })));
//! }
//! ```
//!
//! The code is available on [Github](https://github.com/Geal/nom)
//!
//! There are a few [guides](https://github.com/Geal/nom/tree/master/doc) with more details
//! about [how to write parsers](https://github.com/Geal/nom/blob/master/doc/making_a_new_parser_from_scratch.md),
//! or the [error management system](https://github.com/Geal/nom/blob/master/doc/error_management.md).
//! You can also check out the [recipes] module that contains examples of common patterns.
//!
//! **Looking for a specific combinator? Read the
//! ["choose a combinator" guide](https://github.com/Geal/nom/blob/master/doc/choosing_a_combinator.md)**
//!
//! If you are upgrading to nom 5.0, please read the
//! [migration document](https://github.com/Geal/nom/blob/master/doc/upgrading_to_nom_5.md).
//!
//! ## Parser combinators
//!
//! Parser combinators are an approach to parsers that is very different from
//! software like [lex](https://en.wikipedia.org/wiki/Lex_(software)) and
//! [yacc](https://en.wikipedia.org/wiki/Yacc). Instead of writing the grammar
//! in a separate syntax and generating the corresponding code, you use very small
//! functions with very specific purposes, like "take 5 bytes", or "recognize the
//! word 'HTTP'", and assemble them in meaningful patterns like "recognize
//! 'HTTP', then a space, then a version".
//! The resulting code is small, and looks like the grammar you would have
//! written with other parser approaches.
//!
//! This gives us a few advantages:
//!
//! - The parsers are small and easy to write
//! - The parsers components are easy to reuse (if they're general enough, please add them to nom!)
//! - The parsers components are easy to test separately (unit tests and property-based tests)
//! - The parser combination code looks close to the grammar you would have written
//! - You can build partial parsers, specific to the data you need at the moment, and ignore the rest
//!
//! Here is an example of one such parser, to recognize text between parentheses:
//!
//! ```rust
//! use nom::{
//! IResult,
//! sequence::delimited,
//! // see the "streaming/complete" paragraph lower for an explanation of these submodules
//! character::complete::char,
//! bytes::complete::is_not
//! };
//!
//! fn parens(input: &str) -> IResult<&str, &str> {
//! delimited(char('('), is_not(")"), char(')'))(input)
//! }
//! ```
//!
//! It defines a function named `parens` which will recognize a sequence of the
//! character `(`, the longest byte array not containing `)`, then the character
//! `)`, and will return the byte array in the middle.
//!
//! Here is another parser, written without using nom's combinators this time:
//!
//! ```rust
//! use nom::{IResult, Err, Needed};
//!
//! # fn main() {
//! fn take4(i: &[u8]) -> IResult<&[u8], &[u8]>{
//! if i.len() < 4 {
//! Err(Err::Incomplete(Needed::new(4)))
//! } else {
//! Ok((&i[4..], &i[0..4]))
//! }
//! }
//! # }
//! ```
//!
//! This function takes a byte array as input, and tries to consume 4 bytes.
//! Writing all the parsers manually, like this, is dangerous, despite Rust's
//! safety features. There are still a lot of mistakes one can make. That's why
//! nom provides a list of functions to help in developing parsers.
//!
//! With functions, you would write it like this:
//!
//! ```rust
//! use nom::{IResult, bytes::streaming::take};
//! fn take4(input: &str) -> IResult<&str, &str> {
//! take(4u8)(input)
//! }
//! ```
//!
//! A parser in nom is a function which, for an input type `I`, an output type `O`
//! and an optional error type `E`, will have the following signature:
//!
//! ```rust,compile_fail
//! fn parser(input: I) -> IResult<I, O, E>;
//! ```
//!
//! Or like this, if you don't want to specify a custom error type (it will be `(I, ErrorKind)` by default):
//!
//! ```rust,compile_fail
//! fn parser(input: I) -> IResult<I, O>;
//! ```
//!
//! `IResult` is an alias for the `Result` type:
//!
//! ```rust
//! use nom::{Needed, error::Error};
//!
//! type IResult<I, O, E = Error<I>> = Result<(I, O), Err<E>>;
//!
//! enum Err<E> {
//! Incomplete(Needed),
//! Error(E),
//! Failure(E),
//! }
//! ```
//!
//! It can have the following values:
//!
//! - A correct result `Ok((I,O))` with the first element being the remaining of the input (not parsed yet), and the second the output value;
//! - An error `Err(Err::Error(c))` with `c` an error that can be built from the input position and a parser specific error
//! - An error `Err(Err::Incomplete(Needed))` indicating that more input is necessary. `Needed` can indicate how much data is needed
//! - An error `Err(Err::Failure(c))`. It works like the `Error` case, except it indicates an unrecoverable error: We cannot backtrack and test another parser
//!
//! Please refer to the ["choose a combinator" guide](https://github.com/Geal/nom/blob/master/doc/choosing_a_combinator.md) for an exhaustive list of parsers.
//! See also the rest of the documentation [here](https://github.com/Geal/nom/blob/master/doc).
//!
//! ## Making new parsers with function combinators
//!
//! nom is based on functions that generate parsers, with a signature like
//! this: `(arguments) -> impl Fn(Input) -> IResult<Input, Output, Error>`.
//! The arguments of a combinator can be direct values (like `take` which uses
//! a number of bytes or character as argument) or even other parsers (like
//! `delimited` which takes as argument 3 parsers, and returns the result of
//! the second one if all are successful).
//!
//! Here are some examples:
//!
//! ```rust
//! use nom::IResult;
//! use nom::bytes::complete::{tag, take};
//! fn abcd_parser(i: &str) -> IResult<&str, &str> {
//! tag("abcd")(i) // will consume bytes if the input begins with "abcd"
//! }
//!
//! fn take_10(i: &[u8]) -> IResult<&[u8], &[u8]> {
//! take(10u8)(i) // will consume and return 10 bytes of input
//! }
//! ```
//!
//! ## Combining parsers
//!
//! There are higher level patterns, like the **`alt`** combinator, which
//! provides a choice between multiple parsers. If one branch fails, it tries
//! the next, and returns the result of the first parser that succeeds:
//!
//! ```rust
//! use nom::IResult;
//! use nom::branch::alt;
//! use nom::bytes::complete::tag;
//!
//! let mut alt_tags = alt((tag("abcd"), tag("efgh")));
//!
//! assert_eq!(alt_tags(&b"abcdxxx"[..]), Ok((&b"xxx"[..], &b"abcd"[..])));
//! assert_eq!(alt_tags(&b"efghxxx"[..]), Ok((&b"xxx"[..], &b"efgh"[..])));
//! assert_eq!(alt_tags(&b"ijklxxx"[..]), Err(nom::Err::Error((&b"ijklxxx"[..], nom::error::ErrorKind::Tag))));
//! ```
//!
//! The **`opt`** combinator makes a parser optional. If the child parser returns
//! an error, **`opt`** will still succeed and return None:
//!
//! ```rust
//! use nom::{IResult, combinator::opt, bytes::complete::tag};
//! fn abcd_opt(i: &[u8]) -> IResult<&[u8], Option<&[u8]>> {
//! opt(tag("abcd"))(i)
//! }
//!
//! assert_eq!(abcd_opt(&b"abcdxxx"[..]), Ok((&b"xxx"[..], Some(&b"abcd"[..]))));
//! assert_eq!(abcd_opt(&b"efghxxx"[..]), Ok((&b"efghxxx"[..], None)));
//! ```
//!
//! **`many0`** applies a parser 0 or more times, and returns a vector of the aggregated results:
//!
//! ```rust
//! # #[cfg(feature = "alloc")]
//! # fn main() {
//! use nom::{IResult, multi::many0, bytes::complete::tag};
//! use std::str;
//!
//! fn multi(i: &str) -> IResult<&str, Vec<&str>> {
//! many0(tag("abcd"))(i)
//! }
//!
//! let a = "abcdef";
//! let b = "abcdabcdef";
//! let c = "azerty";
//! assert_eq!(multi(a), Ok(("ef", vec!["abcd"])));
//! assert_eq!(multi(b), Ok(("ef", vec!["abcd", "abcd"])));
//! assert_eq!(multi(c), Ok(("azerty", Vec::new())));
//! # }
//! # #[cfg(not(feature = "alloc"))]
//! # fn main() {}
//! ```
//!
//! Here are some basic combinators available:
//!
//! - **`opt`**: Will make the parser optional (if it returns the `O` type, the new parser returns `Option<O>`) | //! There are more complex (and more useful) parsers like `tuple!`, which is
//! used to apply a series of parsers then assemble their results.
//!
//! Example with `tuple`:
//!
//! ```rust
//! # fn main() {
//! use nom::{error::ErrorKind, Needed,
//! number::streaming::be_u16,
//! bytes::streaming::{tag, take},
//! sequence::tuple};
//!
//! let mut tpl = tuple((be_u16, take(3u8), tag("fg")));
//!
//! assert_eq!(
//! tpl(&b"abcdefgh"[..]),
//! Ok((
//! &b"h"[..],
//! (0x6162u16, &b"cde"[..], &b"fg"[..])
//! ))
//! );
//! assert_eq!(tpl(&b"abcde"[..]), Err(nom::Err::Incomplete(Needed::new(2))));
//! let input = &b"abcdejk"[..];
//! assert_eq!(tpl(input), Err(nom::Err::Error((&input[5..], ErrorKind::Tag))));
//! # }
//! ```
//!
//! But you can also use a sequence of combinators written in imperative style,
//! thanks to the `?` operator:
//!
//! ```rust
//! # fn main() {
//! use nom::{IResult, bytes::complete::tag};
//!
//! #[derive(Debug, PartialEq)]
//! struct A {
//! a: u8,
//! b: u8
//! }
//!
//! fn ret_int1(i:&[u8]) -> IResult<&[u8], u8> { Ok((i,1)) }
//! fn ret_int2(i:&[u8]) -> IResult<&[u8], u8> { Ok((i,2)) }
//!
//! fn f(i: &[u8]) -> IResult<&[u8], A> {
//! // if successful, the parser returns `Ok((remaining_input, output_value))` that we can destructure
//! let (i, _) = tag("abcd")(i)?;
//! let (i, a) = ret_int1(i)?;
//! let (i, _) = tag("efgh")(i)?;
//! let (i, b) = ret_int2(i)?;
//!
//! Ok((i, A { a, b }))
//! }
//!
//! let r = f(b"abcdefghX");
//! assert_eq!(r, Ok((&b"X"[..], A{a: 1, b: 2})));
//! # }
//! ```
//!
//! ## Streaming / Complete
//!
//! Some of nom's modules have `streaming` or `complete` submodules. They hold
//! different variants of the same combinators.
//!
//! A streaming parser assumes that we might not have all of the input data.
//! This can happen with some network protocol or large file parsers, where the
//! input buffer can be full and need to be resized or refilled.
//!
//! A complete parser assumes that we already have all of the input data.
//! This will be the common case with small files that can be read entirely to
//! memory.
//!
//! Here is how it works in practice:
//!
//! ```rust
//! use nom::{IResult, Err, Needed, error::{Error, ErrorKind}, bytes, character};
//!
//! fn take_streaming(i: &[u8]) -> IResult<&[u8], &[u8]> {
//! bytes::streaming::take(4u8)(i)
//! }
//!
//! fn take_complete(i: &[u8]) -> IResult<&[u8], &[u8]> {
//! bytes::complete::take(4u8)(i)
//! }
//!
//! // both parsers will take 4 bytes as expected
//! assert_eq!(take_streaming(&b"abcde"[..]), Ok((&b"e"[..], &b"abcd"[..])));
//! assert_eq!(take_complete(&b"abcde"[..]), Ok((&b"e"[..], &b"abcd"[..])));
//!
//! // if the input is smaller than 4 bytes, the streaming parser
//! // will return `Incomplete` to indicate that we need more data
//! assert_eq!(take_streaming(&b"abc"[..]), Err(Err::Incomplete(Needed::new(1))));
//!
//! // but the complete parser will return an error
//! assert_eq!(take_complete(&b"abc"[..]), Err(Err::Error(Error::new(&b"abc"[..], ErrorKind::Eof))));
//!
//! // the alpha0 function recognizes 0 or more alphabetic characters
//! fn alpha0_streaming(i: &str) -> IResult<&str, &str> {
//! character::streaming::alpha0(i)
//! }
//!
//! fn alpha0_complete(i: &str) -> IResult<&str, &str> {
//! character::complete::alpha0(i)
//! }
//!
//! // if there's a clear limit to the recognized characters, both parsers work the same way
//! assert_eq!(alpha0_streaming("abcd;"), Ok((";", "abcd")));
//! assert_eq!(alpha0_complete("abcd;"), Ok((";", "abcd")));
//!
//! // but when there's no limit, the streaming version returns `Incomplete`, because it cannot
//! // know if more input data should be recognized. The whole input could be "abcd;", or
//! // "abcde;"
//! assert_eq!(alpha0_streaming("abcd"), Err(Err::Incomplete(Needed::new(1))));
//!
//! // while the complete version knows that all of the data is there
//! assert_eq!(alpha0_complete("abcd"), Ok(("", "abcd")));
//! ```
//! **Going further:** Read the [guides](https://github.com/Geal/nom/tree/master/doc),
//! check out the [recipes]!
#![cfg_attr(not(feature = "std"), no_std)]
#![cfg_attr(feature = "cargo-clippy", allow(clippy::doc_markdown))]
#![cfg_attr(nightly, feature(test))]
#![cfg_attr(feature = "docsrs", feature(doc_cfg))]
#![cfg_attr(feature = "docsrs", feature(extended_key_value_attributes))]
#![deny(missing_docs)]
#[cfg_attr(nightly, warn(rustdoc::missing_doc_code_examples))]
#[cfg(feature = "alloc")]
#[macro_use]
extern crate alloc;
#[cfg(doctest)]
extern crate doc_comment;
#[cfg(nightly)]
extern crate test;
#[cfg(doctest)]
doc_comment::doctest!("../README.md");
/// Lib module to re-export everything needed from `std` or `core`/`alloc`. This is how `serde` does
/// it, albeit there it is not public.
#[cfg_attr(nightly, allow(rustdoc::missing_doc_code_examples))]
pub mod lib {
/// `std` facade allowing `std`/`core` to be interchangeable. Reexports `alloc` crate optionally,
/// as well as `core` or `std`
#[cfg(not(feature = "std"))]
#[cfg_attr(nightly, allow(rustdoc::missing_doc_code_examples))]
/// internal std exports for no_std compatibility
pub mod std {
#[doc(hidden)]
#[cfg(not(feature = "alloc"))]
pub use core::borrow;
#[cfg(feature = "alloc")]
#[doc(hidden)]
pub use alloc::{borrow, boxed, string, vec};
#[doc(hidden)]
pub use core::{cmp, convert, fmt, iter, mem, ops, option, result, slice, str};
/// internal reproduction of std prelude
#[doc(hidden)]
pub mod prelude {
pub use core::prelude as v1;
}
}
#[cfg(feature = "std")]
#[cfg_attr(nightly, allow(rustdoc::missing_doc_code_examples))]
/// internal std exports for no_std compatibility
pub mod std {
#[doc(hidden)]
pub use std::{
alloc, borrow, boxed, cmp, collections, convert, fmt, hash, iter, mem, ops, option, result,
slice, str, string, vec,
};
/// internal reproduction of std prelude
#[doc(hidden)]
pub mod prelude {
pub use std::prelude as v1;
}
}
}
pub use self::bits::*;
pub use self::internal::*;
pub use self::traits::*;
pub use self::str::*;
#[macro_use]
pub mod error;
pub mod combinator;
mod internal;
mod traits;
#[macro_use]
pub mod branch;
pub mod multi;
pub mod sequence;
pub mod bits;
pub mod bytes;
pub mod character;
mod str;
pub mod number;
#[cfg(feature = "docsrs")]
#[cfg_attr(feature = "docsrs", cfg_attr(feature = "docsrs", doc = include_str!("../doc/nom_recipes.md")))]
pub mod recipes {} | //! - **`many0`**: Will apply the parser 0 or more times (if it returns the `O` type, the new parser returns `Vec<O>`)
//! - **`many1`**: Will apply the parser 1 or more times
//! | random_line_split |
generate.ts | import selectorsLibrary from '../selectorsLibrary';
import cssVariablesLibrary from '../cssVariablesLibrary';
import keyframesLibrary from '../keyframesLibrary';
interface Stat {
appearanceCount: number;
}
export interface UsageCount {
[s: string]: number;
}
export interface Statistic {
unused: string[];
usageCount: UsageCount;
}
// eslint-disable-next-line @typescript-eslint/explicit-function-return-type
const generate = () => {
const classSelector = selectorsLibrary.getClassSelector();
const idSelector = selectorsLibrary.getIdSelector();
const cssVariables = Object.entries(cssVariablesLibrary.meta);
const keyframes = Object.entries(keyframesLibrary.meta);
const getUnused = (obj: [string, Stat][]): string[] => (
obj.filter((entry) => entry[1].appearanceCount === 0)
.map(([name]) => name)
);
const unusedCssVariables = getUnused(cssVariables);
const unusedKeyframes = getUnused(keyframes);
const unusedClasses = getUnused(Object.entries(classSelector.meta));
const unusedIds = getUnused(Object.entries(idSelector.meta));
const classUsageCount: UsageCount = {};
const idUsageCount: UsageCount = {};
const cssVariablesUsageCount: UsageCount = {};
const keyframesUsageCount: UsageCount = {};
Object.keys(classSelector.values).forEach((v) => {
classUsageCount[v] = classSelector.meta[v].appearanceCount;
});
Object.keys(idSelector.values).forEach((v) => {
idUsageCount[v] = idSelector.meta[v].appearanceCount;
});
cssVariables.forEach(([name, meta]) => {
cssVariablesUsageCount[name] = meta.appearanceCount;
});
keyframes.forEach(([name, meta]) => {
keyframesUsageCount[name] = meta.appearanceCount;
});
return {
ids: {
unused: unusedIds,
usageCount: idUsageCount,
},
classes: {
unused: unusedClasses,
usageCount: classUsageCount,
},
cssVariables: {
unused: unusedCssVariables,
usageCount: cssVariablesUsageCount,
},
keyframes: {
unused: unusedKeyframes,
usageCount: keyframesUsageCount,
},
};
}; |
export default generate; | random_line_split | |
mod.rs | //! Lexical analysis.
use std::str;
use std::fmt;
use kailua_diag::{Locale, Localize, Localized};
use string::{Name, Str};
/// A token.
#[derive(Clone, Debug, PartialEq)]
pub enum Tok {
/// A token which is distinct from all other tokens.
///
/// The lexer emits this token on an error.
Error,
/// A comment token. The parser should ignore this.
///
/// The shebang line (the first line starting with `#`) is also considered as a comment.
Comment,
/// A punctuation.
Punct(Punct),
/// A keyword.
Keyword(Keyword),
/// A number.
Num(f64),
/// A name (either an identifier or a quoted name in the meta block).
Name(Name),
/// A string (either `"string"` or `[[string]]`).
Str(Str),
/// The end of file.
///
/// A valid stream of tokens is expected to have only one EOF token at the end.
EOF,
}
impl Localize for Tok {
fn fmt_localized(&self, f: &mut fmt::Formatter, locale: Locale) -> fmt::Result {
match (&locale[..], self) {
("ko", &Tok::Error) => write!(f, "์๋ชป๋ ๋ฌธ์"),
(_, &Tok::Error) => write!(f, "an invalid character"),
("ko", &Tok::Comment) => write!(f, "์ฃผ์"),
(_, &Tok::Comment) => write!(f, "a comment"),
(_, &Tok::Punct(p)) => write!(f, "{}", Localized::new(&p, locale)),
(_, &Tok::Keyword(w)) => write!(f, "{}", Localized::new(&w, locale)),
("ko", &Tok::Num(_)) => write!(f, "์ซ์"),
(_, &Tok::Num(_)) => write!(f, "a number"),
("ko", &Tok::Name(_)) => write!(f, "์ด๋ฆ"),
(_, &Tok::Name(_)) => write!(f, "a name"),
("ko", &Tok::Str(_)) => write!(f, "๋ฌธ์์ด ๋ฆฌํฐ๋ด"),
(_, &Tok::Str(_)) => write!(f, "a string literal"),
("ko", &Tok::EOF) => write!(f, "ํ์ผ์ ๋"),
(_, &Tok::EOF) => write!(f, "the end of file"),
}
}
}
impl<'a> Localize for &'a Tok {
fn fmt_localized(&self, f: &mut fmt::Formatter, locale: Locale) -> fmt::Result {
(**self).fmt_localized(f, locale)
}
}
macro_rules! define_puncts {
($ty:ident |$locale:ident|: $($i:ident $t:expr, #[$m:meta])*) => (
/// A punctuation.
///
/// This includes Kailua-specific punctuations,
/// which are only generated in the meta block (marked as [M] below).
/// Some of them are also only generated after a particular Lua version
/// (marked as [5.x+] below).
#[derive(Copy, Clone, Debug, PartialEq, Eq)]
pub enum $ty { $(#[$m] $i,)* }
impl Localize for $ty {
fn fmt_localized(&self, f: &mut fmt::Formatter, $locale: Locale) -> fmt::Result {
let text = match *self { $($ty::$i => $t,)* };
fmt::Display::fmt(text, f)
}
}
);
}
define_puncts! { Punct |locale|:
Plus "`+`", /// `+`.
Dash "`-`", /// `-`.
Star "`*`", /// `*`.
Slash "`/`", /// `/`.
Percent "`%`", /// `%`.
Caret "`^`", /// `^`.
Hash "`#`", /// `#`.
EqEq "`==`", /// `==`.
TildeEq "`~=`", /// `~=`.
LtEq "`<=`", /// `<=`.
GtEq "`>=`", /// `>=`.
Lt "`<`", /// `<`.
Gt "`>`", /// `>`.
Eq "`=`", /// `=`.
Amp "`&`", /// `&`. [5.3+]
Tilde "`~`", /// `~`. [5.3+]
Pipe "`|`", /// `|`. [5.3+ or M]
LtLt "`<<`", /// `<<`. [5.3+]
GtGt "`>>`", /// `>>`. [5.3+]
SlashSlash "`//`", /// `//`. [5.3+]
LParen "`(`", /// `(`.
RParen "`)`", /// `)`.
LBrace "`{`", /// `{`.
RBrace "`}`", /// `}`.
LBracket "`[`", /// `[`.
RBracket "`]`", /// `]`.
Semicolon "`;`", /// `;`.
Colon "`:`", /// `:`.
ColonColon "`::`", /// `::`. [5.2+]
Comma "`,`", /// `,`.
Dot "`.`", /// `.`.
DotDot "`..`", /// `..`.
DotDotDot "`...`", /// `...`.
// Kailua extensions | DashDashColon "`--:`", /// `--:`. [M]
DashDashGt "`-->`", /// `-->`. [M]
Ques "`?`", /// `?`. [M]
Bang "`!`", /// `!`. [M]
Newline match &locale[..] { "ko" => "๊ฐํ๋ฌธ์", _ => "a newline" },
/// A newline. Only generated at the end of the meta block.
}
macro_rules! define_keywords {
($ty:ident: everywhere { $($i:ident $t:expr, #[$m:meta])* }
meta_only { $($mi:ident $mt:expr, #[$mm:meta])* }) => (
/// A keyword.
///
/// This includes Kailua-specific keywords,
/// which are only generated in the meta block (marked as [M] below).
/// Some of them are also only generated after a particular Lua version
/// (marked as [5.x+] below).
#[derive(Copy, Clone, Debug, PartialEq, Eq)]
pub enum $ty { $(#[$m] $i,)* $(#[$mm] $mi,)* }
impl $ty {
pub fn from(s: &[u8], in_meta: bool) -> Option<Keyword> {
match (in_meta, s) {
$((_, $t) => Some(Keyword::$i),)*
$((true, $mt) => Some(Keyword::$mi),)*
(_, _) => None,
}
}
pub fn name(&self) -> &'static [u8] {
match *self { $($ty::$i => $t,)* $($ty::$mi => $mt,)* }
}
}
);
}
define_keywords! { Keyword:
everywhere {
And b"and", /// `and`.
Break b"break", /// `break`.
Do b"do", /// `do`.
Else b"else", /// `else`.
Elseif b"elseif", /// `elseif`.
End b"end", /// `end`.
False b"false", /// `false`.
For b"for", /// `for`.
Function b"function", /// `function`.
Goto b"goto", /// `goto`. [5.2+; a normal identifier in Lua 5.1]
If b"if", /// `if`.
In b"in", /// `in`.
Local b"local", /// `local`.
Nil b"nil", /// `nil`.
Not b"not", /// `not`.
Or b"or", /// `or`.
Repeat b"repeat", /// `repeat`.
Return b"return", /// `return`.
Then b"then", /// `then`.
True b"true", /// `true`.
Until b"until", /// `until`.
While b"while", /// `while`.
}
meta_only { // Kailua extensions
Assume b"assume", /// `assume`. [M]
Class b"class", /// `class`. [M]
Const b"const", /// `const`. [M]
Global b"global", /// `global`. [M]
Map b"map", /// `map`. [M]
Method b"method", /// `method`. [M]
Module b"module", /// `module`. [M]
Once b"once", /// `once`. [M]
Open b"open", /// `open`. [M]
Static b"static", /// `static`. [M]
Type b"type", /// `type`. [M]
Var b"var", /// `var`. [M]
Vector b"vector", /// `vector`. [M]
}
}
impl From<Keyword> for Str {
fn from(kw: Keyword) -> Str {
kw.name().into()
}
}
impl From<Keyword> for Name {
fn from(kw: Keyword) -> Name {
kw.name().into()
}
}
impl Localize for Keyword {
fn fmt_localized(&self, f: &mut fmt::Formatter, locale: Locale) -> fmt::Result {
let name = str::from_utf8(self.name()).unwrap();
match &locale[..] {
"ko" => write!(f, "์์ฝ์ด `{}`", name),
_ => write!(f, "a keyword `{}`", name),
}
}
}
mod lexer;
mod nesting;
pub use self::lexer::Lexer;
pub use self::nesting::{Nest, NestedToken, NestingCategory, NestingSerial}; | DashDashHash "`--#`", /// `--#`. [M]
DashDashV "`--v`", /// `--v`. [M] | random_line_split |
mod.rs | //! Lexical analysis.
use std::str;
use std::fmt;
use kailua_diag::{Locale, Localize, Localized};
use string::{Name, Str};
/// A token.
#[derive(Clone, Debug, PartialEq)]
pub enum | {
/// A token which is distinct from all other tokens.
///
/// The lexer emits this token on an error.
Error,
/// A comment token. The parser should ignore this.
///
/// The shebang line (the first line starting with `#`) is also considered as a comment.
Comment,
/// A punctuation.
Punct(Punct),
/// A keyword.
Keyword(Keyword),
/// A number.
Num(f64),
/// A name (either an identifier or a quoted name in the meta block).
Name(Name),
/// A string (either `"string"` or `[[string]]`).
Str(Str),
/// The end of file.
///
/// A valid stream of tokens is expected to have only one EOF token at the end.
EOF,
}
impl Localize for Tok {
fn fmt_localized(&self, f: &mut fmt::Formatter, locale: Locale) -> fmt::Result {
match (&locale[..], self) {
("ko", &Tok::Error) => write!(f, "์๋ชป๋ ๋ฌธ์"),
(_, &Tok::Error) => write!(f, "an invalid character"),
("ko", &Tok::Comment) => write!(f, "์ฃผ์"),
(_, &Tok::Comment) => write!(f, "a comment"),
(_, &Tok::Punct(p)) => write!(f, "{}", Localized::new(&p, locale)),
(_, &Tok::Keyword(w)) => write!(f, "{}", Localized::new(&w, locale)),
("ko", &Tok::Num(_)) => write!(f, "์ซ์"),
(_, &Tok::Num(_)) => write!(f, "a number"),
("ko", &Tok::Name(_)) => write!(f, "์ด๋ฆ"),
(_, &Tok::Name(_)) => write!(f, "a name"),
("ko", &Tok::Str(_)) => write!(f, "๋ฌธ์์ด ๋ฆฌํฐ๋ด"),
(_, &Tok::Str(_)) => write!(f, "a string literal"),
("ko", &Tok::EOF) => write!(f, "ํ์ผ์ ๋"),
(_, &Tok::EOF) => write!(f, "the end of file"),
}
}
}
impl<'a> Localize for &'a Tok {
fn fmt_localized(&self, f: &mut fmt::Formatter, locale: Locale) -> fmt::Result {
(**self).fmt_localized(f, locale)
}
}
macro_rules! define_puncts {
($ty:ident |$locale:ident|: $($i:ident $t:expr, #[$m:meta])*) => (
/// A punctuation.
///
/// This includes Kailua-specific punctuations,
/// which are only generated in the meta block (marked as [M] below).
/// Some of them are also only generated after a particular Lua version
/// (marked as [5.x+] below).
#[derive(Copy, Clone, Debug, PartialEq, Eq)]
pub enum $ty { $(#[$m] $i,)* }
impl Localize for $ty {
fn fmt_localized(&self, f: &mut fmt::Formatter, $locale: Locale) -> fmt::Result {
let text = match *self { $($ty::$i => $t,)* };
fmt::Display::fmt(text, f)
}
}
);
}
define_puncts! { Punct |locale|:
Plus "`+`", /// `+`.
Dash "`-`", /// `-`.
Star "`*`", /// `*`.
Slash "`/`", /// `/`.
Percent "`%`", /// `%`.
Caret "`^`", /// `^`.
Hash "`#`", /// `#`.
EqEq "`==`", /// `==`.
TildeEq "`~=`", /// `~=`.
LtEq "`<=`", /// `<=`.
GtEq "`>=`", /// `>=`.
Lt "`<`", /// `<`.
Gt "`>`", /// `>`.
Eq "`=`", /// `=`.
Amp "`&`", /// `&`. [5.3+]
Tilde "`~`", /// `~`. [5.3+]
Pipe "`|`", /// `|`. [5.3+ or M]
LtLt "`<<`", /// `<<`. [5.3+]
GtGt "`>>`", /// `>>`. [5.3+]
SlashSlash "`//`", /// `//`. [5.3+]
LParen "`(`", /// `(`.
RParen "`)`", /// `)`.
LBrace "`{`", /// `{`.
RBrace "`}`", /// `}`.
LBracket "`[`", /// `[`.
RBracket "`]`", /// `]`.
Semicolon "`;`", /// `;`.
Colon "`:`", /// `:`.
ColonColon "`::`", /// `::`. [5.2+]
Comma "`,`", /// `,`.
Dot "`.`", /// `.`.
DotDot "`..`", /// `..`.
DotDotDot "`...`", /// `...`.
// Kailua extensions
DashDashHash "`--#`", /// `--#`. [M]
DashDashV "`--v`", /// `--v`. [M]
DashDashColon "`--:`", /// `--:`. [M]
DashDashGt "`-->`", /// `-->`. [M]
Ques "`?`", /// `?`. [M]
Bang "`!`", /// `!`. [M]
Newline match &locale[..] { "ko" => "๊ฐํ๋ฌธ์", _ => "a newline" },
/// A newline. Only generated at the end of the meta block.
}
macro_rules! define_keywords {
($ty:ident: everywhere { $($i:ident $t:expr, #[$m:meta])* }
meta_only { $($mi:ident $mt:expr, #[$mm:meta])* }) => (
/// A keyword.
///
/// This includes Kailua-specific keywords,
/// which are only generated in the meta block (marked as [M] below).
/// Some of them are also only generated after a particular Lua version
/// (marked as [5.x+] below).
#[derive(Copy, Clone, Debug, PartialEq, Eq)]
pub enum $ty { $(#[$m] $i,)* $(#[$mm] $mi,)* }
impl $ty {
pub fn from(s: &[u8], in_meta: bool) -> Option<Keyword> {
match (in_meta, s) {
$((_, $t) => Some(Keyword::$i),)*
$((true, $mt) => Some(Keyword::$mi),)*
(_, _) => None,
}
}
pub fn name(&self) -> &'static [u8] {
match *self { $($ty::$i => $t,)* $($ty::$mi => $mt,)* }
}
}
);
}
define_keywords! { Keyword:
everywhere {
And b"and", /// `and`.
Break b"break", /// `break`.
Do b"do", /// `do`.
Else b"else", /// `else`.
Elseif b"elseif", /// `elseif`.
End b"end", /// `end`.
False b"false", /// `false`.
For b"for", /// `for`.
Function b"function", /// `function`.
Goto b"goto", /// `goto`. [5.2+; a normal identifier in Lua 5.1]
If b"if", /// `if`.
In b"in", /// `in`.
Local b"local", /// `local`.
Nil b"nil", /// `nil`.
Not b"not", /// `not`.
Or b"or", /// `or`.
Repeat b"repeat", /// `repeat`.
Return b"return", /// `return`.
Then b"then", /// `then`.
True b"true", /// `true`.
Until b"until", /// `until`.
While b"while", /// `while`.
}
meta_only { // Kailua extensions
Assume b"assume", /// `assume`. [M]
Class b"class", /// `class`. [M]
Const b"const", /// `const`. [M]
Global b"global", /// `global`. [M]
Map b"map", /// `map`. [M]
Method b"method", /// `method`. [M]
Module b"module", /// `module`. [M]
Once b"once", /// `once`. [M]
Open b"open", /// `open`. [M]
Static b"static", /// `static`. [M]
Type b"type", /// `type`. [M]
Var b"var", /// `var`. [M]
Vector b"vector", /// `vector`. [M]
}
}
impl From<Keyword> for Str {
fn from(kw: Keyword) -> Str {
kw.name().into()
}
}
impl From<Keyword> for Name {
fn from(kw: Keyword) -> Name {
kw.name().into()
}
}
impl Localize for Keyword {
fn fmt_localized(&self, f: &mut fmt::Formatter, locale: Locale) -> fmt::Result {
let name = str::from_utf8(self.name()).unwrap();
match &locale[..] {
"ko" => write!(f, "์์ฝ์ด `{}`", name),
_ => write!(f, "a keyword `{}`", name),
}
}
}
mod lexer;
mod nesting;
pub use self::lexer::Lexer;
pub use self::nesting::{Nest, NestedToken, NestingCategory, NestingSerial};
| Tok | identifier_name |
mod.rs | //! Lexical analysis.
use std::str;
use std::fmt;
use kailua_diag::{Locale, Localize, Localized};
use string::{Name, Str};
/// A token.
#[derive(Clone, Debug, PartialEq)]
pub enum Tok {
/// A token which is distinct from all other tokens.
///
/// The lexer emits this token on an error.
Error,
/// A comment token. The parser should ignore this.
///
/// The shebang line (the first line starting with `#`) is also considered as a comment.
Comment,
/// A punctuation.
Punct(Punct),
/// A keyword.
Keyword(Keyword),
/// A number.
Num(f64),
/// A name (either an identifier or a quoted name in the meta block).
Name(Name),
/// A string (either `"string"` or `[[string]]`).
Str(Str),
/// The end of file.
///
/// A valid stream of tokens is expected to have only one EOF token at the end.
EOF,
}
impl Localize for Tok {
fn fmt_localized(&self, f: &mut fmt::Formatter, locale: Locale) -> fmt::Result {
match (&locale[..], self) {
("ko", &Tok::Error) => write!(f, "์๋ชป๋ ๋ฌธ์"),
(_, &Tok::Error) => write!(f, "an invalid character"),
("ko", &Tok::Comment) => write!(f, "์ฃผ์"),
(_, &Tok::Comment) => write!(f, "a comment"),
(_, &Tok::Punct(p)) => write!(f, "{}", Localized::new(&p, locale)),
(_, &Tok::Keyword(w)) => write!(f, "{}", Localized::new(&w, locale)),
("ko", &Tok::Num(_)) => write!(f, "์ซ์"),
(_, &Tok::Num(_)) => write!(f, "a number"),
("ko", &Tok::Name(_)) => write!(f, "์ด๋ฆ"),
(_, &Tok::Name(_)) => write!(f, "a name"),
("ko", &Tok::Str(_)) => write!(f, "๋ฌธ์์ด ๋ฆฌํฐ๋ด"),
(_, &Tok::Str(_)) => write!(f, "a string literal"),
("ko", &Tok::EOF) => write!(f, "ํ์ผ์ ๋"),
(_, &Tok::EOF) => write!(f, "the end of file"),
}
}
}
impl<'a> Localize for &'a Tok {
fn fmt_localized(&self, f: &mut fmt::Formatter, locale: Locale) -> fmt::Result {
(**self).fmt_localized(f, locale)
}
}
macro_rules! define_puncts {
($ty:ident |$locale:ident|: $($i:ident $t:expr, #[$m:meta])*) => (
/// A punctuation.
///
/// This includes Kailua-specific punctuations,
/// which are only generated in the meta block (marked as [M] below).
/// Some of them are also only generated after a particular Lua version
/// (marked as [5.x+] below).
#[derive(Copy, Clone, Debug, PartialEq, Eq)]
pub enum $ty { $(#[$m] $i,)* }
impl Localize for $ty {
fn fmt_localized(&self, f: &mut fmt::Formatter, $locale: Locale) -> fmt::Result {
let text = match *self { $($ty::$i => $t,)* };
fmt::Display::fmt(text, f)
}
}
);
}
define_puncts! { Punct |locale|:
Plus "`+`", /// `+`.
Dash "`-`", /// `-`.
Star "`*`", /// `*`.
Slash "`/`", /// `/`.
Percent "`%`", /// `%`.
Caret "`^`", /// `^`.
Hash "`#`", /// `#`.
EqEq "`==`", /// `==`.
TildeEq "`~=`", /// `~=`.
LtEq "`<=`", /// `<=`.
GtEq "`>=`", /// `>=`.
Lt "`<`", /// `<`.
Gt "`>`", /// `>`.
Eq "`=`", /// `=`.
Amp "`&`", /// `&`. [5.3+]
Tilde "`~`", /// `~`. [5.3+]
Pipe "`|`", /// `|`. [5.3+ or M]
LtLt "`<<`", /// `<<`. [5.3+]
GtGt "`>>`", /// `>>`. [5.3+]
SlashSlash "`//`", /// `//`. [5.3+]
LParen "`(`", /// `(`.
RParen "`)`", /// `)`.
LBrace "`{`", /// `{`.
RBrace "`}`", /// `}`.
LBracket "`[`", /// `[`.
RBracket "`]`", /// `]`.
Semicolon "`;`", /// `;`.
Colon "`:`", /// `:`.
ColonColon "`::`", /// `::`. [5.2+]
Comma "`,`", /// `,`.
Dot "`.`", /// `.`.
DotDot "`..`", /// `..`.
DotDotDot "`...`", /// `...`.
// Kailua extensions
DashDashHash "`--#`", /// `--#`. [M]
DashDashV "`--v`", /// `--v`. [M]
DashDashColon "`--:`", /// `--:`. [M]
DashDashGt "`-->`", /// `-->`. [M]
Ques "`?`", /// `?`. [M]
Bang "`!`", /// `!`. [M]
Newline match &locale[..] { "ko" => "๊ฐํ๋ฌธ์", _ => "a newline" },
/// A newline. Only generated at the end of the meta block.
}
macro_rules! define_keywords {
($ty:ident: everywhere { $($i:ident $t:expr, #[$m:meta])* }
meta_only { $($mi:ident $mt:expr, #[$mm:meta])* }) => (
/// A keyword.
///
/// This includes Kailua-specific keywords,
/// which are only generated in the meta block (marked as [M] below).
/// Some of them are also only generated after a particular Lua version
/// (marked as [5.x+] below).
#[derive(Copy, Clone, Debug, PartialEq, Eq)]
pub enum $ty { $(#[$m] $i,)* $(#[$mm] $mi,)* }
impl $ty {
pub fn from(s: &[u8], in_meta: bool) -> Option<Keyword> {
match (in_meta, s) {
$((_, $t) => Some(Keyword::$i),)*
$((true, $mt) => Some(Keyword::$mi),)*
(_, _) => None,
}
}
pub fn name(&self) -> &'static [u8] {
match *self { $($ty::$i => $t,)* $($ty::$mi => $mt,)* }
}
}
);
}
define_keywords! { Keyword:
everywhere {
And b"and", /// `and`.
Break b"break", /// `break`.
Do b"do", /// `do`.
Else b"else", /// `else`.
Elseif b"elseif", /// `elseif`.
End b"end", /// `end`.
False b"false", /// `false`.
For b"for", /// `for`.
Function b"function", /// `function`.
Goto b"goto", /// `goto`. [5.2+; a normal identifier in Lua 5.1]
If b"if", /// `if`.
In b"in", /// `in`.
Local b"local", /// `local`.
Nil b"nil", /// `nil`.
Not b"not", /// `not`.
Or b"or", /// `or`.
Repeat b"repeat", /// `repeat`.
Return b"return", /// `return`.
Then b"then", /// `then`.
True b"true", /// `true`.
Until b"until", /// `until`.
While b"while", /// `while`.
}
meta_only { // Kailua extensions
Assume b"assume", /// `assume`. [M]
Class b"class", /// `class`. [M]
Const b"const", /// `const`. [M]
Global b"global", /// `global`. [M]
Map b"map", /// `map`. [M]
Method b"method", /// `method`. [M]
Module b"module", /// `module`. [M]
Once b"once", /// `once`. [M]
Open b"open", /// `open`. [M]
Static b"static", /// `static`. [M]
Type b"type", /// `type`. [M]
Var b"var", /// `var`. [M]
Vector b"vector", /// `vector`. [M]
}
}
impl From<Keyword> for Str {
fn from(kw: Keyword) -> Str {
kw.name().into()
}
}
impl From<Keyw | Keyword) -> Name {
kw.name().into()
}
}
impl Localize for Keyword {
fn fmt_localized(&self, f: &mut fmt::Formatter, locale: Locale) -> fmt::Result {
let name = str::from_utf8(self.name()).unwrap();
match &locale[..] {
"ko" => write!(f, "์์ฝ์ด `{}`", name),
_ => write!(f, "a keyword `{}`", name),
}
}
}
mod lexer;
mod nesting;
pub use self::lexer::Lexer;
pub use self::nesting::{Nest, NestedToken, NestingCategory, NestingSerial};
| ord> for Name {
fn from(kw: | identifier_body |
import_jenkinsserver.py | from __future__ import unicode_literals
from optparse import make_option
from django.core.management.base import BaseCommand, CommandError
from django.db import transaction
from jenkins.management.helpers import import_jenkinsserver
# TODO: implement optional field updating...
class Command(BaseCommand):
help = "Import or update a JenkinsServer"
args = "[name] [url] [username] [password]"
option_list = BaseCommand.option_list + (
make_option(
"--update", action="store_true", dest="update",
default=False, help="Update if server already exists."),
)
def handle(self, *args, **options):
if len(args) != 4:
|
name, url, username, password = args
import_jenkinsserver(
name, url, username, password, update=options["update"],
stdout=self.stdout)
transaction.commit_unless_managed()
| raise CommandError("must provide all parameters") | conditional_block |
import_jenkinsserver.py | from __future__ import unicode_literals
from optparse import make_option
from django.core.management.base import BaseCommand, CommandError
from django.db import transaction
from jenkins.management.helpers import import_jenkinsserver
# TODO: implement optional field updating...
class Command(BaseCommand):
help = "Import or update a JenkinsServer"
args = "[name] [url] [username] [password]"
option_list = BaseCommand.option_list + (
make_option(
"--update", action="store_true", dest="update",
default=False, help="Update if server already exists."),
)
def handle(self, *args, **options): |
import_jenkinsserver(
name, url, username, password, update=options["update"],
stdout=self.stdout)
transaction.commit_unless_managed() | if len(args) != 4:
raise CommandError("must provide all parameters")
name, url, username, password = args | random_line_split |
import_jenkinsserver.py | from __future__ import unicode_literals
from optparse import make_option
from django.core.management.base import BaseCommand, CommandError
from django.db import transaction
from jenkins.management.helpers import import_jenkinsserver
# TODO: implement optional field updating...
class Command(BaseCommand):
help = "Import or update a JenkinsServer"
args = "[name] [url] [username] [password]"
option_list = BaseCommand.option_list + (
make_option(
"--update", action="store_true", dest="update",
default=False, help="Update if server already exists."),
)
def | (self, *args, **options):
if len(args) != 4:
raise CommandError("must provide all parameters")
name, url, username, password = args
import_jenkinsserver(
name, url, username, password, update=options["update"],
stdout=self.stdout)
transaction.commit_unless_managed()
| handle | identifier_name |
import_jenkinsserver.py | from __future__ import unicode_literals
from optparse import make_option
from django.core.management.base import BaseCommand, CommandError
from django.db import transaction
from jenkins.management.helpers import import_jenkinsserver
# TODO: implement optional field updating...
class Command(BaseCommand):
help = "Import or update a JenkinsServer"
args = "[name] [url] [username] [password]"
option_list = BaseCommand.option_list + (
make_option(
"--update", action="store_true", dest="update",
default=False, help="Update if server already exists."),
)
def handle(self, *args, **options):
| if len(args) != 4:
raise CommandError("must provide all parameters")
name, url, username, password = args
import_jenkinsserver(
name, url, username, password, update=options["update"],
stdout=self.stdout)
transaction.commit_unless_managed() | identifier_body |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.