repository_name stringclasses 316 values | func_path_in_repository stringlengths 6 223 | func_name stringlengths 1 134 | language stringclasses 1 value | func_code_string stringlengths 57 65.5k | func_documentation_string stringlengths 1 46.3k | split_name stringclasses 1 value | func_code_url stringlengths 91 315 | called_functions listlengths 1 156 ⌀ | enclosing_scope stringlengths 2 1.48M |
|---|---|---|---|---|---|---|---|---|---|
mosdef-hub/foyer | foyer/smarts_graph.py | SMARTSGraph.find_matches | python | def find_matches(self, topology):
# Note: Needs to be updated in sync with the grammar in `smarts.py`.
ring_tokens = ['ring_size', 'ring_count']
has_ring_rules = any(self.ast.select(token)
for token in ring_tokens)
_prepare_atoms(topology, compute_cycles=has_ring_rules)
top_graph = nx.Graph()
top_graph.add_nodes_from(((a.index, {'atom': a})
for a in topology.atoms()))
top_graph.add_edges_from(((b[0].index, b[1].index)
for b in topology.bonds()))
if self._graph_matcher is None:
atom = nx.get_node_attributes(self, name='atom')[0]
if len(atom.select('atom_symbol')) == 1 and not atom.select('not_expression'):
try:
element = atom.select('atom_symbol').strees[0].tail[0]
except IndexError:
try:
atomic_num = atom.select('atomic_num').strees[0].tail[0]
element = pt.Element[int(atomic_num)]
except IndexError:
element = None
else:
element = None
self._graph_matcher = SMARTSMatcher(top_graph, self,
node_match=self._node_match,
element=element)
matched_atoms = set()
for mapping in self._graph_matcher.subgraph_isomorphisms_iter():
mapping = {node_id: atom_id for atom_id, node_id in mapping.items()}
# The first node in the smarts graph always corresponds to the atom
# that we are trying to match.
atom_index = mapping[0]
# Don't yield duplicate matches found via matching the pattern in a
# different order.
if atom_index not in matched_atoms:
matched_atoms.add(atom_index)
yield atom_index | Return sets of atoms that match this SMARTS pattern in a topology.
Notes:
------
When this function gets used in atomtyper.py, we actively modify the
white- and blacklists of the atoms in `topology` after finding a match.
This means that between every successive call of
`subgraph_isomorphisms_iter()`, the topology against which we are
matching may have actually changed. Currently, we take advantage of this
behavior in some edges cases (e.g. see `test_hexa_coordinated` in
`test_smarts.py`). | train | https://github.com/mosdef-hub/foyer/blob/9e39c71208fc01a6cc7b7cbe5a533c56830681d3/foyer/smarts_graph.py#L150-L203 | [
"def _prepare_atoms(topology, compute_cycles=False):\n \"\"\"Compute cycles and add white-/blacklists to atoms.\"\"\"\n atom1 = next(topology.atoms())\n has_whitelists = hasattr(atom1, 'whitelist')\n has_cycles = hasattr(atom1, 'cycles')\n compute_cycles = compute_cycles and not has_cycles\n\n if compute_cycles or not has_whitelists:\n for atom in topology.atoms():\n if compute_cycles:\n atom.cycles = set()\n if not has_whitelists:\n atom.whitelist = OrderedSet()\n atom.blacklist = OrderedSet()\n\n if compute_cycles:\n bond_graph = nx.Graph()\n bond_graph.add_nodes_from(topology.atoms())\n bond_graph.add_edges_from(topology.bonds())\n all_cycles = _find_chordless_cycles(bond_graph, max_cycle_size=8)\n for atom, cycles in zip(bond_graph.nodes, all_cycles):\n for cycle in cycles:\n atom.cycles.add(tuple(cycle))\n"
] | class SMARTSGraph(nx.Graph):
"""A graph representation of a SMARTS pattern.
Attributes
----------
smarts_string : str
parser : foyer.smarts.SMARTS
name : str
overrides : set
Other Parameters
----------
args
kwargs
"""
# Because the first atom in a SMARTS string is always the one we want to
# type, the graph's nodes needs to be ordered.
node_dict_factory = OrderedDict
def __init__(self, smarts_string, parser=None, name=None, overrides=None,
*args, **kwargs):
super(SMARTSGraph, self).__init__(*args, **kwargs)
self.smarts_string = smarts_string
self.name = name
self.overrides = overrides
if parser is None:
self.ast = SMARTS().parse(smarts_string)
else:
self.ast = parser.parse(smarts_string)
self._atom_indices = OrderedDict()
self._add_nodes()
self._add_edges(self.ast)
self._add_label_edges()
self._graph_matcher = None
def _add_nodes(self):
"""Add all atoms in the SMARTS string as nodes in the graph."""
for n, atom in enumerate(self.ast.select('atom')):
self.add_node(n, atom=atom)
self._atom_indices[id(atom)] = n
def _add_edges(self, ast_node, trunk=None):
""""Add all bonds in the SMARTS string as edges in the graph."""
atom_indices = self._atom_indices
for atom in ast_node.tail:
if atom.head == 'atom':
atom_idx = atom_indices[id(atom)]
if atom.is_first_kid and atom.parent().head == 'branch':
trunk_idx = atom_indices[id(trunk)]
self.add_edge(atom_idx, trunk_idx)
if not atom.is_last_kid:
if atom.next_kid.head == 'atom':
next_idx = atom_indices[id(atom.next_kid)]
self.add_edge(atom_idx, next_idx)
elif atom.next_kid.head == 'branch':
trunk = atom
else: # We traveled through the whole branch.
return
elif atom.head == 'branch':
self._add_edges(atom, trunk)
def _add_label_edges(self):
"""Add edges between all atoms with the same atom_label in rings."""
labels = self.ast.select('atom_label')
if not labels:
return
# We need each individual label and atoms with multiple ring labels
# would yield e.g. the string '12' so split those up.
label_digits = defaultdict(list)
for label in labels:
digits = list(label.tail[0])
for digit in digits:
label_digits[digit].append(label.parent())
for label, (atom1, atom2) in label_digits.items():
atom1_idx = self._atom_indices[id(atom1)]
atom2_idx = self._atom_indices[id(atom2)]
self.add_edge(atom1_idx, atom2_idx)
def _node_match(self, host, pattern):
atom_expr = pattern['atom'].tail[0]
atom = host['atom']
return self._atom_expr_matches(atom_expr, atom)
def _atom_expr_matches(self, atom_expr, atom):
if atom_expr.head == 'not_expression':
return not self._atom_expr_matches(atom_expr.tail[0], atom)
elif atom_expr.head in ('and_expression', 'weak_and_expression'):
return (self._atom_expr_matches(atom_expr.tail[0], atom) and
self._atom_expr_matches(atom_expr.tail[1], atom))
elif atom_expr.head == 'or_expression':
return (self._atom_expr_matches(atom_expr.tail[0], atom) or
self._atom_expr_matches(atom_expr.tail[1], atom))
elif atom_expr.head == 'atom_id':
return self._atom_id_matches(atom_expr.tail[0], atom)
elif atom_expr.head == 'atom_symbol':
return self._atom_id_matches(atom_expr, atom)
else:
raise TypeError('Expected atom_id, atom_symbol, and_expression, '
'or_expression, or not_expression. '
'Got {}'.format(atom_expr.head))
@staticmethod
def _atom_id_matches(atom_id, atom):
atomic_num = atom.element.atomic_number
if atom_id.head == 'atomic_num':
return atomic_num == int(atom_id.tail[0])
elif atom_id.head == 'atom_symbol':
if str(atom_id.tail[0]) == '*':
return True
elif str(atom_id.tail[0]).startswith('_'):
return atom.element.name == str(atom_id.tail[0])
else:
return atomic_num == pt.AtomicNum[str(atom_id.tail[0])]
elif atom_id.head == 'has_label':
label = atom_id.tail[0][1:] # Strip the % sign from the beginning.
return label in atom.whitelist
elif atom_id.head == 'neighbor_count':
return len(atom.bond_partners) == int(atom_id.tail[0])
elif atom_id.head == 'ring_size':
cycle_len = int(atom_id.tail[0])
for cycle in atom.cycles:
if len(cycle) == cycle_len:
return True
return False
elif atom_id.head == 'ring_count':
n_cycles = len(atom.cycles)
if n_cycles == int(atom_id.tail[0]):
return True
return False
elif atom_id.head == 'matches_string':
raise NotImplementedError('matches_string is not yet implemented')
|
mosdef-hub/foyer | foyer/smarts_graph.py | SMARTSMatcher.candidate_pairs_iter | python | def candidate_pairs_iter(self):
# All computations are done using the current state!
G2_nodes = self.G2_nodes
# First we compute the inout-terminal sets.
T1_inout = set(self.inout_1.keys()) - set(self.core_1.keys())
T2_inout = set(self.inout_2.keys()) - set(self.core_2.keys())
# If T1_inout and T2_inout are both nonempty.
# P(s) = T1_inout x {min T2_inout}
if T1_inout and T2_inout:
for node in T1_inout:
yield node, min(T2_inout)
else:
# First we determine the candidate node for G2
other_node = min(G2_nodes - set(self.core_2))
host_nodes = self.valid_nodes if other_node == 0 else self.G1.nodes()
for node in host_nodes:
if node not in self.core_1:
yield node, other_node | Iterator over candidate pairs of nodes in G1 and G2. | train | https://github.com/mosdef-hub/foyer/blob/9e39c71208fc01a6cc7b7cbe5a533c56830681d3/foyer/smarts_graph.py#L216-L236 | null | class SMARTSMatcher(isomorphism.vf2userfunc.GraphMatcher):
def __init__(self, G1, G2, node_match, element):
super(SMARTSMatcher, self).__init__(G1, G2, node_match)
self.element = element
if element not in [None, '*']:
self.valid_nodes = [n for n, atom in nx.get_node_attributes(G1, name='atom').items()
if atom.element.symbol == element]
else:
self.valid_nodes = G1.nodes()
|
mosdef-hub/foyer | foyer/atomtyper.py | find_atomtypes | python | def find_atomtypes(topology, forcefield, max_iter=10):
rules = _load_rules(forcefield)
# Only consider rules for elements found in topology
subrules = dict()
system_elements = {a.element.symbol for a in topology.atoms()}
for key,val in rules.items():
atom = val.node[0]['atom']
if len(atom.select('atom_symbol')) == 1 and not atom.select('not_expression'):
try:
element = atom.select('atom_symbol').strees[0].tail[0]
except IndexError:
try:
atomic_num = atom.select('atomic_num').strees[0].tail[0]
element = pt.Element[int(atomic_num)]
except IndexError:
element = None
else:
element = None
if element is None or element in system_elements:
subrules[key] = val
rules = subrules
_iterate_rules(rules, topology, max_iter=max_iter)
_resolve_atomtypes(topology) | Determine atomtypes for all atoms.
Parameters
----------
topology : simtk.openmm.app.Topology
The topology that we are trying to atomtype.
forcefield : foyer.Forcefield
The forcefield object.
max_iter : int, optional, default=10
The maximum number of iterations. | train | https://github.com/mosdef-hub/foyer/blob/9e39c71208fc01a6cc7b7cbe5a533c56830681d3/foyer/atomtyper.py#L7-L43 | [
"def _load_rules(forcefield):\n \"\"\"Load atomtyping rules from a forcefield into SMARTSGraphs. \"\"\"\n rules = dict()\n for rule_name, smarts in forcefield.atomTypeDefinitions.items():\n overrides = forcefield.atomTypeOverrides.get(rule_name)\n if overrides is not None:\n overrides = set(overrides)\n else:\n overrides = set()\n rules[rule_name] = SMARTSGraph(smarts_string=smarts,\n parser=forcefield.parser,\n name=rule_name,\n overrides=overrides)\n return rules\n",
"def _iterate_rules(rules, topology, max_iter):\n \"\"\"Iteratively run all the rules until the white- and backlists converge.\n\n Parameters\n ----------\n rules : dict\n A dictionary mapping rule names (typically atomtype names) to\n SMARTSGraphs that evaluate those rules.\n topology : simtk.openmm.app.Topology\n The topology that we are trying to atomtype.\n max_iter : int\n The maximum number of iterations.\n\n \"\"\"\n atoms = list(topology.atoms())\n for _ in range(max_iter):\n max_iter -= 1\n found_something = False\n for rule in rules.values():\n for match_index in rule.find_matches(topology):\n atom = atoms[match_index]\n if rule.name not in atom.whitelist:\n atom.whitelist.add(rule.name)\n atom.blacklist |= rule.overrides\n found_something = True\n if not found_something:\n break\n",
"def _resolve_atomtypes(topology):\n \"\"\"Determine the final atomtypes from the white- and blacklists. \"\"\"\n for atom in topology.atoms():\n atomtype = [rule_name for rule_name in atom.whitelist - atom.blacklist]\n if len(atomtype) == 1:\n atom.id = atomtype[0]\n elif len(atomtype) > 1:\n raise FoyerError(\"Found multiple types for atom {} ({}): {}.\".format(\n atom.index, atom.element.name, atomtype))\n else:\n raise FoyerError(\"Found no types for atom {} ({}).\".format(\n atom.index, atom.element.name))\n"
] | from warnings import warn
from foyer.exceptions import FoyerError
from foyer.smarts_graph import SMARTSGraph
def _load_rules(forcefield):
"""Load atomtyping rules from a forcefield into SMARTSGraphs. """
rules = dict()
for rule_name, smarts in forcefield.atomTypeDefinitions.items():
overrides = forcefield.atomTypeOverrides.get(rule_name)
if overrides is not None:
overrides = set(overrides)
else:
overrides = set()
rules[rule_name] = SMARTSGraph(smarts_string=smarts,
parser=forcefield.parser,
name=rule_name,
overrides=overrides)
return rules
def _iterate_rules(rules, topology, max_iter):
"""Iteratively run all the rules until the white- and backlists converge.
Parameters
----------
rules : dict
A dictionary mapping rule names (typically atomtype names) to
SMARTSGraphs that evaluate those rules.
topology : simtk.openmm.app.Topology
The topology that we are trying to atomtype.
max_iter : int
The maximum number of iterations.
"""
atoms = list(topology.atoms())
for _ in range(max_iter):
max_iter -= 1
found_something = False
for rule in rules.values():
for match_index in rule.find_matches(topology):
atom = atoms[match_index]
if rule.name not in atom.whitelist:
atom.whitelist.add(rule.name)
atom.blacklist |= rule.overrides
found_something = True
if not found_something:
break
else:
warn("Reached maximum iterations. Something probably went wrong.")
def _resolve_atomtypes(topology):
"""Determine the final atomtypes from the white- and blacklists. """
for atom in topology.atoms():
atomtype = [rule_name for rule_name in atom.whitelist - atom.blacklist]
if len(atomtype) == 1:
atom.id = atomtype[0]
elif len(atomtype) > 1:
raise FoyerError("Found multiple types for atom {} ({}): {}.".format(
atom.index, atom.element.name, atomtype))
else:
raise FoyerError("Found no types for atom {} ({}).".format(
atom.index, atom.element.name))
|
mosdef-hub/foyer | foyer/atomtyper.py | _load_rules | python | def _load_rules(forcefield):
rules = dict()
for rule_name, smarts in forcefield.atomTypeDefinitions.items():
overrides = forcefield.atomTypeOverrides.get(rule_name)
if overrides is not None:
overrides = set(overrides)
else:
overrides = set()
rules[rule_name] = SMARTSGraph(smarts_string=smarts,
parser=forcefield.parser,
name=rule_name,
overrides=overrides)
return rules | Load atomtyping rules from a forcefield into SMARTSGraphs. | train | https://github.com/mosdef-hub/foyer/blob/9e39c71208fc01a6cc7b7cbe5a533c56830681d3/foyer/atomtyper.py#L46-L59 | null | from warnings import warn
from foyer.exceptions import FoyerError
from foyer.smarts_graph import SMARTSGraph
def find_atomtypes(topology, forcefield, max_iter=10):
"""Determine atomtypes for all atoms.
Parameters
----------
topology : simtk.openmm.app.Topology
The topology that we are trying to atomtype.
forcefield : foyer.Forcefield
The forcefield object.
max_iter : int, optional, default=10
The maximum number of iterations.
"""
rules = _load_rules(forcefield)
# Only consider rules for elements found in topology
subrules = dict()
system_elements = {a.element.symbol for a in topology.atoms()}
for key,val in rules.items():
atom = val.node[0]['atom']
if len(atom.select('atom_symbol')) == 1 and not atom.select('not_expression'):
try:
element = atom.select('atom_symbol').strees[0].tail[0]
except IndexError:
try:
atomic_num = atom.select('atomic_num').strees[0].tail[0]
element = pt.Element[int(atomic_num)]
except IndexError:
element = None
else:
element = None
if element is None or element in system_elements:
subrules[key] = val
rules = subrules
_iterate_rules(rules, topology, max_iter=max_iter)
_resolve_atomtypes(topology)
def _iterate_rules(rules, topology, max_iter):
"""Iteratively run all the rules until the white- and backlists converge.
Parameters
----------
rules : dict
A dictionary mapping rule names (typically atomtype names) to
SMARTSGraphs that evaluate those rules.
topology : simtk.openmm.app.Topology
The topology that we are trying to atomtype.
max_iter : int
The maximum number of iterations.
"""
atoms = list(topology.atoms())
for _ in range(max_iter):
max_iter -= 1
found_something = False
for rule in rules.values():
for match_index in rule.find_matches(topology):
atom = atoms[match_index]
if rule.name not in atom.whitelist:
atom.whitelist.add(rule.name)
atom.blacklist |= rule.overrides
found_something = True
if not found_something:
break
else:
warn("Reached maximum iterations. Something probably went wrong.")
def _resolve_atomtypes(topology):
"""Determine the final atomtypes from the white- and blacklists. """
for atom in topology.atoms():
atomtype = [rule_name for rule_name in atom.whitelist - atom.blacklist]
if len(atomtype) == 1:
atom.id = atomtype[0]
elif len(atomtype) > 1:
raise FoyerError("Found multiple types for atom {} ({}): {}.".format(
atom.index, atom.element.name, atomtype))
else:
raise FoyerError("Found no types for atom {} ({}).".format(
atom.index, atom.element.name))
|
mosdef-hub/foyer | foyer/atomtyper.py | _iterate_rules | python | def _iterate_rules(rules, topology, max_iter):
atoms = list(topology.atoms())
for _ in range(max_iter):
max_iter -= 1
found_something = False
for rule in rules.values():
for match_index in rule.find_matches(topology):
atom = atoms[match_index]
if rule.name not in atom.whitelist:
atom.whitelist.add(rule.name)
atom.blacklist |= rule.overrides
found_something = True
if not found_something:
break
else:
warn("Reached maximum iterations. Something probably went wrong.") | Iteratively run all the rules until the white- and backlists converge.
Parameters
----------
rules : dict
A dictionary mapping rule names (typically atomtype names) to
SMARTSGraphs that evaluate those rules.
topology : simtk.openmm.app.Topology
The topology that we are trying to atomtype.
max_iter : int
The maximum number of iterations. | train | https://github.com/mosdef-hub/foyer/blob/9e39c71208fc01a6cc7b7cbe5a533c56830681d3/foyer/atomtyper.py#L62-L90 | null | from warnings import warn
from foyer.exceptions import FoyerError
from foyer.smarts_graph import SMARTSGraph
def find_atomtypes(topology, forcefield, max_iter=10):
"""Determine atomtypes for all atoms.
Parameters
----------
topology : simtk.openmm.app.Topology
The topology that we are trying to atomtype.
forcefield : foyer.Forcefield
The forcefield object.
max_iter : int, optional, default=10
The maximum number of iterations.
"""
rules = _load_rules(forcefield)
# Only consider rules for elements found in topology
subrules = dict()
system_elements = {a.element.symbol for a in topology.atoms()}
for key,val in rules.items():
atom = val.node[0]['atom']
if len(atom.select('atom_symbol')) == 1 and not atom.select('not_expression'):
try:
element = atom.select('atom_symbol').strees[0].tail[0]
except IndexError:
try:
atomic_num = atom.select('atomic_num').strees[0].tail[0]
element = pt.Element[int(atomic_num)]
except IndexError:
element = None
else:
element = None
if element is None or element in system_elements:
subrules[key] = val
rules = subrules
_iterate_rules(rules, topology, max_iter=max_iter)
_resolve_atomtypes(topology)
def _load_rules(forcefield):
"""Load atomtyping rules from a forcefield into SMARTSGraphs. """
rules = dict()
for rule_name, smarts in forcefield.atomTypeDefinitions.items():
overrides = forcefield.atomTypeOverrides.get(rule_name)
if overrides is not None:
overrides = set(overrides)
else:
overrides = set()
rules[rule_name] = SMARTSGraph(smarts_string=smarts,
parser=forcefield.parser,
name=rule_name,
overrides=overrides)
return rules
def _resolve_atomtypes(topology):
"""Determine the final atomtypes from the white- and blacklists. """
for atom in topology.atoms():
atomtype = [rule_name for rule_name in atom.whitelist - atom.blacklist]
if len(atomtype) == 1:
atom.id = atomtype[0]
elif len(atomtype) > 1:
raise FoyerError("Found multiple types for atom {} ({}): {}.".format(
atom.index, atom.element.name, atomtype))
else:
raise FoyerError("Found no types for atom {} ({}).".format(
atom.index, atom.element.name))
|
mosdef-hub/foyer | foyer/atomtyper.py | _resolve_atomtypes | python | def _resolve_atomtypes(topology):
for atom in topology.atoms():
atomtype = [rule_name for rule_name in atom.whitelist - atom.blacklist]
if len(atomtype) == 1:
atom.id = atomtype[0]
elif len(atomtype) > 1:
raise FoyerError("Found multiple types for atom {} ({}): {}.".format(
atom.index, atom.element.name, atomtype))
else:
raise FoyerError("Found no types for atom {} ({}).".format(
atom.index, atom.element.name)) | Determine the final atomtypes from the white- and blacklists. | train | https://github.com/mosdef-hub/foyer/blob/9e39c71208fc01a6cc7b7cbe5a533c56830681d3/foyer/atomtyper.py#L93-L104 | null | from warnings import warn
from foyer.exceptions import FoyerError
from foyer.smarts_graph import SMARTSGraph
def find_atomtypes(topology, forcefield, max_iter=10):
"""Determine atomtypes for all atoms.
Parameters
----------
topology : simtk.openmm.app.Topology
The topology that we are trying to atomtype.
forcefield : foyer.Forcefield
The forcefield object.
max_iter : int, optional, default=10
The maximum number of iterations.
"""
rules = _load_rules(forcefield)
# Only consider rules for elements found in topology
subrules = dict()
system_elements = {a.element.symbol for a in topology.atoms()}
for key,val in rules.items():
atom = val.node[0]['atom']
if len(atom.select('atom_symbol')) == 1 and not atom.select('not_expression'):
try:
element = atom.select('atom_symbol').strees[0].tail[0]
except IndexError:
try:
atomic_num = atom.select('atomic_num').strees[0].tail[0]
element = pt.Element[int(atomic_num)]
except IndexError:
element = None
else:
element = None
if element is None or element in system_elements:
subrules[key] = val
rules = subrules
_iterate_rules(rules, topology, max_iter=max_iter)
_resolve_atomtypes(topology)
def _load_rules(forcefield):
"""Load atomtyping rules from a forcefield into SMARTSGraphs. """
rules = dict()
for rule_name, smarts in forcefield.atomTypeDefinitions.items():
overrides = forcefield.atomTypeOverrides.get(rule_name)
if overrides is not None:
overrides = set(overrides)
else:
overrides = set()
rules[rule_name] = SMARTSGraph(smarts_string=smarts,
parser=forcefield.parser,
name=rule_name,
overrides=overrides)
return rules
def _iterate_rules(rules, topology, max_iter):
"""Iteratively run all the rules until the white- and backlists converge.
Parameters
----------
rules : dict
A dictionary mapping rule names (typically atomtype names) to
SMARTSGraphs that evaluate those rules.
topology : simtk.openmm.app.Topology
The topology that we are trying to atomtype.
max_iter : int
The maximum number of iterations.
"""
atoms = list(topology.atoms())
for _ in range(max_iter):
max_iter -= 1
found_something = False
for rule in rules.values():
for match_index in rule.find_matches(topology):
atom = atoms[match_index]
if rule.name not in atom.whitelist:
atom.whitelist.add(rule.name)
atom.blacklist |= rule.overrides
found_something = True
if not found_something:
break
else:
warn("Reached maximum iterations. Something probably went wrong.")
|
mosdef-hub/foyer | foyer/forcefield.py | generate_topology | python | def generate_topology(non_omm_topology, non_element_types=None,
residues=None):
if non_element_types is None:
non_element_types = set()
if isinstance(non_omm_topology, pmd.Structure):
return _topology_from_parmed(non_omm_topology, non_element_types)
elif has_mbuild:
mb = import_('mbuild')
if (non_omm_topology, mb.Compound):
pmdCompoundStructure = non_omm_topology.to_parmed(residues=residues)
return _topology_from_parmed(pmdCompoundStructure, non_element_types)
else:
raise FoyerError('Unknown topology format: {}\n'
'Supported formats are: '
'"parmed.Structure", '
'"mbuild.Compound", '
'"openmm.app.Topology"'.format(non_omm_topology)) | Create an OpenMM Topology from another supported topology structure. | train | https://github.com/mosdef-hub/foyer/blob/9e39c71208fc01a6cc7b7cbe5a533c56830681d3/foyer/forcefield.py#L87-L105 | [
"def import_(module):\n \"\"\"Import a module, and issue a nice message to stderr if the module isn't installed.\n Parameters\n ----------\n module : str\n The module you'd like to import, as a string\n Returns\n -------\n module : {module, object}\n The module object\n Examples\n --------\n >>> # the following two lines are equivalent. the difference is that the\n >>> # second will check for an ImportError and print you a very nice\n >>> # user-facing message about what's wrong (where you can install the\n >>> # module from, etc) if the import fails\n >>> import tables\n >>> tables = import_('tables')\n \"\"\"\n try:\n return importlib.import_module(module)\n except ImportError as e:\n try:\n message = MESSAGES[module]\n except KeyError:\n message = 'The code at {filename}:{line_number} requires the ' + module + ' package'\n e = ImportError('No module named %s' % module)\n\n frame, filename, line_number, function_name, lines, index = \\\n inspect.getouterframes(inspect.currentframe())[1]\n\n m = message.format(filename=os.path.basename(filename), line_number=line_number)\n m = textwrap.dedent(m)\n\n bar = '\\033[91m' + '#' * max(len(line) for line in m.split(os.linesep)) + '\\033[0m'\n\n print('', file=sys.stderr)\n print(bar, file=sys.stderr)\n print(m, file=sys.stderr)\n print(bar, file=sys.stderr)\n raise DelayImportError(m)\n",
"def _topology_from_parmed(structure, non_element_types):\n \"\"\"Convert a ParmEd Structure to an OpenMM Topology.\"\"\"\n topology = app.Topology()\n residues = dict()\n for pmd_residue in structure.residues:\n chain = topology.addChain()\n omm_residue = topology.addResidue(pmd_residue.name, chain)\n residues[pmd_residue] = omm_residue\n atoms = dict() # pmd.Atom: omm.Atom\n\n for pmd_atom in structure.atoms:\n name = pmd_atom.name\n if pmd_atom.name in non_element_types:\n element = non_element_types[pmd_atom.name]\n else:\n if (isinstance(pmd_atom.atomic_number, int) and\n pmd_atom.atomic_number != 0):\n element = elem.Element.getByAtomicNumber(pmd_atom.atomic_number)\n else:\n element = elem.Element.getBySymbol(pmd_atom.name)\n\n omm_atom = topology.addAtom(name, element, residues[pmd_atom.residue])\n atoms[pmd_atom] = omm_atom\n omm_atom.bond_partners = []\n\n for bond in structure.bonds:\n atom1 = atoms[bond.atom1]\n atom2 = atoms[bond.atom2]\n topology.addBond(atom1, atom2)\n atom1.bond_partners.append(atom2)\n atom2.bond_partners.append(atom1)\n if structure.box_vectors and np.any([x._value for x in structure.box_vectors]):\n topology.setPeriodicBoxVectors(structure.box_vectors)\n\n positions = structure.positions\n return topology, positions\n"
] | import collections
import glob
import itertools
import os
from tempfile import mktemp, mkstemp
import xml.etree.ElementTree as ET
try:
from cStringIO import StringIO
except ImportError:
from io import StringIO
from pkg_resources import resource_filename
import requests
import warnings
import re
import numpy as np
import parmed as pmd
import simtk.openmm.app.element as elem
import foyer.element as custom_elem
import simtk.unit as u
from simtk import openmm as mm
from simtk.openmm import app
from simtk.openmm.app.forcefield import (NoCutoff, CutoffNonPeriodic, HBonds,
AllBonds, HAngles, NonbondedGenerator,
_convertParameterToNumber)
from foyer.atomtyper import find_atomtypes
from foyer.exceptions import FoyerError
from foyer import smarts
from foyer.validator import Validator
from foyer.utils.io import import_, has_mbuild
def preprocess_forcefield_files(forcefield_files=None):
if forcefield_files is None:
return None
preprocessed_files = []
for xml_file in forcefield_files:
if not hasattr(xml_file,'read'):
f = open(xml_file)
_,suffix = os.path.split(xml_file)
else:
f = xml_file
suffix=""
# read and preprocess
xml_contents = f.read()
f.close()
xml_contents = re.sub(r"(def\w*=\w*[\"\'])(.*)([\"\'])", lambda m: m.group(1) + re.sub(r"&(?!amp;)", r"&", m.group(2)) + m.group(3),
xml_contents)
try:
'''
Sort topology objects by precedence, defined by the number of
`type` attributes specified, where a `type` attribute indicates
increased specificity as opposed to use of `class`
'''
root = ET.fromstring(xml_contents)
for element in root:
if 'Force' in element.tag:
element[:] = sorted(element, key=lambda child: (
-1 * len([attr_name for attr_name in child.keys()
if 'type' in attr_name])))
xml_contents = ET.tostring(root, method='xml').decode()
except ET.ParseError:
'''
Provide the user with a warning if sorting could not be performed.
This indicates a bad XML file, which will be passed on to the
Validator to yield a more descriptive error message.
'''
warnings.warn('Invalid XML detected. Could not auto-sort topology '
'objects by precedence.')
# write to temp file
_, temp_file_name = mkstemp(suffix=suffix)
with open(temp_file_name, 'w') as temp_f:
temp_f.write(xml_contents)
# append temp file name to list
preprocessed_files.append(temp_file_name)
return preprocessed_files
def _topology_from_parmed(structure, non_element_types):
"""Convert a ParmEd Structure to an OpenMM Topology."""
topology = app.Topology()
residues = dict()
for pmd_residue in structure.residues:
chain = topology.addChain()
omm_residue = topology.addResidue(pmd_residue.name, chain)
residues[pmd_residue] = omm_residue
atoms = dict() # pmd.Atom: omm.Atom
for pmd_atom in structure.atoms:
name = pmd_atom.name
if pmd_atom.name in non_element_types:
element = non_element_types[pmd_atom.name]
else:
if (isinstance(pmd_atom.atomic_number, int) and
pmd_atom.atomic_number != 0):
element = elem.Element.getByAtomicNumber(pmd_atom.atomic_number)
else:
element = elem.Element.getBySymbol(pmd_atom.name)
omm_atom = topology.addAtom(name, element, residues[pmd_atom.residue])
atoms[pmd_atom] = omm_atom
omm_atom.bond_partners = []
for bond in structure.bonds:
atom1 = atoms[bond.atom1]
atom2 = atoms[bond.atom2]
topology.addBond(atom1, atom2)
atom1.bond_partners.append(atom2)
atom2.bond_partners.append(atom1)
if structure.box_vectors and np.any([x._value for x in structure.box_vectors]):
topology.setPeriodicBoxVectors(structure.box_vectors)
positions = structure.positions
return topology, positions
def _topology_from_residue(res):
"""Converts a openmm.app.Topology.Residue to openmm.app.Topology.
Parameters
----------
res : openmm.app.Topology.Residue
An individual residue in an openmm.app.Topology
Returns
-------
topology : openmm.app.Topology
The generated topology
"""
topology = app.Topology()
chain = topology.addChain()
new_res = topology.addResidue(res.name, chain)
atoms = dict() # { omm.Atom in res : omm.Atom in *new* topology }
for res_atom in res.atoms():
topology_atom = topology.addAtom(name=res_atom.name,
element=res_atom.element,
residue=new_res)
atoms[res_atom] = topology_atom
topology_atom.bond_partners = []
for bond in res.bonds():
atom1 = atoms[bond.atom1]
atom2 = atoms[bond.atom2]
topology.addBond(atom1, atom2)
atom1.bond_partners.append(atom2)
atom2.bond_partners.append(atom1)
return topology
def _check_independent_residues(topology):
"""Check to see if residues will constitute independent graphs."""
for res in topology.residues():
atoms_in_residue = set([atom for atom in res.atoms()])
bond_partners_in_residue = [item for sublist in [atom.bond_partners for atom in res.atoms()] for item in sublist]
# Handle the case of a 'residue' with no neighbors
if not bond_partners_in_residue:
continue
if set(atoms_in_residue) != set(bond_partners_in_residue):
return False
return True
def _update_atomtypes(unatomtyped_topology, res_name, prototype):
"""Update atomtypes in residues in a topology using a prototype topology.
Atomtypes are updated when residues in each topology have matching names.
Parameters
----------
unatomtyped_topology : openmm.app.Topology
Topology lacking atomtypes defined by `find_atomtypes`.
prototype : openmm.app.Topology
Prototype topology with atomtypes defined by `find_atomtypes`.
"""
for res in unatomtyped_topology.residues():
if res.name == res_name:
for old_atom, new_atom_id in zip([atom for atom in res.atoms()], [atom.id for atom in prototype.atoms()]):
old_atom.id = new_atom_id
def _error_or_warn(error, msg):
"""Raise an error or warning if topology objects are not fully parameterized.
Parameters
----------
error : bool
If True, raise an error, else raise a warning
msg : str
The message to be provided with the error or warning
"""
if error:
raise Exception(msg)
else:
warnings.warn(msg)
class Forcefield(app.ForceField):
"""Specialization of OpenMM's Forcefield allowing SMARTS based atomtyping.
Parameters
----------
forcefield_files : list of str, optional, default=None
List of forcefield files to load.
name : str, optional, default=None
Name of a forcefield to load that is packaged within foyer.
"""
def __init__(self, forcefield_files=None, name=None, validation=True, debug=False):
self.atomTypeDefinitions = dict()
self.atomTypeOverrides = dict()
self.atomTypeDesc = dict()
self.atomTypeRefs = dict()
self._included_forcefields = dict()
self.non_element_types = dict()
all_files_to_load = []
if forcefield_files is not None:
if isinstance(forcefield_files, (list, tuple, set)):
for file in forcefield_files:
all_files_to_load.append(file)
else:
all_files_to_load.append(forcefield_files)
if name is not None:
try:
file = self.included_forcefields[name]
except KeyError:
raise IOError('Forcefield {} cannot be found'.format(name))
else:
all_files_to_load.append(file)
preprocessed_files = preprocess_forcefield_files(all_files_to_load)
if validation:
for ff_file_name in preprocessed_files:
Validator(ff_file_name, debug)
super(Forcefield, self).__init__(*preprocessed_files)
self.parser = smarts.SMARTS(self.non_element_types)
self._SystemData = self._SystemData()
@property
def included_forcefields(self):
if any(self._included_forcefields):
return self._included_forcefields
ff_dir = resource_filename('foyer', 'forcefields')
ff_filepaths = set(glob.glob(os.path.join(ff_dir, '*.xml')))
for ff_filepath in ff_filepaths:
_, ff_file = os.path.split(ff_filepath)
basename, _ = os.path.splitext(ff_file)
self._included_forcefields[basename] = ff_filepath
return self._included_forcefields
def _create_element(self, element, mass):
if not isinstance(element, elem.Element):
try:
element = elem.get_by_symbol(element)
except KeyError:
# Enables support for non-atomistic "element types"
if element not in self.non_element_types:
warnings.warn('Non-atomistic element type detected. '
'Creating custom element for {}'.format(element))
element = custom_elem.Element(number=0,
mass=mass,
name=element,
symbol=element)
else:
return element, False
return element, True
def registerAtomType(self, parameters):
"""Register a new atom type. """
name = parameters['name']
if name in self._atomTypes:
raise ValueError('Found multiple definitions for atom type: ' + name)
atom_class = parameters['class']
mass = _convertParameterToNumber(parameters['mass'])
element = None
if 'element' in parameters:
element, custom = self._create_element(parameters['element'], mass)
if custom:
self.non_element_types[element.symbol] = element
self._atomTypes[name] = self.__class__._AtomType(name, atom_class, mass, element)
if atom_class in self._atomClasses:
type_set = self._atomClasses[atom_class]
else:
type_set = set()
self._atomClasses[atom_class] = type_set
type_set.add(name)
self._atomClasses[''].add(name)
name = parameters['name']
if 'def' in parameters:
self.atomTypeDefinitions[name] = parameters['def']
if 'overrides' in parameters:
overrides = set(atype.strip() for atype
in parameters['overrides'].split(","))
if overrides:
self.atomTypeOverrides[name] = overrides
if 'des' in parameters:
self.atomTypeDesc[name] = parameters['desc']
if 'doi' in parameters:
dois = set(doi.strip() for doi in parameters['doi'].split(','))
self.atomTypeRefs[name] = dois
def apply(self, topology, references_file=None, use_residue_map=True,
assert_bond_params=True, assert_angle_params=True,
assert_dihedral_params=True, assert_improper_params=False,
*args, **kwargs):
"""Apply the force field to a molecular structure
Parameters
----------
topology : openmm.app.Topology or parmed.Structure or mbuild.Compound
Molecular structure to apply the force field to
references_file : str, optional, default=None
Name of file where force field references will be written (in Bibtex
format)
use_residue_map : boolean, optional, default=True
Store atomtyped topologies of residues to a dictionary that maps
them to residue names. Each topology, including atomtypes, will be
copied to other residues with the same name. This avoids repeatedly
calling the subgraph isomorphism on idential residues and should
result in better performance for systems with many identical
residues, i.e. a box of water. Note that for this to be applied to
independent molecules, they must each be saved as different
residues in the topology.
assert_bond_params : bool, optional, default=True
If True, Foyer will exit if parameters are not found for all system
bonds.
assert_angle_params : bool, optional, default=True
If True, Foyer will exit if parameters are not found for all system
angles.
assert_dihedral_params : bool, optional, default=True
If True, Foyer will exit if parameters are not found for all system
proper dihedrals.
assert_improper_params : bool, optional, default=False
If True, Foyer will exit if parameters are not found for all system
improper dihedrals.
"""
if self.atomTypeDefinitions == {}:
raise FoyerError('Attempting to atom-type using a force field '
'with no atom type defitions.')
if not isinstance(topology, app.Topology):
residues = kwargs.get('residues')
topology, positions = generate_topology(topology,
self.non_element_types, residues=residues)
else:
positions = np.empty(shape=(topology.getNumAtoms(), 3))
positions[:] = np.nan
box_vectors = topology.getPeriodicBoxVectors()
topology = self.run_atomtyping(topology, use_residue_map=use_residue_map)
system = self.createSystem(topology, *args, **kwargs)
structure = pmd.openmm.load_topology(topology=topology, system=system)
'''
Check that all topology objects (angles, dihedrals, and impropers)
have parameters assigned. OpenMM will generate an error if bond parameters
are not assigned.
'''
data = self._SystemData
if data.bonds:
missing = [b for b in structure.bonds
if b.type is None]
if missing:
nmissing = len(structure.bonds) - len(missing)
msg = ("Parameters have not been assigned to all bonds. "
"Total system bonds: {}, Parametrized bonds: {}"
"".format(len(structure.bonds), nmissing))
_error_or_warn(assert_bond_params, msg)
if data.angles and (len(data.angles) != len(structure.angles)):
msg = ("Parameters have not been assigned to all angles. Total "
"system angles: {}, Parameterized angles: {}"
"".format(len(data.angles), len(structure.angles)))
_error_or_warn(assert_angle_params, msg)
proper_dihedrals = [dihedral for dihedral in structure.dihedrals
if not dihedral.improper]
if data.propers and len(data.propers) != \
len(proper_dihedrals) + len(structure.rb_torsions):
msg = ("Parameters have not been assigned to all proper dihedrals. "
"Total system dihedrals: {}, Parameterized dihedrals: {}. "
"Note that if your system contains torsions of Ryckaert-"
"Bellemans functional form, all of these torsions are "
"processed as propers.".format(len(data.propers),
len(proper_dihedrals) + len(structure.rb_torsions)))
_error_or_warn(assert_dihedral_params, msg)
improper_dihedrals = [dihedral for dihedral in structure.dihedrals
if dihedral.improper]
if data.impropers and len(data.impropers) != \
len(improper_dihedrals) + len(structure.impropers):
msg = ("Parameters have not been assigned to all impropers. Total "
"system impropers: {}, Parameterized impropers: {}. "
"Note that if your system contains torsions of Ryckaert-"
"Bellemans functional form, all of these torsions are "
"processed as propers".format(len(data.impropers),
len(improper_dihedrals) + len(structure.impropers)))
_error_or_warn(assert_improper_params, msg)
structure.bonds.sort(key=lambda x: x.atom1.idx)
structure.positions = positions
if box_vectors is not None:
structure.box_vectors = box_vectors
if references_file:
atom_types = set(atom.type for atom in structure.atoms)
self._write_references_to_file(atom_types, references_file)
return structure
def run_atomtyping(self, topology, use_residue_map=True):
"""Atomtype the topology
Parameters
----------
topology : openmm.app.Topology
Molecular structure to find atom types of
use_residue_map : boolean, optional, default=True
Store atomtyped topologies of residues to a dictionary that maps
them to residue names. Each topology, including atomtypes, will be
copied to other residues with the same name. This avoids repeatedly
calling the subgraph isomorphism on idential residues and should
result in better performance for systems with many identical
residues, i.e. a box of water. Note that for this to be applied to
independent molecules, they must each be saved as different
residues in the topology.
"""
if use_residue_map:
independent_residues = _check_independent_residues(topology)
if independent_residues:
residue_map = dict()
for res in topology.residues():
if res.name not in residue_map.keys():
residue = _topology_from_residue(res)
find_atomtypes(residue, forcefield=self)
residue_map[res.name] = residue
for key, val in residue_map.items():
_update_atomtypes(topology, key, val)
else:
find_atomtypes(topology, forcefield=self)
else:
find_atomtypes(topology, forcefield=self)
if not all([a.id for a in topology.atoms()][0]):
raise ValueError('Not all atoms in topology have atom types')
return topology
def createSystem(self, topology, nonbondedMethod=NoCutoff,
nonbondedCutoff=1.0 * u.nanometer, constraints=None,
rigidWater=True, removeCMMotion=True, hydrogenMass=None,
**args):
"""Construct an OpenMM System representing a Topology with this force field.
Parameters
----------
topology : Topology
The Topology for which to create a System
nonbondedMethod : object=NoCutoff
The method to use for nonbonded interactions. Allowed values are
NoCutoff, CutoffNonPeriodic, CutoffPeriodic, Ewald, or PME.
nonbondedCutoff : distance=1*nanometer
The cutoff distance to use for nonbonded interactions
constraints : object=None
Specifies which bonds and angles should be implemented with constraints.
Allowed values are None, HBonds, AllBonds, or HAngles.
rigidWater : boolean=True
If true, water molecules will be fully rigid regardless of the value
passed for the constraints argument
removeCMMotion : boolean=True
If true, a CMMotionRemover will be added to the System
hydrogenMass : mass=None
The mass to use for hydrogen atoms bound to heavy atoms. Any mass
added to a hydrogen is subtracted from the heavy atom to keep
their total mass the same.
args
Arbitrary additional keyword arguments may also be specified.
This allows extra parameters to be specified that are specific to
particular force fields.
Returns
-------
system
the newly created System
"""
# Overwrite previous _SystemData object
self._SystemData = app.ForceField._SystemData()
data = self._SystemData
data.atoms = list(topology.atoms())
for atom in data.atoms:
data.excludeAtomWith.append([])
# Make a list of all bonds
for bond in topology.bonds():
data.bonds.append(app.ForceField._BondData(bond[0].index, bond[1].index))
# Record which atoms are bonded to each other atom
bonded_to_atom = []
for i in range(len(data.atoms)):
bonded_to_atom.append(set())
data.atomBonds.append([])
for i in range(len(data.bonds)):
bond = data.bonds[i]
bonded_to_atom[bond.atom1].add(bond.atom2)
bonded_to_atom[bond.atom2].add(bond.atom1)
data.atomBonds[bond.atom1].append(i)
data.atomBonds[bond.atom2].append(i)
# TODO: Better way to lookup nonbonded parameters...?
nonbonded_params = None
for generator in self.getGenerators():
if isinstance(generator, NonbondedGenerator):
nonbonded_params = generator.params.paramsForType
break
for chain in topology.chains():
for res in chain.residues():
for atom in res.atoms():
data.atomType[atom] = atom.id
if nonbonded_params:
params = nonbonded_params[atom.id]
data.atomParameters[atom] = params
# Create the System and add atoms
sys = mm.System()
for atom in topology.atoms():
# Look up the atom type name, returning a helpful error message if it cannot be found.
if atom not in data.atomType:
raise Exception("Could not identify atom type for atom '%s'." % str(atom))
typename = data.atomType[atom]
# Look up the type name in the list of registered atom types, returning a helpful error message if it cannot be found.
if typename not in self._atomTypes:
msg = "Could not find typename '%s' for atom '%s' in list of known atom types.\n" % (typename, str(atom))
msg += "Known atom types are: %s" % str(self._atomTypes.keys())
raise Exception(msg)
# Add the particle to the OpenMM system.
mass = self._atomTypes[typename].mass
sys.addParticle(mass)
# Adjust hydrogen masses if requested.
if hydrogenMass is not None:
if not u.is_quantity(hydrogenMass):
hydrogenMass *= u.dalton
for atom1, atom2 in topology.bonds():
if atom1.element == elem.hydrogen:
(atom1, atom2) = (atom2, atom1)
if atom2.element == elem.hydrogen and atom1.element not in (elem.hydrogen, None):
transfer_mass = hydrogenMass - sys.getParticleMass(atom2.index)
sys.setParticleMass(atom2.index, hydrogenMass)
mass = sys.getParticleMass(atom1.index) - transfer_mass
sys.setParticleMass(atom1.index, mass)
# Set periodic boundary conditions.
box_vectors = topology.getPeriodicBoxVectors()
if box_vectors is not None:
sys.setDefaultPeriodicBoxVectors(box_vectors[0],
box_vectors[1],
box_vectors[2])
elif nonbondedMethod not in [NoCutoff, CutoffNonPeriodic]:
raise ValueError('Requested periodic boundary conditions for a '
'Topology that does not specify periodic box '
'dimensions')
# Make a list of all unique angles
unique_angles = set()
for bond in data.bonds:
for atom in bonded_to_atom[bond.atom1]:
if atom != bond.atom2:
if atom < bond.atom2:
unique_angles.add((atom, bond.atom1, bond.atom2))
else:
unique_angles.add((bond.atom2, bond.atom1, atom))
for atom in bonded_to_atom[bond.atom2]:
if atom != bond.atom1:
if atom > bond.atom1:
unique_angles.add((bond.atom1, bond.atom2, atom))
else:
unique_angles.add((atom, bond.atom2, bond.atom1))
data.angles = sorted(list(unique_angles))
# Make a list of all unique proper torsions
unique_propers = set()
for angle in data.angles:
for atom in bonded_to_atom[angle[0]]:
if atom not in angle:
if atom < angle[2]:
unique_propers.add((atom, angle[0], angle[1], angle[2]))
else:
unique_propers.add((angle[2], angle[1], angle[0], atom))
for atom in bonded_to_atom[angle[2]]:
if atom not in angle:
if atom > angle[0]:
unique_propers.add((angle[0], angle[1], angle[2], atom))
else:
unique_propers.add((atom, angle[2], angle[1], angle[0]))
data.propers = sorted(list(unique_propers))
# Make a list of all unique improper torsions
for atom in range(len(bonded_to_atom)):
bonded_to = bonded_to_atom[atom]
if len(bonded_to) > 2:
for subset in itertools.combinations(bonded_to, 3):
data.impropers.append((atom, subset[0], subset[1], subset[2]))
# Identify bonds that should be implemented with constraints
if constraints == AllBonds or constraints == HAngles:
for bond in data.bonds:
bond.isConstrained = True
elif constraints == HBonds:
for bond in data.bonds:
atom1 = data.atoms[bond.atom1]
atom2 = data.atoms[bond.atom2]
bond.isConstrained = atom1.name.startswith('H') or atom2.name.startswith('H')
if rigidWater:
for bond in data.bonds:
atom1 = data.atoms[bond.atom1]
atom2 = data.atoms[bond.atom2]
if atom1.residue.name == 'HOH' and atom2.residue.name == 'HOH':
bond.isConstrained = True
# Identify angles that should be implemented with constraints
if constraints == HAngles:
for angle in data.angles:
atom1 = data.atoms[angle[0]]
atom2 = data.atoms[angle[1]]
atom3 = data.atoms[angle[2]]
numH = 0
if atom1.name.startswith('H'):
numH += 1
if atom3.name.startswith('H'):
numH += 1
data.isAngleConstrained.append(numH == 2 or (numH == 1 and atom2.name.startswith('O')))
else:
data.isAngleConstrained = len(data.angles)*[False]
if rigidWater:
for i in range(len(data.angles)):
angle = data.angles[i]
atom1 = data.atoms[angle[0]]
atom2 = data.atoms[angle[1]]
atom3 = data.atoms[angle[2]]
if atom1.residue.name == 'HOH' and atom2.residue.name == 'HOH' and atom3.residue.name == 'HOH':
data.isAngleConstrained[i] = True
# Add virtual sites
for atom in data.virtualSites:
(site, atoms, excludeWith) = data.virtualSites[atom]
index = atom.index
data.excludeAtomWith[excludeWith].append(index)
if site.type == 'average2':
sys.setVirtualSite(index, mm.TwoParticleAverageSite(
atoms[0], atoms[1], site.weights[0], site.weights[1]))
elif site.type == 'average3':
sys.setVirtualSite(index, mm.ThreeParticleAverageSite(
atoms[0], atoms[1], atoms[2],
site.weights[0], site.weights[1], site.weights[2]))
elif site.type == 'outOfPlane':
sys.setVirtualSite(index, mm.OutOfPlaneSite(
atoms[0], atoms[1], atoms[2],
site.weights[0], site.weights[1], site.weights[2]))
elif site.type == 'localCoords':
local_coord_site = mm.LocalCoordinatesSite(
atoms[0], atoms[1], atoms[2],
mm.Vec3(site.originWeights[0], site.originWeights[1], site.originWeights[2]),
mm.Vec3(site.xWeights[0], site.xWeights[1], site.xWeights[2]),
mm.Vec3(site.yWeights[0], site.yWeights[1], site.yWeights[2]),
mm.Vec3(site.localPos[0], site.localPos[1], site.localPos[2]))
sys.setVirtualSite(index, local_coord_site)
# Add forces to the System
for force in self._forces:
force.createForce(sys, data, nonbondedMethod, nonbondedCutoff, args)
if removeCMMotion:
sys.addForce(mm.CMMotionRemover())
# Let force generators do postprocessing
for force in self._forces:
if 'postprocessSystem' in dir(force):
force.postprocessSystem(sys, data, args)
# Execute scripts found in the XML files.
for script in self._scripts:
exec(script, locals())
return sys
def _write_references_to_file(self, atom_types, references_file):
atomtype_references = {}
for atype in atom_types:
try:
atomtype_references[atype] = self.atomTypeRefs[atype]
except KeyError:
warnings.warn("Reference not found for atom type '{}'."
"".format(atype))
unique_references = collections.defaultdict(list)
for atomtype, dois in atomtype_references.items():
for doi in dois:
unique_references[doi].append(atomtype)
unique_references = collections.OrderedDict(sorted(unique_references.items()))
with open(references_file, 'w') as f:
for doi, atomtypes in unique_references.items():
url = "http://dx.doi.org/" + doi
headers = {"accept": "application/x-bibtex"}
bibtex_ref = requests.get(url, headers=headers).text
note = (',\n\tnote = {Parameters for atom types: ' +
', '.join(sorted(atomtypes)) + '}')
bibtex_ref = bibtex_ref[:-2] + note + bibtex_ref[-2:]
f.write('{}\n'.format(bibtex_ref))
|
mosdef-hub/foyer | foyer/forcefield.py | _topology_from_parmed | python | def _topology_from_parmed(structure, non_element_types):
topology = app.Topology()
residues = dict()
for pmd_residue in structure.residues:
chain = topology.addChain()
omm_residue = topology.addResidue(pmd_residue.name, chain)
residues[pmd_residue] = omm_residue
atoms = dict() # pmd.Atom: omm.Atom
for pmd_atom in structure.atoms:
name = pmd_atom.name
if pmd_atom.name in non_element_types:
element = non_element_types[pmd_atom.name]
else:
if (isinstance(pmd_atom.atomic_number, int) and
pmd_atom.atomic_number != 0):
element = elem.Element.getByAtomicNumber(pmd_atom.atomic_number)
else:
element = elem.Element.getBySymbol(pmd_atom.name)
omm_atom = topology.addAtom(name, element, residues[pmd_atom.residue])
atoms[pmd_atom] = omm_atom
omm_atom.bond_partners = []
for bond in structure.bonds:
atom1 = atoms[bond.atom1]
atom2 = atoms[bond.atom2]
topology.addBond(atom1, atom2)
atom1.bond_partners.append(atom2)
atom2.bond_partners.append(atom1)
if structure.box_vectors and np.any([x._value for x in structure.box_vectors]):
topology.setPeriodicBoxVectors(structure.box_vectors)
positions = structure.positions
return topology, positions | Convert a ParmEd Structure to an OpenMM Topology. | train | https://github.com/mosdef-hub/foyer/blob/9e39c71208fc01a6cc7b7cbe5a533c56830681d3/foyer/forcefield.py#L108-L143 | null | import collections
import glob
import itertools
import os
from tempfile import mktemp, mkstemp
import xml.etree.ElementTree as ET
try:
from cStringIO import StringIO
except ImportError:
from io import StringIO
from pkg_resources import resource_filename
import requests
import warnings
import re
import numpy as np
import parmed as pmd
import simtk.openmm.app.element as elem
import foyer.element as custom_elem
import simtk.unit as u
from simtk import openmm as mm
from simtk.openmm import app
from simtk.openmm.app.forcefield import (NoCutoff, CutoffNonPeriodic, HBonds,
AllBonds, HAngles, NonbondedGenerator,
_convertParameterToNumber)
from foyer.atomtyper import find_atomtypes
from foyer.exceptions import FoyerError
from foyer import smarts
from foyer.validator import Validator
from foyer.utils.io import import_, has_mbuild
def preprocess_forcefield_files(forcefield_files=None):
if forcefield_files is None:
return None
preprocessed_files = []
for xml_file in forcefield_files:
if not hasattr(xml_file,'read'):
f = open(xml_file)
_,suffix = os.path.split(xml_file)
else:
f = xml_file
suffix=""
# read and preprocess
xml_contents = f.read()
f.close()
xml_contents = re.sub(r"(def\w*=\w*[\"\'])(.*)([\"\'])", lambda m: m.group(1) + re.sub(r"&(?!amp;)", r"&", m.group(2)) + m.group(3),
xml_contents)
try:
'''
Sort topology objects by precedence, defined by the number of
`type` attributes specified, where a `type` attribute indicates
increased specificity as opposed to use of `class`
'''
root = ET.fromstring(xml_contents)
for element in root:
if 'Force' in element.tag:
element[:] = sorted(element, key=lambda child: (
-1 * len([attr_name for attr_name in child.keys()
if 'type' in attr_name])))
xml_contents = ET.tostring(root, method='xml').decode()
except ET.ParseError:
'''
Provide the user with a warning if sorting could not be performed.
This indicates a bad XML file, which will be passed on to the
Validator to yield a more descriptive error message.
'''
warnings.warn('Invalid XML detected. Could not auto-sort topology '
'objects by precedence.')
# write to temp file
_, temp_file_name = mkstemp(suffix=suffix)
with open(temp_file_name, 'w') as temp_f:
temp_f.write(xml_contents)
# append temp file name to list
preprocessed_files.append(temp_file_name)
return preprocessed_files
def generate_topology(non_omm_topology, non_element_types=None,
residues=None):
"""Create an OpenMM Topology from another supported topology structure."""
if non_element_types is None:
non_element_types = set()
if isinstance(non_omm_topology, pmd.Structure):
return _topology_from_parmed(non_omm_topology, non_element_types)
elif has_mbuild:
mb = import_('mbuild')
if (non_omm_topology, mb.Compound):
pmdCompoundStructure = non_omm_topology.to_parmed(residues=residues)
return _topology_from_parmed(pmdCompoundStructure, non_element_types)
else:
raise FoyerError('Unknown topology format: {}\n'
'Supported formats are: '
'"parmed.Structure", '
'"mbuild.Compound", '
'"openmm.app.Topology"'.format(non_omm_topology))
def _topology_from_residue(res):
"""Converts a openmm.app.Topology.Residue to openmm.app.Topology.
Parameters
----------
res : openmm.app.Topology.Residue
An individual residue in an openmm.app.Topology
Returns
-------
topology : openmm.app.Topology
The generated topology
"""
topology = app.Topology()
chain = topology.addChain()
new_res = topology.addResidue(res.name, chain)
atoms = dict() # { omm.Atom in res : omm.Atom in *new* topology }
for res_atom in res.atoms():
topology_atom = topology.addAtom(name=res_atom.name,
element=res_atom.element,
residue=new_res)
atoms[res_atom] = topology_atom
topology_atom.bond_partners = []
for bond in res.bonds():
atom1 = atoms[bond.atom1]
atom2 = atoms[bond.atom2]
topology.addBond(atom1, atom2)
atom1.bond_partners.append(atom2)
atom2.bond_partners.append(atom1)
return topology
def _check_independent_residues(topology):
"""Check to see if residues will constitute independent graphs."""
for res in topology.residues():
atoms_in_residue = set([atom for atom in res.atoms()])
bond_partners_in_residue = [item for sublist in [atom.bond_partners for atom in res.atoms()] for item in sublist]
# Handle the case of a 'residue' with no neighbors
if not bond_partners_in_residue:
continue
if set(atoms_in_residue) != set(bond_partners_in_residue):
return False
return True
def _update_atomtypes(unatomtyped_topology, res_name, prototype):
"""Update atomtypes in residues in a topology using a prototype topology.
Atomtypes are updated when residues in each topology have matching names.
Parameters
----------
unatomtyped_topology : openmm.app.Topology
Topology lacking atomtypes defined by `find_atomtypes`.
prototype : openmm.app.Topology
Prototype topology with atomtypes defined by `find_atomtypes`.
"""
for res in unatomtyped_topology.residues():
if res.name == res_name:
for old_atom, new_atom_id in zip([atom for atom in res.atoms()], [atom.id for atom in prototype.atoms()]):
old_atom.id = new_atom_id
def _error_or_warn(error, msg):
"""Raise an error or warning if topology objects are not fully parameterized.
Parameters
----------
error : bool
If True, raise an error, else raise a warning
msg : str
The message to be provided with the error or warning
"""
if error:
raise Exception(msg)
else:
warnings.warn(msg)
class Forcefield(app.ForceField):
"""Specialization of OpenMM's Forcefield allowing SMARTS based atomtyping.
Parameters
----------
forcefield_files : list of str, optional, default=None
List of forcefield files to load.
name : str, optional, default=None
Name of a forcefield to load that is packaged within foyer.
"""
def __init__(self, forcefield_files=None, name=None, validation=True, debug=False):
self.atomTypeDefinitions = dict()
self.atomTypeOverrides = dict()
self.atomTypeDesc = dict()
self.atomTypeRefs = dict()
self._included_forcefields = dict()
self.non_element_types = dict()
all_files_to_load = []
if forcefield_files is not None:
if isinstance(forcefield_files, (list, tuple, set)):
for file in forcefield_files:
all_files_to_load.append(file)
else:
all_files_to_load.append(forcefield_files)
if name is not None:
try:
file = self.included_forcefields[name]
except KeyError:
raise IOError('Forcefield {} cannot be found'.format(name))
else:
all_files_to_load.append(file)
preprocessed_files = preprocess_forcefield_files(all_files_to_load)
if validation:
for ff_file_name in preprocessed_files:
Validator(ff_file_name, debug)
super(Forcefield, self).__init__(*preprocessed_files)
self.parser = smarts.SMARTS(self.non_element_types)
self._SystemData = self._SystemData()
@property
def included_forcefields(self):
if any(self._included_forcefields):
return self._included_forcefields
ff_dir = resource_filename('foyer', 'forcefields')
ff_filepaths = set(glob.glob(os.path.join(ff_dir, '*.xml')))
for ff_filepath in ff_filepaths:
_, ff_file = os.path.split(ff_filepath)
basename, _ = os.path.splitext(ff_file)
self._included_forcefields[basename] = ff_filepath
return self._included_forcefields
def _create_element(self, element, mass):
if not isinstance(element, elem.Element):
try:
element = elem.get_by_symbol(element)
except KeyError:
# Enables support for non-atomistic "element types"
if element not in self.non_element_types:
warnings.warn('Non-atomistic element type detected. '
'Creating custom element for {}'.format(element))
element = custom_elem.Element(number=0,
mass=mass,
name=element,
symbol=element)
else:
return element, False
return element, True
def registerAtomType(self, parameters):
"""Register a new atom type. """
name = parameters['name']
if name in self._atomTypes:
raise ValueError('Found multiple definitions for atom type: ' + name)
atom_class = parameters['class']
mass = _convertParameterToNumber(parameters['mass'])
element = None
if 'element' in parameters:
element, custom = self._create_element(parameters['element'], mass)
if custom:
self.non_element_types[element.symbol] = element
self._atomTypes[name] = self.__class__._AtomType(name, atom_class, mass, element)
if atom_class in self._atomClasses:
type_set = self._atomClasses[atom_class]
else:
type_set = set()
self._atomClasses[atom_class] = type_set
type_set.add(name)
self._atomClasses[''].add(name)
name = parameters['name']
if 'def' in parameters:
self.atomTypeDefinitions[name] = parameters['def']
if 'overrides' in parameters:
overrides = set(atype.strip() for atype
in parameters['overrides'].split(","))
if overrides:
self.atomTypeOverrides[name] = overrides
if 'des' in parameters:
self.atomTypeDesc[name] = parameters['desc']
if 'doi' in parameters:
dois = set(doi.strip() for doi in parameters['doi'].split(','))
self.atomTypeRefs[name] = dois
def apply(self, topology, references_file=None, use_residue_map=True,
assert_bond_params=True, assert_angle_params=True,
assert_dihedral_params=True, assert_improper_params=False,
*args, **kwargs):
"""Apply the force field to a molecular structure
Parameters
----------
topology : openmm.app.Topology or parmed.Structure or mbuild.Compound
Molecular structure to apply the force field to
references_file : str, optional, default=None
Name of file where force field references will be written (in Bibtex
format)
use_residue_map : boolean, optional, default=True
Store atomtyped topologies of residues to a dictionary that maps
them to residue names. Each topology, including atomtypes, will be
copied to other residues with the same name. This avoids repeatedly
calling the subgraph isomorphism on idential residues and should
result in better performance for systems with many identical
residues, i.e. a box of water. Note that for this to be applied to
independent molecules, they must each be saved as different
residues in the topology.
assert_bond_params : bool, optional, default=True
If True, Foyer will exit if parameters are not found for all system
bonds.
assert_angle_params : bool, optional, default=True
If True, Foyer will exit if parameters are not found for all system
angles.
assert_dihedral_params : bool, optional, default=True
If True, Foyer will exit if parameters are not found for all system
proper dihedrals.
assert_improper_params : bool, optional, default=False
If True, Foyer will exit if parameters are not found for all system
improper dihedrals.
"""
if self.atomTypeDefinitions == {}:
raise FoyerError('Attempting to atom-type using a force field '
'with no atom type defitions.')
if not isinstance(topology, app.Topology):
residues = kwargs.get('residues')
topology, positions = generate_topology(topology,
self.non_element_types, residues=residues)
else:
positions = np.empty(shape=(topology.getNumAtoms(), 3))
positions[:] = np.nan
box_vectors = topology.getPeriodicBoxVectors()
topology = self.run_atomtyping(topology, use_residue_map=use_residue_map)
system = self.createSystem(topology, *args, **kwargs)
structure = pmd.openmm.load_topology(topology=topology, system=system)
'''
Check that all topology objects (angles, dihedrals, and impropers)
have parameters assigned. OpenMM will generate an error if bond parameters
are not assigned.
'''
data = self._SystemData
if data.bonds:
missing = [b for b in structure.bonds
if b.type is None]
if missing:
nmissing = len(structure.bonds) - len(missing)
msg = ("Parameters have not been assigned to all bonds. "
"Total system bonds: {}, Parametrized bonds: {}"
"".format(len(structure.bonds), nmissing))
_error_or_warn(assert_bond_params, msg)
if data.angles and (len(data.angles) != len(structure.angles)):
msg = ("Parameters have not been assigned to all angles. Total "
"system angles: {}, Parameterized angles: {}"
"".format(len(data.angles), len(structure.angles)))
_error_or_warn(assert_angle_params, msg)
proper_dihedrals = [dihedral for dihedral in structure.dihedrals
if not dihedral.improper]
if data.propers and len(data.propers) != \
len(proper_dihedrals) + len(structure.rb_torsions):
msg = ("Parameters have not been assigned to all proper dihedrals. "
"Total system dihedrals: {}, Parameterized dihedrals: {}. "
"Note that if your system contains torsions of Ryckaert-"
"Bellemans functional form, all of these torsions are "
"processed as propers.".format(len(data.propers),
len(proper_dihedrals) + len(structure.rb_torsions)))
_error_or_warn(assert_dihedral_params, msg)
improper_dihedrals = [dihedral for dihedral in structure.dihedrals
if dihedral.improper]
if data.impropers and len(data.impropers) != \
len(improper_dihedrals) + len(structure.impropers):
msg = ("Parameters have not been assigned to all impropers. Total "
"system impropers: {}, Parameterized impropers: {}. "
"Note that if your system contains torsions of Ryckaert-"
"Bellemans functional form, all of these torsions are "
"processed as propers".format(len(data.impropers),
len(improper_dihedrals) + len(structure.impropers)))
_error_or_warn(assert_improper_params, msg)
structure.bonds.sort(key=lambda x: x.atom1.idx)
structure.positions = positions
if box_vectors is not None:
structure.box_vectors = box_vectors
if references_file:
atom_types = set(atom.type for atom in structure.atoms)
self._write_references_to_file(atom_types, references_file)
return structure
def run_atomtyping(self, topology, use_residue_map=True):
"""Atomtype the topology
Parameters
----------
topology : openmm.app.Topology
Molecular structure to find atom types of
use_residue_map : boolean, optional, default=True
Store atomtyped topologies of residues to a dictionary that maps
them to residue names. Each topology, including atomtypes, will be
copied to other residues with the same name. This avoids repeatedly
calling the subgraph isomorphism on idential residues and should
result in better performance for systems with many identical
residues, i.e. a box of water. Note that for this to be applied to
independent molecules, they must each be saved as different
residues in the topology.
"""
if use_residue_map:
independent_residues = _check_independent_residues(topology)
if independent_residues:
residue_map = dict()
for res in topology.residues():
if res.name not in residue_map.keys():
residue = _topology_from_residue(res)
find_atomtypes(residue, forcefield=self)
residue_map[res.name] = residue
for key, val in residue_map.items():
_update_atomtypes(topology, key, val)
else:
find_atomtypes(topology, forcefield=self)
else:
find_atomtypes(topology, forcefield=self)
if not all([a.id for a in topology.atoms()][0]):
raise ValueError('Not all atoms in topology have atom types')
return topology
def createSystem(self, topology, nonbondedMethod=NoCutoff,
nonbondedCutoff=1.0 * u.nanometer, constraints=None,
rigidWater=True, removeCMMotion=True, hydrogenMass=None,
**args):
"""Construct an OpenMM System representing a Topology with this force field.
Parameters
----------
topology : Topology
The Topology for which to create a System
nonbondedMethod : object=NoCutoff
The method to use for nonbonded interactions. Allowed values are
NoCutoff, CutoffNonPeriodic, CutoffPeriodic, Ewald, or PME.
nonbondedCutoff : distance=1*nanometer
The cutoff distance to use for nonbonded interactions
constraints : object=None
Specifies which bonds and angles should be implemented with constraints.
Allowed values are None, HBonds, AllBonds, or HAngles.
rigidWater : boolean=True
If true, water molecules will be fully rigid regardless of the value
passed for the constraints argument
removeCMMotion : boolean=True
If true, a CMMotionRemover will be added to the System
hydrogenMass : mass=None
The mass to use for hydrogen atoms bound to heavy atoms. Any mass
added to a hydrogen is subtracted from the heavy atom to keep
their total mass the same.
args
Arbitrary additional keyword arguments may also be specified.
This allows extra parameters to be specified that are specific to
particular force fields.
Returns
-------
system
the newly created System
"""
# Overwrite previous _SystemData object
self._SystemData = app.ForceField._SystemData()
data = self._SystemData
data.atoms = list(topology.atoms())
for atom in data.atoms:
data.excludeAtomWith.append([])
# Make a list of all bonds
for bond in topology.bonds():
data.bonds.append(app.ForceField._BondData(bond[0].index, bond[1].index))
# Record which atoms are bonded to each other atom
bonded_to_atom = []
for i in range(len(data.atoms)):
bonded_to_atom.append(set())
data.atomBonds.append([])
for i in range(len(data.bonds)):
bond = data.bonds[i]
bonded_to_atom[bond.atom1].add(bond.atom2)
bonded_to_atom[bond.atom2].add(bond.atom1)
data.atomBonds[bond.atom1].append(i)
data.atomBonds[bond.atom2].append(i)
# TODO: Better way to lookup nonbonded parameters...?
nonbonded_params = None
for generator in self.getGenerators():
if isinstance(generator, NonbondedGenerator):
nonbonded_params = generator.params.paramsForType
break
for chain in topology.chains():
for res in chain.residues():
for atom in res.atoms():
data.atomType[atom] = atom.id
if nonbonded_params:
params = nonbonded_params[atom.id]
data.atomParameters[atom] = params
# Create the System and add atoms
sys = mm.System()
for atom in topology.atoms():
# Look up the atom type name, returning a helpful error message if it cannot be found.
if atom not in data.atomType:
raise Exception("Could not identify atom type for atom '%s'." % str(atom))
typename = data.atomType[atom]
# Look up the type name in the list of registered atom types, returning a helpful error message if it cannot be found.
if typename not in self._atomTypes:
msg = "Could not find typename '%s' for atom '%s' in list of known atom types.\n" % (typename, str(atom))
msg += "Known atom types are: %s" % str(self._atomTypes.keys())
raise Exception(msg)
# Add the particle to the OpenMM system.
mass = self._atomTypes[typename].mass
sys.addParticle(mass)
# Adjust hydrogen masses if requested.
if hydrogenMass is not None:
if not u.is_quantity(hydrogenMass):
hydrogenMass *= u.dalton
for atom1, atom2 in topology.bonds():
if atom1.element == elem.hydrogen:
(atom1, atom2) = (atom2, atom1)
if atom2.element == elem.hydrogen and atom1.element not in (elem.hydrogen, None):
transfer_mass = hydrogenMass - sys.getParticleMass(atom2.index)
sys.setParticleMass(atom2.index, hydrogenMass)
mass = sys.getParticleMass(atom1.index) - transfer_mass
sys.setParticleMass(atom1.index, mass)
# Set periodic boundary conditions.
box_vectors = topology.getPeriodicBoxVectors()
if box_vectors is not None:
sys.setDefaultPeriodicBoxVectors(box_vectors[0],
box_vectors[1],
box_vectors[2])
elif nonbondedMethod not in [NoCutoff, CutoffNonPeriodic]:
raise ValueError('Requested periodic boundary conditions for a '
'Topology that does not specify periodic box '
'dimensions')
# Make a list of all unique angles
unique_angles = set()
for bond in data.bonds:
for atom in bonded_to_atom[bond.atom1]:
if atom != bond.atom2:
if atom < bond.atom2:
unique_angles.add((atom, bond.atom1, bond.atom2))
else:
unique_angles.add((bond.atom2, bond.atom1, atom))
for atom in bonded_to_atom[bond.atom2]:
if atom != bond.atom1:
if atom > bond.atom1:
unique_angles.add((bond.atom1, bond.atom2, atom))
else:
unique_angles.add((atom, bond.atom2, bond.atom1))
data.angles = sorted(list(unique_angles))
# Make a list of all unique proper torsions
unique_propers = set()
for angle in data.angles:
for atom in bonded_to_atom[angle[0]]:
if atom not in angle:
if atom < angle[2]:
unique_propers.add((atom, angle[0], angle[1], angle[2]))
else:
unique_propers.add((angle[2], angle[1], angle[0], atom))
for atom in bonded_to_atom[angle[2]]:
if atom not in angle:
if atom > angle[0]:
unique_propers.add((angle[0], angle[1], angle[2], atom))
else:
unique_propers.add((atom, angle[2], angle[1], angle[0]))
data.propers = sorted(list(unique_propers))
# Make a list of all unique improper torsions
for atom in range(len(bonded_to_atom)):
bonded_to = bonded_to_atom[atom]
if len(bonded_to) > 2:
for subset in itertools.combinations(bonded_to, 3):
data.impropers.append((atom, subset[0], subset[1], subset[2]))
# Identify bonds that should be implemented with constraints
if constraints == AllBonds or constraints == HAngles:
for bond in data.bonds:
bond.isConstrained = True
elif constraints == HBonds:
for bond in data.bonds:
atom1 = data.atoms[bond.atom1]
atom2 = data.atoms[bond.atom2]
bond.isConstrained = atom1.name.startswith('H') or atom2.name.startswith('H')
if rigidWater:
for bond in data.bonds:
atom1 = data.atoms[bond.atom1]
atom2 = data.atoms[bond.atom2]
if atom1.residue.name == 'HOH' and atom2.residue.name == 'HOH':
bond.isConstrained = True
# Identify angles that should be implemented with constraints
if constraints == HAngles:
for angle in data.angles:
atom1 = data.atoms[angle[0]]
atom2 = data.atoms[angle[1]]
atom3 = data.atoms[angle[2]]
numH = 0
if atom1.name.startswith('H'):
numH += 1
if atom3.name.startswith('H'):
numH += 1
data.isAngleConstrained.append(numH == 2 or (numH == 1 and atom2.name.startswith('O')))
else:
data.isAngleConstrained = len(data.angles)*[False]
if rigidWater:
for i in range(len(data.angles)):
angle = data.angles[i]
atom1 = data.atoms[angle[0]]
atom2 = data.atoms[angle[1]]
atom3 = data.atoms[angle[2]]
if atom1.residue.name == 'HOH' and atom2.residue.name == 'HOH' and atom3.residue.name == 'HOH':
data.isAngleConstrained[i] = True
# Add virtual sites
for atom in data.virtualSites:
(site, atoms, excludeWith) = data.virtualSites[atom]
index = atom.index
data.excludeAtomWith[excludeWith].append(index)
if site.type == 'average2':
sys.setVirtualSite(index, mm.TwoParticleAverageSite(
atoms[0], atoms[1], site.weights[0], site.weights[1]))
elif site.type == 'average3':
sys.setVirtualSite(index, mm.ThreeParticleAverageSite(
atoms[0], atoms[1], atoms[2],
site.weights[0], site.weights[1], site.weights[2]))
elif site.type == 'outOfPlane':
sys.setVirtualSite(index, mm.OutOfPlaneSite(
atoms[0], atoms[1], atoms[2],
site.weights[0], site.weights[1], site.weights[2]))
elif site.type == 'localCoords':
local_coord_site = mm.LocalCoordinatesSite(
atoms[0], atoms[1], atoms[2],
mm.Vec3(site.originWeights[0], site.originWeights[1], site.originWeights[2]),
mm.Vec3(site.xWeights[0], site.xWeights[1], site.xWeights[2]),
mm.Vec3(site.yWeights[0], site.yWeights[1], site.yWeights[2]),
mm.Vec3(site.localPos[0], site.localPos[1], site.localPos[2]))
sys.setVirtualSite(index, local_coord_site)
# Add forces to the System
for force in self._forces:
force.createForce(sys, data, nonbondedMethod, nonbondedCutoff, args)
if removeCMMotion:
sys.addForce(mm.CMMotionRemover())
# Let force generators do postprocessing
for force in self._forces:
if 'postprocessSystem' in dir(force):
force.postprocessSystem(sys, data, args)
# Execute scripts found in the XML files.
for script in self._scripts:
exec(script, locals())
return sys
def _write_references_to_file(self, atom_types, references_file):
atomtype_references = {}
for atype in atom_types:
try:
atomtype_references[atype] = self.atomTypeRefs[atype]
except KeyError:
warnings.warn("Reference not found for atom type '{}'."
"".format(atype))
unique_references = collections.defaultdict(list)
for atomtype, dois in atomtype_references.items():
for doi in dois:
unique_references[doi].append(atomtype)
unique_references = collections.OrderedDict(sorted(unique_references.items()))
with open(references_file, 'w') as f:
for doi, atomtypes in unique_references.items():
url = "http://dx.doi.org/" + doi
headers = {"accept": "application/x-bibtex"}
bibtex_ref = requests.get(url, headers=headers).text
note = (',\n\tnote = {Parameters for atom types: ' +
', '.join(sorted(atomtypes)) + '}')
bibtex_ref = bibtex_ref[:-2] + note + bibtex_ref[-2:]
f.write('{}\n'.format(bibtex_ref))
|
mosdef-hub/foyer | foyer/forcefield.py | _topology_from_residue | python | def _topology_from_residue(res):
topology = app.Topology()
chain = topology.addChain()
new_res = topology.addResidue(res.name, chain)
atoms = dict() # { omm.Atom in res : omm.Atom in *new* topology }
for res_atom in res.atoms():
topology_atom = topology.addAtom(name=res_atom.name,
element=res_atom.element,
residue=new_res)
atoms[res_atom] = topology_atom
topology_atom.bond_partners = []
for bond in res.bonds():
atom1 = atoms[bond.atom1]
atom2 = atoms[bond.atom2]
topology.addBond(atom1, atom2)
atom1.bond_partners.append(atom2)
atom2.bond_partners.append(atom1)
return topology | Converts a openmm.app.Topology.Residue to openmm.app.Topology.
Parameters
----------
res : openmm.app.Topology.Residue
An individual residue in an openmm.app.Topology
Returns
-------
topology : openmm.app.Topology
The generated topology | train | https://github.com/mosdef-hub/foyer/blob/9e39c71208fc01a6cc7b7cbe5a533c56830681d3/foyer/forcefield.py#L146-L180 | null | import collections
import glob
import itertools
import os
from tempfile import mktemp, mkstemp
import xml.etree.ElementTree as ET
try:
from cStringIO import StringIO
except ImportError:
from io import StringIO
from pkg_resources import resource_filename
import requests
import warnings
import re
import numpy as np
import parmed as pmd
import simtk.openmm.app.element as elem
import foyer.element as custom_elem
import simtk.unit as u
from simtk import openmm as mm
from simtk.openmm import app
from simtk.openmm.app.forcefield import (NoCutoff, CutoffNonPeriodic, HBonds,
AllBonds, HAngles, NonbondedGenerator,
_convertParameterToNumber)
from foyer.atomtyper import find_atomtypes
from foyer.exceptions import FoyerError
from foyer import smarts
from foyer.validator import Validator
from foyer.utils.io import import_, has_mbuild
def preprocess_forcefield_files(forcefield_files=None):
if forcefield_files is None:
return None
preprocessed_files = []
for xml_file in forcefield_files:
if not hasattr(xml_file,'read'):
f = open(xml_file)
_,suffix = os.path.split(xml_file)
else:
f = xml_file
suffix=""
# read and preprocess
xml_contents = f.read()
f.close()
xml_contents = re.sub(r"(def\w*=\w*[\"\'])(.*)([\"\'])", lambda m: m.group(1) + re.sub(r"&(?!amp;)", r"&", m.group(2)) + m.group(3),
xml_contents)
try:
'''
Sort topology objects by precedence, defined by the number of
`type` attributes specified, where a `type` attribute indicates
increased specificity as opposed to use of `class`
'''
root = ET.fromstring(xml_contents)
for element in root:
if 'Force' in element.tag:
element[:] = sorted(element, key=lambda child: (
-1 * len([attr_name for attr_name in child.keys()
if 'type' in attr_name])))
xml_contents = ET.tostring(root, method='xml').decode()
except ET.ParseError:
'''
Provide the user with a warning if sorting could not be performed.
This indicates a bad XML file, which will be passed on to the
Validator to yield a more descriptive error message.
'''
warnings.warn('Invalid XML detected. Could not auto-sort topology '
'objects by precedence.')
# write to temp file
_, temp_file_name = mkstemp(suffix=suffix)
with open(temp_file_name, 'w') as temp_f:
temp_f.write(xml_contents)
# append temp file name to list
preprocessed_files.append(temp_file_name)
return preprocessed_files
def generate_topology(non_omm_topology, non_element_types=None,
residues=None):
"""Create an OpenMM Topology from another supported topology structure."""
if non_element_types is None:
non_element_types = set()
if isinstance(non_omm_topology, pmd.Structure):
return _topology_from_parmed(non_omm_topology, non_element_types)
elif has_mbuild:
mb = import_('mbuild')
if (non_omm_topology, mb.Compound):
pmdCompoundStructure = non_omm_topology.to_parmed(residues=residues)
return _topology_from_parmed(pmdCompoundStructure, non_element_types)
else:
raise FoyerError('Unknown topology format: {}\n'
'Supported formats are: '
'"parmed.Structure", '
'"mbuild.Compound", '
'"openmm.app.Topology"'.format(non_omm_topology))
def _topology_from_parmed(structure, non_element_types):
"""Convert a ParmEd Structure to an OpenMM Topology."""
topology = app.Topology()
residues = dict()
for pmd_residue in structure.residues:
chain = topology.addChain()
omm_residue = topology.addResidue(pmd_residue.name, chain)
residues[pmd_residue] = omm_residue
atoms = dict() # pmd.Atom: omm.Atom
for pmd_atom in structure.atoms:
name = pmd_atom.name
if pmd_atom.name in non_element_types:
element = non_element_types[pmd_atom.name]
else:
if (isinstance(pmd_atom.atomic_number, int) and
pmd_atom.atomic_number != 0):
element = elem.Element.getByAtomicNumber(pmd_atom.atomic_number)
else:
element = elem.Element.getBySymbol(pmd_atom.name)
omm_atom = topology.addAtom(name, element, residues[pmd_atom.residue])
atoms[pmd_atom] = omm_atom
omm_atom.bond_partners = []
for bond in structure.bonds:
atom1 = atoms[bond.atom1]
atom2 = atoms[bond.atom2]
topology.addBond(atom1, atom2)
atom1.bond_partners.append(atom2)
atom2.bond_partners.append(atom1)
if structure.box_vectors and np.any([x._value for x in structure.box_vectors]):
topology.setPeriodicBoxVectors(structure.box_vectors)
positions = structure.positions
return topology, positions
def _check_independent_residues(topology):
"""Check to see if residues will constitute independent graphs."""
for res in topology.residues():
atoms_in_residue = set([atom for atom in res.atoms()])
bond_partners_in_residue = [item for sublist in [atom.bond_partners for atom in res.atoms()] for item in sublist]
# Handle the case of a 'residue' with no neighbors
if not bond_partners_in_residue:
continue
if set(atoms_in_residue) != set(bond_partners_in_residue):
return False
return True
def _update_atomtypes(unatomtyped_topology, res_name, prototype):
"""Update atomtypes in residues in a topology using a prototype topology.
Atomtypes are updated when residues in each topology have matching names.
Parameters
----------
unatomtyped_topology : openmm.app.Topology
Topology lacking atomtypes defined by `find_atomtypes`.
prototype : openmm.app.Topology
Prototype topology with atomtypes defined by `find_atomtypes`.
"""
for res in unatomtyped_topology.residues():
if res.name == res_name:
for old_atom, new_atom_id in zip([atom for atom in res.atoms()], [atom.id for atom in prototype.atoms()]):
old_atom.id = new_atom_id
def _error_or_warn(error, msg):
"""Raise an error or warning if topology objects are not fully parameterized.
Parameters
----------
error : bool
If True, raise an error, else raise a warning
msg : str
The message to be provided with the error or warning
"""
if error:
raise Exception(msg)
else:
warnings.warn(msg)
class Forcefield(app.ForceField):
"""Specialization of OpenMM's Forcefield allowing SMARTS based atomtyping.
Parameters
----------
forcefield_files : list of str, optional, default=None
List of forcefield files to load.
name : str, optional, default=None
Name of a forcefield to load that is packaged within foyer.
"""
def __init__(self, forcefield_files=None, name=None, validation=True, debug=False):
self.atomTypeDefinitions = dict()
self.atomTypeOverrides = dict()
self.atomTypeDesc = dict()
self.atomTypeRefs = dict()
self._included_forcefields = dict()
self.non_element_types = dict()
all_files_to_load = []
if forcefield_files is not None:
if isinstance(forcefield_files, (list, tuple, set)):
for file in forcefield_files:
all_files_to_load.append(file)
else:
all_files_to_load.append(forcefield_files)
if name is not None:
try:
file = self.included_forcefields[name]
except KeyError:
raise IOError('Forcefield {} cannot be found'.format(name))
else:
all_files_to_load.append(file)
preprocessed_files = preprocess_forcefield_files(all_files_to_load)
if validation:
for ff_file_name in preprocessed_files:
Validator(ff_file_name, debug)
super(Forcefield, self).__init__(*preprocessed_files)
self.parser = smarts.SMARTS(self.non_element_types)
self._SystemData = self._SystemData()
@property
def included_forcefields(self):
if any(self._included_forcefields):
return self._included_forcefields
ff_dir = resource_filename('foyer', 'forcefields')
ff_filepaths = set(glob.glob(os.path.join(ff_dir, '*.xml')))
for ff_filepath in ff_filepaths:
_, ff_file = os.path.split(ff_filepath)
basename, _ = os.path.splitext(ff_file)
self._included_forcefields[basename] = ff_filepath
return self._included_forcefields
def _create_element(self, element, mass):
if not isinstance(element, elem.Element):
try:
element = elem.get_by_symbol(element)
except KeyError:
# Enables support for non-atomistic "element types"
if element not in self.non_element_types:
warnings.warn('Non-atomistic element type detected. '
'Creating custom element for {}'.format(element))
element = custom_elem.Element(number=0,
mass=mass,
name=element,
symbol=element)
else:
return element, False
return element, True
def registerAtomType(self, parameters):
"""Register a new atom type. """
name = parameters['name']
if name in self._atomTypes:
raise ValueError('Found multiple definitions for atom type: ' + name)
atom_class = parameters['class']
mass = _convertParameterToNumber(parameters['mass'])
element = None
if 'element' in parameters:
element, custom = self._create_element(parameters['element'], mass)
if custom:
self.non_element_types[element.symbol] = element
self._atomTypes[name] = self.__class__._AtomType(name, atom_class, mass, element)
if atom_class in self._atomClasses:
type_set = self._atomClasses[atom_class]
else:
type_set = set()
self._atomClasses[atom_class] = type_set
type_set.add(name)
self._atomClasses[''].add(name)
name = parameters['name']
if 'def' in parameters:
self.atomTypeDefinitions[name] = parameters['def']
if 'overrides' in parameters:
overrides = set(atype.strip() for atype
in parameters['overrides'].split(","))
if overrides:
self.atomTypeOverrides[name] = overrides
if 'des' in parameters:
self.atomTypeDesc[name] = parameters['desc']
if 'doi' in parameters:
dois = set(doi.strip() for doi in parameters['doi'].split(','))
self.atomTypeRefs[name] = dois
def apply(self, topology, references_file=None, use_residue_map=True,
assert_bond_params=True, assert_angle_params=True,
assert_dihedral_params=True, assert_improper_params=False,
*args, **kwargs):
"""Apply the force field to a molecular structure
Parameters
----------
topology : openmm.app.Topology or parmed.Structure or mbuild.Compound
Molecular structure to apply the force field to
references_file : str, optional, default=None
Name of file where force field references will be written (in Bibtex
format)
use_residue_map : boolean, optional, default=True
Store atomtyped topologies of residues to a dictionary that maps
them to residue names. Each topology, including atomtypes, will be
copied to other residues with the same name. This avoids repeatedly
calling the subgraph isomorphism on idential residues and should
result in better performance for systems with many identical
residues, i.e. a box of water. Note that for this to be applied to
independent molecules, they must each be saved as different
residues in the topology.
assert_bond_params : bool, optional, default=True
If True, Foyer will exit if parameters are not found for all system
bonds.
assert_angle_params : bool, optional, default=True
If True, Foyer will exit if parameters are not found for all system
angles.
assert_dihedral_params : bool, optional, default=True
If True, Foyer will exit if parameters are not found for all system
proper dihedrals.
assert_improper_params : bool, optional, default=False
If True, Foyer will exit if parameters are not found for all system
improper dihedrals.
"""
if self.atomTypeDefinitions == {}:
raise FoyerError('Attempting to atom-type using a force field '
'with no atom type defitions.')
if not isinstance(topology, app.Topology):
residues = kwargs.get('residues')
topology, positions = generate_topology(topology,
self.non_element_types, residues=residues)
else:
positions = np.empty(shape=(topology.getNumAtoms(), 3))
positions[:] = np.nan
box_vectors = topology.getPeriodicBoxVectors()
topology = self.run_atomtyping(topology, use_residue_map=use_residue_map)
system = self.createSystem(topology, *args, **kwargs)
structure = pmd.openmm.load_topology(topology=topology, system=system)
'''
Check that all topology objects (angles, dihedrals, and impropers)
have parameters assigned. OpenMM will generate an error if bond parameters
are not assigned.
'''
data = self._SystemData
if data.bonds:
missing = [b for b in structure.bonds
if b.type is None]
if missing:
nmissing = len(structure.bonds) - len(missing)
msg = ("Parameters have not been assigned to all bonds. "
"Total system bonds: {}, Parametrized bonds: {}"
"".format(len(structure.bonds), nmissing))
_error_or_warn(assert_bond_params, msg)
if data.angles and (len(data.angles) != len(structure.angles)):
msg = ("Parameters have not been assigned to all angles. Total "
"system angles: {}, Parameterized angles: {}"
"".format(len(data.angles), len(structure.angles)))
_error_or_warn(assert_angle_params, msg)
proper_dihedrals = [dihedral for dihedral in structure.dihedrals
if not dihedral.improper]
if data.propers and len(data.propers) != \
len(proper_dihedrals) + len(structure.rb_torsions):
msg = ("Parameters have not been assigned to all proper dihedrals. "
"Total system dihedrals: {}, Parameterized dihedrals: {}. "
"Note that if your system contains torsions of Ryckaert-"
"Bellemans functional form, all of these torsions are "
"processed as propers.".format(len(data.propers),
len(proper_dihedrals) + len(structure.rb_torsions)))
_error_or_warn(assert_dihedral_params, msg)
improper_dihedrals = [dihedral for dihedral in structure.dihedrals
if dihedral.improper]
if data.impropers and len(data.impropers) != \
len(improper_dihedrals) + len(structure.impropers):
msg = ("Parameters have not been assigned to all impropers. Total "
"system impropers: {}, Parameterized impropers: {}. "
"Note that if your system contains torsions of Ryckaert-"
"Bellemans functional form, all of these torsions are "
"processed as propers".format(len(data.impropers),
len(improper_dihedrals) + len(structure.impropers)))
_error_or_warn(assert_improper_params, msg)
structure.bonds.sort(key=lambda x: x.atom1.idx)
structure.positions = positions
if box_vectors is not None:
structure.box_vectors = box_vectors
if references_file:
atom_types = set(atom.type for atom in structure.atoms)
self._write_references_to_file(atom_types, references_file)
return structure
def run_atomtyping(self, topology, use_residue_map=True):
"""Atomtype the topology
Parameters
----------
topology : openmm.app.Topology
Molecular structure to find atom types of
use_residue_map : boolean, optional, default=True
Store atomtyped topologies of residues to a dictionary that maps
them to residue names. Each topology, including atomtypes, will be
copied to other residues with the same name. This avoids repeatedly
calling the subgraph isomorphism on idential residues and should
result in better performance for systems with many identical
residues, i.e. a box of water. Note that for this to be applied to
independent molecules, they must each be saved as different
residues in the topology.
"""
if use_residue_map:
independent_residues = _check_independent_residues(topology)
if independent_residues:
residue_map = dict()
for res in topology.residues():
if res.name not in residue_map.keys():
residue = _topology_from_residue(res)
find_atomtypes(residue, forcefield=self)
residue_map[res.name] = residue
for key, val in residue_map.items():
_update_atomtypes(topology, key, val)
else:
find_atomtypes(topology, forcefield=self)
else:
find_atomtypes(topology, forcefield=self)
if not all([a.id for a in topology.atoms()][0]):
raise ValueError('Not all atoms in topology have atom types')
return topology
def createSystem(self, topology, nonbondedMethod=NoCutoff,
nonbondedCutoff=1.0 * u.nanometer, constraints=None,
rigidWater=True, removeCMMotion=True, hydrogenMass=None,
**args):
"""Construct an OpenMM System representing a Topology with this force field.
Parameters
----------
topology : Topology
The Topology for which to create a System
nonbondedMethod : object=NoCutoff
The method to use for nonbonded interactions. Allowed values are
NoCutoff, CutoffNonPeriodic, CutoffPeriodic, Ewald, or PME.
nonbondedCutoff : distance=1*nanometer
The cutoff distance to use for nonbonded interactions
constraints : object=None
Specifies which bonds and angles should be implemented with constraints.
Allowed values are None, HBonds, AllBonds, or HAngles.
rigidWater : boolean=True
If true, water molecules will be fully rigid regardless of the value
passed for the constraints argument
removeCMMotion : boolean=True
If true, a CMMotionRemover will be added to the System
hydrogenMass : mass=None
The mass to use for hydrogen atoms bound to heavy atoms. Any mass
added to a hydrogen is subtracted from the heavy atom to keep
their total mass the same.
args
Arbitrary additional keyword arguments may also be specified.
This allows extra parameters to be specified that are specific to
particular force fields.
Returns
-------
system
the newly created System
"""
# Overwrite previous _SystemData object
self._SystemData = app.ForceField._SystemData()
data = self._SystemData
data.atoms = list(topology.atoms())
for atom in data.atoms:
data.excludeAtomWith.append([])
# Make a list of all bonds
for bond in topology.bonds():
data.bonds.append(app.ForceField._BondData(bond[0].index, bond[1].index))
# Record which atoms are bonded to each other atom
bonded_to_atom = []
for i in range(len(data.atoms)):
bonded_to_atom.append(set())
data.atomBonds.append([])
for i in range(len(data.bonds)):
bond = data.bonds[i]
bonded_to_atom[bond.atom1].add(bond.atom2)
bonded_to_atom[bond.atom2].add(bond.atom1)
data.atomBonds[bond.atom1].append(i)
data.atomBonds[bond.atom2].append(i)
# TODO: Better way to lookup nonbonded parameters...?
nonbonded_params = None
for generator in self.getGenerators():
if isinstance(generator, NonbondedGenerator):
nonbonded_params = generator.params.paramsForType
break
for chain in topology.chains():
for res in chain.residues():
for atom in res.atoms():
data.atomType[atom] = atom.id
if nonbonded_params:
params = nonbonded_params[atom.id]
data.atomParameters[atom] = params
# Create the System and add atoms
sys = mm.System()
for atom in topology.atoms():
# Look up the atom type name, returning a helpful error message if it cannot be found.
if atom not in data.atomType:
raise Exception("Could not identify atom type for atom '%s'." % str(atom))
typename = data.atomType[atom]
# Look up the type name in the list of registered atom types, returning a helpful error message if it cannot be found.
if typename not in self._atomTypes:
msg = "Could not find typename '%s' for atom '%s' in list of known atom types.\n" % (typename, str(atom))
msg += "Known atom types are: %s" % str(self._atomTypes.keys())
raise Exception(msg)
# Add the particle to the OpenMM system.
mass = self._atomTypes[typename].mass
sys.addParticle(mass)
# Adjust hydrogen masses if requested.
if hydrogenMass is not None:
if not u.is_quantity(hydrogenMass):
hydrogenMass *= u.dalton
for atom1, atom2 in topology.bonds():
if atom1.element == elem.hydrogen:
(atom1, atom2) = (atom2, atom1)
if atom2.element == elem.hydrogen and atom1.element not in (elem.hydrogen, None):
transfer_mass = hydrogenMass - sys.getParticleMass(atom2.index)
sys.setParticleMass(atom2.index, hydrogenMass)
mass = sys.getParticleMass(atom1.index) - transfer_mass
sys.setParticleMass(atom1.index, mass)
# Set periodic boundary conditions.
box_vectors = topology.getPeriodicBoxVectors()
if box_vectors is not None:
sys.setDefaultPeriodicBoxVectors(box_vectors[0],
box_vectors[1],
box_vectors[2])
elif nonbondedMethod not in [NoCutoff, CutoffNonPeriodic]:
raise ValueError('Requested periodic boundary conditions for a '
'Topology that does not specify periodic box '
'dimensions')
# Make a list of all unique angles
unique_angles = set()
for bond in data.bonds:
for atom in bonded_to_atom[bond.atom1]:
if atom != bond.atom2:
if atom < bond.atom2:
unique_angles.add((atom, bond.atom1, bond.atom2))
else:
unique_angles.add((bond.atom2, bond.atom1, atom))
for atom in bonded_to_atom[bond.atom2]:
if atom != bond.atom1:
if atom > bond.atom1:
unique_angles.add((bond.atom1, bond.atom2, atom))
else:
unique_angles.add((atom, bond.atom2, bond.atom1))
data.angles = sorted(list(unique_angles))
# Make a list of all unique proper torsions
unique_propers = set()
for angle in data.angles:
for atom in bonded_to_atom[angle[0]]:
if atom not in angle:
if atom < angle[2]:
unique_propers.add((atom, angle[0], angle[1], angle[2]))
else:
unique_propers.add((angle[2], angle[1], angle[0], atom))
for atom in bonded_to_atom[angle[2]]:
if atom not in angle:
if atom > angle[0]:
unique_propers.add((angle[0], angle[1], angle[2], atom))
else:
unique_propers.add((atom, angle[2], angle[1], angle[0]))
data.propers = sorted(list(unique_propers))
# Make a list of all unique improper torsions
for atom in range(len(bonded_to_atom)):
bonded_to = bonded_to_atom[atom]
if len(bonded_to) > 2:
for subset in itertools.combinations(bonded_to, 3):
data.impropers.append((atom, subset[0], subset[1], subset[2]))
# Identify bonds that should be implemented with constraints
if constraints == AllBonds or constraints == HAngles:
for bond in data.bonds:
bond.isConstrained = True
elif constraints == HBonds:
for bond in data.bonds:
atom1 = data.atoms[bond.atom1]
atom2 = data.atoms[bond.atom2]
bond.isConstrained = atom1.name.startswith('H') or atom2.name.startswith('H')
if rigidWater:
for bond in data.bonds:
atom1 = data.atoms[bond.atom1]
atom2 = data.atoms[bond.atom2]
if atom1.residue.name == 'HOH' and atom2.residue.name == 'HOH':
bond.isConstrained = True
# Identify angles that should be implemented with constraints
if constraints == HAngles:
for angle in data.angles:
atom1 = data.atoms[angle[0]]
atom2 = data.atoms[angle[1]]
atom3 = data.atoms[angle[2]]
numH = 0
if atom1.name.startswith('H'):
numH += 1
if atom3.name.startswith('H'):
numH += 1
data.isAngleConstrained.append(numH == 2 or (numH == 1 and atom2.name.startswith('O')))
else:
data.isAngleConstrained = len(data.angles)*[False]
if rigidWater:
for i in range(len(data.angles)):
angle = data.angles[i]
atom1 = data.atoms[angle[0]]
atom2 = data.atoms[angle[1]]
atom3 = data.atoms[angle[2]]
if atom1.residue.name == 'HOH' and atom2.residue.name == 'HOH' and atom3.residue.name == 'HOH':
data.isAngleConstrained[i] = True
# Add virtual sites
for atom in data.virtualSites:
(site, atoms, excludeWith) = data.virtualSites[atom]
index = atom.index
data.excludeAtomWith[excludeWith].append(index)
if site.type == 'average2':
sys.setVirtualSite(index, mm.TwoParticleAverageSite(
atoms[0], atoms[1], site.weights[0], site.weights[1]))
elif site.type == 'average3':
sys.setVirtualSite(index, mm.ThreeParticleAverageSite(
atoms[0], atoms[1], atoms[2],
site.weights[0], site.weights[1], site.weights[2]))
elif site.type == 'outOfPlane':
sys.setVirtualSite(index, mm.OutOfPlaneSite(
atoms[0], atoms[1], atoms[2],
site.weights[0], site.weights[1], site.weights[2]))
elif site.type == 'localCoords':
local_coord_site = mm.LocalCoordinatesSite(
atoms[0], atoms[1], atoms[2],
mm.Vec3(site.originWeights[0], site.originWeights[1], site.originWeights[2]),
mm.Vec3(site.xWeights[0], site.xWeights[1], site.xWeights[2]),
mm.Vec3(site.yWeights[0], site.yWeights[1], site.yWeights[2]),
mm.Vec3(site.localPos[0], site.localPos[1], site.localPos[2]))
sys.setVirtualSite(index, local_coord_site)
# Add forces to the System
for force in self._forces:
force.createForce(sys, data, nonbondedMethod, nonbondedCutoff, args)
if removeCMMotion:
sys.addForce(mm.CMMotionRemover())
# Let force generators do postprocessing
for force in self._forces:
if 'postprocessSystem' in dir(force):
force.postprocessSystem(sys, data, args)
# Execute scripts found in the XML files.
for script in self._scripts:
exec(script, locals())
return sys
def _write_references_to_file(self, atom_types, references_file):
atomtype_references = {}
for atype in atom_types:
try:
atomtype_references[atype] = self.atomTypeRefs[atype]
except KeyError:
warnings.warn("Reference not found for atom type '{}'."
"".format(atype))
unique_references = collections.defaultdict(list)
for atomtype, dois in atomtype_references.items():
for doi in dois:
unique_references[doi].append(atomtype)
unique_references = collections.OrderedDict(sorted(unique_references.items()))
with open(references_file, 'w') as f:
for doi, atomtypes in unique_references.items():
url = "http://dx.doi.org/" + doi
headers = {"accept": "application/x-bibtex"}
bibtex_ref = requests.get(url, headers=headers).text
note = (',\n\tnote = {Parameters for atom types: ' +
', '.join(sorted(atomtypes)) + '}')
bibtex_ref = bibtex_ref[:-2] + note + bibtex_ref[-2:]
f.write('{}\n'.format(bibtex_ref))
|
mosdef-hub/foyer | foyer/forcefield.py | _check_independent_residues | python | def _check_independent_residues(topology):
for res in topology.residues():
atoms_in_residue = set([atom for atom in res.atoms()])
bond_partners_in_residue = [item for sublist in [atom.bond_partners for atom in res.atoms()] for item in sublist]
# Handle the case of a 'residue' with no neighbors
if not bond_partners_in_residue:
continue
if set(atoms_in_residue) != set(bond_partners_in_residue):
return False
return True | Check to see if residues will constitute independent graphs. | train | https://github.com/mosdef-hub/foyer/blob/9e39c71208fc01a6cc7b7cbe5a533c56830681d3/foyer/forcefield.py#L183-L193 | null | import collections
import glob
import itertools
import os
from tempfile import mktemp, mkstemp
import xml.etree.ElementTree as ET
try:
from cStringIO import StringIO
except ImportError:
from io import StringIO
from pkg_resources import resource_filename
import requests
import warnings
import re
import numpy as np
import parmed as pmd
import simtk.openmm.app.element as elem
import foyer.element as custom_elem
import simtk.unit as u
from simtk import openmm as mm
from simtk.openmm import app
from simtk.openmm.app.forcefield import (NoCutoff, CutoffNonPeriodic, HBonds,
AllBonds, HAngles, NonbondedGenerator,
_convertParameterToNumber)
from foyer.atomtyper import find_atomtypes
from foyer.exceptions import FoyerError
from foyer import smarts
from foyer.validator import Validator
from foyer.utils.io import import_, has_mbuild
def preprocess_forcefield_files(forcefield_files=None):
if forcefield_files is None:
return None
preprocessed_files = []
for xml_file in forcefield_files:
if not hasattr(xml_file,'read'):
f = open(xml_file)
_,suffix = os.path.split(xml_file)
else:
f = xml_file
suffix=""
# read and preprocess
xml_contents = f.read()
f.close()
xml_contents = re.sub(r"(def\w*=\w*[\"\'])(.*)([\"\'])", lambda m: m.group(1) + re.sub(r"&(?!amp;)", r"&", m.group(2)) + m.group(3),
xml_contents)
try:
'''
Sort topology objects by precedence, defined by the number of
`type` attributes specified, where a `type` attribute indicates
increased specificity as opposed to use of `class`
'''
root = ET.fromstring(xml_contents)
for element in root:
if 'Force' in element.tag:
element[:] = sorted(element, key=lambda child: (
-1 * len([attr_name for attr_name in child.keys()
if 'type' in attr_name])))
xml_contents = ET.tostring(root, method='xml').decode()
except ET.ParseError:
'''
Provide the user with a warning if sorting could not be performed.
This indicates a bad XML file, which will be passed on to the
Validator to yield a more descriptive error message.
'''
warnings.warn('Invalid XML detected. Could not auto-sort topology '
'objects by precedence.')
# write to temp file
_, temp_file_name = mkstemp(suffix=suffix)
with open(temp_file_name, 'w') as temp_f:
temp_f.write(xml_contents)
# append temp file name to list
preprocessed_files.append(temp_file_name)
return preprocessed_files
def generate_topology(non_omm_topology, non_element_types=None,
residues=None):
"""Create an OpenMM Topology from another supported topology structure."""
if non_element_types is None:
non_element_types = set()
if isinstance(non_omm_topology, pmd.Structure):
return _topology_from_parmed(non_omm_topology, non_element_types)
elif has_mbuild:
mb = import_('mbuild')
if (non_omm_topology, mb.Compound):
pmdCompoundStructure = non_omm_topology.to_parmed(residues=residues)
return _topology_from_parmed(pmdCompoundStructure, non_element_types)
else:
raise FoyerError('Unknown topology format: {}\n'
'Supported formats are: '
'"parmed.Structure", '
'"mbuild.Compound", '
'"openmm.app.Topology"'.format(non_omm_topology))
def _topology_from_parmed(structure, non_element_types):
"""Convert a ParmEd Structure to an OpenMM Topology."""
topology = app.Topology()
residues = dict()
for pmd_residue in structure.residues:
chain = topology.addChain()
omm_residue = topology.addResidue(pmd_residue.name, chain)
residues[pmd_residue] = omm_residue
atoms = dict() # pmd.Atom: omm.Atom
for pmd_atom in structure.atoms:
name = pmd_atom.name
if pmd_atom.name in non_element_types:
element = non_element_types[pmd_atom.name]
else:
if (isinstance(pmd_atom.atomic_number, int) and
pmd_atom.atomic_number != 0):
element = elem.Element.getByAtomicNumber(pmd_atom.atomic_number)
else:
element = elem.Element.getBySymbol(pmd_atom.name)
omm_atom = topology.addAtom(name, element, residues[pmd_atom.residue])
atoms[pmd_atom] = omm_atom
omm_atom.bond_partners = []
for bond in structure.bonds:
atom1 = atoms[bond.atom1]
atom2 = atoms[bond.atom2]
topology.addBond(atom1, atom2)
atom1.bond_partners.append(atom2)
atom2.bond_partners.append(atom1)
if structure.box_vectors and np.any([x._value for x in structure.box_vectors]):
topology.setPeriodicBoxVectors(structure.box_vectors)
positions = structure.positions
return topology, positions
def _topology_from_residue(res):
"""Converts a openmm.app.Topology.Residue to openmm.app.Topology.
Parameters
----------
res : openmm.app.Topology.Residue
An individual residue in an openmm.app.Topology
Returns
-------
topology : openmm.app.Topology
The generated topology
"""
topology = app.Topology()
chain = topology.addChain()
new_res = topology.addResidue(res.name, chain)
atoms = dict() # { omm.Atom in res : omm.Atom in *new* topology }
for res_atom in res.atoms():
topology_atom = topology.addAtom(name=res_atom.name,
element=res_atom.element,
residue=new_res)
atoms[res_atom] = topology_atom
topology_atom.bond_partners = []
for bond in res.bonds():
atom1 = atoms[bond.atom1]
atom2 = atoms[bond.atom2]
topology.addBond(atom1, atom2)
atom1.bond_partners.append(atom2)
atom2.bond_partners.append(atom1)
return topology
def _update_atomtypes(unatomtyped_topology, res_name, prototype):
"""Update atomtypes in residues in a topology using a prototype topology.
Atomtypes are updated when residues in each topology have matching names.
Parameters
----------
unatomtyped_topology : openmm.app.Topology
Topology lacking atomtypes defined by `find_atomtypes`.
prototype : openmm.app.Topology
Prototype topology with atomtypes defined by `find_atomtypes`.
"""
for res in unatomtyped_topology.residues():
if res.name == res_name:
for old_atom, new_atom_id in zip([atom for atom in res.atoms()], [atom.id for atom in prototype.atoms()]):
old_atom.id = new_atom_id
def _error_or_warn(error, msg):
"""Raise an error or warning if topology objects are not fully parameterized.
Parameters
----------
error : bool
If True, raise an error, else raise a warning
msg : str
The message to be provided with the error or warning
"""
if error:
raise Exception(msg)
else:
warnings.warn(msg)
class Forcefield(app.ForceField):
"""Specialization of OpenMM's Forcefield allowing SMARTS based atomtyping.
Parameters
----------
forcefield_files : list of str, optional, default=None
List of forcefield files to load.
name : str, optional, default=None
Name of a forcefield to load that is packaged within foyer.
"""
def __init__(self, forcefield_files=None, name=None, validation=True, debug=False):
self.atomTypeDefinitions = dict()
self.atomTypeOverrides = dict()
self.atomTypeDesc = dict()
self.atomTypeRefs = dict()
self._included_forcefields = dict()
self.non_element_types = dict()
all_files_to_load = []
if forcefield_files is not None:
if isinstance(forcefield_files, (list, tuple, set)):
for file in forcefield_files:
all_files_to_load.append(file)
else:
all_files_to_load.append(forcefield_files)
if name is not None:
try:
file = self.included_forcefields[name]
except KeyError:
raise IOError('Forcefield {} cannot be found'.format(name))
else:
all_files_to_load.append(file)
preprocessed_files = preprocess_forcefield_files(all_files_to_load)
if validation:
for ff_file_name in preprocessed_files:
Validator(ff_file_name, debug)
super(Forcefield, self).__init__(*preprocessed_files)
self.parser = smarts.SMARTS(self.non_element_types)
self._SystemData = self._SystemData()
@property
def included_forcefields(self):
if any(self._included_forcefields):
return self._included_forcefields
ff_dir = resource_filename('foyer', 'forcefields')
ff_filepaths = set(glob.glob(os.path.join(ff_dir, '*.xml')))
for ff_filepath in ff_filepaths:
_, ff_file = os.path.split(ff_filepath)
basename, _ = os.path.splitext(ff_file)
self._included_forcefields[basename] = ff_filepath
return self._included_forcefields
def _create_element(self, element, mass):
if not isinstance(element, elem.Element):
try:
element = elem.get_by_symbol(element)
except KeyError:
# Enables support for non-atomistic "element types"
if element not in self.non_element_types:
warnings.warn('Non-atomistic element type detected. '
'Creating custom element for {}'.format(element))
element = custom_elem.Element(number=0,
mass=mass,
name=element,
symbol=element)
else:
return element, False
return element, True
def registerAtomType(self, parameters):
"""Register a new atom type. """
name = parameters['name']
if name in self._atomTypes:
raise ValueError('Found multiple definitions for atom type: ' + name)
atom_class = parameters['class']
mass = _convertParameterToNumber(parameters['mass'])
element = None
if 'element' in parameters:
element, custom = self._create_element(parameters['element'], mass)
if custom:
self.non_element_types[element.symbol] = element
self._atomTypes[name] = self.__class__._AtomType(name, atom_class, mass, element)
if atom_class in self._atomClasses:
type_set = self._atomClasses[atom_class]
else:
type_set = set()
self._atomClasses[atom_class] = type_set
type_set.add(name)
self._atomClasses[''].add(name)
name = parameters['name']
if 'def' in parameters:
self.atomTypeDefinitions[name] = parameters['def']
if 'overrides' in parameters:
overrides = set(atype.strip() for atype
in parameters['overrides'].split(","))
if overrides:
self.atomTypeOverrides[name] = overrides
if 'des' in parameters:
self.atomTypeDesc[name] = parameters['desc']
if 'doi' in parameters:
dois = set(doi.strip() for doi in parameters['doi'].split(','))
self.atomTypeRefs[name] = dois
def apply(self, topology, references_file=None, use_residue_map=True,
assert_bond_params=True, assert_angle_params=True,
assert_dihedral_params=True, assert_improper_params=False,
*args, **kwargs):
"""Apply the force field to a molecular structure
Parameters
----------
topology : openmm.app.Topology or parmed.Structure or mbuild.Compound
Molecular structure to apply the force field to
references_file : str, optional, default=None
Name of file where force field references will be written (in Bibtex
format)
use_residue_map : boolean, optional, default=True
Store atomtyped topologies of residues to a dictionary that maps
them to residue names. Each topology, including atomtypes, will be
copied to other residues with the same name. This avoids repeatedly
calling the subgraph isomorphism on idential residues and should
result in better performance for systems with many identical
residues, i.e. a box of water. Note that for this to be applied to
independent molecules, they must each be saved as different
residues in the topology.
assert_bond_params : bool, optional, default=True
If True, Foyer will exit if parameters are not found for all system
bonds.
assert_angle_params : bool, optional, default=True
If True, Foyer will exit if parameters are not found for all system
angles.
assert_dihedral_params : bool, optional, default=True
If True, Foyer will exit if parameters are not found for all system
proper dihedrals.
assert_improper_params : bool, optional, default=False
If True, Foyer will exit if parameters are not found for all system
improper dihedrals.
"""
if self.atomTypeDefinitions == {}:
raise FoyerError('Attempting to atom-type using a force field '
'with no atom type defitions.')
if not isinstance(topology, app.Topology):
residues = kwargs.get('residues')
topology, positions = generate_topology(topology,
self.non_element_types, residues=residues)
else:
positions = np.empty(shape=(topology.getNumAtoms(), 3))
positions[:] = np.nan
box_vectors = topology.getPeriodicBoxVectors()
topology = self.run_atomtyping(topology, use_residue_map=use_residue_map)
system = self.createSystem(topology, *args, **kwargs)
structure = pmd.openmm.load_topology(topology=topology, system=system)
'''
Check that all topology objects (angles, dihedrals, and impropers)
have parameters assigned. OpenMM will generate an error if bond parameters
are not assigned.
'''
data = self._SystemData
if data.bonds:
missing = [b for b in structure.bonds
if b.type is None]
if missing:
nmissing = len(structure.bonds) - len(missing)
msg = ("Parameters have not been assigned to all bonds. "
"Total system bonds: {}, Parametrized bonds: {}"
"".format(len(structure.bonds), nmissing))
_error_or_warn(assert_bond_params, msg)
if data.angles and (len(data.angles) != len(structure.angles)):
msg = ("Parameters have not been assigned to all angles. Total "
"system angles: {}, Parameterized angles: {}"
"".format(len(data.angles), len(structure.angles)))
_error_or_warn(assert_angle_params, msg)
proper_dihedrals = [dihedral for dihedral in structure.dihedrals
if not dihedral.improper]
if data.propers and len(data.propers) != \
len(proper_dihedrals) + len(structure.rb_torsions):
msg = ("Parameters have not been assigned to all proper dihedrals. "
"Total system dihedrals: {}, Parameterized dihedrals: {}. "
"Note that if your system contains torsions of Ryckaert-"
"Bellemans functional form, all of these torsions are "
"processed as propers.".format(len(data.propers),
len(proper_dihedrals) + len(structure.rb_torsions)))
_error_or_warn(assert_dihedral_params, msg)
improper_dihedrals = [dihedral for dihedral in structure.dihedrals
if dihedral.improper]
if data.impropers and len(data.impropers) != \
len(improper_dihedrals) + len(structure.impropers):
msg = ("Parameters have not been assigned to all impropers. Total "
"system impropers: {}, Parameterized impropers: {}. "
"Note that if your system contains torsions of Ryckaert-"
"Bellemans functional form, all of these torsions are "
"processed as propers".format(len(data.impropers),
len(improper_dihedrals) + len(structure.impropers)))
_error_or_warn(assert_improper_params, msg)
structure.bonds.sort(key=lambda x: x.atom1.idx)
structure.positions = positions
if box_vectors is not None:
structure.box_vectors = box_vectors
if references_file:
atom_types = set(atom.type for atom in structure.atoms)
self._write_references_to_file(atom_types, references_file)
return structure
def run_atomtyping(self, topology, use_residue_map=True):
"""Atomtype the topology
Parameters
----------
topology : openmm.app.Topology
Molecular structure to find atom types of
use_residue_map : boolean, optional, default=True
Store atomtyped topologies of residues to a dictionary that maps
them to residue names. Each topology, including atomtypes, will be
copied to other residues with the same name. This avoids repeatedly
calling the subgraph isomorphism on idential residues and should
result in better performance for systems with many identical
residues, i.e. a box of water. Note that for this to be applied to
independent molecules, they must each be saved as different
residues in the topology.
"""
if use_residue_map:
independent_residues = _check_independent_residues(topology)
if independent_residues:
residue_map = dict()
for res in topology.residues():
if res.name not in residue_map.keys():
residue = _topology_from_residue(res)
find_atomtypes(residue, forcefield=self)
residue_map[res.name] = residue
for key, val in residue_map.items():
_update_atomtypes(topology, key, val)
else:
find_atomtypes(topology, forcefield=self)
else:
find_atomtypes(topology, forcefield=self)
if not all([a.id for a in topology.atoms()][0]):
raise ValueError('Not all atoms in topology have atom types')
return topology
def createSystem(self, topology, nonbondedMethod=NoCutoff,
nonbondedCutoff=1.0 * u.nanometer, constraints=None,
rigidWater=True, removeCMMotion=True, hydrogenMass=None,
**args):
"""Construct an OpenMM System representing a Topology with this force field.
Parameters
----------
topology : Topology
The Topology for which to create a System
nonbondedMethod : object=NoCutoff
The method to use for nonbonded interactions. Allowed values are
NoCutoff, CutoffNonPeriodic, CutoffPeriodic, Ewald, or PME.
nonbondedCutoff : distance=1*nanometer
The cutoff distance to use for nonbonded interactions
constraints : object=None
Specifies which bonds and angles should be implemented with constraints.
Allowed values are None, HBonds, AllBonds, or HAngles.
rigidWater : boolean=True
If true, water molecules will be fully rigid regardless of the value
passed for the constraints argument
removeCMMotion : boolean=True
If true, a CMMotionRemover will be added to the System
hydrogenMass : mass=None
The mass to use for hydrogen atoms bound to heavy atoms. Any mass
added to a hydrogen is subtracted from the heavy atom to keep
their total mass the same.
args
Arbitrary additional keyword arguments may also be specified.
This allows extra parameters to be specified that are specific to
particular force fields.
Returns
-------
system
the newly created System
"""
# Overwrite previous _SystemData object
self._SystemData = app.ForceField._SystemData()
data = self._SystemData
data.atoms = list(topology.atoms())
for atom in data.atoms:
data.excludeAtomWith.append([])
# Make a list of all bonds
for bond in topology.bonds():
data.bonds.append(app.ForceField._BondData(bond[0].index, bond[1].index))
# Record which atoms are bonded to each other atom
bonded_to_atom = []
for i in range(len(data.atoms)):
bonded_to_atom.append(set())
data.atomBonds.append([])
for i in range(len(data.bonds)):
bond = data.bonds[i]
bonded_to_atom[bond.atom1].add(bond.atom2)
bonded_to_atom[bond.atom2].add(bond.atom1)
data.atomBonds[bond.atom1].append(i)
data.atomBonds[bond.atom2].append(i)
# TODO: Better way to lookup nonbonded parameters...?
nonbonded_params = None
for generator in self.getGenerators():
if isinstance(generator, NonbondedGenerator):
nonbonded_params = generator.params.paramsForType
break
for chain in topology.chains():
for res in chain.residues():
for atom in res.atoms():
data.atomType[atom] = atom.id
if nonbonded_params:
params = nonbonded_params[atom.id]
data.atomParameters[atom] = params
# Create the System and add atoms
sys = mm.System()
for atom in topology.atoms():
# Look up the atom type name, returning a helpful error message if it cannot be found.
if atom not in data.atomType:
raise Exception("Could not identify atom type for atom '%s'." % str(atom))
typename = data.atomType[atom]
# Look up the type name in the list of registered atom types, returning a helpful error message if it cannot be found.
if typename not in self._atomTypes:
msg = "Could not find typename '%s' for atom '%s' in list of known atom types.\n" % (typename, str(atom))
msg += "Known atom types are: %s" % str(self._atomTypes.keys())
raise Exception(msg)
# Add the particle to the OpenMM system.
mass = self._atomTypes[typename].mass
sys.addParticle(mass)
# Adjust hydrogen masses if requested.
if hydrogenMass is not None:
if not u.is_quantity(hydrogenMass):
hydrogenMass *= u.dalton
for atom1, atom2 in topology.bonds():
if atom1.element == elem.hydrogen:
(atom1, atom2) = (atom2, atom1)
if atom2.element == elem.hydrogen and atom1.element not in (elem.hydrogen, None):
transfer_mass = hydrogenMass - sys.getParticleMass(atom2.index)
sys.setParticleMass(atom2.index, hydrogenMass)
mass = sys.getParticleMass(atom1.index) - transfer_mass
sys.setParticleMass(atom1.index, mass)
# Set periodic boundary conditions.
box_vectors = topology.getPeriodicBoxVectors()
if box_vectors is not None:
sys.setDefaultPeriodicBoxVectors(box_vectors[0],
box_vectors[1],
box_vectors[2])
elif nonbondedMethod not in [NoCutoff, CutoffNonPeriodic]:
raise ValueError('Requested periodic boundary conditions for a '
'Topology that does not specify periodic box '
'dimensions')
# Make a list of all unique angles
unique_angles = set()
for bond in data.bonds:
for atom in bonded_to_atom[bond.atom1]:
if atom != bond.atom2:
if atom < bond.atom2:
unique_angles.add((atom, bond.atom1, bond.atom2))
else:
unique_angles.add((bond.atom2, bond.atom1, atom))
for atom in bonded_to_atom[bond.atom2]:
if atom != bond.atom1:
if atom > bond.atom1:
unique_angles.add((bond.atom1, bond.atom2, atom))
else:
unique_angles.add((atom, bond.atom2, bond.atom1))
data.angles = sorted(list(unique_angles))
# Make a list of all unique proper torsions
unique_propers = set()
for angle in data.angles:
for atom in bonded_to_atom[angle[0]]:
if atom not in angle:
if atom < angle[2]:
unique_propers.add((atom, angle[0], angle[1], angle[2]))
else:
unique_propers.add((angle[2], angle[1], angle[0], atom))
for atom in bonded_to_atom[angle[2]]:
if atom not in angle:
if atom > angle[0]:
unique_propers.add((angle[0], angle[1], angle[2], atom))
else:
unique_propers.add((atom, angle[2], angle[1], angle[0]))
data.propers = sorted(list(unique_propers))
# Make a list of all unique improper torsions
for atom in range(len(bonded_to_atom)):
bonded_to = bonded_to_atom[atom]
if len(bonded_to) > 2:
for subset in itertools.combinations(bonded_to, 3):
data.impropers.append((atom, subset[0], subset[1], subset[2]))
# Identify bonds that should be implemented with constraints
if constraints == AllBonds or constraints == HAngles:
for bond in data.bonds:
bond.isConstrained = True
elif constraints == HBonds:
for bond in data.bonds:
atom1 = data.atoms[bond.atom1]
atom2 = data.atoms[bond.atom2]
bond.isConstrained = atom1.name.startswith('H') or atom2.name.startswith('H')
if rigidWater:
for bond in data.bonds:
atom1 = data.atoms[bond.atom1]
atom2 = data.atoms[bond.atom2]
if atom1.residue.name == 'HOH' and atom2.residue.name == 'HOH':
bond.isConstrained = True
# Identify angles that should be implemented with constraints
if constraints == HAngles:
for angle in data.angles:
atom1 = data.atoms[angle[0]]
atom2 = data.atoms[angle[1]]
atom3 = data.atoms[angle[2]]
numH = 0
if atom1.name.startswith('H'):
numH += 1
if atom3.name.startswith('H'):
numH += 1
data.isAngleConstrained.append(numH == 2 or (numH == 1 and atom2.name.startswith('O')))
else:
data.isAngleConstrained = len(data.angles)*[False]
if rigidWater:
for i in range(len(data.angles)):
angle = data.angles[i]
atom1 = data.atoms[angle[0]]
atom2 = data.atoms[angle[1]]
atom3 = data.atoms[angle[2]]
if atom1.residue.name == 'HOH' and atom2.residue.name == 'HOH' and atom3.residue.name == 'HOH':
data.isAngleConstrained[i] = True
# Add virtual sites
for atom in data.virtualSites:
(site, atoms, excludeWith) = data.virtualSites[atom]
index = atom.index
data.excludeAtomWith[excludeWith].append(index)
if site.type == 'average2':
sys.setVirtualSite(index, mm.TwoParticleAverageSite(
atoms[0], atoms[1], site.weights[0], site.weights[1]))
elif site.type == 'average3':
sys.setVirtualSite(index, mm.ThreeParticleAverageSite(
atoms[0], atoms[1], atoms[2],
site.weights[0], site.weights[1], site.weights[2]))
elif site.type == 'outOfPlane':
sys.setVirtualSite(index, mm.OutOfPlaneSite(
atoms[0], atoms[1], atoms[2],
site.weights[0], site.weights[1], site.weights[2]))
elif site.type == 'localCoords':
local_coord_site = mm.LocalCoordinatesSite(
atoms[0], atoms[1], atoms[2],
mm.Vec3(site.originWeights[0], site.originWeights[1], site.originWeights[2]),
mm.Vec3(site.xWeights[0], site.xWeights[1], site.xWeights[2]),
mm.Vec3(site.yWeights[0], site.yWeights[1], site.yWeights[2]),
mm.Vec3(site.localPos[0], site.localPos[1], site.localPos[2]))
sys.setVirtualSite(index, local_coord_site)
# Add forces to the System
for force in self._forces:
force.createForce(sys, data, nonbondedMethod, nonbondedCutoff, args)
if removeCMMotion:
sys.addForce(mm.CMMotionRemover())
# Let force generators do postprocessing
for force in self._forces:
if 'postprocessSystem' in dir(force):
force.postprocessSystem(sys, data, args)
# Execute scripts found in the XML files.
for script in self._scripts:
exec(script, locals())
return sys
def _write_references_to_file(self, atom_types, references_file):
atomtype_references = {}
for atype in atom_types:
try:
atomtype_references[atype] = self.atomTypeRefs[atype]
except KeyError:
warnings.warn("Reference not found for atom type '{}'."
"".format(atype))
unique_references = collections.defaultdict(list)
for atomtype, dois in atomtype_references.items():
for doi in dois:
unique_references[doi].append(atomtype)
unique_references = collections.OrderedDict(sorted(unique_references.items()))
with open(references_file, 'w') as f:
for doi, atomtypes in unique_references.items():
url = "http://dx.doi.org/" + doi
headers = {"accept": "application/x-bibtex"}
bibtex_ref = requests.get(url, headers=headers).text
note = (',\n\tnote = {Parameters for atom types: ' +
', '.join(sorted(atomtypes)) + '}')
bibtex_ref = bibtex_ref[:-2] + note + bibtex_ref[-2:]
f.write('{}\n'.format(bibtex_ref))
|
mosdef-hub/foyer | foyer/forcefield.py | _update_atomtypes | python | def _update_atomtypes(unatomtyped_topology, res_name, prototype):
for res in unatomtyped_topology.residues():
if res.name == res_name:
for old_atom, new_atom_id in zip([atom for atom in res.atoms()], [atom.id for atom in prototype.atoms()]):
old_atom.id = new_atom_id | Update atomtypes in residues in a topology using a prototype topology.
Atomtypes are updated when residues in each topology have matching names.
Parameters
----------
unatomtyped_topology : openmm.app.Topology
Topology lacking atomtypes defined by `find_atomtypes`.
prototype : openmm.app.Topology
Prototype topology with atomtypes defined by `find_atomtypes`. | train | https://github.com/mosdef-hub/foyer/blob/9e39c71208fc01a6cc7b7cbe5a533c56830681d3/foyer/forcefield.py#L196-L212 | null | import collections
import glob
import itertools
import os
from tempfile import mktemp, mkstemp
import xml.etree.ElementTree as ET
try:
from cStringIO import StringIO
except ImportError:
from io import StringIO
from pkg_resources import resource_filename
import requests
import warnings
import re
import numpy as np
import parmed as pmd
import simtk.openmm.app.element as elem
import foyer.element as custom_elem
import simtk.unit as u
from simtk import openmm as mm
from simtk.openmm import app
from simtk.openmm.app.forcefield import (NoCutoff, CutoffNonPeriodic, HBonds,
AllBonds, HAngles, NonbondedGenerator,
_convertParameterToNumber)
from foyer.atomtyper import find_atomtypes
from foyer.exceptions import FoyerError
from foyer import smarts
from foyer.validator import Validator
from foyer.utils.io import import_, has_mbuild
def preprocess_forcefield_files(forcefield_files=None):
if forcefield_files is None:
return None
preprocessed_files = []
for xml_file in forcefield_files:
if not hasattr(xml_file,'read'):
f = open(xml_file)
_,suffix = os.path.split(xml_file)
else:
f = xml_file
suffix=""
# read and preprocess
xml_contents = f.read()
f.close()
xml_contents = re.sub(r"(def\w*=\w*[\"\'])(.*)([\"\'])", lambda m: m.group(1) + re.sub(r"&(?!amp;)", r"&", m.group(2)) + m.group(3),
xml_contents)
try:
'''
Sort topology objects by precedence, defined by the number of
`type` attributes specified, where a `type` attribute indicates
increased specificity as opposed to use of `class`
'''
root = ET.fromstring(xml_contents)
for element in root:
if 'Force' in element.tag:
element[:] = sorted(element, key=lambda child: (
-1 * len([attr_name for attr_name in child.keys()
if 'type' in attr_name])))
xml_contents = ET.tostring(root, method='xml').decode()
except ET.ParseError:
'''
Provide the user with a warning if sorting could not be performed.
This indicates a bad XML file, which will be passed on to the
Validator to yield a more descriptive error message.
'''
warnings.warn('Invalid XML detected. Could not auto-sort topology '
'objects by precedence.')
# write to temp file
_, temp_file_name = mkstemp(suffix=suffix)
with open(temp_file_name, 'w') as temp_f:
temp_f.write(xml_contents)
# append temp file name to list
preprocessed_files.append(temp_file_name)
return preprocessed_files
def generate_topology(non_omm_topology, non_element_types=None,
residues=None):
"""Create an OpenMM Topology from another supported topology structure."""
if non_element_types is None:
non_element_types = set()
if isinstance(non_omm_topology, pmd.Structure):
return _topology_from_parmed(non_omm_topology, non_element_types)
elif has_mbuild:
mb = import_('mbuild')
if (non_omm_topology, mb.Compound):
pmdCompoundStructure = non_omm_topology.to_parmed(residues=residues)
return _topology_from_parmed(pmdCompoundStructure, non_element_types)
else:
raise FoyerError('Unknown topology format: {}\n'
'Supported formats are: '
'"parmed.Structure", '
'"mbuild.Compound", '
'"openmm.app.Topology"'.format(non_omm_topology))
def _topology_from_parmed(structure, non_element_types):
"""Convert a ParmEd Structure to an OpenMM Topology."""
topology = app.Topology()
residues = dict()
for pmd_residue in structure.residues:
chain = topology.addChain()
omm_residue = topology.addResidue(pmd_residue.name, chain)
residues[pmd_residue] = omm_residue
atoms = dict() # pmd.Atom: omm.Atom
for pmd_atom in structure.atoms:
name = pmd_atom.name
if pmd_atom.name in non_element_types:
element = non_element_types[pmd_atom.name]
else:
if (isinstance(pmd_atom.atomic_number, int) and
pmd_atom.atomic_number != 0):
element = elem.Element.getByAtomicNumber(pmd_atom.atomic_number)
else:
element = elem.Element.getBySymbol(pmd_atom.name)
omm_atom = topology.addAtom(name, element, residues[pmd_atom.residue])
atoms[pmd_atom] = omm_atom
omm_atom.bond_partners = []
for bond in structure.bonds:
atom1 = atoms[bond.atom1]
atom2 = atoms[bond.atom2]
topology.addBond(atom1, atom2)
atom1.bond_partners.append(atom2)
atom2.bond_partners.append(atom1)
if structure.box_vectors and np.any([x._value for x in structure.box_vectors]):
topology.setPeriodicBoxVectors(structure.box_vectors)
positions = structure.positions
return topology, positions
def _topology_from_residue(res):
"""Converts a openmm.app.Topology.Residue to openmm.app.Topology.
Parameters
----------
res : openmm.app.Topology.Residue
An individual residue in an openmm.app.Topology
Returns
-------
topology : openmm.app.Topology
The generated topology
"""
topology = app.Topology()
chain = topology.addChain()
new_res = topology.addResidue(res.name, chain)
atoms = dict() # { omm.Atom in res : omm.Atom in *new* topology }
for res_atom in res.atoms():
topology_atom = topology.addAtom(name=res_atom.name,
element=res_atom.element,
residue=new_res)
atoms[res_atom] = topology_atom
topology_atom.bond_partners = []
for bond in res.bonds():
atom1 = atoms[bond.atom1]
atom2 = atoms[bond.atom2]
topology.addBond(atom1, atom2)
atom1.bond_partners.append(atom2)
atom2.bond_partners.append(atom1)
return topology
def _check_independent_residues(topology):
"""Check to see if residues will constitute independent graphs."""
for res in topology.residues():
atoms_in_residue = set([atom for atom in res.atoms()])
bond_partners_in_residue = [item for sublist in [atom.bond_partners for atom in res.atoms()] for item in sublist]
# Handle the case of a 'residue' with no neighbors
if not bond_partners_in_residue:
continue
if set(atoms_in_residue) != set(bond_partners_in_residue):
return False
return True
def _error_or_warn(error, msg):
"""Raise an error or warning if topology objects are not fully parameterized.
Parameters
----------
error : bool
If True, raise an error, else raise a warning
msg : str
The message to be provided with the error or warning
"""
if error:
raise Exception(msg)
else:
warnings.warn(msg)
class Forcefield(app.ForceField):
"""Specialization of OpenMM's Forcefield allowing SMARTS based atomtyping.
Parameters
----------
forcefield_files : list of str, optional, default=None
List of forcefield files to load.
name : str, optional, default=None
Name of a forcefield to load that is packaged within foyer.
"""
def __init__(self, forcefield_files=None, name=None, validation=True, debug=False):
self.atomTypeDefinitions = dict()
self.atomTypeOverrides = dict()
self.atomTypeDesc = dict()
self.atomTypeRefs = dict()
self._included_forcefields = dict()
self.non_element_types = dict()
all_files_to_load = []
if forcefield_files is not None:
if isinstance(forcefield_files, (list, tuple, set)):
for file in forcefield_files:
all_files_to_load.append(file)
else:
all_files_to_load.append(forcefield_files)
if name is not None:
try:
file = self.included_forcefields[name]
except KeyError:
raise IOError('Forcefield {} cannot be found'.format(name))
else:
all_files_to_load.append(file)
preprocessed_files = preprocess_forcefield_files(all_files_to_load)
if validation:
for ff_file_name in preprocessed_files:
Validator(ff_file_name, debug)
super(Forcefield, self).__init__(*preprocessed_files)
self.parser = smarts.SMARTS(self.non_element_types)
self._SystemData = self._SystemData()
@property
def included_forcefields(self):
if any(self._included_forcefields):
return self._included_forcefields
ff_dir = resource_filename('foyer', 'forcefields')
ff_filepaths = set(glob.glob(os.path.join(ff_dir, '*.xml')))
for ff_filepath in ff_filepaths:
_, ff_file = os.path.split(ff_filepath)
basename, _ = os.path.splitext(ff_file)
self._included_forcefields[basename] = ff_filepath
return self._included_forcefields
def _create_element(self, element, mass):
if not isinstance(element, elem.Element):
try:
element = elem.get_by_symbol(element)
except KeyError:
# Enables support for non-atomistic "element types"
if element not in self.non_element_types:
warnings.warn('Non-atomistic element type detected. '
'Creating custom element for {}'.format(element))
element = custom_elem.Element(number=0,
mass=mass,
name=element,
symbol=element)
else:
return element, False
return element, True
def registerAtomType(self, parameters):
"""Register a new atom type. """
name = parameters['name']
if name in self._atomTypes:
raise ValueError('Found multiple definitions for atom type: ' + name)
atom_class = parameters['class']
mass = _convertParameterToNumber(parameters['mass'])
element = None
if 'element' in parameters:
element, custom = self._create_element(parameters['element'], mass)
if custom:
self.non_element_types[element.symbol] = element
self._atomTypes[name] = self.__class__._AtomType(name, atom_class, mass, element)
if atom_class in self._atomClasses:
type_set = self._atomClasses[atom_class]
else:
type_set = set()
self._atomClasses[atom_class] = type_set
type_set.add(name)
self._atomClasses[''].add(name)
name = parameters['name']
if 'def' in parameters:
self.atomTypeDefinitions[name] = parameters['def']
if 'overrides' in parameters:
overrides = set(atype.strip() for atype
in parameters['overrides'].split(","))
if overrides:
self.atomTypeOverrides[name] = overrides
if 'des' in parameters:
self.atomTypeDesc[name] = parameters['desc']
if 'doi' in parameters:
dois = set(doi.strip() for doi in parameters['doi'].split(','))
self.atomTypeRefs[name] = dois
def apply(self, topology, references_file=None, use_residue_map=True,
assert_bond_params=True, assert_angle_params=True,
assert_dihedral_params=True, assert_improper_params=False,
*args, **kwargs):
"""Apply the force field to a molecular structure
Parameters
----------
topology : openmm.app.Topology or parmed.Structure or mbuild.Compound
Molecular structure to apply the force field to
references_file : str, optional, default=None
Name of file where force field references will be written (in Bibtex
format)
use_residue_map : boolean, optional, default=True
Store atomtyped topologies of residues to a dictionary that maps
them to residue names. Each topology, including atomtypes, will be
copied to other residues with the same name. This avoids repeatedly
calling the subgraph isomorphism on idential residues and should
result in better performance for systems with many identical
residues, i.e. a box of water. Note that for this to be applied to
independent molecules, they must each be saved as different
residues in the topology.
assert_bond_params : bool, optional, default=True
If True, Foyer will exit if parameters are not found for all system
bonds.
assert_angle_params : bool, optional, default=True
If True, Foyer will exit if parameters are not found for all system
angles.
assert_dihedral_params : bool, optional, default=True
If True, Foyer will exit if parameters are not found for all system
proper dihedrals.
assert_improper_params : bool, optional, default=False
If True, Foyer will exit if parameters are not found for all system
improper dihedrals.
"""
if self.atomTypeDefinitions == {}:
raise FoyerError('Attempting to atom-type using a force field '
'with no atom type defitions.')
if not isinstance(topology, app.Topology):
residues = kwargs.get('residues')
topology, positions = generate_topology(topology,
self.non_element_types, residues=residues)
else:
positions = np.empty(shape=(topology.getNumAtoms(), 3))
positions[:] = np.nan
box_vectors = topology.getPeriodicBoxVectors()
topology = self.run_atomtyping(topology, use_residue_map=use_residue_map)
system = self.createSystem(topology, *args, **kwargs)
structure = pmd.openmm.load_topology(topology=topology, system=system)
'''
Check that all topology objects (angles, dihedrals, and impropers)
have parameters assigned. OpenMM will generate an error if bond parameters
are not assigned.
'''
data = self._SystemData
if data.bonds:
missing = [b for b in structure.bonds
if b.type is None]
if missing:
nmissing = len(structure.bonds) - len(missing)
msg = ("Parameters have not been assigned to all bonds. "
"Total system bonds: {}, Parametrized bonds: {}"
"".format(len(structure.bonds), nmissing))
_error_or_warn(assert_bond_params, msg)
if data.angles and (len(data.angles) != len(structure.angles)):
msg = ("Parameters have not been assigned to all angles. Total "
"system angles: {}, Parameterized angles: {}"
"".format(len(data.angles), len(structure.angles)))
_error_or_warn(assert_angle_params, msg)
proper_dihedrals = [dihedral for dihedral in structure.dihedrals
if not dihedral.improper]
if data.propers and len(data.propers) != \
len(proper_dihedrals) + len(structure.rb_torsions):
msg = ("Parameters have not been assigned to all proper dihedrals. "
"Total system dihedrals: {}, Parameterized dihedrals: {}. "
"Note that if your system contains torsions of Ryckaert-"
"Bellemans functional form, all of these torsions are "
"processed as propers.".format(len(data.propers),
len(proper_dihedrals) + len(structure.rb_torsions)))
_error_or_warn(assert_dihedral_params, msg)
improper_dihedrals = [dihedral for dihedral in structure.dihedrals
if dihedral.improper]
if data.impropers and len(data.impropers) != \
len(improper_dihedrals) + len(structure.impropers):
msg = ("Parameters have not been assigned to all impropers. Total "
"system impropers: {}, Parameterized impropers: {}. "
"Note that if your system contains torsions of Ryckaert-"
"Bellemans functional form, all of these torsions are "
"processed as propers".format(len(data.impropers),
len(improper_dihedrals) + len(structure.impropers)))
_error_or_warn(assert_improper_params, msg)
structure.bonds.sort(key=lambda x: x.atom1.idx)
structure.positions = positions
if box_vectors is not None:
structure.box_vectors = box_vectors
if references_file:
atom_types = set(atom.type for atom in structure.atoms)
self._write_references_to_file(atom_types, references_file)
return structure
def run_atomtyping(self, topology, use_residue_map=True):
"""Atomtype the topology
Parameters
----------
topology : openmm.app.Topology
Molecular structure to find atom types of
use_residue_map : boolean, optional, default=True
Store atomtyped topologies of residues to a dictionary that maps
them to residue names. Each topology, including atomtypes, will be
copied to other residues with the same name. This avoids repeatedly
calling the subgraph isomorphism on idential residues and should
result in better performance for systems with many identical
residues, i.e. a box of water. Note that for this to be applied to
independent molecules, they must each be saved as different
residues in the topology.
"""
if use_residue_map:
independent_residues = _check_independent_residues(topology)
if independent_residues:
residue_map = dict()
for res in topology.residues():
if res.name not in residue_map.keys():
residue = _topology_from_residue(res)
find_atomtypes(residue, forcefield=self)
residue_map[res.name] = residue
for key, val in residue_map.items():
_update_atomtypes(topology, key, val)
else:
find_atomtypes(topology, forcefield=self)
else:
find_atomtypes(topology, forcefield=self)
if not all([a.id for a in topology.atoms()][0]):
raise ValueError('Not all atoms in topology have atom types')
return topology
def createSystem(self, topology, nonbondedMethod=NoCutoff,
nonbondedCutoff=1.0 * u.nanometer, constraints=None,
rigidWater=True, removeCMMotion=True, hydrogenMass=None,
**args):
"""Construct an OpenMM System representing a Topology with this force field.
Parameters
----------
topology : Topology
The Topology for which to create a System
nonbondedMethod : object=NoCutoff
The method to use for nonbonded interactions. Allowed values are
NoCutoff, CutoffNonPeriodic, CutoffPeriodic, Ewald, or PME.
nonbondedCutoff : distance=1*nanometer
The cutoff distance to use for nonbonded interactions
constraints : object=None
Specifies which bonds and angles should be implemented with constraints.
Allowed values are None, HBonds, AllBonds, or HAngles.
rigidWater : boolean=True
If true, water molecules will be fully rigid regardless of the value
passed for the constraints argument
removeCMMotion : boolean=True
If true, a CMMotionRemover will be added to the System
hydrogenMass : mass=None
The mass to use for hydrogen atoms bound to heavy atoms. Any mass
added to a hydrogen is subtracted from the heavy atom to keep
their total mass the same.
args
Arbitrary additional keyword arguments may also be specified.
This allows extra parameters to be specified that are specific to
particular force fields.
Returns
-------
system
the newly created System
"""
# Overwrite previous _SystemData object
self._SystemData = app.ForceField._SystemData()
data = self._SystemData
data.atoms = list(topology.atoms())
for atom in data.atoms:
data.excludeAtomWith.append([])
# Make a list of all bonds
for bond in topology.bonds():
data.bonds.append(app.ForceField._BondData(bond[0].index, bond[1].index))
# Record which atoms are bonded to each other atom
bonded_to_atom = []
for i in range(len(data.atoms)):
bonded_to_atom.append(set())
data.atomBonds.append([])
for i in range(len(data.bonds)):
bond = data.bonds[i]
bonded_to_atom[bond.atom1].add(bond.atom2)
bonded_to_atom[bond.atom2].add(bond.atom1)
data.atomBonds[bond.atom1].append(i)
data.atomBonds[bond.atom2].append(i)
# TODO: Better way to lookup nonbonded parameters...?
nonbonded_params = None
for generator in self.getGenerators():
if isinstance(generator, NonbondedGenerator):
nonbonded_params = generator.params.paramsForType
break
for chain in topology.chains():
for res in chain.residues():
for atom in res.atoms():
data.atomType[atom] = atom.id
if nonbonded_params:
params = nonbonded_params[atom.id]
data.atomParameters[atom] = params
# Create the System and add atoms
sys = mm.System()
for atom in topology.atoms():
# Look up the atom type name, returning a helpful error message if it cannot be found.
if atom not in data.atomType:
raise Exception("Could not identify atom type for atom '%s'." % str(atom))
typename = data.atomType[atom]
# Look up the type name in the list of registered atom types, returning a helpful error message if it cannot be found.
if typename not in self._atomTypes:
msg = "Could not find typename '%s' for atom '%s' in list of known atom types.\n" % (typename, str(atom))
msg += "Known atom types are: %s" % str(self._atomTypes.keys())
raise Exception(msg)
# Add the particle to the OpenMM system.
mass = self._atomTypes[typename].mass
sys.addParticle(mass)
# Adjust hydrogen masses if requested.
if hydrogenMass is not None:
if not u.is_quantity(hydrogenMass):
hydrogenMass *= u.dalton
for atom1, atom2 in topology.bonds():
if atom1.element == elem.hydrogen:
(atom1, atom2) = (atom2, atom1)
if atom2.element == elem.hydrogen and atom1.element not in (elem.hydrogen, None):
transfer_mass = hydrogenMass - sys.getParticleMass(atom2.index)
sys.setParticleMass(atom2.index, hydrogenMass)
mass = sys.getParticleMass(atom1.index) - transfer_mass
sys.setParticleMass(atom1.index, mass)
# Set periodic boundary conditions.
box_vectors = topology.getPeriodicBoxVectors()
if box_vectors is not None:
sys.setDefaultPeriodicBoxVectors(box_vectors[0],
box_vectors[1],
box_vectors[2])
elif nonbondedMethod not in [NoCutoff, CutoffNonPeriodic]:
raise ValueError('Requested periodic boundary conditions for a '
'Topology that does not specify periodic box '
'dimensions')
# Make a list of all unique angles
unique_angles = set()
for bond in data.bonds:
for atom in bonded_to_atom[bond.atom1]:
if atom != bond.atom2:
if atom < bond.atom2:
unique_angles.add((atom, bond.atom1, bond.atom2))
else:
unique_angles.add((bond.atom2, bond.atom1, atom))
for atom in bonded_to_atom[bond.atom2]:
if atom != bond.atom1:
if atom > bond.atom1:
unique_angles.add((bond.atom1, bond.atom2, atom))
else:
unique_angles.add((atom, bond.atom2, bond.atom1))
data.angles = sorted(list(unique_angles))
# Make a list of all unique proper torsions
unique_propers = set()
for angle in data.angles:
for atom in bonded_to_atom[angle[0]]:
if atom not in angle:
if atom < angle[2]:
unique_propers.add((atom, angle[0], angle[1], angle[2]))
else:
unique_propers.add((angle[2], angle[1], angle[0], atom))
for atom in bonded_to_atom[angle[2]]:
if atom not in angle:
if atom > angle[0]:
unique_propers.add((angle[0], angle[1], angle[2], atom))
else:
unique_propers.add((atom, angle[2], angle[1], angle[0]))
data.propers = sorted(list(unique_propers))
# Make a list of all unique improper torsions
for atom in range(len(bonded_to_atom)):
bonded_to = bonded_to_atom[atom]
if len(bonded_to) > 2:
for subset in itertools.combinations(bonded_to, 3):
data.impropers.append((atom, subset[0], subset[1], subset[2]))
# Identify bonds that should be implemented with constraints
if constraints == AllBonds or constraints == HAngles:
for bond in data.bonds:
bond.isConstrained = True
elif constraints == HBonds:
for bond in data.bonds:
atom1 = data.atoms[bond.atom1]
atom2 = data.atoms[bond.atom2]
bond.isConstrained = atom1.name.startswith('H') or atom2.name.startswith('H')
if rigidWater:
for bond in data.bonds:
atom1 = data.atoms[bond.atom1]
atom2 = data.atoms[bond.atom2]
if atom1.residue.name == 'HOH' and atom2.residue.name == 'HOH':
bond.isConstrained = True
# Identify angles that should be implemented with constraints
if constraints == HAngles:
for angle in data.angles:
atom1 = data.atoms[angle[0]]
atom2 = data.atoms[angle[1]]
atom3 = data.atoms[angle[2]]
numH = 0
if atom1.name.startswith('H'):
numH += 1
if atom3.name.startswith('H'):
numH += 1
data.isAngleConstrained.append(numH == 2 or (numH == 1 and atom2.name.startswith('O')))
else:
data.isAngleConstrained = len(data.angles)*[False]
if rigidWater:
for i in range(len(data.angles)):
angle = data.angles[i]
atom1 = data.atoms[angle[0]]
atom2 = data.atoms[angle[1]]
atom3 = data.atoms[angle[2]]
if atom1.residue.name == 'HOH' and atom2.residue.name == 'HOH' and atom3.residue.name == 'HOH':
data.isAngleConstrained[i] = True
# Add virtual sites
for atom in data.virtualSites:
(site, atoms, excludeWith) = data.virtualSites[atom]
index = atom.index
data.excludeAtomWith[excludeWith].append(index)
if site.type == 'average2':
sys.setVirtualSite(index, mm.TwoParticleAverageSite(
atoms[0], atoms[1], site.weights[0], site.weights[1]))
elif site.type == 'average3':
sys.setVirtualSite(index, mm.ThreeParticleAverageSite(
atoms[0], atoms[1], atoms[2],
site.weights[0], site.weights[1], site.weights[2]))
elif site.type == 'outOfPlane':
sys.setVirtualSite(index, mm.OutOfPlaneSite(
atoms[0], atoms[1], atoms[2],
site.weights[0], site.weights[1], site.weights[2]))
elif site.type == 'localCoords':
local_coord_site = mm.LocalCoordinatesSite(
atoms[0], atoms[1], atoms[2],
mm.Vec3(site.originWeights[0], site.originWeights[1], site.originWeights[2]),
mm.Vec3(site.xWeights[0], site.xWeights[1], site.xWeights[2]),
mm.Vec3(site.yWeights[0], site.yWeights[1], site.yWeights[2]),
mm.Vec3(site.localPos[0], site.localPos[1], site.localPos[2]))
sys.setVirtualSite(index, local_coord_site)
# Add forces to the System
for force in self._forces:
force.createForce(sys, data, nonbondedMethod, nonbondedCutoff, args)
if removeCMMotion:
sys.addForce(mm.CMMotionRemover())
# Let force generators do postprocessing
for force in self._forces:
if 'postprocessSystem' in dir(force):
force.postprocessSystem(sys, data, args)
# Execute scripts found in the XML files.
for script in self._scripts:
exec(script, locals())
return sys
def _write_references_to_file(self, atom_types, references_file):
atomtype_references = {}
for atype in atom_types:
try:
atomtype_references[atype] = self.atomTypeRefs[atype]
except KeyError:
warnings.warn("Reference not found for atom type '{}'."
"".format(atype))
unique_references = collections.defaultdict(list)
for atomtype, dois in atomtype_references.items():
for doi in dois:
unique_references[doi].append(atomtype)
unique_references = collections.OrderedDict(sorted(unique_references.items()))
with open(references_file, 'w') as f:
for doi, atomtypes in unique_references.items():
url = "http://dx.doi.org/" + doi
headers = {"accept": "application/x-bibtex"}
bibtex_ref = requests.get(url, headers=headers).text
note = (',\n\tnote = {Parameters for atom types: ' +
', '.join(sorted(atomtypes)) + '}')
bibtex_ref = bibtex_ref[:-2] + note + bibtex_ref[-2:]
f.write('{}\n'.format(bibtex_ref))
|
mosdef-hub/foyer | foyer/forcefield.py | Forcefield.registerAtomType | python | def registerAtomType(self, parameters):
name = parameters['name']
if name in self._atomTypes:
raise ValueError('Found multiple definitions for atom type: ' + name)
atom_class = parameters['class']
mass = _convertParameterToNumber(parameters['mass'])
element = None
if 'element' in parameters:
element, custom = self._create_element(parameters['element'], mass)
if custom:
self.non_element_types[element.symbol] = element
self._atomTypes[name] = self.__class__._AtomType(name, atom_class, mass, element)
if atom_class in self._atomClasses:
type_set = self._atomClasses[atom_class]
else:
type_set = set()
self._atomClasses[atom_class] = type_set
type_set.add(name)
self._atomClasses[''].add(name)
name = parameters['name']
if 'def' in parameters:
self.atomTypeDefinitions[name] = parameters['def']
if 'overrides' in parameters:
overrides = set(atype.strip() for atype
in parameters['overrides'].split(","))
if overrides:
self.atomTypeOverrides[name] = overrides
if 'des' in parameters:
self.atomTypeDesc[name] = parameters['desc']
if 'doi' in parameters:
dois = set(doi.strip() for doi in parameters['doi'].split(','))
self.atomTypeRefs[name] = dois | Register a new atom type. | train | https://github.com/mosdef-hub/foyer/blob/9e39c71208fc01a6cc7b7cbe5a533c56830681d3/foyer/forcefield.py#L307-L341 | [
"def _create_element(self, element, mass):\n if not isinstance(element, elem.Element):\n try:\n element = elem.get_by_symbol(element)\n except KeyError:\n # Enables support for non-atomistic \"element types\"\n if element not in self.non_element_types:\n warnings.warn('Non-atomistic element type detected. '\n 'Creating custom element for {}'.format(element))\n element = custom_elem.Element(number=0,\n mass=mass,\n name=element,\n symbol=element)\n else:\n return element, False\n\n return element, True\n"
] | class Forcefield(app.ForceField):
"""Specialization of OpenMM's Forcefield allowing SMARTS based atomtyping.
Parameters
----------
forcefield_files : list of str, optional, default=None
List of forcefield files to load.
name : str, optional, default=None
Name of a forcefield to load that is packaged within foyer.
"""
def __init__(self, forcefield_files=None, name=None, validation=True, debug=False):
self.atomTypeDefinitions = dict()
self.atomTypeOverrides = dict()
self.atomTypeDesc = dict()
self.atomTypeRefs = dict()
self._included_forcefields = dict()
self.non_element_types = dict()
all_files_to_load = []
if forcefield_files is not None:
if isinstance(forcefield_files, (list, tuple, set)):
for file in forcefield_files:
all_files_to_load.append(file)
else:
all_files_to_load.append(forcefield_files)
if name is not None:
try:
file = self.included_forcefields[name]
except KeyError:
raise IOError('Forcefield {} cannot be found'.format(name))
else:
all_files_to_load.append(file)
preprocessed_files = preprocess_forcefield_files(all_files_to_load)
if validation:
for ff_file_name in preprocessed_files:
Validator(ff_file_name, debug)
super(Forcefield, self).__init__(*preprocessed_files)
self.parser = smarts.SMARTS(self.non_element_types)
self._SystemData = self._SystemData()
@property
def included_forcefields(self):
if any(self._included_forcefields):
return self._included_forcefields
ff_dir = resource_filename('foyer', 'forcefields')
ff_filepaths = set(glob.glob(os.path.join(ff_dir, '*.xml')))
for ff_filepath in ff_filepaths:
_, ff_file = os.path.split(ff_filepath)
basename, _ = os.path.splitext(ff_file)
self._included_forcefields[basename] = ff_filepath
return self._included_forcefields
def _create_element(self, element, mass):
if not isinstance(element, elem.Element):
try:
element = elem.get_by_symbol(element)
except KeyError:
# Enables support for non-atomistic "element types"
if element not in self.non_element_types:
warnings.warn('Non-atomistic element type detected. '
'Creating custom element for {}'.format(element))
element = custom_elem.Element(number=0,
mass=mass,
name=element,
symbol=element)
else:
return element, False
return element, True
def apply(self, topology, references_file=None, use_residue_map=True,
assert_bond_params=True, assert_angle_params=True,
assert_dihedral_params=True, assert_improper_params=False,
*args, **kwargs):
"""Apply the force field to a molecular structure
Parameters
----------
topology : openmm.app.Topology or parmed.Structure or mbuild.Compound
Molecular structure to apply the force field to
references_file : str, optional, default=None
Name of file where force field references will be written (in Bibtex
format)
use_residue_map : boolean, optional, default=True
Store atomtyped topologies of residues to a dictionary that maps
them to residue names. Each topology, including atomtypes, will be
copied to other residues with the same name. This avoids repeatedly
calling the subgraph isomorphism on idential residues and should
result in better performance for systems with many identical
residues, i.e. a box of water. Note that for this to be applied to
independent molecules, they must each be saved as different
residues in the topology.
assert_bond_params : bool, optional, default=True
If True, Foyer will exit if parameters are not found for all system
bonds.
assert_angle_params : bool, optional, default=True
If True, Foyer will exit if parameters are not found for all system
angles.
assert_dihedral_params : bool, optional, default=True
If True, Foyer will exit if parameters are not found for all system
proper dihedrals.
assert_improper_params : bool, optional, default=False
If True, Foyer will exit if parameters are not found for all system
improper dihedrals.
"""
if self.atomTypeDefinitions == {}:
raise FoyerError('Attempting to atom-type using a force field '
'with no atom type defitions.')
if not isinstance(topology, app.Topology):
residues = kwargs.get('residues')
topology, positions = generate_topology(topology,
self.non_element_types, residues=residues)
else:
positions = np.empty(shape=(topology.getNumAtoms(), 3))
positions[:] = np.nan
box_vectors = topology.getPeriodicBoxVectors()
topology = self.run_atomtyping(topology, use_residue_map=use_residue_map)
system = self.createSystem(topology, *args, **kwargs)
structure = pmd.openmm.load_topology(topology=topology, system=system)
'''
Check that all topology objects (angles, dihedrals, and impropers)
have parameters assigned. OpenMM will generate an error if bond parameters
are not assigned.
'''
data = self._SystemData
if data.bonds:
missing = [b for b in structure.bonds
if b.type is None]
if missing:
nmissing = len(structure.bonds) - len(missing)
msg = ("Parameters have not been assigned to all bonds. "
"Total system bonds: {}, Parametrized bonds: {}"
"".format(len(structure.bonds), nmissing))
_error_or_warn(assert_bond_params, msg)
if data.angles and (len(data.angles) != len(structure.angles)):
msg = ("Parameters have not been assigned to all angles. Total "
"system angles: {}, Parameterized angles: {}"
"".format(len(data.angles), len(structure.angles)))
_error_or_warn(assert_angle_params, msg)
proper_dihedrals = [dihedral for dihedral in structure.dihedrals
if not dihedral.improper]
if data.propers and len(data.propers) != \
len(proper_dihedrals) + len(structure.rb_torsions):
msg = ("Parameters have not been assigned to all proper dihedrals. "
"Total system dihedrals: {}, Parameterized dihedrals: {}. "
"Note that if your system contains torsions of Ryckaert-"
"Bellemans functional form, all of these torsions are "
"processed as propers.".format(len(data.propers),
len(proper_dihedrals) + len(structure.rb_torsions)))
_error_or_warn(assert_dihedral_params, msg)
improper_dihedrals = [dihedral for dihedral in structure.dihedrals
if dihedral.improper]
if data.impropers and len(data.impropers) != \
len(improper_dihedrals) + len(structure.impropers):
msg = ("Parameters have not been assigned to all impropers. Total "
"system impropers: {}, Parameterized impropers: {}. "
"Note that if your system contains torsions of Ryckaert-"
"Bellemans functional form, all of these torsions are "
"processed as propers".format(len(data.impropers),
len(improper_dihedrals) + len(structure.impropers)))
_error_or_warn(assert_improper_params, msg)
structure.bonds.sort(key=lambda x: x.atom1.idx)
structure.positions = positions
if box_vectors is not None:
structure.box_vectors = box_vectors
if references_file:
atom_types = set(atom.type for atom in structure.atoms)
self._write_references_to_file(atom_types, references_file)
return structure
def run_atomtyping(self, topology, use_residue_map=True):
"""Atomtype the topology
Parameters
----------
topology : openmm.app.Topology
Molecular structure to find atom types of
use_residue_map : boolean, optional, default=True
Store atomtyped topologies of residues to a dictionary that maps
them to residue names. Each topology, including atomtypes, will be
copied to other residues with the same name. This avoids repeatedly
calling the subgraph isomorphism on idential residues and should
result in better performance for systems with many identical
residues, i.e. a box of water. Note that for this to be applied to
independent molecules, they must each be saved as different
residues in the topology.
"""
if use_residue_map:
independent_residues = _check_independent_residues(topology)
if independent_residues:
residue_map = dict()
for res in topology.residues():
if res.name not in residue_map.keys():
residue = _topology_from_residue(res)
find_atomtypes(residue, forcefield=self)
residue_map[res.name] = residue
for key, val in residue_map.items():
_update_atomtypes(topology, key, val)
else:
find_atomtypes(topology, forcefield=self)
else:
find_atomtypes(topology, forcefield=self)
if not all([a.id for a in topology.atoms()][0]):
raise ValueError('Not all atoms in topology have atom types')
return topology
def createSystem(self, topology, nonbondedMethod=NoCutoff,
nonbondedCutoff=1.0 * u.nanometer, constraints=None,
rigidWater=True, removeCMMotion=True, hydrogenMass=None,
**args):
"""Construct an OpenMM System representing a Topology with this force field.
Parameters
----------
topology : Topology
The Topology for which to create a System
nonbondedMethod : object=NoCutoff
The method to use for nonbonded interactions. Allowed values are
NoCutoff, CutoffNonPeriodic, CutoffPeriodic, Ewald, or PME.
nonbondedCutoff : distance=1*nanometer
The cutoff distance to use for nonbonded interactions
constraints : object=None
Specifies which bonds and angles should be implemented with constraints.
Allowed values are None, HBonds, AllBonds, or HAngles.
rigidWater : boolean=True
If true, water molecules will be fully rigid regardless of the value
passed for the constraints argument
removeCMMotion : boolean=True
If true, a CMMotionRemover will be added to the System
hydrogenMass : mass=None
The mass to use for hydrogen atoms bound to heavy atoms. Any mass
added to a hydrogen is subtracted from the heavy atom to keep
their total mass the same.
args
Arbitrary additional keyword arguments may also be specified.
This allows extra parameters to be specified that are specific to
particular force fields.
Returns
-------
system
the newly created System
"""
# Overwrite previous _SystemData object
self._SystemData = app.ForceField._SystemData()
data = self._SystemData
data.atoms = list(topology.atoms())
for atom in data.atoms:
data.excludeAtomWith.append([])
# Make a list of all bonds
for bond in topology.bonds():
data.bonds.append(app.ForceField._BondData(bond[0].index, bond[1].index))
# Record which atoms are bonded to each other atom
bonded_to_atom = []
for i in range(len(data.atoms)):
bonded_to_atom.append(set())
data.atomBonds.append([])
for i in range(len(data.bonds)):
bond = data.bonds[i]
bonded_to_atom[bond.atom1].add(bond.atom2)
bonded_to_atom[bond.atom2].add(bond.atom1)
data.atomBonds[bond.atom1].append(i)
data.atomBonds[bond.atom2].append(i)
# TODO: Better way to lookup nonbonded parameters...?
nonbonded_params = None
for generator in self.getGenerators():
if isinstance(generator, NonbondedGenerator):
nonbonded_params = generator.params.paramsForType
break
for chain in topology.chains():
for res in chain.residues():
for atom in res.atoms():
data.atomType[atom] = atom.id
if nonbonded_params:
params = nonbonded_params[atom.id]
data.atomParameters[atom] = params
# Create the System and add atoms
sys = mm.System()
for atom in topology.atoms():
# Look up the atom type name, returning a helpful error message if it cannot be found.
if atom not in data.atomType:
raise Exception("Could not identify atom type for atom '%s'." % str(atom))
typename = data.atomType[atom]
# Look up the type name in the list of registered atom types, returning a helpful error message if it cannot be found.
if typename not in self._atomTypes:
msg = "Could not find typename '%s' for atom '%s' in list of known atom types.\n" % (typename, str(atom))
msg += "Known atom types are: %s" % str(self._atomTypes.keys())
raise Exception(msg)
# Add the particle to the OpenMM system.
mass = self._atomTypes[typename].mass
sys.addParticle(mass)
# Adjust hydrogen masses if requested.
if hydrogenMass is not None:
if not u.is_quantity(hydrogenMass):
hydrogenMass *= u.dalton
for atom1, atom2 in topology.bonds():
if atom1.element == elem.hydrogen:
(atom1, atom2) = (atom2, atom1)
if atom2.element == elem.hydrogen and atom1.element not in (elem.hydrogen, None):
transfer_mass = hydrogenMass - sys.getParticleMass(atom2.index)
sys.setParticleMass(atom2.index, hydrogenMass)
mass = sys.getParticleMass(atom1.index) - transfer_mass
sys.setParticleMass(atom1.index, mass)
# Set periodic boundary conditions.
box_vectors = topology.getPeriodicBoxVectors()
if box_vectors is not None:
sys.setDefaultPeriodicBoxVectors(box_vectors[0],
box_vectors[1],
box_vectors[2])
elif nonbondedMethod not in [NoCutoff, CutoffNonPeriodic]:
raise ValueError('Requested periodic boundary conditions for a '
'Topology that does not specify periodic box '
'dimensions')
# Make a list of all unique angles
unique_angles = set()
for bond in data.bonds:
for atom in bonded_to_atom[bond.atom1]:
if atom != bond.atom2:
if atom < bond.atom2:
unique_angles.add((atom, bond.atom1, bond.atom2))
else:
unique_angles.add((bond.atom2, bond.atom1, atom))
for atom in bonded_to_atom[bond.atom2]:
if atom != bond.atom1:
if atom > bond.atom1:
unique_angles.add((bond.atom1, bond.atom2, atom))
else:
unique_angles.add((atom, bond.atom2, bond.atom1))
data.angles = sorted(list(unique_angles))
# Make a list of all unique proper torsions
unique_propers = set()
for angle in data.angles:
for atom in bonded_to_atom[angle[0]]:
if atom not in angle:
if atom < angle[2]:
unique_propers.add((atom, angle[0], angle[1], angle[2]))
else:
unique_propers.add((angle[2], angle[1], angle[0], atom))
for atom in bonded_to_atom[angle[2]]:
if atom not in angle:
if atom > angle[0]:
unique_propers.add((angle[0], angle[1], angle[2], atom))
else:
unique_propers.add((atom, angle[2], angle[1], angle[0]))
data.propers = sorted(list(unique_propers))
# Make a list of all unique improper torsions
for atom in range(len(bonded_to_atom)):
bonded_to = bonded_to_atom[atom]
if len(bonded_to) > 2:
for subset in itertools.combinations(bonded_to, 3):
data.impropers.append((atom, subset[0], subset[1], subset[2]))
# Identify bonds that should be implemented with constraints
if constraints == AllBonds or constraints == HAngles:
for bond in data.bonds:
bond.isConstrained = True
elif constraints == HBonds:
for bond in data.bonds:
atom1 = data.atoms[bond.atom1]
atom2 = data.atoms[bond.atom2]
bond.isConstrained = atom1.name.startswith('H') or atom2.name.startswith('H')
if rigidWater:
for bond in data.bonds:
atom1 = data.atoms[bond.atom1]
atom2 = data.atoms[bond.atom2]
if atom1.residue.name == 'HOH' and atom2.residue.name == 'HOH':
bond.isConstrained = True
# Identify angles that should be implemented with constraints
if constraints == HAngles:
for angle in data.angles:
atom1 = data.atoms[angle[0]]
atom2 = data.atoms[angle[1]]
atom3 = data.atoms[angle[2]]
numH = 0
if atom1.name.startswith('H'):
numH += 1
if atom3.name.startswith('H'):
numH += 1
data.isAngleConstrained.append(numH == 2 or (numH == 1 and atom2.name.startswith('O')))
else:
data.isAngleConstrained = len(data.angles)*[False]
if rigidWater:
for i in range(len(data.angles)):
angle = data.angles[i]
atom1 = data.atoms[angle[0]]
atom2 = data.atoms[angle[1]]
atom3 = data.atoms[angle[2]]
if atom1.residue.name == 'HOH' and atom2.residue.name == 'HOH' and atom3.residue.name == 'HOH':
data.isAngleConstrained[i] = True
# Add virtual sites
for atom in data.virtualSites:
(site, atoms, excludeWith) = data.virtualSites[atom]
index = atom.index
data.excludeAtomWith[excludeWith].append(index)
if site.type == 'average2':
sys.setVirtualSite(index, mm.TwoParticleAverageSite(
atoms[0], atoms[1], site.weights[0], site.weights[1]))
elif site.type == 'average3':
sys.setVirtualSite(index, mm.ThreeParticleAverageSite(
atoms[0], atoms[1], atoms[2],
site.weights[0], site.weights[1], site.weights[2]))
elif site.type == 'outOfPlane':
sys.setVirtualSite(index, mm.OutOfPlaneSite(
atoms[0], atoms[1], atoms[2],
site.weights[0], site.weights[1], site.weights[2]))
elif site.type == 'localCoords':
local_coord_site = mm.LocalCoordinatesSite(
atoms[0], atoms[1], atoms[2],
mm.Vec3(site.originWeights[0], site.originWeights[1], site.originWeights[2]),
mm.Vec3(site.xWeights[0], site.xWeights[1], site.xWeights[2]),
mm.Vec3(site.yWeights[0], site.yWeights[1], site.yWeights[2]),
mm.Vec3(site.localPos[0], site.localPos[1], site.localPos[2]))
sys.setVirtualSite(index, local_coord_site)
# Add forces to the System
for force in self._forces:
force.createForce(sys, data, nonbondedMethod, nonbondedCutoff, args)
if removeCMMotion:
sys.addForce(mm.CMMotionRemover())
# Let force generators do postprocessing
for force in self._forces:
if 'postprocessSystem' in dir(force):
force.postprocessSystem(sys, data, args)
# Execute scripts found in the XML files.
for script in self._scripts:
exec(script, locals())
return sys
def _write_references_to_file(self, atom_types, references_file):
atomtype_references = {}
for atype in atom_types:
try:
atomtype_references[atype] = self.atomTypeRefs[atype]
except KeyError:
warnings.warn("Reference not found for atom type '{}'."
"".format(atype))
unique_references = collections.defaultdict(list)
for atomtype, dois in atomtype_references.items():
for doi in dois:
unique_references[doi].append(atomtype)
unique_references = collections.OrderedDict(sorted(unique_references.items()))
with open(references_file, 'w') as f:
for doi, atomtypes in unique_references.items():
url = "http://dx.doi.org/" + doi
headers = {"accept": "application/x-bibtex"}
bibtex_ref = requests.get(url, headers=headers).text
note = (',\n\tnote = {Parameters for atom types: ' +
', '.join(sorted(atomtypes)) + '}')
bibtex_ref = bibtex_ref[:-2] + note + bibtex_ref[-2:]
f.write('{}\n'.format(bibtex_ref))
|
mosdef-hub/foyer | foyer/forcefield.py | Forcefield.apply | python | def apply(self, topology, references_file=None, use_residue_map=True,
assert_bond_params=True, assert_angle_params=True,
assert_dihedral_params=True, assert_improper_params=False,
*args, **kwargs):
if self.atomTypeDefinitions == {}:
raise FoyerError('Attempting to atom-type using a force field '
'with no atom type defitions.')
if not isinstance(topology, app.Topology):
residues = kwargs.get('residues')
topology, positions = generate_topology(topology,
self.non_element_types, residues=residues)
else:
positions = np.empty(shape=(topology.getNumAtoms(), 3))
positions[:] = np.nan
box_vectors = topology.getPeriodicBoxVectors()
topology = self.run_atomtyping(topology, use_residue_map=use_residue_map)
system = self.createSystem(topology, *args, **kwargs)
structure = pmd.openmm.load_topology(topology=topology, system=system)
'''
Check that all topology objects (angles, dihedrals, and impropers)
have parameters assigned. OpenMM will generate an error if bond parameters
are not assigned.
'''
data = self._SystemData
if data.bonds:
missing = [b for b in structure.bonds
if b.type is None]
if missing:
nmissing = len(structure.bonds) - len(missing)
msg = ("Parameters have not been assigned to all bonds. "
"Total system bonds: {}, Parametrized bonds: {}"
"".format(len(structure.bonds), nmissing))
_error_or_warn(assert_bond_params, msg)
if data.angles and (len(data.angles) != len(structure.angles)):
msg = ("Parameters have not been assigned to all angles. Total "
"system angles: {}, Parameterized angles: {}"
"".format(len(data.angles), len(structure.angles)))
_error_or_warn(assert_angle_params, msg)
proper_dihedrals = [dihedral for dihedral in structure.dihedrals
if not dihedral.improper]
if data.propers and len(data.propers) != \
len(proper_dihedrals) + len(structure.rb_torsions):
msg = ("Parameters have not been assigned to all proper dihedrals. "
"Total system dihedrals: {}, Parameterized dihedrals: {}. "
"Note that if your system contains torsions of Ryckaert-"
"Bellemans functional form, all of these torsions are "
"processed as propers.".format(len(data.propers),
len(proper_dihedrals) + len(structure.rb_torsions)))
_error_or_warn(assert_dihedral_params, msg)
improper_dihedrals = [dihedral for dihedral in structure.dihedrals
if dihedral.improper]
if data.impropers and len(data.impropers) != \
len(improper_dihedrals) + len(structure.impropers):
msg = ("Parameters have not been assigned to all impropers. Total "
"system impropers: {}, Parameterized impropers: {}. "
"Note that if your system contains torsions of Ryckaert-"
"Bellemans functional form, all of these torsions are "
"processed as propers".format(len(data.impropers),
len(improper_dihedrals) + len(structure.impropers)))
_error_or_warn(assert_improper_params, msg)
structure.bonds.sort(key=lambda x: x.atom1.idx)
structure.positions = positions
if box_vectors is not None:
structure.box_vectors = box_vectors
if references_file:
atom_types = set(atom.type for atom in structure.atoms)
self._write_references_to_file(atom_types, references_file)
return structure | Apply the force field to a molecular structure
Parameters
----------
topology : openmm.app.Topology or parmed.Structure or mbuild.Compound
Molecular structure to apply the force field to
references_file : str, optional, default=None
Name of file where force field references will be written (in Bibtex
format)
use_residue_map : boolean, optional, default=True
Store atomtyped topologies of residues to a dictionary that maps
them to residue names. Each topology, including atomtypes, will be
copied to other residues with the same name. This avoids repeatedly
calling the subgraph isomorphism on idential residues and should
result in better performance for systems with many identical
residues, i.e. a box of water. Note that for this to be applied to
independent molecules, they must each be saved as different
residues in the topology.
assert_bond_params : bool, optional, default=True
If True, Foyer will exit if parameters are not found for all system
bonds.
assert_angle_params : bool, optional, default=True
If True, Foyer will exit if parameters are not found for all system
angles.
assert_dihedral_params : bool, optional, default=True
If True, Foyer will exit if parameters are not found for all system
proper dihedrals.
assert_improper_params : bool, optional, default=False
If True, Foyer will exit if parameters are not found for all system
improper dihedrals. | train | https://github.com/mosdef-hub/foyer/blob/9e39c71208fc01a6cc7b7cbe5a533c56830681d3/foyer/forcefield.py#L343-L450 | [
"def generate_topology(non_omm_topology, non_element_types=None,\n residues=None):\n \"\"\"Create an OpenMM Topology from another supported topology structure.\"\"\"\n if non_element_types is None:\n non_element_types = set()\n\n if isinstance(non_omm_topology, pmd.Structure):\n return _topology_from_parmed(non_omm_topology, non_element_types)\n elif has_mbuild:\n mb = import_('mbuild')\n if (non_omm_topology, mb.Compound):\n pmdCompoundStructure = non_omm_topology.to_parmed(residues=residues)\n return _topology_from_parmed(pmdCompoundStructure, non_element_types)\n else:\n raise FoyerError('Unknown topology format: {}\\n'\n 'Supported formats are: '\n '\"parmed.Structure\", '\n '\"mbuild.Compound\", '\n '\"openmm.app.Topology\"'.format(non_omm_topology))\n",
"def _error_or_warn(error, msg):\n \"\"\"Raise an error or warning if topology objects are not fully parameterized.\n\n Parameters\n ----------\n error : bool\n If True, raise an error, else raise a warning\n msg : str\n The message to be provided with the error or warning\n \"\"\"\n if error:\n raise Exception(msg)\n else:\n warnings.warn(msg)\n",
"def run_atomtyping(self, topology, use_residue_map=True):\n \"\"\"Atomtype the topology\n\n Parameters\n ----------\n topology : openmm.app.Topology\n Molecular structure to find atom types of\n use_residue_map : boolean, optional, default=True\n Store atomtyped topologies of residues to a dictionary that maps\n them to residue names. Each topology, including atomtypes, will be\n copied to other residues with the same name. This avoids repeatedly\n calling the subgraph isomorphism on idential residues and should\n result in better performance for systems with many identical\n residues, i.e. a box of water. Note that for this to be applied to\n independent molecules, they must each be saved as different\n residues in the topology.\n \"\"\"\n if use_residue_map:\n independent_residues = _check_independent_residues(topology)\n\n if independent_residues:\n residue_map = dict()\n\n for res in topology.residues():\n if res.name not in residue_map.keys():\n residue = _topology_from_residue(res)\n find_atomtypes(residue, forcefield=self)\n residue_map[res.name] = residue\n\n for key, val in residue_map.items():\n _update_atomtypes(topology, key, val)\n\n else:\n find_atomtypes(topology, forcefield=self)\n\n else:\n find_atomtypes(topology, forcefield=self)\n\n if not all([a.id for a in topology.atoms()][0]):\n raise ValueError('Not all atoms in topology have atom types')\n\n return topology\n",
"def createSystem(self, topology, nonbondedMethod=NoCutoff,\n nonbondedCutoff=1.0 * u.nanometer, constraints=None,\n rigidWater=True, removeCMMotion=True, hydrogenMass=None,\n **args):\n \"\"\"Construct an OpenMM System representing a Topology with this force field.\n\n Parameters\n ----------\n topology : Topology\n The Topology for which to create a System\n nonbondedMethod : object=NoCutoff\n The method to use for nonbonded interactions. Allowed values are\n NoCutoff, CutoffNonPeriodic, CutoffPeriodic, Ewald, or PME.\n nonbondedCutoff : distance=1*nanometer\n The cutoff distance to use for nonbonded interactions\n constraints : object=None\n Specifies which bonds and angles should be implemented with constraints.\n Allowed values are None, HBonds, AllBonds, or HAngles.\n rigidWater : boolean=True\n If true, water molecules will be fully rigid regardless of the value\n passed for the constraints argument\n removeCMMotion : boolean=True\n If true, a CMMotionRemover will be added to the System\n hydrogenMass : mass=None\n The mass to use for hydrogen atoms bound to heavy atoms. Any mass\n added to a hydrogen is subtracted from the heavy atom to keep\n their total mass the same.\n args\n Arbitrary additional keyword arguments may also be specified.\n This allows extra parameters to be specified that are specific to\n particular force fields.\n\n Returns\n -------\n system\n the newly created System\n \"\"\"\n\n # Overwrite previous _SystemData object\n self._SystemData = app.ForceField._SystemData()\n\n data = self._SystemData\n data.atoms = list(topology.atoms())\n for atom in data.atoms:\n data.excludeAtomWith.append([])\n\n # Make a list of all bonds\n for bond in topology.bonds():\n data.bonds.append(app.ForceField._BondData(bond[0].index, bond[1].index))\n\n # Record which atoms are bonded to each other atom\n bonded_to_atom = []\n for i in range(len(data.atoms)):\n bonded_to_atom.append(set())\n data.atomBonds.append([])\n for i in range(len(data.bonds)):\n bond = data.bonds[i]\n bonded_to_atom[bond.atom1].add(bond.atom2)\n bonded_to_atom[bond.atom2].add(bond.atom1)\n data.atomBonds[bond.atom1].append(i)\n data.atomBonds[bond.atom2].append(i)\n\n # TODO: Better way to lookup nonbonded parameters...?\n nonbonded_params = None\n for generator in self.getGenerators():\n if isinstance(generator, NonbondedGenerator):\n nonbonded_params = generator.params.paramsForType\n break\n\n for chain in topology.chains():\n for res in chain.residues():\n for atom in res.atoms():\n data.atomType[atom] = atom.id\n if nonbonded_params:\n params = nonbonded_params[atom.id]\n data.atomParameters[atom] = params\n\n # Create the System and add atoms\n sys = mm.System()\n for atom in topology.atoms():\n # Look up the atom type name, returning a helpful error message if it cannot be found.\n if atom not in data.atomType:\n raise Exception(\"Could not identify atom type for atom '%s'.\" % str(atom))\n typename = data.atomType[atom]\n\n # Look up the type name in the list of registered atom types, returning a helpful error message if it cannot be found.\n if typename not in self._atomTypes:\n msg = \"Could not find typename '%s' for atom '%s' in list of known atom types.\\n\" % (typename, str(atom))\n msg += \"Known atom types are: %s\" % str(self._atomTypes.keys())\n raise Exception(msg)\n\n # Add the particle to the OpenMM system.\n mass = self._atomTypes[typename].mass\n sys.addParticle(mass)\n\n # Adjust hydrogen masses if requested.\n if hydrogenMass is not None:\n if not u.is_quantity(hydrogenMass):\n hydrogenMass *= u.dalton\n for atom1, atom2 in topology.bonds():\n if atom1.element == elem.hydrogen:\n (atom1, atom2) = (atom2, atom1)\n if atom2.element == elem.hydrogen and atom1.element not in (elem.hydrogen, None):\n transfer_mass = hydrogenMass - sys.getParticleMass(atom2.index)\n sys.setParticleMass(atom2.index, hydrogenMass)\n mass = sys.getParticleMass(atom1.index) - transfer_mass\n sys.setParticleMass(atom1.index, mass)\n\n # Set periodic boundary conditions.\n box_vectors = topology.getPeriodicBoxVectors()\n if box_vectors is not None:\n sys.setDefaultPeriodicBoxVectors(box_vectors[0],\n box_vectors[1],\n box_vectors[2])\n elif nonbondedMethod not in [NoCutoff, CutoffNonPeriodic]:\n raise ValueError('Requested periodic boundary conditions for a '\n 'Topology that does not specify periodic box '\n 'dimensions')\n\n # Make a list of all unique angles\n unique_angles = set()\n for bond in data.bonds:\n for atom in bonded_to_atom[bond.atom1]:\n if atom != bond.atom2:\n if atom < bond.atom2:\n unique_angles.add((atom, bond.atom1, bond.atom2))\n else:\n unique_angles.add((bond.atom2, bond.atom1, atom))\n for atom in bonded_to_atom[bond.atom2]:\n if atom != bond.atom1:\n if atom > bond.atom1:\n unique_angles.add((bond.atom1, bond.atom2, atom))\n else:\n unique_angles.add((atom, bond.atom2, bond.atom1))\n data.angles = sorted(list(unique_angles))\n\n # Make a list of all unique proper torsions\n unique_propers = set()\n for angle in data.angles:\n for atom in bonded_to_atom[angle[0]]:\n if atom not in angle:\n if atom < angle[2]:\n unique_propers.add((atom, angle[0], angle[1], angle[2]))\n else:\n unique_propers.add((angle[2], angle[1], angle[0], atom))\n for atom in bonded_to_atom[angle[2]]:\n if atom not in angle:\n if atom > angle[0]:\n unique_propers.add((angle[0], angle[1], angle[2], atom))\n else:\n unique_propers.add((atom, angle[2], angle[1], angle[0]))\n data.propers = sorted(list(unique_propers))\n\n # Make a list of all unique improper torsions\n for atom in range(len(bonded_to_atom)):\n bonded_to = bonded_to_atom[atom]\n if len(bonded_to) > 2:\n for subset in itertools.combinations(bonded_to, 3):\n data.impropers.append((atom, subset[0], subset[1], subset[2]))\n\n # Identify bonds that should be implemented with constraints\n if constraints == AllBonds or constraints == HAngles:\n for bond in data.bonds:\n bond.isConstrained = True\n elif constraints == HBonds:\n for bond in data.bonds:\n atom1 = data.atoms[bond.atom1]\n atom2 = data.atoms[bond.atom2]\n bond.isConstrained = atom1.name.startswith('H') or atom2.name.startswith('H')\n if rigidWater:\n for bond in data.bonds:\n atom1 = data.atoms[bond.atom1]\n atom2 = data.atoms[bond.atom2]\n if atom1.residue.name == 'HOH' and atom2.residue.name == 'HOH':\n bond.isConstrained = True\n\n # Identify angles that should be implemented with constraints\n if constraints == HAngles:\n for angle in data.angles:\n atom1 = data.atoms[angle[0]]\n atom2 = data.atoms[angle[1]]\n atom3 = data.atoms[angle[2]]\n numH = 0\n if atom1.name.startswith('H'):\n numH += 1\n if atom3.name.startswith('H'):\n numH += 1\n data.isAngleConstrained.append(numH == 2 or (numH == 1 and atom2.name.startswith('O')))\n else:\n data.isAngleConstrained = len(data.angles)*[False]\n if rigidWater:\n for i in range(len(data.angles)):\n angle = data.angles[i]\n atom1 = data.atoms[angle[0]]\n atom2 = data.atoms[angle[1]]\n atom3 = data.atoms[angle[2]]\n if atom1.residue.name == 'HOH' and atom2.residue.name == 'HOH' and atom3.residue.name == 'HOH':\n data.isAngleConstrained[i] = True\n\n # Add virtual sites\n for atom in data.virtualSites:\n (site, atoms, excludeWith) = data.virtualSites[atom]\n index = atom.index\n data.excludeAtomWith[excludeWith].append(index)\n if site.type == 'average2':\n sys.setVirtualSite(index, mm.TwoParticleAverageSite(\n atoms[0], atoms[1], site.weights[0], site.weights[1]))\n elif site.type == 'average3':\n sys.setVirtualSite(index, mm.ThreeParticleAverageSite(\n atoms[0], atoms[1], atoms[2],\n site.weights[0], site.weights[1], site.weights[2]))\n elif site.type == 'outOfPlane':\n sys.setVirtualSite(index, mm.OutOfPlaneSite(\n atoms[0], atoms[1], atoms[2],\n site.weights[0], site.weights[1], site.weights[2]))\n elif site.type == 'localCoords':\n local_coord_site = mm.LocalCoordinatesSite(\n atoms[0], atoms[1], atoms[2],\n mm.Vec3(site.originWeights[0], site.originWeights[1], site.originWeights[2]),\n mm.Vec3(site.xWeights[0], site.xWeights[1], site.xWeights[2]),\n mm.Vec3(site.yWeights[0], site.yWeights[1], site.yWeights[2]),\n mm.Vec3(site.localPos[0], site.localPos[1], site.localPos[2]))\n sys.setVirtualSite(index, local_coord_site)\n\n # Add forces to the System\n for force in self._forces:\n force.createForce(sys, data, nonbondedMethod, nonbondedCutoff, args)\n if removeCMMotion:\n sys.addForce(mm.CMMotionRemover())\n\n # Let force generators do postprocessing\n for force in self._forces:\n if 'postprocessSystem' in dir(force):\n force.postprocessSystem(sys, data, args)\n\n # Execute scripts found in the XML files.\n for script in self._scripts:\n exec(script, locals())\n\n return sys\n",
"def _write_references_to_file(self, atom_types, references_file):\n atomtype_references = {}\n for atype in atom_types:\n try:\n atomtype_references[atype] = self.atomTypeRefs[atype]\n except KeyError:\n warnings.warn(\"Reference not found for atom type '{}'.\"\n \"\".format(atype))\n unique_references = collections.defaultdict(list)\n for atomtype, dois in atomtype_references.items():\n for doi in dois:\n unique_references[doi].append(atomtype)\n unique_references = collections.OrderedDict(sorted(unique_references.items()))\n with open(references_file, 'w') as f:\n for doi, atomtypes in unique_references.items():\n url = \"http://dx.doi.org/\" + doi\n headers = {\"accept\": \"application/x-bibtex\"}\n bibtex_ref = requests.get(url, headers=headers).text\n note = (',\\n\\tnote = {Parameters for atom types: ' +\n ', '.join(sorted(atomtypes)) + '}')\n bibtex_ref = bibtex_ref[:-2] + note + bibtex_ref[-2:]\n f.write('{}\\n'.format(bibtex_ref))\n"
] | class Forcefield(app.ForceField):
"""Specialization of OpenMM's Forcefield allowing SMARTS based atomtyping.
Parameters
----------
forcefield_files : list of str, optional, default=None
List of forcefield files to load.
name : str, optional, default=None
Name of a forcefield to load that is packaged within foyer.
"""
def __init__(self, forcefield_files=None, name=None, validation=True, debug=False):
self.atomTypeDefinitions = dict()
self.atomTypeOverrides = dict()
self.atomTypeDesc = dict()
self.atomTypeRefs = dict()
self._included_forcefields = dict()
self.non_element_types = dict()
all_files_to_load = []
if forcefield_files is not None:
if isinstance(forcefield_files, (list, tuple, set)):
for file in forcefield_files:
all_files_to_load.append(file)
else:
all_files_to_load.append(forcefield_files)
if name is not None:
try:
file = self.included_forcefields[name]
except KeyError:
raise IOError('Forcefield {} cannot be found'.format(name))
else:
all_files_to_load.append(file)
preprocessed_files = preprocess_forcefield_files(all_files_to_load)
if validation:
for ff_file_name in preprocessed_files:
Validator(ff_file_name, debug)
super(Forcefield, self).__init__(*preprocessed_files)
self.parser = smarts.SMARTS(self.non_element_types)
self._SystemData = self._SystemData()
@property
def included_forcefields(self):
if any(self._included_forcefields):
return self._included_forcefields
ff_dir = resource_filename('foyer', 'forcefields')
ff_filepaths = set(glob.glob(os.path.join(ff_dir, '*.xml')))
for ff_filepath in ff_filepaths:
_, ff_file = os.path.split(ff_filepath)
basename, _ = os.path.splitext(ff_file)
self._included_forcefields[basename] = ff_filepath
return self._included_forcefields
def _create_element(self, element, mass):
if not isinstance(element, elem.Element):
try:
element = elem.get_by_symbol(element)
except KeyError:
# Enables support for non-atomistic "element types"
if element not in self.non_element_types:
warnings.warn('Non-atomistic element type detected. '
'Creating custom element for {}'.format(element))
element = custom_elem.Element(number=0,
mass=mass,
name=element,
symbol=element)
else:
return element, False
return element, True
def registerAtomType(self, parameters):
"""Register a new atom type. """
name = parameters['name']
if name in self._atomTypes:
raise ValueError('Found multiple definitions for atom type: ' + name)
atom_class = parameters['class']
mass = _convertParameterToNumber(parameters['mass'])
element = None
if 'element' in parameters:
element, custom = self._create_element(parameters['element'], mass)
if custom:
self.non_element_types[element.symbol] = element
self._atomTypes[name] = self.__class__._AtomType(name, atom_class, mass, element)
if atom_class in self._atomClasses:
type_set = self._atomClasses[atom_class]
else:
type_set = set()
self._atomClasses[atom_class] = type_set
type_set.add(name)
self._atomClasses[''].add(name)
name = parameters['name']
if 'def' in parameters:
self.atomTypeDefinitions[name] = parameters['def']
if 'overrides' in parameters:
overrides = set(atype.strip() for atype
in parameters['overrides'].split(","))
if overrides:
self.atomTypeOverrides[name] = overrides
if 'des' in parameters:
self.atomTypeDesc[name] = parameters['desc']
if 'doi' in parameters:
dois = set(doi.strip() for doi in parameters['doi'].split(','))
self.atomTypeRefs[name] = dois
def run_atomtyping(self, topology, use_residue_map=True):
"""Atomtype the topology
Parameters
----------
topology : openmm.app.Topology
Molecular structure to find atom types of
use_residue_map : boolean, optional, default=True
Store atomtyped topologies of residues to a dictionary that maps
them to residue names. Each topology, including atomtypes, will be
copied to other residues with the same name. This avoids repeatedly
calling the subgraph isomorphism on idential residues and should
result in better performance for systems with many identical
residues, i.e. a box of water. Note that for this to be applied to
independent molecules, they must each be saved as different
residues in the topology.
"""
if use_residue_map:
independent_residues = _check_independent_residues(topology)
if independent_residues:
residue_map = dict()
for res in topology.residues():
if res.name not in residue_map.keys():
residue = _topology_from_residue(res)
find_atomtypes(residue, forcefield=self)
residue_map[res.name] = residue
for key, val in residue_map.items():
_update_atomtypes(topology, key, val)
else:
find_atomtypes(topology, forcefield=self)
else:
find_atomtypes(topology, forcefield=self)
if not all([a.id for a in topology.atoms()][0]):
raise ValueError('Not all atoms in topology have atom types')
return topology
def createSystem(self, topology, nonbondedMethod=NoCutoff,
nonbondedCutoff=1.0 * u.nanometer, constraints=None,
rigidWater=True, removeCMMotion=True, hydrogenMass=None,
**args):
"""Construct an OpenMM System representing a Topology with this force field.
Parameters
----------
topology : Topology
The Topology for which to create a System
nonbondedMethod : object=NoCutoff
The method to use for nonbonded interactions. Allowed values are
NoCutoff, CutoffNonPeriodic, CutoffPeriodic, Ewald, or PME.
nonbondedCutoff : distance=1*nanometer
The cutoff distance to use for nonbonded interactions
constraints : object=None
Specifies which bonds and angles should be implemented with constraints.
Allowed values are None, HBonds, AllBonds, or HAngles.
rigidWater : boolean=True
If true, water molecules will be fully rigid regardless of the value
passed for the constraints argument
removeCMMotion : boolean=True
If true, a CMMotionRemover will be added to the System
hydrogenMass : mass=None
The mass to use for hydrogen atoms bound to heavy atoms. Any mass
added to a hydrogen is subtracted from the heavy atom to keep
their total mass the same.
args
Arbitrary additional keyword arguments may also be specified.
This allows extra parameters to be specified that are specific to
particular force fields.
Returns
-------
system
the newly created System
"""
# Overwrite previous _SystemData object
self._SystemData = app.ForceField._SystemData()
data = self._SystemData
data.atoms = list(topology.atoms())
for atom in data.atoms:
data.excludeAtomWith.append([])
# Make a list of all bonds
for bond in topology.bonds():
data.bonds.append(app.ForceField._BondData(bond[0].index, bond[1].index))
# Record which atoms are bonded to each other atom
bonded_to_atom = []
for i in range(len(data.atoms)):
bonded_to_atom.append(set())
data.atomBonds.append([])
for i in range(len(data.bonds)):
bond = data.bonds[i]
bonded_to_atom[bond.atom1].add(bond.atom2)
bonded_to_atom[bond.atom2].add(bond.atom1)
data.atomBonds[bond.atom1].append(i)
data.atomBonds[bond.atom2].append(i)
# TODO: Better way to lookup nonbonded parameters...?
nonbonded_params = None
for generator in self.getGenerators():
if isinstance(generator, NonbondedGenerator):
nonbonded_params = generator.params.paramsForType
break
for chain in topology.chains():
for res in chain.residues():
for atom in res.atoms():
data.atomType[atom] = atom.id
if nonbonded_params:
params = nonbonded_params[atom.id]
data.atomParameters[atom] = params
# Create the System and add atoms
sys = mm.System()
for atom in topology.atoms():
# Look up the atom type name, returning a helpful error message if it cannot be found.
if atom not in data.atomType:
raise Exception("Could not identify atom type for atom '%s'." % str(atom))
typename = data.atomType[atom]
# Look up the type name in the list of registered atom types, returning a helpful error message if it cannot be found.
if typename not in self._atomTypes:
msg = "Could not find typename '%s' for atom '%s' in list of known atom types.\n" % (typename, str(atom))
msg += "Known atom types are: %s" % str(self._atomTypes.keys())
raise Exception(msg)
# Add the particle to the OpenMM system.
mass = self._atomTypes[typename].mass
sys.addParticle(mass)
# Adjust hydrogen masses if requested.
if hydrogenMass is not None:
if not u.is_quantity(hydrogenMass):
hydrogenMass *= u.dalton
for atom1, atom2 in topology.bonds():
if atom1.element == elem.hydrogen:
(atom1, atom2) = (atom2, atom1)
if atom2.element == elem.hydrogen and atom1.element not in (elem.hydrogen, None):
transfer_mass = hydrogenMass - sys.getParticleMass(atom2.index)
sys.setParticleMass(atom2.index, hydrogenMass)
mass = sys.getParticleMass(atom1.index) - transfer_mass
sys.setParticleMass(atom1.index, mass)
# Set periodic boundary conditions.
box_vectors = topology.getPeriodicBoxVectors()
if box_vectors is not None:
sys.setDefaultPeriodicBoxVectors(box_vectors[0],
box_vectors[1],
box_vectors[2])
elif nonbondedMethod not in [NoCutoff, CutoffNonPeriodic]:
raise ValueError('Requested periodic boundary conditions for a '
'Topology that does not specify periodic box '
'dimensions')
# Make a list of all unique angles
unique_angles = set()
for bond in data.bonds:
for atom in bonded_to_atom[bond.atom1]:
if atom != bond.atom2:
if atom < bond.atom2:
unique_angles.add((atom, bond.atom1, bond.atom2))
else:
unique_angles.add((bond.atom2, bond.atom1, atom))
for atom in bonded_to_atom[bond.atom2]:
if atom != bond.atom1:
if atom > bond.atom1:
unique_angles.add((bond.atom1, bond.atom2, atom))
else:
unique_angles.add((atom, bond.atom2, bond.atom1))
data.angles = sorted(list(unique_angles))
# Make a list of all unique proper torsions
unique_propers = set()
for angle in data.angles:
for atom in bonded_to_atom[angle[0]]:
if atom not in angle:
if atom < angle[2]:
unique_propers.add((atom, angle[0], angle[1], angle[2]))
else:
unique_propers.add((angle[2], angle[1], angle[0], atom))
for atom in bonded_to_atom[angle[2]]:
if atom not in angle:
if atom > angle[0]:
unique_propers.add((angle[0], angle[1], angle[2], atom))
else:
unique_propers.add((atom, angle[2], angle[1], angle[0]))
data.propers = sorted(list(unique_propers))
# Make a list of all unique improper torsions
for atom in range(len(bonded_to_atom)):
bonded_to = bonded_to_atom[atom]
if len(bonded_to) > 2:
for subset in itertools.combinations(bonded_to, 3):
data.impropers.append((atom, subset[0], subset[1], subset[2]))
# Identify bonds that should be implemented with constraints
if constraints == AllBonds or constraints == HAngles:
for bond in data.bonds:
bond.isConstrained = True
elif constraints == HBonds:
for bond in data.bonds:
atom1 = data.atoms[bond.atom1]
atom2 = data.atoms[bond.atom2]
bond.isConstrained = atom1.name.startswith('H') or atom2.name.startswith('H')
if rigidWater:
for bond in data.bonds:
atom1 = data.atoms[bond.atom1]
atom2 = data.atoms[bond.atom2]
if atom1.residue.name == 'HOH' and atom2.residue.name == 'HOH':
bond.isConstrained = True
# Identify angles that should be implemented with constraints
if constraints == HAngles:
for angle in data.angles:
atom1 = data.atoms[angle[0]]
atom2 = data.atoms[angle[1]]
atom3 = data.atoms[angle[2]]
numH = 0
if atom1.name.startswith('H'):
numH += 1
if atom3.name.startswith('H'):
numH += 1
data.isAngleConstrained.append(numH == 2 or (numH == 1 and atom2.name.startswith('O')))
else:
data.isAngleConstrained = len(data.angles)*[False]
if rigidWater:
for i in range(len(data.angles)):
angle = data.angles[i]
atom1 = data.atoms[angle[0]]
atom2 = data.atoms[angle[1]]
atom3 = data.atoms[angle[2]]
if atom1.residue.name == 'HOH' and atom2.residue.name == 'HOH' and atom3.residue.name == 'HOH':
data.isAngleConstrained[i] = True
# Add virtual sites
for atom in data.virtualSites:
(site, atoms, excludeWith) = data.virtualSites[atom]
index = atom.index
data.excludeAtomWith[excludeWith].append(index)
if site.type == 'average2':
sys.setVirtualSite(index, mm.TwoParticleAverageSite(
atoms[0], atoms[1], site.weights[0], site.weights[1]))
elif site.type == 'average3':
sys.setVirtualSite(index, mm.ThreeParticleAverageSite(
atoms[0], atoms[1], atoms[2],
site.weights[0], site.weights[1], site.weights[2]))
elif site.type == 'outOfPlane':
sys.setVirtualSite(index, mm.OutOfPlaneSite(
atoms[0], atoms[1], atoms[2],
site.weights[0], site.weights[1], site.weights[2]))
elif site.type == 'localCoords':
local_coord_site = mm.LocalCoordinatesSite(
atoms[0], atoms[1], atoms[2],
mm.Vec3(site.originWeights[0], site.originWeights[1], site.originWeights[2]),
mm.Vec3(site.xWeights[0], site.xWeights[1], site.xWeights[2]),
mm.Vec3(site.yWeights[0], site.yWeights[1], site.yWeights[2]),
mm.Vec3(site.localPos[0], site.localPos[1], site.localPos[2]))
sys.setVirtualSite(index, local_coord_site)
# Add forces to the System
for force in self._forces:
force.createForce(sys, data, nonbondedMethod, nonbondedCutoff, args)
if removeCMMotion:
sys.addForce(mm.CMMotionRemover())
# Let force generators do postprocessing
for force in self._forces:
if 'postprocessSystem' in dir(force):
force.postprocessSystem(sys, data, args)
# Execute scripts found in the XML files.
for script in self._scripts:
exec(script, locals())
return sys
def _write_references_to_file(self, atom_types, references_file):
atomtype_references = {}
for atype in atom_types:
try:
atomtype_references[atype] = self.atomTypeRefs[atype]
except KeyError:
warnings.warn("Reference not found for atom type '{}'."
"".format(atype))
unique_references = collections.defaultdict(list)
for atomtype, dois in atomtype_references.items():
for doi in dois:
unique_references[doi].append(atomtype)
unique_references = collections.OrderedDict(sorted(unique_references.items()))
with open(references_file, 'w') as f:
for doi, atomtypes in unique_references.items():
url = "http://dx.doi.org/" + doi
headers = {"accept": "application/x-bibtex"}
bibtex_ref = requests.get(url, headers=headers).text
note = (',\n\tnote = {Parameters for atom types: ' +
', '.join(sorted(atomtypes)) + '}')
bibtex_ref = bibtex_ref[:-2] + note + bibtex_ref[-2:]
f.write('{}\n'.format(bibtex_ref))
|
mosdef-hub/foyer | foyer/forcefield.py | Forcefield.run_atomtyping | python | def run_atomtyping(self, topology, use_residue_map=True):
if use_residue_map:
independent_residues = _check_independent_residues(topology)
if independent_residues:
residue_map = dict()
for res in topology.residues():
if res.name not in residue_map.keys():
residue = _topology_from_residue(res)
find_atomtypes(residue, forcefield=self)
residue_map[res.name] = residue
for key, val in residue_map.items():
_update_atomtypes(topology, key, val)
else:
find_atomtypes(topology, forcefield=self)
else:
find_atomtypes(topology, forcefield=self)
if not all([a.id for a in topology.atoms()][0]):
raise ValueError('Not all atoms in topology have atom types')
return topology | Atomtype the topology
Parameters
----------
topology : openmm.app.Topology
Molecular structure to find atom types of
use_residue_map : boolean, optional, default=True
Store atomtyped topologies of residues to a dictionary that maps
them to residue names. Each topology, including atomtypes, will be
copied to other residues with the same name. This avoids repeatedly
calling the subgraph isomorphism on idential residues and should
result in better performance for systems with many identical
residues, i.e. a box of water. Note that for this to be applied to
independent molecules, they must each be saved as different
residues in the topology. | train | https://github.com/mosdef-hub/foyer/blob/9e39c71208fc01a6cc7b7cbe5a533c56830681d3/foyer/forcefield.py#L452-L493 | [
"def find_atomtypes(topology, forcefield, max_iter=10):\n \"\"\"Determine atomtypes for all atoms.\n\n Parameters\n ----------\n topology : simtk.openmm.app.Topology\n The topology that we are trying to atomtype.\n forcefield : foyer.Forcefield\n The forcefield object.\n max_iter : int, optional, default=10\n The maximum number of iterations.\n\n \"\"\"\n rules = _load_rules(forcefield)\n\n # Only consider rules for elements found in topology\n subrules = dict()\n system_elements = {a.element.symbol for a in topology.atoms()}\n for key,val in rules.items():\n atom = val.node[0]['atom']\n if len(atom.select('atom_symbol')) == 1 and not atom.select('not_expression'):\n try:\n element = atom.select('atom_symbol').strees[0].tail[0]\n except IndexError:\n try:\n atomic_num = atom.select('atomic_num').strees[0].tail[0]\n element = pt.Element[int(atomic_num)]\n except IndexError:\n element = None\n else:\n element = None\n if element is None or element in system_elements:\n subrules[key] = val\n rules = subrules\n\n _iterate_rules(rules, topology, max_iter=max_iter)\n _resolve_atomtypes(topology)\n",
"def _topology_from_residue(res):\n \"\"\"Converts a openmm.app.Topology.Residue to openmm.app.Topology.\n\n Parameters\n ----------\n res : openmm.app.Topology.Residue\n An individual residue in an openmm.app.Topology\n\n Returns\n -------\n topology : openmm.app.Topology\n The generated topology\n\n \"\"\"\n topology = app.Topology()\n chain = topology.addChain()\n new_res = topology.addResidue(res.name, chain)\n\n atoms = dict() # { omm.Atom in res : omm.Atom in *new* topology }\n\n for res_atom in res.atoms():\n topology_atom = topology.addAtom(name=res_atom.name,\n element=res_atom.element,\n residue=new_res)\n atoms[res_atom] = topology_atom\n topology_atom.bond_partners = []\n\n for bond in res.bonds():\n atom1 = atoms[bond.atom1]\n atom2 = atoms[bond.atom2]\n topology.addBond(atom1, atom2)\n atom1.bond_partners.append(atom2)\n atom2.bond_partners.append(atom1)\n\n return topology\n",
"def _check_independent_residues(topology):\n \"\"\"Check to see if residues will constitute independent graphs.\"\"\"\n for res in topology.residues():\n atoms_in_residue = set([atom for atom in res.atoms()])\n bond_partners_in_residue = [item for sublist in [atom.bond_partners for atom in res.atoms()] for item in sublist]\n # Handle the case of a 'residue' with no neighbors\n if not bond_partners_in_residue:\n continue\n if set(atoms_in_residue) != set(bond_partners_in_residue):\n return False\n return True\n",
"def _update_atomtypes(unatomtyped_topology, res_name, prototype):\n \"\"\"Update atomtypes in residues in a topology using a prototype topology.\n\n Atomtypes are updated when residues in each topology have matching names.\n\n Parameters\n ----------\n unatomtyped_topology : openmm.app.Topology\n Topology lacking atomtypes defined by `find_atomtypes`.\n prototype : openmm.app.Topology\n Prototype topology with atomtypes defined by `find_atomtypes`.\n\n \"\"\"\n for res in unatomtyped_topology.residues():\n if res.name == res_name:\n for old_atom, new_atom_id in zip([atom for atom in res.atoms()], [atom.id for atom in prototype.atoms()]):\n old_atom.id = new_atom_id\n"
] | class Forcefield(app.ForceField):
"""Specialization of OpenMM's Forcefield allowing SMARTS based atomtyping.
Parameters
----------
forcefield_files : list of str, optional, default=None
List of forcefield files to load.
name : str, optional, default=None
Name of a forcefield to load that is packaged within foyer.
"""
def __init__(self, forcefield_files=None, name=None, validation=True, debug=False):
self.atomTypeDefinitions = dict()
self.atomTypeOverrides = dict()
self.atomTypeDesc = dict()
self.atomTypeRefs = dict()
self._included_forcefields = dict()
self.non_element_types = dict()
all_files_to_load = []
if forcefield_files is not None:
if isinstance(forcefield_files, (list, tuple, set)):
for file in forcefield_files:
all_files_to_load.append(file)
else:
all_files_to_load.append(forcefield_files)
if name is not None:
try:
file = self.included_forcefields[name]
except KeyError:
raise IOError('Forcefield {} cannot be found'.format(name))
else:
all_files_to_load.append(file)
preprocessed_files = preprocess_forcefield_files(all_files_to_load)
if validation:
for ff_file_name in preprocessed_files:
Validator(ff_file_name, debug)
super(Forcefield, self).__init__(*preprocessed_files)
self.parser = smarts.SMARTS(self.non_element_types)
self._SystemData = self._SystemData()
@property
def included_forcefields(self):
if any(self._included_forcefields):
return self._included_forcefields
ff_dir = resource_filename('foyer', 'forcefields')
ff_filepaths = set(glob.glob(os.path.join(ff_dir, '*.xml')))
for ff_filepath in ff_filepaths:
_, ff_file = os.path.split(ff_filepath)
basename, _ = os.path.splitext(ff_file)
self._included_forcefields[basename] = ff_filepath
return self._included_forcefields
def _create_element(self, element, mass):
if not isinstance(element, elem.Element):
try:
element = elem.get_by_symbol(element)
except KeyError:
# Enables support for non-atomistic "element types"
if element not in self.non_element_types:
warnings.warn('Non-atomistic element type detected. '
'Creating custom element for {}'.format(element))
element = custom_elem.Element(number=0,
mass=mass,
name=element,
symbol=element)
else:
return element, False
return element, True
def registerAtomType(self, parameters):
"""Register a new atom type. """
name = parameters['name']
if name in self._atomTypes:
raise ValueError('Found multiple definitions for atom type: ' + name)
atom_class = parameters['class']
mass = _convertParameterToNumber(parameters['mass'])
element = None
if 'element' in parameters:
element, custom = self._create_element(parameters['element'], mass)
if custom:
self.non_element_types[element.symbol] = element
self._atomTypes[name] = self.__class__._AtomType(name, atom_class, mass, element)
if atom_class in self._atomClasses:
type_set = self._atomClasses[atom_class]
else:
type_set = set()
self._atomClasses[atom_class] = type_set
type_set.add(name)
self._atomClasses[''].add(name)
name = parameters['name']
if 'def' in parameters:
self.atomTypeDefinitions[name] = parameters['def']
if 'overrides' in parameters:
overrides = set(atype.strip() for atype
in parameters['overrides'].split(","))
if overrides:
self.atomTypeOverrides[name] = overrides
if 'des' in parameters:
self.atomTypeDesc[name] = parameters['desc']
if 'doi' in parameters:
dois = set(doi.strip() for doi in parameters['doi'].split(','))
self.atomTypeRefs[name] = dois
def apply(self, topology, references_file=None, use_residue_map=True,
assert_bond_params=True, assert_angle_params=True,
assert_dihedral_params=True, assert_improper_params=False,
*args, **kwargs):
"""Apply the force field to a molecular structure
Parameters
----------
topology : openmm.app.Topology or parmed.Structure or mbuild.Compound
Molecular structure to apply the force field to
references_file : str, optional, default=None
Name of file where force field references will be written (in Bibtex
format)
use_residue_map : boolean, optional, default=True
Store atomtyped topologies of residues to a dictionary that maps
them to residue names. Each topology, including atomtypes, will be
copied to other residues with the same name. This avoids repeatedly
calling the subgraph isomorphism on idential residues and should
result in better performance for systems with many identical
residues, i.e. a box of water. Note that for this to be applied to
independent molecules, they must each be saved as different
residues in the topology.
assert_bond_params : bool, optional, default=True
If True, Foyer will exit if parameters are not found for all system
bonds.
assert_angle_params : bool, optional, default=True
If True, Foyer will exit if parameters are not found for all system
angles.
assert_dihedral_params : bool, optional, default=True
If True, Foyer will exit if parameters are not found for all system
proper dihedrals.
assert_improper_params : bool, optional, default=False
If True, Foyer will exit if parameters are not found for all system
improper dihedrals.
"""
if self.atomTypeDefinitions == {}:
raise FoyerError('Attempting to atom-type using a force field '
'with no atom type defitions.')
if not isinstance(topology, app.Topology):
residues = kwargs.get('residues')
topology, positions = generate_topology(topology,
self.non_element_types, residues=residues)
else:
positions = np.empty(shape=(topology.getNumAtoms(), 3))
positions[:] = np.nan
box_vectors = topology.getPeriodicBoxVectors()
topology = self.run_atomtyping(topology, use_residue_map=use_residue_map)
system = self.createSystem(topology, *args, **kwargs)
structure = pmd.openmm.load_topology(topology=topology, system=system)
'''
Check that all topology objects (angles, dihedrals, and impropers)
have parameters assigned. OpenMM will generate an error if bond parameters
are not assigned.
'''
data = self._SystemData
if data.bonds:
missing = [b for b in structure.bonds
if b.type is None]
if missing:
nmissing = len(structure.bonds) - len(missing)
msg = ("Parameters have not been assigned to all bonds. "
"Total system bonds: {}, Parametrized bonds: {}"
"".format(len(structure.bonds), nmissing))
_error_or_warn(assert_bond_params, msg)
if data.angles and (len(data.angles) != len(structure.angles)):
msg = ("Parameters have not been assigned to all angles. Total "
"system angles: {}, Parameterized angles: {}"
"".format(len(data.angles), len(structure.angles)))
_error_or_warn(assert_angle_params, msg)
proper_dihedrals = [dihedral for dihedral in structure.dihedrals
if not dihedral.improper]
if data.propers and len(data.propers) != \
len(proper_dihedrals) + len(structure.rb_torsions):
msg = ("Parameters have not been assigned to all proper dihedrals. "
"Total system dihedrals: {}, Parameterized dihedrals: {}. "
"Note that if your system contains torsions of Ryckaert-"
"Bellemans functional form, all of these torsions are "
"processed as propers.".format(len(data.propers),
len(proper_dihedrals) + len(structure.rb_torsions)))
_error_or_warn(assert_dihedral_params, msg)
improper_dihedrals = [dihedral for dihedral in structure.dihedrals
if dihedral.improper]
if data.impropers and len(data.impropers) != \
len(improper_dihedrals) + len(structure.impropers):
msg = ("Parameters have not been assigned to all impropers. Total "
"system impropers: {}, Parameterized impropers: {}. "
"Note that if your system contains torsions of Ryckaert-"
"Bellemans functional form, all of these torsions are "
"processed as propers".format(len(data.impropers),
len(improper_dihedrals) + len(structure.impropers)))
_error_or_warn(assert_improper_params, msg)
structure.bonds.sort(key=lambda x: x.atom1.idx)
structure.positions = positions
if box_vectors is not None:
structure.box_vectors = box_vectors
if references_file:
atom_types = set(atom.type for atom in structure.atoms)
self._write_references_to_file(atom_types, references_file)
return structure
def createSystem(self, topology, nonbondedMethod=NoCutoff,
nonbondedCutoff=1.0 * u.nanometer, constraints=None,
rigidWater=True, removeCMMotion=True, hydrogenMass=None,
**args):
"""Construct an OpenMM System representing a Topology with this force field.
Parameters
----------
topology : Topology
The Topology for which to create a System
nonbondedMethod : object=NoCutoff
The method to use for nonbonded interactions. Allowed values are
NoCutoff, CutoffNonPeriodic, CutoffPeriodic, Ewald, or PME.
nonbondedCutoff : distance=1*nanometer
The cutoff distance to use for nonbonded interactions
constraints : object=None
Specifies which bonds and angles should be implemented with constraints.
Allowed values are None, HBonds, AllBonds, or HAngles.
rigidWater : boolean=True
If true, water molecules will be fully rigid regardless of the value
passed for the constraints argument
removeCMMotion : boolean=True
If true, a CMMotionRemover will be added to the System
hydrogenMass : mass=None
The mass to use for hydrogen atoms bound to heavy atoms. Any mass
added to a hydrogen is subtracted from the heavy atom to keep
their total mass the same.
args
Arbitrary additional keyword arguments may also be specified.
This allows extra parameters to be specified that are specific to
particular force fields.
Returns
-------
system
the newly created System
"""
# Overwrite previous _SystemData object
self._SystemData = app.ForceField._SystemData()
data = self._SystemData
data.atoms = list(topology.atoms())
for atom in data.atoms:
data.excludeAtomWith.append([])
# Make a list of all bonds
for bond in topology.bonds():
data.bonds.append(app.ForceField._BondData(bond[0].index, bond[1].index))
# Record which atoms are bonded to each other atom
bonded_to_atom = []
for i in range(len(data.atoms)):
bonded_to_atom.append(set())
data.atomBonds.append([])
for i in range(len(data.bonds)):
bond = data.bonds[i]
bonded_to_atom[bond.atom1].add(bond.atom2)
bonded_to_atom[bond.atom2].add(bond.atom1)
data.atomBonds[bond.atom1].append(i)
data.atomBonds[bond.atom2].append(i)
# TODO: Better way to lookup nonbonded parameters...?
nonbonded_params = None
for generator in self.getGenerators():
if isinstance(generator, NonbondedGenerator):
nonbonded_params = generator.params.paramsForType
break
for chain in topology.chains():
for res in chain.residues():
for atom in res.atoms():
data.atomType[atom] = atom.id
if nonbonded_params:
params = nonbonded_params[atom.id]
data.atomParameters[atom] = params
# Create the System and add atoms
sys = mm.System()
for atom in topology.atoms():
# Look up the atom type name, returning a helpful error message if it cannot be found.
if atom not in data.atomType:
raise Exception("Could not identify atom type for atom '%s'." % str(atom))
typename = data.atomType[atom]
# Look up the type name in the list of registered atom types, returning a helpful error message if it cannot be found.
if typename not in self._atomTypes:
msg = "Could not find typename '%s' for atom '%s' in list of known atom types.\n" % (typename, str(atom))
msg += "Known atom types are: %s" % str(self._atomTypes.keys())
raise Exception(msg)
# Add the particle to the OpenMM system.
mass = self._atomTypes[typename].mass
sys.addParticle(mass)
# Adjust hydrogen masses if requested.
if hydrogenMass is not None:
if not u.is_quantity(hydrogenMass):
hydrogenMass *= u.dalton
for atom1, atom2 in topology.bonds():
if atom1.element == elem.hydrogen:
(atom1, atom2) = (atom2, atom1)
if atom2.element == elem.hydrogen and atom1.element not in (elem.hydrogen, None):
transfer_mass = hydrogenMass - sys.getParticleMass(atom2.index)
sys.setParticleMass(atom2.index, hydrogenMass)
mass = sys.getParticleMass(atom1.index) - transfer_mass
sys.setParticleMass(atom1.index, mass)
# Set periodic boundary conditions.
box_vectors = topology.getPeriodicBoxVectors()
if box_vectors is not None:
sys.setDefaultPeriodicBoxVectors(box_vectors[0],
box_vectors[1],
box_vectors[2])
elif nonbondedMethod not in [NoCutoff, CutoffNonPeriodic]:
raise ValueError('Requested periodic boundary conditions for a '
'Topology that does not specify periodic box '
'dimensions')
# Make a list of all unique angles
unique_angles = set()
for bond in data.bonds:
for atom in bonded_to_atom[bond.atom1]:
if atom != bond.atom2:
if atom < bond.atom2:
unique_angles.add((atom, bond.atom1, bond.atom2))
else:
unique_angles.add((bond.atom2, bond.atom1, atom))
for atom in bonded_to_atom[bond.atom2]:
if atom != bond.atom1:
if atom > bond.atom1:
unique_angles.add((bond.atom1, bond.atom2, atom))
else:
unique_angles.add((atom, bond.atom2, bond.atom1))
data.angles = sorted(list(unique_angles))
# Make a list of all unique proper torsions
unique_propers = set()
for angle in data.angles:
for atom in bonded_to_atom[angle[0]]:
if atom not in angle:
if atom < angle[2]:
unique_propers.add((atom, angle[0], angle[1], angle[2]))
else:
unique_propers.add((angle[2], angle[1], angle[0], atom))
for atom in bonded_to_atom[angle[2]]:
if atom not in angle:
if atom > angle[0]:
unique_propers.add((angle[0], angle[1], angle[2], atom))
else:
unique_propers.add((atom, angle[2], angle[1], angle[0]))
data.propers = sorted(list(unique_propers))
# Make a list of all unique improper torsions
for atom in range(len(bonded_to_atom)):
bonded_to = bonded_to_atom[atom]
if len(bonded_to) > 2:
for subset in itertools.combinations(bonded_to, 3):
data.impropers.append((atom, subset[0], subset[1], subset[2]))
# Identify bonds that should be implemented with constraints
if constraints == AllBonds or constraints == HAngles:
for bond in data.bonds:
bond.isConstrained = True
elif constraints == HBonds:
for bond in data.bonds:
atom1 = data.atoms[bond.atom1]
atom2 = data.atoms[bond.atom2]
bond.isConstrained = atom1.name.startswith('H') or atom2.name.startswith('H')
if rigidWater:
for bond in data.bonds:
atom1 = data.atoms[bond.atom1]
atom2 = data.atoms[bond.atom2]
if atom1.residue.name == 'HOH' and atom2.residue.name == 'HOH':
bond.isConstrained = True
# Identify angles that should be implemented with constraints
if constraints == HAngles:
for angle in data.angles:
atom1 = data.atoms[angle[0]]
atom2 = data.atoms[angle[1]]
atom3 = data.atoms[angle[2]]
numH = 0
if atom1.name.startswith('H'):
numH += 1
if atom3.name.startswith('H'):
numH += 1
data.isAngleConstrained.append(numH == 2 or (numH == 1 and atom2.name.startswith('O')))
else:
data.isAngleConstrained = len(data.angles)*[False]
if rigidWater:
for i in range(len(data.angles)):
angle = data.angles[i]
atom1 = data.atoms[angle[0]]
atom2 = data.atoms[angle[1]]
atom3 = data.atoms[angle[2]]
if atom1.residue.name == 'HOH' and atom2.residue.name == 'HOH' and atom3.residue.name == 'HOH':
data.isAngleConstrained[i] = True
# Add virtual sites
for atom in data.virtualSites:
(site, atoms, excludeWith) = data.virtualSites[atom]
index = atom.index
data.excludeAtomWith[excludeWith].append(index)
if site.type == 'average2':
sys.setVirtualSite(index, mm.TwoParticleAverageSite(
atoms[0], atoms[1], site.weights[0], site.weights[1]))
elif site.type == 'average3':
sys.setVirtualSite(index, mm.ThreeParticleAverageSite(
atoms[0], atoms[1], atoms[2],
site.weights[0], site.weights[1], site.weights[2]))
elif site.type == 'outOfPlane':
sys.setVirtualSite(index, mm.OutOfPlaneSite(
atoms[0], atoms[1], atoms[2],
site.weights[0], site.weights[1], site.weights[2]))
elif site.type == 'localCoords':
local_coord_site = mm.LocalCoordinatesSite(
atoms[0], atoms[1], atoms[2],
mm.Vec3(site.originWeights[0], site.originWeights[1], site.originWeights[2]),
mm.Vec3(site.xWeights[0], site.xWeights[1], site.xWeights[2]),
mm.Vec3(site.yWeights[0], site.yWeights[1], site.yWeights[2]),
mm.Vec3(site.localPos[0], site.localPos[1], site.localPos[2]))
sys.setVirtualSite(index, local_coord_site)
# Add forces to the System
for force in self._forces:
force.createForce(sys, data, nonbondedMethod, nonbondedCutoff, args)
if removeCMMotion:
sys.addForce(mm.CMMotionRemover())
# Let force generators do postprocessing
for force in self._forces:
if 'postprocessSystem' in dir(force):
force.postprocessSystem(sys, data, args)
# Execute scripts found in the XML files.
for script in self._scripts:
exec(script, locals())
return sys
def _write_references_to_file(self, atom_types, references_file):
atomtype_references = {}
for atype in atom_types:
try:
atomtype_references[atype] = self.atomTypeRefs[atype]
except KeyError:
warnings.warn("Reference not found for atom type '{}'."
"".format(atype))
unique_references = collections.defaultdict(list)
for atomtype, dois in atomtype_references.items():
for doi in dois:
unique_references[doi].append(atomtype)
unique_references = collections.OrderedDict(sorted(unique_references.items()))
with open(references_file, 'w') as f:
for doi, atomtypes in unique_references.items():
url = "http://dx.doi.org/" + doi
headers = {"accept": "application/x-bibtex"}
bibtex_ref = requests.get(url, headers=headers).text
note = (',\n\tnote = {Parameters for atom types: ' +
', '.join(sorted(atomtypes)) + '}')
bibtex_ref = bibtex_ref[:-2] + note + bibtex_ref[-2:]
f.write('{}\n'.format(bibtex_ref))
|
mosdef-hub/foyer | foyer/forcefield.py | Forcefield.createSystem | python | def createSystem(self, topology, nonbondedMethod=NoCutoff,
nonbondedCutoff=1.0 * u.nanometer, constraints=None,
rigidWater=True, removeCMMotion=True, hydrogenMass=None,
**args):
# Overwrite previous _SystemData object
self._SystemData = app.ForceField._SystemData()
data = self._SystemData
data.atoms = list(topology.atoms())
for atom in data.atoms:
data.excludeAtomWith.append([])
# Make a list of all bonds
for bond in topology.bonds():
data.bonds.append(app.ForceField._BondData(bond[0].index, bond[1].index))
# Record which atoms are bonded to each other atom
bonded_to_atom = []
for i in range(len(data.atoms)):
bonded_to_atom.append(set())
data.atomBonds.append([])
for i in range(len(data.bonds)):
bond = data.bonds[i]
bonded_to_atom[bond.atom1].add(bond.atom2)
bonded_to_atom[bond.atom2].add(bond.atom1)
data.atomBonds[bond.atom1].append(i)
data.atomBonds[bond.atom2].append(i)
# TODO: Better way to lookup nonbonded parameters...?
nonbonded_params = None
for generator in self.getGenerators():
if isinstance(generator, NonbondedGenerator):
nonbonded_params = generator.params.paramsForType
break
for chain in topology.chains():
for res in chain.residues():
for atom in res.atoms():
data.atomType[atom] = atom.id
if nonbonded_params:
params = nonbonded_params[atom.id]
data.atomParameters[atom] = params
# Create the System and add atoms
sys = mm.System()
for atom in topology.atoms():
# Look up the atom type name, returning a helpful error message if it cannot be found.
if atom not in data.atomType:
raise Exception("Could not identify atom type for atom '%s'." % str(atom))
typename = data.atomType[atom]
# Look up the type name in the list of registered atom types, returning a helpful error message if it cannot be found.
if typename not in self._atomTypes:
msg = "Could not find typename '%s' for atom '%s' in list of known atom types.\n" % (typename, str(atom))
msg += "Known atom types are: %s" % str(self._atomTypes.keys())
raise Exception(msg)
# Add the particle to the OpenMM system.
mass = self._atomTypes[typename].mass
sys.addParticle(mass)
# Adjust hydrogen masses if requested.
if hydrogenMass is not None:
if not u.is_quantity(hydrogenMass):
hydrogenMass *= u.dalton
for atom1, atom2 in topology.bonds():
if atom1.element == elem.hydrogen:
(atom1, atom2) = (atom2, atom1)
if atom2.element == elem.hydrogen and atom1.element not in (elem.hydrogen, None):
transfer_mass = hydrogenMass - sys.getParticleMass(atom2.index)
sys.setParticleMass(atom2.index, hydrogenMass)
mass = sys.getParticleMass(atom1.index) - transfer_mass
sys.setParticleMass(atom1.index, mass)
# Set periodic boundary conditions.
box_vectors = topology.getPeriodicBoxVectors()
if box_vectors is not None:
sys.setDefaultPeriodicBoxVectors(box_vectors[0],
box_vectors[1],
box_vectors[2])
elif nonbondedMethod not in [NoCutoff, CutoffNonPeriodic]:
raise ValueError('Requested periodic boundary conditions for a '
'Topology that does not specify periodic box '
'dimensions')
# Make a list of all unique angles
unique_angles = set()
for bond in data.bonds:
for atom in bonded_to_atom[bond.atom1]:
if atom != bond.atom2:
if atom < bond.atom2:
unique_angles.add((atom, bond.atom1, bond.atom2))
else:
unique_angles.add((bond.atom2, bond.atom1, atom))
for atom in bonded_to_atom[bond.atom2]:
if atom != bond.atom1:
if atom > bond.atom1:
unique_angles.add((bond.atom1, bond.atom2, atom))
else:
unique_angles.add((atom, bond.atom2, bond.atom1))
data.angles = sorted(list(unique_angles))
# Make a list of all unique proper torsions
unique_propers = set()
for angle in data.angles:
for atom in bonded_to_atom[angle[0]]:
if atom not in angle:
if atom < angle[2]:
unique_propers.add((atom, angle[0], angle[1], angle[2]))
else:
unique_propers.add((angle[2], angle[1], angle[0], atom))
for atom in bonded_to_atom[angle[2]]:
if atom not in angle:
if atom > angle[0]:
unique_propers.add((angle[0], angle[1], angle[2], atom))
else:
unique_propers.add((atom, angle[2], angle[1], angle[0]))
data.propers = sorted(list(unique_propers))
# Make a list of all unique improper torsions
for atom in range(len(bonded_to_atom)):
bonded_to = bonded_to_atom[atom]
if len(bonded_to) > 2:
for subset in itertools.combinations(bonded_to, 3):
data.impropers.append((atom, subset[0], subset[1], subset[2]))
# Identify bonds that should be implemented with constraints
if constraints == AllBonds or constraints == HAngles:
for bond in data.bonds:
bond.isConstrained = True
elif constraints == HBonds:
for bond in data.bonds:
atom1 = data.atoms[bond.atom1]
atom2 = data.atoms[bond.atom2]
bond.isConstrained = atom1.name.startswith('H') or atom2.name.startswith('H')
if rigidWater:
for bond in data.bonds:
atom1 = data.atoms[bond.atom1]
atom2 = data.atoms[bond.atom2]
if atom1.residue.name == 'HOH' and atom2.residue.name == 'HOH':
bond.isConstrained = True
# Identify angles that should be implemented with constraints
if constraints == HAngles:
for angle in data.angles:
atom1 = data.atoms[angle[0]]
atom2 = data.atoms[angle[1]]
atom3 = data.atoms[angle[2]]
numH = 0
if atom1.name.startswith('H'):
numH += 1
if atom3.name.startswith('H'):
numH += 1
data.isAngleConstrained.append(numH == 2 or (numH == 1 and atom2.name.startswith('O')))
else:
data.isAngleConstrained = len(data.angles)*[False]
if rigidWater:
for i in range(len(data.angles)):
angle = data.angles[i]
atom1 = data.atoms[angle[0]]
atom2 = data.atoms[angle[1]]
atom3 = data.atoms[angle[2]]
if atom1.residue.name == 'HOH' and atom2.residue.name == 'HOH' and atom3.residue.name == 'HOH':
data.isAngleConstrained[i] = True
# Add virtual sites
for atom in data.virtualSites:
(site, atoms, excludeWith) = data.virtualSites[atom]
index = atom.index
data.excludeAtomWith[excludeWith].append(index)
if site.type == 'average2':
sys.setVirtualSite(index, mm.TwoParticleAverageSite(
atoms[0], atoms[1], site.weights[0], site.weights[1]))
elif site.type == 'average3':
sys.setVirtualSite(index, mm.ThreeParticleAverageSite(
atoms[0], atoms[1], atoms[2],
site.weights[0], site.weights[1], site.weights[2]))
elif site.type == 'outOfPlane':
sys.setVirtualSite(index, mm.OutOfPlaneSite(
atoms[0], atoms[1], atoms[2],
site.weights[0], site.weights[1], site.weights[2]))
elif site.type == 'localCoords':
local_coord_site = mm.LocalCoordinatesSite(
atoms[0], atoms[1], atoms[2],
mm.Vec3(site.originWeights[0], site.originWeights[1], site.originWeights[2]),
mm.Vec3(site.xWeights[0], site.xWeights[1], site.xWeights[2]),
mm.Vec3(site.yWeights[0], site.yWeights[1], site.yWeights[2]),
mm.Vec3(site.localPos[0], site.localPos[1], site.localPos[2]))
sys.setVirtualSite(index, local_coord_site)
# Add forces to the System
for force in self._forces:
force.createForce(sys, data, nonbondedMethod, nonbondedCutoff, args)
if removeCMMotion:
sys.addForce(mm.CMMotionRemover())
# Let force generators do postprocessing
for force in self._forces:
if 'postprocessSystem' in dir(force):
force.postprocessSystem(sys, data, args)
# Execute scripts found in the XML files.
for script in self._scripts:
exec(script, locals())
return sys | Construct an OpenMM System representing a Topology with this force field.
Parameters
----------
topology : Topology
The Topology for which to create a System
nonbondedMethod : object=NoCutoff
The method to use for nonbonded interactions. Allowed values are
NoCutoff, CutoffNonPeriodic, CutoffPeriodic, Ewald, or PME.
nonbondedCutoff : distance=1*nanometer
The cutoff distance to use for nonbonded interactions
constraints : object=None
Specifies which bonds and angles should be implemented with constraints.
Allowed values are None, HBonds, AllBonds, or HAngles.
rigidWater : boolean=True
If true, water molecules will be fully rigid regardless of the value
passed for the constraints argument
removeCMMotion : boolean=True
If true, a CMMotionRemover will be added to the System
hydrogenMass : mass=None
The mass to use for hydrogen atoms bound to heavy atoms. Any mass
added to a hydrogen is subtracted from the heavy atom to keep
their total mass the same.
args
Arbitrary additional keyword arguments may also be specified.
This allows extra parameters to be specified that are specific to
particular force fields.
Returns
-------
system
the newly created System | train | https://github.com/mosdef-hub/foyer/blob/9e39c71208fc01a6cc7b7cbe5a533c56830681d3/foyer/forcefield.py#L495-L734 | null | class Forcefield(app.ForceField):
"""Specialization of OpenMM's Forcefield allowing SMARTS based atomtyping.
Parameters
----------
forcefield_files : list of str, optional, default=None
List of forcefield files to load.
name : str, optional, default=None
Name of a forcefield to load that is packaged within foyer.
"""
def __init__(self, forcefield_files=None, name=None, validation=True, debug=False):
self.atomTypeDefinitions = dict()
self.atomTypeOverrides = dict()
self.atomTypeDesc = dict()
self.atomTypeRefs = dict()
self._included_forcefields = dict()
self.non_element_types = dict()
all_files_to_load = []
if forcefield_files is not None:
if isinstance(forcefield_files, (list, tuple, set)):
for file in forcefield_files:
all_files_to_load.append(file)
else:
all_files_to_load.append(forcefield_files)
if name is not None:
try:
file = self.included_forcefields[name]
except KeyError:
raise IOError('Forcefield {} cannot be found'.format(name))
else:
all_files_to_load.append(file)
preprocessed_files = preprocess_forcefield_files(all_files_to_load)
if validation:
for ff_file_name in preprocessed_files:
Validator(ff_file_name, debug)
super(Forcefield, self).__init__(*preprocessed_files)
self.parser = smarts.SMARTS(self.non_element_types)
self._SystemData = self._SystemData()
@property
def included_forcefields(self):
if any(self._included_forcefields):
return self._included_forcefields
ff_dir = resource_filename('foyer', 'forcefields')
ff_filepaths = set(glob.glob(os.path.join(ff_dir, '*.xml')))
for ff_filepath in ff_filepaths:
_, ff_file = os.path.split(ff_filepath)
basename, _ = os.path.splitext(ff_file)
self._included_forcefields[basename] = ff_filepath
return self._included_forcefields
def _create_element(self, element, mass):
if not isinstance(element, elem.Element):
try:
element = elem.get_by_symbol(element)
except KeyError:
# Enables support for non-atomistic "element types"
if element not in self.non_element_types:
warnings.warn('Non-atomistic element type detected. '
'Creating custom element for {}'.format(element))
element = custom_elem.Element(number=0,
mass=mass,
name=element,
symbol=element)
else:
return element, False
return element, True
def registerAtomType(self, parameters):
"""Register a new atom type. """
name = parameters['name']
if name in self._atomTypes:
raise ValueError('Found multiple definitions for atom type: ' + name)
atom_class = parameters['class']
mass = _convertParameterToNumber(parameters['mass'])
element = None
if 'element' in parameters:
element, custom = self._create_element(parameters['element'], mass)
if custom:
self.non_element_types[element.symbol] = element
self._atomTypes[name] = self.__class__._AtomType(name, atom_class, mass, element)
if atom_class in self._atomClasses:
type_set = self._atomClasses[atom_class]
else:
type_set = set()
self._atomClasses[atom_class] = type_set
type_set.add(name)
self._atomClasses[''].add(name)
name = parameters['name']
if 'def' in parameters:
self.atomTypeDefinitions[name] = parameters['def']
if 'overrides' in parameters:
overrides = set(atype.strip() for atype
in parameters['overrides'].split(","))
if overrides:
self.atomTypeOverrides[name] = overrides
if 'des' in parameters:
self.atomTypeDesc[name] = parameters['desc']
if 'doi' in parameters:
dois = set(doi.strip() for doi in parameters['doi'].split(','))
self.atomTypeRefs[name] = dois
def apply(self, topology, references_file=None, use_residue_map=True,
assert_bond_params=True, assert_angle_params=True,
assert_dihedral_params=True, assert_improper_params=False,
*args, **kwargs):
"""Apply the force field to a molecular structure
Parameters
----------
topology : openmm.app.Topology or parmed.Structure or mbuild.Compound
Molecular structure to apply the force field to
references_file : str, optional, default=None
Name of file where force field references will be written (in Bibtex
format)
use_residue_map : boolean, optional, default=True
Store atomtyped topologies of residues to a dictionary that maps
them to residue names. Each topology, including atomtypes, will be
copied to other residues with the same name. This avoids repeatedly
calling the subgraph isomorphism on idential residues and should
result in better performance for systems with many identical
residues, i.e. a box of water. Note that for this to be applied to
independent molecules, they must each be saved as different
residues in the topology.
assert_bond_params : bool, optional, default=True
If True, Foyer will exit if parameters are not found for all system
bonds.
assert_angle_params : bool, optional, default=True
If True, Foyer will exit if parameters are not found for all system
angles.
assert_dihedral_params : bool, optional, default=True
If True, Foyer will exit if parameters are not found for all system
proper dihedrals.
assert_improper_params : bool, optional, default=False
If True, Foyer will exit if parameters are not found for all system
improper dihedrals.
"""
if self.atomTypeDefinitions == {}:
raise FoyerError('Attempting to atom-type using a force field '
'with no atom type defitions.')
if not isinstance(topology, app.Topology):
residues = kwargs.get('residues')
topology, positions = generate_topology(topology,
self.non_element_types, residues=residues)
else:
positions = np.empty(shape=(topology.getNumAtoms(), 3))
positions[:] = np.nan
box_vectors = topology.getPeriodicBoxVectors()
topology = self.run_atomtyping(topology, use_residue_map=use_residue_map)
system = self.createSystem(topology, *args, **kwargs)
structure = pmd.openmm.load_topology(topology=topology, system=system)
'''
Check that all topology objects (angles, dihedrals, and impropers)
have parameters assigned. OpenMM will generate an error if bond parameters
are not assigned.
'''
data = self._SystemData
if data.bonds:
missing = [b for b in structure.bonds
if b.type is None]
if missing:
nmissing = len(structure.bonds) - len(missing)
msg = ("Parameters have not been assigned to all bonds. "
"Total system bonds: {}, Parametrized bonds: {}"
"".format(len(structure.bonds), nmissing))
_error_or_warn(assert_bond_params, msg)
if data.angles and (len(data.angles) != len(structure.angles)):
msg = ("Parameters have not been assigned to all angles. Total "
"system angles: {}, Parameterized angles: {}"
"".format(len(data.angles), len(structure.angles)))
_error_or_warn(assert_angle_params, msg)
proper_dihedrals = [dihedral for dihedral in structure.dihedrals
if not dihedral.improper]
if data.propers and len(data.propers) != \
len(proper_dihedrals) + len(structure.rb_torsions):
msg = ("Parameters have not been assigned to all proper dihedrals. "
"Total system dihedrals: {}, Parameterized dihedrals: {}. "
"Note that if your system contains torsions of Ryckaert-"
"Bellemans functional form, all of these torsions are "
"processed as propers.".format(len(data.propers),
len(proper_dihedrals) + len(structure.rb_torsions)))
_error_or_warn(assert_dihedral_params, msg)
improper_dihedrals = [dihedral for dihedral in structure.dihedrals
if dihedral.improper]
if data.impropers and len(data.impropers) != \
len(improper_dihedrals) + len(structure.impropers):
msg = ("Parameters have not been assigned to all impropers. Total "
"system impropers: {}, Parameterized impropers: {}. "
"Note that if your system contains torsions of Ryckaert-"
"Bellemans functional form, all of these torsions are "
"processed as propers".format(len(data.impropers),
len(improper_dihedrals) + len(structure.impropers)))
_error_or_warn(assert_improper_params, msg)
structure.bonds.sort(key=lambda x: x.atom1.idx)
structure.positions = positions
if box_vectors is not None:
structure.box_vectors = box_vectors
if references_file:
atom_types = set(atom.type for atom in structure.atoms)
self._write_references_to_file(atom_types, references_file)
return structure
def run_atomtyping(self, topology, use_residue_map=True):
"""Atomtype the topology
Parameters
----------
topology : openmm.app.Topology
Molecular structure to find atom types of
use_residue_map : boolean, optional, default=True
Store atomtyped topologies of residues to a dictionary that maps
them to residue names. Each topology, including atomtypes, will be
copied to other residues with the same name. This avoids repeatedly
calling the subgraph isomorphism on idential residues and should
result in better performance for systems with many identical
residues, i.e. a box of water. Note that for this to be applied to
independent molecules, they must each be saved as different
residues in the topology.
"""
if use_residue_map:
independent_residues = _check_independent_residues(topology)
if independent_residues:
residue_map = dict()
for res in topology.residues():
if res.name not in residue_map.keys():
residue = _topology_from_residue(res)
find_atomtypes(residue, forcefield=self)
residue_map[res.name] = residue
for key, val in residue_map.items():
_update_atomtypes(topology, key, val)
else:
find_atomtypes(topology, forcefield=self)
else:
find_atomtypes(topology, forcefield=self)
if not all([a.id for a in topology.atoms()][0]):
raise ValueError('Not all atoms in topology have atom types')
return topology
def _write_references_to_file(self, atom_types, references_file):
atomtype_references = {}
for atype in atom_types:
try:
atomtype_references[atype] = self.atomTypeRefs[atype]
except KeyError:
warnings.warn("Reference not found for atom type '{}'."
"".format(atype))
unique_references = collections.defaultdict(list)
for atomtype, dois in atomtype_references.items():
for doi in dois:
unique_references[doi].append(atomtype)
unique_references = collections.OrderedDict(sorted(unique_references.items()))
with open(references_file, 'w') as f:
for doi, atomtypes in unique_references.items():
url = "http://dx.doi.org/" + doi
headers = {"accept": "application/x-bibtex"}
bibtex_ref = requests.get(url, headers=headers).text
note = (',\n\tnote = {Parameters for atom types: ' +
', '.join(sorted(atomtypes)) + '}')
bibtex_ref = bibtex_ref[:-2] + note + bibtex_ref[-2:]
f.write('{}\n'.format(bibtex_ref))
|
20c/vaping | vaping/plugins/vodka.py | probe_to_graphsrv | python | def probe_to_graphsrv(probe):
config = probe.config
# manual group set up via `group` config key
if "group" in config:
source, group = config["group"].split(".")
group_field = config.get("group_field", "host")
group_value = config[group_field]
graphsrv.group.add(source, group, {group_value:{group_field:group_value}}, **config)
return
# automatic group setup for fping
# FIXME: this should be somehow more dynamic
for k, v in list(config.items()):
if isinstance(v, dict) and "hosts" in v:
r = {}
for host in v.get("hosts"):
if isinstance(host, dict):
r[host["host"]] = host
else:
r[host] = {"host":host}
graphsrv.group.add(probe.name, k, r, **v) | takes a probe instance and generates
a graphsrv data group for it using the
probe's config | train | https://github.com/20c/vaping/blob/c51f00586c99edb3d51e4abdbdfe3174755533ee/vaping/plugins/vodka.py#L20-L49 | null | from __future__ import absolute_import
import vaping
import vaping.config
try:
import vodka
import vodka.data
except ImportError:
pass
try:
import graphsrv
import graphsrv.group
except ImportError:
graphsrv = None
@vaping.plugin.register('vodka')
class VodkaPlugin(vaping.plugins.EmitBase):
def init(self):
self._is_started = False
def start(self):
if self._is_started:
return
vodka.run(self.config, self.vaping.config)
if graphsrv:
# if graphsrv is installed proceed to generate
# target configurations for it from probe config
for node in self.vaping.config.get("probes", []):
probe = vaping.plugin.get_probe(node, self.vaping)
probe_to_graphsrv(probe)
self._is_started = True
def emit(self, message):
if not self._is_started:
self.start()
vodka.data.handle(message.get("type"), message, data_id=message.get("source"), caller=self)
|
20c/vaping | vaping/plugins/__init__.py | PluginBase.new_message | python | def new_message(self):
msg = {}
msg['data'] = []
msg['type'] = self.plugin_type
msg['source'] = self.name
msg['ts'] = (datetime.datetime.utcnow() - datetime.datetime(1970, 1, 1)).total_seconds()
return msg | creates a new message, setting `type`, `source`, `ts`, `data`
- `data` is initialized to an empty array | train | https://github.com/20c/vaping/blob/c51f00586c99edb3d51e4abdbdfe3174755533ee/vaping/plugins/__init__.py#L51-L61 | null | class PluginBase(vaping.io.Thread):
"""
Base plugin class
Initializes:
- `self.config` as plugins config
- `self.log` as a logging object for plugin
- `self.vaping` as a reference to the main vaping object
Then calls alls `self.init()` prefork while loading all modules, init() should
not do anything active, any files opened may be closed when it forks.
Plugins should prefer `init()` to `__init__()` to ensure the class is
completely done initializing.
Calls `self.on_start()` and `self.on_stop()` before and after running in
case any connections need to be created or cleaned up.
"""
def init(self):
"""
called after the plugin is initialized, plugin may define this for any
other initialization code
"""
pass
def on_start(self):
"""
called when the daemon is starting
"""
pass
def on_stop(self):
"""
called when the daemon is stopping
"""
pass
def popen(self, args, **kwargs):
"""
creates a subprocess with passed args
"""
self.log.debug("popen %s", ' '.join(args))
return vaping.io.subprocess.Popen(args, **kwargs)
@property
def log(self):
if not self._logger:
self._logger = logging.getLogger('vaping.plugins.' + self.plugin_type)
return self._logger
def __init__(self, config, ctx):
if hasattr(self, 'default_config'):
self.config = munge.util.recursive_update(copy.deepcopy(self.default_config), copy.deepcopy(config))
else:
self.config = config
# set for pluginmgr
self.pluginmgr_config = self.config
self.vaping = ctx
self.name = self.config.get("name")
self._logger = None
super(PluginBase, self).__init__()
self.init()
def _run(self):
self.on_start()
|
20c/vaping | vaping/plugins/__init__.py | PluginBase.popen | python | def popen(self, args, **kwargs):
self.log.debug("popen %s", ' '.join(args))
return vaping.io.subprocess.Popen(args, **kwargs) | creates a subprocess with passed args | train | https://github.com/20c/vaping/blob/c51f00586c99edb3d51e4abdbdfe3174755533ee/vaping/plugins/__init__.py#L63-L68 | null | class PluginBase(vaping.io.Thread):
"""
Base plugin class
Initializes:
- `self.config` as plugins config
- `self.log` as a logging object for plugin
- `self.vaping` as a reference to the main vaping object
Then calls alls `self.init()` prefork while loading all modules, init() should
not do anything active, any files opened may be closed when it forks.
Plugins should prefer `init()` to `__init__()` to ensure the class is
completely done initializing.
Calls `self.on_start()` and `self.on_stop()` before and after running in
case any connections need to be created or cleaned up.
"""
def init(self):
"""
called after the plugin is initialized, plugin may define this for any
other initialization code
"""
pass
def on_start(self):
"""
called when the daemon is starting
"""
pass
def on_stop(self):
"""
called when the daemon is stopping
"""
pass
def new_message(self):
"""
creates a new message, setting `type`, `source`, `ts`, `data`
- `data` is initialized to an empty array
"""
msg = {}
msg['data'] = []
msg['type'] = self.plugin_type
msg['source'] = self.name
msg['ts'] = (datetime.datetime.utcnow() - datetime.datetime(1970, 1, 1)).total_seconds()
return msg
@property
def log(self):
if not self._logger:
self._logger = logging.getLogger('vaping.plugins.' + self.plugin_type)
return self._logger
def __init__(self, config, ctx):
if hasattr(self, 'default_config'):
self.config = munge.util.recursive_update(copy.deepcopy(self.default_config), copy.deepcopy(config))
else:
self.config = config
# set for pluginmgr
self.pluginmgr_config = self.config
self.vaping = ctx
self.name = self.config.get("name")
self._logger = None
super(PluginBase, self).__init__()
self.init()
def _run(self):
self.on_start()
|
20c/vaping | vaping/plugins/__init__.py | ProbeBase.queue_emission | python | def queue_emission(self, msg):
if not msg:
return
for _emitter in self._emit:
if not hasattr(_emitter, 'emit'):
continue
def emit(emitter=_emitter):
self.log.debug("emit to {}".format(emitter.name))
emitter.emit(msg)
self.log.debug("queue emission to {} ({})".format(
_emitter.name, self._emit_queue.qsize()))
self._emit_queue.put(emit) | queue an emission of a message for all output plugins | train | https://github.com/20c/vaping/blob/c51f00586c99edb3d51e4abdbdfe3174755533ee/vaping/plugins/__init__.py#L131-L145 | null | class ProbeBase(with_metaclass(abc.ABCMeta, PluginBase)):
"""
Base class for probe plugin, used for getting data
expects method probe() to be defined
"""
def init(self):
pass
@abc.abstractmethod
def probe(self):
"""
probe for data, return a list of dicts
"""
def __init__(self, config, ctx, emit=None):
if emit:
self._emit = [emit]
else:
self._emit = []
self._emit_queue = vaping.io.Queue()
super(ProbeBase, self).__init__(config, ctx)
def _run(self):
super(ProbeBase, self)._run()
self.run_level = 1
while self.run_level:
self.send_emission()
msg = self.probe()
if msg:
self.queue_emission(msg)
else:
self.log.debug("probe returned no data")
def send_emission(self):
"""
emit and remove the first emission in the queue
"""
if self._emit_queue.empty():
return
emit = self._emit_queue.get()
emit()
def emit_all(self):
"""
emit and remove all emissions in the queue
"""
while not self._emit_queue.empty():
self.send_emission()
|
20c/vaping | vaping/plugins/__init__.py | ProbeBase.send_emission | python | def send_emission(self):
if self._emit_queue.empty():
return
emit = self._emit_queue.get()
emit() | emit and remove the first emission in the queue | train | https://github.com/20c/vaping/blob/c51f00586c99edb3d51e4abdbdfe3174755533ee/vaping/plugins/__init__.py#L147-L154 | null | class ProbeBase(with_metaclass(abc.ABCMeta, PluginBase)):
"""
Base class for probe plugin, used for getting data
expects method probe() to be defined
"""
def init(self):
pass
@abc.abstractmethod
def probe(self):
"""
probe for data, return a list of dicts
"""
def __init__(self, config, ctx, emit=None):
if emit:
self._emit = [emit]
else:
self._emit = []
self._emit_queue = vaping.io.Queue()
super(ProbeBase, self).__init__(config, ctx)
def _run(self):
super(ProbeBase, self)._run()
self.run_level = 1
while self.run_level:
self.send_emission()
msg = self.probe()
if msg:
self.queue_emission(msg)
else:
self.log.debug("probe returned no data")
def queue_emission(self, msg):
"""
queue an emission of a message for all output plugins
"""
if not msg:
return
for _emitter in self._emit:
if not hasattr(_emitter, 'emit'):
continue
def emit(emitter=_emitter):
self.log.debug("emit to {}".format(emitter.name))
emitter.emit(msg)
self.log.debug("queue emission to {} ({})".format(
_emitter.name, self._emit_queue.qsize()))
self._emit_queue.put(emit)
def emit_all(self):
"""
emit and remove all emissions in the queue
"""
while not self._emit_queue.empty():
self.send_emission()
|
20c/vaping | vaping/plugins/__init__.py | FileProbe.validate_file_handler | python | def validate_file_handler(self):
if self.fh.closed:
try:
self.fh = open(self.path, "r")
self.fh.seek(0, 2)
except OSError as err:
logging.error("Could not reopen file: {}".format(err))
return False
open_stat = os.fstat(self.fh.fileno())
try:
file_stat = os.stat(self.path)
except OSError as err:
logging.error("Could not stat file: {}".format(err))
return False
if open_stat != file_stat:
self.log
self.fh.close()
return False
return True | Here we validate that our filehandler is pointing
to an existing file.
If it doesnt, because file has been deleted, we close
the filehander and try to reopen | train | https://github.com/20c/vaping/blob/c51f00586c99edb3d51e4abdbdfe3174755533ee/vaping/plugins/__init__.py#L245-L273 | null | class FileProbe(ProbeBase):
"""
Probes a file and emits everytime a new line is read
Config:
`path`: path to file
`backlog`: number of bytes to read from backlog (default 0)
`max_lines`: maximum number of lines to read during probe
(default 1000)
"""
def __init__(self, config, ctx, emit=None):
super(FileProbe, self).__init__(config, ctx, emit)
self.path = self.pluginmgr_config.get("path")
self.run_level = 0
self.backlog = int(self.pluginmgr_config.get("backlog",0))
self.max_lines = int(self.pluginmgr_config.get("max_lines",1000))
if self.path:
self.fh = open(self.path, "r")
self.fh.seek(0,2)
if self.backlog:
try:
self.fh.seek(self.fh.tell() - self.backlog, os.SEEK_SET)
except ValueError as exc:
if str(exc).find("negative seek position") > -1:
self.fh.seek(0)
else:
raise
def _run(self):
self.run_level = 1
while self.run_level:
self.send_emission()
for msg in self.probe():
self.queue_emission(msg)
vaping.io.sleep(0.1)
def probe(self):
"""
Probe the file for new lines
"""
# make sure the filehandler is still valid
# (e.g. file stat hasnt changed, file exists etc.)
if not self.validate_file_handler():
return []
messages = []
# read any new lines and push them onto the stack
for line in self.fh.readlines(self.max_lines):
data = {"path":self.path}
msg = self.new_message()
# process the line - this is where parsing happens
parsed = self.process_line(line, data)
if not parsed:
continue
data.update(parsed)
# process the probe - this is where data assignment
# happens
data = self.process_probe(data)
msg["data"] = [data]
messages.append(msg)
# process all new messages before returning them
# for emission
messages = self.process_messages(messages)
return messages
def process_line(self, line, data):
""" override this - parse your line in here """
return data
def process_probe(self, data):
""" override this - assign your data values here """
return data
def process_messages(self, messages):
"""
override this - process your messages before they
are emitted
"""
return messages
|
20c/vaping | vaping/plugins/__init__.py | FileProbe.probe | python | def probe(self):
# make sure the filehandler is still valid
# (e.g. file stat hasnt changed, file exists etc.)
if not self.validate_file_handler():
return []
messages = []
# read any new lines and push them onto the stack
for line in self.fh.readlines(self.max_lines):
data = {"path":self.path}
msg = self.new_message()
# process the line - this is where parsing happens
parsed = self.process_line(line, data)
if not parsed:
continue
data.update(parsed)
# process the probe - this is where data assignment
# happens
data = self.process_probe(data)
msg["data"] = [data]
messages.append(msg)
# process all new messages before returning them
# for emission
messages = self.process_messages(messages)
return messages | Probe the file for new lines | train | https://github.com/20c/vaping/blob/c51f00586c99edb3d51e4abdbdfe3174755533ee/vaping/plugins/__init__.py#L276-L310 | [
"def validate_file_handler(self):\n \"\"\"\n Here we validate that our filehandler is pointing\n to an existing file.\n\n If it doesnt, because file has been deleted, we close\n the filehander and try to reopen\n \"\"\"\n if self.fh.closed:\n try:\n self.fh = open(self.path, \"r\")\n self.fh.seek(0, 2)\n except OSError as err:\n logging.error(\"Could not reopen file: {}\".format(err))\n return False\n\n open_stat = os.fstat(self.fh.fileno())\n try:\n file_stat = os.stat(self.path)\n except OSError as err:\n logging.error(\"Could not stat file: {}\".format(err))\n return False\n\n if open_stat != file_stat:\n self.log\n self.fh.close()\n return False\n\n return True\n"
] | class FileProbe(ProbeBase):
"""
Probes a file and emits everytime a new line is read
Config:
`path`: path to file
`backlog`: number of bytes to read from backlog (default 0)
`max_lines`: maximum number of lines to read during probe
(default 1000)
"""
def __init__(self, config, ctx, emit=None):
super(FileProbe, self).__init__(config, ctx, emit)
self.path = self.pluginmgr_config.get("path")
self.run_level = 0
self.backlog = int(self.pluginmgr_config.get("backlog",0))
self.max_lines = int(self.pluginmgr_config.get("max_lines",1000))
if self.path:
self.fh = open(self.path, "r")
self.fh.seek(0,2)
if self.backlog:
try:
self.fh.seek(self.fh.tell() - self.backlog, os.SEEK_SET)
except ValueError as exc:
if str(exc).find("negative seek position") > -1:
self.fh.seek(0)
else:
raise
def _run(self):
self.run_level = 1
while self.run_level:
self.send_emission()
for msg in self.probe():
self.queue_emission(msg)
vaping.io.sleep(0.1)
def validate_file_handler(self):
"""
Here we validate that our filehandler is pointing
to an existing file.
If it doesnt, because file has been deleted, we close
the filehander and try to reopen
"""
if self.fh.closed:
try:
self.fh = open(self.path, "r")
self.fh.seek(0, 2)
except OSError as err:
logging.error("Could not reopen file: {}".format(err))
return False
open_stat = os.fstat(self.fh.fileno())
try:
file_stat = os.stat(self.path)
except OSError as err:
logging.error("Could not stat file: {}".format(err))
return False
if open_stat != file_stat:
self.log
self.fh.close()
return False
return True
def process_line(self, line, data):
""" override this - parse your line in here """
return data
def process_probe(self, data):
""" override this - assign your data values here """
return data
def process_messages(self, messages):
"""
override this - process your messages before they
are emitted
"""
return messages
|
20c/vaping | vaping/plugins/__init__.py | TimeSeriesDB.filename_formatters | python | def filename_formatters(self, data, row):
r = {
"source" : data.get("source"),
"field" : self.field,
"type" : data.get("type")
}
r.update(**row)
return r | Returns a dict containing the various filename formatter values
Values are gotten from the vaping data message as well as the
currently processed row in the message
- `data`: vaping message
- `row`: vaping message data row | train | https://github.com/20c/vaping/blob/c51f00586c99edb3d51e4abdbdfe3174755533ee/vaping/plugins/__init__.py#L394-L411 | null | class TimeSeriesDB(EmitBase):
"""
Base class for timeseries db storage plugins
"""
def __init__(self, config, ctx):
super(TimeSeriesDB, self).__init__(config, ctx)
# filename template
self.filename = self.config.get("filename")
# field name to read the value from
self.field = self.config.get("field")
if not self.filename:
raise ValueError("No filename specified")
if not self.field:
raise ValueError("No field specified, field should specify which value to store in the database")
def create(self, filename):
"""
Create database
- `filename`: database filename
"""
raise NotImplementedError()
def update(self, filename, time, value):
"""
Update database
- `filename`: database filename
- `time`: timestamp
- `value`
"""
raise NotImplementedError()
def get(self, filename, from_time, to_time):
"""
Retrieve data from database for the specified
timespan
- `filename`: database filename
- `from_time`: from time
- `to_time`: to time
"""
raise NotImplementedError()
def format_filename(self, data, row):
"""
Returns a formatted filename using the template stored
in self.filename
- `data`: vaping message
- `row`: vaping message data row
"""
return self.filename.format(**self.filename_formatters(data, row))
def emit(self, message):
"""
emit to database
"""
# handle vaping data that arrives in a list
if isinstance(message.get("data"), list):
for row in message.get("data"):
# format filename from data
filename = self.format_filename(message, row)
# create database file if it does not exist yet
if not os.path.exists(filename):
self.create(filename)
# update database
self.log.debug("storing time:%d, %s:%.5f in %s" % (
message.get("ts"), self.field, row.get(self.field), filename))
self.update(filename, message.get("ts"), row.get(self.field))
|
20c/vaping | vaping/plugins/__init__.py | TimeSeriesDB.format_filename | python | def format_filename(self, data, row):
return self.filename.format(**self.filename_formatters(data, row)) | Returns a formatted filename using the template stored
in self.filename
- `data`: vaping message
- `row`: vaping message data row | train | https://github.com/20c/vaping/blob/c51f00586c99edb3d51e4abdbdfe3174755533ee/vaping/plugins/__init__.py#L413-L421 | [
"def filename_formatters(self, data, row):\n \"\"\"\n Returns a dict containing the various filename formatter values\n\n Values are gotten from the vaping data message as well as the\n currently processed row in the message\n\n - `data`: vaping message\n - `row`: vaping message data row\n \"\"\"\n\n r = {\n \"source\" : data.get(\"source\"),\n \"field\" : self.field,\n \"type\" : data.get(\"type\")\n }\n r.update(**row)\n return r\n"
] | class TimeSeriesDB(EmitBase):
"""
Base class for timeseries db storage plugins
"""
def __init__(self, config, ctx):
super(TimeSeriesDB, self).__init__(config, ctx)
# filename template
self.filename = self.config.get("filename")
# field name to read the value from
self.field = self.config.get("field")
if not self.filename:
raise ValueError("No filename specified")
if not self.field:
raise ValueError("No field specified, field should specify which value to store in the database")
def create(self, filename):
"""
Create database
- `filename`: database filename
"""
raise NotImplementedError()
def update(self, filename, time, value):
"""
Update database
- `filename`: database filename
- `time`: timestamp
- `value`
"""
raise NotImplementedError()
def get(self, filename, from_time, to_time):
"""
Retrieve data from database for the specified
timespan
- `filename`: database filename
- `from_time`: from time
- `to_time`: to time
"""
raise NotImplementedError()
def filename_formatters(self, data, row):
"""
Returns a dict containing the various filename formatter values
Values are gotten from the vaping data message as well as the
currently processed row in the message
- `data`: vaping message
- `row`: vaping message data row
"""
r = {
"source" : data.get("source"),
"field" : self.field,
"type" : data.get("type")
}
r.update(**row)
return r
def emit(self, message):
"""
emit to database
"""
# handle vaping data that arrives in a list
if isinstance(message.get("data"), list):
for row in message.get("data"):
# format filename from data
filename = self.format_filename(message, row)
# create database file if it does not exist yet
if not os.path.exists(filename):
self.create(filename)
# update database
self.log.debug("storing time:%d, %s:%.5f in %s" % (
message.get("ts"), self.field, row.get(self.field), filename))
self.update(filename, message.get("ts"), row.get(self.field))
|
20c/vaping | vaping/plugins/__init__.py | TimeSeriesDB.emit | python | def emit(self, message):
# handle vaping data that arrives in a list
if isinstance(message.get("data"), list):
for row in message.get("data"):
# format filename from data
filename = self.format_filename(message, row)
# create database file if it does not exist yet
if not os.path.exists(filename):
self.create(filename)
# update database
self.log.debug("storing time:%d, %s:%.5f in %s" % (
message.get("ts"), self.field, row.get(self.field), filename))
self.update(filename, message.get("ts"), row.get(self.field)) | emit to database | train | https://github.com/20c/vaping/blob/c51f00586c99edb3d51e4abdbdfe3174755533ee/vaping/plugins/__init__.py#L423-L442 | [
"def create(self, filename):\n \"\"\"\n Create database\n\n - `filename`: database filename\n \"\"\"\n raise NotImplementedError()\n",
"def update(self, filename, time, value):\n \"\"\"\n Update database\n\n - `filename`: database filename\n - `time`: timestamp\n - `value`\n \"\"\"\n raise NotImplementedError()\n",
"def format_filename(self, data, row):\n \"\"\"\n Returns a formatted filename using the template stored\n in self.filename\n\n - `data`: vaping message\n - `row`: vaping message data row\n \"\"\"\n return self.filename.format(**self.filename_formatters(data, row))\n"
] | class TimeSeriesDB(EmitBase):
"""
Base class for timeseries db storage plugins
"""
def __init__(self, config, ctx):
super(TimeSeriesDB, self).__init__(config, ctx)
# filename template
self.filename = self.config.get("filename")
# field name to read the value from
self.field = self.config.get("field")
if not self.filename:
raise ValueError("No filename specified")
if not self.field:
raise ValueError("No field specified, field should specify which value to store in the database")
def create(self, filename):
"""
Create database
- `filename`: database filename
"""
raise NotImplementedError()
def update(self, filename, time, value):
"""
Update database
- `filename`: database filename
- `time`: timestamp
- `value`
"""
raise NotImplementedError()
def get(self, filename, from_time, to_time):
"""
Retrieve data from database for the specified
timespan
- `filename`: database filename
- `from_time`: from time
- `to_time`: to time
"""
raise NotImplementedError()
def filename_formatters(self, data, row):
"""
Returns a dict containing the various filename formatter values
Values are gotten from the vaping data message as well as the
currently processed row in the message
- `data`: vaping message
- `row`: vaping message data row
"""
r = {
"source" : data.get("source"),
"field" : self.field,
"type" : data.get("type")
}
r.update(**row)
return r
def format_filename(self, data, row):
"""
Returns a formatted filename using the template stored
in self.filename
- `data`: vaping message
- `row`: vaping message data row
"""
return self.filename.format(**self.filename_formatters(data, row))
|
20c/vaping | vaping/config.py | parse_interval | python | def parse_interval(val):
re_intv = re.compile(r"([\d\.]+)([a-zA-Z]+)")
val = val.strip()
total = 0.0
for match in re_intv.findall(val):
unit = match[1]
count = float(match[0])
if unit == 's':
total += count
elif unit == 'm':
total += count * 60
elif unit == 'ms':
total += count / 1000
elif unit == "h":
total += count * 3600
elif unit == 'd':
total += count * 86400
else:
raise ValueError("unknown unit from interval string '%s'" % val)
return total | converts a string to float of seconds
.5 = 500ms
90 = 1m30s | train | https://github.com/20c/vaping/blob/c51f00586c99edb3d51e4abdbdfe3174755533ee/vaping/config.py#L8-L33 | null | from __future__ import division
import re
import munge
class Config(munge.Config):
defaults = {
'config': {
'vaping': {
'home_dir': None,
'pidfile': 'vaping.pid',
'plugin_path': [],
},
},
'config_dir': '~/.vaping',
'codec': 'yaml',
}
|
20c/vaping | vaping/plugins/fping.py | FPingBase.hosts_args | python | def hosts_args(self):
host_args = []
for row in self.hosts:
if isinstance(row, dict):
host_args.append(row["host"])
else:
host_args.append(row)
# using a set changes the order
dedupe = list()
for each in host_args:
if each not in dedupe:
dedupe.append(each)
return dedupe | hosts list can contain strings specifying a host directly
or dicts containing a "host" key to specify the host
this way we can allow passing further config details (color, name etc.)
with each host as well as simply dropping in addresses for quick
setup depending on the user's needs | train | https://github.com/20c/vaping/blob/c51f00586c99edb3d51e4abdbdfe3174755533ee/vaping/plugins/fping.py#L39-L61 | null | class FPingBase(vaping.plugins.TimedProbe):
"""
FPing base plugin
config:
`command` command to run
`interval` time between pings
`count` number of pings to send
`period` time in milliseconds that fping waits between successive packets to an individual target
"""
default_config = {
'command': 'fping',
'interval': '1m',
'count': 5,
'period': 20
}
def __init__(self, config, ctx):
super(FPingBase, self).__init__(config, ctx)
if not which(self.config['command']):
self.log.critical("missing fping, install it or set `command` in the fping config")
raise RuntimeError("fping command not found - install the fping package")
self.count = int(self.config.get('count', 0))
self.period = int(self.config.get('period', 0))
def parse_verbose(self, line):
"""
parse output from verbose format
"""
try:
logging.debug(line)
(host, pings) = line.split(' : ')
cnt = 0
lost = 0
times = []
pings = pings.strip().split(' ')
cnt = len(pings)
for latency in pings:
if latency == '-':
continue
times.append(float(latency))
lost = cnt - len(times)
if lost:
loss = lost / float(cnt)
else:
loss = 0.0
rv = {
'host': host.strip(),
'cnt': cnt,
'loss': loss,
'data': times,
}
if times:
rv['min'] = min(times)
rv['max'] = max(times)
rv['avg'] = sum(times) / len(times)
rv['last'] = times[-1]
return rv
except Exception as e:
logging.error("failed to get data: {}".format(e))
def _run_proc(self):
args = [
self.config['command'],
'-u',
'-C%d' % self.count,
'-p%d' % self.period,
'-e'
]
args.extend(self.hosts_args())
data = list()
# get both stdout and stderr
proc = self.popen(args, stdout=subprocess.PIPE,
stderr=subprocess.STDOUT)
# TODO poll, timeout, maybe from parent process for better control?
with proc.stdout:
for line in iter(proc.stdout.readline, b''):
data.append(self.parse_verbose(line.decode("utf-8")))
return data
|
20c/vaping | vaping/plugins/fping.py | FPingBase.parse_verbose | python | def parse_verbose(self, line):
try:
logging.debug(line)
(host, pings) = line.split(' : ')
cnt = 0
lost = 0
times = []
pings = pings.strip().split(' ')
cnt = len(pings)
for latency in pings:
if latency == '-':
continue
times.append(float(latency))
lost = cnt - len(times)
if lost:
loss = lost / float(cnt)
else:
loss = 0.0
rv = {
'host': host.strip(),
'cnt': cnt,
'loss': loss,
'data': times,
}
if times:
rv['min'] = min(times)
rv['max'] = max(times)
rv['avg'] = sum(times) / len(times)
rv['last'] = times[-1]
return rv
except Exception as e:
logging.error("failed to get data: {}".format(e)) | parse output from verbose format | train | https://github.com/20c/vaping/blob/c51f00586c99edb3d51e4abdbdfe3174755533ee/vaping/plugins/fping.py#L63-L100 | null | class FPingBase(vaping.plugins.TimedProbe):
"""
FPing base plugin
config:
`command` command to run
`interval` time between pings
`count` number of pings to send
`period` time in milliseconds that fping waits between successive packets to an individual target
"""
default_config = {
'command': 'fping',
'interval': '1m',
'count': 5,
'period': 20
}
def __init__(self, config, ctx):
super(FPingBase, self).__init__(config, ctx)
if not which(self.config['command']):
self.log.critical("missing fping, install it or set `command` in the fping config")
raise RuntimeError("fping command not found - install the fping package")
self.count = int(self.config.get('count', 0))
self.period = int(self.config.get('period', 0))
def hosts_args(self):
"""
hosts list can contain strings specifying a host directly
or dicts containing a "host" key to specify the host
this way we can allow passing further config details (color, name etc.)
with each host as well as simply dropping in addresses for quick
setup depending on the user's needs
"""
host_args = []
for row in self.hosts:
if isinstance(row, dict):
host_args.append(row["host"])
else:
host_args.append(row)
# using a set changes the order
dedupe = list()
for each in host_args:
if each not in dedupe:
dedupe.append(each)
return dedupe
def _run_proc(self):
args = [
self.config['command'],
'-u',
'-C%d' % self.count,
'-p%d' % self.period,
'-e'
]
args.extend(self.hosts_args())
data = list()
# get both stdout and stderr
proc = self.popen(args, stdout=subprocess.PIPE,
stderr=subprocess.STDOUT)
# TODO poll, timeout, maybe from parent process for better control?
with proc.stdout:
for line in iter(proc.stdout.readline, b''):
data.append(self.parse_verbose(line.decode("utf-8")))
return data
|
20c/vaping | vaping/cli.py | start | python | def start(ctx, **kwargs):
update_context(ctx, kwargs)
daemon = mk_daemon(ctx)
if ctx.debug or kwargs['no_fork']:
daemon.run()
else:
daemon.start() | start a vaping process | train | https://github.com/20c/vaping/blob/c51f00586c99edb3d51e4abdbdfe3174755533ee/vaping/cli.py#L52-L63 | [
"def update_context(ctx, kwargs):\n ctx.update_options(kwargs)\n\n if not isinstance(ctx.config['vaping']['plugin_path'], list):\n raise ValueError('config item vaping.plugin_path must be a list')\n # set plugin search path to defined + home/plugins\n searchpath = ctx.config['vaping']['plugin_path']\n if ctx.home:\n searchpath.append(os.path.join(ctx.home, 'plugins'))\n vaping.plugin.searchpath = searchpath\n",
"def mk_daemon(ctx):\n if not ctx.config.meta:\n raise ValueError(\"no config specified, please use specify a home directory\")\n return vaping.daemon.Vaping(ctx.config)\n",
"def start(self):\n \"\"\" start daemon \"\"\"\n self._exec()\n",
"def run(self):\n \"\"\" run daemon \"\"\"\n # FIXME - not detaching doesn't work, just run directly for now\n # self._exec(detach=False)\n try:\n with self.pidfile:\n return self._main()\n\n except pidfile.PidFileError:\n # this isn't exposed in pidfile :o\n self.log.error(\"failed to get pid lock, already running?\")\n return 1\n\n finally:\n # call on_stop to let them clean up\n for mod in self.joins:\n self.log.debug(\"stopping %s\", mod.name)\n mod.on_stop()\n"
] | from __future__ import absolute_import
import os
import click
import munge
import munge.click
import vaping
import vaping.daemon
class Context(munge.click.Context):
app_name = 'vaping'
config_class = vaping.Config
def update_context(ctx, kwargs):
ctx.update_options(kwargs)
if not isinstance(ctx.config['vaping']['plugin_path'], list):
raise ValueError('config item vaping.plugin_path must be a list')
# set plugin search path to defined + home/plugins
searchpath = ctx.config['vaping']['plugin_path']
if ctx.home:
searchpath.append(os.path.join(ctx.home, 'plugins'))
vaping.plugin.searchpath = searchpath
def mk_daemon(ctx):
if not ctx.config.meta:
raise ValueError("no config specified, please use specify a home directory")
return vaping.daemon.Vaping(ctx.config)
@click.group()
@click.version_option()
@Context.options
@Context.pass_context()
def cli(ctx, **kwargs):
"""
Vaping
"""
update_context(ctx, kwargs)
@cli.command()
@click.version_option()
@Context.options
@Context.pass_context()
@click.option('-d', '--no-fork', help='do not fork into background', is_flag=True, default=False)
@cli.command()
@click.version_option()
@Context.options
@Context.pass_context()
def stop(ctx, **kwargs):
"""
stop a vaping process
"""
update_context(ctx, kwargs)
daemon = mk_daemon(ctx)
daemon.stop()
@cli.command()
@click.version_option()
@Context.options
@Context.pass_context()
def restart(ctx, **kwargs):
"""
restart a vaping process
"""
update_context(ctx, kwargs)
daemon = mk_daemon(ctx)
daemon.stop()
daemon.start()
|
20c/vaping | vaping/cli.py | stop | python | def stop(ctx, **kwargs):
update_context(ctx, kwargs)
daemon = mk_daemon(ctx)
daemon.stop() | stop a vaping process | train | https://github.com/20c/vaping/blob/c51f00586c99edb3d51e4abdbdfe3174755533ee/vaping/cli.py#L70-L77 | [
"def update_context(ctx, kwargs):\n ctx.update_options(kwargs)\n\n if not isinstance(ctx.config['vaping']['plugin_path'], list):\n raise ValueError('config item vaping.plugin_path must be a list')\n # set plugin search path to defined + home/plugins\n searchpath = ctx.config['vaping']['plugin_path']\n if ctx.home:\n searchpath.append(os.path.join(ctx.home, 'plugins'))\n vaping.plugin.searchpath = searchpath\n",
"def mk_daemon(ctx):\n if not ctx.config.meta:\n raise ValueError(\"no config specified, please use specify a home directory\")\n return vaping.daemon.Vaping(ctx.config)\n",
"def stop(self):\n \"\"\" stop daemon \"\"\"\n try:\n with self.pidfile:\n self.log.error(\"failed to stop, missing pid file or not running\")\n\n except pidfile.PidFileError:\n # this isn't exposed in pidfile :o\n with open(self.pidfile.filename) as fobj:\n pid = int(fobj.readline().rstrip())\n if not pid:\n self.log.error(\"failed to read pid from file\")\n\n self.log.info(\"killing %d\", pid)\n os.kill(pid, signal.SIGTERM)\n"
] | from __future__ import absolute_import
import os
import click
import munge
import munge.click
import vaping
import vaping.daemon
class Context(munge.click.Context):
app_name = 'vaping'
config_class = vaping.Config
def update_context(ctx, kwargs):
ctx.update_options(kwargs)
if not isinstance(ctx.config['vaping']['plugin_path'], list):
raise ValueError('config item vaping.plugin_path must be a list')
# set plugin search path to defined + home/plugins
searchpath = ctx.config['vaping']['plugin_path']
if ctx.home:
searchpath.append(os.path.join(ctx.home, 'plugins'))
vaping.plugin.searchpath = searchpath
def mk_daemon(ctx):
if not ctx.config.meta:
raise ValueError("no config specified, please use specify a home directory")
return vaping.daemon.Vaping(ctx.config)
@click.group()
@click.version_option()
@Context.options
@Context.pass_context()
def cli(ctx, **kwargs):
"""
Vaping
"""
update_context(ctx, kwargs)
@cli.command()
@click.version_option()
@Context.options
@Context.pass_context()
@click.option('-d', '--no-fork', help='do not fork into background', is_flag=True, default=False)
def start(ctx, **kwargs):
"""
start a vaping process
"""
update_context(ctx, kwargs)
daemon = mk_daemon(ctx)
if ctx.debug or kwargs['no_fork']:
daemon.run()
else:
daemon.start()
@cli.command()
@click.version_option()
@Context.options
@Context.pass_context()
@cli.command()
@click.version_option()
@Context.options
@Context.pass_context()
def restart(ctx, **kwargs):
"""
restart a vaping process
"""
update_context(ctx, kwargs)
daemon = mk_daemon(ctx)
daemon.stop()
daemon.start()
|
20c/vaping | vaping/cli.py | restart | python | def restart(ctx, **kwargs):
update_context(ctx, kwargs)
daemon = mk_daemon(ctx)
daemon.stop()
daemon.start() | restart a vaping process | train | https://github.com/20c/vaping/blob/c51f00586c99edb3d51e4abdbdfe3174755533ee/vaping/cli.py#L84-L92 | [
"def update_context(ctx, kwargs):\n ctx.update_options(kwargs)\n\n if not isinstance(ctx.config['vaping']['plugin_path'], list):\n raise ValueError('config item vaping.plugin_path must be a list')\n # set plugin search path to defined + home/plugins\n searchpath = ctx.config['vaping']['plugin_path']\n if ctx.home:\n searchpath.append(os.path.join(ctx.home, 'plugins'))\n vaping.plugin.searchpath = searchpath\n",
"def mk_daemon(ctx):\n if not ctx.config.meta:\n raise ValueError(\"no config specified, please use specify a home directory\")\n return vaping.daemon.Vaping(ctx.config)\n",
"def start(self):\n \"\"\" start daemon \"\"\"\n self._exec()\n",
"def stop(self):\n \"\"\" stop daemon \"\"\"\n try:\n with self.pidfile:\n self.log.error(\"failed to stop, missing pid file or not running\")\n\n except pidfile.PidFileError:\n # this isn't exposed in pidfile :o\n with open(self.pidfile.filename) as fobj:\n pid = int(fobj.readline().rstrip())\n if not pid:\n self.log.error(\"failed to read pid from file\")\n\n self.log.info(\"killing %d\", pid)\n os.kill(pid, signal.SIGTERM)\n"
] | from __future__ import absolute_import
import os
import click
import munge
import munge.click
import vaping
import vaping.daemon
class Context(munge.click.Context):
app_name = 'vaping'
config_class = vaping.Config
def update_context(ctx, kwargs):
ctx.update_options(kwargs)
if not isinstance(ctx.config['vaping']['plugin_path'], list):
raise ValueError('config item vaping.plugin_path must be a list')
# set plugin search path to defined + home/plugins
searchpath = ctx.config['vaping']['plugin_path']
if ctx.home:
searchpath.append(os.path.join(ctx.home, 'plugins'))
vaping.plugin.searchpath = searchpath
def mk_daemon(ctx):
if not ctx.config.meta:
raise ValueError("no config specified, please use specify a home directory")
return vaping.daemon.Vaping(ctx.config)
@click.group()
@click.version_option()
@Context.options
@Context.pass_context()
def cli(ctx, **kwargs):
"""
Vaping
"""
update_context(ctx, kwargs)
@cli.command()
@click.version_option()
@Context.options
@Context.pass_context()
@click.option('-d', '--no-fork', help='do not fork into background', is_flag=True, default=False)
def start(ctx, **kwargs):
"""
start a vaping process
"""
update_context(ctx, kwargs)
daemon = mk_daemon(ctx)
if ctx.debug or kwargs['no_fork']:
daemon.run()
else:
daemon.start()
@cli.command()
@click.version_option()
@Context.options
@Context.pass_context()
def stop(ctx, **kwargs):
"""
stop a vaping process
"""
update_context(ctx, kwargs)
daemon = mk_daemon(ctx)
daemon.stop()
@cli.command()
@click.version_option()
@Context.options
@Context.pass_context()
|
20c/vaping | vaping/daemon.py | Vaping._exec | python | def _exec(self, detach=True):
kwargs = {
'pidfile': self.pidfile,
'working_directory': self.home_dir,
}
# FIXME - doesn't work
if not detach:
kwargs.update({
'detach_process': False,
'files_preserve': [0,1,2],
'stdout': sys.stdout,
'stderr': sys.stderr,
})
ctx = daemon.DaemonContext(**kwargs)
with ctx:
self._main() | daemonize and exec main() | train | https://github.com/20c/vaping/blob/c51f00586c99edb3d51e4abdbdfe3174755533ee/vaping/daemon.py#L97-L118 | [
"def _main(self):\n \"\"\"\n process\n \"\"\"\n probes = self.config.get('probes', None)\n if not probes:\n raise ValueError('no probes specified')\n\n for probe_config in self.config['probes']:\n probe = plugin.get_probe(probe_config, self.plugin_context)\n # FIXME - needs to check for output defined in plugin\n if 'output' not in probe_config:\n raise ValueError(\"no output specified\")\n\n # get all output targets and start / join them\n for output_name in probe_config['output']:\n output = plugin.get_output(output_name, self.plugin_context)\n if not output.started:\n output.start()\n self.joins.append(output)\n probe._emit.append(output)\n\n probe.start()\n self.joins.append(probe)\n\n vaping.io.joinall(self.joins)\n return 0\n"
] | class Vaping(object):
""" Vaping daemon class """
def __init__(self, config=None, config_dir=None):
"""
must either pass config as a dict or vaping.config.Config
or config_dir as a path to where the config dir is located
"""
if config:
if isinstance(config, dict):
self.config = vaping.Config(data=config)
else:
if not config.meta:
raise ValueError("config was not specified or empty")
self.config = config
elif config_dir:
self.config = vaping.Config(read=config_dir)
else:
raise ValueError("config was not specified or empty")
self.joins = []
self._logger = None
self.plugin_context = PluginContext(self.config)
vcfg = self.config.get('vaping', None)
if not vcfg:
vcfg = dict()
# get either home_dir from config, or use config_dir
self.home_dir = vcfg.get('home_dir', None)
if not self.home_dir:
self.home_dir = self.config.meta['config_dir']
if not os.path.exists(self.home_dir):
raise ValueError("home directory '{}' does not exist".format(self.home_dir))
if not os.access(self.home_dir, os.W_OK):
raise ValueError("home directory '{}' is not writable".format(self.home_dir))
# change to home for working dir
os.chdir(self.home_dir)
# instantiate all defined plugins
# TODO remove and let them lazy init?
plugins = self.config.get('plugins', None)
if not plugins:
raise ValueError('no plugins specified')
plugin.instantiate(self.config['plugins'], self.plugin_context)
# check that probes don't name clash with plugins
for probe in self.config.get('probes', []):
if plugin.exists(probe["name"]):
raise ValueError("probes may not share names with plugins ({})".format(probe["name"]))
# TODO move to daemon
pidname = vcfg.get('pidfile', 'vaping.pid')
self.pidfile = pidfile.PidFile(pidname=pidname, piddir=self.home_dir)
@property
def log(self):
if not self._logger:
self._logger = logging.getLogger(__name__)
return self._logger
def _main(self):
"""
process
"""
probes = self.config.get('probes', None)
if not probes:
raise ValueError('no probes specified')
for probe_config in self.config['probes']:
probe = plugin.get_probe(probe_config, self.plugin_context)
# FIXME - needs to check for output defined in plugin
if 'output' not in probe_config:
raise ValueError("no output specified")
# get all output targets and start / join them
for output_name in probe_config['output']:
output = plugin.get_output(output_name, self.plugin_context)
if not output.started:
output.start()
self.joins.append(output)
probe._emit.append(output)
probe.start()
self.joins.append(probe)
vaping.io.joinall(self.joins)
return 0
def start(self):
""" start daemon """
self._exec()
def stop(self):
""" stop daemon """
try:
with self.pidfile:
self.log.error("failed to stop, missing pid file or not running")
except pidfile.PidFileError:
# this isn't exposed in pidfile :o
with open(self.pidfile.filename) as fobj:
pid = int(fobj.readline().rstrip())
if not pid:
self.log.error("failed to read pid from file")
self.log.info("killing %d", pid)
os.kill(pid, signal.SIGTERM)
def run(self):
""" run daemon """
# FIXME - not detaching doesn't work, just run directly for now
# self._exec(detach=False)
try:
with self.pidfile:
return self._main()
except pidfile.PidFileError:
# this isn't exposed in pidfile :o
self.log.error("failed to get pid lock, already running?")
return 1
finally:
# call on_stop to let them clean up
for mod in self.joins:
self.log.debug("stopping %s", mod.name)
mod.on_stop()
|
20c/vaping | vaping/daemon.py | Vaping._main | python | def _main(self):
probes = self.config.get('probes', None)
if not probes:
raise ValueError('no probes specified')
for probe_config in self.config['probes']:
probe = plugin.get_probe(probe_config, self.plugin_context)
# FIXME - needs to check for output defined in plugin
if 'output' not in probe_config:
raise ValueError("no output specified")
# get all output targets and start / join them
for output_name in probe_config['output']:
output = plugin.get_output(output_name, self.plugin_context)
if not output.started:
output.start()
self.joins.append(output)
probe._emit.append(output)
probe.start()
self.joins.append(probe)
vaping.io.joinall(self.joins)
return 0 | process | train | https://github.com/20c/vaping/blob/c51f00586c99edb3d51e4abdbdfe3174755533ee/vaping/daemon.py#L120-L146 | null | class Vaping(object):
""" Vaping daemon class """
def __init__(self, config=None, config_dir=None):
"""
must either pass config as a dict or vaping.config.Config
or config_dir as a path to where the config dir is located
"""
if config:
if isinstance(config, dict):
self.config = vaping.Config(data=config)
else:
if not config.meta:
raise ValueError("config was not specified or empty")
self.config = config
elif config_dir:
self.config = vaping.Config(read=config_dir)
else:
raise ValueError("config was not specified or empty")
self.joins = []
self._logger = None
self.plugin_context = PluginContext(self.config)
vcfg = self.config.get('vaping', None)
if not vcfg:
vcfg = dict()
# get either home_dir from config, or use config_dir
self.home_dir = vcfg.get('home_dir', None)
if not self.home_dir:
self.home_dir = self.config.meta['config_dir']
if not os.path.exists(self.home_dir):
raise ValueError("home directory '{}' does not exist".format(self.home_dir))
if not os.access(self.home_dir, os.W_OK):
raise ValueError("home directory '{}' is not writable".format(self.home_dir))
# change to home for working dir
os.chdir(self.home_dir)
# instantiate all defined plugins
# TODO remove and let them lazy init?
plugins = self.config.get('plugins', None)
if not plugins:
raise ValueError('no plugins specified')
plugin.instantiate(self.config['plugins'], self.plugin_context)
# check that probes don't name clash with plugins
for probe in self.config.get('probes', []):
if plugin.exists(probe["name"]):
raise ValueError("probes may not share names with plugins ({})".format(probe["name"]))
# TODO move to daemon
pidname = vcfg.get('pidfile', 'vaping.pid')
self.pidfile = pidfile.PidFile(pidname=pidname, piddir=self.home_dir)
@property
def log(self):
if not self._logger:
self._logger = logging.getLogger(__name__)
return self._logger
def _exec(self, detach=True):
"""
daemonize and exec main()
"""
kwargs = {
'pidfile': self.pidfile,
'working_directory': self.home_dir,
}
# FIXME - doesn't work
if not detach:
kwargs.update({
'detach_process': False,
'files_preserve': [0,1,2],
'stdout': sys.stdout,
'stderr': sys.stderr,
})
ctx = daemon.DaemonContext(**kwargs)
with ctx:
self._main()
def start(self):
""" start daemon """
self._exec()
def stop(self):
""" stop daemon """
try:
with self.pidfile:
self.log.error("failed to stop, missing pid file or not running")
except pidfile.PidFileError:
# this isn't exposed in pidfile :o
with open(self.pidfile.filename) as fobj:
pid = int(fobj.readline().rstrip())
if not pid:
self.log.error("failed to read pid from file")
self.log.info("killing %d", pid)
os.kill(pid, signal.SIGTERM)
def run(self):
""" run daemon """
# FIXME - not detaching doesn't work, just run directly for now
# self._exec(detach=False)
try:
with self.pidfile:
return self._main()
except pidfile.PidFileError:
# this isn't exposed in pidfile :o
self.log.error("failed to get pid lock, already running?")
return 1
finally:
# call on_stop to let them clean up
for mod in self.joins:
self.log.debug("stopping %s", mod.name)
mod.on_stop()
|
20c/vaping | vaping/daemon.py | Vaping.stop | python | def stop(self):
try:
with self.pidfile:
self.log.error("failed to stop, missing pid file or not running")
except pidfile.PidFileError:
# this isn't exposed in pidfile :o
with open(self.pidfile.filename) as fobj:
pid = int(fobj.readline().rstrip())
if not pid:
self.log.error("failed to read pid from file")
self.log.info("killing %d", pid)
os.kill(pid, signal.SIGTERM) | stop daemon | train | https://github.com/20c/vaping/blob/c51f00586c99edb3d51e4abdbdfe3174755533ee/vaping/daemon.py#L152-L166 | null | class Vaping(object):
""" Vaping daemon class """
def __init__(self, config=None, config_dir=None):
"""
must either pass config as a dict or vaping.config.Config
or config_dir as a path to where the config dir is located
"""
if config:
if isinstance(config, dict):
self.config = vaping.Config(data=config)
else:
if not config.meta:
raise ValueError("config was not specified or empty")
self.config = config
elif config_dir:
self.config = vaping.Config(read=config_dir)
else:
raise ValueError("config was not specified or empty")
self.joins = []
self._logger = None
self.plugin_context = PluginContext(self.config)
vcfg = self.config.get('vaping', None)
if not vcfg:
vcfg = dict()
# get either home_dir from config, or use config_dir
self.home_dir = vcfg.get('home_dir', None)
if not self.home_dir:
self.home_dir = self.config.meta['config_dir']
if not os.path.exists(self.home_dir):
raise ValueError("home directory '{}' does not exist".format(self.home_dir))
if not os.access(self.home_dir, os.W_OK):
raise ValueError("home directory '{}' is not writable".format(self.home_dir))
# change to home for working dir
os.chdir(self.home_dir)
# instantiate all defined plugins
# TODO remove and let them lazy init?
plugins = self.config.get('plugins', None)
if not plugins:
raise ValueError('no plugins specified')
plugin.instantiate(self.config['plugins'], self.plugin_context)
# check that probes don't name clash with plugins
for probe in self.config.get('probes', []):
if plugin.exists(probe["name"]):
raise ValueError("probes may not share names with plugins ({})".format(probe["name"]))
# TODO move to daemon
pidname = vcfg.get('pidfile', 'vaping.pid')
self.pidfile = pidfile.PidFile(pidname=pidname, piddir=self.home_dir)
@property
def log(self):
if not self._logger:
self._logger = logging.getLogger(__name__)
return self._logger
def _exec(self, detach=True):
"""
daemonize and exec main()
"""
kwargs = {
'pidfile': self.pidfile,
'working_directory': self.home_dir,
}
# FIXME - doesn't work
if not detach:
kwargs.update({
'detach_process': False,
'files_preserve': [0,1,2],
'stdout': sys.stdout,
'stderr': sys.stderr,
})
ctx = daemon.DaemonContext(**kwargs)
with ctx:
self._main()
def _main(self):
"""
process
"""
probes = self.config.get('probes', None)
if not probes:
raise ValueError('no probes specified')
for probe_config in self.config['probes']:
probe = plugin.get_probe(probe_config, self.plugin_context)
# FIXME - needs to check for output defined in plugin
if 'output' not in probe_config:
raise ValueError("no output specified")
# get all output targets and start / join them
for output_name in probe_config['output']:
output = plugin.get_output(output_name, self.plugin_context)
if not output.started:
output.start()
self.joins.append(output)
probe._emit.append(output)
probe.start()
self.joins.append(probe)
vaping.io.joinall(self.joins)
return 0
def start(self):
""" start daemon """
self._exec()
def run(self):
""" run daemon """
# FIXME - not detaching doesn't work, just run directly for now
# self._exec(detach=False)
try:
with self.pidfile:
return self._main()
except pidfile.PidFileError:
# this isn't exposed in pidfile :o
self.log.error("failed to get pid lock, already running?")
return 1
finally:
# call on_stop to let them clean up
for mod in self.joins:
self.log.debug("stopping %s", mod.name)
mod.on_stop()
|
20c/vaping | vaping/daemon.py | Vaping.run | python | def run(self):
# FIXME - not detaching doesn't work, just run directly for now
# self._exec(detach=False)
try:
with self.pidfile:
return self._main()
except pidfile.PidFileError:
# this isn't exposed in pidfile :o
self.log.error("failed to get pid lock, already running?")
return 1
finally:
# call on_stop to let them clean up
for mod in self.joins:
self.log.debug("stopping %s", mod.name)
mod.on_stop() | run daemon | train | https://github.com/20c/vaping/blob/c51f00586c99edb3d51e4abdbdfe3174755533ee/vaping/daemon.py#L168-L185 | [
"def _main(self):\n \"\"\"\n process\n \"\"\"\n probes = self.config.get('probes', None)\n if not probes:\n raise ValueError('no probes specified')\n\n for probe_config in self.config['probes']:\n probe = plugin.get_probe(probe_config, self.plugin_context)\n # FIXME - needs to check for output defined in plugin\n if 'output' not in probe_config:\n raise ValueError(\"no output specified\")\n\n # get all output targets and start / join them\n for output_name in probe_config['output']:\n output = plugin.get_output(output_name, self.plugin_context)\n if not output.started:\n output.start()\n self.joins.append(output)\n probe._emit.append(output)\n\n probe.start()\n self.joins.append(probe)\n\n vaping.io.joinall(self.joins)\n return 0\n"
] | class Vaping(object):
""" Vaping daemon class """
def __init__(self, config=None, config_dir=None):
"""
must either pass config as a dict or vaping.config.Config
or config_dir as a path to where the config dir is located
"""
if config:
if isinstance(config, dict):
self.config = vaping.Config(data=config)
else:
if not config.meta:
raise ValueError("config was not specified or empty")
self.config = config
elif config_dir:
self.config = vaping.Config(read=config_dir)
else:
raise ValueError("config was not specified or empty")
self.joins = []
self._logger = None
self.plugin_context = PluginContext(self.config)
vcfg = self.config.get('vaping', None)
if not vcfg:
vcfg = dict()
# get either home_dir from config, or use config_dir
self.home_dir = vcfg.get('home_dir', None)
if not self.home_dir:
self.home_dir = self.config.meta['config_dir']
if not os.path.exists(self.home_dir):
raise ValueError("home directory '{}' does not exist".format(self.home_dir))
if not os.access(self.home_dir, os.W_OK):
raise ValueError("home directory '{}' is not writable".format(self.home_dir))
# change to home for working dir
os.chdir(self.home_dir)
# instantiate all defined plugins
# TODO remove and let them lazy init?
plugins = self.config.get('plugins', None)
if not plugins:
raise ValueError('no plugins specified')
plugin.instantiate(self.config['plugins'], self.plugin_context)
# check that probes don't name clash with plugins
for probe in self.config.get('probes', []):
if plugin.exists(probe["name"]):
raise ValueError("probes may not share names with plugins ({})".format(probe["name"]))
# TODO move to daemon
pidname = vcfg.get('pidfile', 'vaping.pid')
self.pidfile = pidfile.PidFile(pidname=pidname, piddir=self.home_dir)
@property
def log(self):
if not self._logger:
self._logger = logging.getLogger(__name__)
return self._logger
def _exec(self, detach=True):
"""
daemonize and exec main()
"""
kwargs = {
'pidfile': self.pidfile,
'working_directory': self.home_dir,
}
# FIXME - doesn't work
if not detach:
kwargs.update({
'detach_process': False,
'files_preserve': [0,1,2],
'stdout': sys.stdout,
'stderr': sys.stderr,
})
ctx = daemon.DaemonContext(**kwargs)
with ctx:
self._main()
def _main(self):
"""
process
"""
probes = self.config.get('probes', None)
if not probes:
raise ValueError('no probes specified')
for probe_config in self.config['probes']:
probe = plugin.get_probe(probe_config, self.plugin_context)
# FIXME - needs to check for output defined in plugin
if 'output' not in probe_config:
raise ValueError("no output specified")
# get all output targets and start / join them
for output_name in probe_config['output']:
output = plugin.get_output(output_name, self.plugin_context)
if not output.started:
output.start()
self.joins.append(output)
probe._emit.append(output)
probe.start()
self.joins.append(probe)
vaping.io.joinall(self.joins)
return 0
def start(self):
""" start daemon """
self._exec()
def stop(self):
""" stop daemon """
try:
with self.pidfile:
self.log.error("failed to stop, missing pid file or not running")
except pidfile.PidFileError:
# this isn't exposed in pidfile :o
with open(self.pidfile.filename) as fobj:
pid = int(fobj.readline().rstrip())
if not pid:
self.log.error("failed to read pid from file")
self.log.info("killing %d", pid)
os.kill(pid, signal.SIGTERM)
|
toastdriven/restless | restless/resources.py | skip_prepare | python | def skip_prepare(func):
@wraps(func)
def _wrapper(self, *args, **kwargs):
value = func(self, *args, **kwargs)
return Data(value, should_prepare=False)
return _wrapper | A convenience decorator for indicating the raw data should not be prepared. | train | https://github.com/toastdriven/restless/blob/661593b7b43c42d1bc508dec795356297991255e/restless/resources.py#L12-L20 | null | from functools import wraps
import sys
from .constants import OK, CREATED, ACCEPTED, NO_CONTENT
from .data import Data
from .exceptions import MethodNotImplemented, Unauthorized
from .preparers import Preparer
from .serializers import JSONSerializer
from .utils import format_traceback
class Resource(object):
"""
Defines a RESTful resource.
Users are expected to subclass this object & implement a handful of methods:
* ``list``
* ``detail``
* ``create`` (requires authentication)
* ``update`` (requires authentication)
* ``delete`` (requires authentication)
Additionally, the user may choose to implement:
* ``create_detail`` (requires authentication)
* ``update_list`` (requires authentication)
* ``delete_list`` (requires authentication)
Users may also wish to define a ``fields`` attribute on the class. By
providing a dictionary of output names mapped to a dotted lookup path, you
can control the serialized output.
Users may also choose to override the ``status_map`` and/or ``http_methods``
on the class. These respectively control the HTTP status codes returned by
the views and the way views are looked up (based on HTTP method & endpoint).
"""
status_map = {
'list': OK,
'detail': OK,
'create': CREATED,
'update': ACCEPTED,
'delete': NO_CONTENT,
'update_list': ACCEPTED,
'create_detail': CREATED,
'delete_list': NO_CONTENT,
}
http_methods = {
'list': {
'GET': 'list',
'POST': 'create',
'PUT': 'update_list',
'DELETE': 'delete_list',
},
'detail': {
'GET': 'detail',
'POST': 'create_detail',
'PUT': 'update',
'DELETE': 'delete',
}
}
preparer = Preparer()
serializer = JSONSerializer()
def __init__(self, *args, **kwargs):
self.init_args = args
self.init_kwargs = kwargs
self.request = None
self.data = None
self.endpoint = None
self.status = 200
@classmethod
def as_list(cls, *init_args, **init_kwargs):
"""
Used for hooking up the actual list-style endpoints, this returns a
wrapper function that creates a new instance of the resource class &
calls the correct view method for it.
:param init_args: (Optional) Positional params to be persisted along
for instantiating the class itself.
:param init_kwargs: (Optional) Keyword params to be persisted along
for instantiating the class itself.
:returns: View function
"""
return cls.as_view('list', *init_args, **init_kwargs)
@classmethod
def as_detail(cls, *init_args, **init_kwargs):
"""
Used for hooking up the actual detail-style endpoints, this returns a
wrapper function that creates a new instance of the resource class &
calls the correct view method for it.
:param init_args: (Optional) Positional params to be persisted along
for instantiating the class itself.
:param init_kwargs: (Optional) Keyword params to be persisted along
for instantiating the class itself.
:returns: View function
"""
return cls.as_view('detail', *init_args, **init_kwargs)
@classmethod
def as_view(cls, view_type, *init_args, **init_kwargs):
"""
Used for hooking up the all endpoints (including custom ones), this
returns a wrapper function that creates a new instance of the resource
class & calls the correct view method for it.
:param view_type: Should be one of ``list``, ``detail`` or ``custom``.
:type view_type: string
:param init_args: (Optional) Positional params to be persisted along
for instantiating the class itself.
:param init_kwargs: (Optional) Keyword params to be persisted along
for instantiating the class itself.
:returns: View function
"""
@wraps(cls)
def _wrapper(request, *args, **kwargs):
# Make a new instance so that no state potentially leaks between
# instances.
inst = cls(*init_args, **init_kwargs)
inst.request = request
return inst.handle(view_type, *args, **kwargs)
return _wrapper
def request_method(self):
"""
Returns the HTTP method for the current request.
If you're integrating with a new web framework, you might need to
override this method within your subclass.
:returns: The HTTP method in uppercase
:rtype: string
"""
# By default, Django-esque.
return self.request.method.upper()
def request_body(self):
"""
Returns the body of the current request.
Useful for deserializing the content the user sent (typically JSON).
If you're integrating with a new web framework, you might need to
override this method within your subclass.
:returns: The body of the request
:rtype: string
"""
# By default, Django-esque.
return self.request.body
def build_response(self, data, status=200):
"""
Given some data, generates an HTTP response.
If you're integrating with a new web framework, you **MUST**
override this method within your subclass.
:param data: The body of the response to send
:type data: string
:param status: (Optional) The status code to respond with. Default is
``200``
:type status: integer
:returns: A response object
"""
raise NotImplementedError()
def build_error(self, err):
"""
When an exception is encountered, this generates a JSON error message
for display to the user.
:param err: The exception seen. The message is exposed to the user, so
beware of sensitive data leaking.
:type err: Exception
:returns: A response object
"""
data = {
'error': err.args[0],
}
if self.is_debug():
# Add the traceback.
data['traceback'] = format_traceback(sys.exc_info())
body = self.serializer.serialize(data)
status = getattr(err, 'status', 500)
return self.build_response(body, status=status)
def is_debug(self):
"""
Controls whether or not the resource is in a debug environment.
If so, tracebacks will be added to the serialized response.
The default implementation simply returns ``False``, so if you're
integrating with a new web framework, you'll need to override this
method within your subclass.
:returns: If the resource is in a debug environment
:rtype: boolean
"""
return False
def bubble_exceptions(self):
"""
Controls whether or not exceptions will be re-raised when encountered.
The default implementation returns ``False``, which means errors should
return a serialized response.
If you'd like exceptions to be re-raised, override this method & return
``True``.
:returns: Whether exceptions should be re-raised or not
:rtype: boolean
"""
return False
def handle(self, endpoint, *args, **kwargs):
"""
A convenient dispatching method, this centralized some of the common
flow of the views.
This wraps/calls the methods the user defines (``list/detail/create``
etc.), allowing the user to ignore the
authentication/deserialization/serialization/response & just focus on
their data/interactions.
:param endpoint: The style of URI call (typically either ``list`` or
``detail``).
:type endpoint: string
:param args: (Optional) Any positional URI parameter data is passed
along here. Somewhat framework/URL-specific.
:param kwargs: (Optional) Any keyword/named URI parameter data is
passed along here. Somewhat framework/URL-specific.
:returns: A response object
"""
self.endpoint = endpoint
method = self.request_method()
try:
# Use ``.get()`` so we can also dodge potentially incorrect
# ``endpoint`` errors as well.
if not method in self.http_methods.get(endpoint, {}):
raise MethodNotImplemented(
"Unsupported method '{}' for {} endpoint.".format(
method,
endpoint
)
)
if not self.is_authenticated():
raise Unauthorized()
self.data = self.deserialize(method, endpoint, self.request_body())
view_method = getattr(self, self.http_methods[endpoint][method])
data = view_method(*args, **kwargs)
serialized = self.serialize(method, endpoint, data)
except Exception as err:
return self.handle_error(err)
status = self.status_map.get(self.http_methods[endpoint][method], OK)
return self.build_response(serialized, status=status)
def handle_error(self, err):
"""
When an exception is encountered, this generates a serialized error
message to return the user.
:param err: The exception seen. The message is exposed to the user, so
beware of sensitive data leaking.
:type err: Exception
:returns: A response object
"""
if self.bubble_exceptions():
raise err
return self.build_error(err)
def deserialize(self, method, endpoint, body):
"""
A convenience method for deserializing the body of a request.
If called on a list-style endpoint, this calls ``deserialize_list``.
Otherwise, it will call ``deserialize_detail``.
:param method: The HTTP method of the current request
:type method: string
:param endpoint: The endpoint style (``list`` or ``detail``)
:type endpoint: string
:param body: The body of the current request
:type body: string
:returns: The deserialized data
:rtype: ``list`` or ``dict``
"""
if endpoint == 'list':
return self.deserialize_list(body)
return self.deserialize_detail(body)
def deserialize_list(self, body):
"""
Given a string of text, deserializes a (presumed) list out of the body.
:param body: The body of the current request
:type body: string
:returns: The deserialized body or an empty ``list``
"""
if body:
return self.serializer.deserialize(body)
return []
def deserialize_detail(self, body):
"""
Given a string of text, deserializes a (presumed) object out of the body.
:param body: The body of the current request
:type body: string
:returns: The deserialized body or an empty ``dict``
"""
if body:
return self.serializer.deserialize(body)
return {}
def serialize(self, method, endpoint, data):
"""
A convenience method for serializing data for a response.
If called on a list-style endpoint, this calls ``serialize_list``.
Otherwise, it will call ``serialize_detail``.
:param method: The HTTP method of the current request
:type method: string
:param endpoint: The endpoint style (``list`` or ``detail``)
:type endpoint: string
:param data: The body for the response
:type data: string
:returns: A serialized version of the data
:rtype: string
"""
if endpoint == 'list':
# Create is a special-case, because you POST it to the collection,
# not to a detail.
if method == 'POST':
return self.serialize_detail(data)
return self.serialize_list(data)
return self.serialize_detail(data)
def serialize_list(self, data):
"""
Given a collection of data (``objects`` or ``dicts``), serializes them.
:param data: The collection of items to serialize
:type data: list or iterable
:returns: The serialized body
:rtype: string
"""
if data is None:
return ''
# Check for a ``Data``-like object. We should assume ``True`` (all
# data gets prepared) unless it's explicitly marked as not.
if not getattr(data, 'should_prepare', True):
prepped_data = data.value
else:
prepped_data = [self.prepare(item) for item in data]
final_data = self.wrap_list_response(prepped_data)
return self.serializer.serialize(final_data)
def serialize_detail(self, data):
"""
Given a single item (``object`` or ``dict``), serializes it.
:param data: The item to serialize
:type data: object or dict
:returns: The serialized body
:rtype: string
"""
if data is None:
return ''
# Check for a ``Data``-like object. We should assume ``True`` (all
# data gets prepared) unless it's explicitly marked as not.
if not getattr(data, 'should_prepare', True):
prepped_data = data.value
else:
prepped_data = self.prepare(data)
return self.serializer.serialize(prepped_data)
def prepare(self, data):
"""
Given an item (``object`` or ``dict``), this will potentially go through
& reshape the output based on ``self.prepare_with`` object.
:param data: An item to prepare for serialization
:type data: object or dict
:returns: A potentially reshaped dict
:rtype: dict
"""
return self.preparer.prepare(data)
def wrap_list_response(self, data):
"""
Takes a list of data & wraps it in a dictionary (within the ``objects``
key).
For security in JSON responses, it's better to wrap the list results in
an ``object`` (due to the way the ``Array`` constructor can be attacked
in Javascript). See http://haacked.com/archive/2009/06/25/json-hijacking.aspx/
& similar for details.
Overridable to allow for modifying the key names, adding data (or just
insecurely return a plain old list if that's your thing).
:param data: A list of data about to be serialized
:type data: list
:returns: A wrapping dict
:rtype: dict
"""
return {
"objects": data
}
def is_authenticated(self):
"""
A simple hook method for controlling whether a request is authenticated
to continue.
By default, we only allow the safe ``GET`` methods. All others are
denied.
:returns: Whether the request is authenticated or not.
:rtype: boolean
"""
if self.request_method() == 'GET':
return True
return False
# Common methods the user should implement.
def list(self, *args, **kwargs):
"""
Returns the data for a GET on a list-style endpoint.
**MUST BE OVERRIDDEN BY THE USER** - By default, this returns
``MethodNotImplemented``.
:returns: A collection of data
:rtype: list or iterable
"""
raise MethodNotImplemented()
def detail(self, *args, **kwargs):
"""
Returns the data for a GET on a detail-style endpoint.
**MUST BE OVERRIDDEN BY THE USER** - By default, this returns
``MethodNotImplemented``.
:returns: An item
:rtype: object or dict
"""
raise MethodNotImplemented()
def create(self, *args, **kwargs):
"""
Allows for creating data via a POST on a list-style endpoint.
**MUST BE OVERRIDDEN BY THE USER** - By default, this returns
``MethodNotImplemented``.
:returns: May return the created item or ``None``
"""
raise MethodNotImplemented()
def update(self, *args, **kwargs):
"""
Updates existing data for a PUT on a detail-style endpoint.
**MUST BE OVERRIDDEN BY THE USER** - By default, this returns
``MethodNotImplemented``.
:returns: May return the updated item or ``None``
"""
raise MethodNotImplemented()
def delete(self, *args, **kwargs):
"""
Deletes data for a DELETE on a detail-style endpoint.
**MUST BE OVERRIDDEN BY THE USER** - By default, this returns
``MethodNotImplemented``.
:returns: ``None``
"""
raise MethodNotImplemented()
# Uncommon methods the user should implement.
# These have intentionally uglier method names, which reflects just how
# much harder they are to get right.
def update_list(self, *args, **kwargs):
"""
Updates the entire collection for a PUT on a list-style endpoint.
Uncommonly implemented due to the complexity & (varying) busines-logic
involved.
**MUST BE OVERRIDDEN BY THE USER** - By default, this returns
``MethodNotImplemented``.
:returns: A collection of data
:rtype: list or iterable
"""
raise MethodNotImplemented()
def create_detail(self, *args, **kwargs):
"""
Creates a subcollection of data for a POST on a detail-style endpoint.
Uncommonly implemented due to the rarity of having nested collections.
**MUST BE OVERRIDDEN BY THE USER** - By default, this returns
``MethodNotImplemented``.
:returns: A collection of data
:rtype: list or iterable
"""
raise MethodNotImplemented()
def delete_list(self, *args, **kwargs):
"""
Deletes *ALL* data in the collection for a DELETE on a list-style
endpoint.
Uncommonly implemented due to potential of trashing large datasets.
Implement with care.
**MUST BE OVERRIDDEN BY THE USER** - By default, this returns
``MethodNotImplemented``.
:returns: ``None``
"""
raise MethodNotImplemented()
|
toastdriven/restless | restless/resources.py | Resource.as_view | python | def as_view(cls, view_type, *init_args, **init_kwargs):
@wraps(cls)
def _wrapper(request, *args, **kwargs):
# Make a new instance so that no state potentially leaks between
# instances.
inst = cls(*init_args, **init_kwargs)
inst.request = request
return inst.handle(view_type, *args, **kwargs)
return _wrapper | Used for hooking up the all endpoints (including custom ones), this
returns a wrapper function that creates a new instance of the resource
class & calls the correct view method for it.
:param view_type: Should be one of ``list``, ``detail`` or ``custom``.
:type view_type: string
:param init_args: (Optional) Positional params to be persisted along
for instantiating the class itself.
:param init_kwargs: (Optional) Keyword params to be persisted along
for instantiating the class itself.
:returns: View function | train | https://github.com/toastdriven/restless/blob/661593b7b43c42d1bc508dec795356297991255e/restless/resources.py#L119-L144 | null | class Resource(object):
"""
Defines a RESTful resource.
Users are expected to subclass this object & implement a handful of methods:
* ``list``
* ``detail``
* ``create`` (requires authentication)
* ``update`` (requires authentication)
* ``delete`` (requires authentication)
Additionally, the user may choose to implement:
* ``create_detail`` (requires authentication)
* ``update_list`` (requires authentication)
* ``delete_list`` (requires authentication)
Users may also wish to define a ``fields`` attribute on the class. By
providing a dictionary of output names mapped to a dotted lookup path, you
can control the serialized output.
Users may also choose to override the ``status_map`` and/or ``http_methods``
on the class. These respectively control the HTTP status codes returned by
the views and the way views are looked up (based on HTTP method & endpoint).
"""
status_map = {
'list': OK,
'detail': OK,
'create': CREATED,
'update': ACCEPTED,
'delete': NO_CONTENT,
'update_list': ACCEPTED,
'create_detail': CREATED,
'delete_list': NO_CONTENT,
}
http_methods = {
'list': {
'GET': 'list',
'POST': 'create',
'PUT': 'update_list',
'DELETE': 'delete_list',
},
'detail': {
'GET': 'detail',
'POST': 'create_detail',
'PUT': 'update',
'DELETE': 'delete',
}
}
preparer = Preparer()
serializer = JSONSerializer()
def __init__(self, *args, **kwargs):
self.init_args = args
self.init_kwargs = kwargs
self.request = None
self.data = None
self.endpoint = None
self.status = 200
@classmethod
def as_list(cls, *init_args, **init_kwargs):
"""
Used for hooking up the actual list-style endpoints, this returns a
wrapper function that creates a new instance of the resource class &
calls the correct view method for it.
:param init_args: (Optional) Positional params to be persisted along
for instantiating the class itself.
:param init_kwargs: (Optional) Keyword params to be persisted along
for instantiating the class itself.
:returns: View function
"""
return cls.as_view('list', *init_args, **init_kwargs)
@classmethod
def as_detail(cls, *init_args, **init_kwargs):
"""
Used for hooking up the actual detail-style endpoints, this returns a
wrapper function that creates a new instance of the resource class &
calls the correct view method for it.
:param init_args: (Optional) Positional params to be persisted along
for instantiating the class itself.
:param init_kwargs: (Optional) Keyword params to be persisted along
for instantiating the class itself.
:returns: View function
"""
return cls.as_view('detail', *init_args, **init_kwargs)
@classmethod
def request_method(self):
"""
Returns the HTTP method for the current request.
If you're integrating with a new web framework, you might need to
override this method within your subclass.
:returns: The HTTP method in uppercase
:rtype: string
"""
# By default, Django-esque.
return self.request.method.upper()
def request_body(self):
"""
Returns the body of the current request.
Useful for deserializing the content the user sent (typically JSON).
If you're integrating with a new web framework, you might need to
override this method within your subclass.
:returns: The body of the request
:rtype: string
"""
# By default, Django-esque.
return self.request.body
def build_response(self, data, status=200):
"""
Given some data, generates an HTTP response.
If you're integrating with a new web framework, you **MUST**
override this method within your subclass.
:param data: The body of the response to send
:type data: string
:param status: (Optional) The status code to respond with. Default is
``200``
:type status: integer
:returns: A response object
"""
raise NotImplementedError()
def build_error(self, err):
"""
When an exception is encountered, this generates a JSON error message
for display to the user.
:param err: The exception seen. The message is exposed to the user, so
beware of sensitive data leaking.
:type err: Exception
:returns: A response object
"""
data = {
'error': err.args[0],
}
if self.is_debug():
# Add the traceback.
data['traceback'] = format_traceback(sys.exc_info())
body = self.serializer.serialize(data)
status = getattr(err, 'status', 500)
return self.build_response(body, status=status)
def is_debug(self):
"""
Controls whether or not the resource is in a debug environment.
If so, tracebacks will be added to the serialized response.
The default implementation simply returns ``False``, so if you're
integrating with a new web framework, you'll need to override this
method within your subclass.
:returns: If the resource is in a debug environment
:rtype: boolean
"""
return False
def bubble_exceptions(self):
"""
Controls whether or not exceptions will be re-raised when encountered.
The default implementation returns ``False``, which means errors should
return a serialized response.
If you'd like exceptions to be re-raised, override this method & return
``True``.
:returns: Whether exceptions should be re-raised or not
:rtype: boolean
"""
return False
def handle(self, endpoint, *args, **kwargs):
"""
A convenient dispatching method, this centralized some of the common
flow of the views.
This wraps/calls the methods the user defines (``list/detail/create``
etc.), allowing the user to ignore the
authentication/deserialization/serialization/response & just focus on
their data/interactions.
:param endpoint: The style of URI call (typically either ``list`` or
``detail``).
:type endpoint: string
:param args: (Optional) Any positional URI parameter data is passed
along here. Somewhat framework/URL-specific.
:param kwargs: (Optional) Any keyword/named URI parameter data is
passed along here. Somewhat framework/URL-specific.
:returns: A response object
"""
self.endpoint = endpoint
method = self.request_method()
try:
# Use ``.get()`` so we can also dodge potentially incorrect
# ``endpoint`` errors as well.
if not method in self.http_methods.get(endpoint, {}):
raise MethodNotImplemented(
"Unsupported method '{}' for {} endpoint.".format(
method,
endpoint
)
)
if not self.is_authenticated():
raise Unauthorized()
self.data = self.deserialize(method, endpoint, self.request_body())
view_method = getattr(self, self.http_methods[endpoint][method])
data = view_method(*args, **kwargs)
serialized = self.serialize(method, endpoint, data)
except Exception as err:
return self.handle_error(err)
status = self.status_map.get(self.http_methods[endpoint][method], OK)
return self.build_response(serialized, status=status)
def handle_error(self, err):
"""
When an exception is encountered, this generates a serialized error
message to return the user.
:param err: The exception seen. The message is exposed to the user, so
beware of sensitive data leaking.
:type err: Exception
:returns: A response object
"""
if self.bubble_exceptions():
raise err
return self.build_error(err)
def deserialize(self, method, endpoint, body):
"""
A convenience method for deserializing the body of a request.
If called on a list-style endpoint, this calls ``deserialize_list``.
Otherwise, it will call ``deserialize_detail``.
:param method: The HTTP method of the current request
:type method: string
:param endpoint: The endpoint style (``list`` or ``detail``)
:type endpoint: string
:param body: The body of the current request
:type body: string
:returns: The deserialized data
:rtype: ``list`` or ``dict``
"""
if endpoint == 'list':
return self.deserialize_list(body)
return self.deserialize_detail(body)
def deserialize_list(self, body):
"""
Given a string of text, deserializes a (presumed) list out of the body.
:param body: The body of the current request
:type body: string
:returns: The deserialized body or an empty ``list``
"""
if body:
return self.serializer.deserialize(body)
return []
def deserialize_detail(self, body):
"""
Given a string of text, deserializes a (presumed) object out of the body.
:param body: The body of the current request
:type body: string
:returns: The deserialized body or an empty ``dict``
"""
if body:
return self.serializer.deserialize(body)
return {}
def serialize(self, method, endpoint, data):
"""
A convenience method for serializing data for a response.
If called on a list-style endpoint, this calls ``serialize_list``.
Otherwise, it will call ``serialize_detail``.
:param method: The HTTP method of the current request
:type method: string
:param endpoint: The endpoint style (``list`` or ``detail``)
:type endpoint: string
:param data: The body for the response
:type data: string
:returns: A serialized version of the data
:rtype: string
"""
if endpoint == 'list':
# Create is a special-case, because you POST it to the collection,
# not to a detail.
if method == 'POST':
return self.serialize_detail(data)
return self.serialize_list(data)
return self.serialize_detail(data)
def serialize_list(self, data):
"""
Given a collection of data (``objects`` or ``dicts``), serializes them.
:param data: The collection of items to serialize
:type data: list or iterable
:returns: The serialized body
:rtype: string
"""
if data is None:
return ''
# Check for a ``Data``-like object. We should assume ``True`` (all
# data gets prepared) unless it's explicitly marked as not.
if not getattr(data, 'should_prepare', True):
prepped_data = data.value
else:
prepped_data = [self.prepare(item) for item in data]
final_data = self.wrap_list_response(prepped_data)
return self.serializer.serialize(final_data)
def serialize_detail(self, data):
"""
Given a single item (``object`` or ``dict``), serializes it.
:param data: The item to serialize
:type data: object or dict
:returns: The serialized body
:rtype: string
"""
if data is None:
return ''
# Check for a ``Data``-like object. We should assume ``True`` (all
# data gets prepared) unless it's explicitly marked as not.
if not getattr(data, 'should_prepare', True):
prepped_data = data.value
else:
prepped_data = self.prepare(data)
return self.serializer.serialize(prepped_data)
def prepare(self, data):
"""
Given an item (``object`` or ``dict``), this will potentially go through
& reshape the output based on ``self.prepare_with`` object.
:param data: An item to prepare for serialization
:type data: object or dict
:returns: A potentially reshaped dict
:rtype: dict
"""
return self.preparer.prepare(data)
def wrap_list_response(self, data):
"""
Takes a list of data & wraps it in a dictionary (within the ``objects``
key).
For security in JSON responses, it's better to wrap the list results in
an ``object`` (due to the way the ``Array`` constructor can be attacked
in Javascript). See http://haacked.com/archive/2009/06/25/json-hijacking.aspx/
& similar for details.
Overridable to allow for modifying the key names, adding data (or just
insecurely return a plain old list if that's your thing).
:param data: A list of data about to be serialized
:type data: list
:returns: A wrapping dict
:rtype: dict
"""
return {
"objects": data
}
def is_authenticated(self):
"""
A simple hook method for controlling whether a request is authenticated
to continue.
By default, we only allow the safe ``GET`` methods. All others are
denied.
:returns: Whether the request is authenticated or not.
:rtype: boolean
"""
if self.request_method() == 'GET':
return True
return False
# Common methods the user should implement.
def list(self, *args, **kwargs):
"""
Returns the data for a GET on a list-style endpoint.
**MUST BE OVERRIDDEN BY THE USER** - By default, this returns
``MethodNotImplemented``.
:returns: A collection of data
:rtype: list or iterable
"""
raise MethodNotImplemented()
def detail(self, *args, **kwargs):
"""
Returns the data for a GET on a detail-style endpoint.
**MUST BE OVERRIDDEN BY THE USER** - By default, this returns
``MethodNotImplemented``.
:returns: An item
:rtype: object or dict
"""
raise MethodNotImplemented()
def create(self, *args, **kwargs):
"""
Allows for creating data via a POST on a list-style endpoint.
**MUST BE OVERRIDDEN BY THE USER** - By default, this returns
``MethodNotImplemented``.
:returns: May return the created item or ``None``
"""
raise MethodNotImplemented()
def update(self, *args, **kwargs):
"""
Updates existing data for a PUT on a detail-style endpoint.
**MUST BE OVERRIDDEN BY THE USER** - By default, this returns
``MethodNotImplemented``.
:returns: May return the updated item or ``None``
"""
raise MethodNotImplemented()
def delete(self, *args, **kwargs):
"""
Deletes data for a DELETE on a detail-style endpoint.
**MUST BE OVERRIDDEN BY THE USER** - By default, this returns
``MethodNotImplemented``.
:returns: ``None``
"""
raise MethodNotImplemented()
# Uncommon methods the user should implement.
# These have intentionally uglier method names, which reflects just how
# much harder they are to get right.
def update_list(self, *args, **kwargs):
"""
Updates the entire collection for a PUT on a list-style endpoint.
Uncommonly implemented due to the complexity & (varying) busines-logic
involved.
**MUST BE OVERRIDDEN BY THE USER** - By default, this returns
``MethodNotImplemented``.
:returns: A collection of data
:rtype: list or iterable
"""
raise MethodNotImplemented()
def create_detail(self, *args, **kwargs):
"""
Creates a subcollection of data for a POST on a detail-style endpoint.
Uncommonly implemented due to the rarity of having nested collections.
**MUST BE OVERRIDDEN BY THE USER** - By default, this returns
``MethodNotImplemented``.
:returns: A collection of data
:rtype: list or iterable
"""
raise MethodNotImplemented()
def delete_list(self, *args, **kwargs):
"""
Deletes *ALL* data in the collection for a DELETE on a list-style
endpoint.
Uncommonly implemented due to potential of trashing large datasets.
Implement with care.
**MUST BE OVERRIDDEN BY THE USER** - By default, this returns
``MethodNotImplemented``.
:returns: ``None``
"""
raise MethodNotImplemented()
|
toastdriven/restless | restless/resources.py | Resource.build_error | python | def build_error(self, err):
data = {
'error': err.args[0],
}
if self.is_debug():
# Add the traceback.
data['traceback'] = format_traceback(sys.exc_info())
body = self.serializer.serialize(data)
status = getattr(err, 'status', 500)
return self.build_response(body, status=status) | When an exception is encountered, this generates a JSON error message
for display to the user.
:param err: The exception seen. The message is exposed to the user, so
beware of sensitive data leaking.
:type err: Exception
:returns: A response object | train | https://github.com/toastdriven/restless/blob/661593b7b43c42d1bc508dec795356297991255e/restless/resources.py#L192-L213 | [
"def format_traceback(exc_info):\n stack = traceback.format_stack()\n stack = stack[:-2]\n stack.extend(traceback.format_tb(exc_info[2]))\n stack.extend(traceback.format_exception_only(exc_info[0], exc_info[1]))\n stack_str = \"Traceback (most recent call last):\\n\"\n stack_str += \"\".join(stack)\n # Remove the last \\n\n stack_str = stack_str[:-1]\n return stack_str\n",
"def is_debug(self):\n return settings.DEBUG\n",
"def build_response(self, data, status=OK):\n if status == NO_CONTENT:\n # Avoid crashing the client when it tries to parse nonexisting JSON.\n content_type = 'text/plain'\n else:\n content_type = 'application/json'\n resp = HttpResponse(data, content_type=content_type, status=status)\n return resp\n",
"def build_response(self, data, status=200):\n \"\"\"\n Given some data, generates an HTTP response.\n\n If you're integrating with a new web framework, you **MUST**\n override this method within your subclass.\n\n :param data: The body of the response to send\n :type data: string\n\n :param status: (Optional) The status code to respond with. Default is\n ``200``\n :type status: integer\n\n :returns: A response object\n \"\"\"\n raise NotImplementedError()\n",
"def is_debug(self):\n \"\"\"\n Controls whether or not the resource is in a debug environment.\n\n If so, tracebacks will be added to the serialized response.\n\n The default implementation simply returns ``False``, so if you're\n integrating with a new web framework, you'll need to override this\n method within your subclass.\n\n :returns: If the resource is in a debug environment\n :rtype: boolean\n \"\"\"\n return False\n"
] | class Resource(object):
"""
Defines a RESTful resource.
Users are expected to subclass this object & implement a handful of methods:
* ``list``
* ``detail``
* ``create`` (requires authentication)
* ``update`` (requires authentication)
* ``delete`` (requires authentication)
Additionally, the user may choose to implement:
* ``create_detail`` (requires authentication)
* ``update_list`` (requires authentication)
* ``delete_list`` (requires authentication)
Users may also wish to define a ``fields`` attribute on the class. By
providing a dictionary of output names mapped to a dotted lookup path, you
can control the serialized output.
Users may also choose to override the ``status_map`` and/or ``http_methods``
on the class. These respectively control the HTTP status codes returned by
the views and the way views are looked up (based on HTTP method & endpoint).
"""
status_map = {
'list': OK,
'detail': OK,
'create': CREATED,
'update': ACCEPTED,
'delete': NO_CONTENT,
'update_list': ACCEPTED,
'create_detail': CREATED,
'delete_list': NO_CONTENT,
}
http_methods = {
'list': {
'GET': 'list',
'POST': 'create',
'PUT': 'update_list',
'DELETE': 'delete_list',
},
'detail': {
'GET': 'detail',
'POST': 'create_detail',
'PUT': 'update',
'DELETE': 'delete',
}
}
preparer = Preparer()
serializer = JSONSerializer()
def __init__(self, *args, **kwargs):
self.init_args = args
self.init_kwargs = kwargs
self.request = None
self.data = None
self.endpoint = None
self.status = 200
@classmethod
def as_list(cls, *init_args, **init_kwargs):
"""
Used for hooking up the actual list-style endpoints, this returns a
wrapper function that creates a new instance of the resource class &
calls the correct view method for it.
:param init_args: (Optional) Positional params to be persisted along
for instantiating the class itself.
:param init_kwargs: (Optional) Keyword params to be persisted along
for instantiating the class itself.
:returns: View function
"""
return cls.as_view('list', *init_args, **init_kwargs)
@classmethod
def as_detail(cls, *init_args, **init_kwargs):
"""
Used for hooking up the actual detail-style endpoints, this returns a
wrapper function that creates a new instance of the resource class &
calls the correct view method for it.
:param init_args: (Optional) Positional params to be persisted along
for instantiating the class itself.
:param init_kwargs: (Optional) Keyword params to be persisted along
for instantiating the class itself.
:returns: View function
"""
return cls.as_view('detail', *init_args, **init_kwargs)
@classmethod
def as_view(cls, view_type, *init_args, **init_kwargs):
"""
Used for hooking up the all endpoints (including custom ones), this
returns a wrapper function that creates a new instance of the resource
class & calls the correct view method for it.
:param view_type: Should be one of ``list``, ``detail`` or ``custom``.
:type view_type: string
:param init_args: (Optional) Positional params to be persisted along
for instantiating the class itself.
:param init_kwargs: (Optional) Keyword params to be persisted along
for instantiating the class itself.
:returns: View function
"""
@wraps(cls)
def _wrapper(request, *args, **kwargs):
# Make a new instance so that no state potentially leaks between
# instances.
inst = cls(*init_args, **init_kwargs)
inst.request = request
return inst.handle(view_type, *args, **kwargs)
return _wrapper
def request_method(self):
"""
Returns the HTTP method for the current request.
If you're integrating with a new web framework, you might need to
override this method within your subclass.
:returns: The HTTP method in uppercase
:rtype: string
"""
# By default, Django-esque.
return self.request.method.upper()
def request_body(self):
"""
Returns the body of the current request.
Useful for deserializing the content the user sent (typically JSON).
If you're integrating with a new web framework, you might need to
override this method within your subclass.
:returns: The body of the request
:rtype: string
"""
# By default, Django-esque.
return self.request.body
def build_response(self, data, status=200):
"""
Given some data, generates an HTTP response.
If you're integrating with a new web framework, you **MUST**
override this method within your subclass.
:param data: The body of the response to send
:type data: string
:param status: (Optional) The status code to respond with. Default is
``200``
:type status: integer
:returns: A response object
"""
raise NotImplementedError()
def is_debug(self):
"""
Controls whether or not the resource is in a debug environment.
If so, tracebacks will be added to the serialized response.
The default implementation simply returns ``False``, so if you're
integrating with a new web framework, you'll need to override this
method within your subclass.
:returns: If the resource is in a debug environment
:rtype: boolean
"""
return False
def bubble_exceptions(self):
"""
Controls whether or not exceptions will be re-raised when encountered.
The default implementation returns ``False``, which means errors should
return a serialized response.
If you'd like exceptions to be re-raised, override this method & return
``True``.
:returns: Whether exceptions should be re-raised or not
:rtype: boolean
"""
return False
def handle(self, endpoint, *args, **kwargs):
"""
A convenient dispatching method, this centralized some of the common
flow of the views.
This wraps/calls the methods the user defines (``list/detail/create``
etc.), allowing the user to ignore the
authentication/deserialization/serialization/response & just focus on
their data/interactions.
:param endpoint: The style of URI call (typically either ``list`` or
``detail``).
:type endpoint: string
:param args: (Optional) Any positional URI parameter data is passed
along here. Somewhat framework/URL-specific.
:param kwargs: (Optional) Any keyword/named URI parameter data is
passed along here. Somewhat framework/URL-specific.
:returns: A response object
"""
self.endpoint = endpoint
method = self.request_method()
try:
# Use ``.get()`` so we can also dodge potentially incorrect
# ``endpoint`` errors as well.
if not method in self.http_methods.get(endpoint, {}):
raise MethodNotImplemented(
"Unsupported method '{}' for {} endpoint.".format(
method,
endpoint
)
)
if not self.is_authenticated():
raise Unauthorized()
self.data = self.deserialize(method, endpoint, self.request_body())
view_method = getattr(self, self.http_methods[endpoint][method])
data = view_method(*args, **kwargs)
serialized = self.serialize(method, endpoint, data)
except Exception as err:
return self.handle_error(err)
status = self.status_map.get(self.http_methods[endpoint][method], OK)
return self.build_response(serialized, status=status)
def handle_error(self, err):
"""
When an exception is encountered, this generates a serialized error
message to return the user.
:param err: The exception seen. The message is exposed to the user, so
beware of sensitive data leaking.
:type err: Exception
:returns: A response object
"""
if self.bubble_exceptions():
raise err
return self.build_error(err)
def deserialize(self, method, endpoint, body):
"""
A convenience method for deserializing the body of a request.
If called on a list-style endpoint, this calls ``deserialize_list``.
Otherwise, it will call ``deserialize_detail``.
:param method: The HTTP method of the current request
:type method: string
:param endpoint: The endpoint style (``list`` or ``detail``)
:type endpoint: string
:param body: The body of the current request
:type body: string
:returns: The deserialized data
:rtype: ``list`` or ``dict``
"""
if endpoint == 'list':
return self.deserialize_list(body)
return self.deserialize_detail(body)
def deserialize_list(self, body):
"""
Given a string of text, deserializes a (presumed) list out of the body.
:param body: The body of the current request
:type body: string
:returns: The deserialized body or an empty ``list``
"""
if body:
return self.serializer.deserialize(body)
return []
def deserialize_detail(self, body):
"""
Given a string of text, deserializes a (presumed) object out of the body.
:param body: The body of the current request
:type body: string
:returns: The deserialized body or an empty ``dict``
"""
if body:
return self.serializer.deserialize(body)
return {}
def serialize(self, method, endpoint, data):
"""
A convenience method for serializing data for a response.
If called on a list-style endpoint, this calls ``serialize_list``.
Otherwise, it will call ``serialize_detail``.
:param method: The HTTP method of the current request
:type method: string
:param endpoint: The endpoint style (``list`` or ``detail``)
:type endpoint: string
:param data: The body for the response
:type data: string
:returns: A serialized version of the data
:rtype: string
"""
if endpoint == 'list':
# Create is a special-case, because you POST it to the collection,
# not to a detail.
if method == 'POST':
return self.serialize_detail(data)
return self.serialize_list(data)
return self.serialize_detail(data)
def serialize_list(self, data):
"""
Given a collection of data (``objects`` or ``dicts``), serializes them.
:param data: The collection of items to serialize
:type data: list or iterable
:returns: The serialized body
:rtype: string
"""
if data is None:
return ''
# Check for a ``Data``-like object. We should assume ``True`` (all
# data gets prepared) unless it's explicitly marked as not.
if not getattr(data, 'should_prepare', True):
prepped_data = data.value
else:
prepped_data = [self.prepare(item) for item in data]
final_data = self.wrap_list_response(prepped_data)
return self.serializer.serialize(final_data)
def serialize_detail(self, data):
"""
Given a single item (``object`` or ``dict``), serializes it.
:param data: The item to serialize
:type data: object or dict
:returns: The serialized body
:rtype: string
"""
if data is None:
return ''
# Check for a ``Data``-like object. We should assume ``True`` (all
# data gets prepared) unless it's explicitly marked as not.
if not getattr(data, 'should_prepare', True):
prepped_data = data.value
else:
prepped_data = self.prepare(data)
return self.serializer.serialize(prepped_data)
def prepare(self, data):
"""
Given an item (``object`` or ``dict``), this will potentially go through
& reshape the output based on ``self.prepare_with`` object.
:param data: An item to prepare for serialization
:type data: object or dict
:returns: A potentially reshaped dict
:rtype: dict
"""
return self.preparer.prepare(data)
def wrap_list_response(self, data):
"""
Takes a list of data & wraps it in a dictionary (within the ``objects``
key).
For security in JSON responses, it's better to wrap the list results in
an ``object`` (due to the way the ``Array`` constructor can be attacked
in Javascript). See http://haacked.com/archive/2009/06/25/json-hijacking.aspx/
& similar for details.
Overridable to allow for modifying the key names, adding data (or just
insecurely return a plain old list if that's your thing).
:param data: A list of data about to be serialized
:type data: list
:returns: A wrapping dict
:rtype: dict
"""
return {
"objects": data
}
def is_authenticated(self):
"""
A simple hook method for controlling whether a request is authenticated
to continue.
By default, we only allow the safe ``GET`` methods. All others are
denied.
:returns: Whether the request is authenticated or not.
:rtype: boolean
"""
if self.request_method() == 'GET':
return True
return False
# Common methods the user should implement.
def list(self, *args, **kwargs):
"""
Returns the data for a GET on a list-style endpoint.
**MUST BE OVERRIDDEN BY THE USER** - By default, this returns
``MethodNotImplemented``.
:returns: A collection of data
:rtype: list or iterable
"""
raise MethodNotImplemented()
def detail(self, *args, **kwargs):
"""
Returns the data for a GET on a detail-style endpoint.
**MUST BE OVERRIDDEN BY THE USER** - By default, this returns
``MethodNotImplemented``.
:returns: An item
:rtype: object or dict
"""
raise MethodNotImplemented()
def create(self, *args, **kwargs):
"""
Allows for creating data via a POST on a list-style endpoint.
**MUST BE OVERRIDDEN BY THE USER** - By default, this returns
``MethodNotImplemented``.
:returns: May return the created item or ``None``
"""
raise MethodNotImplemented()
def update(self, *args, **kwargs):
"""
Updates existing data for a PUT on a detail-style endpoint.
**MUST BE OVERRIDDEN BY THE USER** - By default, this returns
``MethodNotImplemented``.
:returns: May return the updated item or ``None``
"""
raise MethodNotImplemented()
def delete(self, *args, **kwargs):
"""
Deletes data for a DELETE on a detail-style endpoint.
**MUST BE OVERRIDDEN BY THE USER** - By default, this returns
``MethodNotImplemented``.
:returns: ``None``
"""
raise MethodNotImplemented()
# Uncommon methods the user should implement.
# These have intentionally uglier method names, which reflects just how
# much harder they are to get right.
def update_list(self, *args, **kwargs):
"""
Updates the entire collection for a PUT on a list-style endpoint.
Uncommonly implemented due to the complexity & (varying) busines-logic
involved.
**MUST BE OVERRIDDEN BY THE USER** - By default, this returns
``MethodNotImplemented``.
:returns: A collection of data
:rtype: list or iterable
"""
raise MethodNotImplemented()
def create_detail(self, *args, **kwargs):
"""
Creates a subcollection of data for a POST on a detail-style endpoint.
Uncommonly implemented due to the rarity of having nested collections.
**MUST BE OVERRIDDEN BY THE USER** - By default, this returns
``MethodNotImplemented``.
:returns: A collection of data
:rtype: list or iterable
"""
raise MethodNotImplemented()
def delete_list(self, *args, **kwargs):
"""
Deletes *ALL* data in the collection for a DELETE on a list-style
endpoint.
Uncommonly implemented due to potential of trashing large datasets.
Implement with care.
**MUST BE OVERRIDDEN BY THE USER** - By default, this returns
``MethodNotImplemented``.
:returns: ``None``
"""
raise MethodNotImplemented()
|
toastdriven/restless | restless/resources.py | Resource.deserialize | python | def deserialize(self, method, endpoint, body):
if endpoint == 'list':
return self.deserialize_list(body)
return self.deserialize_detail(body) | A convenience method for deserializing the body of a request.
If called on a list-style endpoint, this calls ``deserialize_list``.
Otherwise, it will call ``deserialize_detail``.
:param method: The HTTP method of the current request
:type method: string
:param endpoint: The endpoint style (``list`` or ``detail``)
:type endpoint: string
:param body: The body of the current request
:type body: string
:returns: The deserialized data
:rtype: ``list`` or ``dict`` | train | https://github.com/toastdriven/restless/blob/661593b7b43c42d1bc508dec795356297991255e/restless/resources.py#L310-L332 | [
"def deserialize_list(self, body):\n \"\"\"\n Given a string of text, deserializes a (presumed) list out of the body.\n\n :param body: The body of the current request\n :type body: string\n\n :returns: The deserialized body or an empty ``list``\n \"\"\"\n if body:\n return self.serializer.deserialize(body)\n\n return []\n",
"def deserialize_detail(self, body):\n \"\"\"\n Given a string of text, deserializes a (presumed) object out of the body.\n\n :param body: The body of the current request\n :type body: string\n\n :returns: The deserialized body or an empty ``dict``\n \"\"\"\n if body:\n return self.serializer.deserialize(body)\n\n return {}\n"
] | class Resource(object):
"""
Defines a RESTful resource.
Users are expected to subclass this object & implement a handful of methods:
* ``list``
* ``detail``
* ``create`` (requires authentication)
* ``update`` (requires authentication)
* ``delete`` (requires authentication)
Additionally, the user may choose to implement:
* ``create_detail`` (requires authentication)
* ``update_list`` (requires authentication)
* ``delete_list`` (requires authentication)
Users may also wish to define a ``fields`` attribute on the class. By
providing a dictionary of output names mapped to a dotted lookup path, you
can control the serialized output.
Users may also choose to override the ``status_map`` and/or ``http_methods``
on the class. These respectively control the HTTP status codes returned by
the views and the way views are looked up (based on HTTP method & endpoint).
"""
status_map = {
'list': OK,
'detail': OK,
'create': CREATED,
'update': ACCEPTED,
'delete': NO_CONTENT,
'update_list': ACCEPTED,
'create_detail': CREATED,
'delete_list': NO_CONTENT,
}
http_methods = {
'list': {
'GET': 'list',
'POST': 'create',
'PUT': 'update_list',
'DELETE': 'delete_list',
},
'detail': {
'GET': 'detail',
'POST': 'create_detail',
'PUT': 'update',
'DELETE': 'delete',
}
}
preparer = Preparer()
serializer = JSONSerializer()
def __init__(self, *args, **kwargs):
self.init_args = args
self.init_kwargs = kwargs
self.request = None
self.data = None
self.endpoint = None
self.status = 200
@classmethod
def as_list(cls, *init_args, **init_kwargs):
"""
Used for hooking up the actual list-style endpoints, this returns a
wrapper function that creates a new instance of the resource class &
calls the correct view method for it.
:param init_args: (Optional) Positional params to be persisted along
for instantiating the class itself.
:param init_kwargs: (Optional) Keyword params to be persisted along
for instantiating the class itself.
:returns: View function
"""
return cls.as_view('list', *init_args, **init_kwargs)
@classmethod
def as_detail(cls, *init_args, **init_kwargs):
"""
Used for hooking up the actual detail-style endpoints, this returns a
wrapper function that creates a new instance of the resource class &
calls the correct view method for it.
:param init_args: (Optional) Positional params to be persisted along
for instantiating the class itself.
:param init_kwargs: (Optional) Keyword params to be persisted along
for instantiating the class itself.
:returns: View function
"""
return cls.as_view('detail', *init_args, **init_kwargs)
@classmethod
def as_view(cls, view_type, *init_args, **init_kwargs):
"""
Used for hooking up the all endpoints (including custom ones), this
returns a wrapper function that creates a new instance of the resource
class & calls the correct view method for it.
:param view_type: Should be one of ``list``, ``detail`` or ``custom``.
:type view_type: string
:param init_args: (Optional) Positional params to be persisted along
for instantiating the class itself.
:param init_kwargs: (Optional) Keyword params to be persisted along
for instantiating the class itself.
:returns: View function
"""
@wraps(cls)
def _wrapper(request, *args, **kwargs):
# Make a new instance so that no state potentially leaks between
# instances.
inst = cls(*init_args, **init_kwargs)
inst.request = request
return inst.handle(view_type, *args, **kwargs)
return _wrapper
def request_method(self):
"""
Returns the HTTP method for the current request.
If you're integrating with a new web framework, you might need to
override this method within your subclass.
:returns: The HTTP method in uppercase
:rtype: string
"""
# By default, Django-esque.
return self.request.method.upper()
def request_body(self):
"""
Returns the body of the current request.
Useful for deserializing the content the user sent (typically JSON).
If you're integrating with a new web framework, you might need to
override this method within your subclass.
:returns: The body of the request
:rtype: string
"""
# By default, Django-esque.
return self.request.body
def build_response(self, data, status=200):
"""
Given some data, generates an HTTP response.
If you're integrating with a new web framework, you **MUST**
override this method within your subclass.
:param data: The body of the response to send
:type data: string
:param status: (Optional) The status code to respond with. Default is
``200``
:type status: integer
:returns: A response object
"""
raise NotImplementedError()
def build_error(self, err):
"""
When an exception is encountered, this generates a JSON error message
for display to the user.
:param err: The exception seen. The message is exposed to the user, so
beware of sensitive data leaking.
:type err: Exception
:returns: A response object
"""
data = {
'error': err.args[0],
}
if self.is_debug():
# Add the traceback.
data['traceback'] = format_traceback(sys.exc_info())
body = self.serializer.serialize(data)
status = getattr(err, 'status', 500)
return self.build_response(body, status=status)
def is_debug(self):
"""
Controls whether or not the resource is in a debug environment.
If so, tracebacks will be added to the serialized response.
The default implementation simply returns ``False``, so if you're
integrating with a new web framework, you'll need to override this
method within your subclass.
:returns: If the resource is in a debug environment
:rtype: boolean
"""
return False
def bubble_exceptions(self):
"""
Controls whether or not exceptions will be re-raised when encountered.
The default implementation returns ``False``, which means errors should
return a serialized response.
If you'd like exceptions to be re-raised, override this method & return
``True``.
:returns: Whether exceptions should be re-raised or not
:rtype: boolean
"""
return False
def handle(self, endpoint, *args, **kwargs):
"""
A convenient dispatching method, this centralized some of the common
flow of the views.
This wraps/calls the methods the user defines (``list/detail/create``
etc.), allowing the user to ignore the
authentication/deserialization/serialization/response & just focus on
their data/interactions.
:param endpoint: The style of URI call (typically either ``list`` or
``detail``).
:type endpoint: string
:param args: (Optional) Any positional URI parameter data is passed
along here. Somewhat framework/URL-specific.
:param kwargs: (Optional) Any keyword/named URI parameter data is
passed along here. Somewhat framework/URL-specific.
:returns: A response object
"""
self.endpoint = endpoint
method = self.request_method()
try:
# Use ``.get()`` so we can also dodge potentially incorrect
# ``endpoint`` errors as well.
if not method in self.http_methods.get(endpoint, {}):
raise MethodNotImplemented(
"Unsupported method '{}' for {} endpoint.".format(
method,
endpoint
)
)
if not self.is_authenticated():
raise Unauthorized()
self.data = self.deserialize(method, endpoint, self.request_body())
view_method = getattr(self, self.http_methods[endpoint][method])
data = view_method(*args, **kwargs)
serialized = self.serialize(method, endpoint, data)
except Exception as err:
return self.handle_error(err)
status = self.status_map.get(self.http_methods[endpoint][method], OK)
return self.build_response(serialized, status=status)
def handle_error(self, err):
"""
When an exception is encountered, this generates a serialized error
message to return the user.
:param err: The exception seen. The message is exposed to the user, so
beware of sensitive data leaking.
:type err: Exception
:returns: A response object
"""
if self.bubble_exceptions():
raise err
return self.build_error(err)
def deserialize_list(self, body):
"""
Given a string of text, deserializes a (presumed) list out of the body.
:param body: The body of the current request
:type body: string
:returns: The deserialized body or an empty ``list``
"""
if body:
return self.serializer.deserialize(body)
return []
def deserialize_detail(self, body):
"""
Given a string of text, deserializes a (presumed) object out of the body.
:param body: The body of the current request
:type body: string
:returns: The deserialized body or an empty ``dict``
"""
if body:
return self.serializer.deserialize(body)
return {}
def serialize(self, method, endpoint, data):
"""
A convenience method for serializing data for a response.
If called on a list-style endpoint, this calls ``serialize_list``.
Otherwise, it will call ``serialize_detail``.
:param method: The HTTP method of the current request
:type method: string
:param endpoint: The endpoint style (``list`` or ``detail``)
:type endpoint: string
:param data: The body for the response
:type data: string
:returns: A serialized version of the data
:rtype: string
"""
if endpoint == 'list':
# Create is a special-case, because you POST it to the collection,
# not to a detail.
if method == 'POST':
return self.serialize_detail(data)
return self.serialize_list(data)
return self.serialize_detail(data)
def serialize_list(self, data):
"""
Given a collection of data (``objects`` or ``dicts``), serializes them.
:param data: The collection of items to serialize
:type data: list or iterable
:returns: The serialized body
:rtype: string
"""
if data is None:
return ''
# Check for a ``Data``-like object. We should assume ``True`` (all
# data gets prepared) unless it's explicitly marked as not.
if not getattr(data, 'should_prepare', True):
prepped_data = data.value
else:
prepped_data = [self.prepare(item) for item in data]
final_data = self.wrap_list_response(prepped_data)
return self.serializer.serialize(final_data)
def serialize_detail(self, data):
"""
Given a single item (``object`` or ``dict``), serializes it.
:param data: The item to serialize
:type data: object or dict
:returns: The serialized body
:rtype: string
"""
if data is None:
return ''
# Check for a ``Data``-like object. We should assume ``True`` (all
# data gets prepared) unless it's explicitly marked as not.
if not getattr(data, 'should_prepare', True):
prepped_data = data.value
else:
prepped_data = self.prepare(data)
return self.serializer.serialize(prepped_data)
def prepare(self, data):
"""
Given an item (``object`` or ``dict``), this will potentially go through
& reshape the output based on ``self.prepare_with`` object.
:param data: An item to prepare for serialization
:type data: object or dict
:returns: A potentially reshaped dict
:rtype: dict
"""
return self.preparer.prepare(data)
def wrap_list_response(self, data):
"""
Takes a list of data & wraps it in a dictionary (within the ``objects``
key).
For security in JSON responses, it's better to wrap the list results in
an ``object`` (due to the way the ``Array`` constructor can be attacked
in Javascript). See http://haacked.com/archive/2009/06/25/json-hijacking.aspx/
& similar for details.
Overridable to allow for modifying the key names, adding data (or just
insecurely return a plain old list if that's your thing).
:param data: A list of data about to be serialized
:type data: list
:returns: A wrapping dict
:rtype: dict
"""
return {
"objects": data
}
def is_authenticated(self):
"""
A simple hook method for controlling whether a request is authenticated
to continue.
By default, we only allow the safe ``GET`` methods. All others are
denied.
:returns: Whether the request is authenticated or not.
:rtype: boolean
"""
if self.request_method() == 'GET':
return True
return False
# Common methods the user should implement.
def list(self, *args, **kwargs):
"""
Returns the data for a GET on a list-style endpoint.
**MUST BE OVERRIDDEN BY THE USER** - By default, this returns
``MethodNotImplemented``.
:returns: A collection of data
:rtype: list or iterable
"""
raise MethodNotImplemented()
def detail(self, *args, **kwargs):
"""
Returns the data for a GET on a detail-style endpoint.
**MUST BE OVERRIDDEN BY THE USER** - By default, this returns
``MethodNotImplemented``.
:returns: An item
:rtype: object or dict
"""
raise MethodNotImplemented()
def create(self, *args, **kwargs):
"""
Allows for creating data via a POST on a list-style endpoint.
**MUST BE OVERRIDDEN BY THE USER** - By default, this returns
``MethodNotImplemented``.
:returns: May return the created item or ``None``
"""
raise MethodNotImplemented()
def update(self, *args, **kwargs):
"""
Updates existing data for a PUT on a detail-style endpoint.
**MUST BE OVERRIDDEN BY THE USER** - By default, this returns
``MethodNotImplemented``.
:returns: May return the updated item or ``None``
"""
raise MethodNotImplemented()
def delete(self, *args, **kwargs):
"""
Deletes data for a DELETE on a detail-style endpoint.
**MUST BE OVERRIDDEN BY THE USER** - By default, this returns
``MethodNotImplemented``.
:returns: ``None``
"""
raise MethodNotImplemented()
# Uncommon methods the user should implement.
# These have intentionally uglier method names, which reflects just how
# much harder they are to get right.
def update_list(self, *args, **kwargs):
"""
Updates the entire collection for a PUT on a list-style endpoint.
Uncommonly implemented due to the complexity & (varying) busines-logic
involved.
**MUST BE OVERRIDDEN BY THE USER** - By default, this returns
``MethodNotImplemented``.
:returns: A collection of data
:rtype: list or iterable
"""
raise MethodNotImplemented()
def create_detail(self, *args, **kwargs):
"""
Creates a subcollection of data for a POST on a detail-style endpoint.
Uncommonly implemented due to the rarity of having nested collections.
**MUST BE OVERRIDDEN BY THE USER** - By default, this returns
``MethodNotImplemented``.
:returns: A collection of data
:rtype: list or iterable
"""
raise MethodNotImplemented()
def delete_list(self, *args, **kwargs):
"""
Deletes *ALL* data in the collection for a DELETE on a list-style
endpoint.
Uncommonly implemented due to potential of trashing large datasets.
Implement with care.
**MUST BE OVERRIDDEN BY THE USER** - By default, this returns
``MethodNotImplemented``.
:returns: ``None``
"""
raise MethodNotImplemented()
|
toastdriven/restless | restless/resources.py | Resource.serialize | python | def serialize(self, method, endpoint, data):
if endpoint == 'list':
# Create is a special-case, because you POST it to the collection,
# not to a detail.
if method == 'POST':
return self.serialize_detail(data)
return self.serialize_list(data)
return self.serialize_detail(data) | A convenience method for serializing data for a response.
If called on a list-style endpoint, this calls ``serialize_list``.
Otherwise, it will call ``serialize_detail``.
:param method: The HTTP method of the current request
:type method: string
:param endpoint: The endpoint style (``list`` or ``detail``)
:type endpoint: string
:param data: The body for the response
:type data: string
:returns: A serialized version of the data
:rtype: string | train | https://github.com/toastdriven/restless/blob/661593b7b43c42d1bc508dec795356297991255e/restless/resources.py#L362-L388 | [
"def serialize_list(self, data):\n \"\"\"\n Given a collection of data (``objects`` or ``dicts``), serializes them.\n\n :param data: The collection of items to serialize\n :type data: list or iterable\n\n :returns: The serialized body\n :rtype: string\n \"\"\"\n if data is None:\n return ''\n\n # Check for a ``Data``-like object. We should assume ``True`` (all\n # data gets prepared) unless it's explicitly marked as not.\n if not getattr(data, 'should_prepare', True):\n prepped_data = data.value\n else:\n prepped_data = [self.prepare(item) for item in data]\n\n final_data = self.wrap_list_response(prepped_data)\n return self.serializer.serialize(final_data)\n",
"def serialize_detail(self, data):\n \"\"\"\n Given a single item (``object`` or ``dict``), serializes it.\n\n :param data: The item to serialize\n :type data: object or dict\n\n :returns: The serialized body\n :rtype: string\n \"\"\"\n if data is None:\n return ''\n\n # Check for a ``Data``-like object. We should assume ``True`` (all\n # data gets prepared) unless it's explicitly marked as not.\n if not getattr(data, 'should_prepare', True):\n prepped_data = data.value\n else:\n prepped_data = self.prepare(data)\n\n return self.serializer.serialize(prepped_data)\n"
] | class Resource(object):
"""
Defines a RESTful resource.
Users are expected to subclass this object & implement a handful of methods:
* ``list``
* ``detail``
* ``create`` (requires authentication)
* ``update`` (requires authentication)
* ``delete`` (requires authentication)
Additionally, the user may choose to implement:
* ``create_detail`` (requires authentication)
* ``update_list`` (requires authentication)
* ``delete_list`` (requires authentication)
Users may also wish to define a ``fields`` attribute on the class. By
providing a dictionary of output names mapped to a dotted lookup path, you
can control the serialized output.
Users may also choose to override the ``status_map`` and/or ``http_methods``
on the class. These respectively control the HTTP status codes returned by
the views and the way views are looked up (based on HTTP method & endpoint).
"""
status_map = {
'list': OK,
'detail': OK,
'create': CREATED,
'update': ACCEPTED,
'delete': NO_CONTENT,
'update_list': ACCEPTED,
'create_detail': CREATED,
'delete_list': NO_CONTENT,
}
http_methods = {
'list': {
'GET': 'list',
'POST': 'create',
'PUT': 'update_list',
'DELETE': 'delete_list',
},
'detail': {
'GET': 'detail',
'POST': 'create_detail',
'PUT': 'update',
'DELETE': 'delete',
}
}
preparer = Preparer()
serializer = JSONSerializer()
def __init__(self, *args, **kwargs):
self.init_args = args
self.init_kwargs = kwargs
self.request = None
self.data = None
self.endpoint = None
self.status = 200
@classmethod
def as_list(cls, *init_args, **init_kwargs):
"""
Used for hooking up the actual list-style endpoints, this returns a
wrapper function that creates a new instance of the resource class &
calls the correct view method for it.
:param init_args: (Optional) Positional params to be persisted along
for instantiating the class itself.
:param init_kwargs: (Optional) Keyword params to be persisted along
for instantiating the class itself.
:returns: View function
"""
return cls.as_view('list', *init_args, **init_kwargs)
@classmethod
def as_detail(cls, *init_args, **init_kwargs):
"""
Used for hooking up the actual detail-style endpoints, this returns a
wrapper function that creates a new instance of the resource class &
calls the correct view method for it.
:param init_args: (Optional) Positional params to be persisted along
for instantiating the class itself.
:param init_kwargs: (Optional) Keyword params to be persisted along
for instantiating the class itself.
:returns: View function
"""
return cls.as_view('detail', *init_args, **init_kwargs)
@classmethod
def as_view(cls, view_type, *init_args, **init_kwargs):
"""
Used for hooking up the all endpoints (including custom ones), this
returns a wrapper function that creates a new instance of the resource
class & calls the correct view method for it.
:param view_type: Should be one of ``list``, ``detail`` or ``custom``.
:type view_type: string
:param init_args: (Optional) Positional params to be persisted along
for instantiating the class itself.
:param init_kwargs: (Optional) Keyword params to be persisted along
for instantiating the class itself.
:returns: View function
"""
@wraps(cls)
def _wrapper(request, *args, **kwargs):
# Make a new instance so that no state potentially leaks between
# instances.
inst = cls(*init_args, **init_kwargs)
inst.request = request
return inst.handle(view_type, *args, **kwargs)
return _wrapper
def request_method(self):
"""
Returns the HTTP method for the current request.
If you're integrating with a new web framework, you might need to
override this method within your subclass.
:returns: The HTTP method in uppercase
:rtype: string
"""
# By default, Django-esque.
return self.request.method.upper()
def request_body(self):
"""
Returns the body of the current request.
Useful for deserializing the content the user sent (typically JSON).
If you're integrating with a new web framework, you might need to
override this method within your subclass.
:returns: The body of the request
:rtype: string
"""
# By default, Django-esque.
return self.request.body
def build_response(self, data, status=200):
"""
Given some data, generates an HTTP response.
If you're integrating with a new web framework, you **MUST**
override this method within your subclass.
:param data: The body of the response to send
:type data: string
:param status: (Optional) The status code to respond with. Default is
``200``
:type status: integer
:returns: A response object
"""
raise NotImplementedError()
def build_error(self, err):
"""
When an exception is encountered, this generates a JSON error message
for display to the user.
:param err: The exception seen. The message is exposed to the user, so
beware of sensitive data leaking.
:type err: Exception
:returns: A response object
"""
data = {
'error': err.args[0],
}
if self.is_debug():
# Add the traceback.
data['traceback'] = format_traceback(sys.exc_info())
body = self.serializer.serialize(data)
status = getattr(err, 'status', 500)
return self.build_response(body, status=status)
def is_debug(self):
"""
Controls whether or not the resource is in a debug environment.
If so, tracebacks will be added to the serialized response.
The default implementation simply returns ``False``, so if you're
integrating with a new web framework, you'll need to override this
method within your subclass.
:returns: If the resource is in a debug environment
:rtype: boolean
"""
return False
def bubble_exceptions(self):
"""
Controls whether or not exceptions will be re-raised when encountered.
The default implementation returns ``False``, which means errors should
return a serialized response.
If you'd like exceptions to be re-raised, override this method & return
``True``.
:returns: Whether exceptions should be re-raised or not
:rtype: boolean
"""
return False
def handle(self, endpoint, *args, **kwargs):
"""
A convenient dispatching method, this centralized some of the common
flow of the views.
This wraps/calls the methods the user defines (``list/detail/create``
etc.), allowing the user to ignore the
authentication/deserialization/serialization/response & just focus on
their data/interactions.
:param endpoint: The style of URI call (typically either ``list`` or
``detail``).
:type endpoint: string
:param args: (Optional) Any positional URI parameter data is passed
along here. Somewhat framework/URL-specific.
:param kwargs: (Optional) Any keyword/named URI parameter data is
passed along here. Somewhat framework/URL-specific.
:returns: A response object
"""
self.endpoint = endpoint
method = self.request_method()
try:
# Use ``.get()`` so we can also dodge potentially incorrect
# ``endpoint`` errors as well.
if not method in self.http_methods.get(endpoint, {}):
raise MethodNotImplemented(
"Unsupported method '{}' for {} endpoint.".format(
method,
endpoint
)
)
if not self.is_authenticated():
raise Unauthorized()
self.data = self.deserialize(method, endpoint, self.request_body())
view_method = getattr(self, self.http_methods[endpoint][method])
data = view_method(*args, **kwargs)
serialized = self.serialize(method, endpoint, data)
except Exception as err:
return self.handle_error(err)
status = self.status_map.get(self.http_methods[endpoint][method], OK)
return self.build_response(serialized, status=status)
def handle_error(self, err):
"""
When an exception is encountered, this generates a serialized error
message to return the user.
:param err: The exception seen. The message is exposed to the user, so
beware of sensitive data leaking.
:type err: Exception
:returns: A response object
"""
if self.bubble_exceptions():
raise err
return self.build_error(err)
def deserialize(self, method, endpoint, body):
"""
A convenience method for deserializing the body of a request.
If called on a list-style endpoint, this calls ``deserialize_list``.
Otherwise, it will call ``deserialize_detail``.
:param method: The HTTP method of the current request
:type method: string
:param endpoint: The endpoint style (``list`` or ``detail``)
:type endpoint: string
:param body: The body of the current request
:type body: string
:returns: The deserialized data
:rtype: ``list`` or ``dict``
"""
if endpoint == 'list':
return self.deserialize_list(body)
return self.deserialize_detail(body)
def deserialize_list(self, body):
"""
Given a string of text, deserializes a (presumed) list out of the body.
:param body: The body of the current request
:type body: string
:returns: The deserialized body or an empty ``list``
"""
if body:
return self.serializer.deserialize(body)
return []
def deserialize_detail(self, body):
"""
Given a string of text, deserializes a (presumed) object out of the body.
:param body: The body of the current request
:type body: string
:returns: The deserialized body or an empty ``dict``
"""
if body:
return self.serializer.deserialize(body)
return {}
def serialize_list(self, data):
"""
Given a collection of data (``objects`` or ``dicts``), serializes them.
:param data: The collection of items to serialize
:type data: list or iterable
:returns: The serialized body
:rtype: string
"""
if data is None:
return ''
# Check for a ``Data``-like object. We should assume ``True`` (all
# data gets prepared) unless it's explicitly marked as not.
if not getattr(data, 'should_prepare', True):
prepped_data = data.value
else:
prepped_data = [self.prepare(item) for item in data]
final_data = self.wrap_list_response(prepped_data)
return self.serializer.serialize(final_data)
def serialize_detail(self, data):
"""
Given a single item (``object`` or ``dict``), serializes it.
:param data: The item to serialize
:type data: object or dict
:returns: The serialized body
:rtype: string
"""
if data is None:
return ''
# Check for a ``Data``-like object. We should assume ``True`` (all
# data gets prepared) unless it's explicitly marked as not.
if not getattr(data, 'should_prepare', True):
prepped_data = data.value
else:
prepped_data = self.prepare(data)
return self.serializer.serialize(prepped_data)
def prepare(self, data):
"""
Given an item (``object`` or ``dict``), this will potentially go through
& reshape the output based on ``self.prepare_with`` object.
:param data: An item to prepare for serialization
:type data: object or dict
:returns: A potentially reshaped dict
:rtype: dict
"""
return self.preparer.prepare(data)
def wrap_list_response(self, data):
"""
Takes a list of data & wraps it in a dictionary (within the ``objects``
key).
For security in JSON responses, it's better to wrap the list results in
an ``object`` (due to the way the ``Array`` constructor can be attacked
in Javascript). See http://haacked.com/archive/2009/06/25/json-hijacking.aspx/
& similar for details.
Overridable to allow for modifying the key names, adding data (or just
insecurely return a plain old list if that's your thing).
:param data: A list of data about to be serialized
:type data: list
:returns: A wrapping dict
:rtype: dict
"""
return {
"objects": data
}
def is_authenticated(self):
"""
A simple hook method for controlling whether a request is authenticated
to continue.
By default, we only allow the safe ``GET`` methods. All others are
denied.
:returns: Whether the request is authenticated or not.
:rtype: boolean
"""
if self.request_method() == 'GET':
return True
return False
# Common methods the user should implement.
def list(self, *args, **kwargs):
"""
Returns the data for a GET on a list-style endpoint.
**MUST BE OVERRIDDEN BY THE USER** - By default, this returns
``MethodNotImplemented``.
:returns: A collection of data
:rtype: list or iterable
"""
raise MethodNotImplemented()
def detail(self, *args, **kwargs):
"""
Returns the data for a GET on a detail-style endpoint.
**MUST BE OVERRIDDEN BY THE USER** - By default, this returns
``MethodNotImplemented``.
:returns: An item
:rtype: object or dict
"""
raise MethodNotImplemented()
def create(self, *args, **kwargs):
"""
Allows for creating data via a POST on a list-style endpoint.
**MUST BE OVERRIDDEN BY THE USER** - By default, this returns
``MethodNotImplemented``.
:returns: May return the created item or ``None``
"""
raise MethodNotImplemented()
def update(self, *args, **kwargs):
"""
Updates existing data for a PUT on a detail-style endpoint.
**MUST BE OVERRIDDEN BY THE USER** - By default, this returns
``MethodNotImplemented``.
:returns: May return the updated item or ``None``
"""
raise MethodNotImplemented()
def delete(self, *args, **kwargs):
"""
Deletes data for a DELETE on a detail-style endpoint.
**MUST BE OVERRIDDEN BY THE USER** - By default, this returns
``MethodNotImplemented``.
:returns: ``None``
"""
raise MethodNotImplemented()
# Uncommon methods the user should implement.
# These have intentionally uglier method names, which reflects just how
# much harder they are to get right.
def update_list(self, *args, **kwargs):
"""
Updates the entire collection for a PUT on a list-style endpoint.
Uncommonly implemented due to the complexity & (varying) busines-logic
involved.
**MUST BE OVERRIDDEN BY THE USER** - By default, this returns
``MethodNotImplemented``.
:returns: A collection of data
:rtype: list or iterable
"""
raise MethodNotImplemented()
def create_detail(self, *args, **kwargs):
"""
Creates a subcollection of data for a POST on a detail-style endpoint.
Uncommonly implemented due to the rarity of having nested collections.
**MUST BE OVERRIDDEN BY THE USER** - By default, this returns
``MethodNotImplemented``.
:returns: A collection of data
:rtype: list or iterable
"""
raise MethodNotImplemented()
def delete_list(self, *args, **kwargs):
"""
Deletes *ALL* data in the collection for a DELETE on a list-style
endpoint.
Uncommonly implemented due to potential of trashing large datasets.
Implement with care.
**MUST BE OVERRIDDEN BY THE USER** - By default, this returns
``MethodNotImplemented``.
:returns: ``None``
"""
raise MethodNotImplemented()
|
toastdriven/restless | restless/resources.py | Resource.serialize_list | python | def serialize_list(self, data):
if data is None:
return ''
# Check for a ``Data``-like object. We should assume ``True`` (all
# data gets prepared) unless it's explicitly marked as not.
if not getattr(data, 'should_prepare', True):
prepped_data = data.value
else:
prepped_data = [self.prepare(item) for item in data]
final_data = self.wrap_list_response(prepped_data)
return self.serializer.serialize(final_data) | Given a collection of data (``objects`` or ``dicts``), serializes them.
:param data: The collection of items to serialize
:type data: list or iterable
:returns: The serialized body
:rtype: string | train | https://github.com/toastdriven/restless/blob/661593b7b43c42d1bc508dec795356297991255e/restless/resources.py#L390-L411 | [
"def wrap_list_response(self, data):\n response_dict = super(DjangoResource, self).wrap_list_response(data)\n\n if hasattr(self, 'page'):\n next_page = self.page.has_next() and self.page.next_page_number() or None\n previous_page = self.page.has_previous() and self.page.previous_page_number() or None\n\n response_dict['pagination'] = {\n 'num_pages': self.page.paginator.num_pages,\n 'count': self.page.paginator.count,\n 'page': self.page.number,\n 'start_index': self.page.start_index(),\n 'end_index': self.page.end_index(),\n 'next_page': next_page,\n 'previous_page': previous_page,\n 'per_page': self.page.paginator.per_page,\n }\n\n return response_dict\n",
"def wrap_list_response(self, data):\n \"\"\"\n Takes a list of data & wraps it in a dictionary (within the ``objects``\n key).\n\n For security in JSON responses, it's better to wrap the list results in\n an ``object`` (due to the way the ``Array`` constructor can be attacked\n in Javascript). See http://haacked.com/archive/2009/06/25/json-hijacking.aspx/\n & similar for details.\n\n Overridable to allow for modifying the key names, adding data (or just\n insecurely return a plain old list if that's your thing).\n\n :param data: A list of data about to be serialized\n :type data: list\n\n :returns: A wrapping dict\n :rtype: dict\n \"\"\"\n return {\n \"objects\": data\n }\n"
] | class Resource(object):
"""
Defines a RESTful resource.
Users are expected to subclass this object & implement a handful of methods:
* ``list``
* ``detail``
* ``create`` (requires authentication)
* ``update`` (requires authentication)
* ``delete`` (requires authentication)
Additionally, the user may choose to implement:
* ``create_detail`` (requires authentication)
* ``update_list`` (requires authentication)
* ``delete_list`` (requires authentication)
Users may also wish to define a ``fields`` attribute on the class. By
providing a dictionary of output names mapped to a dotted lookup path, you
can control the serialized output.
Users may also choose to override the ``status_map`` and/or ``http_methods``
on the class. These respectively control the HTTP status codes returned by
the views and the way views are looked up (based on HTTP method & endpoint).
"""
status_map = {
'list': OK,
'detail': OK,
'create': CREATED,
'update': ACCEPTED,
'delete': NO_CONTENT,
'update_list': ACCEPTED,
'create_detail': CREATED,
'delete_list': NO_CONTENT,
}
http_methods = {
'list': {
'GET': 'list',
'POST': 'create',
'PUT': 'update_list',
'DELETE': 'delete_list',
},
'detail': {
'GET': 'detail',
'POST': 'create_detail',
'PUT': 'update',
'DELETE': 'delete',
}
}
preparer = Preparer()
serializer = JSONSerializer()
def __init__(self, *args, **kwargs):
self.init_args = args
self.init_kwargs = kwargs
self.request = None
self.data = None
self.endpoint = None
self.status = 200
@classmethod
def as_list(cls, *init_args, **init_kwargs):
"""
Used for hooking up the actual list-style endpoints, this returns a
wrapper function that creates a new instance of the resource class &
calls the correct view method for it.
:param init_args: (Optional) Positional params to be persisted along
for instantiating the class itself.
:param init_kwargs: (Optional) Keyword params to be persisted along
for instantiating the class itself.
:returns: View function
"""
return cls.as_view('list', *init_args, **init_kwargs)
@classmethod
def as_detail(cls, *init_args, **init_kwargs):
"""
Used for hooking up the actual detail-style endpoints, this returns a
wrapper function that creates a new instance of the resource class &
calls the correct view method for it.
:param init_args: (Optional) Positional params to be persisted along
for instantiating the class itself.
:param init_kwargs: (Optional) Keyword params to be persisted along
for instantiating the class itself.
:returns: View function
"""
return cls.as_view('detail', *init_args, **init_kwargs)
@classmethod
def as_view(cls, view_type, *init_args, **init_kwargs):
"""
Used for hooking up the all endpoints (including custom ones), this
returns a wrapper function that creates a new instance of the resource
class & calls the correct view method for it.
:param view_type: Should be one of ``list``, ``detail`` or ``custom``.
:type view_type: string
:param init_args: (Optional) Positional params to be persisted along
for instantiating the class itself.
:param init_kwargs: (Optional) Keyword params to be persisted along
for instantiating the class itself.
:returns: View function
"""
@wraps(cls)
def _wrapper(request, *args, **kwargs):
# Make a new instance so that no state potentially leaks between
# instances.
inst = cls(*init_args, **init_kwargs)
inst.request = request
return inst.handle(view_type, *args, **kwargs)
return _wrapper
def request_method(self):
"""
Returns the HTTP method for the current request.
If you're integrating with a new web framework, you might need to
override this method within your subclass.
:returns: The HTTP method in uppercase
:rtype: string
"""
# By default, Django-esque.
return self.request.method.upper()
def request_body(self):
"""
Returns the body of the current request.
Useful for deserializing the content the user sent (typically JSON).
If you're integrating with a new web framework, you might need to
override this method within your subclass.
:returns: The body of the request
:rtype: string
"""
# By default, Django-esque.
return self.request.body
def build_response(self, data, status=200):
"""
Given some data, generates an HTTP response.
If you're integrating with a new web framework, you **MUST**
override this method within your subclass.
:param data: The body of the response to send
:type data: string
:param status: (Optional) The status code to respond with. Default is
``200``
:type status: integer
:returns: A response object
"""
raise NotImplementedError()
def build_error(self, err):
"""
When an exception is encountered, this generates a JSON error message
for display to the user.
:param err: The exception seen. The message is exposed to the user, so
beware of sensitive data leaking.
:type err: Exception
:returns: A response object
"""
data = {
'error': err.args[0],
}
if self.is_debug():
# Add the traceback.
data['traceback'] = format_traceback(sys.exc_info())
body = self.serializer.serialize(data)
status = getattr(err, 'status', 500)
return self.build_response(body, status=status)
def is_debug(self):
"""
Controls whether or not the resource is in a debug environment.
If so, tracebacks will be added to the serialized response.
The default implementation simply returns ``False``, so if you're
integrating with a new web framework, you'll need to override this
method within your subclass.
:returns: If the resource is in a debug environment
:rtype: boolean
"""
return False
def bubble_exceptions(self):
"""
Controls whether or not exceptions will be re-raised when encountered.
The default implementation returns ``False``, which means errors should
return a serialized response.
If you'd like exceptions to be re-raised, override this method & return
``True``.
:returns: Whether exceptions should be re-raised or not
:rtype: boolean
"""
return False
def handle(self, endpoint, *args, **kwargs):
"""
A convenient dispatching method, this centralized some of the common
flow of the views.
This wraps/calls the methods the user defines (``list/detail/create``
etc.), allowing the user to ignore the
authentication/deserialization/serialization/response & just focus on
their data/interactions.
:param endpoint: The style of URI call (typically either ``list`` or
``detail``).
:type endpoint: string
:param args: (Optional) Any positional URI parameter data is passed
along here. Somewhat framework/URL-specific.
:param kwargs: (Optional) Any keyword/named URI parameter data is
passed along here. Somewhat framework/URL-specific.
:returns: A response object
"""
self.endpoint = endpoint
method = self.request_method()
try:
# Use ``.get()`` so we can also dodge potentially incorrect
# ``endpoint`` errors as well.
if not method in self.http_methods.get(endpoint, {}):
raise MethodNotImplemented(
"Unsupported method '{}' for {} endpoint.".format(
method,
endpoint
)
)
if not self.is_authenticated():
raise Unauthorized()
self.data = self.deserialize(method, endpoint, self.request_body())
view_method = getattr(self, self.http_methods[endpoint][method])
data = view_method(*args, **kwargs)
serialized = self.serialize(method, endpoint, data)
except Exception as err:
return self.handle_error(err)
status = self.status_map.get(self.http_methods[endpoint][method], OK)
return self.build_response(serialized, status=status)
def handle_error(self, err):
"""
When an exception is encountered, this generates a serialized error
message to return the user.
:param err: The exception seen. The message is exposed to the user, so
beware of sensitive data leaking.
:type err: Exception
:returns: A response object
"""
if self.bubble_exceptions():
raise err
return self.build_error(err)
def deserialize(self, method, endpoint, body):
"""
A convenience method for deserializing the body of a request.
If called on a list-style endpoint, this calls ``deserialize_list``.
Otherwise, it will call ``deserialize_detail``.
:param method: The HTTP method of the current request
:type method: string
:param endpoint: The endpoint style (``list`` or ``detail``)
:type endpoint: string
:param body: The body of the current request
:type body: string
:returns: The deserialized data
:rtype: ``list`` or ``dict``
"""
if endpoint == 'list':
return self.deserialize_list(body)
return self.deserialize_detail(body)
def deserialize_list(self, body):
"""
Given a string of text, deserializes a (presumed) list out of the body.
:param body: The body of the current request
:type body: string
:returns: The deserialized body or an empty ``list``
"""
if body:
return self.serializer.deserialize(body)
return []
def deserialize_detail(self, body):
"""
Given a string of text, deserializes a (presumed) object out of the body.
:param body: The body of the current request
:type body: string
:returns: The deserialized body or an empty ``dict``
"""
if body:
return self.serializer.deserialize(body)
return {}
def serialize(self, method, endpoint, data):
"""
A convenience method for serializing data for a response.
If called on a list-style endpoint, this calls ``serialize_list``.
Otherwise, it will call ``serialize_detail``.
:param method: The HTTP method of the current request
:type method: string
:param endpoint: The endpoint style (``list`` or ``detail``)
:type endpoint: string
:param data: The body for the response
:type data: string
:returns: A serialized version of the data
:rtype: string
"""
if endpoint == 'list':
# Create is a special-case, because you POST it to the collection,
# not to a detail.
if method == 'POST':
return self.serialize_detail(data)
return self.serialize_list(data)
return self.serialize_detail(data)
def serialize_detail(self, data):
"""
Given a single item (``object`` or ``dict``), serializes it.
:param data: The item to serialize
:type data: object or dict
:returns: The serialized body
:rtype: string
"""
if data is None:
return ''
# Check for a ``Data``-like object. We should assume ``True`` (all
# data gets prepared) unless it's explicitly marked as not.
if not getattr(data, 'should_prepare', True):
prepped_data = data.value
else:
prepped_data = self.prepare(data)
return self.serializer.serialize(prepped_data)
def prepare(self, data):
"""
Given an item (``object`` or ``dict``), this will potentially go through
& reshape the output based on ``self.prepare_with`` object.
:param data: An item to prepare for serialization
:type data: object or dict
:returns: A potentially reshaped dict
:rtype: dict
"""
return self.preparer.prepare(data)
def wrap_list_response(self, data):
"""
Takes a list of data & wraps it in a dictionary (within the ``objects``
key).
For security in JSON responses, it's better to wrap the list results in
an ``object`` (due to the way the ``Array`` constructor can be attacked
in Javascript). See http://haacked.com/archive/2009/06/25/json-hijacking.aspx/
& similar for details.
Overridable to allow for modifying the key names, adding data (or just
insecurely return a plain old list if that's your thing).
:param data: A list of data about to be serialized
:type data: list
:returns: A wrapping dict
:rtype: dict
"""
return {
"objects": data
}
def is_authenticated(self):
"""
A simple hook method for controlling whether a request is authenticated
to continue.
By default, we only allow the safe ``GET`` methods. All others are
denied.
:returns: Whether the request is authenticated or not.
:rtype: boolean
"""
if self.request_method() == 'GET':
return True
return False
# Common methods the user should implement.
def list(self, *args, **kwargs):
"""
Returns the data for a GET on a list-style endpoint.
**MUST BE OVERRIDDEN BY THE USER** - By default, this returns
``MethodNotImplemented``.
:returns: A collection of data
:rtype: list or iterable
"""
raise MethodNotImplemented()
def detail(self, *args, **kwargs):
"""
Returns the data for a GET on a detail-style endpoint.
**MUST BE OVERRIDDEN BY THE USER** - By default, this returns
``MethodNotImplemented``.
:returns: An item
:rtype: object or dict
"""
raise MethodNotImplemented()
def create(self, *args, **kwargs):
"""
Allows for creating data via a POST on a list-style endpoint.
**MUST BE OVERRIDDEN BY THE USER** - By default, this returns
``MethodNotImplemented``.
:returns: May return the created item or ``None``
"""
raise MethodNotImplemented()
def update(self, *args, **kwargs):
"""
Updates existing data for a PUT on a detail-style endpoint.
**MUST BE OVERRIDDEN BY THE USER** - By default, this returns
``MethodNotImplemented``.
:returns: May return the updated item or ``None``
"""
raise MethodNotImplemented()
def delete(self, *args, **kwargs):
"""
Deletes data for a DELETE on a detail-style endpoint.
**MUST BE OVERRIDDEN BY THE USER** - By default, this returns
``MethodNotImplemented``.
:returns: ``None``
"""
raise MethodNotImplemented()
# Uncommon methods the user should implement.
# These have intentionally uglier method names, which reflects just how
# much harder they are to get right.
def update_list(self, *args, **kwargs):
"""
Updates the entire collection for a PUT on a list-style endpoint.
Uncommonly implemented due to the complexity & (varying) busines-logic
involved.
**MUST BE OVERRIDDEN BY THE USER** - By default, this returns
``MethodNotImplemented``.
:returns: A collection of data
:rtype: list or iterable
"""
raise MethodNotImplemented()
def create_detail(self, *args, **kwargs):
"""
Creates a subcollection of data for a POST on a detail-style endpoint.
Uncommonly implemented due to the rarity of having nested collections.
**MUST BE OVERRIDDEN BY THE USER** - By default, this returns
``MethodNotImplemented``.
:returns: A collection of data
:rtype: list or iterable
"""
raise MethodNotImplemented()
def delete_list(self, *args, **kwargs):
"""
Deletes *ALL* data in the collection for a DELETE on a list-style
endpoint.
Uncommonly implemented due to potential of trashing large datasets.
Implement with care.
**MUST BE OVERRIDDEN BY THE USER** - By default, this returns
``MethodNotImplemented``.
:returns: ``None``
"""
raise MethodNotImplemented()
|
toastdriven/restless | restless/resources.py | Resource.serialize_detail | python | def serialize_detail(self, data):
if data is None:
return ''
# Check for a ``Data``-like object. We should assume ``True`` (all
# data gets prepared) unless it's explicitly marked as not.
if not getattr(data, 'should_prepare', True):
prepped_data = data.value
else:
prepped_data = self.prepare(data)
return self.serializer.serialize(prepped_data) | Given a single item (``object`` or ``dict``), serializes it.
:param data: The item to serialize
:type data: object or dict
:returns: The serialized body
:rtype: string | train | https://github.com/toastdriven/restless/blob/661593b7b43c42d1bc508dec795356297991255e/restless/resources.py#L413-L433 | [
"def prepare(self, data):\n \"\"\"\n Given an item (``object`` or ``dict``), this will potentially go through\n & reshape the output based on ``self.prepare_with`` object.\n\n :param data: An item to prepare for serialization\n :type data: object or dict\n\n :returns: A potentially reshaped dict\n :rtype: dict\n \"\"\"\n return self.preparer.prepare(data)\n"
] | class Resource(object):
"""
Defines a RESTful resource.
Users are expected to subclass this object & implement a handful of methods:
* ``list``
* ``detail``
* ``create`` (requires authentication)
* ``update`` (requires authentication)
* ``delete`` (requires authentication)
Additionally, the user may choose to implement:
* ``create_detail`` (requires authentication)
* ``update_list`` (requires authentication)
* ``delete_list`` (requires authentication)
Users may also wish to define a ``fields`` attribute on the class. By
providing a dictionary of output names mapped to a dotted lookup path, you
can control the serialized output.
Users may also choose to override the ``status_map`` and/or ``http_methods``
on the class. These respectively control the HTTP status codes returned by
the views and the way views are looked up (based on HTTP method & endpoint).
"""
status_map = {
'list': OK,
'detail': OK,
'create': CREATED,
'update': ACCEPTED,
'delete': NO_CONTENT,
'update_list': ACCEPTED,
'create_detail': CREATED,
'delete_list': NO_CONTENT,
}
http_methods = {
'list': {
'GET': 'list',
'POST': 'create',
'PUT': 'update_list',
'DELETE': 'delete_list',
},
'detail': {
'GET': 'detail',
'POST': 'create_detail',
'PUT': 'update',
'DELETE': 'delete',
}
}
preparer = Preparer()
serializer = JSONSerializer()
def __init__(self, *args, **kwargs):
self.init_args = args
self.init_kwargs = kwargs
self.request = None
self.data = None
self.endpoint = None
self.status = 200
@classmethod
def as_list(cls, *init_args, **init_kwargs):
"""
Used for hooking up the actual list-style endpoints, this returns a
wrapper function that creates a new instance of the resource class &
calls the correct view method for it.
:param init_args: (Optional) Positional params to be persisted along
for instantiating the class itself.
:param init_kwargs: (Optional) Keyword params to be persisted along
for instantiating the class itself.
:returns: View function
"""
return cls.as_view('list', *init_args, **init_kwargs)
@classmethod
def as_detail(cls, *init_args, **init_kwargs):
"""
Used for hooking up the actual detail-style endpoints, this returns a
wrapper function that creates a new instance of the resource class &
calls the correct view method for it.
:param init_args: (Optional) Positional params to be persisted along
for instantiating the class itself.
:param init_kwargs: (Optional) Keyword params to be persisted along
for instantiating the class itself.
:returns: View function
"""
return cls.as_view('detail', *init_args, **init_kwargs)
@classmethod
def as_view(cls, view_type, *init_args, **init_kwargs):
"""
Used for hooking up the all endpoints (including custom ones), this
returns a wrapper function that creates a new instance of the resource
class & calls the correct view method for it.
:param view_type: Should be one of ``list``, ``detail`` or ``custom``.
:type view_type: string
:param init_args: (Optional) Positional params to be persisted along
for instantiating the class itself.
:param init_kwargs: (Optional) Keyword params to be persisted along
for instantiating the class itself.
:returns: View function
"""
@wraps(cls)
def _wrapper(request, *args, **kwargs):
# Make a new instance so that no state potentially leaks between
# instances.
inst = cls(*init_args, **init_kwargs)
inst.request = request
return inst.handle(view_type, *args, **kwargs)
return _wrapper
def request_method(self):
"""
Returns the HTTP method for the current request.
If you're integrating with a new web framework, you might need to
override this method within your subclass.
:returns: The HTTP method in uppercase
:rtype: string
"""
# By default, Django-esque.
return self.request.method.upper()
def request_body(self):
"""
Returns the body of the current request.
Useful for deserializing the content the user sent (typically JSON).
If you're integrating with a new web framework, you might need to
override this method within your subclass.
:returns: The body of the request
:rtype: string
"""
# By default, Django-esque.
return self.request.body
def build_response(self, data, status=200):
"""
Given some data, generates an HTTP response.
If you're integrating with a new web framework, you **MUST**
override this method within your subclass.
:param data: The body of the response to send
:type data: string
:param status: (Optional) The status code to respond with. Default is
``200``
:type status: integer
:returns: A response object
"""
raise NotImplementedError()
def build_error(self, err):
"""
When an exception is encountered, this generates a JSON error message
for display to the user.
:param err: The exception seen. The message is exposed to the user, so
beware of sensitive data leaking.
:type err: Exception
:returns: A response object
"""
data = {
'error': err.args[0],
}
if self.is_debug():
# Add the traceback.
data['traceback'] = format_traceback(sys.exc_info())
body = self.serializer.serialize(data)
status = getattr(err, 'status', 500)
return self.build_response(body, status=status)
def is_debug(self):
"""
Controls whether or not the resource is in a debug environment.
If so, tracebacks will be added to the serialized response.
The default implementation simply returns ``False``, so if you're
integrating with a new web framework, you'll need to override this
method within your subclass.
:returns: If the resource is in a debug environment
:rtype: boolean
"""
return False
def bubble_exceptions(self):
"""
Controls whether or not exceptions will be re-raised when encountered.
The default implementation returns ``False``, which means errors should
return a serialized response.
If you'd like exceptions to be re-raised, override this method & return
``True``.
:returns: Whether exceptions should be re-raised or not
:rtype: boolean
"""
return False
def handle(self, endpoint, *args, **kwargs):
"""
A convenient dispatching method, this centralized some of the common
flow of the views.
This wraps/calls the methods the user defines (``list/detail/create``
etc.), allowing the user to ignore the
authentication/deserialization/serialization/response & just focus on
their data/interactions.
:param endpoint: The style of URI call (typically either ``list`` or
``detail``).
:type endpoint: string
:param args: (Optional) Any positional URI parameter data is passed
along here. Somewhat framework/URL-specific.
:param kwargs: (Optional) Any keyword/named URI parameter data is
passed along here. Somewhat framework/URL-specific.
:returns: A response object
"""
self.endpoint = endpoint
method = self.request_method()
try:
# Use ``.get()`` so we can also dodge potentially incorrect
# ``endpoint`` errors as well.
if not method in self.http_methods.get(endpoint, {}):
raise MethodNotImplemented(
"Unsupported method '{}' for {} endpoint.".format(
method,
endpoint
)
)
if not self.is_authenticated():
raise Unauthorized()
self.data = self.deserialize(method, endpoint, self.request_body())
view_method = getattr(self, self.http_methods[endpoint][method])
data = view_method(*args, **kwargs)
serialized = self.serialize(method, endpoint, data)
except Exception as err:
return self.handle_error(err)
status = self.status_map.get(self.http_methods[endpoint][method], OK)
return self.build_response(serialized, status=status)
def handle_error(self, err):
"""
When an exception is encountered, this generates a serialized error
message to return the user.
:param err: The exception seen. The message is exposed to the user, so
beware of sensitive data leaking.
:type err: Exception
:returns: A response object
"""
if self.bubble_exceptions():
raise err
return self.build_error(err)
def deserialize(self, method, endpoint, body):
"""
A convenience method for deserializing the body of a request.
If called on a list-style endpoint, this calls ``deserialize_list``.
Otherwise, it will call ``deserialize_detail``.
:param method: The HTTP method of the current request
:type method: string
:param endpoint: The endpoint style (``list`` or ``detail``)
:type endpoint: string
:param body: The body of the current request
:type body: string
:returns: The deserialized data
:rtype: ``list`` or ``dict``
"""
if endpoint == 'list':
return self.deserialize_list(body)
return self.deserialize_detail(body)
def deserialize_list(self, body):
"""
Given a string of text, deserializes a (presumed) list out of the body.
:param body: The body of the current request
:type body: string
:returns: The deserialized body or an empty ``list``
"""
if body:
return self.serializer.deserialize(body)
return []
def deserialize_detail(self, body):
"""
Given a string of text, deserializes a (presumed) object out of the body.
:param body: The body of the current request
:type body: string
:returns: The deserialized body or an empty ``dict``
"""
if body:
return self.serializer.deserialize(body)
return {}
def serialize(self, method, endpoint, data):
"""
A convenience method for serializing data for a response.
If called on a list-style endpoint, this calls ``serialize_list``.
Otherwise, it will call ``serialize_detail``.
:param method: The HTTP method of the current request
:type method: string
:param endpoint: The endpoint style (``list`` or ``detail``)
:type endpoint: string
:param data: The body for the response
:type data: string
:returns: A serialized version of the data
:rtype: string
"""
if endpoint == 'list':
# Create is a special-case, because you POST it to the collection,
# not to a detail.
if method == 'POST':
return self.serialize_detail(data)
return self.serialize_list(data)
return self.serialize_detail(data)
def serialize_list(self, data):
"""
Given a collection of data (``objects`` or ``dicts``), serializes them.
:param data: The collection of items to serialize
:type data: list or iterable
:returns: The serialized body
:rtype: string
"""
if data is None:
return ''
# Check for a ``Data``-like object. We should assume ``True`` (all
# data gets prepared) unless it's explicitly marked as not.
if not getattr(data, 'should_prepare', True):
prepped_data = data.value
else:
prepped_data = [self.prepare(item) for item in data]
final_data = self.wrap_list_response(prepped_data)
return self.serializer.serialize(final_data)
def prepare(self, data):
"""
Given an item (``object`` or ``dict``), this will potentially go through
& reshape the output based on ``self.prepare_with`` object.
:param data: An item to prepare for serialization
:type data: object or dict
:returns: A potentially reshaped dict
:rtype: dict
"""
return self.preparer.prepare(data)
def wrap_list_response(self, data):
"""
Takes a list of data & wraps it in a dictionary (within the ``objects``
key).
For security in JSON responses, it's better to wrap the list results in
an ``object`` (due to the way the ``Array`` constructor can be attacked
in Javascript). See http://haacked.com/archive/2009/06/25/json-hijacking.aspx/
& similar for details.
Overridable to allow for modifying the key names, adding data (or just
insecurely return a plain old list if that's your thing).
:param data: A list of data about to be serialized
:type data: list
:returns: A wrapping dict
:rtype: dict
"""
return {
"objects": data
}
def is_authenticated(self):
"""
A simple hook method for controlling whether a request is authenticated
to continue.
By default, we only allow the safe ``GET`` methods. All others are
denied.
:returns: Whether the request is authenticated or not.
:rtype: boolean
"""
if self.request_method() == 'GET':
return True
return False
# Common methods the user should implement.
def list(self, *args, **kwargs):
"""
Returns the data for a GET on a list-style endpoint.
**MUST BE OVERRIDDEN BY THE USER** - By default, this returns
``MethodNotImplemented``.
:returns: A collection of data
:rtype: list or iterable
"""
raise MethodNotImplemented()
def detail(self, *args, **kwargs):
"""
Returns the data for a GET on a detail-style endpoint.
**MUST BE OVERRIDDEN BY THE USER** - By default, this returns
``MethodNotImplemented``.
:returns: An item
:rtype: object or dict
"""
raise MethodNotImplemented()
def create(self, *args, **kwargs):
"""
Allows for creating data via a POST on a list-style endpoint.
**MUST BE OVERRIDDEN BY THE USER** - By default, this returns
``MethodNotImplemented``.
:returns: May return the created item or ``None``
"""
raise MethodNotImplemented()
def update(self, *args, **kwargs):
"""
Updates existing data for a PUT on a detail-style endpoint.
**MUST BE OVERRIDDEN BY THE USER** - By default, this returns
``MethodNotImplemented``.
:returns: May return the updated item or ``None``
"""
raise MethodNotImplemented()
def delete(self, *args, **kwargs):
"""
Deletes data for a DELETE on a detail-style endpoint.
**MUST BE OVERRIDDEN BY THE USER** - By default, this returns
``MethodNotImplemented``.
:returns: ``None``
"""
raise MethodNotImplemented()
# Uncommon methods the user should implement.
# These have intentionally uglier method names, which reflects just how
# much harder they are to get right.
def update_list(self, *args, **kwargs):
"""
Updates the entire collection for a PUT on a list-style endpoint.
Uncommonly implemented due to the complexity & (varying) busines-logic
involved.
**MUST BE OVERRIDDEN BY THE USER** - By default, this returns
``MethodNotImplemented``.
:returns: A collection of data
:rtype: list or iterable
"""
raise MethodNotImplemented()
def create_detail(self, *args, **kwargs):
"""
Creates a subcollection of data for a POST on a detail-style endpoint.
Uncommonly implemented due to the rarity of having nested collections.
**MUST BE OVERRIDDEN BY THE USER** - By default, this returns
``MethodNotImplemented``.
:returns: A collection of data
:rtype: list or iterable
"""
raise MethodNotImplemented()
def delete_list(self, *args, **kwargs):
"""
Deletes *ALL* data in the collection for a DELETE on a list-style
endpoint.
Uncommonly implemented due to potential of trashing large datasets.
Implement with care.
**MUST BE OVERRIDDEN BY THE USER** - By default, this returns
``MethodNotImplemented``.
:returns: ``None``
"""
raise MethodNotImplemented()
|
toastdriven/restless | restless/tnd.py | _method | python | def _method(self, *args, **kwargs):
yield self.resource_handler.handle(self.__resource_view_type__, *args, **kwargs) | the body of those http-methods used in tornado.web.RequestHandler | train | https://github.com/toastdriven/restless/blob/661593b7b43c42d1bc508dec795356297991255e/restless/tnd.py#L36-L40 | null | from tornado import web, gen
from .constants import OK, NO_CONTENT
from .resources import Resource
from .exceptions import MethodNotImplemented, Unauthorized
import weakref
import inspect
try:
from tornado.concurrent import is_future
except ImportError:
is_future = None
if is_future is None:
"""
Please refer to tornado.concurrent module(newer than 4.0)
for implementation of this function.
"""
try:
from concurrent import futures
except ImportError:
futures = None
from tornado.concurrent import Future
if futures is None:
FUTURES = Future
else:
FUTURES = (Future, futures.Future)
is_future = lambda x: isinstance(x, FUTURES)
@gen.coroutine
class _BridgeMixin(object):
"""
This mixin would pass tornado parameters to restless,
and helps to init a resource instance
"""
def __init__(self, *args, **kwargs):
super(_BridgeMixin, self).__init__(*args, **kwargs)
# create a resource instance based on the registered class
# and init-parameters
self.resource_handler = self.__class__.__resource_cls__(
*self.__resource_args__, **self.__resource_kwargs__
)
self.resource_handler.request = self.request
self.resource_handler.application = self.application
self.resource_handler.ref_rh = weakref.proxy(self) # avoid circular reference between
class TornadoResource(Resource):
"""
A Tornado-specific ``Resource`` subclass.
"""
_request_handler_base_ = web.RequestHandler
"""
To override ``tornado.web.RequestHandler`` we used,
please assign your RequestHandler via this attribute.
"""
def __init__(self, *args, **kwargs):
super(TornadoResource, self).__init__(*args, **kwargs)
self.request = None
"""
a reference to ``tornado.httpclient.HTTPRequest``
"""
self.application = None
"""
a reference to ``tornado.web.Application``
"""
self.ref_rh = None
@property
def r_handler(self):
"""
access to ``tornado.web.RequestHandler``
"""
return self.ref_rh
@classmethod
def as_view(cls, view_type, *init_args, **init_kwargs):
"""
Return a subclass of tornado.web.RequestHandler and
apply required setting.
"""
global _method
new_cls = type(
cls.__name__ + '_' + _BridgeMixin.__name__ + '_restless',
(_BridgeMixin, cls._request_handler_base_,),
dict(
__resource_cls__=cls,
__resource_args__=init_args,
__resource_kwargs__=init_kwargs,
__resource_view_type__=view_type)
)
"""
Add required http-methods to the newly created class
We need to scan through MRO to find what functions users declared,
and then add corresponding http-methods used by Tornado.
"""
bases = inspect.getmro(cls)
bases = bases[0:bases.index(Resource)-1]
for k, v in cls.http_methods[view_type].items():
if any(v in base_cls.__dict__ for base_cls in bases):
setattr(new_cls, k.lower(), _method)
return new_cls
def request_method(self):
return self.request.method
def request_body(self):
return self.request.body
def build_response(self, data, status=OK):
if status == NO_CONTENT:
# Avoid crashing the client when it tries to parse nonexisting JSON.
content_type = 'text/plain'
else:
content_type = 'application/json'
self.ref_rh.set_header("Content-Type", "{}; charset=UTF-8"
.format(content_type))
self.ref_rh.set_status(status)
self.ref_rh.finish(data)
def is_debug(self):
return self.application.settings.get('debug', False)
@gen.coroutine
def handle(self, endpoint, *args, **kwargs):
"""
almost identical to Resource.handle, except
the way we handle the return value of view_method.
"""
method = self.request_method()
try:
if not method in self.http_methods.get(endpoint, {}):
raise MethodNotImplemented(
"Unsupported method '{}' for {} endpoint.".format(
method,
endpoint
)
)
if not self.is_authenticated():
raise Unauthorized()
self.data = self.deserialize(method, endpoint, self.request_body())
view_method = getattr(self, self.http_methods[endpoint][method])
data = view_method(*args, **kwargs)
if is_future(data):
# need to check if the view_method is a generator or not
data = yield data
serialized = self.serialize(method, endpoint, data)
except Exception as err:
raise gen.Return(self.handle_error(err))
status = self.status_map.get(self.http_methods[endpoint][method], OK)
raise gen.Return(self.build_response(serialized, status=status))
|
toastdriven/restless | restless/tnd.py | TornadoResource.as_view | python | def as_view(cls, view_type, *init_args, **init_kwargs):
global _method
new_cls = type(
cls.__name__ + '_' + _BridgeMixin.__name__ + '_restless',
(_BridgeMixin, cls._request_handler_base_,),
dict(
__resource_cls__=cls,
__resource_args__=init_args,
__resource_kwargs__=init_kwargs,
__resource_view_type__=view_type)
)
"""
Add required http-methods to the newly created class
We need to scan through MRO to find what functions users declared,
and then add corresponding http-methods used by Tornado.
"""
bases = inspect.getmro(cls)
bases = bases[0:bases.index(Resource)-1]
for k, v in cls.http_methods[view_type].items():
if any(v in base_cls.__dict__ for base_cls in bases):
setattr(new_cls, k.lower(), _method)
return new_cls | Return a subclass of tornado.web.RequestHandler and
apply required setting. | train | https://github.com/toastdriven/restless/blob/661593b7b43c42d1bc508dec795356297991255e/restless/tnd.py#L95-L123 | null | class TornadoResource(Resource):
"""
A Tornado-specific ``Resource`` subclass.
"""
_request_handler_base_ = web.RequestHandler
"""
To override ``tornado.web.RequestHandler`` we used,
please assign your RequestHandler via this attribute.
"""
def __init__(self, *args, **kwargs):
super(TornadoResource, self).__init__(*args, **kwargs)
self.request = None
"""
a reference to ``tornado.httpclient.HTTPRequest``
"""
self.application = None
"""
a reference to ``tornado.web.Application``
"""
self.ref_rh = None
@property
def r_handler(self):
"""
access to ``tornado.web.RequestHandler``
"""
return self.ref_rh
@classmethod
def request_method(self):
return self.request.method
def request_body(self):
return self.request.body
def build_response(self, data, status=OK):
if status == NO_CONTENT:
# Avoid crashing the client when it tries to parse nonexisting JSON.
content_type = 'text/plain'
else:
content_type = 'application/json'
self.ref_rh.set_header("Content-Type", "{}; charset=UTF-8"
.format(content_type))
self.ref_rh.set_status(status)
self.ref_rh.finish(data)
def is_debug(self):
return self.application.settings.get('debug', False)
@gen.coroutine
def handle(self, endpoint, *args, **kwargs):
"""
almost identical to Resource.handle, except
the way we handle the return value of view_method.
"""
method = self.request_method()
try:
if not method in self.http_methods.get(endpoint, {}):
raise MethodNotImplemented(
"Unsupported method '{}' for {} endpoint.".format(
method,
endpoint
)
)
if not self.is_authenticated():
raise Unauthorized()
self.data = self.deserialize(method, endpoint, self.request_body())
view_method = getattr(self, self.http_methods[endpoint][method])
data = view_method(*args, **kwargs)
if is_future(data):
# need to check if the view_method is a generator or not
data = yield data
serialized = self.serialize(method, endpoint, data)
except Exception as err:
raise gen.Return(self.handle_error(err))
status = self.status_map.get(self.http_methods[endpoint][method], OK)
raise gen.Return(self.build_response(serialized, status=status))
|
toastdriven/restless | restless/tnd.py | TornadoResource.handle | python | def handle(self, endpoint, *args, **kwargs):
method = self.request_method()
try:
if not method in self.http_methods.get(endpoint, {}):
raise MethodNotImplemented(
"Unsupported method '{}' for {} endpoint.".format(
method,
endpoint
)
)
if not self.is_authenticated():
raise Unauthorized()
self.data = self.deserialize(method, endpoint, self.request_body())
view_method = getattr(self, self.http_methods[endpoint][method])
data = view_method(*args, **kwargs)
if is_future(data):
# need to check if the view_method is a generator or not
data = yield data
serialized = self.serialize(method, endpoint, data)
except Exception as err:
raise gen.Return(self.handle_error(err))
status = self.status_map.get(self.http_methods[endpoint][method], OK)
raise gen.Return(self.build_response(serialized, status=status)) | almost identical to Resource.handle, except
the way we handle the return value of view_method. | train | https://github.com/toastdriven/restless/blob/661593b7b43c42d1bc508dec795356297991255e/restless/tnd.py#L147-L177 | [
"def handle_error(self, err):\n \"\"\"\n When an exception is encountered, this generates a serialized error\n message to return the user.\n\n :param err: The exception seen. The message is exposed to the user, so\n beware of sensitive data leaking.\n :type err: Exception\n\n :returns: A response object\n \"\"\"\n if self.bubble_exceptions():\n raise err\n\n return self.build_error(err)\n",
"def request_method(self):\n return self.request.method\n"
] | class TornadoResource(Resource):
"""
A Tornado-specific ``Resource`` subclass.
"""
_request_handler_base_ = web.RequestHandler
"""
To override ``tornado.web.RequestHandler`` we used,
please assign your RequestHandler via this attribute.
"""
def __init__(self, *args, **kwargs):
super(TornadoResource, self).__init__(*args, **kwargs)
self.request = None
"""
a reference to ``tornado.httpclient.HTTPRequest``
"""
self.application = None
"""
a reference to ``tornado.web.Application``
"""
self.ref_rh = None
@property
def r_handler(self):
"""
access to ``tornado.web.RequestHandler``
"""
return self.ref_rh
@classmethod
def as_view(cls, view_type, *init_args, **init_kwargs):
"""
Return a subclass of tornado.web.RequestHandler and
apply required setting.
"""
global _method
new_cls = type(
cls.__name__ + '_' + _BridgeMixin.__name__ + '_restless',
(_BridgeMixin, cls._request_handler_base_,),
dict(
__resource_cls__=cls,
__resource_args__=init_args,
__resource_kwargs__=init_kwargs,
__resource_view_type__=view_type)
)
"""
Add required http-methods to the newly created class
We need to scan through MRO to find what functions users declared,
and then add corresponding http-methods used by Tornado.
"""
bases = inspect.getmro(cls)
bases = bases[0:bases.index(Resource)-1]
for k, v in cls.http_methods[view_type].items():
if any(v in base_cls.__dict__ for base_cls in bases):
setattr(new_cls, k.lower(), _method)
return new_cls
def request_method(self):
return self.request.method
def request_body(self):
return self.request.body
def build_response(self, data, status=OK):
if status == NO_CONTENT:
# Avoid crashing the client when it tries to parse nonexisting JSON.
content_type = 'text/plain'
else:
content_type = 'application/json'
self.ref_rh.set_header("Content-Type", "{}; charset=UTF-8"
.format(content_type))
self.ref_rh.set_status(status)
self.ref_rh.finish(data)
def is_debug(self):
return self.application.settings.get('debug', False)
@gen.coroutine
|
toastdriven/restless | restless/preparers.py | FieldsPreparer.prepare | python | def prepare(self, data):
result = {}
if not self.fields:
# No fields specified. Serialize everything.
return data
for fieldname, lookup in self.fields.items():
if isinstance(lookup, SubPreparer):
result[fieldname] = lookup.prepare(data)
else:
result[fieldname] = self.lookup_data(lookup, data)
return result | Handles transforming the provided data into the fielded data that should
be exposed to the end user.
Uses the ``lookup_data`` method to traverse dotted paths.
Returns a dictionary of data as the response. | train | https://github.com/toastdriven/restless/blob/661593b7b43c42d1bc508dec795356297991255e/restless/preparers.py#L42-L63 | [
"def lookup_data(self, lookup, data):\n \"\"\"\n Given a lookup string, attempts to descend through nested data looking for\n the value.\n\n Can work with either dictionary-alikes or objects (or any combination of\n those).\n\n Lookups should be a string. If it is a dotted path, it will be split on\n ``.`` & it will traverse through to find the final value. If not, it will\n simply attempt to find either a key or attribute of that name & return it.\n\n Example::\n\n >>> data = {\n ... 'type': 'message',\n ... 'greeting': {\n ... 'en': 'hello',\n ... 'fr': 'bonjour',\n ... 'es': 'hola',\n ... },\n ... 'person': Person(\n ... name='daniel'\n ... )\n ... }\n >>> lookup_data('type', data)\n 'message'\n >>> lookup_data('greeting.en', data)\n 'hello'\n >>> lookup_data('person.name', data)\n 'daniel'\n\n \"\"\"\n value = data\n parts = lookup.split('.')\n\n if not parts or not parts[0]:\n return value\n\n part = parts[0]\n remaining_lookup = '.'.join(parts[1:])\n\n if callable(getattr(data, 'keys', None)) and hasattr(data, '__getitem__'):\n # Dictionary enough for us.\n value = data[part]\n elif data is not None:\n # Assume it's an object.\n value = getattr(data, part)\n\n # Call if it's callable except if it's a Django DB manager instance\n # We check if is a manager by checking the db_manager (duck typing)\n if callable(value) and not hasattr(value, 'db_manager'):\n value = value()\n\n if not remaining_lookup:\n return value\n\n # There's more to lookup, so dive in recursively.\n return self.lookup_data(remaining_lookup, value)\n"
] | class FieldsPreparer(Preparer):
"""
A more complex preparation object, this will return a given set of fields.
This takes a ``fields`` parameter, which should be a dictionary of
keys (fieldnames to expose to the user) & values (a dotted lookup path to
the desired attribute/key on the object).
Example::
preparer = FieldsPreparer(fields={
# ``user`` is the key the client will see.
# ``author.pk`` is the dotted path lookup ``FieldsPreparer``
# will traverse on the data to return a value.
'user': 'author.pk',
})
"""
def __init__(self, fields):
super(FieldsPreparer, self).__init__()
self.fields = fields
def lookup_data(self, lookup, data):
"""
Given a lookup string, attempts to descend through nested data looking for
the value.
Can work with either dictionary-alikes or objects (or any combination of
those).
Lookups should be a string. If it is a dotted path, it will be split on
``.`` & it will traverse through to find the final value. If not, it will
simply attempt to find either a key or attribute of that name & return it.
Example::
>>> data = {
... 'type': 'message',
... 'greeting': {
... 'en': 'hello',
... 'fr': 'bonjour',
... 'es': 'hola',
... },
... 'person': Person(
... name='daniel'
... )
... }
>>> lookup_data('type', data)
'message'
>>> lookup_data('greeting.en', data)
'hello'
>>> lookup_data('person.name', data)
'daniel'
"""
value = data
parts = lookup.split('.')
if not parts or not parts[0]:
return value
part = parts[0]
remaining_lookup = '.'.join(parts[1:])
if callable(getattr(data, 'keys', None)) and hasattr(data, '__getitem__'):
# Dictionary enough for us.
value = data[part]
elif data is not None:
# Assume it's an object.
value = getattr(data, part)
# Call if it's callable except if it's a Django DB manager instance
# We check if is a manager by checking the db_manager (duck typing)
if callable(value) and not hasattr(value, 'db_manager'):
value = value()
if not remaining_lookup:
return value
# There's more to lookup, so dive in recursively.
return self.lookup_data(remaining_lookup, value)
|
toastdriven/restless | restless/preparers.py | FieldsPreparer.lookup_data | python | def lookup_data(self, lookup, data):
value = data
parts = lookup.split('.')
if not parts or not parts[0]:
return value
part = parts[0]
remaining_lookup = '.'.join(parts[1:])
if callable(getattr(data, 'keys', None)) and hasattr(data, '__getitem__'):
# Dictionary enough for us.
value = data[part]
elif data is not None:
# Assume it's an object.
value = getattr(data, part)
# Call if it's callable except if it's a Django DB manager instance
# We check if is a manager by checking the db_manager (duck typing)
if callable(value) and not hasattr(value, 'db_manager'):
value = value()
if not remaining_lookup:
return value
# There's more to lookup, so dive in recursively.
return self.lookup_data(remaining_lookup, value) | Given a lookup string, attempts to descend through nested data looking for
the value.
Can work with either dictionary-alikes or objects (or any combination of
those).
Lookups should be a string. If it is a dotted path, it will be split on
``.`` & it will traverse through to find the final value. If not, it will
simply attempt to find either a key or attribute of that name & return it.
Example::
>>> data = {
... 'type': 'message',
... 'greeting': {
... 'en': 'hello',
... 'fr': 'bonjour',
... 'es': 'hola',
... },
... 'person': Person(
... name='daniel'
... )
... }
>>> lookup_data('type', data)
'message'
>>> lookup_data('greeting.en', data)
'hello'
>>> lookup_data('person.name', data)
'daniel' | train | https://github.com/toastdriven/restless/blob/661593b7b43c42d1bc508dec795356297991255e/restless/preparers.py#L65-L123 | [
"def lookup_data(self, lookup, data):\n \"\"\"\n Given a lookup string, attempts to descend through nested data looking for\n the value.\n\n Can work with either dictionary-alikes or objects (or any combination of\n those).\n\n Lookups should be a string. If it is a dotted path, it will be split on\n ``.`` & it will traverse through to find the final value. If not, it will\n simply attempt to find either a key or attribute of that name & return it.\n\n Example::\n\n >>> data = {\n ... 'type': 'message',\n ... 'greeting': {\n ... 'en': 'hello',\n ... 'fr': 'bonjour',\n ... 'es': 'hola',\n ... },\n ... 'person': Person(\n ... name='daniel'\n ... )\n ... }\n >>> lookup_data('type', data)\n 'message'\n >>> lookup_data('greeting.en', data)\n 'hello'\n >>> lookup_data('person.name', data)\n 'daniel'\n\n \"\"\"\n value = data\n parts = lookup.split('.')\n\n if not parts or not parts[0]:\n return value\n\n part = parts[0]\n remaining_lookup = '.'.join(parts[1:])\n\n if callable(getattr(data, 'keys', None)) and hasattr(data, '__getitem__'):\n # Dictionary enough for us.\n value = data[part]\n elif data is not None:\n # Assume it's an object.\n value = getattr(data, part)\n\n # Call if it's callable except if it's a Django DB manager instance\n # We check if is a manager by checking the db_manager (duck typing)\n if callable(value) and not hasattr(value, 'db_manager'):\n value = value()\n\n if not remaining_lookup:\n return value\n\n # There's more to lookup, so dive in recursively.\n return self.lookup_data(remaining_lookup, value)\n"
] | class FieldsPreparer(Preparer):
"""
A more complex preparation object, this will return a given set of fields.
This takes a ``fields`` parameter, which should be a dictionary of
keys (fieldnames to expose to the user) & values (a dotted lookup path to
the desired attribute/key on the object).
Example::
preparer = FieldsPreparer(fields={
# ``user`` is the key the client will see.
# ``author.pk`` is the dotted path lookup ``FieldsPreparer``
# will traverse on the data to return a value.
'user': 'author.pk',
})
"""
def __init__(self, fields):
super(FieldsPreparer, self).__init__()
self.fields = fields
def prepare(self, data):
"""
Handles transforming the provided data into the fielded data that should
be exposed to the end user.
Uses the ``lookup_data`` method to traverse dotted paths.
Returns a dictionary of data as the response.
"""
result = {}
if not self.fields:
# No fields specified. Serialize everything.
return data
for fieldname, lookup in self.fields.items():
if isinstance(lookup, SubPreparer):
result[fieldname] = lookup.prepare(data)
else:
result[fieldname] = self.lookup_data(lookup, data)
return result
|
toastdriven/restless | restless/preparers.py | CollectionSubPreparer.prepare | python | def prepare(self, data):
result = []
for item in self.get_inner_data(data):
result.append(self.preparer.prepare(item))
return result | Handles passing each item in the collection data to the configured
subpreparer.
Uses a loop and the ``get_inner_data`` method to provide the correct
item of the data.
Returns a list of data as the response. | train | https://github.com/toastdriven/restless/blob/661593b7b43c42d1bc508dec795356297991255e/restless/preparers.py#L201-L216 | [
"def get_inner_data(self, data):\n \"\"\"\n Used internally so that the correct data is extracted out of the\n broader dataset, allowing the preparer being called to deal with just\n the expected subset.\n \"\"\"\n return self.lookup_data(self.lookup, data)\n"
] | class CollectionSubPreparer(SubPreparer):
"""
A preparation class designed to handle collections of data.
This is useful in the case where you have a 1-to-many or many-to-many
relationship of data to expose as part of the parent data.
Example::
# First, set up a preparer that handles the data for each thing in
# the broader collection.
comment_preparer = FieldsPreparer(fields={
'comment': 'comment_text',
'created': 'created',
})
# Then use it with the ``CollectionSubPreparer`` to create a list
# of prepared sub items.
preparer = FieldsPreparer(fields={
# A normal blog post field.
'post': 'post_text',
# All the comments on the post.
'comments': CollectionSubPreparer('comments.all', comment_preparer),
})
"""
|
toastdriven/restless | restless/dj.py | DjangoResource.build_url_name | python | def build_url_name(cls, name, name_prefix=None):
if name_prefix is None:
name_prefix = 'api_{}'.format(
cls.__name__.replace('Resource', '').lower()
)
name_prefix = name_prefix.rstrip('_')
return '_'.join([name_prefix, name]) | Given a ``name`` & an optional ``name_prefix``, this generates a name
for a URL.
:param name: The name for the URL (ex. 'detail')
:type name: string
:param name_prefix: (Optional) A prefix for the URL's name (for
resolving). The default is ``None``, which will autocreate a prefix
based on the class name. Ex: ``BlogPostResource`` ->
``api_blog_post_list``
:type name_prefix: string
:returns: The final name
:rtype: string | train | https://github.com/toastdriven/restless/blob/661593b7b43c42d1bc508dec795356297991255e/restless/dj.py#L90-L113 | null | class DjangoResource(Resource):
"""
A Django-specific ``Resource`` subclass.
Doesn't require any special configuration, but helps when working in a
Django environment.
"""
def serialize_list(self, data):
if data is None:
return super(DjangoResource, self).serialize_list(data)
if getattr(self, 'paginate', False):
page_size = getattr(self, 'page_size', getattr(settings, 'RESTLESS_PAGE_SIZE', 10))
paginator = Paginator(data, page_size)
page_number = self.request.GET.get('p', 1)
if page_number not in paginator.page_range:
raise BadRequest('Invalid page number')
self.page = paginator.page(page_number)
data = self.page.object_list
return super(DjangoResource, self).serialize_list(data)
def wrap_list_response(self, data):
response_dict = super(DjangoResource, self).wrap_list_response(data)
if hasattr(self, 'page'):
next_page = self.page.has_next() and self.page.next_page_number() or None
previous_page = self.page.has_previous() and self.page.previous_page_number() or None
response_dict['pagination'] = {
'num_pages': self.page.paginator.num_pages,
'count': self.page.paginator.count,
'page': self.page.number,
'start_index': self.page.start_index(),
'end_index': self.page.end_index(),
'next_page': next_page,
'previous_page': previous_page,
'per_page': self.page.paginator.per_page,
}
return response_dict
# Because Django.
@classmethod
def as_list(self, *args, **kwargs):
return csrf_exempt(super(DjangoResource, self).as_list(*args, **kwargs))
@classmethod
def as_detail(self, *args, **kwargs):
return csrf_exempt(super(DjangoResource, self).as_detail(*args, **kwargs))
def is_debug(self):
return settings.DEBUG
def build_response(self, data, status=OK):
if status == NO_CONTENT:
# Avoid crashing the client when it tries to parse nonexisting JSON.
content_type = 'text/plain'
else:
content_type = 'application/json'
resp = HttpResponse(data, content_type=content_type, status=status)
return resp
def build_error(self, err):
# A bit nicer behavior surrounding things that don't exist.
if isinstance(err, (ObjectDoesNotExist, Http404)):
err = NotFound(msg=six.text_type(err))
return super(DjangoResource, self).build_error(err)
@classmethod
@classmethod
def urls(cls, name_prefix=None):
"""
A convenience method for hooking up the URLs.
This automatically adds a list & a detail endpoint to your URLconf.
:param name_prefix: (Optional) A prefix for the URL's name (for
resolving). The default is ``None``, which will autocreate a prefix
based on the class name. Ex: ``BlogPostResource`` ->
``api_blogpost_list``
:type name_prefix: string
:returns: A list of ``url`` objects for ``include(...)``
"""
return [
url(r'^$', cls.as_list(), name=cls.build_url_name('list', name_prefix)),
url(r'^(?P<pk>[\w-]+)/$', cls.as_detail(), name=cls.build_url_name('detail', name_prefix)),
]
|
toastdriven/restless | restless/dj.py | DjangoResource.urls | python | def urls(cls, name_prefix=None):
return [
url(r'^$', cls.as_list(), name=cls.build_url_name('list', name_prefix)),
url(r'^(?P<pk>[\w-]+)/$', cls.as_detail(), name=cls.build_url_name('detail', name_prefix)),
] | A convenience method for hooking up the URLs.
This automatically adds a list & a detail endpoint to your URLconf.
:param name_prefix: (Optional) A prefix for the URL's name (for
resolving). The default is ``None``, which will autocreate a prefix
based on the class name. Ex: ``BlogPostResource`` ->
``api_blogpost_list``
:type name_prefix: string
:returns: A list of ``url`` objects for ``include(...)`` | train | https://github.com/toastdriven/restless/blob/661593b7b43c42d1bc508dec795356297991255e/restless/dj.py#L116-L133 | [
"def as_list(self, *args, **kwargs):\n return csrf_exempt(super(DjangoResource, self).as_list(*args, **kwargs))\n",
"def as_detail(self, *args, **kwargs):\n return csrf_exempt(super(DjangoResource, self).as_detail(*args, **kwargs))\n",
"def build_url_name(cls, name, name_prefix=None):\n \"\"\"\n Given a ``name`` & an optional ``name_prefix``, this generates a name\n for a URL.\n\n :param name: The name for the URL (ex. 'detail')\n :type name: string\n\n :param name_prefix: (Optional) A prefix for the URL's name (for\n resolving). The default is ``None``, which will autocreate a prefix\n based on the class name. Ex: ``BlogPostResource`` ->\n ``api_blog_post_list``\n :type name_prefix: string\n\n :returns: The final name\n :rtype: string\n \"\"\"\n if name_prefix is None:\n name_prefix = 'api_{}'.format(\n cls.__name__.replace('Resource', '').lower()\n )\n\n name_prefix = name_prefix.rstrip('_')\n return '_'.join([name_prefix, name])\n"
] | class DjangoResource(Resource):
"""
A Django-specific ``Resource`` subclass.
Doesn't require any special configuration, but helps when working in a
Django environment.
"""
def serialize_list(self, data):
if data is None:
return super(DjangoResource, self).serialize_list(data)
if getattr(self, 'paginate', False):
page_size = getattr(self, 'page_size', getattr(settings, 'RESTLESS_PAGE_SIZE', 10))
paginator = Paginator(data, page_size)
page_number = self.request.GET.get('p', 1)
if page_number not in paginator.page_range:
raise BadRequest('Invalid page number')
self.page = paginator.page(page_number)
data = self.page.object_list
return super(DjangoResource, self).serialize_list(data)
def wrap_list_response(self, data):
response_dict = super(DjangoResource, self).wrap_list_response(data)
if hasattr(self, 'page'):
next_page = self.page.has_next() and self.page.next_page_number() or None
previous_page = self.page.has_previous() and self.page.previous_page_number() or None
response_dict['pagination'] = {
'num_pages': self.page.paginator.num_pages,
'count': self.page.paginator.count,
'page': self.page.number,
'start_index': self.page.start_index(),
'end_index': self.page.end_index(),
'next_page': next_page,
'previous_page': previous_page,
'per_page': self.page.paginator.per_page,
}
return response_dict
# Because Django.
@classmethod
def as_list(self, *args, **kwargs):
return csrf_exempt(super(DjangoResource, self).as_list(*args, **kwargs))
@classmethod
def as_detail(self, *args, **kwargs):
return csrf_exempt(super(DjangoResource, self).as_detail(*args, **kwargs))
def is_debug(self):
return settings.DEBUG
def build_response(self, data, status=OK):
if status == NO_CONTENT:
# Avoid crashing the client when it tries to parse nonexisting JSON.
content_type = 'text/plain'
else:
content_type = 'application/json'
resp = HttpResponse(data, content_type=content_type, status=status)
return resp
def build_error(self, err):
# A bit nicer behavior surrounding things that don't exist.
if isinstance(err, (ObjectDoesNotExist, Http404)):
err = NotFound(msg=six.text_type(err))
return super(DjangoResource, self).build_error(err)
@classmethod
def build_url_name(cls, name, name_prefix=None):
"""
Given a ``name`` & an optional ``name_prefix``, this generates a name
for a URL.
:param name: The name for the URL (ex. 'detail')
:type name: string
:param name_prefix: (Optional) A prefix for the URL's name (for
resolving). The default is ``None``, which will autocreate a prefix
based on the class name. Ex: ``BlogPostResource`` ->
``api_blog_post_list``
:type name_prefix: string
:returns: The final name
:rtype: string
"""
if name_prefix is None:
name_prefix = 'api_{}'.format(
cls.__name__.replace('Resource', '').lower()
)
name_prefix = name_prefix.rstrip('_')
return '_'.join([name_prefix, name])
@classmethod
|
toastdriven/restless | restless/fl.py | FlaskResource.build_endpoint_name | python | def build_endpoint_name(cls, name, endpoint_prefix=None):
if endpoint_prefix is None:
endpoint_prefix = 'api_{}'.format(
cls.__name__.replace('Resource', '').lower()
)
endpoint_prefix = endpoint_prefix.rstrip('_')
return '_'.join([endpoint_prefix, name]) | Given a ``name`` & an optional ``endpoint_prefix``, this generates a name
for a URL.
:param name: The name for the URL (ex. 'detail')
:type name: string
:param endpoint_prefix: (Optional) A prefix for the URL's name (for
resolving). The default is ``None``, which will autocreate a prefix
based on the class name. Ex: ``BlogPostResource`` ->
``api_blogpost_list``
:type endpoint_prefix: string
:returns: The final name
:rtype: string | train | https://github.com/toastdriven/restless/blob/661593b7b43c42d1bc508dec795356297991255e/restless/fl.py#L59-L82 | null | class FlaskResource(Resource):
"""
A Flask-specific ``Resource`` subclass.
Doesn't require any special configuration, but helps when working in a
Flask environment.
"""
@classmethod
def as_list(cls, *init_args, **init_kwargs):
# Overridden here, because Flask uses a global ``request`` object
# rather than passing it to each view.
def _wrapper(*args, **kwargs):
# Make a new instance so that no state potentially leaks between
# instances.
inst = cls(*init_args, **init_kwargs)
inst.request = request
return inst.handle('list', *args, **kwargs)
return _wrapper
@classmethod
def as_detail(cls, *init_args, **init_kwargs):
# Overridden here, because Flask uses a global ``request`` object
# rather than passing it to each view.
def _wrapper(*args, **kwargs):
# Make a new instance so that no state potentially leaks between
# instances.
inst = cls(*init_args, **init_kwargs)
inst.request = request
return inst.handle('detail', *args, **kwargs)
return _wrapper
def request_body(self):
return self.request.data
def is_debug(self):
from flask import current_app
return current_app.debug
def build_response(self, data, status=OK):
if status == NO_CONTENT:
# Avoid crashing the client when it tries to parse nonexisting JSON.
content_type = 'text/plain'
else:
content_type = 'application/json'
return make_response(data, status, {
'Content-Type': content_type,
})
@classmethod
@classmethod
def add_url_rules(cls, app, rule_prefix, endpoint_prefix=None):
"""
A convenience method for hooking up the URLs.
This automatically adds a list & a detail endpoint to your routes.
:param app: The ``Flask`` object for your app.
:type app: ``flask.Flask``
:param rule_prefix: The start of the URL to handle.
:type rule_prefix: string
:param endpoint_prefix: (Optional) A prefix for the URL's name (for
endpoints). The default is ``None``, which will autocreate a prefix
based on the class name. Ex: ``BlogPostResource`` ->
``api_blog_post_list``
:type endpoint_prefix: string
:returns: Nothing
"""
methods = ['GET', 'POST', 'PUT', 'DELETE']
app.add_url_rule(
rule_prefix,
endpoint=cls.build_endpoint_name('list', endpoint_prefix),
view_func=cls.as_list(),
methods=methods
)
app.add_url_rule(
rule_prefix + '<pk>/',
endpoint=cls.build_endpoint_name('detail', endpoint_prefix),
view_func=cls.as_detail(),
methods=methods
)
|
toastdriven/restless | restless/fl.py | FlaskResource.add_url_rules | python | def add_url_rules(cls, app, rule_prefix, endpoint_prefix=None):
methods = ['GET', 'POST', 'PUT', 'DELETE']
app.add_url_rule(
rule_prefix,
endpoint=cls.build_endpoint_name('list', endpoint_prefix),
view_func=cls.as_list(),
methods=methods
)
app.add_url_rule(
rule_prefix + '<pk>/',
endpoint=cls.build_endpoint_name('detail', endpoint_prefix),
view_func=cls.as_detail(),
methods=methods
) | A convenience method for hooking up the URLs.
This automatically adds a list & a detail endpoint to your routes.
:param app: The ``Flask`` object for your app.
:type app: ``flask.Flask``
:param rule_prefix: The start of the URL to handle.
:type rule_prefix: string
:param endpoint_prefix: (Optional) A prefix for the URL's name (for
endpoints). The default is ``None``, which will autocreate a prefix
based on the class name. Ex: ``BlogPostResource`` ->
``api_blog_post_list``
:type endpoint_prefix: string
:returns: Nothing | train | https://github.com/toastdriven/restless/blob/661593b7b43c42d1bc508dec795356297991255e/restless/fl.py#L85-L118 | [
"def as_list(cls, *init_args, **init_kwargs):\n # Overridden here, because Flask uses a global ``request`` object\n # rather than passing it to each view.\n def _wrapper(*args, **kwargs):\n # Make a new instance so that no state potentially leaks between\n # instances.\n inst = cls(*init_args, **init_kwargs)\n inst.request = request\n return inst.handle('list', *args, **kwargs)\n\n return _wrapper\n",
"def as_detail(cls, *init_args, **init_kwargs):\n # Overridden here, because Flask uses a global ``request`` object\n # rather than passing it to each view.\n def _wrapper(*args, **kwargs):\n # Make a new instance so that no state potentially leaks between\n # instances.\n inst = cls(*init_args, **init_kwargs)\n inst.request = request\n return inst.handle('detail', *args, **kwargs)\n\n return _wrapper\n",
"def build_endpoint_name(cls, name, endpoint_prefix=None):\n \"\"\"\n Given a ``name`` & an optional ``endpoint_prefix``, this generates a name\n for a URL.\n\n :param name: The name for the URL (ex. 'detail')\n :type name: string\n\n :param endpoint_prefix: (Optional) A prefix for the URL's name (for\n resolving). The default is ``None``, which will autocreate a prefix\n based on the class name. Ex: ``BlogPostResource`` ->\n ``api_blogpost_list``\n :type endpoint_prefix: string\n\n :returns: The final name\n :rtype: string\n \"\"\"\n if endpoint_prefix is None:\n endpoint_prefix = 'api_{}'.format(\n cls.__name__.replace('Resource', '').lower()\n )\n\n endpoint_prefix = endpoint_prefix.rstrip('_')\n return '_'.join([endpoint_prefix, name])\n"
] | class FlaskResource(Resource):
"""
A Flask-specific ``Resource`` subclass.
Doesn't require any special configuration, but helps when working in a
Flask environment.
"""
@classmethod
def as_list(cls, *init_args, **init_kwargs):
# Overridden here, because Flask uses a global ``request`` object
# rather than passing it to each view.
def _wrapper(*args, **kwargs):
# Make a new instance so that no state potentially leaks between
# instances.
inst = cls(*init_args, **init_kwargs)
inst.request = request
return inst.handle('list', *args, **kwargs)
return _wrapper
@classmethod
def as_detail(cls, *init_args, **init_kwargs):
# Overridden here, because Flask uses a global ``request`` object
# rather than passing it to each view.
def _wrapper(*args, **kwargs):
# Make a new instance so that no state potentially leaks between
# instances.
inst = cls(*init_args, **init_kwargs)
inst.request = request
return inst.handle('detail', *args, **kwargs)
return _wrapper
def request_body(self):
return self.request.data
def is_debug(self):
from flask import current_app
return current_app.debug
def build_response(self, data, status=OK):
if status == NO_CONTENT:
# Avoid crashing the client when it tries to parse nonexisting JSON.
content_type = 'text/plain'
else:
content_type = 'application/json'
return make_response(data, status, {
'Content-Type': content_type,
})
@classmethod
def build_endpoint_name(cls, name, endpoint_prefix=None):
"""
Given a ``name`` & an optional ``endpoint_prefix``, this generates a name
for a URL.
:param name: The name for the URL (ex. 'detail')
:type name: string
:param endpoint_prefix: (Optional) A prefix for the URL's name (for
resolving). The default is ``None``, which will autocreate a prefix
based on the class name. Ex: ``BlogPostResource`` ->
``api_blogpost_list``
:type endpoint_prefix: string
:returns: The final name
:rtype: string
"""
if endpoint_prefix is None:
endpoint_prefix = 'api_{}'.format(
cls.__name__.replace('Resource', '').lower()
)
endpoint_prefix = endpoint_prefix.rstrip('_')
return '_'.join([endpoint_prefix, name])
@classmethod
|
toastdriven/restless | restless/pyr.py | PyramidResource.build_routename | python | def build_routename(cls, name, routename_prefix=None):
if routename_prefix is None:
routename_prefix = 'api_{}'.format(
cls.__name__.replace('Resource', '').lower()
)
routename_prefix = routename_prefix.rstrip('_')
return '_'.join([routename_prefix, name]) | Given a ``name`` & an optional ``routename_prefix``, this generates a
name for a URL.
:param name: The name for the URL (ex. 'detail')
:type name: string
:param routename_prefix: (Optional) A prefix for the URL's name (for
resolving). The default is ``None``, which will autocreate a prefix
based on the class name. Ex: ``BlogPostResource`` ->
``api_blogpost_list``
:type routename_prefix: string
:returns: The final name
:rtype: string | train | https://github.com/toastdriven/restless/blob/661593b7b43c42d1bc508dec795356297991255e/restless/pyr.py#L41-L64 | null | class PyramidResource(Resource):
"""
A Pyramid-specific ``Resource`` subclass.
Doesn't require any special configuration, but helps when working in a
Pyramid environment.
"""
@classmethod
def as_list(cls, *args, **kwargs):
return super(PyramidResource, cls).as_list(*args, **kwargs)
@classmethod
def as_detail(cls, *init_args, **init_kwargs):
def _wrapper(request):
# Make a new instance so that no state potentially leaks between
# instances.
inst = cls(*init_args, **init_kwargs)
inst.request = request
name = request.matchdict['name']
return inst.handle('detail', name)
return _wrapper
def build_response(self, data, status=OK):
if status == NO_CONTENT:
# Avoid crashing the client when it tries to parse nonexisting JSON.
content_type = 'text/plain'
else:
content_type = 'application/json'
resp = Response(data, status_code=status, content_type=content_type)
return resp
@classmethod
@classmethod
def add_views(cls, config, rule_prefix, routename_prefix=None):
"""
A convenience method for registering the routes and views in pyramid.
This automatically adds a list and detail endpoint to your routes.
:param config: The pyramid ``Configurator`` object for your app.
:type config: ``pyramid.config.Configurator``
:param rule_prefix: The start of the URL to handle.
:type rule_prefix: string
:param routename_prefix: (Optional) A prefix for the route's name.
The default is ``None``, which will autocreate a prefix based on the
class name. Ex: ``PostResource`` -> ``api_post_list``
:type routename_prefix: string
:returns: ``pyramid.config.Configurator``
"""
methods = ('GET', 'POST', 'PUT', 'DELETE')
config.add_route(
cls.build_routename('list', routename_prefix),
rule_prefix
)
config.add_view(
cls.as_list(),
route_name=cls.build_routename('list', routename_prefix),
request_method=methods
)
config.add_route(
cls.build_routename('detail', routename_prefix),
rule_prefix + '{name}/'
)
config.add_view(
cls.as_detail(),
route_name=cls.build_routename('detail', routename_prefix),
request_method=methods
)
return config
|
toastdriven/restless | restless/pyr.py | PyramidResource.add_views | python | def add_views(cls, config, rule_prefix, routename_prefix=None):
methods = ('GET', 'POST', 'PUT', 'DELETE')
config.add_route(
cls.build_routename('list', routename_prefix),
rule_prefix
)
config.add_view(
cls.as_list(),
route_name=cls.build_routename('list', routename_prefix),
request_method=methods
)
config.add_route(
cls.build_routename('detail', routename_prefix),
rule_prefix + '{name}/'
)
config.add_view(
cls.as_detail(),
route_name=cls.build_routename('detail', routename_prefix),
request_method=methods
)
return config | A convenience method for registering the routes and views in pyramid.
This automatically adds a list and detail endpoint to your routes.
:param config: The pyramid ``Configurator`` object for your app.
:type config: ``pyramid.config.Configurator``
:param rule_prefix: The start of the URL to handle.
:type rule_prefix: string
:param routename_prefix: (Optional) A prefix for the route's name.
The default is ``None``, which will autocreate a prefix based on the
class name. Ex: ``PostResource`` -> ``api_post_list``
:type routename_prefix: string
:returns: ``pyramid.config.Configurator`` | train | https://github.com/toastdriven/restless/blob/661593b7b43c42d1bc508dec795356297991255e/restless/pyr.py#L67-L107 | [
"def as_list(cls, *args, **kwargs):\n return super(PyramidResource, cls).as_list(*args, **kwargs)\n",
"def as_detail(cls, *init_args, **init_kwargs):\n def _wrapper(request):\n # Make a new instance so that no state potentially leaks between\n # instances.\n inst = cls(*init_args, **init_kwargs)\n inst.request = request\n name = request.matchdict['name']\n return inst.handle('detail', name)\n\n return _wrapper\n",
"def build_routename(cls, name, routename_prefix=None):\n \"\"\"\n Given a ``name`` & an optional ``routename_prefix``, this generates a\n name for a URL.\n\n :param name: The name for the URL (ex. 'detail')\n :type name: string\n\n :param routename_prefix: (Optional) A prefix for the URL's name (for\n resolving). The default is ``None``, which will autocreate a prefix\n based on the class name. Ex: ``BlogPostResource`` ->\n ``api_blogpost_list``\n :type routename_prefix: string\n\n :returns: The final name\n :rtype: string\n \"\"\"\n if routename_prefix is None:\n routename_prefix = 'api_{}'.format(\n cls.__name__.replace('Resource', '').lower()\n )\n\n routename_prefix = routename_prefix.rstrip('_')\n return '_'.join([routename_prefix, name])\n"
] | class PyramidResource(Resource):
"""
A Pyramid-specific ``Resource`` subclass.
Doesn't require any special configuration, but helps when working in a
Pyramid environment.
"""
@classmethod
def as_list(cls, *args, **kwargs):
return super(PyramidResource, cls).as_list(*args, **kwargs)
@classmethod
def as_detail(cls, *init_args, **init_kwargs):
def _wrapper(request):
# Make a new instance so that no state potentially leaks between
# instances.
inst = cls(*init_args, **init_kwargs)
inst.request = request
name = request.matchdict['name']
return inst.handle('detail', name)
return _wrapper
def build_response(self, data, status=OK):
if status == NO_CONTENT:
# Avoid crashing the client when it tries to parse nonexisting JSON.
content_type = 'text/plain'
else:
content_type = 'application/json'
resp = Response(data, status_code=status, content_type=content_type)
return resp
@classmethod
def build_routename(cls, name, routename_prefix=None):
"""
Given a ``name`` & an optional ``routename_prefix``, this generates a
name for a URL.
:param name: The name for the URL (ex. 'detail')
:type name: string
:param routename_prefix: (Optional) A prefix for the URL's name (for
resolving). The default is ``None``, which will autocreate a prefix
based on the class name. Ex: ``BlogPostResource`` ->
``api_blogpost_list``
:type routename_prefix: string
:returns: The final name
:rtype: string
"""
if routename_prefix is None:
routename_prefix = 'api_{}'.format(
cls.__name__.replace('Resource', '').lower()
)
routename_prefix = routename_prefix.rstrip('_')
return '_'.join([routename_prefix, name])
@classmethod
|
toastdriven/restless | restless/serializers.py | JSONSerializer.deserialize | python | def deserialize(self, body):
try:
if isinstance(body, bytes):
return json.loads(body.decode('utf-8'))
return json.loads(body)
except ValueError:
raise BadRequest('Request body is not valid JSON') | The low-level deserialization.
Underpins ``deserialize``, ``deserialize_list`` &
``deserialize_detail``.
Has no built-in smarts, simply loads the JSON.
:param body: The body of the current request
:type body: string
:returns: The deserialized data
:rtype: ``list`` or ``dict`` | train | https://github.com/toastdriven/restless/blob/661593b7b43c42d1bc508dec795356297991255e/restless/serializers.py#L47-L67 | null | class JSONSerializer(Serializer):
def serialize(self, data):
"""
The low-level serialization.
Underpins ``serialize``, ``serialize_list`` &
``serialize_detail``.
Has no built-in smarts, simply dumps the JSON.
:param data: The body for the response
:type data: string
:returns: A serialized version of the data
:rtype: string
"""
return json.dumps(data, cls=MoreTypesJSONEncoder)
|
jasonrollins/shareplum | shareplum/shareplum.py | Office365.GetSecurityToken | python | def GetSecurityToken(self, username, password):
url = 'https://login.microsoftonline.com/extSTS.srf'
body = """
<s:Envelope xmlns:s="http://www.w3.org/2003/05/soap-envelope"
xmlns:a="http://www.w3.org/2005/08/addressing"
xmlns:u="http://docs.oasis-open.org/wss/2004/01/oasis-200401-wss-wssecurity-utility-1.0.xsd">
<s:Header>
<a:Action s:mustUnderstand="1">http://schemas.xmlsoap.org/ws/2005/02/trust/RST/Issue</a:Action>
<a:ReplyTo>
<a:Address>http://www.w3.org/2005/08/addressing/anonymous</a:Address>
</a:ReplyTo>
<a:To s:mustUnderstand="1">https://login.microsoftonline.com/extSTS.srf</a:To>
<o:Security s:mustUnderstand="1"
xmlns:o="http://docs.oasis-open.org/wss/2004/01/oasis-200401-wss-wssecurity-secext-1.0.xsd">
<o:UsernameToken>
<o:Username>%s</o:Username>
<o:Password>%s</o:Password>
</o:UsernameToken>
</o:Security>
</s:Header>
<s:Body>
<t:RequestSecurityToken xmlns:t="http://schemas.xmlsoap.org/ws/2005/02/trust">
<wsp:AppliesTo xmlns:wsp="http://schemas.xmlsoap.org/ws/2004/09/policy">
<a:EndpointReference>
<a:Address>%s</a:Address>
</a:EndpointReference>
</wsp:AppliesTo>
<t:KeyType>http://schemas.xmlsoap.org/ws/2005/05/identity/NoProofKey</t:KeyType>
<t:RequestType>http://schemas.xmlsoap.org/ws/2005/02/trust/Issue</t:RequestType>
<t:TokenType>urn:oasis:names:tc:SAML:1.0:assertion</t:TokenType>
</t:RequestSecurityToken>
</s:Body>
</s:Envelope>""" % (username, password, self.share_point_site)
headers = {'accept': 'application/json;odata=verbose'}
response = requests.post(url, body, headers=headers)
xmldoc = etree.fromstring(response.content)
token = xmldoc.find(
'.//{http://docs.oasis-open.org/wss/2004/01/oasis-200401-wss-wssecurity-secext-1.0.xsd}BinarySecurityToken'
)
if token is not None:
return token.text
else:
raise Exception('Check username/password and rootsite') | Grabs a security Token to authenticate to Office 365 services | train | https://github.com/jasonrollins/shareplum/blob/404f320808912619920e2d787f2c4387225a14e0/shareplum/shareplum.py#L20-L68 | null | class Office365(object):
"""
Class to authenticate Office 365 Sharepoint
"""
def __init__(self, share_point_site, username, password):
self.Username = username
self.Password = password
self.share_point_site = share_point_site
def GetCookies(self):
"""
Grabs the cookies form your Office Sharepoint site
and uses it as Authentication for the rest of the calls
"""
sectoken = self.GetSecurityToken(self.Username, self.Password)
url = self.share_point_site+ '/_forms/default.aspx?wa=wsignin1.0'
response = requests.post(url, data=sectoken)
return response.cookies
|
jasonrollins/shareplum | shareplum/shareplum.py | Office365.GetCookies | python | def GetCookies(self):
sectoken = self.GetSecurityToken(self.Username, self.Password)
url = self.share_point_site+ '/_forms/default.aspx?wa=wsignin1.0'
response = requests.post(url, data=sectoken)
return response.cookies | Grabs the cookies form your Office Sharepoint site
and uses it as Authentication for the rest of the calls | train | https://github.com/jasonrollins/shareplum/blob/404f320808912619920e2d787f2c4387225a14e0/shareplum/shareplum.py#L70-L78 | [
"def GetSecurityToken(self, username, password):\n \"\"\"\n Grabs a security Token to authenticate to Office 365 services\n \"\"\"\n url = 'https://login.microsoftonline.com/extSTS.srf'\n body = \"\"\"\n <s:Envelope xmlns:s=\"http://www.w3.org/2003/05/soap-envelope\"\n xmlns:a=\"http://www.w3.org/2005/08/addressing\"\n xmlns:u=\"http://docs.oasis-open.org/wss/2004/01/oasis-200401-wss-wssecurity-utility-1.0.xsd\">\n <s:Header>\n <a:Action s:mustUnderstand=\"1\">http://schemas.xmlsoap.org/ws/2005/02/trust/RST/Issue</a:Action>\n <a:ReplyTo>\n <a:Address>http://www.w3.org/2005/08/addressing/anonymous</a:Address>\n </a:ReplyTo>\n <a:To s:mustUnderstand=\"1\">https://login.microsoftonline.com/extSTS.srf</a:To>\n <o:Security s:mustUnderstand=\"1\"\n xmlns:o=\"http://docs.oasis-open.org/wss/2004/01/oasis-200401-wss-wssecurity-secext-1.0.xsd\">\n <o:UsernameToken>\n <o:Username>%s</o:Username>\n <o:Password>%s</o:Password>\n </o:UsernameToken>\n </o:Security>\n </s:Header>\n <s:Body>\n <t:RequestSecurityToken xmlns:t=\"http://schemas.xmlsoap.org/ws/2005/02/trust\">\n <wsp:AppliesTo xmlns:wsp=\"http://schemas.xmlsoap.org/ws/2004/09/policy\">\n <a:EndpointReference>\n <a:Address>%s</a:Address>\n </a:EndpointReference>\n </wsp:AppliesTo>\n <t:KeyType>http://schemas.xmlsoap.org/ws/2005/05/identity/NoProofKey</t:KeyType>\n <t:RequestType>http://schemas.xmlsoap.org/ws/2005/02/trust/Issue</t:RequestType>\n <t:TokenType>urn:oasis:names:tc:SAML:1.0:assertion</t:TokenType>\n </t:RequestSecurityToken>\n </s:Body>\n </s:Envelope>\"\"\" % (username, password, self.share_point_site)\n headers = {'accept': 'application/json;odata=verbose'}\n\n response = requests.post(url, body, headers=headers)\n\n xmldoc = etree.fromstring(response.content)\n\n token = xmldoc.find(\n './/{http://docs.oasis-open.org/wss/2004/01/oasis-200401-wss-wssecurity-secext-1.0.xsd}BinarySecurityToken'\n )\n if token is not None:\n return token.text\n else:\n raise Exception('Check username/password and rootsite')\n"
] | class Office365(object):
"""
Class to authenticate Office 365 Sharepoint
"""
def __init__(self, share_point_site, username, password):
self.Username = username
self.Password = password
self.share_point_site = share_point_site
def GetSecurityToken(self, username, password):
"""
Grabs a security Token to authenticate to Office 365 services
"""
url = 'https://login.microsoftonline.com/extSTS.srf'
body = """
<s:Envelope xmlns:s="http://www.w3.org/2003/05/soap-envelope"
xmlns:a="http://www.w3.org/2005/08/addressing"
xmlns:u="http://docs.oasis-open.org/wss/2004/01/oasis-200401-wss-wssecurity-utility-1.0.xsd">
<s:Header>
<a:Action s:mustUnderstand="1">http://schemas.xmlsoap.org/ws/2005/02/trust/RST/Issue</a:Action>
<a:ReplyTo>
<a:Address>http://www.w3.org/2005/08/addressing/anonymous</a:Address>
</a:ReplyTo>
<a:To s:mustUnderstand="1">https://login.microsoftonline.com/extSTS.srf</a:To>
<o:Security s:mustUnderstand="1"
xmlns:o="http://docs.oasis-open.org/wss/2004/01/oasis-200401-wss-wssecurity-secext-1.0.xsd">
<o:UsernameToken>
<o:Username>%s</o:Username>
<o:Password>%s</o:Password>
</o:UsernameToken>
</o:Security>
</s:Header>
<s:Body>
<t:RequestSecurityToken xmlns:t="http://schemas.xmlsoap.org/ws/2005/02/trust">
<wsp:AppliesTo xmlns:wsp="http://schemas.xmlsoap.org/ws/2004/09/policy">
<a:EndpointReference>
<a:Address>%s</a:Address>
</a:EndpointReference>
</wsp:AppliesTo>
<t:KeyType>http://schemas.xmlsoap.org/ws/2005/05/identity/NoProofKey</t:KeyType>
<t:RequestType>http://schemas.xmlsoap.org/ws/2005/02/trust/Issue</t:RequestType>
<t:TokenType>urn:oasis:names:tc:SAML:1.0:assertion</t:TokenType>
</t:RequestSecurityToken>
</s:Body>
</s:Envelope>""" % (username, password, self.share_point_site)
headers = {'accept': 'application/json;odata=verbose'}
response = requests.post(url, body, headers=headers)
xmldoc = etree.fromstring(response.content)
token = xmldoc.find(
'.//{http://docs.oasis-open.org/wss/2004/01/oasis-200401-wss-wssecurity-secext-1.0.xsd}BinarySecurityToken'
)
if token is not None:
return token.text
else:
raise Exception('Check username/password and rootsite')
|
jasonrollins/shareplum | shareplum/shareplum.py | Site.AddList | python | def AddList(self, listName, description, templateID):
templateIDs = {'Announcements': '104',
'Contacts': '105',
'Custom List': '100',
'Custom List in Datasheet View': '120',
'DataSources': '110',
'Discussion Board': '108',
'Document Library': '101',
'Events': '106',
'Form Library': '115',
'Issues': '1100',
'Links': '103',
'Picture Library': '109',
'Survey': '102',
'Tasks': '107'}
IDnums = [100, 101, 102, 103, 104, 105, 106,
107, 108, 109, 110, 115, 120, 1100]
# Let's automatically convert the different
# ways we can select the templateID
if type(templateID) == int:
templateID = str(templateID)
elif type(templateID) == str:
if templateID.isdigit():
pass
else:
templateID = templateIDs[templateID]
# Build Request
soap_request = soap('AddList')
soap_request.add_parameter('listName', listName)
soap_request.add_parameter('description', description)
soap_request.add_parameter('templateID', templateID)
self.last_request = str(soap_request)
# Send Request
response = self._session.post(url=self._url('Lists'),
headers=self._headers('AddList'),
data=str(soap_request),
verify=self._verify_ssl,
timeout=self.timeout)
# Parse Request
print(response)
if response == 200:
return response.text
else:
return response | Create a new List
Provide: List Name, List Description, and List Template
Templates Include:
Announcements
Contacts
Custom List
Custom List in Datasheet View
DataSources
Discussion Board
Document Library
Events
Form Library
Issues
Links
Picture Library
Survey
Tasks | train | https://github.com/jasonrollins/shareplum/blob/404f320808912619920e2d787f2c4387225a14e0/shareplum/shareplum.py#L140-L205 | [
"def _url(self, service):\n \"\"\"Full SharePoint Service URL\"\"\"\n return ''.join([self.site_url, self._services_url[service]])\n",
"def _headers(self, soapaction):\n headers = {\"Content-Type\": \"text/xml; charset=UTF-8\",\n \"SOAPAction\": \"http://schemas.microsoft.com/sharepoint/soap/\" + soapaction}\n return headers\n",
"def add_parameter(self, parameter, value=None):\n sub = etree.SubElement(self.command, '{http://schemas.microsoft.com/sharepoint/soap/}' + parameter)\n if value:\n sub.text = value\n"
] | class Site(object):
"""Connect to SharePoint Site
"""
def __init__(self, site_url, auth=None,authcookie=None, verify_ssl=True, ssl_version=None, huge_tree=False, timeout=None):
self.site_url = site_url
self._verify_ssl = verify_ssl
self._session = requests.Session()
if ssl_version is not None:
self._session.mount('https://', SSLAdapter(ssl_version))
self._session.headers.update({'user-agent':
'shareplum/%s' % __version__})
if authcookie is not None:
self._session.cookies = authcookie
else:
self._session.auth = auth
self.huge_tree = huge_tree
self.timeout = timeout
self.last_request = None
self._services_url = {'Alerts': '/_vti_bin/Alerts.asmx',
'Authentication': '/_vti_bin/Authentication.asmx',
'Copy': '/_vti_bin/Copy.asmx',
'Dws': '/_vti_bin/Dws.asmx',
'Forms': '/_vti_bin/Forms.asmx',
'Imaging': '/_vti_bin/Imaging.asmx',
'DspSts': '/_vti_bin/DspSts.asmx',
'Lists': '/_vti_bin/lists.asmx',
'Meetings': '/_vti_bin/Meetings.asmx',
'People': '/_vti_bin/People.asmx',
'Permissions': '/_vti_bin/Permissions.asmx',
'SiteData': '/_vti_bin/SiteData.asmx',
'Sites': '/_vti_bin/Sites.asmx',
'Search': '/_vti_bin/Search.asmx',
'UserGroup': '/_vti_bin/usergroup.asmx',
'Versions': '/_vti_bin/Versions.asmx',
'Views': '/_vti_bin/Views.asmx',
'WebPartPages': '/_vti_bin/WebPartPages.asmx',
'Webs': '/_vti_bin/Webs.asmx'
}
self.users = self.GetUsers()
def _url(self, service):
"""Full SharePoint Service URL"""
return ''.join([self.site_url, self._services_url[service]])
def _headers(self, soapaction):
headers = {"Content-Type": "text/xml; charset=UTF-8",
"SOAPAction": "http://schemas.microsoft.com/sharepoint/soap/" + soapaction}
return headers
# This is part of List but seems awkward under the List Method
def DeleteList(self, listName):
"""Delete a List with given name"""
# Build Request
soap_request = soap('DeleteList')
soap_request.add_parameter('listName', listName)
self.last_request = str(soap_request)
# Send Request
response = self._session.post(url=self._url('Lists'),
headers=self._headers('DeleteList'),
data=str(soap_request),
verify=self._verify_ssl,
timeout=self.timeout)
# Parse Request
if response == 200:
return response.text
else:
return response
def GetListCollection(self):
"""Returns List information for current Site"""
# Build Request
soap_request = soap('GetListCollection')
self.last_request = str(soap_request)
# Send Request
response = self._session.post(url=self._url('SiteData'),
headers=self._headers('GetListCollection'),
data=str(soap_request),
verify=self._verify_ssl,
timeout=self.timeout)
# Parse Response
if response.status_code == 200:
envelope = etree.fromstring(response.text.encode('utf-8'), parser=etree.XMLParser(huge_tree=self.huge_tree))
result = envelope[0][0][0].text
lists = envelope[0][0][1]
data = []
for _list in lists:
_list_data = {}
for item in _list:
key = item.tag.replace('{http://schemas.microsoft.com/sharepoint/soap/}', '')
value = item.text
_list_data[key] = value
data.append(_list_data)
return data
else:
return response
def GetUsers(self, rowlimit=0):
"""Get Items from current list
rowlimit defaulted to 0 (no limit)
"""
# Build Request
soap_request = soap('GetListItems')
soap_request.add_parameter('listName', 'UserInfo')
# Set Row Limit
soap_request.add_parameter('rowLimit', str(rowlimit))
self.last_request = str(soap_request)
# Send Request
response = self._session.post(url=self._url('Lists'),
headers=self._headers('GetListItems'),
data=str(soap_request),
verify=self._verify_ssl,
timeout=self.timeout)
# Parse Response
if response.status_code != 200:
raise ConnectionError('GetUsers GetListItems request failed')
try:
envelope = etree.fromstring(response.text.encode('utf-8'), parser=etree.XMLParser(huge_tree=self.huge_tree))
except:
raise ConnectionError("GetUsers GetListItems response failed to parse correctly")
listitems = envelope[0][0][0][0][0]
data = []
for row in listitems:
# Strip the 'ows_' from the beginning with key[4:]
data.append({key[4:]: value for (key, value) in row.items() if key[4:]})
return {'py': {i['ImnName']: i['ID'] + ';#' + i['ImnName'] for i in data},
'sp': {i['ID'] + ';#' + i['ImnName']: i['ImnName'] for i in data}}
# SharePoint Method Objects
def List(self, listName, exclude_hidden_fields=False):
"""Sharepoint Lists Web Service
Microsoft Developer Network:
The Lists Web service provides methods for working
with SharePoint lists, content types, list items, and files.
"""
return _List(self._session, listName, self._url, self._verify_ssl, self.users, self.huge_tree, self.timeout, exclude_hidden_fields=exclude_hidden_fields)
|
jasonrollins/shareplum | shareplum/shareplum.py | Site.DeleteList | python | def DeleteList(self, listName):
# Build Request
soap_request = soap('DeleteList')
soap_request.add_parameter('listName', listName)
self.last_request = str(soap_request)
# Send Request
response = self._session.post(url=self._url('Lists'),
headers=self._headers('DeleteList'),
data=str(soap_request),
verify=self._verify_ssl,
timeout=self.timeout)
# Parse Request
if response == 200:
return response.text
else:
return response | Delete a List with given name | train | https://github.com/jasonrollins/shareplum/blob/404f320808912619920e2d787f2c4387225a14e0/shareplum/shareplum.py#L207-L226 | [
"def _url(self, service):\n \"\"\"Full SharePoint Service URL\"\"\"\n return ''.join([self.site_url, self._services_url[service]])\n",
"def _headers(self, soapaction):\n headers = {\"Content-Type\": \"text/xml; charset=UTF-8\",\n \"SOAPAction\": \"http://schemas.microsoft.com/sharepoint/soap/\" + soapaction}\n return headers\n",
"def add_parameter(self, parameter, value=None):\n sub = etree.SubElement(self.command, '{http://schemas.microsoft.com/sharepoint/soap/}' + parameter)\n if value:\n sub.text = value\n"
] | class Site(object):
"""Connect to SharePoint Site
"""
def __init__(self, site_url, auth=None,authcookie=None, verify_ssl=True, ssl_version=None, huge_tree=False, timeout=None):
self.site_url = site_url
self._verify_ssl = verify_ssl
self._session = requests.Session()
if ssl_version is not None:
self._session.mount('https://', SSLAdapter(ssl_version))
self._session.headers.update({'user-agent':
'shareplum/%s' % __version__})
if authcookie is not None:
self._session.cookies = authcookie
else:
self._session.auth = auth
self.huge_tree = huge_tree
self.timeout = timeout
self.last_request = None
self._services_url = {'Alerts': '/_vti_bin/Alerts.asmx',
'Authentication': '/_vti_bin/Authentication.asmx',
'Copy': '/_vti_bin/Copy.asmx',
'Dws': '/_vti_bin/Dws.asmx',
'Forms': '/_vti_bin/Forms.asmx',
'Imaging': '/_vti_bin/Imaging.asmx',
'DspSts': '/_vti_bin/DspSts.asmx',
'Lists': '/_vti_bin/lists.asmx',
'Meetings': '/_vti_bin/Meetings.asmx',
'People': '/_vti_bin/People.asmx',
'Permissions': '/_vti_bin/Permissions.asmx',
'SiteData': '/_vti_bin/SiteData.asmx',
'Sites': '/_vti_bin/Sites.asmx',
'Search': '/_vti_bin/Search.asmx',
'UserGroup': '/_vti_bin/usergroup.asmx',
'Versions': '/_vti_bin/Versions.asmx',
'Views': '/_vti_bin/Views.asmx',
'WebPartPages': '/_vti_bin/WebPartPages.asmx',
'Webs': '/_vti_bin/Webs.asmx'
}
self.users = self.GetUsers()
def _url(self, service):
"""Full SharePoint Service URL"""
return ''.join([self.site_url, self._services_url[service]])
def _headers(self, soapaction):
headers = {"Content-Type": "text/xml; charset=UTF-8",
"SOAPAction": "http://schemas.microsoft.com/sharepoint/soap/" + soapaction}
return headers
# This is part of List but seems awkward under the List Method
def AddList(self, listName, description, templateID):
"""Create a new List
Provide: List Name, List Description, and List Template
Templates Include:
Announcements
Contacts
Custom List
Custom List in Datasheet View
DataSources
Discussion Board
Document Library
Events
Form Library
Issues
Links
Picture Library
Survey
Tasks
"""
templateIDs = {'Announcements': '104',
'Contacts': '105',
'Custom List': '100',
'Custom List in Datasheet View': '120',
'DataSources': '110',
'Discussion Board': '108',
'Document Library': '101',
'Events': '106',
'Form Library': '115',
'Issues': '1100',
'Links': '103',
'Picture Library': '109',
'Survey': '102',
'Tasks': '107'}
IDnums = [100, 101, 102, 103, 104, 105, 106,
107, 108, 109, 110, 115, 120, 1100]
# Let's automatically convert the different
# ways we can select the templateID
if type(templateID) == int:
templateID = str(templateID)
elif type(templateID) == str:
if templateID.isdigit():
pass
else:
templateID = templateIDs[templateID]
# Build Request
soap_request = soap('AddList')
soap_request.add_parameter('listName', listName)
soap_request.add_parameter('description', description)
soap_request.add_parameter('templateID', templateID)
self.last_request = str(soap_request)
# Send Request
response = self._session.post(url=self._url('Lists'),
headers=self._headers('AddList'),
data=str(soap_request),
verify=self._verify_ssl,
timeout=self.timeout)
# Parse Request
print(response)
if response == 200:
return response.text
else:
return response
def GetListCollection(self):
"""Returns List information for current Site"""
# Build Request
soap_request = soap('GetListCollection')
self.last_request = str(soap_request)
# Send Request
response = self._session.post(url=self._url('SiteData'),
headers=self._headers('GetListCollection'),
data=str(soap_request),
verify=self._verify_ssl,
timeout=self.timeout)
# Parse Response
if response.status_code == 200:
envelope = etree.fromstring(response.text.encode('utf-8'), parser=etree.XMLParser(huge_tree=self.huge_tree))
result = envelope[0][0][0].text
lists = envelope[0][0][1]
data = []
for _list in lists:
_list_data = {}
for item in _list:
key = item.tag.replace('{http://schemas.microsoft.com/sharepoint/soap/}', '')
value = item.text
_list_data[key] = value
data.append(_list_data)
return data
else:
return response
def GetUsers(self, rowlimit=0):
"""Get Items from current list
rowlimit defaulted to 0 (no limit)
"""
# Build Request
soap_request = soap('GetListItems')
soap_request.add_parameter('listName', 'UserInfo')
# Set Row Limit
soap_request.add_parameter('rowLimit', str(rowlimit))
self.last_request = str(soap_request)
# Send Request
response = self._session.post(url=self._url('Lists'),
headers=self._headers('GetListItems'),
data=str(soap_request),
verify=self._verify_ssl,
timeout=self.timeout)
# Parse Response
if response.status_code != 200:
raise ConnectionError('GetUsers GetListItems request failed')
try:
envelope = etree.fromstring(response.text.encode('utf-8'), parser=etree.XMLParser(huge_tree=self.huge_tree))
except:
raise ConnectionError("GetUsers GetListItems response failed to parse correctly")
listitems = envelope[0][0][0][0][0]
data = []
for row in listitems:
# Strip the 'ows_' from the beginning with key[4:]
data.append({key[4:]: value for (key, value) in row.items() if key[4:]})
return {'py': {i['ImnName']: i['ID'] + ';#' + i['ImnName'] for i in data},
'sp': {i['ID'] + ';#' + i['ImnName']: i['ImnName'] for i in data}}
# SharePoint Method Objects
def List(self, listName, exclude_hidden_fields=False):
"""Sharepoint Lists Web Service
Microsoft Developer Network:
The Lists Web service provides methods for working
with SharePoint lists, content types, list items, and files.
"""
return _List(self._session, listName, self._url, self._verify_ssl, self.users, self.huge_tree, self.timeout, exclude_hidden_fields=exclude_hidden_fields)
|
jasonrollins/shareplum | shareplum/shareplum.py | Site.GetListCollection | python | def GetListCollection(self):
# Build Request
soap_request = soap('GetListCollection')
self.last_request = str(soap_request)
# Send Request
response = self._session.post(url=self._url('SiteData'),
headers=self._headers('GetListCollection'),
data=str(soap_request),
verify=self._verify_ssl,
timeout=self.timeout)
# Parse Response
if response.status_code == 200:
envelope = etree.fromstring(response.text.encode('utf-8'), parser=etree.XMLParser(huge_tree=self.huge_tree))
result = envelope[0][0][0].text
lists = envelope[0][0][1]
data = []
for _list in lists:
_list_data = {}
for item in _list:
key = item.tag.replace('{http://schemas.microsoft.com/sharepoint/soap/}', '')
value = item.text
_list_data[key] = value
data.append(_list_data)
return data
else:
return response | Returns List information for current Site | train | https://github.com/jasonrollins/shareplum/blob/404f320808912619920e2d787f2c4387225a14e0/shareplum/shareplum.py#L228-L257 | [
"def _url(self, service):\n \"\"\"Full SharePoint Service URL\"\"\"\n return ''.join([self.site_url, self._services_url[service]])\n",
"def _headers(self, soapaction):\n headers = {\"Content-Type\": \"text/xml; charset=UTF-8\",\n \"SOAPAction\": \"http://schemas.microsoft.com/sharepoint/soap/\" + soapaction}\n return headers\n"
] | class Site(object):
"""Connect to SharePoint Site
"""
def __init__(self, site_url, auth=None,authcookie=None, verify_ssl=True, ssl_version=None, huge_tree=False, timeout=None):
self.site_url = site_url
self._verify_ssl = verify_ssl
self._session = requests.Session()
if ssl_version is not None:
self._session.mount('https://', SSLAdapter(ssl_version))
self._session.headers.update({'user-agent':
'shareplum/%s' % __version__})
if authcookie is not None:
self._session.cookies = authcookie
else:
self._session.auth = auth
self.huge_tree = huge_tree
self.timeout = timeout
self.last_request = None
self._services_url = {'Alerts': '/_vti_bin/Alerts.asmx',
'Authentication': '/_vti_bin/Authentication.asmx',
'Copy': '/_vti_bin/Copy.asmx',
'Dws': '/_vti_bin/Dws.asmx',
'Forms': '/_vti_bin/Forms.asmx',
'Imaging': '/_vti_bin/Imaging.asmx',
'DspSts': '/_vti_bin/DspSts.asmx',
'Lists': '/_vti_bin/lists.asmx',
'Meetings': '/_vti_bin/Meetings.asmx',
'People': '/_vti_bin/People.asmx',
'Permissions': '/_vti_bin/Permissions.asmx',
'SiteData': '/_vti_bin/SiteData.asmx',
'Sites': '/_vti_bin/Sites.asmx',
'Search': '/_vti_bin/Search.asmx',
'UserGroup': '/_vti_bin/usergroup.asmx',
'Versions': '/_vti_bin/Versions.asmx',
'Views': '/_vti_bin/Views.asmx',
'WebPartPages': '/_vti_bin/WebPartPages.asmx',
'Webs': '/_vti_bin/Webs.asmx'
}
self.users = self.GetUsers()
def _url(self, service):
"""Full SharePoint Service URL"""
return ''.join([self.site_url, self._services_url[service]])
def _headers(self, soapaction):
headers = {"Content-Type": "text/xml; charset=UTF-8",
"SOAPAction": "http://schemas.microsoft.com/sharepoint/soap/" + soapaction}
return headers
# This is part of List but seems awkward under the List Method
def AddList(self, listName, description, templateID):
"""Create a new List
Provide: List Name, List Description, and List Template
Templates Include:
Announcements
Contacts
Custom List
Custom List in Datasheet View
DataSources
Discussion Board
Document Library
Events
Form Library
Issues
Links
Picture Library
Survey
Tasks
"""
templateIDs = {'Announcements': '104',
'Contacts': '105',
'Custom List': '100',
'Custom List in Datasheet View': '120',
'DataSources': '110',
'Discussion Board': '108',
'Document Library': '101',
'Events': '106',
'Form Library': '115',
'Issues': '1100',
'Links': '103',
'Picture Library': '109',
'Survey': '102',
'Tasks': '107'}
IDnums = [100, 101, 102, 103, 104, 105, 106,
107, 108, 109, 110, 115, 120, 1100]
# Let's automatically convert the different
# ways we can select the templateID
if type(templateID) == int:
templateID = str(templateID)
elif type(templateID) == str:
if templateID.isdigit():
pass
else:
templateID = templateIDs[templateID]
# Build Request
soap_request = soap('AddList')
soap_request.add_parameter('listName', listName)
soap_request.add_parameter('description', description)
soap_request.add_parameter('templateID', templateID)
self.last_request = str(soap_request)
# Send Request
response = self._session.post(url=self._url('Lists'),
headers=self._headers('AddList'),
data=str(soap_request),
verify=self._verify_ssl,
timeout=self.timeout)
# Parse Request
print(response)
if response == 200:
return response.text
else:
return response
def DeleteList(self, listName):
"""Delete a List with given name"""
# Build Request
soap_request = soap('DeleteList')
soap_request.add_parameter('listName', listName)
self.last_request = str(soap_request)
# Send Request
response = self._session.post(url=self._url('Lists'),
headers=self._headers('DeleteList'),
data=str(soap_request),
verify=self._verify_ssl,
timeout=self.timeout)
# Parse Request
if response == 200:
return response.text
else:
return response
def GetUsers(self, rowlimit=0):
"""Get Items from current list
rowlimit defaulted to 0 (no limit)
"""
# Build Request
soap_request = soap('GetListItems')
soap_request.add_parameter('listName', 'UserInfo')
# Set Row Limit
soap_request.add_parameter('rowLimit', str(rowlimit))
self.last_request = str(soap_request)
# Send Request
response = self._session.post(url=self._url('Lists'),
headers=self._headers('GetListItems'),
data=str(soap_request),
verify=self._verify_ssl,
timeout=self.timeout)
# Parse Response
if response.status_code != 200:
raise ConnectionError('GetUsers GetListItems request failed')
try:
envelope = etree.fromstring(response.text.encode('utf-8'), parser=etree.XMLParser(huge_tree=self.huge_tree))
except:
raise ConnectionError("GetUsers GetListItems response failed to parse correctly")
listitems = envelope[0][0][0][0][0]
data = []
for row in listitems:
# Strip the 'ows_' from the beginning with key[4:]
data.append({key[4:]: value for (key, value) in row.items() if key[4:]})
return {'py': {i['ImnName']: i['ID'] + ';#' + i['ImnName'] for i in data},
'sp': {i['ID'] + ';#' + i['ImnName']: i['ImnName'] for i in data}}
# SharePoint Method Objects
def List(self, listName, exclude_hidden_fields=False):
"""Sharepoint Lists Web Service
Microsoft Developer Network:
The Lists Web service provides methods for working
with SharePoint lists, content types, list items, and files.
"""
return _List(self._session, listName, self._url, self._verify_ssl, self.users, self.huge_tree, self.timeout, exclude_hidden_fields=exclude_hidden_fields)
|
jasonrollins/shareplum | shareplum/shareplum.py | Site.GetUsers | python | def GetUsers(self, rowlimit=0):
# Build Request
soap_request = soap('GetListItems')
soap_request.add_parameter('listName', 'UserInfo')
# Set Row Limit
soap_request.add_parameter('rowLimit', str(rowlimit))
self.last_request = str(soap_request)
# Send Request
response = self._session.post(url=self._url('Lists'),
headers=self._headers('GetListItems'),
data=str(soap_request),
verify=self._verify_ssl,
timeout=self.timeout)
# Parse Response
if response.status_code != 200:
raise ConnectionError('GetUsers GetListItems request failed')
try:
envelope = etree.fromstring(response.text.encode('utf-8'), parser=etree.XMLParser(huge_tree=self.huge_tree))
except:
raise ConnectionError("GetUsers GetListItems response failed to parse correctly")
listitems = envelope[0][0][0][0][0]
data = []
for row in listitems:
# Strip the 'ows_' from the beginning with key[4:]
data.append({key[4:]: value for (key, value) in row.items() if key[4:]})
return {'py': {i['ImnName']: i['ID'] + ';#' + i['ImnName'] for i in data},
'sp': {i['ID'] + ';#' + i['ImnName']: i['ImnName'] for i in data}} | Get Items from current list
rowlimit defaulted to 0 (no limit) | train | https://github.com/jasonrollins/shareplum/blob/404f320808912619920e2d787f2c4387225a14e0/shareplum/shareplum.py#L259-L293 | [
"def _url(self, service):\n \"\"\"Full SharePoint Service URL\"\"\"\n return ''.join([self.site_url, self._services_url[service]])\n",
"def _headers(self, soapaction):\n headers = {\"Content-Type\": \"text/xml; charset=UTF-8\",\n \"SOAPAction\": \"http://schemas.microsoft.com/sharepoint/soap/\" + soapaction}\n return headers\n",
"def add_parameter(self, parameter, value=None):\n sub = etree.SubElement(self.command, '{http://schemas.microsoft.com/sharepoint/soap/}' + parameter)\n if value:\n sub.text = value\n"
] | class Site(object):
"""Connect to SharePoint Site
"""
def __init__(self, site_url, auth=None,authcookie=None, verify_ssl=True, ssl_version=None, huge_tree=False, timeout=None):
self.site_url = site_url
self._verify_ssl = verify_ssl
self._session = requests.Session()
if ssl_version is not None:
self._session.mount('https://', SSLAdapter(ssl_version))
self._session.headers.update({'user-agent':
'shareplum/%s' % __version__})
if authcookie is not None:
self._session.cookies = authcookie
else:
self._session.auth = auth
self.huge_tree = huge_tree
self.timeout = timeout
self.last_request = None
self._services_url = {'Alerts': '/_vti_bin/Alerts.asmx',
'Authentication': '/_vti_bin/Authentication.asmx',
'Copy': '/_vti_bin/Copy.asmx',
'Dws': '/_vti_bin/Dws.asmx',
'Forms': '/_vti_bin/Forms.asmx',
'Imaging': '/_vti_bin/Imaging.asmx',
'DspSts': '/_vti_bin/DspSts.asmx',
'Lists': '/_vti_bin/lists.asmx',
'Meetings': '/_vti_bin/Meetings.asmx',
'People': '/_vti_bin/People.asmx',
'Permissions': '/_vti_bin/Permissions.asmx',
'SiteData': '/_vti_bin/SiteData.asmx',
'Sites': '/_vti_bin/Sites.asmx',
'Search': '/_vti_bin/Search.asmx',
'UserGroup': '/_vti_bin/usergroup.asmx',
'Versions': '/_vti_bin/Versions.asmx',
'Views': '/_vti_bin/Views.asmx',
'WebPartPages': '/_vti_bin/WebPartPages.asmx',
'Webs': '/_vti_bin/Webs.asmx'
}
self.users = self.GetUsers()
def _url(self, service):
"""Full SharePoint Service URL"""
return ''.join([self.site_url, self._services_url[service]])
def _headers(self, soapaction):
headers = {"Content-Type": "text/xml; charset=UTF-8",
"SOAPAction": "http://schemas.microsoft.com/sharepoint/soap/" + soapaction}
return headers
# This is part of List but seems awkward under the List Method
def AddList(self, listName, description, templateID):
"""Create a new List
Provide: List Name, List Description, and List Template
Templates Include:
Announcements
Contacts
Custom List
Custom List in Datasheet View
DataSources
Discussion Board
Document Library
Events
Form Library
Issues
Links
Picture Library
Survey
Tasks
"""
templateIDs = {'Announcements': '104',
'Contacts': '105',
'Custom List': '100',
'Custom List in Datasheet View': '120',
'DataSources': '110',
'Discussion Board': '108',
'Document Library': '101',
'Events': '106',
'Form Library': '115',
'Issues': '1100',
'Links': '103',
'Picture Library': '109',
'Survey': '102',
'Tasks': '107'}
IDnums = [100, 101, 102, 103, 104, 105, 106,
107, 108, 109, 110, 115, 120, 1100]
# Let's automatically convert the different
# ways we can select the templateID
if type(templateID) == int:
templateID = str(templateID)
elif type(templateID) == str:
if templateID.isdigit():
pass
else:
templateID = templateIDs[templateID]
# Build Request
soap_request = soap('AddList')
soap_request.add_parameter('listName', listName)
soap_request.add_parameter('description', description)
soap_request.add_parameter('templateID', templateID)
self.last_request = str(soap_request)
# Send Request
response = self._session.post(url=self._url('Lists'),
headers=self._headers('AddList'),
data=str(soap_request),
verify=self._verify_ssl,
timeout=self.timeout)
# Parse Request
print(response)
if response == 200:
return response.text
else:
return response
def DeleteList(self, listName):
"""Delete a List with given name"""
# Build Request
soap_request = soap('DeleteList')
soap_request.add_parameter('listName', listName)
self.last_request = str(soap_request)
# Send Request
response = self._session.post(url=self._url('Lists'),
headers=self._headers('DeleteList'),
data=str(soap_request),
verify=self._verify_ssl,
timeout=self.timeout)
# Parse Request
if response == 200:
return response.text
else:
return response
def GetListCollection(self):
"""Returns List information for current Site"""
# Build Request
soap_request = soap('GetListCollection')
self.last_request = str(soap_request)
# Send Request
response = self._session.post(url=self._url('SiteData'),
headers=self._headers('GetListCollection'),
data=str(soap_request),
verify=self._verify_ssl,
timeout=self.timeout)
# Parse Response
if response.status_code == 200:
envelope = etree.fromstring(response.text.encode('utf-8'), parser=etree.XMLParser(huge_tree=self.huge_tree))
result = envelope[0][0][0].text
lists = envelope[0][0][1]
data = []
for _list in lists:
_list_data = {}
for item in _list:
key = item.tag.replace('{http://schemas.microsoft.com/sharepoint/soap/}', '')
value = item.text
_list_data[key] = value
data.append(_list_data)
return data
else:
return response
# SharePoint Method Objects
def List(self, listName, exclude_hidden_fields=False):
"""Sharepoint Lists Web Service
Microsoft Developer Network:
The Lists Web service provides methods for working
with SharePoint lists, content types, list items, and files.
"""
return _List(self._session, listName, self._url, self._verify_ssl, self.users, self.huge_tree, self.timeout, exclude_hidden_fields=exclude_hidden_fields)
|
jasonrollins/shareplum | shareplum/shareplum.py | Site.List | python | def List(self, listName, exclude_hidden_fields=False):
return _List(self._session, listName, self._url, self._verify_ssl, self.users, self.huge_tree, self.timeout, exclude_hidden_fields=exclude_hidden_fields) | Sharepoint Lists Web Service
Microsoft Developer Network:
The Lists Web service provides methods for working
with SharePoint lists, content types, list items, and files. | train | https://github.com/jasonrollins/shareplum/blob/404f320808912619920e2d787f2c4387225a14e0/shareplum/shareplum.py#L297-L303 | null | class Site(object):
"""Connect to SharePoint Site
"""
def __init__(self, site_url, auth=None,authcookie=None, verify_ssl=True, ssl_version=None, huge_tree=False, timeout=None):
self.site_url = site_url
self._verify_ssl = verify_ssl
self._session = requests.Session()
if ssl_version is not None:
self._session.mount('https://', SSLAdapter(ssl_version))
self._session.headers.update({'user-agent':
'shareplum/%s' % __version__})
if authcookie is not None:
self._session.cookies = authcookie
else:
self._session.auth = auth
self.huge_tree = huge_tree
self.timeout = timeout
self.last_request = None
self._services_url = {'Alerts': '/_vti_bin/Alerts.asmx',
'Authentication': '/_vti_bin/Authentication.asmx',
'Copy': '/_vti_bin/Copy.asmx',
'Dws': '/_vti_bin/Dws.asmx',
'Forms': '/_vti_bin/Forms.asmx',
'Imaging': '/_vti_bin/Imaging.asmx',
'DspSts': '/_vti_bin/DspSts.asmx',
'Lists': '/_vti_bin/lists.asmx',
'Meetings': '/_vti_bin/Meetings.asmx',
'People': '/_vti_bin/People.asmx',
'Permissions': '/_vti_bin/Permissions.asmx',
'SiteData': '/_vti_bin/SiteData.asmx',
'Sites': '/_vti_bin/Sites.asmx',
'Search': '/_vti_bin/Search.asmx',
'UserGroup': '/_vti_bin/usergroup.asmx',
'Versions': '/_vti_bin/Versions.asmx',
'Views': '/_vti_bin/Views.asmx',
'WebPartPages': '/_vti_bin/WebPartPages.asmx',
'Webs': '/_vti_bin/Webs.asmx'
}
self.users = self.GetUsers()
def _url(self, service):
"""Full SharePoint Service URL"""
return ''.join([self.site_url, self._services_url[service]])
def _headers(self, soapaction):
headers = {"Content-Type": "text/xml; charset=UTF-8",
"SOAPAction": "http://schemas.microsoft.com/sharepoint/soap/" + soapaction}
return headers
# This is part of List but seems awkward under the List Method
def AddList(self, listName, description, templateID):
"""Create a new List
Provide: List Name, List Description, and List Template
Templates Include:
Announcements
Contacts
Custom List
Custom List in Datasheet View
DataSources
Discussion Board
Document Library
Events
Form Library
Issues
Links
Picture Library
Survey
Tasks
"""
templateIDs = {'Announcements': '104',
'Contacts': '105',
'Custom List': '100',
'Custom List in Datasheet View': '120',
'DataSources': '110',
'Discussion Board': '108',
'Document Library': '101',
'Events': '106',
'Form Library': '115',
'Issues': '1100',
'Links': '103',
'Picture Library': '109',
'Survey': '102',
'Tasks': '107'}
IDnums = [100, 101, 102, 103, 104, 105, 106,
107, 108, 109, 110, 115, 120, 1100]
# Let's automatically convert the different
# ways we can select the templateID
if type(templateID) == int:
templateID = str(templateID)
elif type(templateID) == str:
if templateID.isdigit():
pass
else:
templateID = templateIDs[templateID]
# Build Request
soap_request = soap('AddList')
soap_request.add_parameter('listName', listName)
soap_request.add_parameter('description', description)
soap_request.add_parameter('templateID', templateID)
self.last_request = str(soap_request)
# Send Request
response = self._session.post(url=self._url('Lists'),
headers=self._headers('AddList'),
data=str(soap_request),
verify=self._verify_ssl,
timeout=self.timeout)
# Parse Request
print(response)
if response == 200:
return response.text
else:
return response
def DeleteList(self, listName):
"""Delete a List with given name"""
# Build Request
soap_request = soap('DeleteList')
soap_request.add_parameter('listName', listName)
self.last_request = str(soap_request)
# Send Request
response = self._session.post(url=self._url('Lists'),
headers=self._headers('DeleteList'),
data=str(soap_request),
verify=self._verify_ssl,
timeout=self.timeout)
# Parse Request
if response == 200:
return response.text
else:
return response
def GetListCollection(self):
"""Returns List information for current Site"""
# Build Request
soap_request = soap('GetListCollection')
self.last_request = str(soap_request)
# Send Request
response = self._session.post(url=self._url('SiteData'),
headers=self._headers('GetListCollection'),
data=str(soap_request),
verify=self._verify_ssl,
timeout=self.timeout)
# Parse Response
if response.status_code == 200:
envelope = etree.fromstring(response.text.encode('utf-8'), parser=etree.XMLParser(huge_tree=self.huge_tree))
result = envelope[0][0][0].text
lists = envelope[0][0][1]
data = []
for _list in lists:
_list_data = {}
for item in _list:
key = item.tag.replace('{http://schemas.microsoft.com/sharepoint/soap/}', '')
value = item.text
_list_data[key] = value
data.append(_list_data)
return data
else:
return response
def GetUsers(self, rowlimit=0):
"""Get Items from current list
rowlimit defaulted to 0 (no limit)
"""
# Build Request
soap_request = soap('GetListItems')
soap_request.add_parameter('listName', 'UserInfo')
# Set Row Limit
soap_request.add_parameter('rowLimit', str(rowlimit))
self.last_request = str(soap_request)
# Send Request
response = self._session.post(url=self._url('Lists'),
headers=self._headers('GetListItems'),
data=str(soap_request),
verify=self._verify_ssl,
timeout=self.timeout)
# Parse Response
if response.status_code != 200:
raise ConnectionError('GetUsers GetListItems request failed')
try:
envelope = etree.fromstring(response.text.encode('utf-8'), parser=etree.XMLParser(huge_tree=self.huge_tree))
except:
raise ConnectionError("GetUsers GetListItems response failed to parse correctly")
listitems = envelope[0][0][0][0][0]
data = []
for row in listitems:
# Strip the 'ows_' from the beginning with key[4:]
data.append({key[4:]: value for (key, value) in row.items() if key[4:]})
return {'py': {i['ImnName']: i['ID'] + ';#' + i['ImnName'] for i in data},
'sp': {i['ID'] + ';#' + i['ImnName']: i['ImnName'] for i in data}}
# SharePoint Method Objects
|
jasonrollins/shareplum | shareplum/shareplum.py | _List._convert_to_internal | python | def _convert_to_internal(self, data):
"""From 'Column Title' to 'Column_x0020_Title'"""
for _dict in data:
keys = list(_dict.keys())[:]
for key in keys:
if key not in self._disp_cols:
raise Exception(key + ' not a column in current List.')
_dict[self._disp_cols[key]['name']] = self._sp_type(key, _dict.pop(key)) | From 'Column Title' to 'Column_x0020_Title | train | https://github.com/jasonrollins/shareplum/blob/404f320808912619920e2d787f2c4387225a14e0/shareplum/shareplum.py#L358-L365 | [
"def _sp_type(self, key, value):\n \"\"\"Returns proper type from the schema\"\"\"\n try:\n field_type = self._disp_cols[key]['type']\n if field_type in ['Number', 'Currency']:\n return value\n elif field_type == 'DateTime':\n return value.strftime('%Y-%m-%d %H:%M:%S')\n elif field_type == 'Boolean':\n if value == 'Yes':\n return '1'\n elif value == 'No':\n return '0'\n else:\n raise Exception(\"%s not a valid Boolean Value, only 'Yes' or 'No'\" % value)\n elif field_type == 'User':\n return self.users['py'][value]\n else:\n return value\n except AttributeError:\n return value\n"
] | class _List(object):
"""Sharepoint Lists Web Service
Microsoft Developer Network:
The Lists Web service provides methods for working
with SharePoint lists, content types, list items, and files.
"""
def __init__(self, session, listName, url, verify_ssl, users, huge_tree, timeout, exclude_hidden_fields=False):
self._session = session
self.listName = listName
self._url = url
self._verify_ssl = verify_ssl
self.users = users
self.huge_tree = huge_tree
self.timeout = timeout
self._exclude_hidden_fields = exclude_hidden_fields
# List Info
self.fields = []
self.regional_settings = {}
self.server_settings = {}
self.GetList()
self.views = self.GetViewCollection()
# fields sometimes share the same displayname
# filtering fields to only contain visible fields, minimizes the chance of a one field hiding another
if exclude_hidden_fields:
self.fields = [field for field in self.fields if field.get("Hidden", "FALSE") == "FALSE"]
self._sp_cols = {i['Name']: {'name': i['DisplayName'], 'type': i['Type']} for i in self.fields}
self._disp_cols = {i['DisplayName']: {'name': i['Name'], 'type': i['Type']} for i in self.fields}
title_col = self._sp_cols['Title']['name']
title_type = self._sp_cols['Title']['type']
self._disp_cols[title_col] = {'name': 'Title', 'type': title_type}
# This is a shorter lists that removes the problems with duplicate names for "Title"
standard_source = 'http://schemas.microsoft.com/sharepoint/v3'
# self._sp_cols = {i['Name']: {'name': i['DisplayName'], 'type': i['Type']} for i in self.fields \
# if i['StaticName'] == 'Title' or i['SourceID'] != standard_source}
# self._disp_cols = {i['DisplayName']: {'name': i['Name'], 'type': i['Type']} for i in self.fields \
# if i['StaticName'] == 'Title' or i['SourceID'] != standard_source}
self.last_request = None
self.date_format = re.compile('\d+-\d+-\d+ \d+:\d+:\d+')
def _url(self, service):
"""Full SharePoint Service URL"""
return ''.join([self.site_url, self._services_url[service]])
def _headers(self, soapaction):
headers = {"Content-Type": "text/xml; charset=UTF-8",
"SOAPAction": "http://schemas.microsoft.com/sharepoint/soap/" + soapaction}
return headers
def _convert_to_display(self, data):
"""From 'Column_x0020_Title' to 'Column Title'"""
for _dict in data:
keys = list(_dict.keys())[:]
for key in keys:
if key not in self._sp_cols:
raise Exception(key + ' not a column in current List.')
_dict[self._sp_cols[key]['name']] = self._python_type(key, _dict.pop(key))
def _python_type(self, key, value):
"""Returns proper type from the schema"""
try:
field_type = self._sp_cols[key]['type']
if field_type in ['Number', 'Currency']:
return float(value)
elif field_type == 'DateTime':
# Need to remove the '123;#' from created dates, but we will do it for all dates
# self.date_format = re.compile('\d+-\d+-\d+ \d+:\d+:\d+')
value = self.date_format.search(value).group(0)
# NOTE: I used to round this just date (7/28/2018)
return datetime.strptime(value, '%Y-%m-%d %H:%M:%S')
elif field_type == 'Boolean':
if value == '1':
return 'Yes'
elif value == '0':
return 'No'
else:
return ''
elif field_type in ('User', 'UserMulti'):
# Sometimes the User no longer exists or
# has a diffrent ID number so we just remove the "123;#"
# from the beginning of their name
if value in self.users['sp']:
return self.users['sp'][value]
elif '#' in value:
return value.split('#')[1]
else:
return value
else:
return value
except AttributeError:
return value
def _sp_type(self, key, value):
"""Returns proper type from the schema"""
try:
field_type = self._disp_cols[key]['type']
if field_type in ['Number', 'Currency']:
return value
elif field_type == 'DateTime':
return value.strftime('%Y-%m-%d %H:%M:%S')
elif field_type == 'Boolean':
if value == 'Yes':
return '1'
elif value == 'No':
return '0'
else:
raise Exception("%s not a valid Boolean Value, only 'Yes' or 'No'" % value)
elif field_type == 'User':
return self.users['py'][value]
else:
return value
except AttributeError:
return value
def GetListItems(self, viewname=None, fields=None, query=None, rowlimit=0, debug=False):
"""Get Items from current list
rowlimit defaulted to 0 (unlimited)
"""
# Build Request
soap_request = soap('GetListItems')
soap_request.add_parameter('listName', self.listName)
# Convert Displayed View Name to View ID
if viewname:
soap_request.add_parameter('viewName', self.views[viewname]['Name'][1:-1])
# Add viewFields
if fields:
# Convert to SharePoint Style Column Names
for i, val in enumerate(fields):
fields[i] = self._disp_cols[val]['name']
viewfields = fields
soap_request.add_view_fields(fields)
# Check for viewname and query
if [viewname, query] == [None, None]:
# Add a query if the viewname and query are not provided
# We sort by 'ID' here Ascending is the default
soap_request.add_query({'OrderBy': ['ID']})
elif viewname:
viewfields = self.GetView(viewname)['fields'] ## Might be wrong
else:
# No fields or views provided so get everything
viewfields = [x for x in self._sp_cols]
# Add query
if query:
if 'Where' in query:
where = etree.Element('Where')
parents = []
parents.append(where)
for i, field in enumerate(query['Where']):
if field == 'And':
parents.append(etree.SubElement(parents[-1], 'And'))
elif field == 'Or':
if parents[-1].tag == 'Or':
parents.pop()
parents.append(etree.SubElement(parents[-1], 'Or'))
else:
_type = etree.SubElement(parents[-1], field[0])
field_ref = etree.SubElement(_type, 'FieldRef')
field_ref.set('Name', self._disp_cols[field[1]]['name'])
if len(field) == 3:
value = etree.SubElement(_type, 'Value')
value.set('Type', self._disp_cols[field[1]]['type'])
value.text = self._sp_type(field[1], field[2])
query['Where'] = where
soap_request.add_query(query)
# Set Row Limit
soap_request.add_parameter('rowLimit', str(rowlimit))
self.last_request = str(soap_request)
# Send Request
response = self._session.post(url=self._url('Lists'),
headers=self._headers('GetListItems'),
data=str(soap_request),
verify=self._verify_ssl,
timeout=self.timeout)
# Parse Response
if response.status_code == 200:
envelope = etree.fromstring(response.text.encode('utf-8'), parser=etree.XMLParser(huge_tree=self.huge_tree))
listitems = envelope[0][0][0][0][0]
data = []
for row in listitems:
# Strip the 'ows_' from the beginning with key[4:]
data.append({key[4:]: value for (key, value) in row.items() if key[4:] in viewfields})
self._convert_to_display(data)
if debug:
return response
else:
return data
else:
return response
def GetList(self):
"""Get Info on Current List
This is run in __init__ so you don't
have to run it again.
Access from self.schema
"""
# Build Request
soap_request = soap('GetList')
soap_request.add_parameter('listName', self.listName)
self.last_request = str(soap_request)
# Send Request
response = self._session.post(url=self._url('Lists'),
headers=self._headers('GetList'),
data=str(soap_request),
verify=self._verify_ssl,
timeout=self.timeout)
# Parse Response
if response.status_code == 200:
envelope = etree.fromstring(response.text.encode('utf-8'), parser=etree.XMLParser(huge_tree=self.huge_tree))
_list = envelope[0][0][0][0]
info = {key: value for (key, value) in _list.items()}
for row in _list[0].getchildren():
self.fields.append({key: value for (key, value) in row.items()})
for setting in _list[1].getchildren():
self.regional_settings[
setting.tag.strip('{http://schemas.microsoft.com/sharepoint/soap/}')] = setting.text
for setting in _list[2].getchildren():
self.server_settings[
setting.tag.strip('{http://schemas.microsoft.com/sharepoint/soap/}')] = setting.text
fields = envelope[0][0][0][0][0]
else:
raise Exception("ERROR:", response.status_code, response.text)
def GetView(self, viewname):
"""Get Info on View Name
"""
# Build Request
soap_request = soap('GetView')
soap_request.add_parameter('listName', self.listName)
if viewname == None:
views = self.GetViewCollection()
for view in views:
if 'DefaultView' in view:
if views[view]['DefaultView'] == 'TRUE':
viewname = view
break
if self.listName not in ['UserInfo', 'User Information List']:
soap_request.add_parameter('viewName', self.views[viewname]['Name'][1:-1])
else:
soap_request.add_parameter('viewName', viewname)
self.last_request = str(soap_request)
# Send Request
response = self._session.post(url=self._url('Views'),
headers=self._headers('GetView'),
data=str(soap_request),
verify=self._verify_ssl,
timeout=self.timeout)
# Parse Response
if response.status_code == 200:
envelope = etree.fromstring(response.text.encode('utf-8'), parser=etree.XMLParser(huge_tree=self.huge_tree))
view = envelope[0][0][0][0]
info = {key: value for (key, value) in view.items()}
fields = [x.items()[0][1] for x in view[1]]
return {'info': info, 'fields': fields}
else:
raise Exception("ERROR:", response.status_code, response.text)
def GetViewCollection(self):
"""Get Views for Current List
This is run in __init__ so you don't
have to run it again.
Access from self.views
"""
# Build Request
soap_request = soap('GetViewCollection')
soap_request.add_parameter('listName', self.listName)
self.last_request = str(soap_request)
# Send Request
response = self._session.post(url=self._url('Views'),
headers=self._headers('GetViewCollection'),
data=str(soap_request),
verify=self._verify_ssl,
timeout=self.timeout)
# Parse Response
if response.status_code == 200:
envelope = etree.fromstring(response.text.encode('utf-8'), parser=etree.XMLParser(huge_tree=self.huge_tree))
views = envelope[0][0][0][0]
data = []
for row in views.getchildren():
data.append({key: value for (key, value) in row.items()})
view = {}
for row in data:
view[row['DisplayName']] = row
return view
else:
return ("ERROR", response.status_code)
def UpdateList(self, listName, data, listVersion):
### Todo: Complete this one
# Build Request
soap_request = soap('UpdateList')
soap_request.add_parameter('listName', listName)
soap_request.add_parameter('newFields', description)
soap_request.add_parameter('newFields', description)
soap_request.add_parameter('updateFields', templateID)
soap_request.add_parameter('deleteFields', templateID)
soap_request.add_parameter('listVersion', templateID)
self.last_request = str(soap_request)
# Send Request
response = self._session.post(url=self._url('Lists'),
headers=self._headers('AddList'),
data=str(soap_request),
verify=self._verify_ssl,
timeout=self.timeout)
pass
def UpdateListItems(self, data, kind):
"""Update List Items
kind = 'New', 'Update', or 'Delete'
New:
Provide data like so:
data = [{'Title': 'New Title', 'Col1': 'New Value'}]
Update:
Provide data like so:
data = [{'ID': 23, 'Title': 'Updated Title'},
{'ID': 28, 'Col1': 'Updated Value'}]
Delete:
Just provied a list of ID's
data = [23, 28]
"""
if type(data) != list:
raise Exception('data must be a list of dictionaries')
# Build Request
soap_request = soap('UpdateListItems')
soap_request.add_parameter('listName', self.listName)
if kind != 'Delete':
self._convert_to_internal(data)
soap_request.add_actions(data, kind)
self.last_request = str(soap_request)
# Send Request
response = self._session.post(url=self._url('Lists'),
headers=self._headers('UpdateListItems'),
data=str(soap_request),
verify=self._verify_ssl,
timeout=self.timeout)
# Parse Response
if response.status_code == 200:
envelope = etree.fromstring(response.text.encode('utf-8'), parser=etree.XMLParser(huge_tree=self.huge_tree))
results = envelope[0][0][0][0]
data = {}
for result in results:
if result.text != '0x00000000' and result[0].text != '0x00000000':
data[result.attrib['ID']] = (result[0].text, result[1].text)
else:
data[result.attrib['ID']] = result[0].text
return data
else:
return response
def GetAttachmentCollection(self, _id):
"""Get Attachments for given List Item ID"""
# Build Request
soap_request = soap('GetAttachmentCollection')
soap_request.add_parameter('listName', self.listName)
soap_request.add_parameter('listItemID', _id)
self.last_request = str(soap_request)
# Send Request
response = self._session.post(url=self._url('Lists'),
headers=self._headers('GetAttachmentCollection'),
data=str(soap_request),
verify=False,
timeout=self.timeout)
# Parse Request
if response.status_code == 200:
envelope = etree.fromstring(response.text.encode('utf-8'), parser=etree.XMLParser(huge_tree=self.huge_tree))
attaches = envelope[0][0][0][0]
attachments = []
for attachment in attaches.getchildren():
attachments.append(attachment.text)
return attachments
else:
return response
|
jasonrollins/shareplum | shareplum/shareplum.py | _List._convert_to_display | python | def _convert_to_display(self, data):
"""From 'Column_x0020_Title' to 'Column Title'"""
for _dict in data:
keys = list(_dict.keys())[:]
for key in keys:
if key not in self._sp_cols:
raise Exception(key + ' not a column in current List.')
_dict[self._sp_cols[key]['name']] = self._python_type(key, _dict.pop(key)) | From 'Column_x0020_Title' to 'Column Title | train | https://github.com/jasonrollins/shareplum/blob/404f320808912619920e2d787f2c4387225a14e0/shareplum/shareplum.py#L367-L374 | null | class _List(object):
"""Sharepoint Lists Web Service
Microsoft Developer Network:
The Lists Web service provides methods for working
with SharePoint lists, content types, list items, and files.
"""
def __init__(self, session, listName, url, verify_ssl, users, huge_tree, timeout, exclude_hidden_fields=False):
self._session = session
self.listName = listName
self._url = url
self._verify_ssl = verify_ssl
self.users = users
self.huge_tree = huge_tree
self.timeout = timeout
self._exclude_hidden_fields = exclude_hidden_fields
# List Info
self.fields = []
self.regional_settings = {}
self.server_settings = {}
self.GetList()
self.views = self.GetViewCollection()
# fields sometimes share the same displayname
# filtering fields to only contain visible fields, minimizes the chance of a one field hiding another
if exclude_hidden_fields:
self.fields = [field for field in self.fields if field.get("Hidden", "FALSE") == "FALSE"]
self._sp_cols = {i['Name']: {'name': i['DisplayName'], 'type': i['Type']} for i in self.fields}
self._disp_cols = {i['DisplayName']: {'name': i['Name'], 'type': i['Type']} for i in self.fields}
title_col = self._sp_cols['Title']['name']
title_type = self._sp_cols['Title']['type']
self._disp_cols[title_col] = {'name': 'Title', 'type': title_type}
# This is a shorter lists that removes the problems with duplicate names for "Title"
standard_source = 'http://schemas.microsoft.com/sharepoint/v3'
# self._sp_cols = {i['Name']: {'name': i['DisplayName'], 'type': i['Type']} for i in self.fields \
# if i['StaticName'] == 'Title' or i['SourceID'] != standard_source}
# self._disp_cols = {i['DisplayName']: {'name': i['Name'], 'type': i['Type']} for i in self.fields \
# if i['StaticName'] == 'Title' or i['SourceID'] != standard_source}
self.last_request = None
self.date_format = re.compile('\d+-\d+-\d+ \d+:\d+:\d+')
def _url(self, service):
"""Full SharePoint Service URL"""
return ''.join([self.site_url, self._services_url[service]])
def _headers(self, soapaction):
headers = {"Content-Type": "text/xml; charset=UTF-8",
"SOAPAction": "http://schemas.microsoft.com/sharepoint/soap/" + soapaction}
return headers
def _convert_to_internal(self, data):
"""From 'Column Title' to 'Column_x0020_Title'"""
for _dict in data:
keys = list(_dict.keys())[:]
for key in keys:
if key not in self._disp_cols:
raise Exception(key + ' not a column in current List.')
_dict[self._disp_cols[key]['name']] = self._sp_type(key, _dict.pop(key))
def _python_type(self, key, value):
"""Returns proper type from the schema"""
try:
field_type = self._sp_cols[key]['type']
if field_type in ['Number', 'Currency']:
return float(value)
elif field_type == 'DateTime':
# Need to remove the '123;#' from created dates, but we will do it for all dates
# self.date_format = re.compile('\d+-\d+-\d+ \d+:\d+:\d+')
value = self.date_format.search(value).group(0)
# NOTE: I used to round this just date (7/28/2018)
return datetime.strptime(value, '%Y-%m-%d %H:%M:%S')
elif field_type == 'Boolean':
if value == '1':
return 'Yes'
elif value == '0':
return 'No'
else:
return ''
elif field_type in ('User', 'UserMulti'):
# Sometimes the User no longer exists or
# has a diffrent ID number so we just remove the "123;#"
# from the beginning of their name
if value in self.users['sp']:
return self.users['sp'][value]
elif '#' in value:
return value.split('#')[1]
else:
return value
else:
return value
except AttributeError:
return value
def _sp_type(self, key, value):
"""Returns proper type from the schema"""
try:
field_type = self._disp_cols[key]['type']
if field_type in ['Number', 'Currency']:
return value
elif field_type == 'DateTime':
return value.strftime('%Y-%m-%d %H:%M:%S')
elif field_type == 'Boolean':
if value == 'Yes':
return '1'
elif value == 'No':
return '0'
else:
raise Exception("%s not a valid Boolean Value, only 'Yes' or 'No'" % value)
elif field_type == 'User':
return self.users['py'][value]
else:
return value
except AttributeError:
return value
def GetListItems(self, viewname=None, fields=None, query=None, rowlimit=0, debug=False):
"""Get Items from current list
rowlimit defaulted to 0 (unlimited)
"""
# Build Request
soap_request = soap('GetListItems')
soap_request.add_parameter('listName', self.listName)
# Convert Displayed View Name to View ID
if viewname:
soap_request.add_parameter('viewName', self.views[viewname]['Name'][1:-1])
# Add viewFields
if fields:
# Convert to SharePoint Style Column Names
for i, val in enumerate(fields):
fields[i] = self._disp_cols[val]['name']
viewfields = fields
soap_request.add_view_fields(fields)
# Check for viewname and query
if [viewname, query] == [None, None]:
# Add a query if the viewname and query are not provided
# We sort by 'ID' here Ascending is the default
soap_request.add_query({'OrderBy': ['ID']})
elif viewname:
viewfields = self.GetView(viewname)['fields'] ## Might be wrong
else:
# No fields or views provided so get everything
viewfields = [x for x in self._sp_cols]
# Add query
if query:
if 'Where' in query:
where = etree.Element('Where')
parents = []
parents.append(where)
for i, field in enumerate(query['Where']):
if field == 'And':
parents.append(etree.SubElement(parents[-1], 'And'))
elif field == 'Or':
if parents[-1].tag == 'Or':
parents.pop()
parents.append(etree.SubElement(parents[-1], 'Or'))
else:
_type = etree.SubElement(parents[-1], field[0])
field_ref = etree.SubElement(_type, 'FieldRef')
field_ref.set('Name', self._disp_cols[field[1]]['name'])
if len(field) == 3:
value = etree.SubElement(_type, 'Value')
value.set('Type', self._disp_cols[field[1]]['type'])
value.text = self._sp_type(field[1], field[2])
query['Where'] = where
soap_request.add_query(query)
# Set Row Limit
soap_request.add_parameter('rowLimit', str(rowlimit))
self.last_request = str(soap_request)
# Send Request
response = self._session.post(url=self._url('Lists'),
headers=self._headers('GetListItems'),
data=str(soap_request),
verify=self._verify_ssl,
timeout=self.timeout)
# Parse Response
if response.status_code == 200:
envelope = etree.fromstring(response.text.encode('utf-8'), parser=etree.XMLParser(huge_tree=self.huge_tree))
listitems = envelope[0][0][0][0][0]
data = []
for row in listitems:
# Strip the 'ows_' from the beginning with key[4:]
data.append({key[4:]: value for (key, value) in row.items() if key[4:] in viewfields})
self._convert_to_display(data)
if debug:
return response
else:
return data
else:
return response
def GetList(self):
"""Get Info on Current List
This is run in __init__ so you don't
have to run it again.
Access from self.schema
"""
# Build Request
soap_request = soap('GetList')
soap_request.add_parameter('listName', self.listName)
self.last_request = str(soap_request)
# Send Request
response = self._session.post(url=self._url('Lists'),
headers=self._headers('GetList'),
data=str(soap_request),
verify=self._verify_ssl,
timeout=self.timeout)
# Parse Response
if response.status_code == 200:
envelope = etree.fromstring(response.text.encode('utf-8'), parser=etree.XMLParser(huge_tree=self.huge_tree))
_list = envelope[0][0][0][0]
info = {key: value for (key, value) in _list.items()}
for row in _list[0].getchildren():
self.fields.append({key: value for (key, value) in row.items()})
for setting in _list[1].getchildren():
self.regional_settings[
setting.tag.strip('{http://schemas.microsoft.com/sharepoint/soap/}')] = setting.text
for setting in _list[2].getchildren():
self.server_settings[
setting.tag.strip('{http://schemas.microsoft.com/sharepoint/soap/}')] = setting.text
fields = envelope[0][0][0][0][0]
else:
raise Exception("ERROR:", response.status_code, response.text)
def GetView(self, viewname):
"""Get Info on View Name
"""
# Build Request
soap_request = soap('GetView')
soap_request.add_parameter('listName', self.listName)
if viewname == None:
views = self.GetViewCollection()
for view in views:
if 'DefaultView' in view:
if views[view]['DefaultView'] == 'TRUE':
viewname = view
break
if self.listName not in ['UserInfo', 'User Information List']:
soap_request.add_parameter('viewName', self.views[viewname]['Name'][1:-1])
else:
soap_request.add_parameter('viewName', viewname)
self.last_request = str(soap_request)
# Send Request
response = self._session.post(url=self._url('Views'),
headers=self._headers('GetView'),
data=str(soap_request),
verify=self._verify_ssl,
timeout=self.timeout)
# Parse Response
if response.status_code == 200:
envelope = etree.fromstring(response.text.encode('utf-8'), parser=etree.XMLParser(huge_tree=self.huge_tree))
view = envelope[0][0][0][0]
info = {key: value for (key, value) in view.items()}
fields = [x.items()[0][1] for x in view[1]]
return {'info': info, 'fields': fields}
else:
raise Exception("ERROR:", response.status_code, response.text)
def GetViewCollection(self):
"""Get Views for Current List
This is run in __init__ so you don't
have to run it again.
Access from self.views
"""
# Build Request
soap_request = soap('GetViewCollection')
soap_request.add_parameter('listName', self.listName)
self.last_request = str(soap_request)
# Send Request
response = self._session.post(url=self._url('Views'),
headers=self._headers('GetViewCollection'),
data=str(soap_request),
verify=self._verify_ssl,
timeout=self.timeout)
# Parse Response
if response.status_code == 200:
envelope = etree.fromstring(response.text.encode('utf-8'), parser=etree.XMLParser(huge_tree=self.huge_tree))
views = envelope[0][0][0][0]
data = []
for row in views.getchildren():
data.append({key: value for (key, value) in row.items()})
view = {}
for row in data:
view[row['DisplayName']] = row
return view
else:
return ("ERROR", response.status_code)
def UpdateList(self, listName, data, listVersion):
### Todo: Complete this one
# Build Request
soap_request = soap('UpdateList')
soap_request.add_parameter('listName', listName)
soap_request.add_parameter('newFields', description)
soap_request.add_parameter('newFields', description)
soap_request.add_parameter('updateFields', templateID)
soap_request.add_parameter('deleteFields', templateID)
soap_request.add_parameter('listVersion', templateID)
self.last_request = str(soap_request)
# Send Request
response = self._session.post(url=self._url('Lists'),
headers=self._headers('AddList'),
data=str(soap_request),
verify=self._verify_ssl,
timeout=self.timeout)
pass
def UpdateListItems(self, data, kind):
"""Update List Items
kind = 'New', 'Update', or 'Delete'
New:
Provide data like so:
data = [{'Title': 'New Title', 'Col1': 'New Value'}]
Update:
Provide data like so:
data = [{'ID': 23, 'Title': 'Updated Title'},
{'ID': 28, 'Col1': 'Updated Value'}]
Delete:
Just provied a list of ID's
data = [23, 28]
"""
if type(data) != list:
raise Exception('data must be a list of dictionaries')
# Build Request
soap_request = soap('UpdateListItems')
soap_request.add_parameter('listName', self.listName)
if kind != 'Delete':
self._convert_to_internal(data)
soap_request.add_actions(data, kind)
self.last_request = str(soap_request)
# Send Request
response = self._session.post(url=self._url('Lists'),
headers=self._headers('UpdateListItems'),
data=str(soap_request),
verify=self._verify_ssl,
timeout=self.timeout)
# Parse Response
if response.status_code == 200:
envelope = etree.fromstring(response.text.encode('utf-8'), parser=etree.XMLParser(huge_tree=self.huge_tree))
results = envelope[0][0][0][0]
data = {}
for result in results:
if result.text != '0x00000000' and result[0].text != '0x00000000':
data[result.attrib['ID']] = (result[0].text, result[1].text)
else:
data[result.attrib['ID']] = result[0].text
return data
else:
return response
def GetAttachmentCollection(self, _id):
"""Get Attachments for given List Item ID"""
# Build Request
soap_request = soap('GetAttachmentCollection')
soap_request.add_parameter('listName', self.listName)
soap_request.add_parameter('listItemID', _id)
self.last_request = str(soap_request)
# Send Request
response = self._session.post(url=self._url('Lists'),
headers=self._headers('GetAttachmentCollection'),
data=str(soap_request),
verify=False,
timeout=self.timeout)
# Parse Request
if response.status_code == 200:
envelope = etree.fromstring(response.text.encode('utf-8'), parser=etree.XMLParser(huge_tree=self.huge_tree))
attaches = envelope[0][0][0][0]
attachments = []
for attachment in attaches.getchildren():
attachments.append(attachment.text)
return attachments
else:
return response
|
jasonrollins/shareplum | shareplum/shareplum.py | _List._python_type | python | def _python_type(self, key, value):
try:
field_type = self._sp_cols[key]['type']
if field_type in ['Number', 'Currency']:
return float(value)
elif field_type == 'DateTime':
# Need to remove the '123;#' from created dates, but we will do it for all dates
# self.date_format = re.compile('\d+-\d+-\d+ \d+:\d+:\d+')
value = self.date_format.search(value).group(0)
# NOTE: I used to round this just date (7/28/2018)
return datetime.strptime(value, '%Y-%m-%d %H:%M:%S')
elif field_type == 'Boolean':
if value == '1':
return 'Yes'
elif value == '0':
return 'No'
else:
return ''
elif field_type in ('User', 'UserMulti'):
# Sometimes the User no longer exists or
# has a diffrent ID number so we just remove the "123;#"
# from the beginning of their name
if value in self.users['sp']:
return self.users['sp'][value]
elif '#' in value:
return value.split('#')[1]
else:
return value
else:
return value
except AttributeError:
return value | Returns proper type from the schema | train | https://github.com/jasonrollins/shareplum/blob/404f320808912619920e2d787f2c4387225a14e0/shareplum/shareplum.py#L376-L411 | null | class _List(object):
"""Sharepoint Lists Web Service
Microsoft Developer Network:
The Lists Web service provides methods for working
with SharePoint lists, content types, list items, and files.
"""
def __init__(self, session, listName, url, verify_ssl, users, huge_tree, timeout, exclude_hidden_fields=False):
self._session = session
self.listName = listName
self._url = url
self._verify_ssl = verify_ssl
self.users = users
self.huge_tree = huge_tree
self.timeout = timeout
self._exclude_hidden_fields = exclude_hidden_fields
# List Info
self.fields = []
self.regional_settings = {}
self.server_settings = {}
self.GetList()
self.views = self.GetViewCollection()
# fields sometimes share the same displayname
# filtering fields to only contain visible fields, minimizes the chance of a one field hiding another
if exclude_hidden_fields:
self.fields = [field for field in self.fields if field.get("Hidden", "FALSE") == "FALSE"]
self._sp_cols = {i['Name']: {'name': i['DisplayName'], 'type': i['Type']} for i in self.fields}
self._disp_cols = {i['DisplayName']: {'name': i['Name'], 'type': i['Type']} for i in self.fields}
title_col = self._sp_cols['Title']['name']
title_type = self._sp_cols['Title']['type']
self._disp_cols[title_col] = {'name': 'Title', 'type': title_type}
# This is a shorter lists that removes the problems with duplicate names for "Title"
standard_source = 'http://schemas.microsoft.com/sharepoint/v3'
# self._sp_cols = {i['Name']: {'name': i['DisplayName'], 'type': i['Type']} for i in self.fields \
# if i['StaticName'] == 'Title' or i['SourceID'] != standard_source}
# self._disp_cols = {i['DisplayName']: {'name': i['Name'], 'type': i['Type']} for i in self.fields \
# if i['StaticName'] == 'Title' or i['SourceID'] != standard_source}
self.last_request = None
self.date_format = re.compile('\d+-\d+-\d+ \d+:\d+:\d+')
def _url(self, service):
"""Full SharePoint Service URL"""
return ''.join([self.site_url, self._services_url[service]])
def _headers(self, soapaction):
headers = {"Content-Type": "text/xml; charset=UTF-8",
"SOAPAction": "http://schemas.microsoft.com/sharepoint/soap/" + soapaction}
return headers
def _convert_to_internal(self, data):
"""From 'Column Title' to 'Column_x0020_Title'"""
for _dict in data:
keys = list(_dict.keys())[:]
for key in keys:
if key not in self._disp_cols:
raise Exception(key + ' not a column in current List.')
_dict[self._disp_cols[key]['name']] = self._sp_type(key, _dict.pop(key))
def _convert_to_display(self, data):
"""From 'Column_x0020_Title' to 'Column Title'"""
for _dict in data:
keys = list(_dict.keys())[:]
for key in keys:
if key not in self._sp_cols:
raise Exception(key + ' not a column in current List.')
_dict[self._sp_cols[key]['name']] = self._python_type(key, _dict.pop(key))
def _python_type(self, key, value):
"""Returns proper type from the schema"""
try:
field_type = self._sp_cols[key]['type']
if field_type in ['Number', 'Currency']:
return float(value)
elif field_type == 'DateTime':
# Need to remove the '123;#' from created dates, but we will do it for all dates
# self.date_format = re.compile('\d+-\d+-\d+ \d+:\d+:\d+')
value = self.date_format.search(value).group(0)
# NOTE: I used to round this just date (7/28/2018)
return datetime.strptime(value, '%Y-%m-%d %H:%M:%S')
elif field_type == 'Boolean':
if value == '1':
return 'Yes'
elif value == '0':
return 'No'
else:
return ''
elif field_type in ('User', 'UserMulti'):
# Sometimes the User no longer exists or
# has a diffrent ID number so we just remove the "123;#"
# from the beginning of their name
if value in self.users['sp']:
return self.users['sp'][value]
elif '#' in value:
return value.split('#')[1]
else:
return value
else:
return value
except AttributeError:
return value
def _sp_type(self, key, value):
"""Returns proper type from the schema"""
try:
field_type = self._disp_cols[key]['type']
if field_type in ['Number', 'Currency']:
return value
elif field_type == 'DateTime':
return value.strftime('%Y-%m-%d %H:%M:%S')
elif field_type == 'Boolean':
if value == 'Yes':
return '1'
elif value == 'No':
return '0'
else:
raise Exception("%s not a valid Boolean Value, only 'Yes' or 'No'" % value)
elif field_type == 'User':
return self.users['py'][value]
else:
return value
except AttributeError:
return value
def GetListItems(self, viewname=None, fields=None, query=None, rowlimit=0, debug=False):
"""Get Items from current list
rowlimit defaulted to 0 (unlimited)
"""
# Build Request
soap_request = soap('GetListItems')
soap_request.add_parameter('listName', self.listName)
# Convert Displayed View Name to View ID
if viewname:
soap_request.add_parameter('viewName', self.views[viewname]['Name'][1:-1])
# Add viewFields
if fields:
# Convert to SharePoint Style Column Names
for i, val in enumerate(fields):
fields[i] = self._disp_cols[val]['name']
viewfields = fields
soap_request.add_view_fields(fields)
# Check for viewname and query
if [viewname, query] == [None, None]:
# Add a query if the viewname and query are not provided
# We sort by 'ID' here Ascending is the default
soap_request.add_query({'OrderBy': ['ID']})
elif viewname:
viewfields = self.GetView(viewname)['fields'] ## Might be wrong
else:
# No fields or views provided so get everything
viewfields = [x for x in self._sp_cols]
# Add query
if query:
if 'Where' in query:
where = etree.Element('Where')
parents = []
parents.append(where)
for i, field in enumerate(query['Where']):
if field == 'And':
parents.append(etree.SubElement(parents[-1], 'And'))
elif field == 'Or':
if parents[-1].tag == 'Or':
parents.pop()
parents.append(etree.SubElement(parents[-1], 'Or'))
else:
_type = etree.SubElement(parents[-1], field[0])
field_ref = etree.SubElement(_type, 'FieldRef')
field_ref.set('Name', self._disp_cols[field[1]]['name'])
if len(field) == 3:
value = etree.SubElement(_type, 'Value')
value.set('Type', self._disp_cols[field[1]]['type'])
value.text = self._sp_type(field[1], field[2])
query['Where'] = where
soap_request.add_query(query)
# Set Row Limit
soap_request.add_parameter('rowLimit', str(rowlimit))
self.last_request = str(soap_request)
# Send Request
response = self._session.post(url=self._url('Lists'),
headers=self._headers('GetListItems'),
data=str(soap_request),
verify=self._verify_ssl,
timeout=self.timeout)
# Parse Response
if response.status_code == 200:
envelope = etree.fromstring(response.text.encode('utf-8'), parser=etree.XMLParser(huge_tree=self.huge_tree))
listitems = envelope[0][0][0][0][0]
data = []
for row in listitems:
# Strip the 'ows_' from the beginning with key[4:]
data.append({key[4:]: value for (key, value) in row.items() if key[4:] in viewfields})
self._convert_to_display(data)
if debug:
return response
else:
return data
else:
return response
def GetList(self):
"""Get Info on Current List
This is run in __init__ so you don't
have to run it again.
Access from self.schema
"""
# Build Request
soap_request = soap('GetList')
soap_request.add_parameter('listName', self.listName)
self.last_request = str(soap_request)
# Send Request
response = self._session.post(url=self._url('Lists'),
headers=self._headers('GetList'),
data=str(soap_request),
verify=self._verify_ssl,
timeout=self.timeout)
# Parse Response
if response.status_code == 200:
envelope = etree.fromstring(response.text.encode('utf-8'), parser=etree.XMLParser(huge_tree=self.huge_tree))
_list = envelope[0][0][0][0]
info = {key: value for (key, value) in _list.items()}
for row in _list[0].getchildren():
self.fields.append({key: value for (key, value) in row.items()})
for setting in _list[1].getchildren():
self.regional_settings[
setting.tag.strip('{http://schemas.microsoft.com/sharepoint/soap/}')] = setting.text
for setting in _list[2].getchildren():
self.server_settings[
setting.tag.strip('{http://schemas.microsoft.com/sharepoint/soap/}')] = setting.text
fields = envelope[0][0][0][0][0]
else:
raise Exception("ERROR:", response.status_code, response.text)
def GetView(self, viewname):
"""Get Info on View Name
"""
# Build Request
soap_request = soap('GetView')
soap_request.add_parameter('listName', self.listName)
if viewname == None:
views = self.GetViewCollection()
for view in views:
if 'DefaultView' in view:
if views[view]['DefaultView'] == 'TRUE':
viewname = view
break
if self.listName not in ['UserInfo', 'User Information List']:
soap_request.add_parameter('viewName', self.views[viewname]['Name'][1:-1])
else:
soap_request.add_parameter('viewName', viewname)
self.last_request = str(soap_request)
# Send Request
response = self._session.post(url=self._url('Views'),
headers=self._headers('GetView'),
data=str(soap_request),
verify=self._verify_ssl,
timeout=self.timeout)
# Parse Response
if response.status_code == 200:
envelope = etree.fromstring(response.text.encode('utf-8'), parser=etree.XMLParser(huge_tree=self.huge_tree))
view = envelope[0][0][0][0]
info = {key: value for (key, value) in view.items()}
fields = [x.items()[0][1] for x in view[1]]
return {'info': info, 'fields': fields}
else:
raise Exception("ERROR:", response.status_code, response.text)
def GetViewCollection(self):
"""Get Views for Current List
This is run in __init__ so you don't
have to run it again.
Access from self.views
"""
# Build Request
soap_request = soap('GetViewCollection')
soap_request.add_parameter('listName', self.listName)
self.last_request = str(soap_request)
# Send Request
response = self._session.post(url=self._url('Views'),
headers=self._headers('GetViewCollection'),
data=str(soap_request),
verify=self._verify_ssl,
timeout=self.timeout)
# Parse Response
if response.status_code == 200:
envelope = etree.fromstring(response.text.encode('utf-8'), parser=etree.XMLParser(huge_tree=self.huge_tree))
views = envelope[0][0][0][0]
data = []
for row in views.getchildren():
data.append({key: value for (key, value) in row.items()})
view = {}
for row in data:
view[row['DisplayName']] = row
return view
else:
return ("ERROR", response.status_code)
def UpdateList(self, listName, data, listVersion):
### Todo: Complete this one
# Build Request
soap_request = soap('UpdateList')
soap_request.add_parameter('listName', listName)
soap_request.add_parameter('newFields', description)
soap_request.add_parameter('newFields', description)
soap_request.add_parameter('updateFields', templateID)
soap_request.add_parameter('deleteFields', templateID)
soap_request.add_parameter('listVersion', templateID)
self.last_request = str(soap_request)
# Send Request
response = self._session.post(url=self._url('Lists'),
headers=self._headers('AddList'),
data=str(soap_request),
verify=self._verify_ssl,
timeout=self.timeout)
pass
def UpdateListItems(self, data, kind):
"""Update List Items
kind = 'New', 'Update', or 'Delete'
New:
Provide data like so:
data = [{'Title': 'New Title', 'Col1': 'New Value'}]
Update:
Provide data like so:
data = [{'ID': 23, 'Title': 'Updated Title'},
{'ID': 28, 'Col1': 'Updated Value'}]
Delete:
Just provied a list of ID's
data = [23, 28]
"""
if type(data) != list:
raise Exception('data must be a list of dictionaries')
# Build Request
soap_request = soap('UpdateListItems')
soap_request.add_parameter('listName', self.listName)
if kind != 'Delete':
self._convert_to_internal(data)
soap_request.add_actions(data, kind)
self.last_request = str(soap_request)
# Send Request
response = self._session.post(url=self._url('Lists'),
headers=self._headers('UpdateListItems'),
data=str(soap_request),
verify=self._verify_ssl,
timeout=self.timeout)
# Parse Response
if response.status_code == 200:
envelope = etree.fromstring(response.text.encode('utf-8'), parser=etree.XMLParser(huge_tree=self.huge_tree))
results = envelope[0][0][0][0]
data = {}
for result in results:
if result.text != '0x00000000' and result[0].text != '0x00000000':
data[result.attrib['ID']] = (result[0].text, result[1].text)
else:
data[result.attrib['ID']] = result[0].text
return data
else:
return response
def GetAttachmentCollection(self, _id):
"""Get Attachments for given List Item ID"""
# Build Request
soap_request = soap('GetAttachmentCollection')
soap_request.add_parameter('listName', self.listName)
soap_request.add_parameter('listItemID', _id)
self.last_request = str(soap_request)
# Send Request
response = self._session.post(url=self._url('Lists'),
headers=self._headers('GetAttachmentCollection'),
data=str(soap_request),
verify=False,
timeout=self.timeout)
# Parse Request
if response.status_code == 200:
envelope = etree.fromstring(response.text.encode('utf-8'), parser=etree.XMLParser(huge_tree=self.huge_tree))
attaches = envelope[0][0][0][0]
attachments = []
for attachment in attaches.getchildren():
attachments.append(attachment.text)
return attachments
else:
return response
|
jasonrollins/shareplum | shareplum/shareplum.py | _List._sp_type | python | def _sp_type(self, key, value):
try:
field_type = self._disp_cols[key]['type']
if field_type in ['Number', 'Currency']:
return value
elif field_type == 'DateTime':
return value.strftime('%Y-%m-%d %H:%M:%S')
elif field_type == 'Boolean':
if value == 'Yes':
return '1'
elif value == 'No':
return '0'
else:
raise Exception("%s not a valid Boolean Value, only 'Yes' or 'No'" % value)
elif field_type == 'User':
return self.users['py'][value]
else:
return value
except AttributeError:
return value | Returns proper type from the schema | train | https://github.com/jasonrollins/shareplum/blob/404f320808912619920e2d787f2c4387225a14e0/shareplum/shareplum.py#L413-L433 | null | class _List(object):
"""Sharepoint Lists Web Service
Microsoft Developer Network:
The Lists Web service provides methods for working
with SharePoint lists, content types, list items, and files.
"""
def __init__(self, session, listName, url, verify_ssl, users, huge_tree, timeout, exclude_hidden_fields=False):
self._session = session
self.listName = listName
self._url = url
self._verify_ssl = verify_ssl
self.users = users
self.huge_tree = huge_tree
self.timeout = timeout
self._exclude_hidden_fields = exclude_hidden_fields
# List Info
self.fields = []
self.regional_settings = {}
self.server_settings = {}
self.GetList()
self.views = self.GetViewCollection()
# fields sometimes share the same displayname
# filtering fields to only contain visible fields, minimizes the chance of a one field hiding another
if exclude_hidden_fields:
self.fields = [field for field in self.fields if field.get("Hidden", "FALSE") == "FALSE"]
self._sp_cols = {i['Name']: {'name': i['DisplayName'], 'type': i['Type']} for i in self.fields}
self._disp_cols = {i['DisplayName']: {'name': i['Name'], 'type': i['Type']} for i in self.fields}
title_col = self._sp_cols['Title']['name']
title_type = self._sp_cols['Title']['type']
self._disp_cols[title_col] = {'name': 'Title', 'type': title_type}
# This is a shorter lists that removes the problems with duplicate names for "Title"
standard_source = 'http://schemas.microsoft.com/sharepoint/v3'
# self._sp_cols = {i['Name']: {'name': i['DisplayName'], 'type': i['Type']} for i in self.fields \
# if i['StaticName'] == 'Title' or i['SourceID'] != standard_source}
# self._disp_cols = {i['DisplayName']: {'name': i['Name'], 'type': i['Type']} for i in self.fields \
# if i['StaticName'] == 'Title' or i['SourceID'] != standard_source}
self.last_request = None
self.date_format = re.compile('\d+-\d+-\d+ \d+:\d+:\d+')
def _url(self, service):
"""Full SharePoint Service URL"""
return ''.join([self.site_url, self._services_url[service]])
def _headers(self, soapaction):
headers = {"Content-Type": "text/xml; charset=UTF-8",
"SOAPAction": "http://schemas.microsoft.com/sharepoint/soap/" + soapaction}
return headers
def _convert_to_internal(self, data):
"""From 'Column Title' to 'Column_x0020_Title'"""
for _dict in data:
keys = list(_dict.keys())[:]
for key in keys:
if key not in self._disp_cols:
raise Exception(key + ' not a column in current List.')
_dict[self._disp_cols[key]['name']] = self._sp_type(key, _dict.pop(key))
def _convert_to_display(self, data):
"""From 'Column_x0020_Title' to 'Column Title'"""
for _dict in data:
keys = list(_dict.keys())[:]
for key in keys:
if key not in self._sp_cols:
raise Exception(key + ' not a column in current List.')
_dict[self._sp_cols[key]['name']] = self._python_type(key, _dict.pop(key))
def _python_type(self, key, value):
"""Returns proper type from the schema"""
try:
field_type = self._sp_cols[key]['type']
if field_type in ['Number', 'Currency']:
return float(value)
elif field_type == 'DateTime':
# Need to remove the '123;#' from created dates, but we will do it for all dates
# self.date_format = re.compile('\d+-\d+-\d+ \d+:\d+:\d+')
value = self.date_format.search(value).group(0)
# NOTE: I used to round this just date (7/28/2018)
return datetime.strptime(value, '%Y-%m-%d %H:%M:%S')
elif field_type == 'Boolean':
if value == '1':
return 'Yes'
elif value == '0':
return 'No'
else:
return ''
elif field_type in ('User', 'UserMulti'):
# Sometimes the User no longer exists or
# has a diffrent ID number so we just remove the "123;#"
# from the beginning of their name
if value in self.users['sp']:
return self.users['sp'][value]
elif '#' in value:
return value.split('#')[1]
else:
return value
else:
return value
except AttributeError:
return value
def GetListItems(self, viewname=None, fields=None, query=None, rowlimit=0, debug=False):
"""Get Items from current list
rowlimit defaulted to 0 (unlimited)
"""
# Build Request
soap_request = soap('GetListItems')
soap_request.add_parameter('listName', self.listName)
# Convert Displayed View Name to View ID
if viewname:
soap_request.add_parameter('viewName', self.views[viewname]['Name'][1:-1])
# Add viewFields
if fields:
# Convert to SharePoint Style Column Names
for i, val in enumerate(fields):
fields[i] = self._disp_cols[val]['name']
viewfields = fields
soap_request.add_view_fields(fields)
# Check for viewname and query
if [viewname, query] == [None, None]:
# Add a query if the viewname and query are not provided
# We sort by 'ID' here Ascending is the default
soap_request.add_query({'OrderBy': ['ID']})
elif viewname:
viewfields = self.GetView(viewname)['fields'] ## Might be wrong
else:
# No fields or views provided so get everything
viewfields = [x for x in self._sp_cols]
# Add query
if query:
if 'Where' in query:
where = etree.Element('Where')
parents = []
parents.append(where)
for i, field in enumerate(query['Where']):
if field == 'And':
parents.append(etree.SubElement(parents[-1], 'And'))
elif field == 'Or':
if parents[-1].tag == 'Or':
parents.pop()
parents.append(etree.SubElement(parents[-1], 'Or'))
else:
_type = etree.SubElement(parents[-1], field[0])
field_ref = etree.SubElement(_type, 'FieldRef')
field_ref.set('Name', self._disp_cols[field[1]]['name'])
if len(field) == 3:
value = etree.SubElement(_type, 'Value')
value.set('Type', self._disp_cols[field[1]]['type'])
value.text = self._sp_type(field[1], field[2])
query['Where'] = where
soap_request.add_query(query)
# Set Row Limit
soap_request.add_parameter('rowLimit', str(rowlimit))
self.last_request = str(soap_request)
# Send Request
response = self._session.post(url=self._url('Lists'),
headers=self._headers('GetListItems'),
data=str(soap_request),
verify=self._verify_ssl,
timeout=self.timeout)
# Parse Response
if response.status_code == 200:
envelope = etree.fromstring(response.text.encode('utf-8'), parser=etree.XMLParser(huge_tree=self.huge_tree))
listitems = envelope[0][0][0][0][0]
data = []
for row in listitems:
# Strip the 'ows_' from the beginning with key[4:]
data.append({key[4:]: value for (key, value) in row.items() if key[4:] in viewfields})
self._convert_to_display(data)
if debug:
return response
else:
return data
else:
return response
def GetList(self):
"""Get Info on Current List
This is run in __init__ so you don't
have to run it again.
Access from self.schema
"""
# Build Request
soap_request = soap('GetList')
soap_request.add_parameter('listName', self.listName)
self.last_request = str(soap_request)
# Send Request
response = self._session.post(url=self._url('Lists'),
headers=self._headers('GetList'),
data=str(soap_request),
verify=self._verify_ssl,
timeout=self.timeout)
# Parse Response
if response.status_code == 200:
envelope = etree.fromstring(response.text.encode('utf-8'), parser=etree.XMLParser(huge_tree=self.huge_tree))
_list = envelope[0][0][0][0]
info = {key: value for (key, value) in _list.items()}
for row in _list[0].getchildren():
self.fields.append({key: value for (key, value) in row.items()})
for setting in _list[1].getchildren():
self.regional_settings[
setting.tag.strip('{http://schemas.microsoft.com/sharepoint/soap/}')] = setting.text
for setting in _list[2].getchildren():
self.server_settings[
setting.tag.strip('{http://schemas.microsoft.com/sharepoint/soap/}')] = setting.text
fields = envelope[0][0][0][0][0]
else:
raise Exception("ERROR:", response.status_code, response.text)
def GetView(self, viewname):
"""Get Info on View Name
"""
# Build Request
soap_request = soap('GetView')
soap_request.add_parameter('listName', self.listName)
if viewname == None:
views = self.GetViewCollection()
for view in views:
if 'DefaultView' in view:
if views[view]['DefaultView'] == 'TRUE':
viewname = view
break
if self.listName not in ['UserInfo', 'User Information List']:
soap_request.add_parameter('viewName', self.views[viewname]['Name'][1:-1])
else:
soap_request.add_parameter('viewName', viewname)
self.last_request = str(soap_request)
# Send Request
response = self._session.post(url=self._url('Views'),
headers=self._headers('GetView'),
data=str(soap_request),
verify=self._verify_ssl,
timeout=self.timeout)
# Parse Response
if response.status_code == 200:
envelope = etree.fromstring(response.text.encode('utf-8'), parser=etree.XMLParser(huge_tree=self.huge_tree))
view = envelope[0][0][0][0]
info = {key: value for (key, value) in view.items()}
fields = [x.items()[0][1] for x in view[1]]
return {'info': info, 'fields': fields}
else:
raise Exception("ERROR:", response.status_code, response.text)
def GetViewCollection(self):
"""Get Views for Current List
This is run in __init__ so you don't
have to run it again.
Access from self.views
"""
# Build Request
soap_request = soap('GetViewCollection')
soap_request.add_parameter('listName', self.listName)
self.last_request = str(soap_request)
# Send Request
response = self._session.post(url=self._url('Views'),
headers=self._headers('GetViewCollection'),
data=str(soap_request),
verify=self._verify_ssl,
timeout=self.timeout)
# Parse Response
if response.status_code == 200:
envelope = etree.fromstring(response.text.encode('utf-8'), parser=etree.XMLParser(huge_tree=self.huge_tree))
views = envelope[0][0][0][0]
data = []
for row in views.getchildren():
data.append({key: value for (key, value) in row.items()})
view = {}
for row in data:
view[row['DisplayName']] = row
return view
else:
return ("ERROR", response.status_code)
def UpdateList(self, listName, data, listVersion):
### Todo: Complete this one
# Build Request
soap_request = soap('UpdateList')
soap_request.add_parameter('listName', listName)
soap_request.add_parameter('newFields', description)
soap_request.add_parameter('newFields', description)
soap_request.add_parameter('updateFields', templateID)
soap_request.add_parameter('deleteFields', templateID)
soap_request.add_parameter('listVersion', templateID)
self.last_request = str(soap_request)
# Send Request
response = self._session.post(url=self._url('Lists'),
headers=self._headers('AddList'),
data=str(soap_request),
verify=self._verify_ssl,
timeout=self.timeout)
pass
def UpdateListItems(self, data, kind):
"""Update List Items
kind = 'New', 'Update', or 'Delete'
New:
Provide data like so:
data = [{'Title': 'New Title', 'Col1': 'New Value'}]
Update:
Provide data like so:
data = [{'ID': 23, 'Title': 'Updated Title'},
{'ID': 28, 'Col1': 'Updated Value'}]
Delete:
Just provied a list of ID's
data = [23, 28]
"""
if type(data) != list:
raise Exception('data must be a list of dictionaries')
# Build Request
soap_request = soap('UpdateListItems')
soap_request.add_parameter('listName', self.listName)
if kind != 'Delete':
self._convert_to_internal(data)
soap_request.add_actions(data, kind)
self.last_request = str(soap_request)
# Send Request
response = self._session.post(url=self._url('Lists'),
headers=self._headers('UpdateListItems'),
data=str(soap_request),
verify=self._verify_ssl,
timeout=self.timeout)
# Parse Response
if response.status_code == 200:
envelope = etree.fromstring(response.text.encode('utf-8'), parser=etree.XMLParser(huge_tree=self.huge_tree))
results = envelope[0][0][0][0]
data = {}
for result in results:
if result.text != '0x00000000' and result[0].text != '0x00000000':
data[result.attrib['ID']] = (result[0].text, result[1].text)
else:
data[result.attrib['ID']] = result[0].text
return data
else:
return response
def GetAttachmentCollection(self, _id):
"""Get Attachments for given List Item ID"""
# Build Request
soap_request = soap('GetAttachmentCollection')
soap_request.add_parameter('listName', self.listName)
soap_request.add_parameter('listItemID', _id)
self.last_request = str(soap_request)
# Send Request
response = self._session.post(url=self._url('Lists'),
headers=self._headers('GetAttachmentCollection'),
data=str(soap_request),
verify=False,
timeout=self.timeout)
# Parse Request
if response.status_code == 200:
envelope = etree.fromstring(response.text.encode('utf-8'), parser=etree.XMLParser(huge_tree=self.huge_tree))
attaches = envelope[0][0][0][0]
attachments = []
for attachment in attaches.getchildren():
attachments.append(attachment.text)
return attachments
else:
return response
|
jasonrollins/shareplum | shareplum/shareplum.py | _List.GetListItems | python | def GetListItems(self, viewname=None, fields=None, query=None, rowlimit=0, debug=False):
# Build Request
soap_request = soap('GetListItems')
soap_request.add_parameter('listName', self.listName)
# Convert Displayed View Name to View ID
if viewname:
soap_request.add_parameter('viewName', self.views[viewname]['Name'][1:-1])
# Add viewFields
if fields:
# Convert to SharePoint Style Column Names
for i, val in enumerate(fields):
fields[i] = self._disp_cols[val]['name']
viewfields = fields
soap_request.add_view_fields(fields)
# Check for viewname and query
if [viewname, query] == [None, None]:
# Add a query if the viewname and query are not provided
# We sort by 'ID' here Ascending is the default
soap_request.add_query({'OrderBy': ['ID']})
elif viewname:
viewfields = self.GetView(viewname)['fields'] ## Might be wrong
else:
# No fields or views provided so get everything
viewfields = [x for x in self._sp_cols]
# Add query
if query:
if 'Where' in query:
where = etree.Element('Where')
parents = []
parents.append(where)
for i, field in enumerate(query['Where']):
if field == 'And':
parents.append(etree.SubElement(parents[-1], 'And'))
elif field == 'Or':
if parents[-1].tag == 'Or':
parents.pop()
parents.append(etree.SubElement(parents[-1], 'Or'))
else:
_type = etree.SubElement(parents[-1], field[0])
field_ref = etree.SubElement(_type, 'FieldRef')
field_ref.set('Name', self._disp_cols[field[1]]['name'])
if len(field) == 3:
value = etree.SubElement(_type, 'Value')
value.set('Type', self._disp_cols[field[1]]['type'])
value.text = self._sp_type(field[1], field[2])
query['Where'] = where
soap_request.add_query(query)
# Set Row Limit
soap_request.add_parameter('rowLimit', str(rowlimit))
self.last_request = str(soap_request)
# Send Request
response = self._session.post(url=self._url('Lists'),
headers=self._headers('GetListItems'),
data=str(soap_request),
verify=self._verify_ssl,
timeout=self.timeout)
# Parse Response
if response.status_code == 200:
envelope = etree.fromstring(response.text.encode('utf-8'), parser=etree.XMLParser(huge_tree=self.huge_tree))
listitems = envelope[0][0][0][0][0]
data = []
for row in listitems:
# Strip the 'ows_' from the beginning with key[4:]
data.append({key[4:]: value for (key, value) in row.items() if key[4:] in viewfields})
self._convert_to_display(data)
if debug:
return response
else:
return data
else:
return response | Get Items from current list
rowlimit defaulted to 0 (unlimited) | train | https://github.com/jasonrollins/shareplum/blob/404f320808912619920e2d787f2c4387225a14e0/shareplum/shareplum.py#L435-L521 | [
"def _url(self, service):\n \"\"\"Full SharePoint Service URL\"\"\"\n return ''.join([self.site_url, self._services_url[service]])\n",
"def _headers(self, soapaction):\n headers = {\"Content-Type\": \"text/xml; charset=UTF-8\",\n \"SOAPAction\": \"http://schemas.microsoft.com/sharepoint/soap/\" + soapaction}\n return headers\n",
"def _convert_to_display(self, data):\n \"\"\"From 'Column_x0020_Title' to 'Column Title'\"\"\"\n for _dict in data:\n keys = list(_dict.keys())[:]\n for key in keys:\n if key not in self._sp_cols:\n raise Exception(key + ' not a column in current List.')\n _dict[self._sp_cols[key]['name']] = self._python_type(key, _dict.pop(key))\n",
"def _sp_type(self, key, value):\n \"\"\"Returns proper type from the schema\"\"\"\n try:\n field_type = self._disp_cols[key]['type']\n if field_type in ['Number', 'Currency']:\n return value\n elif field_type == 'DateTime':\n return value.strftime('%Y-%m-%d %H:%M:%S')\n elif field_type == 'Boolean':\n if value == 'Yes':\n return '1'\n elif value == 'No':\n return '0'\n else:\n raise Exception(\"%s not a valid Boolean Value, only 'Yes' or 'No'\" % value)\n elif field_type == 'User':\n return self.users['py'][value]\n else:\n return value\n except AttributeError:\n return value\n",
"def GetView(self, viewname):\n \"\"\"Get Info on View Name\n \"\"\"\n\n # Build Request\n soap_request = soap('GetView')\n soap_request.add_parameter('listName', self.listName)\n\n if viewname == None:\n views = self.GetViewCollection()\n for view in views:\n if 'DefaultView' in view:\n if views[view]['DefaultView'] == 'TRUE':\n viewname = view\n break\n\n if self.listName not in ['UserInfo', 'User Information List']:\n soap_request.add_parameter('viewName', self.views[viewname]['Name'][1:-1])\n else:\n soap_request.add_parameter('viewName', viewname)\n self.last_request = str(soap_request)\n\n # Send Request\n response = self._session.post(url=self._url('Views'),\n headers=self._headers('GetView'),\n data=str(soap_request),\n verify=self._verify_ssl,\n timeout=self.timeout)\n\n # Parse Response\n if response.status_code == 200:\n envelope = etree.fromstring(response.text.encode('utf-8'), parser=etree.XMLParser(huge_tree=self.huge_tree))\n view = envelope[0][0][0][0]\n info = {key: value for (key, value) in view.items()}\n fields = [x.items()[0][1] for x in view[1]]\n return {'info': info, 'fields': fields}\n\n else:\n raise Exception(\"ERROR:\", response.status_code, response.text)\n",
"def add_parameter(self, parameter, value=None):\n sub = etree.SubElement(self.command, '{http://schemas.microsoft.com/sharepoint/soap/}' + parameter)\n if value:\n sub.text = value\n",
"def add_view_fields(self, fields):\n viewFields = etree.SubElement(self.command, '{http://schemas.microsoft.com/sharepoint/soap/}viewFields')\n viewFields.set('ViewFieldsOnly', 'true')\n ViewFields = etree.SubElement(viewFields, 'ViewFields')\n for field in fields:\n view_field = etree.SubElement(ViewFields, 'FieldRef')\n view_field.set('Name', field)\n",
"def add_query(self, pyquery):\n query = etree.SubElement(self.command, '{http://schemas.microsoft.com/sharepoint/soap/}query')\n Query = etree.SubElement(query, 'Query')\n if 'OrderBy' in pyquery:\n order = etree.SubElement(Query, 'OrderBy')\n for field in pyquery['OrderBy']:\n fieldref = etree.SubElement(order, 'FieldRef')\n if type(field) == tuple:\n fieldref.set('Name', field[0])\n if field[1] == 'DESCENDING':\n fieldref.set('Ascending', 'FALSE')\n else:\n fieldref.set('Name', field)\n\n if 'GroupBy' in pyquery:\n order = etree.SubElement(Query, 'GroupBy')\n for field in pyquery['GroupBy']:\n fieldref = etree.SubElement(order, 'FieldRef')\n fieldref.set('Name', field)\n\n if 'Where' in pyquery:\n Query.append(pyquery['Where'])\n"
] | class _List(object):
"""Sharepoint Lists Web Service
Microsoft Developer Network:
The Lists Web service provides methods for working
with SharePoint lists, content types, list items, and files.
"""
def __init__(self, session, listName, url, verify_ssl, users, huge_tree, timeout, exclude_hidden_fields=False):
self._session = session
self.listName = listName
self._url = url
self._verify_ssl = verify_ssl
self.users = users
self.huge_tree = huge_tree
self.timeout = timeout
self._exclude_hidden_fields = exclude_hidden_fields
# List Info
self.fields = []
self.regional_settings = {}
self.server_settings = {}
self.GetList()
self.views = self.GetViewCollection()
# fields sometimes share the same displayname
# filtering fields to only contain visible fields, minimizes the chance of a one field hiding another
if exclude_hidden_fields:
self.fields = [field for field in self.fields if field.get("Hidden", "FALSE") == "FALSE"]
self._sp_cols = {i['Name']: {'name': i['DisplayName'], 'type': i['Type']} for i in self.fields}
self._disp_cols = {i['DisplayName']: {'name': i['Name'], 'type': i['Type']} for i in self.fields}
title_col = self._sp_cols['Title']['name']
title_type = self._sp_cols['Title']['type']
self._disp_cols[title_col] = {'name': 'Title', 'type': title_type}
# This is a shorter lists that removes the problems with duplicate names for "Title"
standard_source = 'http://schemas.microsoft.com/sharepoint/v3'
# self._sp_cols = {i['Name']: {'name': i['DisplayName'], 'type': i['Type']} for i in self.fields \
# if i['StaticName'] == 'Title' or i['SourceID'] != standard_source}
# self._disp_cols = {i['DisplayName']: {'name': i['Name'], 'type': i['Type']} for i in self.fields \
# if i['StaticName'] == 'Title' or i['SourceID'] != standard_source}
self.last_request = None
self.date_format = re.compile('\d+-\d+-\d+ \d+:\d+:\d+')
def _url(self, service):
"""Full SharePoint Service URL"""
return ''.join([self.site_url, self._services_url[service]])
def _headers(self, soapaction):
headers = {"Content-Type": "text/xml; charset=UTF-8",
"SOAPAction": "http://schemas.microsoft.com/sharepoint/soap/" + soapaction}
return headers
def _convert_to_internal(self, data):
"""From 'Column Title' to 'Column_x0020_Title'"""
for _dict in data:
keys = list(_dict.keys())[:]
for key in keys:
if key not in self._disp_cols:
raise Exception(key + ' not a column in current List.')
_dict[self._disp_cols[key]['name']] = self._sp_type(key, _dict.pop(key))
def _convert_to_display(self, data):
"""From 'Column_x0020_Title' to 'Column Title'"""
for _dict in data:
keys = list(_dict.keys())[:]
for key in keys:
if key not in self._sp_cols:
raise Exception(key + ' not a column in current List.')
_dict[self._sp_cols[key]['name']] = self._python_type(key, _dict.pop(key))
def _python_type(self, key, value):
"""Returns proper type from the schema"""
try:
field_type = self._sp_cols[key]['type']
if field_type in ['Number', 'Currency']:
return float(value)
elif field_type == 'DateTime':
# Need to remove the '123;#' from created dates, but we will do it for all dates
# self.date_format = re.compile('\d+-\d+-\d+ \d+:\d+:\d+')
value = self.date_format.search(value).group(0)
# NOTE: I used to round this just date (7/28/2018)
return datetime.strptime(value, '%Y-%m-%d %H:%M:%S')
elif field_type == 'Boolean':
if value == '1':
return 'Yes'
elif value == '0':
return 'No'
else:
return ''
elif field_type in ('User', 'UserMulti'):
# Sometimes the User no longer exists or
# has a diffrent ID number so we just remove the "123;#"
# from the beginning of their name
if value in self.users['sp']:
return self.users['sp'][value]
elif '#' in value:
return value.split('#')[1]
else:
return value
else:
return value
except AttributeError:
return value
def _sp_type(self, key, value):
"""Returns proper type from the schema"""
try:
field_type = self._disp_cols[key]['type']
if field_type in ['Number', 'Currency']:
return value
elif field_type == 'DateTime':
return value.strftime('%Y-%m-%d %H:%M:%S')
elif field_type == 'Boolean':
if value == 'Yes':
return '1'
elif value == 'No':
return '0'
else:
raise Exception("%s not a valid Boolean Value, only 'Yes' or 'No'" % value)
elif field_type == 'User':
return self.users['py'][value]
else:
return value
except AttributeError:
return value
def GetList(self):
"""Get Info on Current List
This is run in __init__ so you don't
have to run it again.
Access from self.schema
"""
# Build Request
soap_request = soap('GetList')
soap_request.add_parameter('listName', self.listName)
self.last_request = str(soap_request)
# Send Request
response = self._session.post(url=self._url('Lists'),
headers=self._headers('GetList'),
data=str(soap_request),
verify=self._verify_ssl,
timeout=self.timeout)
# Parse Response
if response.status_code == 200:
envelope = etree.fromstring(response.text.encode('utf-8'), parser=etree.XMLParser(huge_tree=self.huge_tree))
_list = envelope[0][0][0][0]
info = {key: value for (key, value) in _list.items()}
for row in _list[0].getchildren():
self.fields.append({key: value for (key, value) in row.items()})
for setting in _list[1].getchildren():
self.regional_settings[
setting.tag.strip('{http://schemas.microsoft.com/sharepoint/soap/}')] = setting.text
for setting in _list[2].getchildren():
self.server_settings[
setting.tag.strip('{http://schemas.microsoft.com/sharepoint/soap/}')] = setting.text
fields = envelope[0][0][0][0][0]
else:
raise Exception("ERROR:", response.status_code, response.text)
def GetView(self, viewname):
"""Get Info on View Name
"""
# Build Request
soap_request = soap('GetView')
soap_request.add_parameter('listName', self.listName)
if viewname == None:
views = self.GetViewCollection()
for view in views:
if 'DefaultView' in view:
if views[view]['DefaultView'] == 'TRUE':
viewname = view
break
if self.listName not in ['UserInfo', 'User Information List']:
soap_request.add_parameter('viewName', self.views[viewname]['Name'][1:-1])
else:
soap_request.add_parameter('viewName', viewname)
self.last_request = str(soap_request)
# Send Request
response = self._session.post(url=self._url('Views'),
headers=self._headers('GetView'),
data=str(soap_request),
verify=self._verify_ssl,
timeout=self.timeout)
# Parse Response
if response.status_code == 200:
envelope = etree.fromstring(response.text.encode('utf-8'), parser=etree.XMLParser(huge_tree=self.huge_tree))
view = envelope[0][0][0][0]
info = {key: value for (key, value) in view.items()}
fields = [x.items()[0][1] for x in view[1]]
return {'info': info, 'fields': fields}
else:
raise Exception("ERROR:", response.status_code, response.text)
def GetViewCollection(self):
"""Get Views for Current List
This is run in __init__ so you don't
have to run it again.
Access from self.views
"""
# Build Request
soap_request = soap('GetViewCollection')
soap_request.add_parameter('listName', self.listName)
self.last_request = str(soap_request)
# Send Request
response = self._session.post(url=self._url('Views'),
headers=self._headers('GetViewCollection'),
data=str(soap_request),
verify=self._verify_ssl,
timeout=self.timeout)
# Parse Response
if response.status_code == 200:
envelope = etree.fromstring(response.text.encode('utf-8'), parser=etree.XMLParser(huge_tree=self.huge_tree))
views = envelope[0][0][0][0]
data = []
for row in views.getchildren():
data.append({key: value for (key, value) in row.items()})
view = {}
for row in data:
view[row['DisplayName']] = row
return view
else:
return ("ERROR", response.status_code)
def UpdateList(self, listName, data, listVersion):
### Todo: Complete this one
# Build Request
soap_request = soap('UpdateList')
soap_request.add_parameter('listName', listName)
soap_request.add_parameter('newFields', description)
soap_request.add_parameter('newFields', description)
soap_request.add_parameter('updateFields', templateID)
soap_request.add_parameter('deleteFields', templateID)
soap_request.add_parameter('listVersion', templateID)
self.last_request = str(soap_request)
# Send Request
response = self._session.post(url=self._url('Lists'),
headers=self._headers('AddList'),
data=str(soap_request),
verify=self._verify_ssl,
timeout=self.timeout)
pass
def UpdateListItems(self, data, kind):
"""Update List Items
kind = 'New', 'Update', or 'Delete'
New:
Provide data like so:
data = [{'Title': 'New Title', 'Col1': 'New Value'}]
Update:
Provide data like so:
data = [{'ID': 23, 'Title': 'Updated Title'},
{'ID': 28, 'Col1': 'Updated Value'}]
Delete:
Just provied a list of ID's
data = [23, 28]
"""
if type(data) != list:
raise Exception('data must be a list of dictionaries')
# Build Request
soap_request = soap('UpdateListItems')
soap_request.add_parameter('listName', self.listName)
if kind != 'Delete':
self._convert_to_internal(data)
soap_request.add_actions(data, kind)
self.last_request = str(soap_request)
# Send Request
response = self._session.post(url=self._url('Lists'),
headers=self._headers('UpdateListItems'),
data=str(soap_request),
verify=self._verify_ssl,
timeout=self.timeout)
# Parse Response
if response.status_code == 200:
envelope = etree.fromstring(response.text.encode('utf-8'), parser=etree.XMLParser(huge_tree=self.huge_tree))
results = envelope[0][0][0][0]
data = {}
for result in results:
if result.text != '0x00000000' and result[0].text != '0x00000000':
data[result.attrib['ID']] = (result[0].text, result[1].text)
else:
data[result.attrib['ID']] = result[0].text
return data
else:
return response
def GetAttachmentCollection(self, _id):
"""Get Attachments for given List Item ID"""
# Build Request
soap_request = soap('GetAttachmentCollection')
soap_request.add_parameter('listName', self.listName)
soap_request.add_parameter('listItemID', _id)
self.last_request = str(soap_request)
# Send Request
response = self._session.post(url=self._url('Lists'),
headers=self._headers('GetAttachmentCollection'),
data=str(soap_request),
verify=False,
timeout=self.timeout)
# Parse Request
if response.status_code == 200:
envelope = etree.fromstring(response.text.encode('utf-8'), parser=etree.XMLParser(huge_tree=self.huge_tree))
attaches = envelope[0][0][0][0]
attachments = []
for attachment in attaches.getchildren():
attachments.append(attachment.text)
return attachments
else:
return response
|
jasonrollins/shareplum | shareplum/shareplum.py | _List.GetList | python | def GetList(self):
# Build Request
soap_request = soap('GetList')
soap_request.add_parameter('listName', self.listName)
self.last_request = str(soap_request)
# Send Request
response = self._session.post(url=self._url('Lists'),
headers=self._headers('GetList'),
data=str(soap_request),
verify=self._verify_ssl,
timeout=self.timeout)
# Parse Response
if response.status_code == 200:
envelope = etree.fromstring(response.text.encode('utf-8'), parser=etree.XMLParser(huge_tree=self.huge_tree))
_list = envelope[0][0][0][0]
info = {key: value for (key, value) in _list.items()}
for row in _list[0].getchildren():
self.fields.append({key: value for (key, value) in row.items()})
for setting in _list[1].getchildren():
self.regional_settings[
setting.tag.strip('{http://schemas.microsoft.com/sharepoint/soap/}')] = setting.text
for setting in _list[2].getchildren():
self.server_settings[
setting.tag.strip('{http://schemas.microsoft.com/sharepoint/soap/}')] = setting.text
fields = envelope[0][0][0][0][0]
else:
raise Exception("ERROR:", response.status_code, response.text) | Get Info on Current List
This is run in __init__ so you don't
have to run it again.
Access from self.schema | train | https://github.com/jasonrollins/shareplum/blob/404f320808912619920e2d787f2c4387225a14e0/shareplum/shareplum.py#L523-L560 | [
"def _url(self, service):\n \"\"\"Full SharePoint Service URL\"\"\"\n return ''.join([self.site_url, self._services_url[service]])\n",
"def _headers(self, soapaction):\n headers = {\"Content-Type\": \"text/xml; charset=UTF-8\",\n \"SOAPAction\": \"http://schemas.microsoft.com/sharepoint/soap/\" + soapaction}\n return headers\n",
"def add_parameter(self, parameter, value=None):\n sub = etree.SubElement(self.command, '{http://schemas.microsoft.com/sharepoint/soap/}' + parameter)\n if value:\n sub.text = value\n"
] | class _List(object):
"""Sharepoint Lists Web Service
Microsoft Developer Network:
The Lists Web service provides methods for working
with SharePoint lists, content types, list items, and files.
"""
def __init__(self, session, listName, url, verify_ssl, users, huge_tree, timeout, exclude_hidden_fields=False):
self._session = session
self.listName = listName
self._url = url
self._verify_ssl = verify_ssl
self.users = users
self.huge_tree = huge_tree
self.timeout = timeout
self._exclude_hidden_fields = exclude_hidden_fields
# List Info
self.fields = []
self.regional_settings = {}
self.server_settings = {}
self.GetList()
self.views = self.GetViewCollection()
# fields sometimes share the same displayname
# filtering fields to only contain visible fields, minimizes the chance of a one field hiding another
if exclude_hidden_fields:
self.fields = [field for field in self.fields if field.get("Hidden", "FALSE") == "FALSE"]
self._sp_cols = {i['Name']: {'name': i['DisplayName'], 'type': i['Type']} for i in self.fields}
self._disp_cols = {i['DisplayName']: {'name': i['Name'], 'type': i['Type']} for i in self.fields}
title_col = self._sp_cols['Title']['name']
title_type = self._sp_cols['Title']['type']
self._disp_cols[title_col] = {'name': 'Title', 'type': title_type}
# This is a shorter lists that removes the problems with duplicate names for "Title"
standard_source = 'http://schemas.microsoft.com/sharepoint/v3'
# self._sp_cols = {i['Name']: {'name': i['DisplayName'], 'type': i['Type']} for i in self.fields \
# if i['StaticName'] == 'Title' or i['SourceID'] != standard_source}
# self._disp_cols = {i['DisplayName']: {'name': i['Name'], 'type': i['Type']} for i in self.fields \
# if i['StaticName'] == 'Title' or i['SourceID'] != standard_source}
self.last_request = None
self.date_format = re.compile('\d+-\d+-\d+ \d+:\d+:\d+')
def _url(self, service):
"""Full SharePoint Service URL"""
return ''.join([self.site_url, self._services_url[service]])
def _headers(self, soapaction):
headers = {"Content-Type": "text/xml; charset=UTF-8",
"SOAPAction": "http://schemas.microsoft.com/sharepoint/soap/" + soapaction}
return headers
def _convert_to_internal(self, data):
"""From 'Column Title' to 'Column_x0020_Title'"""
for _dict in data:
keys = list(_dict.keys())[:]
for key in keys:
if key not in self._disp_cols:
raise Exception(key + ' not a column in current List.')
_dict[self._disp_cols[key]['name']] = self._sp_type(key, _dict.pop(key))
def _convert_to_display(self, data):
"""From 'Column_x0020_Title' to 'Column Title'"""
for _dict in data:
keys = list(_dict.keys())[:]
for key in keys:
if key not in self._sp_cols:
raise Exception(key + ' not a column in current List.')
_dict[self._sp_cols[key]['name']] = self._python_type(key, _dict.pop(key))
def _python_type(self, key, value):
"""Returns proper type from the schema"""
try:
field_type = self._sp_cols[key]['type']
if field_type in ['Number', 'Currency']:
return float(value)
elif field_type == 'DateTime':
# Need to remove the '123;#' from created dates, but we will do it for all dates
# self.date_format = re.compile('\d+-\d+-\d+ \d+:\d+:\d+')
value = self.date_format.search(value).group(0)
# NOTE: I used to round this just date (7/28/2018)
return datetime.strptime(value, '%Y-%m-%d %H:%M:%S')
elif field_type == 'Boolean':
if value == '1':
return 'Yes'
elif value == '0':
return 'No'
else:
return ''
elif field_type in ('User', 'UserMulti'):
# Sometimes the User no longer exists or
# has a diffrent ID number so we just remove the "123;#"
# from the beginning of their name
if value in self.users['sp']:
return self.users['sp'][value]
elif '#' in value:
return value.split('#')[1]
else:
return value
else:
return value
except AttributeError:
return value
def _sp_type(self, key, value):
"""Returns proper type from the schema"""
try:
field_type = self._disp_cols[key]['type']
if field_type in ['Number', 'Currency']:
return value
elif field_type == 'DateTime':
return value.strftime('%Y-%m-%d %H:%M:%S')
elif field_type == 'Boolean':
if value == 'Yes':
return '1'
elif value == 'No':
return '0'
else:
raise Exception("%s not a valid Boolean Value, only 'Yes' or 'No'" % value)
elif field_type == 'User':
return self.users['py'][value]
else:
return value
except AttributeError:
return value
def GetListItems(self, viewname=None, fields=None, query=None, rowlimit=0, debug=False):
"""Get Items from current list
rowlimit defaulted to 0 (unlimited)
"""
# Build Request
soap_request = soap('GetListItems')
soap_request.add_parameter('listName', self.listName)
# Convert Displayed View Name to View ID
if viewname:
soap_request.add_parameter('viewName', self.views[viewname]['Name'][1:-1])
# Add viewFields
if fields:
# Convert to SharePoint Style Column Names
for i, val in enumerate(fields):
fields[i] = self._disp_cols[val]['name']
viewfields = fields
soap_request.add_view_fields(fields)
# Check for viewname and query
if [viewname, query] == [None, None]:
# Add a query if the viewname and query are not provided
# We sort by 'ID' here Ascending is the default
soap_request.add_query({'OrderBy': ['ID']})
elif viewname:
viewfields = self.GetView(viewname)['fields'] ## Might be wrong
else:
# No fields or views provided so get everything
viewfields = [x for x in self._sp_cols]
# Add query
if query:
if 'Where' in query:
where = etree.Element('Where')
parents = []
parents.append(where)
for i, field in enumerate(query['Where']):
if field == 'And':
parents.append(etree.SubElement(parents[-1], 'And'))
elif field == 'Or':
if parents[-1].tag == 'Or':
parents.pop()
parents.append(etree.SubElement(parents[-1], 'Or'))
else:
_type = etree.SubElement(parents[-1], field[0])
field_ref = etree.SubElement(_type, 'FieldRef')
field_ref.set('Name', self._disp_cols[field[1]]['name'])
if len(field) == 3:
value = etree.SubElement(_type, 'Value')
value.set('Type', self._disp_cols[field[1]]['type'])
value.text = self._sp_type(field[1], field[2])
query['Where'] = where
soap_request.add_query(query)
# Set Row Limit
soap_request.add_parameter('rowLimit', str(rowlimit))
self.last_request = str(soap_request)
# Send Request
response = self._session.post(url=self._url('Lists'),
headers=self._headers('GetListItems'),
data=str(soap_request),
verify=self._verify_ssl,
timeout=self.timeout)
# Parse Response
if response.status_code == 200:
envelope = etree.fromstring(response.text.encode('utf-8'), parser=etree.XMLParser(huge_tree=self.huge_tree))
listitems = envelope[0][0][0][0][0]
data = []
for row in listitems:
# Strip the 'ows_' from the beginning with key[4:]
data.append({key[4:]: value for (key, value) in row.items() if key[4:] in viewfields})
self._convert_to_display(data)
if debug:
return response
else:
return data
else:
return response
def GetView(self, viewname):
"""Get Info on View Name
"""
# Build Request
soap_request = soap('GetView')
soap_request.add_parameter('listName', self.listName)
if viewname == None:
views = self.GetViewCollection()
for view in views:
if 'DefaultView' in view:
if views[view]['DefaultView'] == 'TRUE':
viewname = view
break
if self.listName not in ['UserInfo', 'User Information List']:
soap_request.add_parameter('viewName', self.views[viewname]['Name'][1:-1])
else:
soap_request.add_parameter('viewName', viewname)
self.last_request = str(soap_request)
# Send Request
response = self._session.post(url=self._url('Views'),
headers=self._headers('GetView'),
data=str(soap_request),
verify=self._verify_ssl,
timeout=self.timeout)
# Parse Response
if response.status_code == 200:
envelope = etree.fromstring(response.text.encode('utf-8'), parser=etree.XMLParser(huge_tree=self.huge_tree))
view = envelope[0][0][0][0]
info = {key: value for (key, value) in view.items()}
fields = [x.items()[0][1] for x in view[1]]
return {'info': info, 'fields': fields}
else:
raise Exception("ERROR:", response.status_code, response.text)
def GetViewCollection(self):
"""Get Views for Current List
This is run in __init__ so you don't
have to run it again.
Access from self.views
"""
# Build Request
soap_request = soap('GetViewCollection')
soap_request.add_parameter('listName', self.listName)
self.last_request = str(soap_request)
# Send Request
response = self._session.post(url=self._url('Views'),
headers=self._headers('GetViewCollection'),
data=str(soap_request),
verify=self._verify_ssl,
timeout=self.timeout)
# Parse Response
if response.status_code == 200:
envelope = etree.fromstring(response.text.encode('utf-8'), parser=etree.XMLParser(huge_tree=self.huge_tree))
views = envelope[0][0][0][0]
data = []
for row in views.getchildren():
data.append({key: value for (key, value) in row.items()})
view = {}
for row in data:
view[row['DisplayName']] = row
return view
else:
return ("ERROR", response.status_code)
def UpdateList(self, listName, data, listVersion):
### Todo: Complete this one
# Build Request
soap_request = soap('UpdateList')
soap_request.add_parameter('listName', listName)
soap_request.add_parameter('newFields', description)
soap_request.add_parameter('newFields', description)
soap_request.add_parameter('updateFields', templateID)
soap_request.add_parameter('deleteFields', templateID)
soap_request.add_parameter('listVersion', templateID)
self.last_request = str(soap_request)
# Send Request
response = self._session.post(url=self._url('Lists'),
headers=self._headers('AddList'),
data=str(soap_request),
verify=self._verify_ssl,
timeout=self.timeout)
pass
def UpdateListItems(self, data, kind):
"""Update List Items
kind = 'New', 'Update', or 'Delete'
New:
Provide data like so:
data = [{'Title': 'New Title', 'Col1': 'New Value'}]
Update:
Provide data like so:
data = [{'ID': 23, 'Title': 'Updated Title'},
{'ID': 28, 'Col1': 'Updated Value'}]
Delete:
Just provied a list of ID's
data = [23, 28]
"""
if type(data) != list:
raise Exception('data must be a list of dictionaries')
# Build Request
soap_request = soap('UpdateListItems')
soap_request.add_parameter('listName', self.listName)
if kind != 'Delete':
self._convert_to_internal(data)
soap_request.add_actions(data, kind)
self.last_request = str(soap_request)
# Send Request
response = self._session.post(url=self._url('Lists'),
headers=self._headers('UpdateListItems'),
data=str(soap_request),
verify=self._verify_ssl,
timeout=self.timeout)
# Parse Response
if response.status_code == 200:
envelope = etree.fromstring(response.text.encode('utf-8'), parser=etree.XMLParser(huge_tree=self.huge_tree))
results = envelope[0][0][0][0]
data = {}
for result in results:
if result.text != '0x00000000' and result[0].text != '0x00000000':
data[result.attrib['ID']] = (result[0].text, result[1].text)
else:
data[result.attrib['ID']] = result[0].text
return data
else:
return response
def GetAttachmentCollection(self, _id):
"""Get Attachments for given List Item ID"""
# Build Request
soap_request = soap('GetAttachmentCollection')
soap_request.add_parameter('listName', self.listName)
soap_request.add_parameter('listItemID', _id)
self.last_request = str(soap_request)
# Send Request
response = self._session.post(url=self._url('Lists'),
headers=self._headers('GetAttachmentCollection'),
data=str(soap_request),
verify=False,
timeout=self.timeout)
# Parse Request
if response.status_code == 200:
envelope = etree.fromstring(response.text.encode('utf-8'), parser=etree.XMLParser(huge_tree=self.huge_tree))
attaches = envelope[0][0][0][0]
attachments = []
for attachment in attaches.getchildren():
attachments.append(attachment.text)
return attachments
else:
return response
|
jasonrollins/shareplum | shareplum/shareplum.py | _List.GetView | python | def GetView(self, viewname):
# Build Request
soap_request = soap('GetView')
soap_request.add_parameter('listName', self.listName)
if viewname == None:
views = self.GetViewCollection()
for view in views:
if 'DefaultView' in view:
if views[view]['DefaultView'] == 'TRUE':
viewname = view
break
if self.listName not in ['UserInfo', 'User Information List']:
soap_request.add_parameter('viewName', self.views[viewname]['Name'][1:-1])
else:
soap_request.add_parameter('viewName', viewname)
self.last_request = str(soap_request)
# Send Request
response = self._session.post(url=self._url('Views'),
headers=self._headers('GetView'),
data=str(soap_request),
verify=self._verify_ssl,
timeout=self.timeout)
# Parse Response
if response.status_code == 200:
envelope = etree.fromstring(response.text.encode('utf-8'), parser=etree.XMLParser(huge_tree=self.huge_tree))
view = envelope[0][0][0][0]
info = {key: value for (key, value) in view.items()}
fields = [x.items()[0][1] for x in view[1]]
return {'info': info, 'fields': fields}
else:
raise Exception("ERROR:", response.status_code, response.text) | Get Info on View Name | train | https://github.com/jasonrollins/shareplum/blob/404f320808912619920e2d787f2c4387225a14e0/shareplum/shareplum.py#L562-L600 | [
"def _url(self, service):\n \"\"\"Full SharePoint Service URL\"\"\"\n return ''.join([self.site_url, self._services_url[service]])\n",
"def _headers(self, soapaction):\n headers = {\"Content-Type\": \"text/xml; charset=UTF-8\",\n \"SOAPAction\": \"http://schemas.microsoft.com/sharepoint/soap/\" + soapaction}\n return headers\n",
"def GetViewCollection(self):\n \"\"\"Get Views for Current List\n This is run in __init__ so you don't\n have to run it again.\n Access from self.views\n \"\"\"\n\n # Build Request\n soap_request = soap('GetViewCollection')\n soap_request.add_parameter('listName', self.listName)\n self.last_request = str(soap_request)\n\n # Send Request\n response = self._session.post(url=self._url('Views'),\n headers=self._headers('GetViewCollection'),\n data=str(soap_request),\n verify=self._verify_ssl,\n timeout=self.timeout)\n\n # Parse Response\n if response.status_code == 200:\n envelope = etree.fromstring(response.text.encode('utf-8'), parser=etree.XMLParser(huge_tree=self.huge_tree))\n views = envelope[0][0][0][0]\n data = []\n for row in views.getchildren():\n data.append({key: value for (key, value) in row.items()})\n view = {}\n for row in data:\n view[row['DisplayName']] = row\n return view\n\n else:\n return (\"ERROR\", response.status_code)\n",
"def add_parameter(self, parameter, value=None):\n sub = etree.SubElement(self.command, '{http://schemas.microsoft.com/sharepoint/soap/}' + parameter)\n if value:\n sub.text = value\n"
] | class _List(object):
"""Sharepoint Lists Web Service
Microsoft Developer Network:
The Lists Web service provides methods for working
with SharePoint lists, content types, list items, and files.
"""
def __init__(self, session, listName, url, verify_ssl, users, huge_tree, timeout, exclude_hidden_fields=False):
self._session = session
self.listName = listName
self._url = url
self._verify_ssl = verify_ssl
self.users = users
self.huge_tree = huge_tree
self.timeout = timeout
self._exclude_hidden_fields = exclude_hidden_fields
# List Info
self.fields = []
self.regional_settings = {}
self.server_settings = {}
self.GetList()
self.views = self.GetViewCollection()
# fields sometimes share the same displayname
# filtering fields to only contain visible fields, minimizes the chance of a one field hiding another
if exclude_hidden_fields:
self.fields = [field for field in self.fields if field.get("Hidden", "FALSE") == "FALSE"]
self._sp_cols = {i['Name']: {'name': i['DisplayName'], 'type': i['Type']} for i in self.fields}
self._disp_cols = {i['DisplayName']: {'name': i['Name'], 'type': i['Type']} for i in self.fields}
title_col = self._sp_cols['Title']['name']
title_type = self._sp_cols['Title']['type']
self._disp_cols[title_col] = {'name': 'Title', 'type': title_type}
# This is a shorter lists that removes the problems with duplicate names for "Title"
standard_source = 'http://schemas.microsoft.com/sharepoint/v3'
# self._sp_cols = {i['Name']: {'name': i['DisplayName'], 'type': i['Type']} for i in self.fields \
# if i['StaticName'] == 'Title' or i['SourceID'] != standard_source}
# self._disp_cols = {i['DisplayName']: {'name': i['Name'], 'type': i['Type']} for i in self.fields \
# if i['StaticName'] == 'Title' or i['SourceID'] != standard_source}
self.last_request = None
self.date_format = re.compile('\d+-\d+-\d+ \d+:\d+:\d+')
def _url(self, service):
"""Full SharePoint Service URL"""
return ''.join([self.site_url, self._services_url[service]])
def _headers(self, soapaction):
headers = {"Content-Type": "text/xml; charset=UTF-8",
"SOAPAction": "http://schemas.microsoft.com/sharepoint/soap/" + soapaction}
return headers
def _convert_to_internal(self, data):
"""From 'Column Title' to 'Column_x0020_Title'"""
for _dict in data:
keys = list(_dict.keys())[:]
for key in keys:
if key not in self._disp_cols:
raise Exception(key + ' not a column in current List.')
_dict[self._disp_cols[key]['name']] = self._sp_type(key, _dict.pop(key))
def _convert_to_display(self, data):
"""From 'Column_x0020_Title' to 'Column Title'"""
for _dict in data:
keys = list(_dict.keys())[:]
for key in keys:
if key not in self._sp_cols:
raise Exception(key + ' not a column in current List.')
_dict[self._sp_cols[key]['name']] = self._python_type(key, _dict.pop(key))
def _python_type(self, key, value):
"""Returns proper type from the schema"""
try:
field_type = self._sp_cols[key]['type']
if field_type in ['Number', 'Currency']:
return float(value)
elif field_type == 'DateTime':
# Need to remove the '123;#' from created dates, but we will do it for all dates
# self.date_format = re.compile('\d+-\d+-\d+ \d+:\d+:\d+')
value = self.date_format.search(value).group(0)
# NOTE: I used to round this just date (7/28/2018)
return datetime.strptime(value, '%Y-%m-%d %H:%M:%S')
elif field_type == 'Boolean':
if value == '1':
return 'Yes'
elif value == '0':
return 'No'
else:
return ''
elif field_type in ('User', 'UserMulti'):
# Sometimes the User no longer exists or
# has a diffrent ID number so we just remove the "123;#"
# from the beginning of their name
if value in self.users['sp']:
return self.users['sp'][value]
elif '#' in value:
return value.split('#')[1]
else:
return value
else:
return value
except AttributeError:
return value
def _sp_type(self, key, value):
"""Returns proper type from the schema"""
try:
field_type = self._disp_cols[key]['type']
if field_type in ['Number', 'Currency']:
return value
elif field_type == 'DateTime':
return value.strftime('%Y-%m-%d %H:%M:%S')
elif field_type == 'Boolean':
if value == 'Yes':
return '1'
elif value == 'No':
return '0'
else:
raise Exception("%s not a valid Boolean Value, only 'Yes' or 'No'" % value)
elif field_type == 'User':
return self.users['py'][value]
else:
return value
except AttributeError:
return value
def GetListItems(self, viewname=None, fields=None, query=None, rowlimit=0, debug=False):
"""Get Items from current list
rowlimit defaulted to 0 (unlimited)
"""
# Build Request
soap_request = soap('GetListItems')
soap_request.add_parameter('listName', self.listName)
# Convert Displayed View Name to View ID
if viewname:
soap_request.add_parameter('viewName', self.views[viewname]['Name'][1:-1])
# Add viewFields
if fields:
# Convert to SharePoint Style Column Names
for i, val in enumerate(fields):
fields[i] = self._disp_cols[val]['name']
viewfields = fields
soap_request.add_view_fields(fields)
# Check for viewname and query
if [viewname, query] == [None, None]:
# Add a query if the viewname and query are not provided
# We sort by 'ID' here Ascending is the default
soap_request.add_query({'OrderBy': ['ID']})
elif viewname:
viewfields = self.GetView(viewname)['fields'] ## Might be wrong
else:
# No fields or views provided so get everything
viewfields = [x for x in self._sp_cols]
# Add query
if query:
if 'Where' in query:
where = etree.Element('Where')
parents = []
parents.append(where)
for i, field in enumerate(query['Where']):
if field == 'And':
parents.append(etree.SubElement(parents[-1], 'And'))
elif field == 'Or':
if parents[-1].tag == 'Or':
parents.pop()
parents.append(etree.SubElement(parents[-1], 'Or'))
else:
_type = etree.SubElement(parents[-1], field[0])
field_ref = etree.SubElement(_type, 'FieldRef')
field_ref.set('Name', self._disp_cols[field[1]]['name'])
if len(field) == 3:
value = etree.SubElement(_type, 'Value')
value.set('Type', self._disp_cols[field[1]]['type'])
value.text = self._sp_type(field[1], field[2])
query['Where'] = where
soap_request.add_query(query)
# Set Row Limit
soap_request.add_parameter('rowLimit', str(rowlimit))
self.last_request = str(soap_request)
# Send Request
response = self._session.post(url=self._url('Lists'),
headers=self._headers('GetListItems'),
data=str(soap_request),
verify=self._verify_ssl,
timeout=self.timeout)
# Parse Response
if response.status_code == 200:
envelope = etree.fromstring(response.text.encode('utf-8'), parser=etree.XMLParser(huge_tree=self.huge_tree))
listitems = envelope[0][0][0][0][0]
data = []
for row in listitems:
# Strip the 'ows_' from the beginning with key[4:]
data.append({key[4:]: value for (key, value) in row.items() if key[4:] in viewfields})
self._convert_to_display(data)
if debug:
return response
else:
return data
else:
return response
def GetList(self):
"""Get Info on Current List
This is run in __init__ so you don't
have to run it again.
Access from self.schema
"""
# Build Request
soap_request = soap('GetList')
soap_request.add_parameter('listName', self.listName)
self.last_request = str(soap_request)
# Send Request
response = self._session.post(url=self._url('Lists'),
headers=self._headers('GetList'),
data=str(soap_request),
verify=self._verify_ssl,
timeout=self.timeout)
# Parse Response
if response.status_code == 200:
envelope = etree.fromstring(response.text.encode('utf-8'), parser=etree.XMLParser(huge_tree=self.huge_tree))
_list = envelope[0][0][0][0]
info = {key: value for (key, value) in _list.items()}
for row in _list[0].getchildren():
self.fields.append({key: value for (key, value) in row.items()})
for setting in _list[1].getchildren():
self.regional_settings[
setting.tag.strip('{http://schemas.microsoft.com/sharepoint/soap/}')] = setting.text
for setting in _list[2].getchildren():
self.server_settings[
setting.tag.strip('{http://schemas.microsoft.com/sharepoint/soap/}')] = setting.text
fields = envelope[0][0][0][0][0]
else:
raise Exception("ERROR:", response.status_code, response.text)
def GetViewCollection(self):
"""Get Views for Current List
This is run in __init__ so you don't
have to run it again.
Access from self.views
"""
# Build Request
soap_request = soap('GetViewCollection')
soap_request.add_parameter('listName', self.listName)
self.last_request = str(soap_request)
# Send Request
response = self._session.post(url=self._url('Views'),
headers=self._headers('GetViewCollection'),
data=str(soap_request),
verify=self._verify_ssl,
timeout=self.timeout)
# Parse Response
if response.status_code == 200:
envelope = etree.fromstring(response.text.encode('utf-8'), parser=etree.XMLParser(huge_tree=self.huge_tree))
views = envelope[0][0][0][0]
data = []
for row in views.getchildren():
data.append({key: value for (key, value) in row.items()})
view = {}
for row in data:
view[row['DisplayName']] = row
return view
else:
return ("ERROR", response.status_code)
def UpdateList(self, listName, data, listVersion):
### Todo: Complete this one
# Build Request
soap_request = soap('UpdateList')
soap_request.add_parameter('listName', listName)
soap_request.add_parameter('newFields', description)
soap_request.add_parameter('newFields', description)
soap_request.add_parameter('updateFields', templateID)
soap_request.add_parameter('deleteFields', templateID)
soap_request.add_parameter('listVersion', templateID)
self.last_request = str(soap_request)
# Send Request
response = self._session.post(url=self._url('Lists'),
headers=self._headers('AddList'),
data=str(soap_request),
verify=self._verify_ssl,
timeout=self.timeout)
pass
def UpdateListItems(self, data, kind):
"""Update List Items
kind = 'New', 'Update', or 'Delete'
New:
Provide data like so:
data = [{'Title': 'New Title', 'Col1': 'New Value'}]
Update:
Provide data like so:
data = [{'ID': 23, 'Title': 'Updated Title'},
{'ID': 28, 'Col1': 'Updated Value'}]
Delete:
Just provied a list of ID's
data = [23, 28]
"""
if type(data) != list:
raise Exception('data must be a list of dictionaries')
# Build Request
soap_request = soap('UpdateListItems')
soap_request.add_parameter('listName', self.listName)
if kind != 'Delete':
self._convert_to_internal(data)
soap_request.add_actions(data, kind)
self.last_request = str(soap_request)
# Send Request
response = self._session.post(url=self._url('Lists'),
headers=self._headers('UpdateListItems'),
data=str(soap_request),
verify=self._verify_ssl,
timeout=self.timeout)
# Parse Response
if response.status_code == 200:
envelope = etree.fromstring(response.text.encode('utf-8'), parser=etree.XMLParser(huge_tree=self.huge_tree))
results = envelope[0][0][0][0]
data = {}
for result in results:
if result.text != '0x00000000' and result[0].text != '0x00000000':
data[result.attrib['ID']] = (result[0].text, result[1].text)
else:
data[result.attrib['ID']] = result[0].text
return data
else:
return response
def GetAttachmentCollection(self, _id):
"""Get Attachments for given List Item ID"""
# Build Request
soap_request = soap('GetAttachmentCollection')
soap_request.add_parameter('listName', self.listName)
soap_request.add_parameter('listItemID', _id)
self.last_request = str(soap_request)
# Send Request
response = self._session.post(url=self._url('Lists'),
headers=self._headers('GetAttachmentCollection'),
data=str(soap_request),
verify=False,
timeout=self.timeout)
# Parse Request
if response.status_code == 200:
envelope = etree.fromstring(response.text.encode('utf-8'), parser=etree.XMLParser(huge_tree=self.huge_tree))
attaches = envelope[0][0][0][0]
attachments = []
for attachment in attaches.getchildren():
attachments.append(attachment.text)
return attachments
else:
return response
|
jasonrollins/shareplum | shareplum/shareplum.py | _List.GetViewCollection | python | def GetViewCollection(self):
# Build Request
soap_request = soap('GetViewCollection')
soap_request.add_parameter('listName', self.listName)
self.last_request = str(soap_request)
# Send Request
response = self._session.post(url=self._url('Views'),
headers=self._headers('GetViewCollection'),
data=str(soap_request),
verify=self._verify_ssl,
timeout=self.timeout)
# Parse Response
if response.status_code == 200:
envelope = etree.fromstring(response.text.encode('utf-8'), parser=etree.XMLParser(huge_tree=self.huge_tree))
views = envelope[0][0][0][0]
data = []
for row in views.getchildren():
data.append({key: value for (key, value) in row.items()})
view = {}
for row in data:
view[row['DisplayName']] = row
return view
else:
return ("ERROR", response.status_code) | Get Views for Current List
This is run in __init__ so you don't
have to run it again.
Access from self.views | train | https://github.com/jasonrollins/shareplum/blob/404f320808912619920e2d787f2c4387225a14e0/shareplum/shareplum.py#L602-L634 | [
"def _url(self, service):\n \"\"\"Full SharePoint Service URL\"\"\"\n return ''.join([self.site_url, self._services_url[service]])\n",
"def _headers(self, soapaction):\n headers = {\"Content-Type\": \"text/xml; charset=UTF-8\",\n \"SOAPAction\": \"http://schemas.microsoft.com/sharepoint/soap/\" + soapaction}\n return headers\n",
"def add_parameter(self, parameter, value=None):\n sub = etree.SubElement(self.command, '{http://schemas.microsoft.com/sharepoint/soap/}' + parameter)\n if value:\n sub.text = value\n"
] | class _List(object):
"""Sharepoint Lists Web Service
Microsoft Developer Network:
The Lists Web service provides methods for working
with SharePoint lists, content types, list items, and files.
"""
def __init__(self, session, listName, url, verify_ssl, users, huge_tree, timeout, exclude_hidden_fields=False):
self._session = session
self.listName = listName
self._url = url
self._verify_ssl = verify_ssl
self.users = users
self.huge_tree = huge_tree
self.timeout = timeout
self._exclude_hidden_fields = exclude_hidden_fields
# List Info
self.fields = []
self.regional_settings = {}
self.server_settings = {}
self.GetList()
self.views = self.GetViewCollection()
# fields sometimes share the same displayname
# filtering fields to only contain visible fields, minimizes the chance of a one field hiding another
if exclude_hidden_fields:
self.fields = [field for field in self.fields if field.get("Hidden", "FALSE") == "FALSE"]
self._sp_cols = {i['Name']: {'name': i['DisplayName'], 'type': i['Type']} for i in self.fields}
self._disp_cols = {i['DisplayName']: {'name': i['Name'], 'type': i['Type']} for i in self.fields}
title_col = self._sp_cols['Title']['name']
title_type = self._sp_cols['Title']['type']
self._disp_cols[title_col] = {'name': 'Title', 'type': title_type}
# This is a shorter lists that removes the problems with duplicate names for "Title"
standard_source = 'http://schemas.microsoft.com/sharepoint/v3'
# self._sp_cols = {i['Name']: {'name': i['DisplayName'], 'type': i['Type']} for i in self.fields \
# if i['StaticName'] == 'Title' or i['SourceID'] != standard_source}
# self._disp_cols = {i['DisplayName']: {'name': i['Name'], 'type': i['Type']} for i in self.fields \
# if i['StaticName'] == 'Title' or i['SourceID'] != standard_source}
self.last_request = None
self.date_format = re.compile('\d+-\d+-\d+ \d+:\d+:\d+')
def _url(self, service):
"""Full SharePoint Service URL"""
return ''.join([self.site_url, self._services_url[service]])
def _headers(self, soapaction):
headers = {"Content-Type": "text/xml; charset=UTF-8",
"SOAPAction": "http://schemas.microsoft.com/sharepoint/soap/" + soapaction}
return headers
def _convert_to_internal(self, data):
"""From 'Column Title' to 'Column_x0020_Title'"""
for _dict in data:
keys = list(_dict.keys())[:]
for key in keys:
if key not in self._disp_cols:
raise Exception(key + ' not a column in current List.')
_dict[self._disp_cols[key]['name']] = self._sp_type(key, _dict.pop(key))
def _convert_to_display(self, data):
"""From 'Column_x0020_Title' to 'Column Title'"""
for _dict in data:
keys = list(_dict.keys())[:]
for key in keys:
if key not in self._sp_cols:
raise Exception(key + ' not a column in current List.')
_dict[self._sp_cols[key]['name']] = self._python_type(key, _dict.pop(key))
def _python_type(self, key, value):
"""Returns proper type from the schema"""
try:
field_type = self._sp_cols[key]['type']
if field_type in ['Number', 'Currency']:
return float(value)
elif field_type == 'DateTime':
# Need to remove the '123;#' from created dates, but we will do it for all dates
# self.date_format = re.compile('\d+-\d+-\d+ \d+:\d+:\d+')
value = self.date_format.search(value).group(0)
# NOTE: I used to round this just date (7/28/2018)
return datetime.strptime(value, '%Y-%m-%d %H:%M:%S')
elif field_type == 'Boolean':
if value == '1':
return 'Yes'
elif value == '0':
return 'No'
else:
return ''
elif field_type in ('User', 'UserMulti'):
# Sometimes the User no longer exists or
# has a diffrent ID number so we just remove the "123;#"
# from the beginning of their name
if value in self.users['sp']:
return self.users['sp'][value]
elif '#' in value:
return value.split('#')[1]
else:
return value
else:
return value
except AttributeError:
return value
def _sp_type(self, key, value):
"""Returns proper type from the schema"""
try:
field_type = self._disp_cols[key]['type']
if field_type in ['Number', 'Currency']:
return value
elif field_type == 'DateTime':
return value.strftime('%Y-%m-%d %H:%M:%S')
elif field_type == 'Boolean':
if value == 'Yes':
return '1'
elif value == 'No':
return '0'
else:
raise Exception("%s not a valid Boolean Value, only 'Yes' or 'No'" % value)
elif field_type == 'User':
return self.users['py'][value]
else:
return value
except AttributeError:
return value
def GetListItems(self, viewname=None, fields=None, query=None, rowlimit=0, debug=False):
"""Get Items from current list
rowlimit defaulted to 0 (unlimited)
"""
# Build Request
soap_request = soap('GetListItems')
soap_request.add_parameter('listName', self.listName)
# Convert Displayed View Name to View ID
if viewname:
soap_request.add_parameter('viewName', self.views[viewname]['Name'][1:-1])
# Add viewFields
if fields:
# Convert to SharePoint Style Column Names
for i, val in enumerate(fields):
fields[i] = self._disp_cols[val]['name']
viewfields = fields
soap_request.add_view_fields(fields)
# Check for viewname and query
if [viewname, query] == [None, None]:
# Add a query if the viewname and query are not provided
# We sort by 'ID' here Ascending is the default
soap_request.add_query({'OrderBy': ['ID']})
elif viewname:
viewfields = self.GetView(viewname)['fields'] ## Might be wrong
else:
# No fields or views provided so get everything
viewfields = [x for x in self._sp_cols]
# Add query
if query:
if 'Where' in query:
where = etree.Element('Where')
parents = []
parents.append(where)
for i, field in enumerate(query['Where']):
if field == 'And':
parents.append(etree.SubElement(parents[-1], 'And'))
elif field == 'Or':
if parents[-1].tag == 'Or':
parents.pop()
parents.append(etree.SubElement(parents[-1], 'Or'))
else:
_type = etree.SubElement(parents[-1], field[0])
field_ref = etree.SubElement(_type, 'FieldRef')
field_ref.set('Name', self._disp_cols[field[1]]['name'])
if len(field) == 3:
value = etree.SubElement(_type, 'Value')
value.set('Type', self._disp_cols[field[1]]['type'])
value.text = self._sp_type(field[1], field[2])
query['Where'] = where
soap_request.add_query(query)
# Set Row Limit
soap_request.add_parameter('rowLimit', str(rowlimit))
self.last_request = str(soap_request)
# Send Request
response = self._session.post(url=self._url('Lists'),
headers=self._headers('GetListItems'),
data=str(soap_request),
verify=self._verify_ssl,
timeout=self.timeout)
# Parse Response
if response.status_code == 200:
envelope = etree.fromstring(response.text.encode('utf-8'), parser=etree.XMLParser(huge_tree=self.huge_tree))
listitems = envelope[0][0][0][0][0]
data = []
for row in listitems:
# Strip the 'ows_' from the beginning with key[4:]
data.append({key[4:]: value for (key, value) in row.items() if key[4:] in viewfields})
self._convert_to_display(data)
if debug:
return response
else:
return data
else:
return response
def GetList(self):
"""Get Info on Current List
This is run in __init__ so you don't
have to run it again.
Access from self.schema
"""
# Build Request
soap_request = soap('GetList')
soap_request.add_parameter('listName', self.listName)
self.last_request = str(soap_request)
# Send Request
response = self._session.post(url=self._url('Lists'),
headers=self._headers('GetList'),
data=str(soap_request),
verify=self._verify_ssl,
timeout=self.timeout)
# Parse Response
if response.status_code == 200:
envelope = etree.fromstring(response.text.encode('utf-8'), parser=etree.XMLParser(huge_tree=self.huge_tree))
_list = envelope[0][0][0][0]
info = {key: value for (key, value) in _list.items()}
for row in _list[0].getchildren():
self.fields.append({key: value for (key, value) in row.items()})
for setting in _list[1].getchildren():
self.regional_settings[
setting.tag.strip('{http://schemas.microsoft.com/sharepoint/soap/}')] = setting.text
for setting in _list[2].getchildren():
self.server_settings[
setting.tag.strip('{http://schemas.microsoft.com/sharepoint/soap/}')] = setting.text
fields = envelope[0][0][0][0][0]
else:
raise Exception("ERROR:", response.status_code, response.text)
def GetView(self, viewname):
"""Get Info on View Name
"""
# Build Request
soap_request = soap('GetView')
soap_request.add_parameter('listName', self.listName)
if viewname == None:
views = self.GetViewCollection()
for view in views:
if 'DefaultView' in view:
if views[view]['DefaultView'] == 'TRUE':
viewname = view
break
if self.listName not in ['UserInfo', 'User Information List']:
soap_request.add_parameter('viewName', self.views[viewname]['Name'][1:-1])
else:
soap_request.add_parameter('viewName', viewname)
self.last_request = str(soap_request)
# Send Request
response = self._session.post(url=self._url('Views'),
headers=self._headers('GetView'),
data=str(soap_request),
verify=self._verify_ssl,
timeout=self.timeout)
# Parse Response
if response.status_code == 200:
envelope = etree.fromstring(response.text.encode('utf-8'), parser=etree.XMLParser(huge_tree=self.huge_tree))
view = envelope[0][0][0][0]
info = {key: value for (key, value) in view.items()}
fields = [x.items()[0][1] for x in view[1]]
return {'info': info, 'fields': fields}
else:
raise Exception("ERROR:", response.status_code, response.text)
def UpdateList(self, listName, data, listVersion):
### Todo: Complete this one
# Build Request
soap_request = soap('UpdateList')
soap_request.add_parameter('listName', listName)
soap_request.add_parameter('newFields', description)
soap_request.add_parameter('newFields', description)
soap_request.add_parameter('updateFields', templateID)
soap_request.add_parameter('deleteFields', templateID)
soap_request.add_parameter('listVersion', templateID)
self.last_request = str(soap_request)
# Send Request
response = self._session.post(url=self._url('Lists'),
headers=self._headers('AddList'),
data=str(soap_request),
verify=self._verify_ssl,
timeout=self.timeout)
pass
def UpdateListItems(self, data, kind):
"""Update List Items
kind = 'New', 'Update', or 'Delete'
New:
Provide data like so:
data = [{'Title': 'New Title', 'Col1': 'New Value'}]
Update:
Provide data like so:
data = [{'ID': 23, 'Title': 'Updated Title'},
{'ID': 28, 'Col1': 'Updated Value'}]
Delete:
Just provied a list of ID's
data = [23, 28]
"""
if type(data) != list:
raise Exception('data must be a list of dictionaries')
# Build Request
soap_request = soap('UpdateListItems')
soap_request.add_parameter('listName', self.listName)
if kind != 'Delete':
self._convert_to_internal(data)
soap_request.add_actions(data, kind)
self.last_request = str(soap_request)
# Send Request
response = self._session.post(url=self._url('Lists'),
headers=self._headers('UpdateListItems'),
data=str(soap_request),
verify=self._verify_ssl,
timeout=self.timeout)
# Parse Response
if response.status_code == 200:
envelope = etree.fromstring(response.text.encode('utf-8'), parser=etree.XMLParser(huge_tree=self.huge_tree))
results = envelope[0][0][0][0]
data = {}
for result in results:
if result.text != '0x00000000' and result[0].text != '0x00000000':
data[result.attrib['ID']] = (result[0].text, result[1].text)
else:
data[result.attrib['ID']] = result[0].text
return data
else:
return response
def GetAttachmentCollection(self, _id):
"""Get Attachments for given List Item ID"""
# Build Request
soap_request = soap('GetAttachmentCollection')
soap_request.add_parameter('listName', self.listName)
soap_request.add_parameter('listItemID', _id)
self.last_request = str(soap_request)
# Send Request
response = self._session.post(url=self._url('Lists'),
headers=self._headers('GetAttachmentCollection'),
data=str(soap_request),
verify=False,
timeout=self.timeout)
# Parse Request
if response.status_code == 200:
envelope = etree.fromstring(response.text.encode('utf-8'), parser=etree.XMLParser(huge_tree=self.huge_tree))
attaches = envelope[0][0][0][0]
attachments = []
for attachment in attaches.getchildren():
attachments.append(attachment.text)
return attachments
else:
return response
|
jasonrollins/shareplum | shareplum/shareplum.py | _List.UpdateListItems | python | def UpdateListItems(self, data, kind):
if type(data) != list:
raise Exception('data must be a list of dictionaries')
# Build Request
soap_request = soap('UpdateListItems')
soap_request.add_parameter('listName', self.listName)
if kind != 'Delete':
self._convert_to_internal(data)
soap_request.add_actions(data, kind)
self.last_request = str(soap_request)
# Send Request
response = self._session.post(url=self._url('Lists'),
headers=self._headers('UpdateListItems'),
data=str(soap_request),
verify=self._verify_ssl,
timeout=self.timeout)
# Parse Response
if response.status_code == 200:
envelope = etree.fromstring(response.text.encode('utf-8'), parser=etree.XMLParser(huge_tree=self.huge_tree))
results = envelope[0][0][0][0]
data = {}
for result in results:
if result.text != '0x00000000' and result[0].text != '0x00000000':
data[result.attrib['ID']] = (result[0].text, result[1].text)
else:
data[result.attrib['ID']] = result[0].text
return data
else:
return response | Update List Items
kind = 'New', 'Update', or 'Delete'
New:
Provide data like so:
data = [{'Title': 'New Title', 'Col1': 'New Value'}]
Update:
Provide data like so:
data = [{'ID': 23, 'Title': 'Updated Title'},
{'ID': 28, 'Col1': 'Updated Value'}]
Delete:
Just provied a list of ID's
data = [23, 28] | train | https://github.com/jasonrollins/shareplum/blob/404f320808912619920e2d787f2c4387225a14e0/shareplum/shareplum.py#L658-L704 | [
"def _url(self, service):\n \"\"\"Full SharePoint Service URL\"\"\"\n return ''.join([self.site_url, self._services_url[service]])\n",
"def _headers(self, soapaction):\n headers = {\"Content-Type\": \"text/xml; charset=UTF-8\",\n \"SOAPAction\": \"http://schemas.microsoft.com/sharepoint/soap/\" + soapaction}\n return headers\n",
"def _convert_to_internal(self, data):\n \"\"\"From 'Column Title' to 'Column_x0020_Title'\"\"\"\n for _dict in data:\n keys = list(_dict.keys())[:]\n for key in keys:\n if key not in self._disp_cols:\n raise Exception(key + ' not a column in current List.')\n _dict[self._disp_cols[key]['name']] = self._sp_type(key, _dict.pop(key))\n",
"def add_parameter(self, parameter, value=None):\n sub = etree.SubElement(self.command, '{http://schemas.microsoft.com/sharepoint/soap/}' + parameter)\n if value:\n sub.text = value\n",
"def add_actions(self, data, kind):\n if not self.updates:\n updates = etree.SubElement(self.command, '{http://schemas.microsoft.com/sharepoint/soap/}updates')\n self.batch = etree.SubElement(updates, 'Batch')\n self.batch.set('OnError', 'Return')\n self.batch.set('ListVersion', '1')\n\n if kind == 'Delete':\n for index, _id in enumerate(data, 1):\n method = etree.SubElement(self.batch, 'Method')\n method.set('ID', str(index))\n method.set('Cmd', kind)\n field = etree.SubElement(method, 'Field')\n field.set('Name', 'ID')\n field.text = str(_id)\n\n else:\n for index, row in enumerate(data, 1):\n method = etree.SubElement(self.batch, 'Method')\n method.set('ID', str(index))\n method.set('Cmd', kind)\n for key, value in row.items():\n field = etree.SubElement(method, 'Field')\n field.set('Name', key)\n field.text = str(value)\n"
] | class _List(object):
"""Sharepoint Lists Web Service
Microsoft Developer Network:
The Lists Web service provides methods for working
with SharePoint lists, content types, list items, and files.
"""
def __init__(self, session, listName, url, verify_ssl, users, huge_tree, timeout, exclude_hidden_fields=False):
self._session = session
self.listName = listName
self._url = url
self._verify_ssl = verify_ssl
self.users = users
self.huge_tree = huge_tree
self.timeout = timeout
self._exclude_hidden_fields = exclude_hidden_fields
# List Info
self.fields = []
self.regional_settings = {}
self.server_settings = {}
self.GetList()
self.views = self.GetViewCollection()
# fields sometimes share the same displayname
# filtering fields to only contain visible fields, minimizes the chance of a one field hiding another
if exclude_hidden_fields:
self.fields = [field for field in self.fields if field.get("Hidden", "FALSE") == "FALSE"]
self._sp_cols = {i['Name']: {'name': i['DisplayName'], 'type': i['Type']} for i in self.fields}
self._disp_cols = {i['DisplayName']: {'name': i['Name'], 'type': i['Type']} for i in self.fields}
title_col = self._sp_cols['Title']['name']
title_type = self._sp_cols['Title']['type']
self._disp_cols[title_col] = {'name': 'Title', 'type': title_type}
# This is a shorter lists that removes the problems with duplicate names for "Title"
standard_source = 'http://schemas.microsoft.com/sharepoint/v3'
# self._sp_cols = {i['Name']: {'name': i['DisplayName'], 'type': i['Type']} for i in self.fields \
# if i['StaticName'] == 'Title' or i['SourceID'] != standard_source}
# self._disp_cols = {i['DisplayName']: {'name': i['Name'], 'type': i['Type']} for i in self.fields \
# if i['StaticName'] == 'Title' or i['SourceID'] != standard_source}
self.last_request = None
self.date_format = re.compile('\d+-\d+-\d+ \d+:\d+:\d+')
def _url(self, service):
"""Full SharePoint Service URL"""
return ''.join([self.site_url, self._services_url[service]])
def _headers(self, soapaction):
headers = {"Content-Type": "text/xml; charset=UTF-8",
"SOAPAction": "http://schemas.microsoft.com/sharepoint/soap/" + soapaction}
return headers
def _convert_to_internal(self, data):
"""From 'Column Title' to 'Column_x0020_Title'"""
for _dict in data:
keys = list(_dict.keys())[:]
for key in keys:
if key not in self._disp_cols:
raise Exception(key + ' not a column in current List.')
_dict[self._disp_cols[key]['name']] = self._sp_type(key, _dict.pop(key))
def _convert_to_display(self, data):
"""From 'Column_x0020_Title' to 'Column Title'"""
for _dict in data:
keys = list(_dict.keys())[:]
for key in keys:
if key not in self._sp_cols:
raise Exception(key + ' not a column in current List.')
_dict[self._sp_cols[key]['name']] = self._python_type(key, _dict.pop(key))
def _python_type(self, key, value):
"""Returns proper type from the schema"""
try:
field_type = self._sp_cols[key]['type']
if field_type in ['Number', 'Currency']:
return float(value)
elif field_type == 'DateTime':
# Need to remove the '123;#' from created dates, but we will do it for all dates
# self.date_format = re.compile('\d+-\d+-\d+ \d+:\d+:\d+')
value = self.date_format.search(value).group(0)
# NOTE: I used to round this just date (7/28/2018)
return datetime.strptime(value, '%Y-%m-%d %H:%M:%S')
elif field_type == 'Boolean':
if value == '1':
return 'Yes'
elif value == '0':
return 'No'
else:
return ''
elif field_type in ('User', 'UserMulti'):
# Sometimes the User no longer exists or
# has a diffrent ID number so we just remove the "123;#"
# from the beginning of their name
if value in self.users['sp']:
return self.users['sp'][value]
elif '#' in value:
return value.split('#')[1]
else:
return value
else:
return value
except AttributeError:
return value
def _sp_type(self, key, value):
"""Returns proper type from the schema"""
try:
field_type = self._disp_cols[key]['type']
if field_type in ['Number', 'Currency']:
return value
elif field_type == 'DateTime':
return value.strftime('%Y-%m-%d %H:%M:%S')
elif field_type == 'Boolean':
if value == 'Yes':
return '1'
elif value == 'No':
return '0'
else:
raise Exception("%s not a valid Boolean Value, only 'Yes' or 'No'" % value)
elif field_type == 'User':
return self.users['py'][value]
else:
return value
except AttributeError:
return value
def GetListItems(self, viewname=None, fields=None, query=None, rowlimit=0, debug=False):
"""Get Items from current list
rowlimit defaulted to 0 (unlimited)
"""
# Build Request
soap_request = soap('GetListItems')
soap_request.add_parameter('listName', self.listName)
# Convert Displayed View Name to View ID
if viewname:
soap_request.add_parameter('viewName', self.views[viewname]['Name'][1:-1])
# Add viewFields
if fields:
# Convert to SharePoint Style Column Names
for i, val in enumerate(fields):
fields[i] = self._disp_cols[val]['name']
viewfields = fields
soap_request.add_view_fields(fields)
# Check for viewname and query
if [viewname, query] == [None, None]:
# Add a query if the viewname and query are not provided
# We sort by 'ID' here Ascending is the default
soap_request.add_query({'OrderBy': ['ID']})
elif viewname:
viewfields = self.GetView(viewname)['fields'] ## Might be wrong
else:
# No fields or views provided so get everything
viewfields = [x for x in self._sp_cols]
# Add query
if query:
if 'Where' in query:
where = etree.Element('Where')
parents = []
parents.append(where)
for i, field in enumerate(query['Where']):
if field == 'And':
parents.append(etree.SubElement(parents[-1], 'And'))
elif field == 'Or':
if parents[-1].tag == 'Or':
parents.pop()
parents.append(etree.SubElement(parents[-1], 'Or'))
else:
_type = etree.SubElement(parents[-1], field[0])
field_ref = etree.SubElement(_type, 'FieldRef')
field_ref.set('Name', self._disp_cols[field[1]]['name'])
if len(field) == 3:
value = etree.SubElement(_type, 'Value')
value.set('Type', self._disp_cols[field[1]]['type'])
value.text = self._sp_type(field[1], field[2])
query['Where'] = where
soap_request.add_query(query)
# Set Row Limit
soap_request.add_parameter('rowLimit', str(rowlimit))
self.last_request = str(soap_request)
# Send Request
response = self._session.post(url=self._url('Lists'),
headers=self._headers('GetListItems'),
data=str(soap_request),
verify=self._verify_ssl,
timeout=self.timeout)
# Parse Response
if response.status_code == 200:
envelope = etree.fromstring(response.text.encode('utf-8'), parser=etree.XMLParser(huge_tree=self.huge_tree))
listitems = envelope[0][0][0][0][0]
data = []
for row in listitems:
# Strip the 'ows_' from the beginning with key[4:]
data.append({key[4:]: value for (key, value) in row.items() if key[4:] in viewfields})
self._convert_to_display(data)
if debug:
return response
else:
return data
else:
return response
def GetList(self):
"""Get Info on Current List
This is run in __init__ so you don't
have to run it again.
Access from self.schema
"""
# Build Request
soap_request = soap('GetList')
soap_request.add_parameter('listName', self.listName)
self.last_request = str(soap_request)
# Send Request
response = self._session.post(url=self._url('Lists'),
headers=self._headers('GetList'),
data=str(soap_request),
verify=self._verify_ssl,
timeout=self.timeout)
# Parse Response
if response.status_code == 200:
envelope = etree.fromstring(response.text.encode('utf-8'), parser=etree.XMLParser(huge_tree=self.huge_tree))
_list = envelope[0][0][0][0]
info = {key: value for (key, value) in _list.items()}
for row in _list[0].getchildren():
self.fields.append({key: value for (key, value) in row.items()})
for setting in _list[1].getchildren():
self.regional_settings[
setting.tag.strip('{http://schemas.microsoft.com/sharepoint/soap/}')] = setting.text
for setting in _list[2].getchildren():
self.server_settings[
setting.tag.strip('{http://schemas.microsoft.com/sharepoint/soap/}')] = setting.text
fields = envelope[0][0][0][0][0]
else:
raise Exception("ERROR:", response.status_code, response.text)
def GetView(self, viewname):
"""Get Info on View Name
"""
# Build Request
soap_request = soap('GetView')
soap_request.add_parameter('listName', self.listName)
if viewname == None:
views = self.GetViewCollection()
for view in views:
if 'DefaultView' in view:
if views[view]['DefaultView'] == 'TRUE':
viewname = view
break
if self.listName not in ['UserInfo', 'User Information List']:
soap_request.add_parameter('viewName', self.views[viewname]['Name'][1:-1])
else:
soap_request.add_parameter('viewName', viewname)
self.last_request = str(soap_request)
# Send Request
response = self._session.post(url=self._url('Views'),
headers=self._headers('GetView'),
data=str(soap_request),
verify=self._verify_ssl,
timeout=self.timeout)
# Parse Response
if response.status_code == 200:
envelope = etree.fromstring(response.text.encode('utf-8'), parser=etree.XMLParser(huge_tree=self.huge_tree))
view = envelope[0][0][0][0]
info = {key: value for (key, value) in view.items()}
fields = [x.items()[0][1] for x in view[1]]
return {'info': info, 'fields': fields}
else:
raise Exception("ERROR:", response.status_code, response.text)
def GetViewCollection(self):
"""Get Views for Current List
This is run in __init__ so you don't
have to run it again.
Access from self.views
"""
# Build Request
soap_request = soap('GetViewCollection')
soap_request.add_parameter('listName', self.listName)
self.last_request = str(soap_request)
# Send Request
response = self._session.post(url=self._url('Views'),
headers=self._headers('GetViewCollection'),
data=str(soap_request),
verify=self._verify_ssl,
timeout=self.timeout)
# Parse Response
if response.status_code == 200:
envelope = etree.fromstring(response.text.encode('utf-8'), parser=etree.XMLParser(huge_tree=self.huge_tree))
views = envelope[0][0][0][0]
data = []
for row in views.getchildren():
data.append({key: value for (key, value) in row.items()})
view = {}
for row in data:
view[row['DisplayName']] = row
return view
else:
return ("ERROR", response.status_code)
def UpdateList(self, listName, data, listVersion):
### Todo: Complete this one
# Build Request
soap_request = soap('UpdateList')
soap_request.add_parameter('listName', listName)
soap_request.add_parameter('newFields', description)
soap_request.add_parameter('newFields', description)
soap_request.add_parameter('updateFields', templateID)
soap_request.add_parameter('deleteFields', templateID)
soap_request.add_parameter('listVersion', templateID)
self.last_request = str(soap_request)
# Send Request
response = self._session.post(url=self._url('Lists'),
headers=self._headers('AddList'),
data=str(soap_request),
verify=self._verify_ssl,
timeout=self.timeout)
pass
def GetAttachmentCollection(self, _id):
"""Get Attachments for given List Item ID"""
# Build Request
soap_request = soap('GetAttachmentCollection')
soap_request.add_parameter('listName', self.listName)
soap_request.add_parameter('listItemID', _id)
self.last_request = str(soap_request)
# Send Request
response = self._session.post(url=self._url('Lists'),
headers=self._headers('GetAttachmentCollection'),
data=str(soap_request),
verify=False,
timeout=self.timeout)
# Parse Request
if response.status_code == 200:
envelope = etree.fromstring(response.text.encode('utf-8'), parser=etree.XMLParser(huge_tree=self.huge_tree))
attaches = envelope[0][0][0][0]
attachments = []
for attachment in attaches.getchildren():
attachments.append(attachment.text)
return attachments
else:
return response
|
jasonrollins/shareplum | shareplum/shareplum.py | _List.GetAttachmentCollection | python | def GetAttachmentCollection(self, _id):
# Build Request
soap_request = soap('GetAttachmentCollection')
soap_request.add_parameter('listName', self.listName)
soap_request.add_parameter('listItemID', _id)
self.last_request = str(soap_request)
# Send Request
response = self._session.post(url=self._url('Lists'),
headers=self._headers('GetAttachmentCollection'),
data=str(soap_request),
verify=False,
timeout=self.timeout)
# Parse Request
if response.status_code == 200:
envelope = etree.fromstring(response.text.encode('utf-8'), parser=etree.XMLParser(huge_tree=self.huge_tree))
attaches = envelope[0][0][0][0]
attachments = []
for attachment in attaches.getchildren():
attachments.append(attachment.text)
return attachments
else:
return response | Get Attachments for given List Item ID | train | https://github.com/jasonrollins/shareplum/blob/404f320808912619920e2d787f2c4387225a14e0/shareplum/shareplum.py#L706-L731 | [
"def _url(self, service):\n \"\"\"Full SharePoint Service URL\"\"\"\n return ''.join([self.site_url, self._services_url[service]])\n",
"def _headers(self, soapaction):\n headers = {\"Content-Type\": \"text/xml; charset=UTF-8\",\n \"SOAPAction\": \"http://schemas.microsoft.com/sharepoint/soap/\" + soapaction}\n return headers\n",
"def add_parameter(self, parameter, value=None):\n sub = etree.SubElement(self.command, '{http://schemas.microsoft.com/sharepoint/soap/}' + parameter)\n if value:\n sub.text = value\n"
] | class _List(object):
"""Sharepoint Lists Web Service
Microsoft Developer Network:
The Lists Web service provides methods for working
with SharePoint lists, content types, list items, and files.
"""
def __init__(self, session, listName, url, verify_ssl, users, huge_tree, timeout, exclude_hidden_fields=False):
self._session = session
self.listName = listName
self._url = url
self._verify_ssl = verify_ssl
self.users = users
self.huge_tree = huge_tree
self.timeout = timeout
self._exclude_hidden_fields = exclude_hidden_fields
# List Info
self.fields = []
self.regional_settings = {}
self.server_settings = {}
self.GetList()
self.views = self.GetViewCollection()
# fields sometimes share the same displayname
# filtering fields to only contain visible fields, minimizes the chance of a one field hiding another
if exclude_hidden_fields:
self.fields = [field for field in self.fields if field.get("Hidden", "FALSE") == "FALSE"]
self._sp_cols = {i['Name']: {'name': i['DisplayName'], 'type': i['Type']} for i in self.fields}
self._disp_cols = {i['DisplayName']: {'name': i['Name'], 'type': i['Type']} for i in self.fields}
title_col = self._sp_cols['Title']['name']
title_type = self._sp_cols['Title']['type']
self._disp_cols[title_col] = {'name': 'Title', 'type': title_type}
# This is a shorter lists that removes the problems with duplicate names for "Title"
standard_source = 'http://schemas.microsoft.com/sharepoint/v3'
# self._sp_cols = {i['Name']: {'name': i['DisplayName'], 'type': i['Type']} for i in self.fields \
# if i['StaticName'] == 'Title' or i['SourceID'] != standard_source}
# self._disp_cols = {i['DisplayName']: {'name': i['Name'], 'type': i['Type']} for i in self.fields \
# if i['StaticName'] == 'Title' or i['SourceID'] != standard_source}
self.last_request = None
self.date_format = re.compile('\d+-\d+-\d+ \d+:\d+:\d+')
def _url(self, service):
"""Full SharePoint Service URL"""
return ''.join([self.site_url, self._services_url[service]])
def _headers(self, soapaction):
headers = {"Content-Type": "text/xml; charset=UTF-8",
"SOAPAction": "http://schemas.microsoft.com/sharepoint/soap/" + soapaction}
return headers
def _convert_to_internal(self, data):
"""From 'Column Title' to 'Column_x0020_Title'"""
for _dict in data:
keys = list(_dict.keys())[:]
for key in keys:
if key not in self._disp_cols:
raise Exception(key + ' not a column in current List.')
_dict[self._disp_cols[key]['name']] = self._sp_type(key, _dict.pop(key))
def _convert_to_display(self, data):
"""From 'Column_x0020_Title' to 'Column Title'"""
for _dict in data:
keys = list(_dict.keys())[:]
for key in keys:
if key not in self._sp_cols:
raise Exception(key + ' not a column in current List.')
_dict[self._sp_cols[key]['name']] = self._python_type(key, _dict.pop(key))
def _python_type(self, key, value):
"""Returns proper type from the schema"""
try:
field_type = self._sp_cols[key]['type']
if field_type in ['Number', 'Currency']:
return float(value)
elif field_type == 'DateTime':
# Need to remove the '123;#' from created dates, but we will do it for all dates
# self.date_format = re.compile('\d+-\d+-\d+ \d+:\d+:\d+')
value = self.date_format.search(value).group(0)
# NOTE: I used to round this just date (7/28/2018)
return datetime.strptime(value, '%Y-%m-%d %H:%M:%S')
elif field_type == 'Boolean':
if value == '1':
return 'Yes'
elif value == '0':
return 'No'
else:
return ''
elif field_type in ('User', 'UserMulti'):
# Sometimes the User no longer exists or
# has a diffrent ID number so we just remove the "123;#"
# from the beginning of their name
if value in self.users['sp']:
return self.users['sp'][value]
elif '#' in value:
return value.split('#')[1]
else:
return value
else:
return value
except AttributeError:
return value
def _sp_type(self, key, value):
"""Returns proper type from the schema"""
try:
field_type = self._disp_cols[key]['type']
if field_type in ['Number', 'Currency']:
return value
elif field_type == 'DateTime':
return value.strftime('%Y-%m-%d %H:%M:%S')
elif field_type == 'Boolean':
if value == 'Yes':
return '1'
elif value == 'No':
return '0'
else:
raise Exception("%s not a valid Boolean Value, only 'Yes' or 'No'" % value)
elif field_type == 'User':
return self.users['py'][value]
else:
return value
except AttributeError:
return value
def GetListItems(self, viewname=None, fields=None, query=None, rowlimit=0, debug=False):
"""Get Items from current list
rowlimit defaulted to 0 (unlimited)
"""
# Build Request
soap_request = soap('GetListItems')
soap_request.add_parameter('listName', self.listName)
# Convert Displayed View Name to View ID
if viewname:
soap_request.add_parameter('viewName', self.views[viewname]['Name'][1:-1])
# Add viewFields
if fields:
# Convert to SharePoint Style Column Names
for i, val in enumerate(fields):
fields[i] = self._disp_cols[val]['name']
viewfields = fields
soap_request.add_view_fields(fields)
# Check for viewname and query
if [viewname, query] == [None, None]:
# Add a query if the viewname and query are not provided
# We sort by 'ID' here Ascending is the default
soap_request.add_query({'OrderBy': ['ID']})
elif viewname:
viewfields = self.GetView(viewname)['fields'] ## Might be wrong
else:
# No fields or views provided so get everything
viewfields = [x for x in self._sp_cols]
# Add query
if query:
if 'Where' in query:
where = etree.Element('Where')
parents = []
parents.append(where)
for i, field in enumerate(query['Where']):
if field == 'And':
parents.append(etree.SubElement(parents[-1], 'And'))
elif field == 'Or':
if parents[-1].tag == 'Or':
parents.pop()
parents.append(etree.SubElement(parents[-1], 'Or'))
else:
_type = etree.SubElement(parents[-1], field[0])
field_ref = etree.SubElement(_type, 'FieldRef')
field_ref.set('Name', self._disp_cols[field[1]]['name'])
if len(field) == 3:
value = etree.SubElement(_type, 'Value')
value.set('Type', self._disp_cols[field[1]]['type'])
value.text = self._sp_type(field[1], field[2])
query['Where'] = where
soap_request.add_query(query)
# Set Row Limit
soap_request.add_parameter('rowLimit', str(rowlimit))
self.last_request = str(soap_request)
# Send Request
response = self._session.post(url=self._url('Lists'),
headers=self._headers('GetListItems'),
data=str(soap_request),
verify=self._verify_ssl,
timeout=self.timeout)
# Parse Response
if response.status_code == 200:
envelope = etree.fromstring(response.text.encode('utf-8'), parser=etree.XMLParser(huge_tree=self.huge_tree))
listitems = envelope[0][0][0][0][0]
data = []
for row in listitems:
# Strip the 'ows_' from the beginning with key[4:]
data.append({key[4:]: value for (key, value) in row.items() if key[4:] in viewfields})
self._convert_to_display(data)
if debug:
return response
else:
return data
else:
return response
def GetList(self):
"""Get Info on Current List
This is run in __init__ so you don't
have to run it again.
Access from self.schema
"""
# Build Request
soap_request = soap('GetList')
soap_request.add_parameter('listName', self.listName)
self.last_request = str(soap_request)
# Send Request
response = self._session.post(url=self._url('Lists'),
headers=self._headers('GetList'),
data=str(soap_request),
verify=self._verify_ssl,
timeout=self.timeout)
# Parse Response
if response.status_code == 200:
envelope = etree.fromstring(response.text.encode('utf-8'), parser=etree.XMLParser(huge_tree=self.huge_tree))
_list = envelope[0][0][0][0]
info = {key: value for (key, value) in _list.items()}
for row in _list[0].getchildren():
self.fields.append({key: value for (key, value) in row.items()})
for setting in _list[1].getchildren():
self.regional_settings[
setting.tag.strip('{http://schemas.microsoft.com/sharepoint/soap/}')] = setting.text
for setting in _list[2].getchildren():
self.server_settings[
setting.tag.strip('{http://schemas.microsoft.com/sharepoint/soap/}')] = setting.text
fields = envelope[0][0][0][0][0]
else:
raise Exception("ERROR:", response.status_code, response.text)
def GetView(self, viewname):
"""Get Info on View Name
"""
# Build Request
soap_request = soap('GetView')
soap_request.add_parameter('listName', self.listName)
if viewname == None:
views = self.GetViewCollection()
for view in views:
if 'DefaultView' in view:
if views[view]['DefaultView'] == 'TRUE':
viewname = view
break
if self.listName not in ['UserInfo', 'User Information List']:
soap_request.add_parameter('viewName', self.views[viewname]['Name'][1:-1])
else:
soap_request.add_parameter('viewName', viewname)
self.last_request = str(soap_request)
# Send Request
response = self._session.post(url=self._url('Views'),
headers=self._headers('GetView'),
data=str(soap_request),
verify=self._verify_ssl,
timeout=self.timeout)
# Parse Response
if response.status_code == 200:
envelope = etree.fromstring(response.text.encode('utf-8'), parser=etree.XMLParser(huge_tree=self.huge_tree))
view = envelope[0][0][0][0]
info = {key: value for (key, value) in view.items()}
fields = [x.items()[0][1] for x in view[1]]
return {'info': info, 'fields': fields}
else:
raise Exception("ERROR:", response.status_code, response.text)
def GetViewCollection(self):
"""Get Views for Current List
This is run in __init__ so you don't
have to run it again.
Access from self.views
"""
# Build Request
soap_request = soap('GetViewCollection')
soap_request.add_parameter('listName', self.listName)
self.last_request = str(soap_request)
# Send Request
response = self._session.post(url=self._url('Views'),
headers=self._headers('GetViewCollection'),
data=str(soap_request),
verify=self._verify_ssl,
timeout=self.timeout)
# Parse Response
if response.status_code == 200:
envelope = etree.fromstring(response.text.encode('utf-8'), parser=etree.XMLParser(huge_tree=self.huge_tree))
views = envelope[0][0][0][0]
data = []
for row in views.getchildren():
data.append({key: value for (key, value) in row.items()})
view = {}
for row in data:
view[row['DisplayName']] = row
return view
else:
return ("ERROR", response.status_code)
def UpdateList(self, listName, data, listVersion):
### Todo: Complete this one
# Build Request
soap_request = soap('UpdateList')
soap_request.add_parameter('listName', listName)
soap_request.add_parameter('newFields', description)
soap_request.add_parameter('newFields', description)
soap_request.add_parameter('updateFields', templateID)
soap_request.add_parameter('deleteFields', templateID)
soap_request.add_parameter('listVersion', templateID)
self.last_request = str(soap_request)
# Send Request
response = self._session.post(url=self._url('Lists'),
headers=self._headers('AddList'),
data=str(soap_request),
verify=self._verify_ssl,
timeout=self.timeout)
pass
def UpdateListItems(self, data, kind):
"""Update List Items
kind = 'New', 'Update', or 'Delete'
New:
Provide data like so:
data = [{'Title': 'New Title', 'Col1': 'New Value'}]
Update:
Provide data like so:
data = [{'ID': 23, 'Title': 'Updated Title'},
{'ID': 28, 'Col1': 'Updated Value'}]
Delete:
Just provied a list of ID's
data = [23, 28]
"""
if type(data) != list:
raise Exception('data must be a list of dictionaries')
# Build Request
soap_request = soap('UpdateListItems')
soap_request.add_parameter('listName', self.listName)
if kind != 'Delete':
self._convert_to_internal(data)
soap_request.add_actions(data, kind)
self.last_request = str(soap_request)
# Send Request
response = self._session.post(url=self._url('Lists'),
headers=self._headers('UpdateListItems'),
data=str(soap_request),
verify=self._verify_ssl,
timeout=self.timeout)
# Parse Response
if response.status_code == 200:
envelope = etree.fromstring(response.text.encode('utf-8'), parser=etree.XMLParser(huge_tree=self.huge_tree))
results = envelope[0][0][0][0]
data = {}
for result in results:
if result.text != '0x00000000' and result[0].text != '0x00000000':
data[result.attrib['ID']] = (result[0].text, result[1].text)
else:
data[result.attrib['ID']] = result[0].text
return data
else:
return response
|
jasonrollins/shareplum | shareplum/ListDict.py | changes | python | def changes(new_cmp_dict, old_cmp_dict, id_column, columns):
update_ldict = []
same_keys = set(new_cmp_dict).intersection(set(old_cmp_dict))
for same_key in same_keys:
# Get the Union of the set of keys
# for both dictionaries to account
# for missing keys
old_dict = old_cmp_dict[same_key]
new_dict = new_cmp_dict[same_key]
dict_keys = set(old_dict).intersection(set(new_dict))
update_dict = {}
for dict_key in columns:
old_val = old_dict.get(dict_key, 'NaN')
new_val = new_dict.get(dict_key, 'NaN')
if old_val != new_val and new_val != 'NaN':
if id_column!=None:
try:
update_dict[id_column] = old_dict[id_column]
except KeyError:
print("Input Dictionary 'old_cmp_dict' must have ID column")
update_dict[dict_key] = new_val
if update_dict:
update_ldict.append(update_dict)
return update_ldict | Return a list dict of the changes of the
rows that exist in both dictionaries
User must provide an ID column for old_cmp_dict | train | https://github.com/jasonrollins/shareplum/blob/404f320808912619920e2d787f2c4387225a14e0/shareplum/ListDict.py#L4-L33 | null | # This is a group of small functions
# used to work with a list of dictionaries
def unique(new_cmp_dict, old_cmp_dict):
"""Return a list dict of
the unique keys in new_cmp_dict
"""
newkeys = set(new_cmp_dict)
oldkeys = set(old_cmp_dict)
unique = newkeys - oldkeys
unique_ldict = []
for key in unique:
unique_ldict.append(new_cmp_dict[key])
return unique_ldict
def full_dict(ldict, keys):
"""Return Comparison Dictionaries
from list dict on keys
keys: a list of keys that when
combined make the row in the list unique
"""
if type(keys) == str:
keys = [keys]
else:
keys = keys
cmp_dict = {}
for line in ldict:
index = []
for key in keys:
index.append(str(line.get(key, '')))
index = '-'.join(index)
cmp_dict[index] = line
return cmp_dict
|
jasonrollins/shareplum | shareplum/ListDict.py | unique | python | def unique(new_cmp_dict, old_cmp_dict):
newkeys = set(new_cmp_dict)
oldkeys = set(old_cmp_dict)
unique = newkeys - oldkeys
unique_ldict = []
for key in unique:
unique_ldict.append(new_cmp_dict[key])
return unique_ldict | Return a list dict of
the unique keys in new_cmp_dict | train | https://github.com/jasonrollins/shareplum/blob/404f320808912619920e2d787f2c4387225a14e0/shareplum/ListDict.py#L35-L45 | null | # This is a group of small functions
# used to work with a list of dictionaries
def changes(new_cmp_dict, old_cmp_dict, id_column, columns):
"""Return a list dict of the changes of the
rows that exist in both dictionaries
User must provide an ID column for old_cmp_dict
"""
update_ldict = []
same_keys = set(new_cmp_dict).intersection(set(old_cmp_dict))
for same_key in same_keys:
# Get the Union of the set of keys
# for both dictionaries to account
# for missing keys
old_dict = old_cmp_dict[same_key]
new_dict = new_cmp_dict[same_key]
dict_keys = set(old_dict).intersection(set(new_dict))
update_dict = {}
for dict_key in columns:
old_val = old_dict.get(dict_key, 'NaN')
new_val = new_dict.get(dict_key, 'NaN')
if old_val != new_val and new_val != 'NaN':
if id_column!=None:
try:
update_dict[id_column] = old_dict[id_column]
except KeyError:
print("Input Dictionary 'old_cmp_dict' must have ID column")
update_dict[dict_key] = new_val
if update_dict:
update_ldict.append(update_dict)
return update_ldict
def full_dict(ldict, keys):
"""Return Comparison Dictionaries
from list dict on keys
keys: a list of keys that when
combined make the row in the list unique
"""
if type(keys) == str:
keys = [keys]
else:
keys = keys
cmp_dict = {}
for line in ldict:
index = []
for key in keys:
index.append(str(line.get(key, '')))
index = '-'.join(index)
cmp_dict[index] = line
return cmp_dict
|
jasonrollins/shareplum | shareplum/ListDict.py | full_dict | python | def full_dict(ldict, keys):
if type(keys) == str:
keys = [keys]
else:
keys = keys
cmp_dict = {}
for line in ldict:
index = []
for key in keys:
index.append(str(line.get(key, '')))
index = '-'.join(index)
cmp_dict[index] = line
return cmp_dict | Return Comparison Dictionaries
from list dict on keys
keys: a list of keys that when
combined make the row in the list unique | train | https://github.com/jasonrollins/shareplum/blob/404f320808912619920e2d787f2c4387225a14e0/shareplum/ListDict.py#L47-L66 | null | # This is a group of small functions
# used to work with a list of dictionaries
def changes(new_cmp_dict, old_cmp_dict, id_column, columns):
"""Return a list dict of the changes of the
rows that exist in both dictionaries
User must provide an ID column for old_cmp_dict
"""
update_ldict = []
same_keys = set(new_cmp_dict).intersection(set(old_cmp_dict))
for same_key in same_keys:
# Get the Union of the set of keys
# for both dictionaries to account
# for missing keys
old_dict = old_cmp_dict[same_key]
new_dict = new_cmp_dict[same_key]
dict_keys = set(old_dict).intersection(set(new_dict))
update_dict = {}
for dict_key in columns:
old_val = old_dict.get(dict_key, 'NaN')
new_val = new_dict.get(dict_key, 'NaN')
if old_val != new_val and new_val != 'NaN':
if id_column!=None:
try:
update_dict[id_column] = old_dict[id_column]
except KeyError:
print("Input Dictionary 'old_cmp_dict' must have ID column")
update_dict[dict_key] = new_val
if update_dict:
update_ldict.append(update_dict)
return update_ldict
def unique(new_cmp_dict, old_cmp_dict):
"""Return a list dict of
the unique keys in new_cmp_dict
"""
newkeys = set(new_cmp_dict)
oldkeys = set(old_cmp_dict)
unique = newkeys - oldkeys
unique_ldict = []
for key in unique:
unique_ldict.append(new_cmp_dict[key])
return unique_ldict
|
sloria/konch | docopt.py | transform | python | def transform(pattern):
result = []
groups = [[pattern]]
while groups:
children = groups.pop(0)
parents = [Required, Optional, OptionsShortcut, Either, OneOrMore]
if any(t in map(type, children) for t in parents):
child = [c for c in children if type(c) in parents][0]
children.remove(child)
if type(child) is Either:
for c in child.children:
groups.append([c] + children)
elif type(child) is OneOrMore:
groups.append(child.children * 2 + children)
else:
groups.append(child.children + children)
else:
result.append(children)
return Either(*[Required(*e) for e in result]) | Expand pattern into an (almost) equivalent one, but with single Either.
Example: ((-a | -b) (-c | -d)) => (-a -c | -a -d | -b -c | -b -d)
Quirks: [-a] => (-a), (-a...) => (-a -a) | train | https://github.com/sloria/konch/blob/15160bd0a0cac967eeeab84794bd6cdd0b5b637d/docopt.py#L73-L97 | null | # flake8: noqa
"""Pythonic command-line interface parser that will make you smile.
* http://docopt.org
* Repository and issue-tracker: https://github.com/docopt/docopt
* Licensed under terms of MIT license (see LICENSE-MIT)
* Copyright (c) 2013 Vladimir Keleshev, vladimir@keleshev.com
"""
import sys
import re
__all__ = ['docopt']
__version__ = '0.6.2'
class DocoptLanguageError(Exception):
"""Error in construction of usage-message by developer."""
class DocoptExit(SystemExit):
"""Exit in case user invoked program with incorrect arguments."""
usage = ''
def __init__(self, message=''):
SystemExit.__init__(self, (message + '\n' + self.usage).strip())
class Pattern(object):
def __eq__(self, other):
return repr(self) == repr(other)
def __hash__(self):
return hash(repr(self))
def fix(self):
self.fix_identities()
self.fix_repeating_arguments()
return self
def fix_identities(self, uniq=None):
"""Make pattern-tree tips point to same object if they are equal."""
if not hasattr(self, 'children'):
return self
uniq = list(set(self.flat())) if uniq is None else uniq
for i, child in enumerate(self.children):
if not hasattr(child, 'children'):
assert child in uniq
self.children[i] = uniq[uniq.index(child)]
else:
child.fix_identities(uniq)
def fix_repeating_arguments(self):
"""Fix elements that should accumulate/increment values."""
either = [list(child.children) for child in transform(self).children]
for case in either:
for e in [child for child in case if case.count(child) > 1]:
if type(e) is Argument or type(e) is Option and e.argcount:
if e.value is None:
e.value = []
elif type(e.value) is not list:
e.value = e.value.split()
if type(e) is Command or type(e) is Option and e.argcount == 0:
e.value = 0
return self
class LeafPattern(Pattern):
"""Leaf/terminal node of a pattern tree."""
def __init__(self, name, value=None):
self.name, self.value = name, value
def __repr__(self):
return '%s(%r, %r)' % (self.__class__.__name__, self.name, self.value)
def flat(self, *types):
return [self] if not types or type(self) in types else []
def match(self, left, collected=None):
collected = [] if collected is None else collected
pos, match = self.single_match(left)
if match is None:
return False, left, collected
left_ = left[:pos] + left[pos + 1:]
same_name = [a for a in collected if a.name == self.name]
if type(self.value) in (int, list):
if type(self.value) is int:
increment = 1
else:
increment = ([match.value] if type(match.value) is str
else match.value)
if not same_name:
match.value = increment
return True, left_, collected + [match]
same_name[0].value += increment
return True, left_, collected
return True, left_, collected + [match]
class BranchPattern(Pattern):
"""Branch/inner node of a pattern tree."""
def __init__(self, *children):
self.children = list(children)
def __repr__(self):
return '%s(%s)' % (self.__class__.__name__,
', '.join(repr(a) for a in self.children))
def flat(self, *types):
if type(self) in types:
return [self]
return sum([child.flat(*types) for child in self.children], [])
class Argument(LeafPattern):
def single_match(self, left):
for n, pattern in enumerate(left):
if type(pattern) is Argument:
return n, Argument(self.name, pattern.value)
return None, None
@classmethod
def parse(class_, source):
name = re.findall('(<\S*?>)', source)[0]
value = re.findall('\[default: (.*)\]', source, flags=re.I)
return class_(name, value[0] if value else None)
class Command(Argument):
def __init__(self, name, value=False):
self.name, self.value = name, value
def single_match(self, left):
for n, pattern in enumerate(left):
if type(pattern) is Argument:
if pattern.value == self.name:
return n, Command(self.name, True)
else:
break
return None, None
class Option(LeafPattern):
def __init__(self, short=None, long=None, argcount=0, value=False):
assert argcount in (0, 1)
self.short, self.long, self.argcount = short, long, argcount
self.value = None if value is False and argcount else value
@classmethod
def parse(class_, option_description):
short, long, argcount, value = None, None, 0, False
options, _, description = option_description.strip().partition(' ')
options = options.replace(',', ' ').replace('=', ' ')
for s in options.split():
if s.startswith('--'):
long = s
elif s.startswith('-'):
short = s
else:
argcount = 1
if argcount:
matched = re.findall('\[default: (.*)\]', description, flags=re.I)
value = matched[0] if matched else None
return class_(short, long, argcount, value)
def single_match(self, left):
for n, pattern in enumerate(left):
if self.name == pattern.name:
return n, pattern
return None, None
@property
def name(self):
return self.long or self.short
def __repr__(self):
return 'Option(%r, %r, %r, %r)' % (self.short, self.long,
self.argcount, self.value)
class Required(BranchPattern):
def match(self, left, collected=None):
collected = [] if collected is None else collected
l = left
c = collected
for pattern in self.children:
matched, l, c = pattern.match(l, c)
if not matched:
return False, left, collected
return True, l, c
class Optional(BranchPattern):
def match(self, left, collected=None):
collected = [] if collected is None else collected
for pattern in self.children:
m, left, collected = pattern.match(left, collected)
return True, left, collected
class OptionsShortcut(Optional):
"""Marker/placeholder for [options] shortcut."""
class OneOrMore(BranchPattern):
def match(self, left, collected=None):
assert len(self.children) == 1
collected = [] if collected is None else collected
l = left
c = collected
l_ = None
matched = True
times = 0
while matched:
# could it be that something didn't match but changed l or c?
matched, l, c = self.children[0].match(l, c)
times += 1 if matched else 0
if l_ == l:
break
l_ = l
if times >= 1:
return True, l, c
return False, left, collected
class Either(BranchPattern):
def match(self, left, collected=None):
collected = [] if collected is None else collected
outcomes = []
for pattern in self.children:
matched, _, _ = outcome = pattern.match(left, collected)
if matched:
outcomes.append(outcome)
if outcomes:
return min(outcomes, key=lambda outcome: len(outcome[1]))
return False, left, collected
class Tokens(list):
def __init__(self, source, error=DocoptExit):
self += source.split() if hasattr(source, 'split') else source
self.error = error
@staticmethod
def from_pattern(source):
source = re.sub(r'([\[\]\(\)\|]|\.\.\.)', r' \1 ', source)
source = [s for s in re.split('\s+|(\S*<.*?>)', source) if s]
return Tokens(source, error=DocoptLanguageError)
def move(self):
return self.pop(0) if len(self) else None
def current(self):
return self[0] if len(self) else None
def parse_long(tokens, options):
"""long ::= '--' chars [ ( ' ' | '=' ) chars ] ;"""
long, eq, value = tokens.move().partition('=')
assert long.startswith('--')
value = None if eq == value == '' else value
similar = [o for o in options if o.long == long]
if tokens.error is DocoptExit and similar == []: # if no exact match
similar = [o for o in options if o.long and o.long.startswith(long)]
if len(similar) > 1: # might be simply specified ambiguously 2+ times?
raise tokens.error('%s is not a unique prefix: %s?' %
(long, ', '.join(o.long for o in similar)))
elif len(similar) < 1:
argcount = 1 if eq == '=' else 0
o = Option(None, long, argcount)
options.append(o)
if tokens.error is DocoptExit:
o = Option(None, long, argcount, value if argcount else True)
else:
o = Option(similar[0].short, similar[0].long,
similar[0].argcount, similar[0].value)
if o.argcount == 0:
if value is not None:
raise tokens.error('%s must not have an argument' % o.long)
else:
if value is None:
if tokens.current() in [None, '--']:
raise tokens.error('%s requires argument' % o.long)
value = tokens.move()
if tokens.error is DocoptExit:
o.value = value if value is not None else True
return [o]
def parse_shorts(tokens, options):
"""shorts ::= '-' ( chars )* [ [ ' ' ] chars ] ;"""
token = tokens.move()
assert token.startswith('-') and not token.startswith('--')
left = token.lstrip('-')
parsed = []
while left != '':
short, left = '-' + left[0], left[1:]
similar = [o for o in options if o.short == short]
if len(similar) > 1:
raise tokens.error('%s is specified ambiguously %d times' %
(short, len(similar)))
elif len(similar) < 1:
o = Option(short, None, 0)
options.append(o)
if tokens.error is DocoptExit:
o = Option(short, None, 0, True)
else: # why copying is necessary here?
o = Option(short, similar[0].long,
similar[0].argcount, similar[0].value)
value = None
if o.argcount != 0:
if left == '':
if tokens.current() in [None, '--']:
raise tokens.error('%s requires argument' % short)
value = tokens.move()
else:
value = left
left = ''
if tokens.error is DocoptExit:
o.value = value if value is not None else True
parsed.append(o)
return parsed
def parse_pattern(source, options):
tokens = Tokens.from_pattern(source)
result = parse_expr(tokens, options)
if tokens.current() is not None:
raise tokens.error('unexpected ending: %r' % ' '.join(tokens))
return Required(*result)
def parse_expr(tokens, options):
"""expr ::= seq ( '|' seq )* ;"""
seq = parse_seq(tokens, options)
if tokens.current() != '|':
return seq
result = [Required(*seq)] if len(seq) > 1 else seq
while tokens.current() == '|':
tokens.move()
seq = parse_seq(tokens, options)
result += [Required(*seq)] if len(seq) > 1 else seq
return [Either(*result)] if len(result) > 1 else result
def parse_seq(tokens, options):
"""seq ::= ( atom [ '...' ] )* ;"""
result = []
while tokens.current() not in [None, ']', ')', '|']:
atom = parse_atom(tokens, options)
if tokens.current() == '...':
atom = [OneOrMore(*atom)]
tokens.move()
result += atom
return result
def parse_atom(tokens, options):
"""atom ::= '(' expr ')' | '[' expr ']' | 'options'
| long | shorts | argument | command ;
"""
token = tokens.current()
result = []
if token in '([':
tokens.move()
matching, pattern = {'(': [')', Required], '[': [']', Optional]}[token]
result = pattern(*parse_expr(tokens, options))
if tokens.move() != matching:
raise tokens.error("unmatched '%s'" % token)
return [result]
elif token == 'options':
tokens.move()
return [OptionsShortcut()]
elif token.startswith('--') and token != '--':
return parse_long(tokens, options)
elif token.startswith('-') and token not in ('-', '--'):
return parse_shorts(tokens, options)
elif token.startswith('<') and token.endswith('>') or token.isupper():
return [Argument(tokens.move())]
else:
return [Command(tokens.move())]
def parse_argv(tokens, options, options_first=False):
"""Parse command-line argument vector.
If options_first:
argv ::= [ long | shorts ]* [ argument ]* [ '--' [ argument ]* ] ;
else:
argv ::= [ long | shorts | argument ]* [ '--' [ argument ]* ] ;
"""
parsed = []
while tokens.current() is not None:
if tokens.current() == '--':
return parsed + [Argument(None, v) for v in tokens]
elif tokens.current().startswith('--'):
parsed += parse_long(tokens, options)
elif tokens.current().startswith('-') and tokens.current() != '-':
parsed += parse_shorts(tokens, options)
elif options_first:
return parsed + [Argument(None, v) for v in tokens]
else:
parsed.append(Argument(None, tokens.move()))
return parsed
def parse_defaults(doc):
defaults = []
for s in parse_section('options:', doc):
# FIXME corner case "bla: options: --foo"
_, _, s = s.partition(':') # get rid of "options:"
split = re.split('\n[ \t]*(-\S+?)', '\n' + s)[1:]
split = [s1 + s2 for s1, s2 in zip(split[::2], split[1::2])]
options = [Option.parse(s) for s in split if s.startswith('-')]
defaults += options
return defaults
def parse_section(name, source):
pattern = re.compile('^([^\n]*' + name + '[^\n]*\n?(?:[ \t].*?(?:\n|$))*)',
re.IGNORECASE | re.MULTILINE)
return [s.strip() for s in pattern.findall(source)]
def formal_usage(section):
_, _, section = section.partition(':') # drop "usage:"
pu = section.split()
return '( ' + ' '.join(') | (' if s == pu[0] else s for s in pu[1:]) + ' )'
def extras(help, version, options, doc):
if help and any((o.name in ('-h', '--help')) and o.value for o in options):
print(doc.strip("\n"))
sys.exit()
if version and any(o.name == '--version' and o.value for o in options):
print(version)
sys.exit()
class Dict(dict):
def __repr__(self):
return '{%s}' % ',\n '.join('%r: %r' % i for i in sorted(self.items()))
def docopt(doc, argv=None, help=True, version=None, options_first=False):
"""Parse `argv` based on command-line interface described in `doc`.
`docopt` creates your command-line interface based on its
description that you pass as `doc`. Such description can contain
--options, <positional-argument>, commands, which could be
[optional], (required), (mutually | exclusive) or repeated...
Parameters
----------
doc : str
Description of your command-line interface.
argv : list of str, optional
Argument vector to be parsed. sys.argv[1:] is used if not
provided.
help : bool (default: True)
Set to False to disable automatic help on -h or --help
options.
version : any object
If passed, the object will be printed if --version is in
`argv`.
options_first : bool (default: False)
Set to True to require options precede positional arguments,
i.e. to forbid options and positional arguments intermix.
Returns
-------
args : dict
A dictionary, where keys are names of command-line elements
such as e.g. "--verbose" and "<path>", and values are the
parsed values of those elements.
Example
-------
>>> from docopt import docopt
>>> doc = '''
... Usage:
... my_program tcp <host> <port> [--timeout=<seconds>]
... my_program serial <port> [--baud=<n>] [--timeout=<seconds>]
... my_program (-h | --help | --version)
...
... Options:
... -h, --help Show this screen and exit.
... --baud=<n> Baudrate [default: 9600]
... '''
>>> argv = ['tcp', '127.0.0.1', '80', '--timeout', '30']
>>> docopt(doc, argv)
{'--baud': '9600',
'--help': False,
'--timeout': '30',
'--version': False,
'<host>': '127.0.0.1',
'<port>': '80',
'serial': False,
'tcp': True}
See also
--------
* For video introduction see http://docopt.org
* Full documentation is available in README.rst as well as online
at https://github.com/docopt/docopt#readme
"""
argv = sys.argv[1:] if argv is None else argv
usage_sections = parse_section('usage:', doc)
if len(usage_sections) == 0:
raise DocoptLanguageError('"usage:" (case-insensitive) not found.')
if len(usage_sections) > 1:
raise DocoptLanguageError('More than one "usage:" (case-insensitive).')
DocoptExit.usage = usage_sections[0]
options = parse_defaults(doc)
pattern = parse_pattern(formal_usage(DocoptExit.usage), options)
# [default] syntax for argument is disabled
#for a in pattern.flat(Argument):
# same_name = [d for d in arguments if d.name == a.name]
# if same_name:
# a.value = same_name[0].value
argv = parse_argv(Tokens(argv), list(options), options_first)
pattern_options = set(pattern.flat(Option))
for options_shortcut in pattern.flat(OptionsShortcut):
doc_options = parse_defaults(doc)
options_shortcut.children = list(set(doc_options) - pattern_options)
#if any_options:
# options_shortcut.children += [Option(o.short, o.long, o.argcount)
# for o in argv if type(o) is Option]
extras(help, version, argv, doc)
matched, left, collected = pattern.fix().match(argv)
if matched and left == []: # better error message if left?
return Dict((a.name, a.value) for a in (pattern.flat() + collected))
raise DocoptExit()
|
sloria/konch | docopt.py | parse_long | python | def parse_long(tokens, options):
long, eq, value = tokens.move().partition('=')
assert long.startswith('--')
value = None if eq == value == '' else value
similar = [o for o in options if o.long == long]
if tokens.error is DocoptExit and similar == []: # if no exact match
similar = [o for o in options if o.long and o.long.startswith(long)]
if len(similar) > 1: # might be simply specified ambiguously 2+ times?
raise tokens.error('%s is not a unique prefix: %s?' %
(long, ', '.join(o.long for o in similar)))
elif len(similar) < 1:
argcount = 1 if eq == '=' else 0
o = Option(None, long, argcount)
options.append(o)
if tokens.error is DocoptExit:
o = Option(None, long, argcount, value if argcount else True)
else:
o = Option(similar[0].short, similar[0].long,
similar[0].argcount, similar[0].value)
if o.argcount == 0:
if value is not None:
raise tokens.error('%s must not have an argument' % o.long)
else:
if value is None:
if tokens.current() in [None, '--']:
raise tokens.error('%s requires argument' % o.long)
value = tokens.move()
if tokens.error is DocoptExit:
o.value = value if value is not None else True
return [o] | long ::= '--' chars [ ( ' ' | '=' ) chars ] ; | train | https://github.com/sloria/konch/blob/15160bd0a0cac967eeeab84794bd6cdd0b5b637d/docopt.py#L302-L332 | null | # flake8: noqa
"""Pythonic command-line interface parser that will make you smile.
* http://docopt.org
* Repository and issue-tracker: https://github.com/docopt/docopt
* Licensed under terms of MIT license (see LICENSE-MIT)
* Copyright (c) 2013 Vladimir Keleshev, vladimir@keleshev.com
"""
import sys
import re
__all__ = ['docopt']
__version__ = '0.6.2'
class DocoptLanguageError(Exception):
"""Error in construction of usage-message by developer."""
class DocoptExit(SystemExit):
"""Exit in case user invoked program with incorrect arguments."""
usage = ''
def __init__(self, message=''):
SystemExit.__init__(self, (message + '\n' + self.usage).strip())
class Pattern(object):
def __eq__(self, other):
return repr(self) == repr(other)
def __hash__(self):
return hash(repr(self))
def fix(self):
self.fix_identities()
self.fix_repeating_arguments()
return self
def fix_identities(self, uniq=None):
"""Make pattern-tree tips point to same object if they are equal."""
if not hasattr(self, 'children'):
return self
uniq = list(set(self.flat())) if uniq is None else uniq
for i, child in enumerate(self.children):
if not hasattr(child, 'children'):
assert child in uniq
self.children[i] = uniq[uniq.index(child)]
else:
child.fix_identities(uniq)
def fix_repeating_arguments(self):
"""Fix elements that should accumulate/increment values."""
either = [list(child.children) for child in transform(self).children]
for case in either:
for e in [child for child in case if case.count(child) > 1]:
if type(e) is Argument or type(e) is Option and e.argcount:
if e.value is None:
e.value = []
elif type(e.value) is not list:
e.value = e.value.split()
if type(e) is Command or type(e) is Option and e.argcount == 0:
e.value = 0
return self
def transform(pattern):
"""Expand pattern into an (almost) equivalent one, but with single Either.
Example: ((-a | -b) (-c | -d)) => (-a -c | -a -d | -b -c | -b -d)
Quirks: [-a] => (-a), (-a...) => (-a -a)
"""
result = []
groups = [[pattern]]
while groups:
children = groups.pop(0)
parents = [Required, Optional, OptionsShortcut, Either, OneOrMore]
if any(t in map(type, children) for t in parents):
child = [c for c in children if type(c) in parents][0]
children.remove(child)
if type(child) is Either:
for c in child.children:
groups.append([c] + children)
elif type(child) is OneOrMore:
groups.append(child.children * 2 + children)
else:
groups.append(child.children + children)
else:
result.append(children)
return Either(*[Required(*e) for e in result])
class LeafPattern(Pattern):
"""Leaf/terminal node of a pattern tree."""
def __init__(self, name, value=None):
self.name, self.value = name, value
def __repr__(self):
return '%s(%r, %r)' % (self.__class__.__name__, self.name, self.value)
def flat(self, *types):
return [self] if not types or type(self) in types else []
def match(self, left, collected=None):
collected = [] if collected is None else collected
pos, match = self.single_match(left)
if match is None:
return False, left, collected
left_ = left[:pos] + left[pos + 1:]
same_name = [a for a in collected if a.name == self.name]
if type(self.value) in (int, list):
if type(self.value) is int:
increment = 1
else:
increment = ([match.value] if type(match.value) is str
else match.value)
if not same_name:
match.value = increment
return True, left_, collected + [match]
same_name[0].value += increment
return True, left_, collected
return True, left_, collected + [match]
class BranchPattern(Pattern):
"""Branch/inner node of a pattern tree."""
def __init__(self, *children):
self.children = list(children)
def __repr__(self):
return '%s(%s)' % (self.__class__.__name__,
', '.join(repr(a) for a in self.children))
def flat(self, *types):
if type(self) in types:
return [self]
return sum([child.flat(*types) for child in self.children], [])
class Argument(LeafPattern):
def single_match(self, left):
for n, pattern in enumerate(left):
if type(pattern) is Argument:
return n, Argument(self.name, pattern.value)
return None, None
@classmethod
def parse(class_, source):
name = re.findall('(<\S*?>)', source)[0]
value = re.findall('\[default: (.*)\]', source, flags=re.I)
return class_(name, value[0] if value else None)
class Command(Argument):
def __init__(self, name, value=False):
self.name, self.value = name, value
def single_match(self, left):
for n, pattern in enumerate(left):
if type(pattern) is Argument:
if pattern.value == self.name:
return n, Command(self.name, True)
else:
break
return None, None
class Option(LeafPattern):
def __init__(self, short=None, long=None, argcount=0, value=False):
assert argcount in (0, 1)
self.short, self.long, self.argcount = short, long, argcount
self.value = None if value is False and argcount else value
@classmethod
def parse(class_, option_description):
short, long, argcount, value = None, None, 0, False
options, _, description = option_description.strip().partition(' ')
options = options.replace(',', ' ').replace('=', ' ')
for s in options.split():
if s.startswith('--'):
long = s
elif s.startswith('-'):
short = s
else:
argcount = 1
if argcount:
matched = re.findall('\[default: (.*)\]', description, flags=re.I)
value = matched[0] if matched else None
return class_(short, long, argcount, value)
def single_match(self, left):
for n, pattern in enumerate(left):
if self.name == pattern.name:
return n, pattern
return None, None
@property
def name(self):
return self.long or self.short
def __repr__(self):
return 'Option(%r, %r, %r, %r)' % (self.short, self.long,
self.argcount, self.value)
class Required(BranchPattern):
def match(self, left, collected=None):
collected = [] if collected is None else collected
l = left
c = collected
for pattern in self.children:
matched, l, c = pattern.match(l, c)
if not matched:
return False, left, collected
return True, l, c
class Optional(BranchPattern):
def match(self, left, collected=None):
collected = [] if collected is None else collected
for pattern in self.children:
m, left, collected = pattern.match(left, collected)
return True, left, collected
class OptionsShortcut(Optional):
"""Marker/placeholder for [options] shortcut."""
class OneOrMore(BranchPattern):
def match(self, left, collected=None):
assert len(self.children) == 1
collected = [] if collected is None else collected
l = left
c = collected
l_ = None
matched = True
times = 0
while matched:
# could it be that something didn't match but changed l or c?
matched, l, c = self.children[0].match(l, c)
times += 1 if matched else 0
if l_ == l:
break
l_ = l
if times >= 1:
return True, l, c
return False, left, collected
class Either(BranchPattern):
def match(self, left, collected=None):
collected = [] if collected is None else collected
outcomes = []
for pattern in self.children:
matched, _, _ = outcome = pattern.match(left, collected)
if matched:
outcomes.append(outcome)
if outcomes:
return min(outcomes, key=lambda outcome: len(outcome[1]))
return False, left, collected
class Tokens(list):
def __init__(self, source, error=DocoptExit):
self += source.split() if hasattr(source, 'split') else source
self.error = error
@staticmethod
def from_pattern(source):
source = re.sub(r'([\[\]\(\)\|]|\.\.\.)', r' \1 ', source)
source = [s for s in re.split('\s+|(\S*<.*?>)', source) if s]
return Tokens(source, error=DocoptLanguageError)
def move(self):
return self.pop(0) if len(self) else None
def current(self):
return self[0] if len(self) else None
def parse_shorts(tokens, options):
"""shorts ::= '-' ( chars )* [ [ ' ' ] chars ] ;"""
token = tokens.move()
assert token.startswith('-') and not token.startswith('--')
left = token.lstrip('-')
parsed = []
while left != '':
short, left = '-' + left[0], left[1:]
similar = [o for o in options if o.short == short]
if len(similar) > 1:
raise tokens.error('%s is specified ambiguously %d times' %
(short, len(similar)))
elif len(similar) < 1:
o = Option(short, None, 0)
options.append(o)
if tokens.error is DocoptExit:
o = Option(short, None, 0, True)
else: # why copying is necessary here?
o = Option(short, similar[0].long,
similar[0].argcount, similar[0].value)
value = None
if o.argcount != 0:
if left == '':
if tokens.current() in [None, '--']:
raise tokens.error('%s requires argument' % short)
value = tokens.move()
else:
value = left
left = ''
if tokens.error is DocoptExit:
o.value = value if value is not None else True
parsed.append(o)
return parsed
def parse_pattern(source, options):
tokens = Tokens.from_pattern(source)
result = parse_expr(tokens, options)
if tokens.current() is not None:
raise tokens.error('unexpected ending: %r' % ' '.join(tokens))
return Required(*result)
def parse_expr(tokens, options):
"""expr ::= seq ( '|' seq )* ;"""
seq = parse_seq(tokens, options)
if tokens.current() != '|':
return seq
result = [Required(*seq)] if len(seq) > 1 else seq
while tokens.current() == '|':
tokens.move()
seq = parse_seq(tokens, options)
result += [Required(*seq)] if len(seq) > 1 else seq
return [Either(*result)] if len(result) > 1 else result
def parse_seq(tokens, options):
"""seq ::= ( atom [ '...' ] )* ;"""
result = []
while tokens.current() not in [None, ']', ')', '|']:
atom = parse_atom(tokens, options)
if tokens.current() == '...':
atom = [OneOrMore(*atom)]
tokens.move()
result += atom
return result
def parse_atom(tokens, options):
"""atom ::= '(' expr ')' | '[' expr ']' | 'options'
| long | shorts | argument | command ;
"""
token = tokens.current()
result = []
if token in '([':
tokens.move()
matching, pattern = {'(': [')', Required], '[': [']', Optional]}[token]
result = pattern(*parse_expr(tokens, options))
if tokens.move() != matching:
raise tokens.error("unmatched '%s'" % token)
return [result]
elif token == 'options':
tokens.move()
return [OptionsShortcut()]
elif token.startswith('--') and token != '--':
return parse_long(tokens, options)
elif token.startswith('-') and token not in ('-', '--'):
return parse_shorts(tokens, options)
elif token.startswith('<') and token.endswith('>') or token.isupper():
return [Argument(tokens.move())]
else:
return [Command(tokens.move())]
def parse_argv(tokens, options, options_first=False):
"""Parse command-line argument vector.
If options_first:
argv ::= [ long | shorts ]* [ argument ]* [ '--' [ argument ]* ] ;
else:
argv ::= [ long | shorts | argument ]* [ '--' [ argument ]* ] ;
"""
parsed = []
while tokens.current() is not None:
if tokens.current() == '--':
return parsed + [Argument(None, v) for v in tokens]
elif tokens.current().startswith('--'):
parsed += parse_long(tokens, options)
elif tokens.current().startswith('-') and tokens.current() != '-':
parsed += parse_shorts(tokens, options)
elif options_first:
return parsed + [Argument(None, v) for v in tokens]
else:
parsed.append(Argument(None, tokens.move()))
return parsed
def parse_defaults(doc):
defaults = []
for s in parse_section('options:', doc):
# FIXME corner case "bla: options: --foo"
_, _, s = s.partition(':') # get rid of "options:"
split = re.split('\n[ \t]*(-\S+?)', '\n' + s)[1:]
split = [s1 + s2 for s1, s2 in zip(split[::2], split[1::2])]
options = [Option.parse(s) for s in split if s.startswith('-')]
defaults += options
return defaults
def parse_section(name, source):
pattern = re.compile('^([^\n]*' + name + '[^\n]*\n?(?:[ \t].*?(?:\n|$))*)',
re.IGNORECASE | re.MULTILINE)
return [s.strip() for s in pattern.findall(source)]
def formal_usage(section):
_, _, section = section.partition(':') # drop "usage:"
pu = section.split()
return '( ' + ' '.join(') | (' if s == pu[0] else s for s in pu[1:]) + ' )'
def extras(help, version, options, doc):
if help and any((o.name in ('-h', '--help')) and o.value for o in options):
print(doc.strip("\n"))
sys.exit()
if version and any(o.name == '--version' and o.value for o in options):
print(version)
sys.exit()
class Dict(dict):
def __repr__(self):
return '{%s}' % ',\n '.join('%r: %r' % i for i in sorted(self.items()))
def docopt(doc, argv=None, help=True, version=None, options_first=False):
"""Parse `argv` based on command-line interface described in `doc`.
`docopt` creates your command-line interface based on its
description that you pass as `doc`. Such description can contain
--options, <positional-argument>, commands, which could be
[optional], (required), (mutually | exclusive) or repeated...
Parameters
----------
doc : str
Description of your command-line interface.
argv : list of str, optional
Argument vector to be parsed. sys.argv[1:] is used if not
provided.
help : bool (default: True)
Set to False to disable automatic help on -h or --help
options.
version : any object
If passed, the object will be printed if --version is in
`argv`.
options_first : bool (default: False)
Set to True to require options precede positional arguments,
i.e. to forbid options and positional arguments intermix.
Returns
-------
args : dict
A dictionary, where keys are names of command-line elements
such as e.g. "--verbose" and "<path>", and values are the
parsed values of those elements.
Example
-------
>>> from docopt import docopt
>>> doc = '''
... Usage:
... my_program tcp <host> <port> [--timeout=<seconds>]
... my_program serial <port> [--baud=<n>] [--timeout=<seconds>]
... my_program (-h | --help | --version)
...
... Options:
... -h, --help Show this screen and exit.
... --baud=<n> Baudrate [default: 9600]
... '''
>>> argv = ['tcp', '127.0.0.1', '80', '--timeout', '30']
>>> docopt(doc, argv)
{'--baud': '9600',
'--help': False,
'--timeout': '30',
'--version': False,
'<host>': '127.0.0.1',
'<port>': '80',
'serial': False,
'tcp': True}
See also
--------
* For video introduction see http://docopt.org
* Full documentation is available in README.rst as well as online
at https://github.com/docopt/docopt#readme
"""
argv = sys.argv[1:] if argv is None else argv
usage_sections = parse_section('usage:', doc)
if len(usage_sections) == 0:
raise DocoptLanguageError('"usage:" (case-insensitive) not found.')
if len(usage_sections) > 1:
raise DocoptLanguageError('More than one "usage:" (case-insensitive).')
DocoptExit.usage = usage_sections[0]
options = parse_defaults(doc)
pattern = parse_pattern(formal_usage(DocoptExit.usage), options)
# [default] syntax for argument is disabled
#for a in pattern.flat(Argument):
# same_name = [d for d in arguments if d.name == a.name]
# if same_name:
# a.value = same_name[0].value
argv = parse_argv(Tokens(argv), list(options), options_first)
pattern_options = set(pattern.flat(Option))
for options_shortcut in pattern.flat(OptionsShortcut):
doc_options = parse_defaults(doc)
options_shortcut.children = list(set(doc_options) - pattern_options)
#if any_options:
# options_shortcut.children += [Option(o.short, o.long, o.argcount)
# for o in argv if type(o) is Option]
extras(help, version, argv, doc)
matched, left, collected = pattern.fix().match(argv)
if matched and left == []: # better error message if left?
return Dict((a.name, a.value) for a in (pattern.flat() + collected))
raise DocoptExit()
|
sloria/konch | docopt.py | parse_shorts | python | def parse_shorts(tokens, options):
token = tokens.move()
assert token.startswith('-') and not token.startswith('--')
left = token.lstrip('-')
parsed = []
while left != '':
short, left = '-' + left[0], left[1:]
similar = [o for o in options if o.short == short]
if len(similar) > 1:
raise tokens.error('%s is specified ambiguously %d times' %
(short, len(similar)))
elif len(similar) < 1:
o = Option(short, None, 0)
options.append(o)
if tokens.error is DocoptExit:
o = Option(short, None, 0, True)
else: # why copying is necessary here?
o = Option(short, similar[0].long,
similar[0].argcount, similar[0].value)
value = None
if o.argcount != 0:
if left == '':
if tokens.current() in [None, '--']:
raise tokens.error('%s requires argument' % short)
value = tokens.move()
else:
value = left
left = ''
if tokens.error is DocoptExit:
o.value = value if value is not None else True
parsed.append(o)
return parsed | shorts ::= '-' ( chars )* [ [ ' ' ] chars ] ; | train | https://github.com/sloria/konch/blob/15160bd0a0cac967eeeab84794bd6cdd0b5b637d/docopt.py#L335-L367 | null | # flake8: noqa
"""Pythonic command-line interface parser that will make you smile.
* http://docopt.org
* Repository and issue-tracker: https://github.com/docopt/docopt
* Licensed under terms of MIT license (see LICENSE-MIT)
* Copyright (c) 2013 Vladimir Keleshev, vladimir@keleshev.com
"""
import sys
import re
__all__ = ['docopt']
__version__ = '0.6.2'
class DocoptLanguageError(Exception):
"""Error in construction of usage-message by developer."""
class DocoptExit(SystemExit):
"""Exit in case user invoked program with incorrect arguments."""
usage = ''
def __init__(self, message=''):
SystemExit.__init__(self, (message + '\n' + self.usage).strip())
class Pattern(object):
def __eq__(self, other):
return repr(self) == repr(other)
def __hash__(self):
return hash(repr(self))
def fix(self):
self.fix_identities()
self.fix_repeating_arguments()
return self
def fix_identities(self, uniq=None):
"""Make pattern-tree tips point to same object if they are equal."""
if not hasattr(self, 'children'):
return self
uniq = list(set(self.flat())) if uniq is None else uniq
for i, child in enumerate(self.children):
if not hasattr(child, 'children'):
assert child in uniq
self.children[i] = uniq[uniq.index(child)]
else:
child.fix_identities(uniq)
def fix_repeating_arguments(self):
"""Fix elements that should accumulate/increment values."""
either = [list(child.children) for child in transform(self).children]
for case in either:
for e in [child for child in case if case.count(child) > 1]:
if type(e) is Argument or type(e) is Option and e.argcount:
if e.value is None:
e.value = []
elif type(e.value) is not list:
e.value = e.value.split()
if type(e) is Command or type(e) is Option and e.argcount == 0:
e.value = 0
return self
def transform(pattern):
"""Expand pattern into an (almost) equivalent one, but with single Either.
Example: ((-a | -b) (-c | -d)) => (-a -c | -a -d | -b -c | -b -d)
Quirks: [-a] => (-a), (-a...) => (-a -a)
"""
result = []
groups = [[pattern]]
while groups:
children = groups.pop(0)
parents = [Required, Optional, OptionsShortcut, Either, OneOrMore]
if any(t in map(type, children) for t in parents):
child = [c for c in children if type(c) in parents][0]
children.remove(child)
if type(child) is Either:
for c in child.children:
groups.append([c] + children)
elif type(child) is OneOrMore:
groups.append(child.children * 2 + children)
else:
groups.append(child.children + children)
else:
result.append(children)
return Either(*[Required(*e) for e in result])
class LeafPattern(Pattern):
"""Leaf/terminal node of a pattern tree."""
def __init__(self, name, value=None):
self.name, self.value = name, value
def __repr__(self):
return '%s(%r, %r)' % (self.__class__.__name__, self.name, self.value)
def flat(self, *types):
return [self] if not types or type(self) in types else []
def match(self, left, collected=None):
collected = [] if collected is None else collected
pos, match = self.single_match(left)
if match is None:
return False, left, collected
left_ = left[:pos] + left[pos + 1:]
same_name = [a for a in collected if a.name == self.name]
if type(self.value) in (int, list):
if type(self.value) is int:
increment = 1
else:
increment = ([match.value] if type(match.value) is str
else match.value)
if not same_name:
match.value = increment
return True, left_, collected + [match]
same_name[0].value += increment
return True, left_, collected
return True, left_, collected + [match]
class BranchPattern(Pattern):
"""Branch/inner node of a pattern tree."""
def __init__(self, *children):
self.children = list(children)
def __repr__(self):
return '%s(%s)' % (self.__class__.__name__,
', '.join(repr(a) for a in self.children))
def flat(self, *types):
if type(self) in types:
return [self]
return sum([child.flat(*types) for child in self.children], [])
class Argument(LeafPattern):
def single_match(self, left):
for n, pattern in enumerate(left):
if type(pattern) is Argument:
return n, Argument(self.name, pattern.value)
return None, None
@classmethod
def parse(class_, source):
name = re.findall('(<\S*?>)', source)[0]
value = re.findall('\[default: (.*)\]', source, flags=re.I)
return class_(name, value[0] if value else None)
class Command(Argument):
def __init__(self, name, value=False):
self.name, self.value = name, value
def single_match(self, left):
for n, pattern in enumerate(left):
if type(pattern) is Argument:
if pattern.value == self.name:
return n, Command(self.name, True)
else:
break
return None, None
class Option(LeafPattern):
def __init__(self, short=None, long=None, argcount=0, value=False):
assert argcount in (0, 1)
self.short, self.long, self.argcount = short, long, argcount
self.value = None if value is False and argcount else value
@classmethod
def parse(class_, option_description):
short, long, argcount, value = None, None, 0, False
options, _, description = option_description.strip().partition(' ')
options = options.replace(',', ' ').replace('=', ' ')
for s in options.split():
if s.startswith('--'):
long = s
elif s.startswith('-'):
short = s
else:
argcount = 1
if argcount:
matched = re.findall('\[default: (.*)\]', description, flags=re.I)
value = matched[0] if matched else None
return class_(short, long, argcount, value)
def single_match(self, left):
for n, pattern in enumerate(left):
if self.name == pattern.name:
return n, pattern
return None, None
@property
def name(self):
return self.long or self.short
def __repr__(self):
return 'Option(%r, %r, %r, %r)' % (self.short, self.long,
self.argcount, self.value)
class Required(BranchPattern):
def match(self, left, collected=None):
collected = [] if collected is None else collected
l = left
c = collected
for pattern in self.children:
matched, l, c = pattern.match(l, c)
if not matched:
return False, left, collected
return True, l, c
class Optional(BranchPattern):
def match(self, left, collected=None):
collected = [] if collected is None else collected
for pattern in self.children:
m, left, collected = pattern.match(left, collected)
return True, left, collected
class OptionsShortcut(Optional):
"""Marker/placeholder for [options] shortcut."""
class OneOrMore(BranchPattern):
def match(self, left, collected=None):
assert len(self.children) == 1
collected = [] if collected is None else collected
l = left
c = collected
l_ = None
matched = True
times = 0
while matched:
# could it be that something didn't match but changed l or c?
matched, l, c = self.children[0].match(l, c)
times += 1 if matched else 0
if l_ == l:
break
l_ = l
if times >= 1:
return True, l, c
return False, left, collected
class Either(BranchPattern):
def match(self, left, collected=None):
collected = [] if collected is None else collected
outcomes = []
for pattern in self.children:
matched, _, _ = outcome = pattern.match(left, collected)
if matched:
outcomes.append(outcome)
if outcomes:
return min(outcomes, key=lambda outcome: len(outcome[1]))
return False, left, collected
class Tokens(list):
def __init__(self, source, error=DocoptExit):
self += source.split() if hasattr(source, 'split') else source
self.error = error
@staticmethod
def from_pattern(source):
source = re.sub(r'([\[\]\(\)\|]|\.\.\.)', r' \1 ', source)
source = [s for s in re.split('\s+|(\S*<.*?>)', source) if s]
return Tokens(source, error=DocoptLanguageError)
def move(self):
return self.pop(0) if len(self) else None
def current(self):
return self[0] if len(self) else None
def parse_long(tokens, options):
"""long ::= '--' chars [ ( ' ' | '=' ) chars ] ;"""
long, eq, value = tokens.move().partition('=')
assert long.startswith('--')
value = None if eq == value == '' else value
similar = [o for o in options if o.long == long]
if tokens.error is DocoptExit and similar == []: # if no exact match
similar = [o for o in options if o.long and o.long.startswith(long)]
if len(similar) > 1: # might be simply specified ambiguously 2+ times?
raise tokens.error('%s is not a unique prefix: %s?' %
(long, ', '.join(o.long for o in similar)))
elif len(similar) < 1:
argcount = 1 if eq == '=' else 0
o = Option(None, long, argcount)
options.append(o)
if tokens.error is DocoptExit:
o = Option(None, long, argcount, value if argcount else True)
else:
o = Option(similar[0].short, similar[0].long,
similar[0].argcount, similar[0].value)
if o.argcount == 0:
if value is not None:
raise tokens.error('%s must not have an argument' % o.long)
else:
if value is None:
if tokens.current() in [None, '--']:
raise tokens.error('%s requires argument' % o.long)
value = tokens.move()
if tokens.error is DocoptExit:
o.value = value if value is not None else True
return [o]
def parse_pattern(source, options):
tokens = Tokens.from_pattern(source)
result = parse_expr(tokens, options)
if tokens.current() is not None:
raise tokens.error('unexpected ending: %r' % ' '.join(tokens))
return Required(*result)
def parse_expr(tokens, options):
"""expr ::= seq ( '|' seq )* ;"""
seq = parse_seq(tokens, options)
if tokens.current() != '|':
return seq
result = [Required(*seq)] if len(seq) > 1 else seq
while tokens.current() == '|':
tokens.move()
seq = parse_seq(tokens, options)
result += [Required(*seq)] if len(seq) > 1 else seq
return [Either(*result)] if len(result) > 1 else result
def parse_seq(tokens, options):
"""seq ::= ( atom [ '...' ] )* ;"""
result = []
while tokens.current() not in [None, ']', ')', '|']:
atom = parse_atom(tokens, options)
if tokens.current() == '...':
atom = [OneOrMore(*atom)]
tokens.move()
result += atom
return result
def parse_atom(tokens, options):
"""atom ::= '(' expr ')' | '[' expr ']' | 'options'
| long | shorts | argument | command ;
"""
token = tokens.current()
result = []
if token in '([':
tokens.move()
matching, pattern = {'(': [')', Required], '[': [']', Optional]}[token]
result = pattern(*parse_expr(tokens, options))
if tokens.move() != matching:
raise tokens.error("unmatched '%s'" % token)
return [result]
elif token == 'options':
tokens.move()
return [OptionsShortcut()]
elif token.startswith('--') and token != '--':
return parse_long(tokens, options)
elif token.startswith('-') and token not in ('-', '--'):
return parse_shorts(tokens, options)
elif token.startswith('<') and token.endswith('>') or token.isupper():
return [Argument(tokens.move())]
else:
return [Command(tokens.move())]
def parse_argv(tokens, options, options_first=False):
"""Parse command-line argument vector.
If options_first:
argv ::= [ long | shorts ]* [ argument ]* [ '--' [ argument ]* ] ;
else:
argv ::= [ long | shorts | argument ]* [ '--' [ argument ]* ] ;
"""
parsed = []
while tokens.current() is not None:
if tokens.current() == '--':
return parsed + [Argument(None, v) for v in tokens]
elif tokens.current().startswith('--'):
parsed += parse_long(tokens, options)
elif tokens.current().startswith('-') and tokens.current() != '-':
parsed += parse_shorts(tokens, options)
elif options_first:
return parsed + [Argument(None, v) for v in tokens]
else:
parsed.append(Argument(None, tokens.move()))
return parsed
def parse_defaults(doc):
defaults = []
for s in parse_section('options:', doc):
# FIXME corner case "bla: options: --foo"
_, _, s = s.partition(':') # get rid of "options:"
split = re.split('\n[ \t]*(-\S+?)', '\n' + s)[1:]
split = [s1 + s2 for s1, s2 in zip(split[::2], split[1::2])]
options = [Option.parse(s) for s in split if s.startswith('-')]
defaults += options
return defaults
def parse_section(name, source):
pattern = re.compile('^([^\n]*' + name + '[^\n]*\n?(?:[ \t].*?(?:\n|$))*)',
re.IGNORECASE | re.MULTILINE)
return [s.strip() for s in pattern.findall(source)]
def formal_usage(section):
_, _, section = section.partition(':') # drop "usage:"
pu = section.split()
return '( ' + ' '.join(') | (' if s == pu[0] else s for s in pu[1:]) + ' )'
def extras(help, version, options, doc):
if help and any((o.name in ('-h', '--help')) and o.value for o in options):
print(doc.strip("\n"))
sys.exit()
if version and any(o.name == '--version' and o.value for o in options):
print(version)
sys.exit()
class Dict(dict):
def __repr__(self):
return '{%s}' % ',\n '.join('%r: %r' % i for i in sorted(self.items()))
def docopt(doc, argv=None, help=True, version=None, options_first=False):
"""Parse `argv` based on command-line interface described in `doc`.
`docopt` creates your command-line interface based on its
description that you pass as `doc`. Such description can contain
--options, <positional-argument>, commands, which could be
[optional], (required), (mutually | exclusive) or repeated...
Parameters
----------
doc : str
Description of your command-line interface.
argv : list of str, optional
Argument vector to be parsed. sys.argv[1:] is used if not
provided.
help : bool (default: True)
Set to False to disable automatic help on -h or --help
options.
version : any object
If passed, the object will be printed if --version is in
`argv`.
options_first : bool (default: False)
Set to True to require options precede positional arguments,
i.e. to forbid options and positional arguments intermix.
Returns
-------
args : dict
A dictionary, where keys are names of command-line elements
such as e.g. "--verbose" and "<path>", and values are the
parsed values of those elements.
Example
-------
>>> from docopt import docopt
>>> doc = '''
... Usage:
... my_program tcp <host> <port> [--timeout=<seconds>]
... my_program serial <port> [--baud=<n>] [--timeout=<seconds>]
... my_program (-h | --help | --version)
...
... Options:
... -h, --help Show this screen and exit.
... --baud=<n> Baudrate [default: 9600]
... '''
>>> argv = ['tcp', '127.0.0.1', '80', '--timeout', '30']
>>> docopt(doc, argv)
{'--baud': '9600',
'--help': False,
'--timeout': '30',
'--version': False,
'<host>': '127.0.0.1',
'<port>': '80',
'serial': False,
'tcp': True}
See also
--------
* For video introduction see http://docopt.org
* Full documentation is available in README.rst as well as online
at https://github.com/docopt/docopt#readme
"""
argv = sys.argv[1:] if argv is None else argv
usage_sections = parse_section('usage:', doc)
if len(usage_sections) == 0:
raise DocoptLanguageError('"usage:" (case-insensitive) not found.')
if len(usage_sections) > 1:
raise DocoptLanguageError('More than one "usage:" (case-insensitive).')
DocoptExit.usage = usage_sections[0]
options = parse_defaults(doc)
pattern = parse_pattern(formal_usage(DocoptExit.usage), options)
# [default] syntax for argument is disabled
#for a in pattern.flat(Argument):
# same_name = [d for d in arguments if d.name == a.name]
# if same_name:
# a.value = same_name[0].value
argv = parse_argv(Tokens(argv), list(options), options_first)
pattern_options = set(pattern.flat(Option))
for options_shortcut in pattern.flat(OptionsShortcut):
doc_options = parse_defaults(doc)
options_shortcut.children = list(set(doc_options) - pattern_options)
#if any_options:
# options_shortcut.children += [Option(o.short, o.long, o.argcount)
# for o in argv if type(o) is Option]
extras(help, version, argv, doc)
matched, left, collected = pattern.fix().match(argv)
if matched and left == []: # better error message if left?
return Dict((a.name, a.value) for a in (pattern.flat() + collected))
raise DocoptExit()
|
sloria/konch | docopt.py | docopt | python | def docopt(doc, argv=None, help=True, version=None, options_first=False):
argv = sys.argv[1:] if argv is None else argv
usage_sections = parse_section('usage:', doc)
if len(usage_sections) == 0:
raise DocoptLanguageError('"usage:" (case-insensitive) not found.')
if len(usage_sections) > 1:
raise DocoptLanguageError('More than one "usage:" (case-insensitive).')
DocoptExit.usage = usage_sections[0]
options = parse_defaults(doc)
pattern = parse_pattern(formal_usage(DocoptExit.usage), options)
# [default] syntax for argument is disabled
#for a in pattern.flat(Argument):
# same_name = [d for d in arguments if d.name == a.name]
# if same_name:
# a.value = same_name[0].value
argv = parse_argv(Tokens(argv), list(options), options_first)
pattern_options = set(pattern.flat(Option))
for options_shortcut in pattern.flat(OptionsShortcut):
doc_options = parse_defaults(doc)
options_shortcut.children = list(set(doc_options) - pattern_options)
#if any_options:
# options_shortcut.children += [Option(o.short, o.long, o.argcount)
# for o in argv if type(o) is Option]
extras(help, version, argv, doc)
matched, left, collected = pattern.fix().match(argv)
if matched and left == []: # better error message if left?
return Dict((a.name, a.value) for a in (pattern.flat() + collected))
raise DocoptExit() | Parse `argv` based on command-line interface described in `doc`.
`docopt` creates your command-line interface based on its
description that you pass as `doc`. Such description can contain
--options, <positional-argument>, commands, which could be
[optional], (required), (mutually | exclusive) or repeated...
Parameters
----------
doc : str
Description of your command-line interface.
argv : list of str, optional
Argument vector to be parsed. sys.argv[1:] is used if not
provided.
help : bool (default: True)
Set to False to disable automatic help on -h or --help
options.
version : any object
If passed, the object will be printed if --version is in
`argv`.
options_first : bool (default: False)
Set to True to require options precede positional arguments,
i.e. to forbid options and positional arguments intermix.
Returns
-------
args : dict
A dictionary, where keys are names of command-line elements
such as e.g. "--verbose" and "<path>", and values are the
parsed values of those elements.
Example
-------
>>> from docopt import docopt
>>> doc = '''
... Usage:
... my_program tcp <host> <port> [--timeout=<seconds>]
... my_program serial <port> [--baud=<n>] [--timeout=<seconds>]
... my_program (-h | --help | --version)
...
... Options:
... -h, --help Show this screen and exit.
... --baud=<n> Baudrate [default: 9600]
... '''
>>> argv = ['tcp', '127.0.0.1', '80', '--timeout', '30']
>>> docopt(doc, argv)
{'--baud': '9600',
'--help': False,
'--timeout': '30',
'--version': False,
'<host>': '127.0.0.1',
'<port>': '80',
'serial': False,
'tcp': True}
See also
--------
* For video introduction see http://docopt.org
* Full documentation is available in README.rst as well as online
at https://github.com/docopt/docopt#readme | train | https://github.com/sloria/konch/blob/15160bd0a0cac967eeeab84794bd6cdd0b5b637d/docopt.py#L491-L582 | [
"def extras(help, version, options, doc):\n if help and any((o.name in ('-h', '--help')) and o.value for o in options):\n print(doc.strip(\"\\n\"))\n sys.exit()\n if version and any(o.name == '--version' and o.value for o in options):\n print(version)\n sys.exit()\n",
"def parse_pattern(source, options):\n tokens = Tokens.from_pattern(source)\n result = parse_expr(tokens, options)\n if tokens.current() is not None:\n raise tokens.error('unexpected ending: %r' % ' '.join(tokens))\n return Required(*result)\n",
"def parse_argv(tokens, options, options_first=False):\n \"\"\"Parse command-line argument vector.\n\n If options_first:\n argv ::= [ long | shorts ]* [ argument ]* [ '--' [ argument ]* ] ;\n else:\n argv ::= [ long | shorts | argument ]* [ '--' [ argument ]* ] ;\n\n \"\"\"\n parsed = []\n while tokens.current() is not None:\n if tokens.current() == '--':\n return parsed + [Argument(None, v) for v in tokens]\n elif tokens.current().startswith('--'):\n parsed += parse_long(tokens, options)\n elif tokens.current().startswith('-') and tokens.current() != '-':\n parsed += parse_shorts(tokens, options)\n elif options_first:\n return parsed + [Argument(None, v) for v in tokens]\n else:\n parsed.append(Argument(None, tokens.move()))\n return parsed\n",
"def parse_defaults(doc):\n defaults = []\n for s in parse_section('options:', doc):\n # FIXME corner case \"bla: options: --foo\"\n _, _, s = s.partition(':') # get rid of \"options:\"\n split = re.split('\\n[ \\t]*(-\\S+?)', '\\n' + s)[1:]\n split = [s1 + s2 for s1, s2 in zip(split[::2], split[1::2])]\n options = [Option.parse(s) for s in split if s.startswith('-')]\n defaults += options\n return defaults\n",
"def parse_section(name, source):\n pattern = re.compile('^([^\\n]*' + name + '[^\\n]*\\n?(?:[ \\t].*?(?:\\n|$))*)',\n re.IGNORECASE | re.MULTILINE)\n return [s.strip() for s in pattern.findall(source)]\n",
"def formal_usage(section):\n _, _, section = section.partition(':') # drop \"usage:\"\n pu = section.split()\n return '( ' + ' '.join(') | (' if s == pu[0] else s for s in pu[1:]) + ' )'\n",
"def fix(self):\n self.fix_identities()\n self.fix_repeating_arguments()\n return self\n",
"def flat(self, *types):\n if type(self) in types:\n return [self]\n return sum([child.flat(*types) for child in self.children], [])\n",
"def match(self, left, collected=None):\n collected = [] if collected is None else collected\n l = left\n c = collected\n for pattern in self.children:\n matched, l, c = pattern.match(l, c)\n if not matched:\n return False, left, collected\n return True, l, c\n"
] | # flake8: noqa
"""Pythonic command-line interface parser that will make you smile.
* http://docopt.org
* Repository and issue-tracker: https://github.com/docopt/docopt
* Licensed under terms of MIT license (see LICENSE-MIT)
* Copyright (c) 2013 Vladimir Keleshev, vladimir@keleshev.com
"""
import sys
import re
__all__ = ['docopt']
__version__ = '0.6.2'
class DocoptLanguageError(Exception):
"""Error in construction of usage-message by developer."""
class DocoptExit(SystemExit):
"""Exit in case user invoked program with incorrect arguments."""
usage = ''
def __init__(self, message=''):
SystemExit.__init__(self, (message + '\n' + self.usage).strip())
class Pattern(object):
def __eq__(self, other):
return repr(self) == repr(other)
def __hash__(self):
return hash(repr(self))
def fix(self):
self.fix_identities()
self.fix_repeating_arguments()
return self
def fix_identities(self, uniq=None):
"""Make pattern-tree tips point to same object if they are equal."""
if not hasattr(self, 'children'):
return self
uniq = list(set(self.flat())) if uniq is None else uniq
for i, child in enumerate(self.children):
if not hasattr(child, 'children'):
assert child in uniq
self.children[i] = uniq[uniq.index(child)]
else:
child.fix_identities(uniq)
def fix_repeating_arguments(self):
"""Fix elements that should accumulate/increment values."""
either = [list(child.children) for child in transform(self).children]
for case in either:
for e in [child for child in case if case.count(child) > 1]:
if type(e) is Argument or type(e) is Option and e.argcount:
if e.value is None:
e.value = []
elif type(e.value) is not list:
e.value = e.value.split()
if type(e) is Command or type(e) is Option and e.argcount == 0:
e.value = 0
return self
def transform(pattern):
"""Expand pattern into an (almost) equivalent one, but with single Either.
Example: ((-a | -b) (-c | -d)) => (-a -c | -a -d | -b -c | -b -d)
Quirks: [-a] => (-a), (-a...) => (-a -a)
"""
result = []
groups = [[pattern]]
while groups:
children = groups.pop(0)
parents = [Required, Optional, OptionsShortcut, Either, OneOrMore]
if any(t in map(type, children) for t in parents):
child = [c for c in children if type(c) in parents][0]
children.remove(child)
if type(child) is Either:
for c in child.children:
groups.append([c] + children)
elif type(child) is OneOrMore:
groups.append(child.children * 2 + children)
else:
groups.append(child.children + children)
else:
result.append(children)
return Either(*[Required(*e) for e in result])
class LeafPattern(Pattern):
"""Leaf/terminal node of a pattern tree."""
def __init__(self, name, value=None):
self.name, self.value = name, value
def __repr__(self):
return '%s(%r, %r)' % (self.__class__.__name__, self.name, self.value)
def flat(self, *types):
return [self] if not types or type(self) in types else []
def match(self, left, collected=None):
collected = [] if collected is None else collected
pos, match = self.single_match(left)
if match is None:
return False, left, collected
left_ = left[:pos] + left[pos + 1:]
same_name = [a for a in collected if a.name == self.name]
if type(self.value) in (int, list):
if type(self.value) is int:
increment = 1
else:
increment = ([match.value] if type(match.value) is str
else match.value)
if not same_name:
match.value = increment
return True, left_, collected + [match]
same_name[0].value += increment
return True, left_, collected
return True, left_, collected + [match]
class BranchPattern(Pattern):
"""Branch/inner node of a pattern tree."""
def __init__(self, *children):
self.children = list(children)
def __repr__(self):
return '%s(%s)' % (self.__class__.__name__,
', '.join(repr(a) for a in self.children))
def flat(self, *types):
if type(self) in types:
return [self]
return sum([child.flat(*types) for child in self.children], [])
class Argument(LeafPattern):
def single_match(self, left):
for n, pattern in enumerate(left):
if type(pattern) is Argument:
return n, Argument(self.name, pattern.value)
return None, None
@classmethod
def parse(class_, source):
name = re.findall('(<\S*?>)', source)[0]
value = re.findall('\[default: (.*)\]', source, flags=re.I)
return class_(name, value[0] if value else None)
class Command(Argument):
def __init__(self, name, value=False):
self.name, self.value = name, value
def single_match(self, left):
for n, pattern in enumerate(left):
if type(pattern) is Argument:
if pattern.value == self.name:
return n, Command(self.name, True)
else:
break
return None, None
class Option(LeafPattern):
def __init__(self, short=None, long=None, argcount=0, value=False):
assert argcount in (0, 1)
self.short, self.long, self.argcount = short, long, argcount
self.value = None if value is False and argcount else value
@classmethod
def parse(class_, option_description):
short, long, argcount, value = None, None, 0, False
options, _, description = option_description.strip().partition(' ')
options = options.replace(',', ' ').replace('=', ' ')
for s in options.split():
if s.startswith('--'):
long = s
elif s.startswith('-'):
short = s
else:
argcount = 1
if argcount:
matched = re.findall('\[default: (.*)\]', description, flags=re.I)
value = matched[0] if matched else None
return class_(short, long, argcount, value)
def single_match(self, left):
for n, pattern in enumerate(left):
if self.name == pattern.name:
return n, pattern
return None, None
@property
def name(self):
return self.long or self.short
def __repr__(self):
return 'Option(%r, %r, %r, %r)' % (self.short, self.long,
self.argcount, self.value)
class Required(BranchPattern):
def match(self, left, collected=None):
collected = [] if collected is None else collected
l = left
c = collected
for pattern in self.children:
matched, l, c = pattern.match(l, c)
if not matched:
return False, left, collected
return True, l, c
class Optional(BranchPattern):
def match(self, left, collected=None):
collected = [] if collected is None else collected
for pattern in self.children:
m, left, collected = pattern.match(left, collected)
return True, left, collected
class OptionsShortcut(Optional):
"""Marker/placeholder for [options] shortcut."""
class OneOrMore(BranchPattern):
def match(self, left, collected=None):
assert len(self.children) == 1
collected = [] if collected is None else collected
l = left
c = collected
l_ = None
matched = True
times = 0
while matched:
# could it be that something didn't match but changed l or c?
matched, l, c = self.children[0].match(l, c)
times += 1 if matched else 0
if l_ == l:
break
l_ = l
if times >= 1:
return True, l, c
return False, left, collected
class Either(BranchPattern):
def match(self, left, collected=None):
collected = [] if collected is None else collected
outcomes = []
for pattern in self.children:
matched, _, _ = outcome = pattern.match(left, collected)
if matched:
outcomes.append(outcome)
if outcomes:
return min(outcomes, key=lambda outcome: len(outcome[1]))
return False, left, collected
class Tokens(list):
def __init__(self, source, error=DocoptExit):
self += source.split() if hasattr(source, 'split') else source
self.error = error
@staticmethod
def from_pattern(source):
source = re.sub(r'([\[\]\(\)\|]|\.\.\.)', r' \1 ', source)
source = [s for s in re.split('\s+|(\S*<.*?>)', source) if s]
return Tokens(source, error=DocoptLanguageError)
def move(self):
return self.pop(0) if len(self) else None
def current(self):
return self[0] if len(self) else None
def parse_long(tokens, options):
"""long ::= '--' chars [ ( ' ' | '=' ) chars ] ;"""
long, eq, value = tokens.move().partition('=')
assert long.startswith('--')
value = None if eq == value == '' else value
similar = [o for o in options if o.long == long]
if tokens.error is DocoptExit and similar == []: # if no exact match
similar = [o for o in options if o.long and o.long.startswith(long)]
if len(similar) > 1: # might be simply specified ambiguously 2+ times?
raise tokens.error('%s is not a unique prefix: %s?' %
(long, ', '.join(o.long for o in similar)))
elif len(similar) < 1:
argcount = 1 if eq == '=' else 0
o = Option(None, long, argcount)
options.append(o)
if tokens.error is DocoptExit:
o = Option(None, long, argcount, value if argcount else True)
else:
o = Option(similar[0].short, similar[0].long,
similar[0].argcount, similar[0].value)
if o.argcount == 0:
if value is not None:
raise tokens.error('%s must not have an argument' % o.long)
else:
if value is None:
if tokens.current() in [None, '--']:
raise tokens.error('%s requires argument' % o.long)
value = tokens.move()
if tokens.error is DocoptExit:
o.value = value if value is not None else True
return [o]
def parse_shorts(tokens, options):
"""shorts ::= '-' ( chars )* [ [ ' ' ] chars ] ;"""
token = tokens.move()
assert token.startswith('-') and not token.startswith('--')
left = token.lstrip('-')
parsed = []
while left != '':
short, left = '-' + left[0], left[1:]
similar = [o for o in options if o.short == short]
if len(similar) > 1:
raise tokens.error('%s is specified ambiguously %d times' %
(short, len(similar)))
elif len(similar) < 1:
o = Option(short, None, 0)
options.append(o)
if tokens.error is DocoptExit:
o = Option(short, None, 0, True)
else: # why copying is necessary here?
o = Option(short, similar[0].long,
similar[0].argcount, similar[0].value)
value = None
if o.argcount != 0:
if left == '':
if tokens.current() in [None, '--']:
raise tokens.error('%s requires argument' % short)
value = tokens.move()
else:
value = left
left = ''
if tokens.error is DocoptExit:
o.value = value if value is not None else True
parsed.append(o)
return parsed
def parse_pattern(source, options):
tokens = Tokens.from_pattern(source)
result = parse_expr(tokens, options)
if tokens.current() is not None:
raise tokens.error('unexpected ending: %r' % ' '.join(tokens))
return Required(*result)
def parse_expr(tokens, options):
"""expr ::= seq ( '|' seq )* ;"""
seq = parse_seq(tokens, options)
if tokens.current() != '|':
return seq
result = [Required(*seq)] if len(seq) > 1 else seq
while tokens.current() == '|':
tokens.move()
seq = parse_seq(tokens, options)
result += [Required(*seq)] if len(seq) > 1 else seq
return [Either(*result)] if len(result) > 1 else result
def parse_seq(tokens, options):
"""seq ::= ( atom [ '...' ] )* ;"""
result = []
while tokens.current() not in [None, ']', ')', '|']:
atom = parse_atom(tokens, options)
if tokens.current() == '...':
atom = [OneOrMore(*atom)]
tokens.move()
result += atom
return result
def parse_atom(tokens, options):
"""atom ::= '(' expr ')' | '[' expr ']' | 'options'
| long | shorts | argument | command ;
"""
token = tokens.current()
result = []
if token in '([':
tokens.move()
matching, pattern = {'(': [')', Required], '[': [']', Optional]}[token]
result = pattern(*parse_expr(tokens, options))
if tokens.move() != matching:
raise tokens.error("unmatched '%s'" % token)
return [result]
elif token == 'options':
tokens.move()
return [OptionsShortcut()]
elif token.startswith('--') and token != '--':
return parse_long(tokens, options)
elif token.startswith('-') and token not in ('-', '--'):
return parse_shorts(tokens, options)
elif token.startswith('<') and token.endswith('>') or token.isupper():
return [Argument(tokens.move())]
else:
return [Command(tokens.move())]
def parse_argv(tokens, options, options_first=False):
"""Parse command-line argument vector.
If options_first:
argv ::= [ long | shorts ]* [ argument ]* [ '--' [ argument ]* ] ;
else:
argv ::= [ long | shorts | argument ]* [ '--' [ argument ]* ] ;
"""
parsed = []
while tokens.current() is not None:
if tokens.current() == '--':
return parsed + [Argument(None, v) for v in tokens]
elif tokens.current().startswith('--'):
parsed += parse_long(tokens, options)
elif tokens.current().startswith('-') and tokens.current() != '-':
parsed += parse_shorts(tokens, options)
elif options_first:
return parsed + [Argument(None, v) for v in tokens]
else:
parsed.append(Argument(None, tokens.move()))
return parsed
def parse_defaults(doc):
defaults = []
for s in parse_section('options:', doc):
# FIXME corner case "bla: options: --foo"
_, _, s = s.partition(':') # get rid of "options:"
split = re.split('\n[ \t]*(-\S+?)', '\n' + s)[1:]
split = [s1 + s2 for s1, s2 in zip(split[::2], split[1::2])]
options = [Option.parse(s) for s in split if s.startswith('-')]
defaults += options
return defaults
def parse_section(name, source):
pattern = re.compile('^([^\n]*' + name + '[^\n]*\n?(?:[ \t].*?(?:\n|$))*)',
re.IGNORECASE | re.MULTILINE)
return [s.strip() for s in pattern.findall(source)]
def formal_usage(section):
_, _, section = section.partition(':') # drop "usage:"
pu = section.split()
return '( ' + ' '.join(') | (' if s == pu[0] else s for s in pu[1:]) + ' )'
def extras(help, version, options, doc):
if help and any((o.name in ('-h', '--help')) and o.value for o in options):
print(doc.strip("\n"))
sys.exit()
if version and any(o.name == '--version' and o.value for o in options):
print(version)
sys.exit()
class Dict(dict):
def __repr__(self):
return '{%s}' % ',\n '.join('%r: %r' % i for i in sorted(self.items()))
|
sloria/konch | docopt.py | Pattern.fix_identities | python | def fix_identities(self, uniq=None):
if not hasattr(self, 'children'):
return self
uniq = list(set(self.flat())) if uniq is None else uniq
for i, child in enumerate(self.children):
if not hasattr(child, 'children'):
assert child in uniq
self.children[i] = uniq[uniq.index(child)]
else:
child.fix_identities(uniq) | Make pattern-tree tips point to same object if they are equal. | train | https://github.com/sloria/konch/blob/15160bd0a0cac967eeeab84794bd6cdd0b5b637d/docopt.py#L46-L56 | null | class Pattern(object):
def __eq__(self, other):
return repr(self) == repr(other)
def __hash__(self):
return hash(repr(self))
def fix(self):
self.fix_identities()
self.fix_repeating_arguments()
return self
def fix_repeating_arguments(self):
"""Fix elements that should accumulate/increment values."""
either = [list(child.children) for child in transform(self).children]
for case in either:
for e in [child for child in case if case.count(child) > 1]:
if type(e) is Argument or type(e) is Option and e.argcount:
if e.value is None:
e.value = []
elif type(e.value) is not list:
e.value = e.value.split()
if type(e) is Command or type(e) is Option and e.argcount == 0:
e.value = 0
return self
|
sloria/konch | docopt.py | Pattern.fix_repeating_arguments | python | def fix_repeating_arguments(self):
either = [list(child.children) for child in transform(self).children]
for case in either:
for e in [child for child in case if case.count(child) > 1]:
if type(e) is Argument or type(e) is Option and e.argcount:
if e.value is None:
e.value = []
elif type(e.value) is not list:
e.value = e.value.split()
if type(e) is Command or type(e) is Option and e.argcount == 0:
e.value = 0
return self | Fix elements that should accumulate/increment values. | train | https://github.com/sloria/konch/blob/15160bd0a0cac967eeeab84794bd6cdd0b5b637d/docopt.py#L58-L70 | [
"def transform(pattern):\n \"\"\"Expand pattern into an (almost) equivalent one, but with single Either.\n\n Example: ((-a | -b) (-c | -d)) => (-a -c | -a -d | -b -c | -b -d)\n Quirks: [-a] => (-a), (-a...) => (-a -a)\n\n \"\"\"\n result = []\n groups = [[pattern]]\n while groups:\n children = groups.pop(0)\n parents = [Required, Optional, OptionsShortcut, Either, OneOrMore]\n if any(t in map(type, children) for t in parents):\n child = [c for c in children if type(c) in parents][0]\n children.remove(child)\n if type(child) is Either:\n for c in child.children:\n groups.append([c] + children)\n elif type(child) is OneOrMore:\n groups.append(child.children * 2 + children)\n else:\n groups.append(child.children + children)\n else:\n result.append(children)\n return Either(*[Required(*e) for e in result])\n"
] | class Pattern(object):
def __eq__(self, other):
return repr(self) == repr(other)
def __hash__(self):
return hash(repr(self))
def fix(self):
self.fix_identities()
self.fix_repeating_arguments()
return self
def fix_identities(self, uniq=None):
"""Make pattern-tree tips point to same object if they are equal."""
if not hasattr(self, 'children'):
return self
uniq = list(set(self.flat())) if uniq is None else uniq
for i, child in enumerate(self.children):
if not hasattr(child, 'children'):
assert child in uniq
self.children[i] = uniq[uniq.index(child)]
else:
child.fix_identities(uniq)
|
sloria/konch | setup.py | find_version | python | def find_version(fname):
version = ""
with open(fname, "r") as fp:
reg = re.compile(r'__version__ = [\'"]([^\'"]*)[\'"]')
for line in fp:
m = reg.match(line)
if m:
version = m.group(1)
break
if not version:
raise RuntimeError("Cannot find version information")
return version | Attempts to find the version number in the file names fname.
Raises RuntimeError if not found. | train | https://github.com/sloria/konch/blob/15160bd0a0cac967eeeab84794bd6cdd0b5b637d/setup.py#L46-L60 | null | import re
from setuptools import setup, Command
EXTRAS_REQUIRE = {
"tests": ["pytest", "mock", "scripttest==1.3", "ipython", "bpython"],
"lint": [
"mypy==0.701",
"flake8==3.7.7",
"flake8-bugbear==19.3.0",
"pre-commit==1.15.2",
],
}
EXTRAS_REQUIRE["dev"] = (
EXTRAS_REQUIRE["tests"] + EXTRAS_REQUIRE["lint"] + ["ptpython", "tox"]
)
PYTHON_REQUIRES = ">=3.6"
class Shell(Command):
user_options = [
("name=", "n", "Named config to use."),
("shell=", "s", "Shell to use."),
("file=", "f", "File path of konch config file to execute."),
]
def initialize_options(self):
self.name = None
self.shell = None
self.file = None
def finalize_options(self):
pass
def run(self):
import konch
argv = []
for each in ("name", "shell", "file"):
opt = getattr(self, each)
if opt:
argv.append(f"--{each}={opt}")
konch.main(argv)
def read(fname):
with open(fname) as fp:
content = fp.read()
return content
setup(
name="konch",
version=find_version("konch.py"),
description=(
"CLI and configuration utility for the Python shell, optimized "
"for simplicity and productivity."
),
long_description=read("README.rst"),
author="Steven Loria",
author_email="sloria1@gmail.com",
url="https://github.com/sloria/konch",
install_requires=[],
cmdclass={"shell": Shell},
extras_require=EXTRAS_REQUIRE,
python_requires=PYTHON_REQUIRES,
license="MIT",
zip_safe=False,
keywords="konch shell custom ipython bpython repl ptpython ptipython",
classifiers=[
"Intended Audience :: Developers",
"License :: OSI Approved :: MIT License",
"Natural Language :: English",
"Programming Language :: Python :: 3",
"Programming Language :: Python :: 3.6",
"Programming Language :: Python :: 3.7",
"Topic :: System :: Shells",
],
py_modules=["konch", "docopt"],
entry_points={"console_scripts": ["konch = konch:main"]},
project_urls={
"Changelog": "https://konch.readthedocs.io/en/latest/changelog.html",
"Issues": "https://github.com/sloria/konch/issues",
"Source": "https://github.com/sloria/konch/",
},
)
|
sloria/konch | konch.py | format_context | python | def format_context(
context: Context, formatter: typing.Union[str, Formatter] = "full"
) -> str:
if not context:
return ""
if callable(formatter):
formatter_func = formatter
else:
if formatter in CONTEXT_FORMATTERS:
formatter_func = CONTEXT_FORMATTERS[formatter]
else:
raise ValueError(f'Invalid context format: "{formatter}"')
return formatter_func(context) | Output the a context dictionary as a string. | train | https://github.com/sloria/konch/blob/15160bd0a0cac967eeeab84794bd6cdd0b5b637d/konch.py#L245-L259 | [
"def my_formatter(ctx):\n return \"*\".join(sorted(ctx.keys()))\n"
] | #!/usr/bin/env python3
"""konch: Customizes your Python shell.
Usage:
konch
konch init [<config_file>] [-d]
konch edit [<config_file>] [-d]
konch allow [<config_file>] [-d]
konch deny [<config_file>] [-d]
konch [--name=<name>] [--file=<file>] [--shell=<shell_name>] [-d]
Options:
-h --help Show this screen.
-v --version Show version.
init Creates a starter .konchrc file.
edit Edit your .konchrc file.
-n --name=<name> Named config to use.
-s --shell=<shell_name> Shell to use. Can be either "ipy" (IPython),
"bpy" (BPython), "bpyc" (BPython Curses),
"ptpy" (PtPython), "ptipy" (PtIPython),
"py" (built-in Python shell), or "auto".
Overrides the 'shell' option in .konchrc.
-f --file=<file> File path of konch config file to execute. If not provided,
konch will use the .konchrc file in the current
directory.
-d --debug Enable debugging/verbose mode.
Environment variables:
KONCH_AUTH_FILE: File where to store authorization data for config files.
Defaults to ~/.local/share/konch_auth.
KONCH_EDITOR: Editor command to use when running `konch edit`.
Falls back to $VISUAL then $EDITOR.
NO_COLOR: Disable ANSI colors.
"""
from collections.abc import Iterable
from pathlib import Path
import code
import hashlib
import imp
import json
import logging
import os
import random
import subprocess
import sys
import typing
import types
import warnings
from docopt import docopt
__version__ = "4.2.1"
logger = logging.getLogger(__name__)
class KonchError(Exception):
pass
class ShellNotAvailableError(KonchError):
pass
class KonchrcNotAuthorizedError(KonchError):
pass
class KonchrcChangedError(KonchrcNotAuthorizedError):
pass
class AuthFile:
def __init__(self, data: typing.Dict[str, str]) -> None:
self.data = data
def __repr__(self) -> str:
return f"AuthFile({self.data!r})"
@classmethod
def load(cls, path: typing.Optional[Path] = None) -> "AuthFile":
filepath = path or cls.get_path()
try:
with Path(filepath).open("r", encoding="utf-8") as fp:
data = json.load(fp)
except FileNotFoundError:
data = {}
except json.JSONDecodeError as error:
# File exists but is empty
if error.doc.strip() == "":
data = {}
else:
raise
return cls(data)
def allow(self, filepath: Path) -> None:
logger.debug(f"Authorizing {filepath}")
self.data[str(Path(filepath).resolve())] = self._hash_file(filepath)
def deny(self, filepath: Path) -> None:
if not filepath.exists():
raise FileNotFoundError(f"{filepath} not found")
try:
logger.debug(f"Removing authorization for {filepath}")
del self.data[str(filepath.resolve())]
except KeyError:
pass
def check(
self, filepath: typing.Union[Path, None], raise_error: bool = True
) -> bool:
if not filepath:
return False
if str(filepath.resolve()) not in self.data:
if raise_error:
raise KonchrcNotAuthorizedError
else:
return False
else:
file_hash = self._hash_file(filepath)
if file_hash != self.data[str(filepath.resolve())]:
if raise_error:
raise KonchrcChangedError
else:
return False
return True
def save(self) -> None:
filepath = self.get_path()
filepath.parent.mkdir(parents=True, exist_ok=True)
with Path(filepath).open("w", encoding="utf-8") as fp:
json.dump(self.data, fp)
def __enter__(self) -> "AuthFile":
return self
def __exit__(
self,
exc_type: typing.Type[Exception],
exc_value: Exception,
exc_traceback: types.TracebackType,
) -> None:
if not exc_type:
self.save()
@staticmethod
def get_path() -> Path:
if "KONCH_AUTH_FILE" in os.environ:
return Path(os.environ["KONCH_AUTH_FILE"])
elif "XDG_DATA_HOME" in os.environ:
return Path(os.environ["XDG_DATA_HOME"]) / "konch_auth"
else:
return Path.home() / ".local" / "share" / "konch_auth"
@staticmethod
def _hash_file(filepath: Path) -> str:
# https://stackoverflow.com/a/22058673/1157536
BUF_SIZE = 65536 # read in 64kb chunks
sha1 = hashlib.sha1()
with Path(filepath).open("rb") as f:
while True:
data = f.read(BUF_SIZE)
if not data:
break
sha1.update(data) # type: ignore
return sha1.hexdigest()
RED = 31
GREEN = 32
YELLOW = 33
BOLD = 1
RESET_ALL = 0
def style(
text: str,
fg: typing.Optional[int] = None,
*,
bold: bool = False,
file: typing.IO = sys.stdout,
) -> str:
use_color = not os.environ.get("NO_COLOR") and file.isatty()
if use_color:
parts = [
fg and f"\033[{fg}m",
bold and f"\033[{BOLD}m",
text,
f"\033[{RESET_ALL}m",
]
return "".join([e for e in parts if e])
else:
return text
def sprint(text: str, *args: typing.Any, **kwargs: typing.Any) -> None:
file = kwargs.pop("file", sys.stdout)
return print(style(text, file=file, *args, **kwargs), file=file)
def print_error(text: str) -> None:
prefix = style("ERROR", RED, file=sys.stderr)
return sprint(f"{prefix}: {text}", file=sys.stderr)
def print_warning(text: str) -> None:
prefix = style("WARNING", YELLOW, file=sys.stderr)
return sprint(f"{prefix}: {text}", file=sys.stderr)
Context = typing.Mapping[str, typing.Any]
Formatter = typing.Callable[[Context], str]
ContextFormat = typing.Union[str, Formatter]
def _full_formatter(context: Context) -> str:
line_format = "{name}: {obj!r}"
context_str = "\n".join(
[
line_format.format(name=name, obj=obj)
for name, obj in sorted(context.items(), key=lambda i: i[0].lower())
]
)
header = style("Context:", bold=True)
return f"\n{header}\n{context_str}"
def _short_formatter(context: Context) -> str:
context_str = ", ".join(sorted(context.keys(), key=str.lower))
header = style("Context:", bold=True)
return f"\n{header}\n{context_str}"
def _hide_formatter(context: Context) -> str:
return ""
CONTEXT_FORMATTERS: typing.Dict[str, Formatter] = {
"full": _full_formatter,
"short": _short_formatter,
"hide": _hide_formatter,
}
BANNER_TEMPLATE = """{version}
{text}
{context}
"""
def make_banner(
text: typing.Optional[str] = None,
context: typing.Optional[Context] = None,
banner_template: typing.Optional[str] = None,
context_format: ContextFormat = "full",
) -> str:
"""Generates a full banner with version info, the given text, and a
formatted list of context variables.
"""
banner_text = text or speak()
banner_template = banner_template or BANNER_TEMPLATE
ctx = format_context(context or {}, formatter=context_format)
out = banner_template.format(version=sys.version, text=banner_text, context=ctx)
return out
def context_list2dict(context_list: typing.Sequence[typing.Any]) -> Context:
"""Converts a list of objects (functions, classes, or modules) to a
dictionary mapping the object names to the objects.
"""
return {obj.__name__.split(".")[-1]: obj for obj in context_list}
def _relpath(p: Path) -> Path:
return p.resolve().relative_to(Path.cwd())
class Shell:
"""Base shell class.
:param dict context: Dictionary, list, or callable (that returns a `dict` or `list`)
that defines what variables will be available when the shell is run.
:param str banner: Banner text that appears on startup.
:param str prompt: Custom input prompt.
:param str output: Custom output prompt.
:param context_format: Formatter for the context dictionary in the banner.
Either 'full', 'short', 'hide', or a function that receives the context
dictionary and outputs a string.
"""
banner_template: str = BANNER_TEMPLATE
def __init__(
self,
context: Context,
banner: typing.Optional[str] = None,
prompt: typing.Optional[str] = None,
output: typing.Optional[str] = None,
context_format: ContextFormat = "full",
**kwargs: typing.Any,
) -> None:
self.context = context() if callable(context) else context
self.context_format = context_format
self.banner = make_banner(
banner,
self.context,
context_format=self.context_format,
banner_template=self.banner_template,
)
self.prompt = prompt
self.output = output
def check_availability(self) -> bool:
raise NotImplementedError
def start(self) -> None:
raise NotImplementedError
class PythonShell(Shell):
"""The built-in Python shell."""
def check_availability(self) -> bool:
return True
def start(self) -> None:
try:
import readline
except ImportError:
pass
else:
# We don't have to wrap the following import in a 'try', because
# we already know 'readline' was imported successfully.
import rlcompleter
readline.set_completer(rlcompleter.Completer(self.context).complete)
readline.parse_and_bind("tab:complete")
if self.prompt:
sys.ps1 = self.prompt
if self.output:
warnings.warn("Custom output templates not supported by PythonShell.")
code.interact(self.banner, local=self.context)
return None
def configure_ipython_prompt(
config, prompt: typing.Optional[str] = None, output: typing.Optional[str] = None
) -> None:
import IPython
if IPython.version_info[0] >= 5: # Custom prompt API changed in IPython 5.0
from pygments.token import Token
# https://ipython.readthedocs.io/en/stable/config/details.html#custom-prompts # noqa: B950
class CustomPrompt(IPython.terminal.prompts.Prompts):
def in_prompt_tokens(self, *args, **kwargs):
if prompt is None:
return super().in_prompt_tokens(*args, **kwargs)
if isinstance(prompt, (str, bytes)):
return [(Token.Prompt, prompt)]
else:
return prompt
def out_prompt_tokens(self, *args, **kwargs):
if output is None:
return super().out_prompt_tokens(*args, **kwargs)
if isinstance(output, (str, bytes)):
return [(Token.OutPrompt, output)]
else:
return prompt
config.TerminalInteractiveShell.prompts_class = CustomPrompt
else:
prompt_config = config.PromptManager
if prompt:
prompt_config.in_template = prompt
if output:
prompt_config.out_template = output
return None
class IPythonShell(Shell):
"""The IPython shell.
:param list ipy_extensions: List of IPython extension names to load upon startup.
:param bool ipy_autoreload: Whether to load and initialize the IPython autoreload
extension upon startup. Can also be an integer, which will be passed as
the argument to the %autoreload line magic.
:param kwargs: The same kwargs as `Shell.__init__`.
"""
def __init__(
self,
ipy_extensions: typing.Optional[typing.List[str]] = None,
ipy_autoreload: bool = False,
ipy_colors: typing.Optional[str] = None,
ipy_highlighting_style: typing.Optional[str] = None,
*args: typing.Any,
**kwargs: typing.Any,
):
self.ipy_extensions = ipy_extensions
self.ipy_autoreload = ipy_autoreload
self.ipy_colors = ipy_colors
self.ipy_highlighting_style = ipy_highlighting_style
Shell.__init__(self, *args, **kwargs)
@staticmethod
def init_autoreload(mode: int) -> None:
"""Load and initialize the IPython autoreload extension."""
from IPython.extensions import autoreload
ip = get_ipython() # type: ignore # noqa: F821
autoreload.load_ipython_extension(ip)
ip.magics_manager.magics["line"]["autoreload"](str(mode))
def check_availability(self) -> bool:
try:
import IPython # noqa: F401
except ImportError:
raise ShellNotAvailableError("IPython shell not available.")
return True
def start(self) -> None:
try:
from IPython import start_ipython
from IPython.utils import io
from traitlets.config.loader import Config as IPyConfig
except ImportError:
raise ShellNotAvailableError(
"IPython shell not available " "or IPython version not supported."
)
# Hack to show custom banner
# TerminalIPythonApp/start_app doesn't allow you to customize the
# banner directly, so we write it to stdout before starting the IPython app
io.stdout.write(self.banner)
# Pass exec_lines in order to start autoreload
if self.ipy_autoreload:
if not isinstance(self.ipy_autoreload, bool):
mode = self.ipy_autoreload
else:
mode = 2
logger.debug(f"Initializing IPython autoreload in mode {mode}")
exec_lines = [
"import konch as __konch",
f"__konch.IPythonShell.init_autoreload({mode})",
]
else:
exec_lines = []
ipy_config = IPyConfig()
if self.ipy_colors:
ipy_config.TerminalInteractiveShell.colors = self.ipy_colors
if self.ipy_highlighting_style:
ipy_config.TerminalInteractiveShell.highlighting_style = (
self.ipy_highlighting_style
)
configure_ipython_prompt(ipy_config, prompt=self.prompt, output=self.output)
# Use start_ipython rather than embed so that IPython is loaded in the "normal"
# way. See https://github.com/django/django/pull/512
start_ipython(
display_banner=False,
user_ns=self.context,
config=ipy_config,
extensions=self.ipy_extensions or [],
exec_lines=exec_lines,
argv=[],
)
return None
class PtPythonShell(Shell):
def __init__(self, ptpy_vi_mode: bool = False, *args, **kwargs):
self.ptpy_vi_mode = ptpy_vi_mode
Shell.__init__(self, *args, **kwargs)
def check_availability(self) -> bool:
try:
import ptpython # noqa: F401
except ImportError:
raise ShellNotAvailableError("PtPython shell not available.")
return True
def start(self) -> None:
try:
from ptpython.repl import embed, run_config
except ImportError:
raise ShellNotAvailableError("PtPython shell not available.")
print(self.banner)
config_dir = Path("~/.ptpython/").expanduser()
# Startup path
startup_paths = []
if "PYTHONSTARTUP" in os.environ:
startup_paths.append(os.environ["PYTHONSTARTUP"])
# Apply config file
def configure(repl):
path = config_dir / "config.py"
if path.exists():
run_config(repl, str(path))
embed(
globals=self.context,
history_filename=config_dir / "history",
vi_mode=self.ptpy_vi_mode,
startup_paths=startup_paths,
configure=configure,
)
return None
class PtIPythonShell(PtPythonShell):
banner_template: str = "{text}\n{context}"
def __init__(
self, ipy_extensions: typing.Optional[typing.List[str]] = None, *args, **kwargs
) -> None:
self.ipy_extensions = ipy_extensions or []
PtPythonShell.__init__(self, *args, **kwargs)
def check_availability(self) -> bool:
try:
import ptpython.ipython # noqa: F401
import IPython # noqa: F401
except ImportError:
raise ShellNotAvailableError("PtIPython shell not available.")
return True
def start(self) -> None:
try:
from ptpython.ipython import embed
from ptpython.repl import run_config
from IPython.terminal.ipapp import load_default_config
except ImportError:
raise ShellNotAvailableError("PtIPython shell not available.")
config_dir = Path("~/.ptpython/").expanduser()
# Apply config file
def configure(repl):
path = config_dir / "config.py"
if path.exists():
run_config(repl, str(path))
# Startup path
startup_paths = []
if "PYTHONSTARTUP" in os.environ:
startup_paths.append(os.environ["PYTHONSTARTUP"])
# exec scripts from startup paths
for path in startup_paths:
if Path(path).exists():
with Path(path).open("rb") as f:
code = compile(f.read(), path, "exec")
exec(code, self.context, self.context)
else:
print(f"File not found: {path}\n\n")
sys.exit(1)
ipy_config = load_default_config()
ipy_config.InteractiveShellEmbed = ipy_config.TerminalInteractiveShell
ipy_config["InteractiveShellApp"]["extensions"] = self.ipy_extensions
configure_ipython_prompt(ipy_config, prompt=self.prompt, output=self.output)
embed(
config=ipy_config,
configure=configure,
history_filename=config_dir / "history",
user_ns=self.context,
header=self.banner,
vi_mode=self.ptpy_vi_mode,
)
return None
class BPythonShell(Shell):
"""The BPython shell."""
def check_availability(self) -> bool:
try:
import bpython # noqa: F401
except ImportError:
raise ShellNotAvailableError("BPython shell not available.")
return True
def start(self) -> None:
try:
from bpython import embed
except ImportError:
raise ShellNotAvailableError("BPython shell not available.")
if self.prompt:
warnings.warn("Custom prompts not supported by BPythonShell.")
if self.output:
warnings.warn("Custom output templates not supported by BPythonShell.")
embed(banner=self.banner, locals_=self.context)
return None
class BPythonCursesShell(Shell):
"""The BPython Curses shell."""
def check_availability(self) -> bool:
try:
import bpython.cli # noqa: F401
except ImportError:
raise ShellNotAvailableError("BPython Curses shell not available.")
return True
def start(self) -> None:
try:
from bpython.cli import main
except ImportError:
raise ShellNotAvailableError("BPython Curses shell not available.")
if self.prompt:
warnings.warn("Custom prompts not supported by BPython Curses shell.")
if self.output:
warnings.warn(
"Custom output templates not supported by BPython Curses shell."
)
main(banner=self.banner, locals_=self.context, args=["-i", "-q"])
return None
class AutoShell(Shell):
"""Shell that runs PtIpython, PtPython, IPython, or BPython if available.
Falls back to built-in Python shell.
"""
# Shell classes in precedence order
SHELLS = [
PtIPythonShell,
PtPythonShell,
IPythonShell,
BPythonShell,
BPythonCursesShell,
PythonShell,
]
def __init__(self, context: Context, banner: str, **kwargs):
Shell.__init__(self, context, **kwargs)
self.kwargs = kwargs
self.banner = banner
def check_availability(self) -> bool:
return True
def start(self) -> None:
shell_args = {
"context": self.context,
"banner": self.banner,
"prompt": self.prompt,
"output": self.output,
"context_format": self.context_format,
}
shell_args.update(self.kwargs)
shell = None
for shell_class in self.SHELLS:
try:
shell = shell_class(**shell_args)
shell.check_availability()
except ShellNotAvailableError:
continue
else:
break
else:
raise ShellNotAvailableError("No available shell to run.")
return shell.start()
CONCHES: typing.List[str] = [
'"My conch told me to come save you guys."\n"Hooray for the magic conches!"',
'"All hail the Magic Conch!"',
'"Hooray for the magic conches!"',
'"Uh, hello there. Magic Conch, I was wondering... '
'should I have the spaghetti or the turkey?"',
'"This copyrighted conch is the cornerstone of our organization."',
'"Praise the Magic Conch!"',
'"the conch exploded into a thousand white fragments and ceased to exist."',
"\"S'right. It's a shell!\"",
'"Ralph felt a kind of affectionate reverence for the conch"',
'"Conch! Conch!"',
'"That\'s why you got the conch out of the water"',
'"the summons of the conch"',
'"Whoever holds the conch gets to speak."',
'"They\'ll come when they hear us--"',
'"We gotta drop the load!"',
'"Dude, we\'re falling right out the sky!!"',
(
'"Oh, Magic Conch Shell, what do we need to do to get '
'out of the Kelp Forest?"\n"Nothing."'
),
'"The shell knows all!"',
'"we must never question the wisdom of the Magic Conch."',
'"The Magic Conch! A club member!"',
'"The shell has spoken!"',
'"This copyrighted conch is the cornerstone of our organization."',
'"All right, Magic Conch... what do we do now?"',
'"Ohhh! The Magic Conch Shell! Ask it something! Ask it something!"',
]
def speak() -> str:
return random.choice(CONCHES)
class Config(dict):
"""A dict-like config object. Behaves like a normal dict except that
the ``context`` will always be converted from a list to a dict.
Defines the default configuration.
"""
def __init__(
self,
context: typing.Optional[Context] = None,
banner: typing.Optional[str] = None,
shell: typing.Type[Shell] = AutoShell,
prompt: typing.Optional[str] = None,
output: typing.Optional[str] = None,
context_format: str = "full",
**kwargs: typing.Any,
) -> None:
ctx = Config.transform_val(context) or {}
super().__init__(
context=ctx,
banner=banner,
shell=shell,
prompt=prompt,
output=output,
context_format=context_format,
**kwargs,
)
def __setitem__(self, key: typing.Any, value: typing.Any) -> None:
if key == "context":
value = Config.transform_val(value)
super().__setitem__(key, value)
@staticmethod
def transform_val(val: typing.Any) -> typing.Any:
if isinstance(val, (list, tuple)):
return context_list2dict(val)
return val
def update(self, d: typing.Mapping) -> None: # type: ignore
for key in d.keys():
# Shallow-merge context
if key == "context":
self["context"].update(Config.transform_val(d["context"]))
else:
self[key] = d[key]
SHELL_MAP: typing.Dict[str, typing.Type[Shell]] = {
"ipy": IPythonShell,
"ipython": IPythonShell,
"bpy": BPythonShell,
"bpython": BPythonShell,
"bpyc": BPythonCursesShell,
"bpython-curses": BPythonCursesShell,
"py": PythonShell,
"python": PythonShell,
"auto": AutoShell,
"ptpy": PtPythonShell,
"ptpython": PtPythonShell,
"ptipy": PtIPythonShell,
"ptipython": PtIPythonShell,
}
# _cfg and _config_registry are singletons that may be mutated in a .konchrc file
_cfg = Config()
_config_registry = {"default": _cfg}
def start(
context: typing.Optional[typing.Mapping] = None,
banner: typing.Optional[str] = None,
shell: typing.Type[Shell] = AutoShell,
prompt: typing.Optional[str] = None,
output: typing.Optional[str] = None,
context_format: str = "full",
**kwargs: typing.Any,
) -> None:
"""Start up the konch shell. Takes the same parameters as Shell.__init__.
"""
logger.debug(f"Using shell: {shell!r}")
if banner is None:
banner = speak()
# Default to global config
context_ = context or _cfg["context"]
banner_ = banner or _cfg["banner"]
if isinstance(shell, type) and issubclass(shell, Shell):
shell_ = shell
else:
shell_ = SHELL_MAP.get(shell or _cfg["shell"], _cfg["shell"])
prompt_ = prompt or _cfg["prompt"]
output_ = output or _cfg["output"]
context_format_ = context_format or _cfg["context_format"]
shell_(
context=context_,
banner=banner_,
prompt=prompt_,
output=output_,
context_format=context_format_,
**kwargs,
).start()
def config(config_dict: typing.Mapping) -> Config:
"""Configures the konch shell. This function should be called in a
.konchrc file.
:param dict config_dict: Dict that may contain 'context', 'banner', and/or
'shell' (default shell class to use).
"""
logger.debug(f"Updating with {config_dict}")
_cfg.update(config_dict)
return _cfg
def named_config(name: str, config_dict: typing.Mapping) -> None:
"""Adds a named config to the config registry. The first argument
may either be a string or a collection of strings.
This function should be called in a .konchrc file.
"""
names = (
name
if isinstance(name, Iterable) and not isinstance(name, (str, bytes))
else [name]
)
for each in names:
_config_registry[each] = Config(**config_dict)
def reset_config() -> Config:
global _cfg
_cfg = Config()
return _cfg
def __ensure_directory_in_path(filename: Path) -> None:
"""Ensures that a file's directory is in the Python path.
"""
directory = Path(filename).parent.resolve()
if directory not in sys.path:
logger.debug(f"Adding {directory} to sys.path")
sys.path.insert(0, str(directory))
CONFIG_FILE = Path(".konchrc")
DEFAULT_CONFIG_FILE = Path.home() / ".konchrc.default"
SEPARATOR = f"\n{'*' * 46}\n"
def confirm(text: str, default: bool = False) -> bool:
"""Display a confirmation prompt."""
choices = "Y/n" if default else "y/N"
prompt = f"{style(text, bold=True)} [{choices}]: "
while 1:
try:
print(prompt, end="")
value = input("").lower().strip()
except (KeyboardInterrupt, EOFError):
sys.exit(1)
if value in ("y", "yes"):
rv = True
elif value in ("n", "no"):
rv = False
elif value == "":
rv = default
else:
print_error("Error: invalid input")
continue
break
return rv
def use_file(
filename: typing.Union[Path, str, None], trust: bool = False
) -> typing.Union[types.ModuleType, None]:
"""Load filename as a python file. Import ``filename`` and return it
as a module.
"""
config_file = filename or resolve_path(CONFIG_FILE)
def preview_unauthorized() -> None:
if not config_file:
return None
print(SEPARATOR, file=sys.stderr)
with Path(config_file).open("r", encoding="utf-8") as fp:
for line in fp:
print(line, end="", file=sys.stderr)
print(SEPARATOR, file=sys.stderr)
if config_file and not Path(config_file).exists():
print_error(f'"{filename}" not found.')
sys.exit(1)
if config_file and Path(config_file).exists():
if not trust:
with AuthFile.load() as authfile:
try:
authfile.check(Path(config_file))
except KonchrcChangedError:
print_error(f'"{config_file}" has changed since you last used it.')
preview_unauthorized()
if confirm("Would you like to authorize it?"):
authfile.allow(Path(config_file))
print()
else:
sys.exit(1)
except KonchrcNotAuthorizedError:
print_error(f'"{config_file}" is blocked.')
preview_unauthorized()
if confirm("Would you like to authorize it?"):
authfile.allow(Path(config_file))
print()
else:
sys.exit(1)
logger.info(f"Using {config_file}")
# Ensure that relative imports are possible
__ensure_directory_in_path(Path(config_file))
mod = None
try:
mod = imp.load_source("konchrc", str(config_file))
except UnboundLocalError: # File not found
pass
else:
return mod
if not config_file:
print_warning("No konch config file found.")
else:
print_warning(f'"{config_file}" not found.')
return None
def resolve_path(filename: Path) -> typing.Union[Path, None]:
"""Find a file by walking up parent directories until the file is found.
Return the absolute path of the file.
"""
current = Path.cwd()
# Stop search at home directory
sentinel_dir = Path.home().parent.resolve()
while current != sentinel_dir:
target = Path(current) / Path(filename)
if target.exists():
return target.resolve()
else:
current = current.parent.resolve()
return None
def get_editor() -> str:
for key in "KONCH_EDITOR", "VISUAL", "EDITOR":
ret = os.environ.get(key)
if ret:
return ret
if sys.platform.startswith("win"):
return "notepad"
for editor in "vim", "nano":
if os.system("which %s &> /dev/null" % editor) == 0:
return editor
return "vi"
def edit_file(
filename: typing.Optional[Path], editor: typing.Optional[str] = None
) -> None:
if not filename:
print_error("filename not passed.")
sys.exit(1)
editor = editor or get_editor()
try:
result = subprocess.Popen(f'{editor} "{filename}"', shell=True)
exit_code = result.wait()
if exit_code != 0:
print_error(f"{editor}: Editing failed!")
sys.exit(1)
except OSError as err:
print_error(f"{editor}: Editing failed: {err}")
sys.exit(1)
else:
with AuthFile.load() as authfile:
authfile.allow(filename)
INIT_TEMPLATE = """# vi: set ft=python :
import konch
import sys
import os
# Available options:
# "context", "banner", "shell", "prompt", "output",
# "context_format", "ipy_extensions", "ipy_autoreload",
# "ipy_colors", "ipy_highlighting_style", "ptpy_vi_mode"
# See: https://konch.readthedocs.io/en/latest/#configuration
konch.config({
"context": [
sys,
os,
]
})
def setup():
pass
def teardown():
pass
"""
def init_config(config_file: Path) -> typing.NoReturn:
if not config_file.exists():
print(f'Writing to "{config_file.resolve()}"...')
print(SEPARATOR)
print(INIT_TEMPLATE, end="")
print(SEPARATOR)
init_template = INIT_TEMPLATE
if DEFAULT_CONFIG_FILE.exists(): # use ~/.konchrc.default if it exists
with Path(DEFAULT_CONFIG_FILE).open("r") as fp:
init_template = fp.read()
with Path(config_file).open("w") as fp:
fp.write(init_template)
with AuthFile.load() as authfile:
authfile.allow(config_file)
relpath = _relpath(config_file)
is_default = relpath == Path(CONFIG_FILE)
edit_cmd = "konch edit" if is_default else f"konch edit {relpath}"
run_cmd = "konch" if is_default else f"konch -f {relpath}"
print(f"{style('Done!', GREEN)} ✨ 🐚 ✨")
print(f"To edit your config: `{style(edit_cmd, bold=True)}`")
print(f"To start the shell: `{style(run_cmd, bold=True)}`")
sys.exit(0)
else:
print_error(f'"{config_file}" already exists in this directory.')
sys.exit(1)
def edit_config(
config_file: typing.Optional[Path] = None, editor: typing.Optional[str] = None
) -> typing.NoReturn:
filename = config_file or resolve_path(CONFIG_FILE)
if not filename:
print_error('No ".konchrc" file found.')
styled_cmd = style("konch init", bold=True, file=sys.stderr)
print(f"Run `{styled_cmd}` to create it.", file=sys.stderr)
sys.exit(1)
if not filename.exists():
print_error(f'"{filename}" does not exist.')
relpath = _relpath(filename)
is_default = relpath == Path(CONFIG_FILE)
cmd = "konch init" if is_default else f"konch init {filename}"
styled_cmd = style(cmd, bold=True, file=sys.stderr)
print(f"Run `{styled_cmd}` to create it.", file=sys.stderr)
sys.exit(1)
print(f'Editing file: "{filename}"')
edit_file(filename, editor=editor)
sys.exit(0)
def allow_config(config_file: typing.Optional[Path] = None) -> typing.NoReturn:
filename: typing.Union[Path, None]
if config_file and config_file.is_dir():
filename = Path(config_file) / CONFIG_FILE
else:
filename = config_file or resolve_path(CONFIG_FILE)
if not filename:
print_error("No config file found.")
sys.exit(1)
with AuthFile.load() as authfile:
if authfile.check(filename, raise_error=False):
print_warning(f'"{filename}" is already authorized.')
else:
try:
print(f'Authorizing "{filename}"...')
authfile.allow(filename)
except FileNotFoundError:
print_error(f'"{filename}" does not exist.')
sys.exit(1)
print(f"{style('Done!', GREEN)} ✨ 🐚 ✨")
relpath = _relpath(filename)
cmd = "konch" if relpath == Path(CONFIG_FILE) else f"konch -f {relpath}"
print(f"You can now start a shell with `{style(cmd, bold=True)}`.")
sys.exit(0)
def deny_config(config_file: typing.Optional[Path] = None) -> typing.NoReturn:
filename: typing.Union[Path, None]
if config_file and config_file.is_dir():
filename = Path(config_file) / CONFIG_FILE
else:
filename = config_file or resolve_path(CONFIG_FILE)
if not filename:
print_error("No config file found.")
sys.exit(1)
print(f'Removing authorization for "{filename}"...')
with AuthFile.load() as authfile:
try:
authfile.deny(filename)
except FileNotFoundError:
print_error(f'"{filename}" does not exist.')
sys.exit(1)
else:
print(style("Done!", GREEN))
sys.exit(0)
def parse_args(argv: typing.Optional[typing.Sequence] = None) -> typing.Dict[str, str]:
"""Exposes the docopt command-line arguments parser.
Return a dictionary of arguments.
"""
return docopt(__doc__, argv=argv, version=__version__)
def main(argv: typing.Optional[typing.Sequence] = None) -> typing.NoReturn:
"""Main entry point for the konch CLI."""
args = parse_args(argv)
if args["--debug"]:
logging.basicConfig(
format="%(levelname)s %(filename)s: %(message)s", level=logging.DEBUG
)
logger.debug(args)
config_file: typing.Union[Path, None]
if args["init"]:
config_file = Path(args["<config_file>"] or CONFIG_FILE)
init_config(config_file)
else:
config_file = Path(args["<config_file>"]) if args["<config_file>"] else None
if args["edit"]:
edit_config(config_file)
elif args["allow"]:
allow_config(config_file)
elif args["deny"]:
deny_config(config_file)
mod = use_file(Path(args["--file"]) if args["--file"] else None)
if hasattr(mod, "setup"):
mod.setup() # type: ignore
if args["--name"]:
if args["--name"] not in _config_registry:
print_error(f'Invalid --name: "{args["--name"]}"')
sys.exit(1)
config_dict = _config_registry[args["--name"]]
logger.debug(f'Using named config: "{args["--name"]}"')
logger.debug(config_dict)
else:
config_dict = _cfg
# Allow default shell to be overriden by command-line argument
shell_name = args["--shell"]
if shell_name:
config_dict["shell"] = SHELL_MAP.get(shell_name.lower(), AutoShell)
logger.debug(f"Starting with config {config_dict}")
start(**config_dict)
if hasattr(mod, "teardown"):
mod.teardown() # type: ignore
sys.exit(0)
if __name__ == "__main__":
main()
|
sloria/konch | konch.py | make_banner | python | def make_banner(
text: typing.Optional[str] = None,
context: typing.Optional[Context] = None,
banner_template: typing.Optional[str] = None,
context_format: ContextFormat = "full",
) -> str:
banner_text = text or speak()
banner_template = banner_template or BANNER_TEMPLATE
ctx = format_context(context or {}, formatter=context_format)
out = banner_template.format(version=sys.version, text=banner_text, context=ctx)
return out | Generates a full banner with version info, the given text, and a
formatted list of context variables. | train | https://github.com/sloria/konch/blob/15160bd0a0cac967eeeab84794bd6cdd0b5b637d/konch.py#L269-L282 | [
"def format_context(\n context: Context, formatter: typing.Union[str, Formatter] = \"full\"\n) -> str:\n \"\"\"Output the a context dictionary as a string.\"\"\"\n if not context:\n return \"\"\n\n if callable(formatter):\n formatter_func = formatter\n else:\n if formatter in CONTEXT_FORMATTERS:\n formatter_func = CONTEXT_FORMATTERS[formatter]\n else:\n raise ValueError(f'Invalid context format: \"{formatter}\"')\n return formatter_func(context)\n",
"def speak() -> str:\n return random.choice(CONCHES)\n"
] | #!/usr/bin/env python3
"""konch: Customizes your Python shell.
Usage:
konch
konch init [<config_file>] [-d]
konch edit [<config_file>] [-d]
konch allow [<config_file>] [-d]
konch deny [<config_file>] [-d]
konch [--name=<name>] [--file=<file>] [--shell=<shell_name>] [-d]
Options:
-h --help Show this screen.
-v --version Show version.
init Creates a starter .konchrc file.
edit Edit your .konchrc file.
-n --name=<name> Named config to use.
-s --shell=<shell_name> Shell to use. Can be either "ipy" (IPython),
"bpy" (BPython), "bpyc" (BPython Curses),
"ptpy" (PtPython), "ptipy" (PtIPython),
"py" (built-in Python shell), or "auto".
Overrides the 'shell' option in .konchrc.
-f --file=<file> File path of konch config file to execute. If not provided,
konch will use the .konchrc file in the current
directory.
-d --debug Enable debugging/verbose mode.
Environment variables:
KONCH_AUTH_FILE: File where to store authorization data for config files.
Defaults to ~/.local/share/konch_auth.
KONCH_EDITOR: Editor command to use when running `konch edit`.
Falls back to $VISUAL then $EDITOR.
NO_COLOR: Disable ANSI colors.
"""
from collections.abc import Iterable
from pathlib import Path
import code
import hashlib
import imp
import json
import logging
import os
import random
import subprocess
import sys
import typing
import types
import warnings
from docopt import docopt
__version__ = "4.2.1"
logger = logging.getLogger(__name__)
class KonchError(Exception):
pass
class ShellNotAvailableError(KonchError):
pass
class KonchrcNotAuthorizedError(KonchError):
pass
class KonchrcChangedError(KonchrcNotAuthorizedError):
pass
class AuthFile:
def __init__(self, data: typing.Dict[str, str]) -> None:
self.data = data
def __repr__(self) -> str:
return f"AuthFile({self.data!r})"
@classmethod
def load(cls, path: typing.Optional[Path] = None) -> "AuthFile":
filepath = path or cls.get_path()
try:
with Path(filepath).open("r", encoding="utf-8") as fp:
data = json.load(fp)
except FileNotFoundError:
data = {}
except json.JSONDecodeError as error:
# File exists but is empty
if error.doc.strip() == "":
data = {}
else:
raise
return cls(data)
def allow(self, filepath: Path) -> None:
logger.debug(f"Authorizing {filepath}")
self.data[str(Path(filepath).resolve())] = self._hash_file(filepath)
def deny(self, filepath: Path) -> None:
if not filepath.exists():
raise FileNotFoundError(f"{filepath} not found")
try:
logger.debug(f"Removing authorization for {filepath}")
del self.data[str(filepath.resolve())]
except KeyError:
pass
def check(
self, filepath: typing.Union[Path, None], raise_error: bool = True
) -> bool:
if not filepath:
return False
if str(filepath.resolve()) not in self.data:
if raise_error:
raise KonchrcNotAuthorizedError
else:
return False
else:
file_hash = self._hash_file(filepath)
if file_hash != self.data[str(filepath.resolve())]:
if raise_error:
raise KonchrcChangedError
else:
return False
return True
def save(self) -> None:
filepath = self.get_path()
filepath.parent.mkdir(parents=True, exist_ok=True)
with Path(filepath).open("w", encoding="utf-8") as fp:
json.dump(self.data, fp)
def __enter__(self) -> "AuthFile":
return self
def __exit__(
self,
exc_type: typing.Type[Exception],
exc_value: Exception,
exc_traceback: types.TracebackType,
) -> None:
if not exc_type:
self.save()
@staticmethod
def get_path() -> Path:
if "KONCH_AUTH_FILE" in os.environ:
return Path(os.environ["KONCH_AUTH_FILE"])
elif "XDG_DATA_HOME" in os.environ:
return Path(os.environ["XDG_DATA_HOME"]) / "konch_auth"
else:
return Path.home() / ".local" / "share" / "konch_auth"
@staticmethod
def _hash_file(filepath: Path) -> str:
# https://stackoverflow.com/a/22058673/1157536
BUF_SIZE = 65536 # read in 64kb chunks
sha1 = hashlib.sha1()
with Path(filepath).open("rb") as f:
while True:
data = f.read(BUF_SIZE)
if not data:
break
sha1.update(data) # type: ignore
return sha1.hexdigest()
RED = 31
GREEN = 32
YELLOW = 33
BOLD = 1
RESET_ALL = 0
def style(
text: str,
fg: typing.Optional[int] = None,
*,
bold: bool = False,
file: typing.IO = sys.stdout,
) -> str:
use_color = not os.environ.get("NO_COLOR") and file.isatty()
if use_color:
parts = [
fg and f"\033[{fg}m",
bold and f"\033[{BOLD}m",
text,
f"\033[{RESET_ALL}m",
]
return "".join([e for e in parts if e])
else:
return text
def sprint(text: str, *args: typing.Any, **kwargs: typing.Any) -> None:
file = kwargs.pop("file", sys.stdout)
return print(style(text, file=file, *args, **kwargs), file=file)
def print_error(text: str) -> None:
prefix = style("ERROR", RED, file=sys.stderr)
return sprint(f"{prefix}: {text}", file=sys.stderr)
def print_warning(text: str) -> None:
prefix = style("WARNING", YELLOW, file=sys.stderr)
return sprint(f"{prefix}: {text}", file=sys.stderr)
Context = typing.Mapping[str, typing.Any]
Formatter = typing.Callable[[Context], str]
ContextFormat = typing.Union[str, Formatter]
def _full_formatter(context: Context) -> str:
line_format = "{name}: {obj!r}"
context_str = "\n".join(
[
line_format.format(name=name, obj=obj)
for name, obj in sorted(context.items(), key=lambda i: i[0].lower())
]
)
header = style("Context:", bold=True)
return f"\n{header}\n{context_str}"
def _short_formatter(context: Context) -> str:
context_str = ", ".join(sorted(context.keys(), key=str.lower))
header = style("Context:", bold=True)
return f"\n{header}\n{context_str}"
def _hide_formatter(context: Context) -> str:
return ""
CONTEXT_FORMATTERS: typing.Dict[str, Formatter] = {
"full": _full_formatter,
"short": _short_formatter,
"hide": _hide_formatter,
}
def format_context(
context: Context, formatter: typing.Union[str, Formatter] = "full"
) -> str:
"""Output the a context dictionary as a string."""
if not context:
return ""
if callable(formatter):
formatter_func = formatter
else:
if formatter in CONTEXT_FORMATTERS:
formatter_func = CONTEXT_FORMATTERS[formatter]
else:
raise ValueError(f'Invalid context format: "{formatter}"')
return formatter_func(context)
BANNER_TEMPLATE = """{version}
{text}
{context}
"""
def context_list2dict(context_list: typing.Sequence[typing.Any]) -> Context:
"""Converts a list of objects (functions, classes, or modules) to a
dictionary mapping the object names to the objects.
"""
return {obj.__name__.split(".")[-1]: obj for obj in context_list}
def _relpath(p: Path) -> Path:
return p.resolve().relative_to(Path.cwd())
class Shell:
"""Base shell class.
:param dict context: Dictionary, list, or callable (that returns a `dict` or `list`)
that defines what variables will be available when the shell is run.
:param str banner: Banner text that appears on startup.
:param str prompt: Custom input prompt.
:param str output: Custom output prompt.
:param context_format: Formatter for the context dictionary in the banner.
Either 'full', 'short', 'hide', or a function that receives the context
dictionary and outputs a string.
"""
banner_template: str = BANNER_TEMPLATE
def __init__(
self,
context: Context,
banner: typing.Optional[str] = None,
prompt: typing.Optional[str] = None,
output: typing.Optional[str] = None,
context_format: ContextFormat = "full",
**kwargs: typing.Any,
) -> None:
self.context = context() if callable(context) else context
self.context_format = context_format
self.banner = make_banner(
banner,
self.context,
context_format=self.context_format,
banner_template=self.banner_template,
)
self.prompt = prompt
self.output = output
def check_availability(self) -> bool:
raise NotImplementedError
def start(self) -> None:
raise NotImplementedError
class PythonShell(Shell):
"""The built-in Python shell."""
def check_availability(self) -> bool:
return True
def start(self) -> None:
try:
import readline
except ImportError:
pass
else:
# We don't have to wrap the following import in a 'try', because
# we already know 'readline' was imported successfully.
import rlcompleter
readline.set_completer(rlcompleter.Completer(self.context).complete)
readline.parse_and_bind("tab:complete")
if self.prompt:
sys.ps1 = self.prompt
if self.output:
warnings.warn("Custom output templates not supported by PythonShell.")
code.interact(self.banner, local=self.context)
return None
def configure_ipython_prompt(
config, prompt: typing.Optional[str] = None, output: typing.Optional[str] = None
) -> None:
import IPython
if IPython.version_info[0] >= 5: # Custom prompt API changed in IPython 5.0
from pygments.token import Token
# https://ipython.readthedocs.io/en/stable/config/details.html#custom-prompts # noqa: B950
class CustomPrompt(IPython.terminal.prompts.Prompts):
def in_prompt_tokens(self, *args, **kwargs):
if prompt is None:
return super().in_prompt_tokens(*args, **kwargs)
if isinstance(prompt, (str, bytes)):
return [(Token.Prompt, prompt)]
else:
return prompt
def out_prompt_tokens(self, *args, **kwargs):
if output is None:
return super().out_prompt_tokens(*args, **kwargs)
if isinstance(output, (str, bytes)):
return [(Token.OutPrompt, output)]
else:
return prompt
config.TerminalInteractiveShell.prompts_class = CustomPrompt
else:
prompt_config = config.PromptManager
if prompt:
prompt_config.in_template = prompt
if output:
prompt_config.out_template = output
return None
class IPythonShell(Shell):
"""The IPython shell.
:param list ipy_extensions: List of IPython extension names to load upon startup.
:param bool ipy_autoreload: Whether to load and initialize the IPython autoreload
extension upon startup. Can also be an integer, which will be passed as
the argument to the %autoreload line magic.
:param kwargs: The same kwargs as `Shell.__init__`.
"""
def __init__(
self,
ipy_extensions: typing.Optional[typing.List[str]] = None,
ipy_autoreload: bool = False,
ipy_colors: typing.Optional[str] = None,
ipy_highlighting_style: typing.Optional[str] = None,
*args: typing.Any,
**kwargs: typing.Any,
):
self.ipy_extensions = ipy_extensions
self.ipy_autoreload = ipy_autoreload
self.ipy_colors = ipy_colors
self.ipy_highlighting_style = ipy_highlighting_style
Shell.__init__(self, *args, **kwargs)
@staticmethod
def init_autoreload(mode: int) -> None:
"""Load and initialize the IPython autoreload extension."""
from IPython.extensions import autoreload
ip = get_ipython() # type: ignore # noqa: F821
autoreload.load_ipython_extension(ip)
ip.magics_manager.magics["line"]["autoreload"](str(mode))
def check_availability(self) -> bool:
try:
import IPython # noqa: F401
except ImportError:
raise ShellNotAvailableError("IPython shell not available.")
return True
def start(self) -> None:
try:
from IPython import start_ipython
from IPython.utils import io
from traitlets.config.loader import Config as IPyConfig
except ImportError:
raise ShellNotAvailableError(
"IPython shell not available " "or IPython version not supported."
)
# Hack to show custom banner
# TerminalIPythonApp/start_app doesn't allow you to customize the
# banner directly, so we write it to stdout before starting the IPython app
io.stdout.write(self.banner)
# Pass exec_lines in order to start autoreload
if self.ipy_autoreload:
if not isinstance(self.ipy_autoreload, bool):
mode = self.ipy_autoreload
else:
mode = 2
logger.debug(f"Initializing IPython autoreload in mode {mode}")
exec_lines = [
"import konch as __konch",
f"__konch.IPythonShell.init_autoreload({mode})",
]
else:
exec_lines = []
ipy_config = IPyConfig()
if self.ipy_colors:
ipy_config.TerminalInteractiveShell.colors = self.ipy_colors
if self.ipy_highlighting_style:
ipy_config.TerminalInteractiveShell.highlighting_style = (
self.ipy_highlighting_style
)
configure_ipython_prompt(ipy_config, prompt=self.prompt, output=self.output)
# Use start_ipython rather than embed so that IPython is loaded in the "normal"
# way. See https://github.com/django/django/pull/512
start_ipython(
display_banner=False,
user_ns=self.context,
config=ipy_config,
extensions=self.ipy_extensions or [],
exec_lines=exec_lines,
argv=[],
)
return None
class PtPythonShell(Shell):
def __init__(self, ptpy_vi_mode: bool = False, *args, **kwargs):
self.ptpy_vi_mode = ptpy_vi_mode
Shell.__init__(self, *args, **kwargs)
def check_availability(self) -> bool:
try:
import ptpython # noqa: F401
except ImportError:
raise ShellNotAvailableError("PtPython shell not available.")
return True
def start(self) -> None:
try:
from ptpython.repl import embed, run_config
except ImportError:
raise ShellNotAvailableError("PtPython shell not available.")
print(self.banner)
config_dir = Path("~/.ptpython/").expanduser()
# Startup path
startup_paths = []
if "PYTHONSTARTUP" in os.environ:
startup_paths.append(os.environ["PYTHONSTARTUP"])
# Apply config file
def configure(repl):
path = config_dir / "config.py"
if path.exists():
run_config(repl, str(path))
embed(
globals=self.context,
history_filename=config_dir / "history",
vi_mode=self.ptpy_vi_mode,
startup_paths=startup_paths,
configure=configure,
)
return None
class PtIPythonShell(PtPythonShell):
banner_template: str = "{text}\n{context}"
def __init__(
self, ipy_extensions: typing.Optional[typing.List[str]] = None, *args, **kwargs
) -> None:
self.ipy_extensions = ipy_extensions or []
PtPythonShell.__init__(self, *args, **kwargs)
def check_availability(self) -> bool:
try:
import ptpython.ipython # noqa: F401
import IPython # noqa: F401
except ImportError:
raise ShellNotAvailableError("PtIPython shell not available.")
return True
def start(self) -> None:
try:
from ptpython.ipython import embed
from ptpython.repl import run_config
from IPython.terminal.ipapp import load_default_config
except ImportError:
raise ShellNotAvailableError("PtIPython shell not available.")
config_dir = Path("~/.ptpython/").expanduser()
# Apply config file
def configure(repl):
path = config_dir / "config.py"
if path.exists():
run_config(repl, str(path))
# Startup path
startup_paths = []
if "PYTHONSTARTUP" in os.environ:
startup_paths.append(os.environ["PYTHONSTARTUP"])
# exec scripts from startup paths
for path in startup_paths:
if Path(path).exists():
with Path(path).open("rb") as f:
code = compile(f.read(), path, "exec")
exec(code, self.context, self.context)
else:
print(f"File not found: {path}\n\n")
sys.exit(1)
ipy_config = load_default_config()
ipy_config.InteractiveShellEmbed = ipy_config.TerminalInteractiveShell
ipy_config["InteractiveShellApp"]["extensions"] = self.ipy_extensions
configure_ipython_prompt(ipy_config, prompt=self.prompt, output=self.output)
embed(
config=ipy_config,
configure=configure,
history_filename=config_dir / "history",
user_ns=self.context,
header=self.banner,
vi_mode=self.ptpy_vi_mode,
)
return None
class BPythonShell(Shell):
"""The BPython shell."""
def check_availability(self) -> bool:
try:
import bpython # noqa: F401
except ImportError:
raise ShellNotAvailableError("BPython shell not available.")
return True
def start(self) -> None:
try:
from bpython import embed
except ImportError:
raise ShellNotAvailableError("BPython shell not available.")
if self.prompt:
warnings.warn("Custom prompts not supported by BPythonShell.")
if self.output:
warnings.warn("Custom output templates not supported by BPythonShell.")
embed(banner=self.banner, locals_=self.context)
return None
class BPythonCursesShell(Shell):
"""The BPython Curses shell."""
def check_availability(self) -> bool:
try:
import bpython.cli # noqa: F401
except ImportError:
raise ShellNotAvailableError("BPython Curses shell not available.")
return True
def start(self) -> None:
try:
from bpython.cli import main
except ImportError:
raise ShellNotAvailableError("BPython Curses shell not available.")
if self.prompt:
warnings.warn("Custom prompts not supported by BPython Curses shell.")
if self.output:
warnings.warn(
"Custom output templates not supported by BPython Curses shell."
)
main(banner=self.banner, locals_=self.context, args=["-i", "-q"])
return None
class AutoShell(Shell):
"""Shell that runs PtIpython, PtPython, IPython, or BPython if available.
Falls back to built-in Python shell.
"""
# Shell classes in precedence order
SHELLS = [
PtIPythonShell,
PtPythonShell,
IPythonShell,
BPythonShell,
BPythonCursesShell,
PythonShell,
]
def __init__(self, context: Context, banner: str, **kwargs):
Shell.__init__(self, context, **kwargs)
self.kwargs = kwargs
self.banner = banner
def check_availability(self) -> bool:
return True
def start(self) -> None:
shell_args = {
"context": self.context,
"banner": self.banner,
"prompt": self.prompt,
"output": self.output,
"context_format": self.context_format,
}
shell_args.update(self.kwargs)
shell = None
for shell_class in self.SHELLS:
try:
shell = shell_class(**shell_args)
shell.check_availability()
except ShellNotAvailableError:
continue
else:
break
else:
raise ShellNotAvailableError("No available shell to run.")
return shell.start()
CONCHES: typing.List[str] = [
'"My conch told me to come save you guys."\n"Hooray for the magic conches!"',
'"All hail the Magic Conch!"',
'"Hooray for the magic conches!"',
'"Uh, hello there. Magic Conch, I was wondering... '
'should I have the spaghetti or the turkey?"',
'"This copyrighted conch is the cornerstone of our organization."',
'"Praise the Magic Conch!"',
'"the conch exploded into a thousand white fragments and ceased to exist."',
"\"S'right. It's a shell!\"",
'"Ralph felt a kind of affectionate reverence for the conch"',
'"Conch! Conch!"',
'"That\'s why you got the conch out of the water"',
'"the summons of the conch"',
'"Whoever holds the conch gets to speak."',
'"They\'ll come when they hear us--"',
'"We gotta drop the load!"',
'"Dude, we\'re falling right out the sky!!"',
(
'"Oh, Magic Conch Shell, what do we need to do to get '
'out of the Kelp Forest?"\n"Nothing."'
),
'"The shell knows all!"',
'"we must never question the wisdom of the Magic Conch."',
'"The Magic Conch! A club member!"',
'"The shell has spoken!"',
'"This copyrighted conch is the cornerstone of our organization."',
'"All right, Magic Conch... what do we do now?"',
'"Ohhh! The Magic Conch Shell! Ask it something! Ask it something!"',
]
def speak() -> str:
return random.choice(CONCHES)
class Config(dict):
"""A dict-like config object. Behaves like a normal dict except that
the ``context`` will always be converted from a list to a dict.
Defines the default configuration.
"""
def __init__(
self,
context: typing.Optional[Context] = None,
banner: typing.Optional[str] = None,
shell: typing.Type[Shell] = AutoShell,
prompt: typing.Optional[str] = None,
output: typing.Optional[str] = None,
context_format: str = "full",
**kwargs: typing.Any,
) -> None:
ctx = Config.transform_val(context) or {}
super().__init__(
context=ctx,
banner=banner,
shell=shell,
prompt=prompt,
output=output,
context_format=context_format,
**kwargs,
)
def __setitem__(self, key: typing.Any, value: typing.Any) -> None:
if key == "context":
value = Config.transform_val(value)
super().__setitem__(key, value)
@staticmethod
def transform_val(val: typing.Any) -> typing.Any:
if isinstance(val, (list, tuple)):
return context_list2dict(val)
return val
def update(self, d: typing.Mapping) -> None: # type: ignore
for key in d.keys():
# Shallow-merge context
if key == "context":
self["context"].update(Config.transform_val(d["context"]))
else:
self[key] = d[key]
SHELL_MAP: typing.Dict[str, typing.Type[Shell]] = {
"ipy": IPythonShell,
"ipython": IPythonShell,
"bpy": BPythonShell,
"bpython": BPythonShell,
"bpyc": BPythonCursesShell,
"bpython-curses": BPythonCursesShell,
"py": PythonShell,
"python": PythonShell,
"auto": AutoShell,
"ptpy": PtPythonShell,
"ptpython": PtPythonShell,
"ptipy": PtIPythonShell,
"ptipython": PtIPythonShell,
}
# _cfg and _config_registry are singletons that may be mutated in a .konchrc file
_cfg = Config()
_config_registry = {"default": _cfg}
def start(
context: typing.Optional[typing.Mapping] = None,
banner: typing.Optional[str] = None,
shell: typing.Type[Shell] = AutoShell,
prompt: typing.Optional[str] = None,
output: typing.Optional[str] = None,
context_format: str = "full",
**kwargs: typing.Any,
) -> None:
"""Start up the konch shell. Takes the same parameters as Shell.__init__.
"""
logger.debug(f"Using shell: {shell!r}")
if banner is None:
banner = speak()
# Default to global config
context_ = context or _cfg["context"]
banner_ = banner or _cfg["banner"]
if isinstance(shell, type) and issubclass(shell, Shell):
shell_ = shell
else:
shell_ = SHELL_MAP.get(shell or _cfg["shell"], _cfg["shell"])
prompt_ = prompt or _cfg["prompt"]
output_ = output or _cfg["output"]
context_format_ = context_format or _cfg["context_format"]
shell_(
context=context_,
banner=banner_,
prompt=prompt_,
output=output_,
context_format=context_format_,
**kwargs,
).start()
def config(config_dict: typing.Mapping) -> Config:
"""Configures the konch shell. This function should be called in a
.konchrc file.
:param dict config_dict: Dict that may contain 'context', 'banner', and/or
'shell' (default shell class to use).
"""
logger.debug(f"Updating with {config_dict}")
_cfg.update(config_dict)
return _cfg
def named_config(name: str, config_dict: typing.Mapping) -> None:
"""Adds a named config to the config registry. The first argument
may either be a string or a collection of strings.
This function should be called in a .konchrc file.
"""
names = (
name
if isinstance(name, Iterable) and not isinstance(name, (str, bytes))
else [name]
)
for each in names:
_config_registry[each] = Config(**config_dict)
def reset_config() -> Config:
global _cfg
_cfg = Config()
return _cfg
def __ensure_directory_in_path(filename: Path) -> None:
"""Ensures that a file's directory is in the Python path.
"""
directory = Path(filename).parent.resolve()
if directory not in sys.path:
logger.debug(f"Adding {directory} to sys.path")
sys.path.insert(0, str(directory))
CONFIG_FILE = Path(".konchrc")
DEFAULT_CONFIG_FILE = Path.home() / ".konchrc.default"
SEPARATOR = f"\n{'*' * 46}\n"
def confirm(text: str, default: bool = False) -> bool:
"""Display a confirmation prompt."""
choices = "Y/n" if default else "y/N"
prompt = f"{style(text, bold=True)} [{choices}]: "
while 1:
try:
print(prompt, end="")
value = input("").lower().strip()
except (KeyboardInterrupt, EOFError):
sys.exit(1)
if value in ("y", "yes"):
rv = True
elif value in ("n", "no"):
rv = False
elif value == "":
rv = default
else:
print_error("Error: invalid input")
continue
break
return rv
def use_file(
filename: typing.Union[Path, str, None], trust: bool = False
) -> typing.Union[types.ModuleType, None]:
"""Load filename as a python file. Import ``filename`` and return it
as a module.
"""
config_file = filename or resolve_path(CONFIG_FILE)
def preview_unauthorized() -> None:
if not config_file:
return None
print(SEPARATOR, file=sys.stderr)
with Path(config_file).open("r", encoding="utf-8") as fp:
for line in fp:
print(line, end="", file=sys.stderr)
print(SEPARATOR, file=sys.stderr)
if config_file and not Path(config_file).exists():
print_error(f'"{filename}" not found.')
sys.exit(1)
if config_file and Path(config_file).exists():
if not trust:
with AuthFile.load() as authfile:
try:
authfile.check(Path(config_file))
except KonchrcChangedError:
print_error(f'"{config_file}" has changed since you last used it.')
preview_unauthorized()
if confirm("Would you like to authorize it?"):
authfile.allow(Path(config_file))
print()
else:
sys.exit(1)
except KonchrcNotAuthorizedError:
print_error(f'"{config_file}" is blocked.')
preview_unauthorized()
if confirm("Would you like to authorize it?"):
authfile.allow(Path(config_file))
print()
else:
sys.exit(1)
logger.info(f"Using {config_file}")
# Ensure that relative imports are possible
__ensure_directory_in_path(Path(config_file))
mod = None
try:
mod = imp.load_source("konchrc", str(config_file))
except UnboundLocalError: # File not found
pass
else:
return mod
if not config_file:
print_warning("No konch config file found.")
else:
print_warning(f'"{config_file}" not found.')
return None
def resolve_path(filename: Path) -> typing.Union[Path, None]:
"""Find a file by walking up parent directories until the file is found.
Return the absolute path of the file.
"""
current = Path.cwd()
# Stop search at home directory
sentinel_dir = Path.home().parent.resolve()
while current != sentinel_dir:
target = Path(current) / Path(filename)
if target.exists():
return target.resolve()
else:
current = current.parent.resolve()
return None
def get_editor() -> str:
for key in "KONCH_EDITOR", "VISUAL", "EDITOR":
ret = os.environ.get(key)
if ret:
return ret
if sys.platform.startswith("win"):
return "notepad"
for editor in "vim", "nano":
if os.system("which %s &> /dev/null" % editor) == 0:
return editor
return "vi"
def edit_file(
filename: typing.Optional[Path], editor: typing.Optional[str] = None
) -> None:
if not filename:
print_error("filename not passed.")
sys.exit(1)
editor = editor or get_editor()
try:
result = subprocess.Popen(f'{editor} "{filename}"', shell=True)
exit_code = result.wait()
if exit_code != 0:
print_error(f"{editor}: Editing failed!")
sys.exit(1)
except OSError as err:
print_error(f"{editor}: Editing failed: {err}")
sys.exit(1)
else:
with AuthFile.load() as authfile:
authfile.allow(filename)
INIT_TEMPLATE = """# vi: set ft=python :
import konch
import sys
import os
# Available options:
# "context", "banner", "shell", "prompt", "output",
# "context_format", "ipy_extensions", "ipy_autoreload",
# "ipy_colors", "ipy_highlighting_style", "ptpy_vi_mode"
# See: https://konch.readthedocs.io/en/latest/#configuration
konch.config({
"context": [
sys,
os,
]
})
def setup():
pass
def teardown():
pass
"""
def init_config(config_file: Path) -> typing.NoReturn:
if not config_file.exists():
print(f'Writing to "{config_file.resolve()}"...')
print(SEPARATOR)
print(INIT_TEMPLATE, end="")
print(SEPARATOR)
init_template = INIT_TEMPLATE
if DEFAULT_CONFIG_FILE.exists(): # use ~/.konchrc.default if it exists
with Path(DEFAULT_CONFIG_FILE).open("r") as fp:
init_template = fp.read()
with Path(config_file).open("w") as fp:
fp.write(init_template)
with AuthFile.load() as authfile:
authfile.allow(config_file)
relpath = _relpath(config_file)
is_default = relpath == Path(CONFIG_FILE)
edit_cmd = "konch edit" if is_default else f"konch edit {relpath}"
run_cmd = "konch" if is_default else f"konch -f {relpath}"
print(f"{style('Done!', GREEN)} ✨ 🐚 ✨")
print(f"To edit your config: `{style(edit_cmd, bold=True)}`")
print(f"To start the shell: `{style(run_cmd, bold=True)}`")
sys.exit(0)
else:
print_error(f'"{config_file}" already exists in this directory.')
sys.exit(1)
def edit_config(
config_file: typing.Optional[Path] = None, editor: typing.Optional[str] = None
) -> typing.NoReturn:
filename = config_file or resolve_path(CONFIG_FILE)
if not filename:
print_error('No ".konchrc" file found.')
styled_cmd = style("konch init", bold=True, file=sys.stderr)
print(f"Run `{styled_cmd}` to create it.", file=sys.stderr)
sys.exit(1)
if not filename.exists():
print_error(f'"{filename}" does not exist.')
relpath = _relpath(filename)
is_default = relpath == Path(CONFIG_FILE)
cmd = "konch init" if is_default else f"konch init {filename}"
styled_cmd = style(cmd, bold=True, file=sys.stderr)
print(f"Run `{styled_cmd}` to create it.", file=sys.stderr)
sys.exit(1)
print(f'Editing file: "{filename}"')
edit_file(filename, editor=editor)
sys.exit(0)
def allow_config(config_file: typing.Optional[Path] = None) -> typing.NoReturn:
filename: typing.Union[Path, None]
if config_file and config_file.is_dir():
filename = Path(config_file) / CONFIG_FILE
else:
filename = config_file or resolve_path(CONFIG_FILE)
if not filename:
print_error("No config file found.")
sys.exit(1)
with AuthFile.load() as authfile:
if authfile.check(filename, raise_error=False):
print_warning(f'"{filename}" is already authorized.')
else:
try:
print(f'Authorizing "{filename}"...')
authfile.allow(filename)
except FileNotFoundError:
print_error(f'"{filename}" does not exist.')
sys.exit(1)
print(f"{style('Done!', GREEN)} ✨ 🐚 ✨")
relpath = _relpath(filename)
cmd = "konch" if relpath == Path(CONFIG_FILE) else f"konch -f {relpath}"
print(f"You can now start a shell with `{style(cmd, bold=True)}`.")
sys.exit(0)
def deny_config(config_file: typing.Optional[Path] = None) -> typing.NoReturn:
filename: typing.Union[Path, None]
if config_file and config_file.is_dir():
filename = Path(config_file) / CONFIG_FILE
else:
filename = config_file or resolve_path(CONFIG_FILE)
if not filename:
print_error("No config file found.")
sys.exit(1)
print(f'Removing authorization for "{filename}"...')
with AuthFile.load() as authfile:
try:
authfile.deny(filename)
except FileNotFoundError:
print_error(f'"{filename}" does not exist.')
sys.exit(1)
else:
print(style("Done!", GREEN))
sys.exit(0)
def parse_args(argv: typing.Optional[typing.Sequence] = None) -> typing.Dict[str, str]:
"""Exposes the docopt command-line arguments parser.
Return a dictionary of arguments.
"""
return docopt(__doc__, argv=argv, version=__version__)
def main(argv: typing.Optional[typing.Sequence] = None) -> typing.NoReturn:
"""Main entry point for the konch CLI."""
args = parse_args(argv)
if args["--debug"]:
logging.basicConfig(
format="%(levelname)s %(filename)s: %(message)s", level=logging.DEBUG
)
logger.debug(args)
config_file: typing.Union[Path, None]
if args["init"]:
config_file = Path(args["<config_file>"] or CONFIG_FILE)
init_config(config_file)
else:
config_file = Path(args["<config_file>"]) if args["<config_file>"] else None
if args["edit"]:
edit_config(config_file)
elif args["allow"]:
allow_config(config_file)
elif args["deny"]:
deny_config(config_file)
mod = use_file(Path(args["--file"]) if args["--file"] else None)
if hasattr(mod, "setup"):
mod.setup() # type: ignore
if args["--name"]:
if args["--name"] not in _config_registry:
print_error(f'Invalid --name: "{args["--name"]}"')
sys.exit(1)
config_dict = _config_registry[args["--name"]]
logger.debug(f'Using named config: "{args["--name"]}"')
logger.debug(config_dict)
else:
config_dict = _cfg
# Allow default shell to be overriden by command-line argument
shell_name = args["--shell"]
if shell_name:
config_dict["shell"] = SHELL_MAP.get(shell_name.lower(), AutoShell)
logger.debug(f"Starting with config {config_dict}")
start(**config_dict)
if hasattr(mod, "teardown"):
mod.teardown() # type: ignore
sys.exit(0)
if __name__ == "__main__":
main()
|
sloria/konch | konch.py | context_list2dict | python | def context_list2dict(context_list: typing.Sequence[typing.Any]) -> Context:
return {obj.__name__.split(".")[-1]: obj for obj in context_list} | Converts a list of objects (functions, classes, or modules) to a
dictionary mapping the object names to the objects. | train | https://github.com/sloria/konch/blob/15160bd0a0cac967eeeab84794bd6cdd0b5b637d/konch.py#L285-L289 | null | #!/usr/bin/env python3
"""konch: Customizes your Python shell.
Usage:
konch
konch init [<config_file>] [-d]
konch edit [<config_file>] [-d]
konch allow [<config_file>] [-d]
konch deny [<config_file>] [-d]
konch [--name=<name>] [--file=<file>] [--shell=<shell_name>] [-d]
Options:
-h --help Show this screen.
-v --version Show version.
init Creates a starter .konchrc file.
edit Edit your .konchrc file.
-n --name=<name> Named config to use.
-s --shell=<shell_name> Shell to use. Can be either "ipy" (IPython),
"bpy" (BPython), "bpyc" (BPython Curses),
"ptpy" (PtPython), "ptipy" (PtIPython),
"py" (built-in Python shell), or "auto".
Overrides the 'shell' option in .konchrc.
-f --file=<file> File path of konch config file to execute. If not provided,
konch will use the .konchrc file in the current
directory.
-d --debug Enable debugging/verbose mode.
Environment variables:
KONCH_AUTH_FILE: File where to store authorization data for config files.
Defaults to ~/.local/share/konch_auth.
KONCH_EDITOR: Editor command to use when running `konch edit`.
Falls back to $VISUAL then $EDITOR.
NO_COLOR: Disable ANSI colors.
"""
from collections.abc import Iterable
from pathlib import Path
import code
import hashlib
import imp
import json
import logging
import os
import random
import subprocess
import sys
import typing
import types
import warnings
from docopt import docopt
__version__ = "4.2.1"
logger = logging.getLogger(__name__)
class KonchError(Exception):
pass
class ShellNotAvailableError(KonchError):
pass
class KonchrcNotAuthorizedError(KonchError):
pass
class KonchrcChangedError(KonchrcNotAuthorizedError):
pass
class AuthFile:
def __init__(self, data: typing.Dict[str, str]) -> None:
self.data = data
def __repr__(self) -> str:
return f"AuthFile({self.data!r})"
@classmethod
def load(cls, path: typing.Optional[Path] = None) -> "AuthFile":
filepath = path or cls.get_path()
try:
with Path(filepath).open("r", encoding="utf-8") as fp:
data = json.load(fp)
except FileNotFoundError:
data = {}
except json.JSONDecodeError as error:
# File exists but is empty
if error.doc.strip() == "":
data = {}
else:
raise
return cls(data)
def allow(self, filepath: Path) -> None:
logger.debug(f"Authorizing {filepath}")
self.data[str(Path(filepath).resolve())] = self._hash_file(filepath)
def deny(self, filepath: Path) -> None:
if not filepath.exists():
raise FileNotFoundError(f"{filepath} not found")
try:
logger.debug(f"Removing authorization for {filepath}")
del self.data[str(filepath.resolve())]
except KeyError:
pass
def check(
self, filepath: typing.Union[Path, None], raise_error: bool = True
) -> bool:
if not filepath:
return False
if str(filepath.resolve()) not in self.data:
if raise_error:
raise KonchrcNotAuthorizedError
else:
return False
else:
file_hash = self._hash_file(filepath)
if file_hash != self.data[str(filepath.resolve())]:
if raise_error:
raise KonchrcChangedError
else:
return False
return True
def save(self) -> None:
filepath = self.get_path()
filepath.parent.mkdir(parents=True, exist_ok=True)
with Path(filepath).open("w", encoding="utf-8") as fp:
json.dump(self.data, fp)
def __enter__(self) -> "AuthFile":
return self
def __exit__(
self,
exc_type: typing.Type[Exception],
exc_value: Exception,
exc_traceback: types.TracebackType,
) -> None:
if not exc_type:
self.save()
@staticmethod
def get_path() -> Path:
if "KONCH_AUTH_FILE" in os.environ:
return Path(os.environ["KONCH_AUTH_FILE"])
elif "XDG_DATA_HOME" in os.environ:
return Path(os.environ["XDG_DATA_HOME"]) / "konch_auth"
else:
return Path.home() / ".local" / "share" / "konch_auth"
@staticmethod
def _hash_file(filepath: Path) -> str:
# https://stackoverflow.com/a/22058673/1157536
BUF_SIZE = 65536 # read in 64kb chunks
sha1 = hashlib.sha1()
with Path(filepath).open("rb") as f:
while True:
data = f.read(BUF_SIZE)
if not data:
break
sha1.update(data) # type: ignore
return sha1.hexdigest()
RED = 31
GREEN = 32
YELLOW = 33
BOLD = 1
RESET_ALL = 0
def style(
text: str,
fg: typing.Optional[int] = None,
*,
bold: bool = False,
file: typing.IO = sys.stdout,
) -> str:
use_color = not os.environ.get("NO_COLOR") and file.isatty()
if use_color:
parts = [
fg and f"\033[{fg}m",
bold and f"\033[{BOLD}m",
text,
f"\033[{RESET_ALL}m",
]
return "".join([e for e in parts if e])
else:
return text
def sprint(text: str, *args: typing.Any, **kwargs: typing.Any) -> None:
file = kwargs.pop("file", sys.stdout)
return print(style(text, file=file, *args, **kwargs), file=file)
def print_error(text: str) -> None:
prefix = style("ERROR", RED, file=sys.stderr)
return sprint(f"{prefix}: {text}", file=sys.stderr)
def print_warning(text: str) -> None:
prefix = style("WARNING", YELLOW, file=sys.stderr)
return sprint(f"{prefix}: {text}", file=sys.stderr)
Context = typing.Mapping[str, typing.Any]
Formatter = typing.Callable[[Context], str]
ContextFormat = typing.Union[str, Formatter]
def _full_formatter(context: Context) -> str:
line_format = "{name}: {obj!r}"
context_str = "\n".join(
[
line_format.format(name=name, obj=obj)
for name, obj in sorted(context.items(), key=lambda i: i[0].lower())
]
)
header = style("Context:", bold=True)
return f"\n{header}\n{context_str}"
def _short_formatter(context: Context) -> str:
context_str = ", ".join(sorted(context.keys(), key=str.lower))
header = style("Context:", bold=True)
return f"\n{header}\n{context_str}"
def _hide_formatter(context: Context) -> str:
return ""
CONTEXT_FORMATTERS: typing.Dict[str, Formatter] = {
"full": _full_formatter,
"short": _short_formatter,
"hide": _hide_formatter,
}
def format_context(
context: Context, formatter: typing.Union[str, Formatter] = "full"
) -> str:
"""Output the a context dictionary as a string."""
if not context:
return ""
if callable(formatter):
formatter_func = formatter
else:
if formatter in CONTEXT_FORMATTERS:
formatter_func = CONTEXT_FORMATTERS[formatter]
else:
raise ValueError(f'Invalid context format: "{formatter}"')
return formatter_func(context)
BANNER_TEMPLATE = """{version}
{text}
{context}
"""
def make_banner(
text: typing.Optional[str] = None,
context: typing.Optional[Context] = None,
banner_template: typing.Optional[str] = None,
context_format: ContextFormat = "full",
) -> str:
"""Generates a full banner with version info, the given text, and a
formatted list of context variables.
"""
banner_text = text or speak()
banner_template = banner_template or BANNER_TEMPLATE
ctx = format_context(context or {}, formatter=context_format)
out = banner_template.format(version=sys.version, text=banner_text, context=ctx)
return out
def _relpath(p: Path) -> Path:
return p.resolve().relative_to(Path.cwd())
class Shell:
"""Base shell class.
:param dict context: Dictionary, list, or callable (that returns a `dict` or `list`)
that defines what variables will be available when the shell is run.
:param str banner: Banner text that appears on startup.
:param str prompt: Custom input prompt.
:param str output: Custom output prompt.
:param context_format: Formatter for the context dictionary in the banner.
Either 'full', 'short', 'hide', or a function that receives the context
dictionary and outputs a string.
"""
banner_template: str = BANNER_TEMPLATE
def __init__(
self,
context: Context,
banner: typing.Optional[str] = None,
prompt: typing.Optional[str] = None,
output: typing.Optional[str] = None,
context_format: ContextFormat = "full",
**kwargs: typing.Any,
) -> None:
self.context = context() if callable(context) else context
self.context_format = context_format
self.banner = make_banner(
banner,
self.context,
context_format=self.context_format,
banner_template=self.banner_template,
)
self.prompt = prompt
self.output = output
def check_availability(self) -> bool:
raise NotImplementedError
def start(self) -> None:
raise NotImplementedError
class PythonShell(Shell):
"""The built-in Python shell."""
def check_availability(self) -> bool:
return True
def start(self) -> None:
try:
import readline
except ImportError:
pass
else:
# We don't have to wrap the following import in a 'try', because
# we already know 'readline' was imported successfully.
import rlcompleter
readline.set_completer(rlcompleter.Completer(self.context).complete)
readline.parse_and_bind("tab:complete")
if self.prompt:
sys.ps1 = self.prompt
if self.output:
warnings.warn("Custom output templates not supported by PythonShell.")
code.interact(self.banner, local=self.context)
return None
def configure_ipython_prompt(
config, prompt: typing.Optional[str] = None, output: typing.Optional[str] = None
) -> None:
import IPython
if IPython.version_info[0] >= 5: # Custom prompt API changed in IPython 5.0
from pygments.token import Token
# https://ipython.readthedocs.io/en/stable/config/details.html#custom-prompts # noqa: B950
class CustomPrompt(IPython.terminal.prompts.Prompts):
def in_prompt_tokens(self, *args, **kwargs):
if prompt is None:
return super().in_prompt_tokens(*args, **kwargs)
if isinstance(prompt, (str, bytes)):
return [(Token.Prompt, prompt)]
else:
return prompt
def out_prompt_tokens(self, *args, **kwargs):
if output is None:
return super().out_prompt_tokens(*args, **kwargs)
if isinstance(output, (str, bytes)):
return [(Token.OutPrompt, output)]
else:
return prompt
config.TerminalInteractiveShell.prompts_class = CustomPrompt
else:
prompt_config = config.PromptManager
if prompt:
prompt_config.in_template = prompt
if output:
prompt_config.out_template = output
return None
class IPythonShell(Shell):
"""The IPython shell.
:param list ipy_extensions: List of IPython extension names to load upon startup.
:param bool ipy_autoreload: Whether to load and initialize the IPython autoreload
extension upon startup. Can also be an integer, which will be passed as
the argument to the %autoreload line magic.
:param kwargs: The same kwargs as `Shell.__init__`.
"""
def __init__(
self,
ipy_extensions: typing.Optional[typing.List[str]] = None,
ipy_autoreload: bool = False,
ipy_colors: typing.Optional[str] = None,
ipy_highlighting_style: typing.Optional[str] = None,
*args: typing.Any,
**kwargs: typing.Any,
):
self.ipy_extensions = ipy_extensions
self.ipy_autoreload = ipy_autoreload
self.ipy_colors = ipy_colors
self.ipy_highlighting_style = ipy_highlighting_style
Shell.__init__(self, *args, **kwargs)
@staticmethod
def init_autoreload(mode: int) -> None:
"""Load and initialize the IPython autoreload extension."""
from IPython.extensions import autoreload
ip = get_ipython() # type: ignore # noqa: F821
autoreload.load_ipython_extension(ip)
ip.magics_manager.magics["line"]["autoreload"](str(mode))
def check_availability(self) -> bool:
try:
import IPython # noqa: F401
except ImportError:
raise ShellNotAvailableError("IPython shell not available.")
return True
def start(self) -> None:
try:
from IPython import start_ipython
from IPython.utils import io
from traitlets.config.loader import Config as IPyConfig
except ImportError:
raise ShellNotAvailableError(
"IPython shell not available " "or IPython version not supported."
)
# Hack to show custom banner
# TerminalIPythonApp/start_app doesn't allow you to customize the
# banner directly, so we write it to stdout before starting the IPython app
io.stdout.write(self.banner)
# Pass exec_lines in order to start autoreload
if self.ipy_autoreload:
if not isinstance(self.ipy_autoreload, bool):
mode = self.ipy_autoreload
else:
mode = 2
logger.debug(f"Initializing IPython autoreload in mode {mode}")
exec_lines = [
"import konch as __konch",
f"__konch.IPythonShell.init_autoreload({mode})",
]
else:
exec_lines = []
ipy_config = IPyConfig()
if self.ipy_colors:
ipy_config.TerminalInteractiveShell.colors = self.ipy_colors
if self.ipy_highlighting_style:
ipy_config.TerminalInteractiveShell.highlighting_style = (
self.ipy_highlighting_style
)
configure_ipython_prompt(ipy_config, prompt=self.prompt, output=self.output)
# Use start_ipython rather than embed so that IPython is loaded in the "normal"
# way. See https://github.com/django/django/pull/512
start_ipython(
display_banner=False,
user_ns=self.context,
config=ipy_config,
extensions=self.ipy_extensions or [],
exec_lines=exec_lines,
argv=[],
)
return None
class PtPythonShell(Shell):
def __init__(self, ptpy_vi_mode: bool = False, *args, **kwargs):
self.ptpy_vi_mode = ptpy_vi_mode
Shell.__init__(self, *args, **kwargs)
def check_availability(self) -> bool:
try:
import ptpython # noqa: F401
except ImportError:
raise ShellNotAvailableError("PtPython shell not available.")
return True
def start(self) -> None:
try:
from ptpython.repl import embed, run_config
except ImportError:
raise ShellNotAvailableError("PtPython shell not available.")
print(self.banner)
config_dir = Path("~/.ptpython/").expanduser()
# Startup path
startup_paths = []
if "PYTHONSTARTUP" in os.environ:
startup_paths.append(os.environ["PYTHONSTARTUP"])
# Apply config file
def configure(repl):
path = config_dir / "config.py"
if path.exists():
run_config(repl, str(path))
embed(
globals=self.context,
history_filename=config_dir / "history",
vi_mode=self.ptpy_vi_mode,
startup_paths=startup_paths,
configure=configure,
)
return None
class PtIPythonShell(PtPythonShell):
banner_template: str = "{text}\n{context}"
def __init__(
self, ipy_extensions: typing.Optional[typing.List[str]] = None, *args, **kwargs
) -> None:
self.ipy_extensions = ipy_extensions or []
PtPythonShell.__init__(self, *args, **kwargs)
def check_availability(self) -> bool:
try:
import ptpython.ipython # noqa: F401
import IPython # noqa: F401
except ImportError:
raise ShellNotAvailableError("PtIPython shell not available.")
return True
def start(self) -> None:
try:
from ptpython.ipython import embed
from ptpython.repl import run_config
from IPython.terminal.ipapp import load_default_config
except ImportError:
raise ShellNotAvailableError("PtIPython shell not available.")
config_dir = Path("~/.ptpython/").expanduser()
# Apply config file
def configure(repl):
path = config_dir / "config.py"
if path.exists():
run_config(repl, str(path))
# Startup path
startup_paths = []
if "PYTHONSTARTUP" in os.environ:
startup_paths.append(os.environ["PYTHONSTARTUP"])
# exec scripts from startup paths
for path in startup_paths:
if Path(path).exists():
with Path(path).open("rb") as f:
code = compile(f.read(), path, "exec")
exec(code, self.context, self.context)
else:
print(f"File not found: {path}\n\n")
sys.exit(1)
ipy_config = load_default_config()
ipy_config.InteractiveShellEmbed = ipy_config.TerminalInteractiveShell
ipy_config["InteractiveShellApp"]["extensions"] = self.ipy_extensions
configure_ipython_prompt(ipy_config, prompt=self.prompt, output=self.output)
embed(
config=ipy_config,
configure=configure,
history_filename=config_dir / "history",
user_ns=self.context,
header=self.banner,
vi_mode=self.ptpy_vi_mode,
)
return None
class BPythonShell(Shell):
"""The BPython shell."""
def check_availability(self) -> bool:
try:
import bpython # noqa: F401
except ImportError:
raise ShellNotAvailableError("BPython shell not available.")
return True
def start(self) -> None:
try:
from bpython import embed
except ImportError:
raise ShellNotAvailableError("BPython shell not available.")
if self.prompt:
warnings.warn("Custom prompts not supported by BPythonShell.")
if self.output:
warnings.warn("Custom output templates not supported by BPythonShell.")
embed(banner=self.banner, locals_=self.context)
return None
class BPythonCursesShell(Shell):
"""The BPython Curses shell."""
def check_availability(self) -> bool:
try:
import bpython.cli # noqa: F401
except ImportError:
raise ShellNotAvailableError("BPython Curses shell not available.")
return True
def start(self) -> None:
try:
from bpython.cli import main
except ImportError:
raise ShellNotAvailableError("BPython Curses shell not available.")
if self.prompt:
warnings.warn("Custom prompts not supported by BPython Curses shell.")
if self.output:
warnings.warn(
"Custom output templates not supported by BPython Curses shell."
)
main(banner=self.banner, locals_=self.context, args=["-i", "-q"])
return None
class AutoShell(Shell):
"""Shell that runs PtIpython, PtPython, IPython, or BPython if available.
Falls back to built-in Python shell.
"""
# Shell classes in precedence order
SHELLS = [
PtIPythonShell,
PtPythonShell,
IPythonShell,
BPythonShell,
BPythonCursesShell,
PythonShell,
]
def __init__(self, context: Context, banner: str, **kwargs):
Shell.__init__(self, context, **kwargs)
self.kwargs = kwargs
self.banner = banner
def check_availability(self) -> bool:
return True
def start(self) -> None:
shell_args = {
"context": self.context,
"banner": self.banner,
"prompt": self.prompt,
"output": self.output,
"context_format": self.context_format,
}
shell_args.update(self.kwargs)
shell = None
for shell_class in self.SHELLS:
try:
shell = shell_class(**shell_args)
shell.check_availability()
except ShellNotAvailableError:
continue
else:
break
else:
raise ShellNotAvailableError("No available shell to run.")
return shell.start()
CONCHES: typing.List[str] = [
'"My conch told me to come save you guys."\n"Hooray for the magic conches!"',
'"All hail the Magic Conch!"',
'"Hooray for the magic conches!"',
'"Uh, hello there. Magic Conch, I was wondering... '
'should I have the spaghetti or the turkey?"',
'"This copyrighted conch is the cornerstone of our organization."',
'"Praise the Magic Conch!"',
'"the conch exploded into a thousand white fragments and ceased to exist."',
"\"S'right. It's a shell!\"",
'"Ralph felt a kind of affectionate reverence for the conch"',
'"Conch! Conch!"',
'"That\'s why you got the conch out of the water"',
'"the summons of the conch"',
'"Whoever holds the conch gets to speak."',
'"They\'ll come when they hear us--"',
'"We gotta drop the load!"',
'"Dude, we\'re falling right out the sky!!"',
(
'"Oh, Magic Conch Shell, what do we need to do to get '
'out of the Kelp Forest?"\n"Nothing."'
),
'"The shell knows all!"',
'"we must never question the wisdom of the Magic Conch."',
'"The Magic Conch! A club member!"',
'"The shell has spoken!"',
'"This copyrighted conch is the cornerstone of our organization."',
'"All right, Magic Conch... what do we do now?"',
'"Ohhh! The Magic Conch Shell! Ask it something! Ask it something!"',
]
def speak() -> str:
return random.choice(CONCHES)
class Config(dict):
"""A dict-like config object. Behaves like a normal dict except that
the ``context`` will always be converted from a list to a dict.
Defines the default configuration.
"""
def __init__(
self,
context: typing.Optional[Context] = None,
banner: typing.Optional[str] = None,
shell: typing.Type[Shell] = AutoShell,
prompt: typing.Optional[str] = None,
output: typing.Optional[str] = None,
context_format: str = "full",
**kwargs: typing.Any,
) -> None:
ctx = Config.transform_val(context) or {}
super().__init__(
context=ctx,
banner=banner,
shell=shell,
prompt=prompt,
output=output,
context_format=context_format,
**kwargs,
)
def __setitem__(self, key: typing.Any, value: typing.Any) -> None:
if key == "context":
value = Config.transform_val(value)
super().__setitem__(key, value)
@staticmethod
def transform_val(val: typing.Any) -> typing.Any:
if isinstance(val, (list, tuple)):
return context_list2dict(val)
return val
def update(self, d: typing.Mapping) -> None: # type: ignore
for key in d.keys():
# Shallow-merge context
if key == "context":
self["context"].update(Config.transform_val(d["context"]))
else:
self[key] = d[key]
SHELL_MAP: typing.Dict[str, typing.Type[Shell]] = {
"ipy": IPythonShell,
"ipython": IPythonShell,
"bpy": BPythonShell,
"bpython": BPythonShell,
"bpyc": BPythonCursesShell,
"bpython-curses": BPythonCursesShell,
"py": PythonShell,
"python": PythonShell,
"auto": AutoShell,
"ptpy": PtPythonShell,
"ptpython": PtPythonShell,
"ptipy": PtIPythonShell,
"ptipython": PtIPythonShell,
}
# _cfg and _config_registry are singletons that may be mutated in a .konchrc file
_cfg = Config()
_config_registry = {"default": _cfg}
def start(
context: typing.Optional[typing.Mapping] = None,
banner: typing.Optional[str] = None,
shell: typing.Type[Shell] = AutoShell,
prompt: typing.Optional[str] = None,
output: typing.Optional[str] = None,
context_format: str = "full",
**kwargs: typing.Any,
) -> None:
"""Start up the konch shell. Takes the same parameters as Shell.__init__.
"""
logger.debug(f"Using shell: {shell!r}")
if banner is None:
banner = speak()
# Default to global config
context_ = context or _cfg["context"]
banner_ = banner or _cfg["banner"]
if isinstance(shell, type) and issubclass(shell, Shell):
shell_ = shell
else:
shell_ = SHELL_MAP.get(shell or _cfg["shell"], _cfg["shell"])
prompt_ = prompt or _cfg["prompt"]
output_ = output or _cfg["output"]
context_format_ = context_format or _cfg["context_format"]
shell_(
context=context_,
banner=banner_,
prompt=prompt_,
output=output_,
context_format=context_format_,
**kwargs,
).start()
def config(config_dict: typing.Mapping) -> Config:
"""Configures the konch shell. This function should be called in a
.konchrc file.
:param dict config_dict: Dict that may contain 'context', 'banner', and/or
'shell' (default shell class to use).
"""
logger.debug(f"Updating with {config_dict}")
_cfg.update(config_dict)
return _cfg
def named_config(name: str, config_dict: typing.Mapping) -> None:
"""Adds a named config to the config registry. The first argument
may either be a string or a collection of strings.
This function should be called in a .konchrc file.
"""
names = (
name
if isinstance(name, Iterable) and not isinstance(name, (str, bytes))
else [name]
)
for each in names:
_config_registry[each] = Config(**config_dict)
def reset_config() -> Config:
global _cfg
_cfg = Config()
return _cfg
def __ensure_directory_in_path(filename: Path) -> None:
"""Ensures that a file's directory is in the Python path.
"""
directory = Path(filename).parent.resolve()
if directory not in sys.path:
logger.debug(f"Adding {directory} to sys.path")
sys.path.insert(0, str(directory))
CONFIG_FILE = Path(".konchrc")
DEFAULT_CONFIG_FILE = Path.home() / ".konchrc.default"
SEPARATOR = f"\n{'*' * 46}\n"
def confirm(text: str, default: bool = False) -> bool:
"""Display a confirmation prompt."""
choices = "Y/n" if default else "y/N"
prompt = f"{style(text, bold=True)} [{choices}]: "
while 1:
try:
print(prompt, end="")
value = input("").lower().strip()
except (KeyboardInterrupt, EOFError):
sys.exit(1)
if value in ("y", "yes"):
rv = True
elif value in ("n", "no"):
rv = False
elif value == "":
rv = default
else:
print_error("Error: invalid input")
continue
break
return rv
def use_file(
filename: typing.Union[Path, str, None], trust: bool = False
) -> typing.Union[types.ModuleType, None]:
"""Load filename as a python file. Import ``filename`` and return it
as a module.
"""
config_file = filename or resolve_path(CONFIG_FILE)
def preview_unauthorized() -> None:
if not config_file:
return None
print(SEPARATOR, file=sys.stderr)
with Path(config_file).open("r", encoding="utf-8") as fp:
for line in fp:
print(line, end="", file=sys.stderr)
print(SEPARATOR, file=sys.stderr)
if config_file and not Path(config_file).exists():
print_error(f'"{filename}" not found.')
sys.exit(1)
if config_file and Path(config_file).exists():
if not trust:
with AuthFile.load() as authfile:
try:
authfile.check(Path(config_file))
except KonchrcChangedError:
print_error(f'"{config_file}" has changed since you last used it.')
preview_unauthorized()
if confirm("Would you like to authorize it?"):
authfile.allow(Path(config_file))
print()
else:
sys.exit(1)
except KonchrcNotAuthorizedError:
print_error(f'"{config_file}" is blocked.')
preview_unauthorized()
if confirm("Would you like to authorize it?"):
authfile.allow(Path(config_file))
print()
else:
sys.exit(1)
logger.info(f"Using {config_file}")
# Ensure that relative imports are possible
__ensure_directory_in_path(Path(config_file))
mod = None
try:
mod = imp.load_source("konchrc", str(config_file))
except UnboundLocalError: # File not found
pass
else:
return mod
if not config_file:
print_warning("No konch config file found.")
else:
print_warning(f'"{config_file}" not found.')
return None
def resolve_path(filename: Path) -> typing.Union[Path, None]:
"""Find a file by walking up parent directories until the file is found.
Return the absolute path of the file.
"""
current = Path.cwd()
# Stop search at home directory
sentinel_dir = Path.home().parent.resolve()
while current != sentinel_dir:
target = Path(current) / Path(filename)
if target.exists():
return target.resolve()
else:
current = current.parent.resolve()
return None
def get_editor() -> str:
for key in "KONCH_EDITOR", "VISUAL", "EDITOR":
ret = os.environ.get(key)
if ret:
return ret
if sys.platform.startswith("win"):
return "notepad"
for editor in "vim", "nano":
if os.system("which %s &> /dev/null" % editor) == 0:
return editor
return "vi"
def edit_file(
filename: typing.Optional[Path], editor: typing.Optional[str] = None
) -> None:
if not filename:
print_error("filename not passed.")
sys.exit(1)
editor = editor or get_editor()
try:
result = subprocess.Popen(f'{editor} "{filename}"', shell=True)
exit_code = result.wait()
if exit_code != 0:
print_error(f"{editor}: Editing failed!")
sys.exit(1)
except OSError as err:
print_error(f"{editor}: Editing failed: {err}")
sys.exit(1)
else:
with AuthFile.load() as authfile:
authfile.allow(filename)
INIT_TEMPLATE = """# vi: set ft=python :
import konch
import sys
import os
# Available options:
# "context", "banner", "shell", "prompt", "output",
# "context_format", "ipy_extensions", "ipy_autoreload",
# "ipy_colors", "ipy_highlighting_style", "ptpy_vi_mode"
# See: https://konch.readthedocs.io/en/latest/#configuration
konch.config({
"context": [
sys,
os,
]
})
def setup():
pass
def teardown():
pass
"""
def init_config(config_file: Path) -> typing.NoReturn:
if not config_file.exists():
print(f'Writing to "{config_file.resolve()}"...')
print(SEPARATOR)
print(INIT_TEMPLATE, end="")
print(SEPARATOR)
init_template = INIT_TEMPLATE
if DEFAULT_CONFIG_FILE.exists(): # use ~/.konchrc.default if it exists
with Path(DEFAULT_CONFIG_FILE).open("r") as fp:
init_template = fp.read()
with Path(config_file).open("w") as fp:
fp.write(init_template)
with AuthFile.load() as authfile:
authfile.allow(config_file)
relpath = _relpath(config_file)
is_default = relpath == Path(CONFIG_FILE)
edit_cmd = "konch edit" if is_default else f"konch edit {relpath}"
run_cmd = "konch" if is_default else f"konch -f {relpath}"
print(f"{style('Done!', GREEN)} ✨ 🐚 ✨")
print(f"To edit your config: `{style(edit_cmd, bold=True)}`")
print(f"To start the shell: `{style(run_cmd, bold=True)}`")
sys.exit(0)
else:
print_error(f'"{config_file}" already exists in this directory.')
sys.exit(1)
def edit_config(
config_file: typing.Optional[Path] = None, editor: typing.Optional[str] = None
) -> typing.NoReturn:
filename = config_file or resolve_path(CONFIG_FILE)
if not filename:
print_error('No ".konchrc" file found.')
styled_cmd = style("konch init", bold=True, file=sys.stderr)
print(f"Run `{styled_cmd}` to create it.", file=sys.stderr)
sys.exit(1)
if not filename.exists():
print_error(f'"{filename}" does not exist.')
relpath = _relpath(filename)
is_default = relpath == Path(CONFIG_FILE)
cmd = "konch init" if is_default else f"konch init {filename}"
styled_cmd = style(cmd, bold=True, file=sys.stderr)
print(f"Run `{styled_cmd}` to create it.", file=sys.stderr)
sys.exit(1)
print(f'Editing file: "{filename}"')
edit_file(filename, editor=editor)
sys.exit(0)
def allow_config(config_file: typing.Optional[Path] = None) -> typing.NoReturn:
filename: typing.Union[Path, None]
if config_file and config_file.is_dir():
filename = Path(config_file) / CONFIG_FILE
else:
filename = config_file or resolve_path(CONFIG_FILE)
if not filename:
print_error("No config file found.")
sys.exit(1)
with AuthFile.load() as authfile:
if authfile.check(filename, raise_error=False):
print_warning(f'"{filename}" is already authorized.')
else:
try:
print(f'Authorizing "{filename}"...')
authfile.allow(filename)
except FileNotFoundError:
print_error(f'"{filename}" does not exist.')
sys.exit(1)
print(f"{style('Done!', GREEN)} ✨ 🐚 ✨")
relpath = _relpath(filename)
cmd = "konch" if relpath == Path(CONFIG_FILE) else f"konch -f {relpath}"
print(f"You can now start a shell with `{style(cmd, bold=True)}`.")
sys.exit(0)
def deny_config(config_file: typing.Optional[Path] = None) -> typing.NoReturn:
filename: typing.Union[Path, None]
if config_file and config_file.is_dir():
filename = Path(config_file) / CONFIG_FILE
else:
filename = config_file or resolve_path(CONFIG_FILE)
if not filename:
print_error("No config file found.")
sys.exit(1)
print(f'Removing authorization for "{filename}"...')
with AuthFile.load() as authfile:
try:
authfile.deny(filename)
except FileNotFoundError:
print_error(f'"{filename}" does not exist.')
sys.exit(1)
else:
print(style("Done!", GREEN))
sys.exit(0)
def parse_args(argv: typing.Optional[typing.Sequence] = None) -> typing.Dict[str, str]:
"""Exposes the docopt command-line arguments parser.
Return a dictionary of arguments.
"""
return docopt(__doc__, argv=argv, version=__version__)
def main(argv: typing.Optional[typing.Sequence] = None) -> typing.NoReturn:
"""Main entry point for the konch CLI."""
args = parse_args(argv)
if args["--debug"]:
logging.basicConfig(
format="%(levelname)s %(filename)s: %(message)s", level=logging.DEBUG
)
logger.debug(args)
config_file: typing.Union[Path, None]
if args["init"]:
config_file = Path(args["<config_file>"] or CONFIG_FILE)
init_config(config_file)
else:
config_file = Path(args["<config_file>"]) if args["<config_file>"] else None
if args["edit"]:
edit_config(config_file)
elif args["allow"]:
allow_config(config_file)
elif args["deny"]:
deny_config(config_file)
mod = use_file(Path(args["--file"]) if args["--file"] else None)
if hasattr(mod, "setup"):
mod.setup() # type: ignore
if args["--name"]:
if args["--name"] not in _config_registry:
print_error(f'Invalid --name: "{args["--name"]}"')
sys.exit(1)
config_dict = _config_registry[args["--name"]]
logger.debug(f'Using named config: "{args["--name"]}"')
logger.debug(config_dict)
else:
config_dict = _cfg
# Allow default shell to be overriden by command-line argument
shell_name = args["--shell"]
if shell_name:
config_dict["shell"] = SHELL_MAP.get(shell_name.lower(), AutoShell)
logger.debug(f"Starting with config {config_dict}")
start(**config_dict)
if hasattr(mod, "teardown"):
mod.teardown() # type: ignore
sys.exit(0)
if __name__ == "__main__":
main()
|
sloria/konch | konch.py | start | python | def start(
context: typing.Optional[typing.Mapping] = None,
banner: typing.Optional[str] = None,
shell: typing.Type[Shell] = AutoShell,
prompt: typing.Optional[str] = None,
output: typing.Optional[str] = None,
context_format: str = "full",
**kwargs: typing.Any,
) -> None:
logger.debug(f"Using shell: {shell!r}")
if banner is None:
banner = speak()
# Default to global config
context_ = context or _cfg["context"]
banner_ = banner or _cfg["banner"]
if isinstance(shell, type) and issubclass(shell, Shell):
shell_ = shell
else:
shell_ = SHELL_MAP.get(shell or _cfg["shell"], _cfg["shell"])
prompt_ = prompt or _cfg["prompt"]
output_ = output or _cfg["output"]
context_format_ = context_format or _cfg["context_format"]
shell_(
context=context_,
banner=banner_,
prompt=prompt_,
output=output_,
context_format=context_format_,
**kwargs,
).start() | Start up the konch shell. Takes the same parameters as Shell.__init__. | train | https://github.com/sloria/konch/blob/15160bd0a0cac967eeeab84794bd6cdd0b5b637d/konch.py#L794-L825 | [
"def speak() -> str:\n return random.choice(CONCHES)\n",
"def start(self) -> None:\n shell_args = {\n \"context\": self.context,\n \"banner\": self.banner,\n \"prompt\": self.prompt,\n \"output\": self.output,\n \"context_format\": self.context_format,\n }\n shell_args.update(self.kwargs)\n shell = None\n\n for shell_class in self.SHELLS:\n try:\n shell = shell_class(**shell_args)\n shell.check_availability()\n except ShellNotAvailableError:\n continue\n else:\n break\n else:\n raise ShellNotAvailableError(\"No available shell to run.\")\n return shell.start()\n"
] | #!/usr/bin/env python3
"""konch: Customizes your Python shell.
Usage:
konch
konch init [<config_file>] [-d]
konch edit [<config_file>] [-d]
konch allow [<config_file>] [-d]
konch deny [<config_file>] [-d]
konch [--name=<name>] [--file=<file>] [--shell=<shell_name>] [-d]
Options:
-h --help Show this screen.
-v --version Show version.
init Creates a starter .konchrc file.
edit Edit your .konchrc file.
-n --name=<name> Named config to use.
-s --shell=<shell_name> Shell to use. Can be either "ipy" (IPython),
"bpy" (BPython), "bpyc" (BPython Curses),
"ptpy" (PtPython), "ptipy" (PtIPython),
"py" (built-in Python shell), or "auto".
Overrides the 'shell' option in .konchrc.
-f --file=<file> File path of konch config file to execute. If not provided,
konch will use the .konchrc file in the current
directory.
-d --debug Enable debugging/verbose mode.
Environment variables:
KONCH_AUTH_FILE: File where to store authorization data for config files.
Defaults to ~/.local/share/konch_auth.
KONCH_EDITOR: Editor command to use when running `konch edit`.
Falls back to $VISUAL then $EDITOR.
NO_COLOR: Disable ANSI colors.
"""
from collections.abc import Iterable
from pathlib import Path
import code
import hashlib
import imp
import json
import logging
import os
import random
import subprocess
import sys
import typing
import types
import warnings
from docopt import docopt
__version__ = "4.2.1"
logger = logging.getLogger(__name__)
class KonchError(Exception):
pass
class ShellNotAvailableError(KonchError):
pass
class KonchrcNotAuthorizedError(KonchError):
pass
class KonchrcChangedError(KonchrcNotAuthorizedError):
pass
class AuthFile:
def __init__(self, data: typing.Dict[str, str]) -> None:
self.data = data
def __repr__(self) -> str:
return f"AuthFile({self.data!r})"
@classmethod
def load(cls, path: typing.Optional[Path] = None) -> "AuthFile":
filepath = path or cls.get_path()
try:
with Path(filepath).open("r", encoding="utf-8") as fp:
data = json.load(fp)
except FileNotFoundError:
data = {}
except json.JSONDecodeError as error:
# File exists but is empty
if error.doc.strip() == "":
data = {}
else:
raise
return cls(data)
def allow(self, filepath: Path) -> None:
logger.debug(f"Authorizing {filepath}")
self.data[str(Path(filepath).resolve())] = self._hash_file(filepath)
def deny(self, filepath: Path) -> None:
if not filepath.exists():
raise FileNotFoundError(f"{filepath} not found")
try:
logger.debug(f"Removing authorization for {filepath}")
del self.data[str(filepath.resolve())]
except KeyError:
pass
def check(
self, filepath: typing.Union[Path, None], raise_error: bool = True
) -> bool:
if not filepath:
return False
if str(filepath.resolve()) not in self.data:
if raise_error:
raise KonchrcNotAuthorizedError
else:
return False
else:
file_hash = self._hash_file(filepath)
if file_hash != self.data[str(filepath.resolve())]:
if raise_error:
raise KonchrcChangedError
else:
return False
return True
def save(self) -> None:
filepath = self.get_path()
filepath.parent.mkdir(parents=True, exist_ok=True)
with Path(filepath).open("w", encoding="utf-8") as fp:
json.dump(self.data, fp)
def __enter__(self) -> "AuthFile":
return self
def __exit__(
self,
exc_type: typing.Type[Exception],
exc_value: Exception,
exc_traceback: types.TracebackType,
) -> None:
if not exc_type:
self.save()
@staticmethod
def get_path() -> Path:
if "KONCH_AUTH_FILE" in os.environ:
return Path(os.environ["KONCH_AUTH_FILE"])
elif "XDG_DATA_HOME" in os.environ:
return Path(os.environ["XDG_DATA_HOME"]) / "konch_auth"
else:
return Path.home() / ".local" / "share" / "konch_auth"
@staticmethod
def _hash_file(filepath: Path) -> str:
# https://stackoverflow.com/a/22058673/1157536
BUF_SIZE = 65536 # read in 64kb chunks
sha1 = hashlib.sha1()
with Path(filepath).open("rb") as f:
while True:
data = f.read(BUF_SIZE)
if not data:
break
sha1.update(data) # type: ignore
return sha1.hexdigest()
RED = 31
GREEN = 32
YELLOW = 33
BOLD = 1
RESET_ALL = 0
def style(
text: str,
fg: typing.Optional[int] = None,
*,
bold: bool = False,
file: typing.IO = sys.stdout,
) -> str:
use_color = not os.environ.get("NO_COLOR") and file.isatty()
if use_color:
parts = [
fg and f"\033[{fg}m",
bold and f"\033[{BOLD}m",
text,
f"\033[{RESET_ALL}m",
]
return "".join([e for e in parts if e])
else:
return text
def sprint(text: str, *args: typing.Any, **kwargs: typing.Any) -> None:
file = kwargs.pop("file", sys.stdout)
return print(style(text, file=file, *args, **kwargs), file=file)
def print_error(text: str) -> None:
prefix = style("ERROR", RED, file=sys.stderr)
return sprint(f"{prefix}: {text}", file=sys.stderr)
def print_warning(text: str) -> None:
prefix = style("WARNING", YELLOW, file=sys.stderr)
return sprint(f"{prefix}: {text}", file=sys.stderr)
Context = typing.Mapping[str, typing.Any]
Formatter = typing.Callable[[Context], str]
ContextFormat = typing.Union[str, Formatter]
def _full_formatter(context: Context) -> str:
line_format = "{name}: {obj!r}"
context_str = "\n".join(
[
line_format.format(name=name, obj=obj)
for name, obj in sorted(context.items(), key=lambda i: i[0].lower())
]
)
header = style("Context:", bold=True)
return f"\n{header}\n{context_str}"
def _short_formatter(context: Context) -> str:
context_str = ", ".join(sorted(context.keys(), key=str.lower))
header = style("Context:", bold=True)
return f"\n{header}\n{context_str}"
def _hide_formatter(context: Context) -> str:
return ""
CONTEXT_FORMATTERS: typing.Dict[str, Formatter] = {
"full": _full_formatter,
"short": _short_formatter,
"hide": _hide_formatter,
}
def format_context(
context: Context, formatter: typing.Union[str, Formatter] = "full"
) -> str:
"""Output the a context dictionary as a string."""
if not context:
return ""
if callable(formatter):
formatter_func = formatter
else:
if formatter in CONTEXT_FORMATTERS:
formatter_func = CONTEXT_FORMATTERS[formatter]
else:
raise ValueError(f'Invalid context format: "{formatter}"')
return formatter_func(context)
BANNER_TEMPLATE = """{version}
{text}
{context}
"""
def make_banner(
text: typing.Optional[str] = None,
context: typing.Optional[Context] = None,
banner_template: typing.Optional[str] = None,
context_format: ContextFormat = "full",
) -> str:
"""Generates a full banner with version info, the given text, and a
formatted list of context variables.
"""
banner_text = text or speak()
banner_template = banner_template or BANNER_TEMPLATE
ctx = format_context(context or {}, formatter=context_format)
out = banner_template.format(version=sys.version, text=banner_text, context=ctx)
return out
def context_list2dict(context_list: typing.Sequence[typing.Any]) -> Context:
"""Converts a list of objects (functions, classes, or modules) to a
dictionary mapping the object names to the objects.
"""
return {obj.__name__.split(".")[-1]: obj for obj in context_list}
def _relpath(p: Path) -> Path:
return p.resolve().relative_to(Path.cwd())
class Shell:
"""Base shell class.
:param dict context: Dictionary, list, or callable (that returns a `dict` or `list`)
that defines what variables will be available when the shell is run.
:param str banner: Banner text that appears on startup.
:param str prompt: Custom input prompt.
:param str output: Custom output prompt.
:param context_format: Formatter for the context dictionary in the banner.
Either 'full', 'short', 'hide', or a function that receives the context
dictionary and outputs a string.
"""
banner_template: str = BANNER_TEMPLATE
def __init__(
self,
context: Context,
banner: typing.Optional[str] = None,
prompt: typing.Optional[str] = None,
output: typing.Optional[str] = None,
context_format: ContextFormat = "full",
**kwargs: typing.Any,
) -> None:
self.context = context() if callable(context) else context
self.context_format = context_format
self.banner = make_banner(
banner,
self.context,
context_format=self.context_format,
banner_template=self.banner_template,
)
self.prompt = prompt
self.output = output
def check_availability(self) -> bool:
raise NotImplementedError
def start(self) -> None:
raise NotImplementedError
class PythonShell(Shell):
"""The built-in Python shell."""
def check_availability(self) -> bool:
return True
def start(self) -> None:
try:
import readline
except ImportError:
pass
else:
# We don't have to wrap the following import in a 'try', because
# we already know 'readline' was imported successfully.
import rlcompleter
readline.set_completer(rlcompleter.Completer(self.context).complete)
readline.parse_and_bind("tab:complete")
if self.prompt:
sys.ps1 = self.prompt
if self.output:
warnings.warn("Custom output templates not supported by PythonShell.")
code.interact(self.banner, local=self.context)
return None
def configure_ipython_prompt(
config, prompt: typing.Optional[str] = None, output: typing.Optional[str] = None
) -> None:
import IPython
if IPython.version_info[0] >= 5: # Custom prompt API changed in IPython 5.0
from pygments.token import Token
# https://ipython.readthedocs.io/en/stable/config/details.html#custom-prompts # noqa: B950
class CustomPrompt(IPython.terminal.prompts.Prompts):
def in_prompt_tokens(self, *args, **kwargs):
if prompt is None:
return super().in_prompt_tokens(*args, **kwargs)
if isinstance(prompt, (str, bytes)):
return [(Token.Prompt, prompt)]
else:
return prompt
def out_prompt_tokens(self, *args, **kwargs):
if output is None:
return super().out_prompt_tokens(*args, **kwargs)
if isinstance(output, (str, bytes)):
return [(Token.OutPrompt, output)]
else:
return prompt
config.TerminalInteractiveShell.prompts_class = CustomPrompt
else:
prompt_config = config.PromptManager
if prompt:
prompt_config.in_template = prompt
if output:
prompt_config.out_template = output
return None
class IPythonShell(Shell):
"""The IPython shell.
:param list ipy_extensions: List of IPython extension names to load upon startup.
:param bool ipy_autoreload: Whether to load and initialize the IPython autoreload
extension upon startup. Can also be an integer, which will be passed as
the argument to the %autoreload line magic.
:param kwargs: The same kwargs as `Shell.__init__`.
"""
def __init__(
self,
ipy_extensions: typing.Optional[typing.List[str]] = None,
ipy_autoreload: bool = False,
ipy_colors: typing.Optional[str] = None,
ipy_highlighting_style: typing.Optional[str] = None,
*args: typing.Any,
**kwargs: typing.Any,
):
self.ipy_extensions = ipy_extensions
self.ipy_autoreload = ipy_autoreload
self.ipy_colors = ipy_colors
self.ipy_highlighting_style = ipy_highlighting_style
Shell.__init__(self, *args, **kwargs)
@staticmethod
def init_autoreload(mode: int) -> None:
"""Load and initialize the IPython autoreload extension."""
from IPython.extensions import autoreload
ip = get_ipython() # type: ignore # noqa: F821
autoreload.load_ipython_extension(ip)
ip.magics_manager.magics["line"]["autoreload"](str(mode))
def check_availability(self) -> bool:
try:
import IPython # noqa: F401
except ImportError:
raise ShellNotAvailableError("IPython shell not available.")
return True
def start(self) -> None:
try:
from IPython import start_ipython
from IPython.utils import io
from traitlets.config.loader import Config as IPyConfig
except ImportError:
raise ShellNotAvailableError(
"IPython shell not available " "or IPython version not supported."
)
# Hack to show custom banner
# TerminalIPythonApp/start_app doesn't allow you to customize the
# banner directly, so we write it to stdout before starting the IPython app
io.stdout.write(self.banner)
# Pass exec_lines in order to start autoreload
if self.ipy_autoreload:
if not isinstance(self.ipy_autoreload, bool):
mode = self.ipy_autoreload
else:
mode = 2
logger.debug(f"Initializing IPython autoreload in mode {mode}")
exec_lines = [
"import konch as __konch",
f"__konch.IPythonShell.init_autoreload({mode})",
]
else:
exec_lines = []
ipy_config = IPyConfig()
if self.ipy_colors:
ipy_config.TerminalInteractiveShell.colors = self.ipy_colors
if self.ipy_highlighting_style:
ipy_config.TerminalInteractiveShell.highlighting_style = (
self.ipy_highlighting_style
)
configure_ipython_prompt(ipy_config, prompt=self.prompt, output=self.output)
# Use start_ipython rather than embed so that IPython is loaded in the "normal"
# way. See https://github.com/django/django/pull/512
start_ipython(
display_banner=False,
user_ns=self.context,
config=ipy_config,
extensions=self.ipy_extensions or [],
exec_lines=exec_lines,
argv=[],
)
return None
class PtPythonShell(Shell):
def __init__(self, ptpy_vi_mode: bool = False, *args, **kwargs):
self.ptpy_vi_mode = ptpy_vi_mode
Shell.__init__(self, *args, **kwargs)
def check_availability(self) -> bool:
try:
import ptpython # noqa: F401
except ImportError:
raise ShellNotAvailableError("PtPython shell not available.")
return True
def start(self) -> None:
try:
from ptpython.repl import embed, run_config
except ImportError:
raise ShellNotAvailableError("PtPython shell not available.")
print(self.banner)
config_dir = Path("~/.ptpython/").expanduser()
# Startup path
startup_paths = []
if "PYTHONSTARTUP" in os.environ:
startup_paths.append(os.environ["PYTHONSTARTUP"])
# Apply config file
def configure(repl):
path = config_dir / "config.py"
if path.exists():
run_config(repl, str(path))
embed(
globals=self.context,
history_filename=config_dir / "history",
vi_mode=self.ptpy_vi_mode,
startup_paths=startup_paths,
configure=configure,
)
return None
class PtIPythonShell(PtPythonShell):
banner_template: str = "{text}\n{context}"
def __init__(
self, ipy_extensions: typing.Optional[typing.List[str]] = None, *args, **kwargs
) -> None:
self.ipy_extensions = ipy_extensions or []
PtPythonShell.__init__(self, *args, **kwargs)
def check_availability(self) -> bool:
try:
import ptpython.ipython # noqa: F401
import IPython # noqa: F401
except ImportError:
raise ShellNotAvailableError("PtIPython shell not available.")
return True
def start(self) -> None:
try:
from ptpython.ipython import embed
from ptpython.repl import run_config
from IPython.terminal.ipapp import load_default_config
except ImportError:
raise ShellNotAvailableError("PtIPython shell not available.")
config_dir = Path("~/.ptpython/").expanduser()
# Apply config file
def configure(repl):
path = config_dir / "config.py"
if path.exists():
run_config(repl, str(path))
# Startup path
startup_paths = []
if "PYTHONSTARTUP" in os.environ:
startup_paths.append(os.environ["PYTHONSTARTUP"])
# exec scripts from startup paths
for path in startup_paths:
if Path(path).exists():
with Path(path).open("rb") as f:
code = compile(f.read(), path, "exec")
exec(code, self.context, self.context)
else:
print(f"File not found: {path}\n\n")
sys.exit(1)
ipy_config = load_default_config()
ipy_config.InteractiveShellEmbed = ipy_config.TerminalInteractiveShell
ipy_config["InteractiveShellApp"]["extensions"] = self.ipy_extensions
configure_ipython_prompt(ipy_config, prompt=self.prompt, output=self.output)
embed(
config=ipy_config,
configure=configure,
history_filename=config_dir / "history",
user_ns=self.context,
header=self.banner,
vi_mode=self.ptpy_vi_mode,
)
return None
class BPythonShell(Shell):
"""The BPython shell."""
def check_availability(self) -> bool:
try:
import bpython # noqa: F401
except ImportError:
raise ShellNotAvailableError("BPython shell not available.")
return True
def start(self) -> None:
try:
from bpython import embed
except ImportError:
raise ShellNotAvailableError("BPython shell not available.")
if self.prompt:
warnings.warn("Custom prompts not supported by BPythonShell.")
if self.output:
warnings.warn("Custom output templates not supported by BPythonShell.")
embed(banner=self.banner, locals_=self.context)
return None
class BPythonCursesShell(Shell):
"""The BPython Curses shell."""
def check_availability(self) -> bool:
try:
import bpython.cli # noqa: F401
except ImportError:
raise ShellNotAvailableError("BPython Curses shell not available.")
return True
def start(self) -> None:
try:
from bpython.cli import main
except ImportError:
raise ShellNotAvailableError("BPython Curses shell not available.")
if self.prompt:
warnings.warn("Custom prompts not supported by BPython Curses shell.")
if self.output:
warnings.warn(
"Custom output templates not supported by BPython Curses shell."
)
main(banner=self.banner, locals_=self.context, args=["-i", "-q"])
return None
class AutoShell(Shell):
"""Shell that runs PtIpython, PtPython, IPython, or BPython if available.
Falls back to built-in Python shell.
"""
# Shell classes in precedence order
SHELLS = [
PtIPythonShell,
PtPythonShell,
IPythonShell,
BPythonShell,
BPythonCursesShell,
PythonShell,
]
def __init__(self, context: Context, banner: str, **kwargs):
Shell.__init__(self, context, **kwargs)
self.kwargs = kwargs
self.banner = banner
def check_availability(self) -> bool:
return True
def start(self) -> None:
shell_args = {
"context": self.context,
"banner": self.banner,
"prompt": self.prompt,
"output": self.output,
"context_format": self.context_format,
}
shell_args.update(self.kwargs)
shell = None
for shell_class in self.SHELLS:
try:
shell = shell_class(**shell_args)
shell.check_availability()
except ShellNotAvailableError:
continue
else:
break
else:
raise ShellNotAvailableError("No available shell to run.")
return shell.start()
CONCHES: typing.List[str] = [
'"My conch told me to come save you guys."\n"Hooray for the magic conches!"',
'"All hail the Magic Conch!"',
'"Hooray for the magic conches!"',
'"Uh, hello there. Magic Conch, I was wondering... '
'should I have the spaghetti or the turkey?"',
'"This copyrighted conch is the cornerstone of our organization."',
'"Praise the Magic Conch!"',
'"the conch exploded into a thousand white fragments and ceased to exist."',
"\"S'right. It's a shell!\"",
'"Ralph felt a kind of affectionate reverence for the conch"',
'"Conch! Conch!"',
'"That\'s why you got the conch out of the water"',
'"the summons of the conch"',
'"Whoever holds the conch gets to speak."',
'"They\'ll come when they hear us--"',
'"We gotta drop the load!"',
'"Dude, we\'re falling right out the sky!!"',
(
'"Oh, Magic Conch Shell, what do we need to do to get '
'out of the Kelp Forest?"\n"Nothing."'
),
'"The shell knows all!"',
'"we must never question the wisdom of the Magic Conch."',
'"The Magic Conch! A club member!"',
'"The shell has spoken!"',
'"This copyrighted conch is the cornerstone of our organization."',
'"All right, Magic Conch... what do we do now?"',
'"Ohhh! The Magic Conch Shell! Ask it something! Ask it something!"',
]
def speak() -> str:
return random.choice(CONCHES)
class Config(dict):
"""A dict-like config object. Behaves like a normal dict except that
the ``context`` will always be converted from a list to a dict.
Defines the default configuration.
"""
def __init__(
self,
context: typing.Optional[Context] = None,
banner: typing.Optional[str] = None,
shell: typing.Type[Shell] = AutoShell,
prompt: typing.Optional[str] = None,
output: typing.Optional[str] = None,
context_format: str = "full",
**kwargs: typing.Any,
) -> None:
ctx = Config.transform_val(context) or {}
super().__init__(
context=ctx,
banner=banner,
shell=shell,
prompt=prompt,
output=output,
context_format=context_format,
**kwargs,
)
def __setitem__(self, key: typing.Any, value: typing.Any) -> None:
if key == "context":
value = Config.transform_val(value)
super().__setitem__(key, value)
@staticmethod
def transform_val(val: typing.Any) -> typing.Any:
if isinstance(val, (list, tuple)):
return context_list2dict(val)
return val
def update(self, d: typing.Mapping) -> None: # type: ignore
for key in d.keys():
# Shallow-merge context
if key == "context":
self["context"].update(Config.transform_val(d["context"]))
else:
self[key] = d[key]
SHELL_MAP: typing.Dict[str, typing.Type[Shell]] = {
"ipy": IPythonShell,
"ipython": IPythonShell,
"bpy": BPythonShell,
"bpython": BPythonShell,
"bpyc": BPythonCursesShell,
"bpython-curses": BPythonCursesShell,
"py": PythonShell,
"python": PythonShell,
"auto": AutoShell,
"ptpy": PtPythonShell,
"ptpython": PtPythonShell,
"ptipy": PtIPythonShell,
"ptipython": PtIPythonShell,
}
# _cfg and _config_registry are singletons that may be mutated in a .konchrc file
_cfg = Config()
_config_registry = {"default": _cfg}
def config(config_dict: typing.Mapping) -> Config:
"""Configures the konch shell. This function should be called in a
.konchrc file.
:param dict config_dict: Dict that may contain 'context', 'banner', and/or
'shell' (default shell class to use).
"""
logger.debug(f"Updating with {config_dict}")
_cfg.update(config_dict)
return _cfg
def named_config(name: str, config_dict: typing.Mapping) -> None:
"""Adds a named config to the config registry. The first argument
may either be a string or a collection of strings.
This function should be called in a .konchrc file.
"""
names = (
name
if isinstance(name, Iterable) and not isinstance(name, (str, bytes))
else [name]
)
for each in names:
_config_registry[each] = Config(**config_dict)
def reset_config() -> Config:
global _cfg
_cfg = Config()
return _cfg
def __ensure_directory_in_path(filename: Path) -> None:
"""Ensures that a file's directory is in the Python path.
"""
directory = Path(filename).parent.resolve()
if directory not in sys.path:
logger.debug(f"Adding {directory} to sys.path")
sys.path.insert(0, str(directory))
CONFIG_FILE = Path(".konchrc")
DEFAULT_CONFIG_FILE = Path.home() / ".konchrc.default"
SEPARATOR = f"\n{'*' * 46}\n"
def confirm(text: str, default: bool = False) -> bool:
"""Display a confirmation prompt."""
choices = "Y/n" if default else "y/N"
prompt = f"{style(text, bold=True)} [{choices}]: "
while 1:
try:
print(prompt, end="")
value = input("").lower().strip()
except (KeyboardInterrupt, EOFError):
sys.exit(1)
if value in ("y", "yes"):
rv = True
elif value in ("n", "no"):
rv = False
elif value == "":
rv = default
else:
print_error("Error: invalid input")
continue
break
return rv
def use_file(
filename: typing.Union[Path, str, None], trust: bool = False
) -> typing.Union[types.ModuleType, None]:
"""Load filename as a python file. Import ``filename`` and return it
as a module.
"""
config_file = filename or resolve_path(CONFIG_FILE)
def preview_unauthorized() -> None:
if not config_file:
return None
print(SEPARATOR, file=sys.stderr)
with Path(config_file).open("r", encoding="utf-8") as fp:
for line in fp:
print(line, end="", file=sys.stderr)
print(SEPARATOR, file=sys.stderr)
if config_file and not Path(config_file).exists():
print_error(f'"{filename}" not found.')
sys.exit(1)
if config_file and Path(config_file).exists():
if not trust:
with AuthFile.load() as authfile:
try:
authfile.check(Path(config_file))
except KonchrcChangedError:
print_error(f'"{config_file}" has changed since you last used it.')
preview_unauthorized()
if confirm("Would you like to authorize it?"):
authfile.allow(Path(config_file))
print()
else:
sys.exit(1)
except KonchrcNotAuthorizedError:
print_error(f'"{config_file}" is blocked.')
preview_unauthorized()
if confirm("Would you like to authorize it?"):
authfile.allow(Path(config_file))
print()
else:
sys.exit(1)
logger.info(f"Using {config_file}")
# Ensure that relative imports are possible
__ensure_directory_in_path(Path(config_file))
mod = None
try:
mod = imp.load_source("konchrc", str(config_file))
except UnboundLocalError: # File not found
pass
else:
return mod
if not config_file:
print_warning("No konch config file found.")
else:
print_warning(f'"{config_file}" not found.')
return None
def resolve_path(filename: Path) -> typing.Union[Path, None]:
"""Find a file by walking up parent directories until the file is found.
Return the absolute path of the file.
"""
current = Path.cwd()
# Stop search at home directory
sentinel_dir = Path.home().parent.resolve()
while current != sentinel_dir:
target = Path(current) / Path(filename)
if target.exists():
return target.resolve()
else:
current = current.parent.resolve()
return None
def get_editor() -> str:
for key in "KONCH_EDITOR", "VISUAL", "EDITOR":
ret = os.environ.get(key)
if ret:
return ret
if sys.platform.startswith("win"):
return "notepad"
for editor in "vim", "nano":
if os.system("which %s &> /dev/null" % editor) == 0:
return editor
return "vi"
def edit_file(
filename: typing.Optional[Path], editor: typing.Optional[str] = None
) -> None:
if not filename:
print_error("filename not passed.")
sys.exit(1)
editor = editor or get_editor()
try:
result = subprocess.Popen(f'{editor} "{filename}"', shell=True)
exit_code = result.wait()
if exit_code != 0:
print_error(f"{editor}: Editing failed!")
sys.exit(1)
except OSError as err:
print_error(f"{editor}: Editing failed: {err}")
sys.exit(1)
else:
with AuthFile.load() as authfile:
authfile.allow(filename)
INIT_TEMPLATE = """# vi: set ft=python :
import konch
import sys
import os
# Available options:
# "context", "banner", "shell", "prompt", "output",
# "context_format", "ipy_extensions", "ipy_autoreload",
# "ipy_colors", "ipy_highlighting_style", "ptpy_vi_mode"
# See: https://konch.readthedocs.io/en/latest/#configuration
konch.config({
"context": [
sys,
os,
]
})
def setup():
pass
def teardown():
pass
"""
def init_config(config_file: Path) -> typing.NoReturn:
if not config_file.exists():
print(f'Writing to "{config_file.resolve()}"...')
print(SEPARATOR)
print(INIT_TEMPLATE, end="")
print(SEPARATOR)
init_template = INIT_TEMPLATE
if DEFAULT_CONFIG_FILE.exists(): # use ~/.konchrc.default if it exists
with Path(DEFAULT_CONFIG_FILE).open("r") as fp:
init_template = fp.read()
with Path(config_file).open("w") as fp:
fp.write(init_template)
with AuthFile.load() as authfile:
authfile.allow(config_file)
relpath = _relpath(config_file)
is_default = relpath == Path(CONFIG_FILE)
edit_cmd = "konch edit" if is_default else f"konch edit {relpath}"
run_cmd = "konch" if is_default else f"konch -f {relpath}"
print(f"{style('Done!', GREEN)} ✨ 🐚 ✨")
print(f"To edit your config: `{style(edit_cmd, bold=True)}`")
print(f"To start the shell: `{style(run_cmd, bold=True)}`")
sys.exit(0)
else:
print_error(f'"{config_file}" already exists in this directory.')
sys.exit(1)
def edit_config(
config_file: typing.Optional[Path] = None, editor: typing.Optional[str] = None
) -> typing.NoReturn:
filename = config_file or resolve_path(CONFIG_FILE)
if not filename:
print_error('No ".konchrc" file found.')
styled_cmd = style("konch init", bold=True, file=sys.stderr)
print(f"Run `{styled_cmd}` to create it.", file=sys.stderr)
sys.exit(1)
if not filename.exists():
print_error(f'"{filename}" does not exist.')
relpath = _relpath(filename)
is_default = relpath == Path(CONFIG_FILE)
cmd = "konch init" if is_default else f"konch init {filename}"
styled_cmd = style(cmd, bold=True, file=sys.stderr)
print(f"Run `{styled_cmd}` to create it.", file=sys.stderr)
sys.exit(1)
print(f'Editing file: "{filename}"')
edit_file(filename, editor=editor)
sys.exit(0)
def allow_config(config_file: typing.Optional[Path] = None) -> typing.NoReturn:
filename: typing.Union[Path, None]
if config_file and config_file.is_dir():
filename = Path(config_file) / CONFIG_FILE
else:
filename = config_file or resolve_path(CONFIG_FILE)
if not filename:
print_error("No config file found.")
sys.exit(1)
with AuthFile.load() as authfile:
if authfile.check(filename, raise_error=False):
print_warning(f'"{filename}" is already authorized.')
else:
try:
print(f'Authorizing "{filename}"...')
authfile.allow(filename)
except FileNotFoundError:
print_error(f'"{filename}" does not exist.')
sys.exit(1)
print(f"{style('Done!', GREEN)} ✨ 🐚 ✨")
relpath = _relpath(filename)
cmd = "konch" if relpath == Path(CONFIG_FILE) else f"konch -f {relpath}"
print(f"You can now start a shell with `{style(cmd, bold=True)}`.")
sys.exit(0)
def deny_config(config_file: typing.Optional[Path] = None) -> typing.NoReturn:
filename: typing.Union[Path, None]
if config_file and config_file.is_dir():
filename = Path(config_file) / CONFIG_FILE
else:
filename = config_file or resolve_path(CONFIG_FILE)
if not filename:
print_error("No config file found.")
sys.exit(1)
print(f'Removing authorization for "{filename}"...')
with AuthFile.load() as authfile:
try:
authfile.deny(filename)
except FileNotFoundError:
print_error(f'"{filename}" does not exist.')
sys.exit(1)
else:
print(style("Done!", GREEN))
sys.exit(0)
def parse_args(argv: typing.Optional[typing.Sequence] = None) -> typing.Dict[str, str]:
"""Exposes the docopt command-line arguments parser.
Return a dictionary of arguments.
"""
return docopt(__doc__, argv=argv, version=__version__)
def main(argv: typing.Optional[typing.Sequence] = None) -> typing.NoReturn:
"""Main entry point for the konch CLI."""
args = parse_args(argv)
if args["--debug"]:
logging.basicConfig(
format="%(levelname)s %(filename)s: %(message)s", level=logging.DEBUG
)
logger.debug(args)
config_file: typing.Union[Path, None]
if args["init"]:
config_file = Path(args["<config_file>"] or CONFIG_FILE)
init_config(config_file)
else:
config_file = Path(args["<config_file>"]) if args["<config_file>"] else None
if args["edit"]:
edit_config(config_file)
elif args["allow"]:
allow_config(config_file)
elif args["deny"]:
deny_config(config_file)
mod = use_file(Path(args["--file"]) if args["--file"] else None)
if hasattr(mod, "setup"):
mod.setup() # type: ignore
if args["--name"]:
if args["--name"] not in _config_registry:
print_error(f'Invalid --name: "{args["--name"]}"')
sys.exit(1)
config_dict = _config_registry[args["--name"]]
logger.debug(f'Using named config: "{args["--name"]}"')
logger.debug(config_dict)
else:
config_dict = _cfg
# Allow default shell to be overriden by command-line argument
shell_name = args["--shell"]
if shell_name:
config_dict["shell"] = SHELL_MAP.get(shell_name.lower(), AutoShell)
logger.debug(f"Starting with config {config_dict}")
start(**config_dict)
if hasattr(mod, "teardown"):
mod.teardown() # type: ignore
sys.exit(0)
if __name__ == "__main__":
main()
|
sloria/konch | konch.py | config | python | def config(config_dict: typing.Mapping) -> Config:
logger.debug(f"Updating with {config_dict}")
_cfg.update(config_dict)
return _cfg | Configures the konch shell. This function should be called in a
.konchrc file.
:param dict config_dict: Dict that may contain 'context', 'banner', and/or
'shell' (default shell class to use). | train | https://github.com/sloria/konch/blob/15160bd0a0cac967eeeab84794bd6cdd0b5b637d/konch.py#L828-L837 | null | #!/usr/bin/env python3
"""konch: Customizes your Python shell.
Usage:
konch
konch init [<config_file>] [-d]
konch edit [<config_file>] [-d]
konch allow [<config_file>] [-d]
konch deny [<config_file>] [-d]
konch [--name=<name>] [--file=<file>] [--shell=<shell_name>] [-d]
Options:
-h --help Show this screen.
-v --version Show version.
init Creates a starter .konchrc file.
edit Edit your .konchrc file.
-n --name=<name> Named config to use.
-s --shell=<shell_name> Shell to use. Can be either "ipy" (IPython),
"bpy" (BPython), "bpyc" (BPython Curses),
"ptpy" (PtPython), "ptipy" (PtIPython),
"py" (built-in Python shell), or "auto".
Overrides the 'shell' option in .konchrc.
-f --file=<file> File path of konch config file to execute. If not provided,
konch will use the .konchrc file in the current
directory.
-d --debug Enable debugging/verbose mode.
Environment variables:
KONCH_AUTH_FILE: File where to store authorization data for config files.
Defaults to ~/.local/share/konch_auth.
KONCH_EDITOR: Editor command to use when running `konch edit`.
Falls back to $VISUAL then $EDITOR.
NO_COLOR: Disable ANSI colors.
"""
from collections.abc import Iterable
from pathlib import Path
import code
import hashlib
import imp
import json
import logging
import os
import random
import subprocess
import sys
import typing
import types
import warnings
from docopt import docopt
__version__ = "4.2.1"
logger = logging.getLogger(__name__)
class KonchError(Exception):
pass
class ShellNotAvailableError(KonchError):
pass
class KonchrcNotAuthorizedError(KonchError):
pass
class KonchrcChangedError(KonchrcNotAuthorizedError):
pass
class AuthFile:
def __init__(self, data: typing.Dict[str, str]) -> None:
self.data = data
def __repr__(self) -> str:
return f"AuthFile({self.data!r})"
@classmethod
def load(cls, path: typing.Optional[Path] = None) -> "AuthFile":
filepath = path or cls.get_path()
try:
with Path(filepath).open("r", encoding="utf-8") as fp:
data = json.load(fp)
except FileNotFoundError:
data = {}
except json.JSONDecodeError as error:
# File exists but is empty
if error.doc.strip() == "":
data = {}
else:
raise
return cls(data)
def allow(self, filepath: Path) -> None:
logger.debug(f"Authorizing {filepath}")
self.data[str(Path(filepath).resolve())] = self._hash_file(filepath)
def deny(self, filepath: Path) -> None:
if not filepath.exists():
raise FileNotFoundError(f"{filepath} not found")
try:
logger.debug(f"Removing authorization for {filepath}")
del self.data[str(filepath.resolve())]
except KeyError:
pass
def check(
self, filepath: typing.Union[Path, None], raise_error: bool = True
) -> bool:
if not filepath:
return False
if str(filepath.resolve()) not in self.data:
if raise_error:
raise KonchrcNotAuthorizedError
else:
return False
else:
file_hash = self._hash_file(filepath)
if file_hash != self.data[str(filepath.resolve())]:
if raise_error:
raise KonchrcChangedError
else:
return False
return True
def save(self) -> None:
filepath = self.get_path()
filepath.parent.mkdir(parents=True, exist_ok=True)
with Path(filepath).open("w", encoding="utf-8") as fp:
json.dump(self.data, fp)
def __enter__(self) -> "AuthFile":
return self
def __exit__(
self,
exc_type: typing.Type[Exception],
exc_value: Exception,
exc_traceback: types.TracebackType,
) -> None:
if not exc_type:
self.save()
@staticmethod
def get_path() -> Path:
if "KONCH_AUTH_FILE" in os.environ:
return Path(os.environ["KONCH_AUTH_FILE"])
elif "XDG_DATA_HOME" in os.environ:
return Path(os.environ["XDG_DATA_HOME"]) / "konch_auth"
else:
return Path.home() / ".local" / "share" / "konch_auth"
@staticmethod
def _hash_file(filepath: Path) -> str:
# https://stackoverflow.com/a/22058673/1157536
BUF_SIZE = 65536 # read in 64kb chunks
sha1 = hashlib.sha1()
with Path(filepath).open("rb") as f:
while True:
data = f.read(BUF_SIZE)
if not data:
break
sha1.update(data) # type: ignore
return sha1.hexdigest()
RED = 31
GREEN = 32
YELLOW = 33
BOLD = 1
RESET_ALL = 0
def style(
text: str,
fg: typing.Optional[int] = None,
*,
bold: bool = False,
file: typing.IO = sys.stdout,
) -> str:
use_color = not os.environ.get("NO_COLOR") and file.isatty()
if use_color:
parts = [
fg and f"\033[{fg}m",
bold and f"\033[{BOLD}m",
text,
f"\033[{RESET_ALL}m",
]
return "".join([e for e in parts if e])
else:
return text
def sprint(text: str, *args: typing.Any, **kwargs: typing.Any) -> None:
file = kwargs.pop("file", sys.stdout)
return print(style(text, file=file, *args, **kwargs), file=file)
def print_error(text: str) -> None:
prefix = style("ERROR", RED, file=sys.stderr)
return sprint(f"{prefix}: {text}", file=sys.stderr)
def print_warning(text: str) -> None:
prefix = style("WARNING", YELLOW, file=sys.stderr)
return sprint(f"{prefix}: {text}", file=sys.stderr)
Context = typing.Mapping[str, typing.Any]
Formatter = typing.Callable[[Context], str]
ContextFormat = typing.Union[str, Formatter]
def _full_formatter(context: Context) -> str:
line_format = "{name}: {obj!r}"
context_str = "\n".join(
[
line_format.format(name=name, obj=obj)
for name, obj in sorted(context.items(), key=lambda i: i[0].lower())
]
)
header = style("Context:", bold=True)
return f"\n{header}\n{context_str}"
def _short_formatter(context: Context) -> str:
context_str = ", ".join(sorted(context.keys(), key=str.lower))
header = style("Context:", bold=True)
return f"\n{header}\n{context_str}"
def _hide_formatter(context: Context) -> str:
return ""
CONTEXT_FORMATTERS: typing.Dict[str, Formatter] = {
"full": _full_formatter,
"short": _short_formatter,
"hide": _hide_formatter,
}
def format_context(
context: Context, formatter: typing.Union[str, Formatter] = "full"
) -> str:
"""Output the a context dictionary as a string."""
if not context:
return ""
if callable(formatter):
formatter_func = formatter
else:
if formatter in CONTEXT_FORMATTERS:
formatter_func = CONTEXT_FORMATTERS[formatter]
else:
raise ValueError(f'Invalid context format: "{formatter}"')
return formatter_func(context)
BANNER_TEMPLATE = """{version}
{text}
{context}
"""
def make_banner(
text: typing.Optional[str] = None,
context: typing.Optional[Context] = None,
banner_template: typing.Optional[str] = None,
context_format: ContextFormat = "full",
) -> str:
"""Generates a full banner with version info, the given text, and a
formatted list of context variables.
"""
banner_text = text or speak()
banner_template = banner_template or BANNER_TEMPLATE
ctx = format_context(context or {}, formatter=context_format)
out = banner_template.format(version=sys.version, text=banner_text, context=ctx)
return out
def context_list2dict(context_list: typing.Sequence[typing.Any]) -> Context:
"""Converts a list of objects (functions, classes, or modules) to a
dictionary mapping the object names to the objects.
"""
return {obj.__name__.split(".")[-1]: obj for obj in context_list}
def _relpath(p: Path) -> Path:
return p.resolve().relative_to(Path.cwd())
class Shell:
"""Base shell class.
:param dict context: Dictionary, list, or callable (that returns a `dict` or `list`)
that defines what variables will be available when the shell is run.
:param str banner: Banner text that appears on startup.
:param str prompt: Custom input prompt.
:param str output: Custom output prompt.
:param context_format: Formatter for the context dictionary in the banner.
Either 'full', 'short', 'hide', or a function that receives the context
dictionary and outputs a string.
"""
banner_template: str = BANNER_TEMPLATE
def __init__(
self,
context: Context,
banner: typing.Optional[str] = None,
prompt: typing.Optional[str] = None,
output: typing.Optional[str] = None,
context_format: ContextFormat = "full",
**kwargs: typing.Any,
) -> None:
self.context = context() if callable(context) else context
self.context_format = context_format
self.banner = make_banner(
banner,
self.context,
context_format=self.context_format,
banner_template=self.banner_template,
)
self.prompt = prompt
self.output = output
def check_availability(self) -> bool:
raise NotImplementedError
def start(self) -> None:
raise NotImplementedError
class PythonShell(Shell):
"""The built-in Python shell."""
def check_availability(self) -> bool:
return True
def start(self) -> None:
try:
import readline
except ImportError:
pass
else:
# We don't have to wrap the following import in a 'try', because
# we already know 'readline' was imported successfully.
import rlcompleter
readline.set_completer(rlcompleter.Completer(self.context).complete)
readline.parse_and_bind("tab:complete")
if self.prompt:
sys.ps1 = self.prompt
if self.output:
warnings.warn("Custom output templates not supported by PythonShell.")
code.interact(self.banner, local=self.context)
return None
def configure_ipython_prompt(
config, prompt: typing.Optional[str] = None, output: typing.Optional[str] = None
) -> None:
import IPython
if IPython.version_info[0] >= 5: # Custom prompt API changed in IPython 5.0
from pygments.token import Token
# https://ipython.readthedocs.io/en/stable/config/details.html#custom-prompts # noqa: B950
class CustomPrompt(IPython.terminal.prompts.Prompts):
def in_prompt_tokens(self, *args, **kwargs):
if prompt is None:
return super().in_prompt_tokens(*args, **kwargs)
if isinstance(prompt, (str, bytes)):
return [(Token.Prompt, prompt)]
else:
return prompt
def out_prompt_tokens(self, *args, **kwargs):
if output is None:
return super().out_prompt_tokens(*args, **kwargs)
if isinstance(output, (str, bytes)):
return [(Token.OutPrompt, output)]
else:
return prompt
config.TerminalInteractiveShell.prompts_class = CustomPrompt
else:
prompt_config = config.PromptManager
if prompt:
prompt_config.in_template = prompt
if output:
prompt_config.out_template = output
return None
class IPythonShell(Shell):
"""The IPython shell.
:param list ipy_extensions: List of IPython extension names to load upon startup.
:param bool ipy_autoreload: Whether to load and initialize the IPython autoreload
extension upon startup. Can also be an integer, which will be passed as
the argument to the %autoreload line magic.
:param kwargs: The same kwargs as `Shell.__init__`.
"""
def __init__(
self,
ipy_extensions: typing.Optional[typing.List[str]] = None,
ipy_autoreload: bool = False,
ipy_colors: typing.Optional[str] = None,
ipy_highlighting_style: typing.Optional[str] = None,
*args: typing.Any,
**kwargs: typing.Any,
):
self.ipy_extensions = ipy_extensions
self.ipy_autoreload = ipy_autoreload
self.ipy_colors = ipy_colors
self.ipy_highlighting_style = ipy_highlighting_style
Shell.__init__(self, *args, **kwargs)
@staticmethod
def init_autoreload(mode: int) -> None:
"""Load and initialize the IPython autoreload extension."""
from IPython.extensions import autoreload
ip = get_ipython() # type: ignore # noqa: F821
autoreload.load_ipython_extension(ip)
ip.magics_manager.magics["line"]["autoreload"](str(mode))
def check_availability(self) -> bool:
try:
import IPython # noqa: F401
except ImportError:
raise ShellNotAvailableError("IPython shell not available.")
return True
def start(self) -> None:
try:
from IPython import start_ipython
from IPython.utils import io
from traitlets.config.loader import Config as IPyConfig
except ImportError:
raise ShellNotAvailableError(
"IPython shell not available " "or IPython version not supported."
)
# Hack to show custom banner
# TerminalIPythonApp/start_app doesn't allow you to customize the
# banner directly, so we write it to stdout before starting the IPython app
io.stdout.write(self.banner)
# Pass exec_lines in order to start autoreload
if self.ipy_autoreload:
if not isinstance(self.ipy_autoreload, bool):
mode = self.ipy_autoreload
else:
mode = 2
logger.debug(f"Initializing IPython autoreload in mode {mode}")
exec_lines = [
"import konch as __konch",
f"__konch.IPythonShell.init_autoreload({mode})",
]
else:
exec_lines = []
ipy_config = IPyConfig()
if self.ipy_colors:
ipy_config.TerminalInteractiveShell.colors = self.ipy_colors
if self.ipy_highlighting_style:
ipy_config.TerminalInteractiveShell.highlighting_style = (
self.ipy_highlighting_style
)
configure_ipython_prompt(ipy_config, prompt=self.prompt, output=self.output)
# Use start_ipython rather than embed so that IPython is loaded in the "normal"
# way. See https://github.com/django/django/pull/512
start_ipython(
display_banner=False,
user_ns=self.context,
config=ipy_config,
extensions=self.ipy_extensions or [],
exec_lines=exec_lines,
argv=[],
)
return None
class PtPythonShell(Shell):
def __init__(self, ptpy_vi_mode: bool = False, *args, **kwargs):
self.ptpy_vi_mode = ptpy_vi_mode
Shell.__init__(self, *args, **kwargs)
def check_availability(self) -> bool:
try:
import ptpython # noqa: F401
except ImportError:
raise ShellNotAvailableError("PtPython shell not available.")
return True
def start(self) -> None:
try:
from ptpython.repl import embed, run_config
except ImportError:
raise ShellNotAvailableError("PtPython shell not available.")
print(self.banner)
config_dir = Path("~/.ptpython/").expanduser()
# Startup path
startup_paths = []
if "PYTHONSTARTUP" in os.environ:
startup_paths.append(os.environ["PYTHONSTARTUP"])
# Apply config file
def configure(repl):
path = config_dir / "config.py"
if path.exists():
run_config(repl, str(path))
embed(
globals=self.context,
history_filename=config_dir / "history",
vi_mode=self.ptpy_vi_mode,
startup_paths=startup_paths,
configure=configure,
)
return None
class PtIPythonShell(PtPythonShell):
banner_template: str = "{text}\n{context}"
def __init__(
self, ipy_extensions: typing.Optional[typing.List[str]] = None, *args, **kwargs
) -> None:
self.ipy_extensions = ipy_extensions or []
PtPythonShell.__init__(self, *args, **kwargs)
def check_availability(self) -> bool:
try:
import ptpython.ipython # noqa: F401
import IPython # noqa: F401
except ImportError:
raise ShellNotAvailableError("PtIPython shell not available.")
return True
def start(self) -> None:
try:
from ptpython.ipython import embed
from ptpython.repl import run_config
from IPython.terminal.ipapp import load_default_config
except ImportError:
raise ShellNotAvailableError("PtIPython shell not available.")
config_dir = Path("~/.ptpython/").expanduser()
# Apply config file
def configure(repl):
path = config_dir / "config.py"
if path.exists():
run_config(repl, str(path))
# Startup path
startup_paths = []
if "PYTHONSTARTUP" in os.environ:
startup_paths.append(os.environ["PYTHONSTARTUP"])
# exec scripts from startup paths
for path in startup_paths:
if Path(path).exists():
with Path(path).open("rb") as f:
code = compile(f.read(), path, "exec")
exec(code, self.context, self.context)
else:
print(f"File not found: {path}\n\n")
sys.exit(1)
ipy_config = load_default_config()
ipy_config.InteractiveShellEmbed = ipy_config.TerminalInteractiveShell
ipy_config["InteractiveShellApp"]["extensions"] = self.ipy_extensions
configure_ipython_prompt(ipy_config, prompt=self.prompt, output=self.output)
embed(
config=ipy_config,
configure=configure,
history_filename=config_dir / "history",
user_ns=self.context,
header=self.banner,
vi_mode=self.ptpy_vi_mode,
)
return None
class BPythonShell(Shell):
"""The BPython shell."""
def check_availability(self) -> bool:
try:
import bpython # noqa: F401
except ImportError:
raise ShellNotAvailableError("BPython shell not available.")
return True
def start(self) -> None:
try:
from bpython import embed
except ImportError:
raise ShellNotAvailableError("BPython shell not available.")
if self.prompt:
warnings.warn("Custom prompts not supported by BPythonShell.")
if self.output:
warnings.warn("Custom output templates not supported by BPythonShell.")
embed(banner=self.banner, locals_=self.context)
return None
class BPythonCursesShell(Shell):
"""The BPython Curses shell."""
def check_availability(self) -> bool:
try:
import bpython.cli # noqa: F401
except ImportError:
raise ShellNotAvailableError("BPython Curses shell not available.")
return True
def start(self) -> None:
try:
from bpython.cli import main
except ImportError:
raise ShellNotAvailableError("BPython Curses shell not available.")
if self.prompt:
warnings.warn("Custom prompts not supported by BPython Curses shell.")
if self.output:
warnings.warn(
"Custom output templates not supported by BPython Curses shell."
)
main(banner=self.banner, locals_=self.context, args=["-i", "-q"])
return None
class AutoShell(Shell):
"""Shell that runs PtIpython, PtPython, IPython, or BPython if available.
Falls back to built-in Python shell.
"""
# Shell classes in precedence order
SHELLS = [
PtIPythonShell,
PtPythonShell,
IPythonShell,
BPythonShell,
BPythonCursesShell,
PythonShell,
]
def __init__(self, context: Context, banner: str, **kwargs):
Shell.__init__(self, context, **kwargs)
self.kwargs = kwargs
self.banner = banner
def check_availability(self) -> bool:
return True
def start(self) -> None:
shell_args = {
"context": self.context,
"banner": self.banner,
"prompt": self.prompt,
"output": self.output,
"context_format": self.context_format,
}
shell_args.update(self.kwargs)
shell = None
for shell_class in self.SHELLS:
try:
shell = shell_class(**shell_args)
shell.check_availability()
except ShellNotAvailableError:
continue
else:
break
else:
raise ShellNotAvailableError("No available shell to run.")
return shell.start()
CONCHES: typing.List[str] = [
'"My conch told me to come save you guys."\n"Hooray for the magic conches!"',
'"All hail the Magic Conch!"',
'"Hooray for the magic conches!"',
'"Uh, hello there. Magic Conch, I was wondering... '
'should I have the spaghetti or the turkey?"',
'"This copyrighted conch is the cornerstone of our organization."',
'"Praise the Magic Conch!"',
'"the conch exploded into a thousand white fragments and ceased to exist."',
"\"S'right. It's a shell!\"",
'"Ralph felt a kind of affectionate reverence for the conch"',
'"Conch! Conch!"',
'"That\'s why you got the conch out of the water"',
'"the summons of the conch"',
'"Whoever holds the conch gets to speak."',
'"They\'ll come when they hear us--"',
'"We gotta drop the load!"',
'"Dude, we\'re falling right out the sky!!"',
(
'"Oh, Magic Conch Shell, what do we need to do to get '
'out of the Kelp Forest?"\n"Nothing."'
),
'"The shell knows all!"',
'"we must never question the wisdom of the Magic Conch."',
'"The Magic Conch! A club member!"',
'"The shell has spoken!"',
'"This copyrighted conch is the cornerstone of our organization."',
'"All right, Magic Conch... what do we do now?"',
'"Ohhh! The Magic Conch Shell! Ask it something! Ask it something!"',
]
def speak() -> str:
return random.choice(CONCHES)
class Config(dict):
"""A dict-like config object. Behaves like a normal dict except that
the ``context`` will always be converted from a list to a dict.
Defines the default configuration.
"""
def __init__(
self,
context: typing.Optional[Context] = None,
banner: typing.Optional[str] = None,
shell: typing.Type[Shell] = AutoShell,
prompt: typing.Optional[str] = None,
output: typing.Optional[str] = None,
context_format: str = "full",
**kwargs: typing.Any,
) -> None:
ctx = Config.transform_val(context) or {}
super().__init__(
context=ctx,
banner=banner,
shell=shell,
prompt=prompt,
output=output,
context_format=context_format,
**kwargs,
)
def __setitem__(self, key: typing.Any, value: typing.Any) -> None:
if key == "context":
value = Config.transform_val(value)
super().__setitem__(key, value)
@staticmethod
def transform_val(val: typing.Any) -> typing.Any:
if isinstance(val, (list, tuple)):
return context_list2dict(val)
return val
def update(self, d: typing.Mapping) -> None: # type: ignore
for key in d.keys():
# Shallow-merge context
if key == "context":
self["context"].update(Config.transform_val(d["context"]))
else:
self[key] = d[key]
SHELL_MAP: typing.Dict[str, typing.Type[Shell]] = {
"ipy": IPythonShell,
"ipython": IPythonShell,
"bpy": BPythonShell,
"bpython": BPythonShell,
"bpyc": BPythonCursesShell,
"bpython-curses": BPythonCursesShell,
"py": PythonShell,
"python": PythonShell,
"auto": AutoShell,
"ptpy": PtPythonShell,
"ptpython": PtPythonShell,
"ptipy": PtIPythonShell,
"ptipython": PtIPythonShell,
}
# _cfg and _config_registry are singletons that may be mutated in a .konchrc file
_cfg = Config()
_config_registry = {"default": _cfg}
def start(
context: typing.Optional[typing.Mapping] = None,
banner: typing.Optional[str] = None,
shell: typing.Type[Shell] = AutoShell,
prompt: typing.Optional[str] = None,
output: typing.Optional[str] = None,
context_format: str = "full",
**kwargs: typing.Any,
) -> None:
"""Start up the konch shell. Takes the same parameters as Shell.__init__.
"""
logger.debug(f"Using shell: {shell!r}")
if banner is None:
banner = speak()
# Default to global config
context_ = context or _cfg["context"]
banner_ = banner or _cfg["banner"]
if isinstance(shell, type) and issubclass(shell, Shell):
shell_ = shell
else:
shell_ = SHELL_MAP.get(shell or _cfg["shell"], _cfg["shell"])
prompt_ = prompt or _cfg["prompt"]
output_ = output or _cfg["output"]
context_format_ = context_format or _cfg["context_format"]
shell_(
context=context_,
banner=banner_,
prompt=prompt_,
output=output_,
context_format=context_format_,
**kwargs,
).start()
def named_config(name: str, config_dict: typing.Mapping) -> None:
"""Adds a named config to the config registry. The first argument
may either be a string or a collection of strings.
This function should be called in a .konchrc file.
"""
names = (
name
if isinstance(name, Iterable) and not isinstance(name, (str, bytes))
else [name]
)
for each in names:
_config_registry[each] = Config(**config_dict)
def reset_config() -> Config:
global _cfg
_cfg = Config()
return _cfg
def __ensure_directory_in_path(filename: Path) -> None:
"""Ensures that a file's directory is in the Python path.
"""
directory = Path(filename).parent.resolve()
if directory not in sys.path:
logger.debug(f"Adding {directory} to sys.path")
sys.path.insert(0, str(directory))
CONFIG_FILE = Path(".konchrc")
DEFAULT_CONFIG_FILE = Path.home() / ".konchrc.default"
SEPARATOR = f"\n{'*' * 46}\n"
def confirm(text: str, default: bool = False) -> bool:
"""Display a confirmation prompt."""
choices = "Y/n" if default else "y/N"
prompt = f"{style(text, bold=True)} [{choices}]: "
while 1:
try:
print(prompt, end="")
value = input("").lower().strip()
except (KeyboardInterrupt, EOFError):
sys.exit(1)
if value in ("y", "yes"):
rv = True
elif value in ("n", "no"):
rv = False
elif value == "":
rv = default
else:
print_error("Error: invalid input")
continue
break
return rv
def use_file(
filename: typing.Union[Path, str, None], trust: bool = False
) -> typing.Union[types.ModuleType, None]:
"""Load filename as a python file. Import ``filename`` and return it
as a module.
"""
config_file = filename or resolve_path(CONFIG_FILE)
def preview_unauthorized() -> None:
if not config_file:
return None
print(SEPARATOR, file=sys.stderr)
with Path(config_file).open("r", encoding="utf-8") as fp:
for line in fp:
print(line, end="", file=sys.stderr)
print(SEPARATOR, file=sys.stderr)
if config_file and not Path(config_file).exists():
print_error(f'"{filename}" not found.')
sys.exit(1)
if config_file and Path(config_file).exists():
if not trust:
with AuthFile.load() as authfile:
try:
authfile.check(Path(config_file))
except KonchrcChangedError:
print_error(f'"{config_file}" has changed since you last used it.')
preview_unauthorized()
if confirm("Would you like to authorize it?"):
authfile.allow(Path(config_file))
print()
else:
sys.exit(1)
except KonchrcNotAuthorizedError:
print_error(f'"{config_file}" is blocked.')
preview_unauthorized()
if confirm("Would you like to authorize it?"):
authfile.allow(Path(config_file))
print()
else:
sys.exit(1)
logger.info(f"Using {config_file}")
# Ensure that relative imports are possible
__ensure_directory_in_path(Path(config_file))
mod = None
try:
mod = imp.load_source("konchrc", str(config_file))
except UnboundLocalError: # File not found
pass
else:
return mod
if not config_file:
print_warning("No konch config file found.")
else:
print_warning(f'"{config_file}" not found.')
return None
def resolve_path(filename: Path) -> typing.Union[Path, None]:
"""Find a file by walking up parent directories until the file is found.
Return the absolute path of the file.
"""
current = Path.cwd()
# Stop search at home directory
sentinel_dir = Path.home().parent.resolve()
while current != sentinel_dir:
target = Path(current) / Path(filename)
if target.exists():
return target.resolve()
else:
current = current.parent.resolve()
return None
def get_editor() -> str:
for key in "KONCH_EDITOR", "VISUAL", "EDITOR":
ret = os.environ.get(key)
if ret:
return ret
if sys.platform.startswith("win"):
return "notepad"
for editor in "vim", "nano":
if os.system("which %s &> /dev/null" % editor) == 0:
return editor
return "vi"
def edit_file(
filename: typing.Optional[Path], editor: typing.Optional[str] = None
) -> None:
if not filename:
print_error("filename not passed.")
sys.exit(1)
editor = editor or get_editor()
try:
result = subprocess.Popen(f'{editor} "{filename}"', shell=True)
exit_code = result.wait()
if exit_code != 0:
print_error(f"{editor}: Editing failed!")
sys.exit(1)
except OSError as err:
print_error(f"{editor}: Editing failed: {err}")
sys.exit(1)
else:
with AuthFile.load() as authfile:
authfile.allow(filename)
INIT_TEMPLATE = """# vi: set ft=python :
import konch
import sys
import os
# Available options:
# "context", "banner", "shell", "prompt", "output",
# "context_format", "ipy_extensions", "ipy_autoreload",
# "ipy_colors", "ipy_highlighting_style", "ptpy_vi_mode"
# See: https://konch.readthedocs.io/en/latest/#configuration
konch.config({
"context": [
sys,
os,
]
})
def setup():
pass
def teardown():
pass
"""
def init_config(config_file: Path) -> typing.NoReturn:
if not config_file.exists():
print(f'Writing to "{config_file.resolve()}"...')
print(SEPARATOR)
print(INIT_TEMPLATE, end="")
print(SEPARATOR)
init_template = INIT_TEMPLATE
if DEFAULT_CONFIG_FILE.exists(): # use ~/.konchrc.default if it exists
with Path(DEFAULT_CONFIG_FILE).open("r") as fp:
init_template = fp.read()
with Path(config_file).open("w") as fp:
fp.write(init_template)
with AuthFile.load() as authfile:
authfile.allow(config_file)
relpath = _relpath(config_file)
is_default = relpath == Path(CONFIG_FILE)
edit_cmd = "konch edit" if is_default else f"konch edit {relpath}"
run_cmd = "konch" if is_default else f"konch -f {relpath}"
print(f"{style('Done!', GREEN)} ✨ 🐚 ✨")
print(f"To edit your config: `{style(edit_cmd, bold=True)}`")
print(f"To start the shell: `{style(run_cmd, bold=True)}`")
sys.exit(0)
else:
print_error(f'"{config_file}" already exists in this directory.')
sys.exit(1)
def edit_config(
config_file: typing.Optional[Path] = None, editor: typing.Optional[str] = None
) -> typing.NoReturn:
filename = config_file or resolve_path(CONFIG_FILE)
if not filename:
print_error('No ".konchrc" file found.')
styled_cmd = style("konch init", bold=True, file=sys.stderr)
print(f"Run `{styled_cmd}` to create it.", file=sys.stderr)
sys.exit(1)
if not filename.exists():
print_error(f'"{filename}" does not exist.')
relpath = _relpath(filename)
is_default = relpath == Path(CONFIG_FILE)
cmd = "konch init" if is_default else f"konch init {filename}"
styled_cmd = style(cmd, bold=True, file=sys.stderr)
print(f"Run `{styled_cmd}` to create it.", file=sys.stderr)
sys.exit(1)
print(f'Editing file: "{filename}"')
edit_file(filename, editor=editor)
sys.exit(0)
def allow_config(config_file: typing.Optional[Path] = None) -> typing.NoReturn:
filename: typing.Union[Path, None]
if config_file and config_file.is_dir():
filename = Path(config_file) / CONFIG_FILE
else:
filename = config_file or resolve_path(CONFIG_FILE)
if not filename:
print_error("No config file found.")
sys.exit(1)
with AuthFile.load() as authfile:
if authfile.check(filename, raise_error=False):
print_warning(f'"{filename}" is already authorized.')
else:
try:
print(f'Authorizing "{filename}"...')
authfile.allow(filename)
except FileNotFoundError:
print_error(f'"{filename}" does not exist.')
sys.exit(1)
print(f"{style('Done!', GREEN)} ✨ 🐚 ✨")
relpath = _relpath(filename)
cmd = "konch" if relpath == Path(CONFIG_FILE) else f"konch -f {relpath}"
print(f"You can now start a shell with `{style(cmd, bold=True)}`.")
sys.exit(0)
def deny_config(config_file: typing.Optional[Path] = None) -> typing.NoReturn:
filename: typing.Union[Path, None]
if config_file and config_file.is_dir():
filename = Path(config_file) / CONFIG_FILE
else:
filename = config_file or resolve_path(CONFIG_FILE)
if not filename:
print_error("No config file found.")
sys.exit(1)
print(f'Removing authorization for "{filename}"...')
with AuthFile.load() as authfile:
try:
authfile.deny(filename)
except FileNotFoundError:
print_error(f'"{filename}" does not exist.')
sys.exit(1)
else:
print(style("Done!", GREEN))
sys.exit(0)
def parse_args(argv: typing.Optional[typing.Sequence] = None) -> typing.Dict[str, str]:
"""Exposes the docopt command-line arguments parser.
Return a dictionary of arguments.
"""
return docopt(__doc__, argv=argv, version=__version__)
def main(argv: typing.Optional[typing.Sequence] = None) -> typing.NoReturn:
"""Main entry point for the konch CLI."""
args = parse_args(argv)
if args["--debug"]:
logging.basicConfig(
format="%(levelname)s %(filename)s: %(message)s", level=logging.DEBUG
)
logger.debug(args)
config_file: typing.Union[Path, None]
if args["init"]:
config_file = Path(args["<config_file>"] or CONFIG_FILE)
init_config(config_file)
else:
config_file = Path(args["<config_file>"]) if args["<config_file>"] else None
if args["edit"]:
edit_config(config_file)
elif args["allow"]:
allow_config(config_file)
elif args["deny"]:
deny_config(config_file)
mod = use_file(Path(args["--file"]) if args["--file"] else None)
if hasattr(mod, "setup"):
mod.setup() # type: ignore
if args["--name"]:
if args["--name"] not in _config_registry:
print_error(f'Invalid --name: "{args["--name"]}"')
sys.exit(1)
config_dict = _config_registry[args["--name"]]
logger.debug(f'Using named config: "{args["--name"]}"')
logger.debug(config_dict)
else:
config_dict = _cfg
# Allow default shell to be overriden by command-line argument
shell_name = args["--shell"]
if shell_name:
config_dict["shell"] = SHELL_MAP.get(shell_name.lower(), AutoShell)
logger.debug(f"Starting with config {config_dict}")
start(**config_dict)
if hasattr(mod, "teardown"):
mod.teardown() # type: ignore
sys.exit(0)
if __name__ == "__main__":
main()
|
sloria/konch | konch.py | named_config | python | def named_config(name: str, config_dict: typing.Mapping) -> None:
names = (
name
if isinstance(name, Iterable) and not isinstance(name, (str, bytes))
else [name]
)
for each in names:
_config_registry[each] = Config(**config_dict) | Adds a named config to the config registry. The first argument
may either be a string or a collection of strings.
This function should be called in a .konchrc file. | train | https://github.com/sloria/konch/blob/15160bd0a0cac967eeeab84794bd6cdd0b5b637d/konch.py#L840-L852 | null | #!/usr/bin/env python3
"""konch: Customizes your Python shell.
Usage:
konch
konch init [<config_file>] [-d]
konch edit [<config_file>] [-d]
konch allow [<config_file>] [-d]
konch deny [<config_file>] [-d]
konch [--name=<name>] [--file=<file>] [--shell=<shell_name>] [-d]
Options:
-h --help Show this screen.
-v --version Show version.
init Creates a starter .konchrc file.
edit Edit your .konchrc file.
-n --name=<name> Named config to use.
-s --shell=<shell_name> Shell to use. Can be either "ipy" (IPython),
"bpy" (BPython), "bpyc" (BPython Curses),
"ptpy" (PtPython), "ptipy" (PtIPython),
"py" (built-in Python shell), or "auto".
Overrides the 'shell' option in .konchrc.
-f --file=<file> File path of konch config file to execute. If not provided,
konch will use the .konchrc file in the current
directory.
-d --debug Enable debugging/verbose mode.
Environment variables:
KONCH_AUTH_FILE: File where to store authorization data for config files.
Defaults to ~/.local/share/konch_auth.
KONCH_EDITOR: Editor command to use when running `konch edit`.
Falls back to $VISUAL then $EDITOR.
NO_COLOR: Disable ANSI colors.
"""
from collections.abc import Iterable
from pathlib import Path
import code
import hashlib
import imp
import json
import logging
import os
import random
import subprocess
import sys
import typing
import types
import warnings
from docopt import docopt
__version__ = "4.2.1"
logger = logging.getLogger(__name__)
class KonchError(Exception):
pass
class ShellNotAvailableError(KonchError):
pass
class KonchrcNotAuthorizedError(KonchError):
pass
class KonchrcChangedError(KonchrcNotAuthorizedError):
pass
class AuthFile:
def __init__(self, data: typing.Dict[str, str]) -> None:
self.data = data
def __repr__(self) -> str:
return f"AuthFile({self.data!r})"
@classmethod
def load(cls, path: typing.Optional[Path] = None) -> "AuthFile":
filepath = path or cls.get_path()
try:
with Path(filepath).open("r", encoding="utf-8") as fp:
data = json.load(fp)
except FileNotFoundError:
data = {}
except json.JSONDecodeError as error:
# File exists but is empty
if error.doc.strip() == "":
data = {}
else:
raise
return cls(data)
def allow(self, filepath: Path) -> None:
logger.debug(f"Authorizing {filepath}")
self.data[str(Path(filepath).resolve())] = self._hash_file(filepath)
def deny(self, filepath: Path) -> None:
if not filepath.exists():
raise FileNotFoundError(f"{filepath} not found")
try:
logger.debug(f"Removing authorization for {filepath}")
del self.data[str(filepath.resolve())]
except KeyError:
pass
def check(
self, filepath: typing.Union[Path, None], raise_error: bool = True
) -> bool:
if not filepath:
return False
if str(filepath.resolve()) not in self.data:
if raise_error:
raise KonchrcNotAuthorizedError
else:
return False
else:
file_hash = self._hash_file(filepath)
if file_hash != self.data[str(filepath.resolve())]:
if raise_error:
raise KonchrcChangedError
else:
return False
return True
def save(self) -> None:
filepath = self.get_path()
filepath.parent.mkdir(parents=True, exist_ok=True)
with Path(filepath).open("w", encoding="utf-8") as fp:
json.dump(self.data, fp)
def __enter__(self) -> "AuthFile":
return self
def __exit__(
self,
exc_type: typing.Type[Exception],
exc_value: Exception,
exc_traceback: types.TracebackType,
) -> None:
if not exc_type:
self.save()
@staticmethod
def get_path() -> Path:
if "KONCH_AUTH_FILE" in os.environ:
return Path(os.environ["KONCH_AUTH_FILE"])
elif "XDG_DATA_HOME" in os.environ:
return Path(os.environ["XDG_DATA_HOME"]) / "konch_auth"
else:
return Path.home() / ".local" / "share" / "konch_auth"
@staticmethod
def _hash_file(filepath: Path) -> str:
# https://stackoverflow.com/a/22058673/1157536
BUF_SIZE = 65536 # read in 64kb chunks
sha1 = hashlib.sha1()
with Path(filepath).open("rb") as f:
while True:
data = f.read(BUF_SIZE)
if not data:
break
sha1.update(data) # type: ignore
return sha1.hexdigest()
RED = 31
GREEN = 32
YELLOW = 33
BOLD = 1
RESET_ALL = 0
def style(
text: str,
fg: typing.Optional[int] = None,
*,
bold: bool = False,
file: typing.IO = sys.stdout,
) -> str:
use_color = not os.environ.get("NO_COLOR") and file.isatty()
if use_color:
parts = [
fg and f"\033[{fg}m",
bold and f"\033[{BOLD}m",
text,
f"\033[{RESET_ALL}m",
]
return "".join([e for e in parts if e])
else:
return text
def sprint(text: str, *args: typing.Any, **kwargs: typing.Any) -> None:
file = kwargs.pop("file", sys.stdout)
return print(style(text, file=file, *args, **kwargs), file=file)
def print_error(text: str) -> None:
prefix = style("ERROR", RED, file=sys.stderr)
return sprint(f"{prefix}: {text}", file=sys.stderr)
def print_warning(text: str) -> None:
prefix = style("WARNING", YELLOW, file=sys.stderr)
return sprint(f"{prefix}: {text}", file=sys.stderr)
Context = typing.Mapping[str, typing.Any]
Formatter = typing.Callable[[Context], str]
ContextFormat = typing.Union[str, Formatter]
def _full_formatter(context: Context) -> str:
line_format = "{name}: {obj!r}"
context_str = "\n".join(
[
line_format.format(name=name, obj=obj)
for name, obj in sorted(context.items(), key=lambda i: i[0].lower())
]
)
header = style("Context:", bold=True)
return f"\n{header}\n{context_str}"
def _short_formatter(context: Context) -> str:
context_str = ", ".join(sorted(context.keys(), key=str.lower))
header = style("Context:", bold=True)
return f"\n{header}\n{context_str}"
def _hide_formatter(context: Context) -> str:
return ""
CONTEXT_FORMATTERS: typing.Dict[str, Formatter] = {
"full": _full_formatter,
"short": _short_formatter,
"hide": _hide_formatter,
}
def format_context(
context: Context, formatter: typing.Union[str, Formatter] = "full"
) -> str:
"""Output the a context dictionary as a string."""
if not context:
return ""
if callable(formatter):
formatter_func = formatter
else:
if formatter in CONTEXT_FORMATTERS:
formatter_func = CONTEXT_FORMATTERS[formatter]
else:
raise ValueError(f'Invalid context format: "{formatter}"')
return formatter_func(context)
BANNER_TEMPLATE = """{version}
{text}
{context}
"""
def make_banner(
text: typing.Optional[str] = None,
context: typing.Optional[Context] = None,
banner_template: typing.Optional[str] = None,
context_format: ContextFormat = "full",
) -> str:
"""Generates a full banner with version info, the given text, and a
formatted list of context variables.
"""
banner_text = text or speak()
banner_template = banner_template or BANNER_TEMPLATE
ctx = format_context(context or {}, formatter=context_format)
out = banner_template.format(version=sys.version, text=banner_text, context=ctx)
return out
def context_list2dict(context_list: typing.Sequence[typing.Any]) -> Context:
"""Converts a list of objects (functions, classes, or modules) to a
dictionary mapping the object names to the objects.
"""
return {obj.__name__.split(".")[-1]: obj for obj in context_list}
def _relpath(p: Path) -> Path:
return p.resolve().relative_to(Path.cwd())
class Shell:
"""Base shell class.
:param dict context: Dictionary, list, or callable (that returns a `dict` or `list`)
that defines what variables will be available when the shell is run.
:param str banner: Banner text that appears on startup.
:param str prompt: Custom input prompt.
:param str output: Custom output prompt.
:param context_format: Formatter for the context dictionary in the banner.
Either 'full', 'short', 'hide', or a function that receives the context
dictionary and outputs a string.
"""
banner_template: str = BANNER_TEMPLATE
def __init__(
self,
context: Context,
banner: typing.Optional[str] = None,
prompt: typing.Optional[str] = None,
output: typing.Optional[str] = None,
context_format: ContextFormat = "full",
**kwargs: typing.Any,
) -> None:
self.context = context() if callable(context) else context
self.context_format = context_format
self.banner = make_banner(
banner,
self.context,
context_format=self.context_format,
banner_template=self.banner_template,
)
self.prompt = prompt
self.output = output
def check_availability(self) -> bool:
raise NotImplementedError
def start(self) -> None:
raise NotImplementedError
class PythonShell(Shell):
"""The built-in Python shell."""
def check_availability(self) -> bool:
return True
def start(self) -> None:
try:
import readline
except ImportError:
pass
else:
# We don't have to wrap the following import in a 'try', because
# we already know 'readline' was imported successfully.
import rlcompleter
readline.set_completer(rlcompleter.Completer(self.context).complete)
readline.parse_and_bind("tab:complete")
if self.prompt:
sys.ps1 = self.prompt
if self.output:
warnings.warn("Custom output templates not supported by PythonShell.")
code.interact(self.banner, local=self.context)
return None
def configure_ipython_prompt(
config, prompt: typing.Optional[str] = None, output: typing.Optional[str] = None
) -> None:
import IPython
if IPython.version_info[0] >= 5: # Custom prompt API changed in IPython 5.0
from pygments.token import Token
# https://ipython.readthedocs.io/en/stable/config/details.html#custom-prompts # noqa: B950
class CustomPrompt(IPython.terminal.prompts.Prompts):
def in_prompt_tokens(self, *args, **kwargs):
if prompt is None:
return super().in_prompt_tokens(*args, **kwargs)
if isinstance(prompt, (str, bytes)):
return [(Token.Prompt, prompt)]
else:
return prompt
def out_prompt_tokens(self, *args, **kwargs):
if output is None:
return super().out_prompt_tokens(*args, **kwargs)
if isinstance(output, (str, bytes)):
return [(Token.OutPrompt, output)]
else:
return prompt
config.TerminalInteractiveShell.prompts_class = CustomPrompt
else:
prompt_config = config.PromptManager
if prompt:
prompt_config.in_template = prompt
if output:
prompt_config.out_template = output
return None
class IPythonShell(Shell):
"""The IPython shell.
:param list ipy_extensions: List of IPython extension names to load upon startup.
:param bool ipy_autoreload: Whether to load and initialize the IPython autoreload
extension upon startup. Can also be an integer, which will be passed as
the argument to the %autoreload line magic.
:param kwargs: The same kwargs as `Shell.__init__`.
"""
def __init__(
self,
ipy_extensions: typing.Optional[typing.List[str]] = None,
ipy_autoreload: bool = False,
ipy_colors: typing.Optional[str] = None,
ipy_highlighting_style: typing.Optional[str] = None,
*args: typing.Any,
**kwargs: typing.Any,
):
self.ipy_extensions = ipy_extensions
self.ipy_autoreload = ipy_autoreload
self.ipy_colors = ipy_colors
self.ipy_highlighting_style = ipy_highlighting_style
Shell.__init__(self, *args, **kwargs)
@staticmethod
def init_autoreload(mode: int) -> None:
"""Load and initialize the IPython autoreload extension."""
from IPython.extensions import autoreload
ip = get_ipython() # type: ignore # noqa: F821
autoreload.load_ipython_extension(ip)
ip.magics_manager.magics["line"]["autoreload"](str(mode))
def check_availability(self) -> bool:
try:
import IPython # noqa: F401
except ImportError:
raise ShellNotAvailableError("IPython shell not available.")
return True
def start(self) -> None:
try:
from IPython import start_ipython
from IPython.utils import io
from traitlets.config.loader import Config as IPyConfig
except ImportError:
raise ShellNotAvailableError(
"IPython shell not available " "or IPython version not supported."
)
# Hack to show custom banner
# TerminalIPythonApp/start_app doesn't allow you to customize the
# banner directly, so we write it to stdout before starting the IPython app
io.stdout.write(self.banner)
# Pass exec_lines in order to start autoreload
if self.ipy_autoreload:
if not isinstance(self.ipy_autoreload, bool):
mode = self.ipy_autoreload
else:
mode = 2
logger.debug(f"Initializing IPython autoreload in mode {mode}")
exec_lines = [
"import konch as __konch",
f"__konch.IPythonShell.init_autoreload({mode})",
]
else:
exec_lines = []
ipy_config = IPyConfig()
if self.ipy_colors:
ipy_config.TerminalInteractiveShell.colors = self.ipy_colors
if self.ipy_highlighting_style:
ipy_config.TerminalInteractiveShell.highlighting_style = (
self.ipy_highlighting_style
)
configure_ipython_prompt(ipy_config, prompt=self.prompt, output=self.output)
# Use start_ipython rather than embed so that IPython is loaded in the "normal"
# way. See https://github.com/django/django/pull/512
start_ipython(
display_banner=False,
user_ns=self.context,
config=ipy_config,
extensions=self.ipy_extensions or [],
exec_lines=exec_lines,
argv=[],
)
return None
class PtPythonShell(Shell):
def __init__(self, ptpy_vi_mode: bool = False, *args, **kwargs):
self.ptpy_vi_mode = ptpy_vi_mode
Shell.__init__(self, *args, **kwargs)
def check_availability(self) -> bool:
try:
import ptpython # noqa: F401
except ImportError:
raise ShellNotAvailableError("PtPython shell not available.")
return True
def start(self) -> None:
try:
from ptpython.repl import embed, run_config
except ImportError:
raise ShellNotAvailableError("PtPython shell not available.")
print(self.banner)
config_dir = Path("~/.ptpython/").expanduser()
# Startup path
startup_paths = []
if "PYTHONSTARTUP" in os.environ:
startup_paths.append(os.environ["PYTHONSTARTUP"])
# Apply config file
def configure(repl):
path = config_dir / "config.py"
if path.exists():
run_config(repl, str(path))
embed(
globals=self.context,
history_filename=config_dir / "history",
vi_mode=self.ptpy_vi_mode,
startup_paths=startup_paths,
configure=configure,
)
return None
class PtIPythonShell(PtPythonShell):
banner_template: str = "{text}\n{context}"
def __init__(
self, ipy_extensions: typing.Optional[typing.List[str]] = None, *args, **kwargs
) -> None:
self.ipy_extensions = ipy_extensions or []
PtPythonShell.__init__(self, *args, **kwargs)
def check_availability(self) -> bool:
try:
import ptpython.ipython # noqa: F401
import IPython # noqa: F401
except ImportError:
raise ShellNotAvailableError("PtIPython shell not available.")
return True
def start(self) -> None:
try:
from ptpython.ipython import embed
from ptpython.repl import run_config
from IPython.terminal.ipapp import load_default_config
except ImportError:
raise ShellNotAvailableError("PtIPython shell not available.")
config_dir = Path("~/.ptpython/").expanduser()
# Apply config file
def configure(repl):
path = config_dir / "config.py"
if path.exists():
run_config(repl, str(path))
# Startup path
startup_paths = []
if "PYTHONSTARTUP" in os.environ:
startup_paths.append(os.environ["PYTHONSTARTUP"])
# exec scripts from startup paths
for path in startup_paths:
if Path(path).exists():
with Path(path).open("rb") as f:
code = compile(f.read(), path, "exec")
exec(code, self.context, self.context)
else:
print(f"File not found: {path}\n\n")
sys.exit(1)
ipy_config = load_default_config()
ipy_config.InteractiveShellEmbed = ipy_config.TerminalInteractiveShell
ipy_config["InteractiveShellApp"]["extensions"] = self.ipy_extensions
configure_ipython_prompt(ipy_config, prompt=self.prompt, output=self.output)
embed(
config=ipy_config,
configure=configure,
history_filename=config_dir / "history",
user_ns=self.context,
header=self.banner,
vi_mode=self.ptpy_vi_mode,
)
return None
class BPythonShell(Shell):
"""The BPython shell."""
def check_availability(self) -> bool:
try:
import bpython # noqa: F401
except ImportError:
raise ShellNotAvailableError("BPython shell not available.")
return True
def start(self) -> None:
try:
from bpython import embed
except ImportError:
raise ShellNotAvailableError("BPython shell not available.")
if self.prompt:
warnings.warn("Custom prompts not supported by BPythonShell.")
if self.output:
warnings.warn("Custom output templates not supported by BPythonShell.")
embed(banner=self.banner, locals_=self.context)
return None
class BPythonCursesShell(Shell):
"""The BPython Curses shell."""
def check_availability(self) -> bool:
try:
import bpython.cli # noqa: F401
except ImportError:
raise ShellNotAvailableError("BPython Curses shell not available.")
return True
def start(self) -> None:
try:
from bpython.cli import main
except ImportError:
raise ShellNotAvailableError("BPython Curses shell not available.")
if self.prompt:
warnings.warn("Custom prompts not supported by BPython Curses shell.")
if self.output:
warnings.warn(
"Custom output templates not supported by BPython Curses shell."
)
main(banner=self.banner, locals_=self.context, args=["-i", "-q"])
return None
class AutoShell(Shell):
"""Shell that runs PtIpython, PtPython, IPython, or BPython if available.
Falls back to built-in Python shell.
"""
# Shell classes in precedence order
SHELLS = [
PtIPythonShell,
PtPythonShell,
IPythonShell,
BPythonShell,
BPythonCursesShell,
PythonShell,
]
def __init__(self, context: Context, banner: str, **kwargs):
Shell.__init__(self, context, **kwargs)
self.kwargs = kwargs
self.banner = banner
def check_availability(self) -> bool:
return True
def start(self) -> None:
shell_args = {
"context": self.context,
"banner": self.banner,
"prompt": self.prompt,
"output": self.output,
"context_format": self.context_format,
}
shell_args.update(self.kwargs)
shell = None
for shell_class in self.SHELLS:
try:
shell = shell_class(**shell_args)
shell.check_availability()
except ShellNotAvailableError:
continue
else:
break
else:
raise ShellNotAvailableError("No available shell to run.")
return shell.start()
CONCHES: typing.List[str] = [
'"My conch told me to come save you guys."\n"Hooray for the magic conches!"',
'"All hail the Magic Conch!"',
'"Hooray for the magic conches!"',
'"Uh, hello there. Magic Conch, I was wondering... '
'should I have the spaghetti or the turkey?"',
'"This copyrighted conch is the cornerstone of our organization."',
'"Praise the Magic Conch!"',
'"the conch exploded into a thousand white fragments and ceased to exist."',
"\"S'right. It's a shell!\"",
'"Ralph felt a kind of affectionate reverence for the conch"',
'"Conch! Conch!"',
'"That\'s why you got the conch out of the water"',
'"the summons of the conch"',
'"Whoever holds the conch gets to speak."',
'"They\'ll come when they hear us--"',
'"We gotta drop the load!"',
'"Dude, we\'re falling right out the sky!!"',
(
'"Oh, Magic Conch Shell, what do we need to do to get '
'out of the Kelp Forest?"\n"Nothing."'
),
'"The shell knows all!"',
'"we must never question the wisdom of the Magic Conch."',
'"The Magic Conch! A club member!"',
'"The shell has spoken!"',
'"This copyrighted conch is the cornerstone of our organization."',
'"All right, Magic Conch... what do we do now?"',
'"Ohhh! The Magic Conch Shell! Ask it something! Ask it something!"',
]
def speak() -> str:
return random.choice(CONCHES)
class Config(dict):
"""A dict-like config object. Behaves like a normal dict except that
the ``context`` will always be converted from a list to a dict.
Defines the default configuration.
"""
def __init__(
self,
context: typing.Optional[Context] = None,
banner: typing.Optional[str] = None,
shell: typing.Type[Shell] = AutoShell,
prompt: typing.Optional[str] = None,
output: typing.Optional[str] = None,
context_format: str = "full",
**kwargs: typing.Any,
) -> None:
ctx = Config.transform_val(context) or {}
super().__init__(
context=ctx,
banner=banner,
shell=shell,
prompt=prompt,
output=output,
context_format=context_format,
**kwargs,
)
def __setitem__(self, key: typing.Any, value: typing.Any) -> None:
if key == "context":
value = Config.transform_val(value)
super().__setitem__(key, value)
@staticmethod
def transform_val(val: typing.Any) -> typing.Any:
if isinstance(val, (list, tuple)):
return context_list2dict(val)
return val
def update(self, d: typing.Mapping) -> None: # type: ignore
for key in d.keys():
# Shallow-merge context
if key == "context":
self["context"].update(Config.transform_val(d["context"]))
else:
self[key] = d[key]
SHELL_MAP: typing.Dict[str, typing.Type[Shell]] = {
"ipy": IPythonShell,
"ipython": IPythonShell,
"bpy": BPythonShell,
"bpython": BPythonShell,
"bpyc": BPythonCursesShell,
"bpython-curses": BPythonCursesShell,
"py": PythonShell,
"python": PythonShell,
"auto": AutoShell,
"ptpy": PtPythonShell,
"ptpython": PtPythonShell,
"ptipy": PtIPythonShell,
"ptipython": PtIPythonShell,
}
# _cfg and _config_registry are singletons that may be mutated in a .konchrc file
_cfg = Config()
_config_registry = {"default": _cfg}
def start(
context: typing.Optional[typing.Mapping] = None,
banner: typing.Optional[str] = None,
shell: typing.Type[Shell] = AutoShell,
prompt: typing.Optional[str] = None,
output: typing.Optional[str] = None,
context_format: str = "full",
**kwargs: typing.Any,
) -> None:
"""Start up the konch shell. Takes the same parameters as Shell.__init__.
"""
logger.debug(f"Using shell: {shell!r}")
if banner is None:
banner = speak()
# Default to global config
context_ = context or _cfg["context"]
banner_ = banner or _cfg["banner"]
if isinstance(shell, type) and issubclass(shell, Shell):
shell_ = shell
else:
shell_ = SHELL_MAP.get(shell or _cfg["shell"], _cfg["shell"])
prompt_ = prompt or _cfg["prompt"]
output_ = output or _cfg["output"]
context_format_ = context_format or _cfg["context_format"]
shell_(
context=context_,
banner=banner_,
prompt=prompt_,
output=output_,
context_format=context_format_,
**kwargs,
).start()
def config(config_dict: typing.Mapping) -> Config:
"""Configures the konch shell. This function should be called in a
.konchrc file.
:param dict config_dict: Dict that may contain 'context', 'banner', and/or
'shell' (default shell class to use).
"""
logger.debug(f"Updating with {config_dict}")
_cfg.update(config_dict)
return _cfg
def reset_config() -> Config:
global _cfg
_cfg = Config()
return _cfg
def __ensure_directory_in_path(filename: Path) -> None:
"""Ensures that a file's directory is in the Python path.
"""
directory = Path(filename).parent.resolve()
if directory not in sys.path:
logger.debug(f"Adding {directory} to sys.path")
sys.path.insert(0, str(directory))
CONFIG_FILE = Path(".konchrc")
DEFAULT_CONFIG_FILE = Path.home() / ".konchrc.default"
SEPARATOR = f"\n{'*' * 46}\n"
def confirm(text: str, default: bool = False) -> bool:
"""Display a confirmation prompt."""
choices = "Y/n" if default else "y/N"
prompt = f"{style(text, bold=True)} [{choices}]: "
while 1:
try:
print(prompt, end="")
value = input("").lower().strip()
except (KeyboardInterrupt, EOFError):
sys.exit(1)
if value in ("y", "yes"):
rv = True
elif value in ("n", "no"):
rv = False
elif value == "":
rv = default
else:
print_error("Error: invalid input")
continue
break
return rv
def use_file(
filename: typing.Union[Path, str, None], trust: bool = False
) -> typing.Union[types.ModuleType, None]:
"""Load filename as a python file. Import ``filename`` and return it
as a module.
"""
config_file = filename or resolve_path(CONFIG_FILE)
def preview_unauthorized() -> None:
if not config_file:
return None
print(SEPARATOR, file=sys.stderr)
with Path(config_file).open("r", encoding="utf-8") as fp:
for line in fp:
print(line, end="", file=sys.stderr)
print(SEPARATOR, file=sys.stderr)
if config_file and not Path(config_file).exists():
print_error(f'"{filename}" not found.')
sys.exit(1)
if config_file and Path(config_file).exists():
if not trust:
with AuthFile.load() as authfile:
try:
authfile.check(Path(config_file))
except KonchrcChangedError:
print_error(f'"{config_file}" has changed since you last used it.')
preview_unauthorized()
if confirm("Would you like to authorize it?"):
authfile.allow(Path(config_file))
print()
else:
sys.exit(1)
except KonchrcNotAuthorizedError:
print_error(f'"{config_file}" is blocked.')
preview_unauthorized()
if confirm("Would you like to authorize it?"):
authfile.allow(Path(config_file))
print()
else:
sys.exit(1)
logger.info(f"Using {config_file}")
# Ensure that relative imports are possible
__ensure_directory_in_path(Path(config_file))
mod = None
try:
mod = imp.load_source("konchrc", str(config_file))
except UnboundLocalError: # File not found
pass
else:
return mod
if not config_file:
print_warning("No konch config file found.")
else:
print_warning(f'"{config_file}" not found.')
return None
def resolve_path(filename: Path) -> typing.Union[Path, None]:
"""Find a file by walking up parent directories until the file is found.
Return the absolute path of the file.
"""
current = Path.cwd()
# Stop search at home directory
sentinel_dir = Path.home().parent.resolve()
while current != sentinel_dir:
target = Path(current) / Path(filename)
if target.exists():
return target.resolve()
else:
current = current.parent.resolve()
return None
def get_editor() -> str:
for key in "KONCH_EDITOR", "VISUAL", "EDITOR":
ret = os.environ.get(key)
if ret:
return ret
if sys.platform.startswith("win"):
return "notepad"
for editor in "vim", "nano":
if os.system("which %s &> /dev/null" % editor) == 0:
return editor
return "vi"
def edit_file(
filename: typing.Optional[Path], editor: typing.Optional[str] = None
) -> None:
if not filename:
print_error("filename not passed.")
sys.exit(1)
editor = editor or get_editor()
try:
result = subprocess.Popen(f'{editor} "{filename}"', shell=True)
exit_code = result.wait()
if exit_code != 0:
print_error(f"{editor}: Editing failed!")
sys.exit(1)
except OSError as err:
print_error(f"{editor}: Editing failed: {err}")
sys.exit(1)
else:
with AuthFile.load() as authfile:
authfile.allow(filename)
INIT_TEMPLATE = """# vi: set ft=python :
import konch
import sys
import os
# Available options:
# "context", "banner", "shell", "prompt", "output",
# "context_format", "ipy_extensions", "ipy_autoreload",
# "ipy_colors", "ipy_highlighting_style", "ptpy_vi_mode"
# See: https://konch.readthedocs.io/en/latest/#configuration
konch.config({
"context": [
sys,
os,
]
})
def setup():
pass
def teardown():
pass
"""
def init_config(config_file: Path) -> typing.NoReturn:
if not config_file.exists():
print(f'Writing to "{config_file.resolve()}"...')
print(SEPARATOR)
print(INIT_TEMPLATE, end="")
print(SEPARATOR)
init_template = INIT_TEMPLATE
if DEFAULT_CONFIG_FILE.exists(): # use ~/.konchrc.default if it exists
with Path(DEFAULT_CONFIG_FILE).open("r") as fp:
init_template = fp.read()
with Path(config_file).open("w") as fp:
fp.write(init_template)
with AuthFile.load() as authfile:
authfile.allow(config_file)
relpath = _relpath(config_file)
is_default = relpath == Path(CONFIG_FILE)
edit_cmd = "konch edit" if is_default else f"konch edit {relpath}"
run_cmd = "konch" if is_default else f"konch -f {relpath}"
print(f"{style('Done!', GREEN)} ✨ 🐚 ✨")
print(f"To edit your config: `{style(edit_cmd, bold=True)}`")
print(f"To start the shell: `{style(run_cmd, bold=True)}`")
sys.exit(0)
else:
print_error(f'"{config_file}" already exists in this directory.')
sys.exit(1)
def edit_config(
config_file: typing.Optional[Path] = None, editor: typing.Optional[str] = None
) -> typing.NoReturn:
filename = config_file or resolve_path(CONFIG_FILE)
if not filename:
print_error('No ".konchrc" file found.')
styled_cmd = style("konch init", bold=True, file=sys.stderr)
print(f"Run `{styled_cmd}` to create it.", file=sys.stderr)
sys.exit(1)
if not filename.exists():
print_error(f'"{filename}" does not exist.')
relpath = _relpath(filename)
is_default = relpath == Path(CONFIG_FILE)
cmd = "konch init" if is_default else f"konch init {filename}"
styled_cmd = style(cmd, bold=True, file=sys.stderr)
print(f"Run `{styled_cmd}` to create it.", file=sys.stderr)
sys.exit(1)
print(f'Editing file: "{filename}"')
edit_file(filename, editor=editor)
sys.exit(0)
def allow_config(config_file: typing.Optional[Path] = None) -> typing.NoReturn:
filename: typing.Union[Path, None]
if config_file and config_file.is_dir():
filename = Path(config_file) / CONFIG_FILE
else:
filename = config_file or resolve_path(CONFIG_FILE)
if not filename:
print_error("No config file found.")
sys.exit(1)
with AuthFile.load() as authfile:
if authfile.check(filename, raise_error=False):
print_warning(f'"{filename}" is already authorized.')
else:
try:
print(f'Authorizing "{filename}"...')
authfile.allow(filename)
except FileNotFoundError:
print_error(f'"{filename}" does not exist.')
sys.exit(1)
print(f"{style('Done!', GREEN)} ✨ 🐚 ✨")
relpath = _relpath(filename)
cmd = "konch" if relpath == Path(CONFIG_FILE) else f"konch -f {relpath}"
print(f"You can now start a shell with `{style(cmd, bold=True)}`.")
sys.exit(0)
def deny_config(config_file: typing.Optional[Path] = None) -> typing.NoReturn:
filename: typing.Union[Path, None]
if config_file and config_file.is_dir():
filename = Path(config_file) / CONFIG_FILE
else:
filename = config_file or resolve_path(CONFIG_FILE)
if not filename:
print_error("No config file found.")
sys.exit(1)
print(f'Removing authorization for "{filename}"...')
with AuthFile.load() as authfile:
try:
authfile.deny(filename)
except FileNotFoundError:
print_error(f'"{filename}" does not exist.')
sys.exit(1)
else:
print(style("Done!", GREEN))
sys.exit(0)
def parse_args(argv: typing.Optional[typing.Sequence] = None) -> typing.Dict[str, str]:
"""Exposes the docopt command-line arguments parser.
Return a dictionary of arguments.
"""
return docopt(__doc__, argv=argv, version=__version__)
def main(argv: typing.Optional[typing.Sequence] = None) -> typing.NoReturn:
"""Main entry point for the konch CLI."""
args = parse_args(argv)
if args["--debug"]:
logging.basicConfig(
format="%(levelname)s %(filename)s: %(message)s", level=logging.DEBUG
)
logger.debug(args)
config_file: typing.Union[Path, None]
if args["init"]:
config_file = Path(args["<config_file>"] or CONFIG_FILE)
init_config(config_file)
else:
config_file = Path(args["<config_file>"]) if args["<config_file>"] else None
if args["edit"]:
edit_config(config_file)
elif args["allow"]:
allow_config(config_file)
elif args["deny"]:
deny_config(config_file)
mod = use_file(Path(args["--file"]) if args["--file"] else None)
if hasattr(mod, "setup"):
mod.setup() # type: ignore
if args["--name"]:
if args["--name"] not in _config_registry:
print_error(f'Invalid --name: "{args["--name"]}"')
sys.exit(1)
config_dict = _config_registry[args["--name"]]
logger.debug(f'Using named config: "{args["--name"]}"')
logger.debug(config_dict)
else:
config_dict = _cfg
# Allow default shell to be overriden by command-line argument
shell_name = args["--shell"]
if shell_name:
config_dict["shell"] = SHELL_MAP.get(shell_name.lower(), AutoShell)
logger.debug(f"Starting with config {config_dict}")
start(**config_dict)
if hasattr(mod, "teardown"):
mod.teardown() # type: ignore
sys.exit(0)
if __name__ == "__main__":
main()
|
sloria/konch | konch.py | __ensure_directory_in_path | python | def __ensure_directory_in_path(filename: Path) -> None:
directory = Path(filename).parent.resolve()
if directory not in sys.path:
logger.debug(f"Adding {directory} to sys.path")
sys.path.insert(0, str(directory)) | Ensures that a file's directory is in the Python path. | train | https://github.com/sloria/konch/blob/15160bd0a0cac967eeeab84794bd6cdd0b5b637d/konch.py#L861-L867 | null | #!/usr/bin/env python3
"""konch: Customizes your Python shell.
Usage:
konch
konch init [<config_file>] [-d]
konch edit [<config_file>] [-d]
konch allow [<config_file>] [-d]
konch deny [<config_file>] [-d]
konch [--name=<name>] [--file=<file>] [--shell=<shell_name>] [-d]
Options:
-h --help Show this screen.
-v --version Show version.
init Creates a starter .konchrc file.
edit Edit your .konchrc file.
-n --name=<name> Named config to use.
-s --shell=<shell_name> Shell to use. Can be either "ipy" (IPython),
"bpy" (BPython), "bpyc" (BPython Curses),
"ptpy" (PtPython), "ptipy" (PtIPython),
"py" (built-in Python shell), or "auto".
Overrides the 'shell' option in .konchrc.
-f --file=<file> File path of konch config file to execute. If not provided,
konch will use the .konchrc file in the current
directory.
-d --debug Enable debugging/verbose mode.
Environment variables:
KONCH_AUTH_FILE: File where to store authorization data for config files.
Defaults to ~/.local/share/konch_auth.
KONCH_EDITOR: Editor command to use when running `konch edit`.
Falls back to $VISUAL then $EDITOR.
NO_COLOR: Disable ANSI colors.
"""
from collections.abc import Iterable
from pathlib import Path
import code
import hashlib
import imp
import json
import logging
import os
import random
import subprocess
import sys
import typing
import types
import warnings
from docopt import docopt
__version__ = "4.2.1"
logger = logging.getLogger(__name__)
class KonchError(Exception):
pass
class ShellNotAvailableError(KonchError):
pass
class KonchrcNotAuthorizedError(KonchError):
pass
class KonchrcChangedError(KonchrcNotAuthorizedError):
pass
class AuthFile:
def __init__(self, data: typing.Dict[str, str]) -> None:
self.data = data
def __repr__(self) -> str:
return f"AuthFile({self.data!r})"
@classmethod
def load(cls, path: typing.Optional[Path] = None) -> "AuthFile":
filepath = path or cls.get_path()
try:
with Path(filepath).open("r", encoding="utf-8") as fp:
data = json.load(fp)
except FileNotFoundError:
data = {}
except json.JSONDecodeError as error:
# File exists but is empty
if error.doc.strip() == "":
data = {}
else:
raise
return cls(data)
def allow(self, filepath: Path) -> None:
logger.debug(f"Authorizing {filepath}")
self.data[str(Path(filepath).resolve())] = self._hash_file(filepath)
def deny(self, filepath: Path) -> None:
if not filepath.exists():
raise FileNotFoundError(f"{filepath} not found")
try:
logger.debug(f"Removing authorization for {filepath}")
del self.data[str(filepath.resolve())]
except KeyError:
pass
def check(
self, filepath: typing.Union[Path, None], raise_error: bool = True
) -> bool:
if not filepath:
return False
if str(filepath.resolve()) not in self.data:
if raise_error:
raise KonchrcNotAuthorizedError
else:
return False
else:
file_hash = self._hash_file(filepath)
if file_hash != self.data[str(filepath.resolve())]:
if raise_error:
raise KonchrcChangedError
else:
return False
return True
def save(self) -> None:
filepath = self.get_path()
filepath.parent.mkdir(parents=True, exist_ok=True)
with Path(filepath).open("w", encoding="utf-8") as fp:
json.dump(self.data, fp)
def __enter__(self) -> "AuthFile":
return self
def __exit__(
self,
exc_type: typing.Type[Exception],
exc_value: Exception,
exc_traceback: types.TracebackType,
) -> None:
if not exc_type:
self.save()
@staticmethod
def get_path() -> Path:
if "KONCH_AUTH_FILE" in os.environ:
return Path(os.environ["KONCH_AUTH_FILE"])
elif "XDG_DATA_HOME" in os.environ:
return Path(os.environ["XDG_DATA_HOME"]) / "konch_auth"
else:
return Path.home() / ".local" / "share" / "konch_auth"
@staticmethod
def _hash_file(filepath: Path) -> str:
# https://stackoverflow.com/a/22058673/1157536
BUF_SIZE = 65536 # read in 64kb chunks
sha1 = hashlib.sha1()
with Path(filepath).open("rb") as f:
while True:
data = f.read(BUF_SIZE)
if not data:
break
sha1.update(data) # type: ignore
return sha1.hexdigest()
RED = 31
GREEN = 32
YELLOW = 33
BOLD = 1
RESET_ALL = 0
def style(
text: str,
fg: typing.Optional[int] = None,
*,
bold: bool = False,
file: typing.IO = sys.stdout,
) -> str:
use_color = not os.environ.get("NO_COLOR") and file.isatty()
if use_color:
parts = [
fg and f"\033[{fg}m",
bold and f"\033[{BOLD}m",
text,
f"\033[{RESET_ALL}m",
]
return "".join([e for e in parts if e])
else:
return text
def sprint(text: str, *args: typing.Any, **kwargs: typing.Any) -> None:
file = kwargs.pop("file", sys.stdout)
return print(style(text, file=file, *args, **kwargs), file=file)
def print_error(text: str) -> None:
prefix = style("ERROR", RED, file=sys.stderr)
return sprint(f"{prefix}: {text}", file=sys.stderr)
def print_warning(text: str) -> None:
prefix = style("WARNING", YELLOW, file=sys.stderr)
return sprint(f"{prefix}: {text}", file=sys.stderr)
Context = typing.Mapping[str, typing.Any]
Formatter = typing.Callable[[Context], str]
ContextFormat = typing.Union[str, Formatter]
def _full_formatter(context: Context) -> str:
line_format = "{name}: {obj!r}"
context_str = "\n".join(
[
line_format.format(name=name, obj=obj)
for name, obj in sorted(context.items(), key=lambda i: i[0].lower())
]
)
header = style("Context:", bold=True)
return f"\n{header}\n{context_str}"
def _short_formatter(context: Context) -> str:
context_str = ", ".join(sorted(context.keys(), key=str.lower))
header = style("Context:", bold=True)
return f"\n{header}\n{context_str}"
def _hide_formatter(context: Context) -> str:
return ""
CONTEXT_FORMATTERS: typing.Dict[str, Formatter] = {
"full": _full_formatter,
"short": _short_formatter,
"hide": _hide_formatter,
}
def format_context(
context: Context, formatter: typing.Union[str, Formatter] = "full"
) -> str:
"""Output the a context dictionary as a string."""
if not context:
return ""
if callable(formatter):
formatter_func = formatter
else:
if formatter in CONTEXT_FORMATTERS:
formatter_func = CONTEXT_FORMATTERS[formatter]
else:
raise ValueError(f'Invalid context format: "{formatter}"')
return formatter_func(context)
BANNER_TEMPLATE = """{version}
{text}
{context}
"""
def make_banner(
text: typing.Optional[str] = None,
context: typing.Optional[Context] = None,
banner_template: typing.Optional[str] = None,
context_format: ContextFormat = "full",
) -> str:
"""Generates a full banner with version info, the given text, and a
formatted list of context variables.
"""
banner_text = text or speak()
banner_template = banner_template or BANNER_TEMPLATE
ctx = format_context(context or {}, formatter=context_format)
out = banner_template.format(version=sys.version, text=banner_text, context=ctx)
return out
def context_list2dict(context_list: typing.Sequence[typing.Any]) -> Context:
"""Converts a list of objects (functions, classes, or modules) to a
dictionary mapping the object names to the objects.
"""
return {obj.__name__.split(".")[-1]: obj for obj in context_list}
def _relpath(p: Path) -> Path:
return p.resolve().relative_to(Path.cwd())
class Shell:
"""Base shell class.
:param dict context: Dictionary, list, or callable (that returns a `dict` or `list`)
that defines what variables will be available when the shell is run.
:param str banner: Banner text that appears on startup.
:param str prompt: Custom input prompt.
:param str output: Custom output prompt.
:param context_format: Formatter for the context dictionary in the banner.
Either 'full', 'short', 'hide', or a function that receives the context
dictionary and outputs a string.
"""
banner_template: str = BANNER_TEMPLATE
def __init__(
self,
context: Context,
banner: typing.Optional[str] = None,
prompt: typing.Optional[str] = None,
output: typing.Optional[str] = None,
context_format: ContextFormat = "full",
**kwargs: typing.Any,
) -> None:
self.context = context() if callable(context) else context
self.context_format = context_format
self.banner = make_banner(
banner,
self.context,
context_format=self.context_format,
banner_template=self.banner_template,
)
self.prompt = prompt
self.output = output
def check_availability(self) -> bool:
raise NotImplementedError
def start(self) -> None:
raise NotImplementedError
class PythonShell(Shell):
"""The built-in Python shell."""
def check_availability(self) -> bool:
return True
def start(self) -> None:
try:
import readline
except ImportError:
pass
else:
# We don't have to wrap the following import in a 'try', because
# we already know 'readline' was imported successfully.
import rlcompleter
readline.set_completer(rlcompleter.Completer(self.context).complete)
readline.parse_and_bind("tab:complete")
if self.prompt:
sys.ps1 = self.prompt
if self.output:
warnings.warn("Custom output templates not supported by PythonShell.")
code.interact(self.banner, local=self.context)
return None
def configure_ipython_prompt(
config, prompt: typing.Optional[str] = None, output: typing.Optional[str] = None
) -> None:
import IPython
if IPython.version_info[0] >= 5: # Custom prompt API changed in IPython 5.0
from pygments.token import Token
# https://ipython.readthedocs.io/en/stable/config/details.html#custom-prompts # noqa: B950
class CustomPrompt(IPython.terminal.prompts.Prompts):
def in_prompt_tokens(self, *args, **kwargs):
if prompt is None:
return super().in_prompt_tokens(*args, **kwargs)
if isinstance(prompt, (str, bytes)):
return [(Token.Prompt, prompt)]
else:
return prompt
def out_prompt_tokens(self, *args, **kwargs):
if output is None:
return super().out_prompt_tokens(*args, **kwargs)
if isinstance(output, (str, bytes)):
return [(Token.OutPrompt, output)]
else:
return prompt
config.TerminalInteractiveShell.prompts_class = CustomPrompt
else:
prompt_config = config.PromptManager
if prompt:
prompt_config.in_template = prompt
if output:
prompt_config.out_template = output
return None
class IPythonShell(Shell):
"""The IPython shell.
:param list ipy_extensions: List of IPython extension names to load upon startup.
:param bool ipy_autoreload: Whether to load and initialize the IPython autoreload
extension upon startup. Can also be an integer, which will be passed as
the argument to the %autoreload line magic.
:param kwargs: The same kwargs as `Shell.__init__`.
"""
def __init__(
self,
ipy_extensions: typing.Optional[typing.List[str]] = None,
ipy_autoreload: bool = False,
ipy_colors: typing.Optional[str] = None,
ipy_highlighting_style: typing.Optional[str] = None,
*args: typing.Any,
**kwargs: typing.Any,
):
self.ipy_extensions = ipy_extensions
self.ipy_autoreload = ipy_autoreload
self.ipy_colors = ipy_colors
self.ipy_highlighting_style = ipy_highlighting_style
Shell.__init__(self, *args, **kwargs)
@staticmethod
def init_autoreload(mode: int) -> None:
"""Load and initialize the IPython autoreload extension."""
from IPython.extensions import autoreload
ip = get_ipython() # type: ignore # noqa: F821
autoreload.load_ipython_extension(ip)
ip.magics_manager.magics["line"]["autoreload"](str(mode))
def check_availability(self) -> bool:
try:
import IPython # noqa: F401
except ImportError:
raise ShellNotAvailableError("IPython shell not available.")
return True
def start(self) -> None:
try:
from IPython import start_ipython
from IPython.utils import io
from traitlets.config.loader import Config as IPyConfig
except ImportError:
raise ShellNotAvailableError(
"IPython shell not available " "or IPython version not supported."
)
# Hack to show custom banner
# TerminalIPythonApp/start_app doesn't allow you to customize the
# banner directly, so we write it to stdout before starting the IPython app
io.stdout.write(self.banner)
# Pass exec_lines in order to start autoreload
if self.ipy_autoreload:
if not isinstance(self.ipy_autoreload, bool):
mode = self.ipy_autoreload
else:
mode = 2
logger.debug(f"Initializing IPython autoreload in mode {mode}")
exec_lines = [
"import konch as __konch",
f"__konch.IPythonShell.init_autoreload({mode})",
]
else:
exec_lines = []
ipy_config = IPyConfig()
if self.ipy_colors:
ipy_config.TerminalInteractiveShell.colors = self.ipy_colors
if self.ipy_highlighting_style:
ipy_config.TerminalInteractiveShell.highlighting_style = (
self.ipy_highlighting_style
)
configure_ipython_prompt(ipy_config, prompt=self.prompt, output=self.output)
# Use start_ipython rather than embed so that IPython is loaded in the "normal"
# way. See https://github.com/django/django/pull/512
start_ipython(
display_banner=False,
user_ns=self.context,
config=ipy_config,
extensions=self.ipy_extensions or [],
exec_lines=exec_lines,
argv=[],
)
return None
class PtPythonShell(Shell):
def __init__(self, ptpy_vi_mode: bool = False, *args, **kwargs):
self.ptpy_vi_mode = ptpy_vi_mode
Shell.__init__(self, *args, **kwargs)
def check_availability(self) -> bool:
try:
import ptpython # noqa: F401
except ImportError:
raise ShellNotAvailableError("PtPython shell not available.")
return True
def start(self) -> None:
try:
from ptpython.repl import embed, run_config
except ImportError:
raise ShellNotAvailableError("PtPython shell not available.")
print(self.banner)
config_dir = Path("~/.ptpython/").expanduser()
# Startup path
startup_paths = []
if "PYTHONSTARTUP" in os.environ:
startup_paths.append(os.environ["PYTHONSTARTUP"])
# Apply config file
def configure(repl):
path = config_dir / "config.py"
if path.exists():
run_config(repl, str(path))
embed(
globals=self.context,
history_filename=config_dir / "history",
vi_mode=self.ptpy_vi_mode,
startup_paths=startup_paths,
configure=configure,
)
return None
class PtIPythonShell(PtPythonShell):
banner_template: str = "{text}\n{context}"
def __init__(
self, ipy_extensions: typing.Optional[typing.List[str]] = None, *args, **kwargs
) -> None:
self.ipy_extensions = ipy_extensions or []
PtPythonShell.__init__(self, *args, **kwargs)
def check_availability(self) -> bool:
try:
import ptpython.ipython # noqa: F401
import IPython # noqa: F401
except ImportError:
raise ShellNotAvailableError("PtIPython shell not available.")
return True
def start(self) -> None:
try:
from ptpython.ipython import embed
from ptpython.repl import run_config
from IPython.terminal.ipapp import load_default_config
except ImportError:
raise ShellNotAvailableError("PtIPython shell not available.")
config_dir = Path("~/.ptpython/").expanduser()
# Apply config file
def configure(repl):
path = config_dir / "config.py"
if path.exists():
run_config(repl, str(path))
# Startup path
startup_paths = []
if "PYTHONSTARTUP" in os.environ:
startup_paths.append(os.environ["PYTHONSTARTUP"])
# exec scripts from startup paths
for path in startup_paths:
if Path(path).exists():
with Path(path).open("rb") as f:
code = compile(f.read(), path, "exec")
exec(code, self.context, self.context)
else:
print(f"File not found: {path}\n\n")
sys.exit(1)
ipy_config = load_default_config()
ipy_config.InteractiveShellEmbed = ipy_config.TerminalInteractiveShell
ipy_config["InteractiveShellApp"]["extensions"] = self.ipy_extensions
configure_ipython_prompt(ipy_config, prompt=self.prompt, output=self.output)
embed(
config=ipy_config,
configure=configure,
history_filename=config_dir / "history",
user_ns=self.context,
header=self.banner,
vi_mode=self.ptpy_vi_mode,
)
return None
class BPythonShell(Shell):
"""The BPython shell."""
def check_availability(self) -> bool:
try:
import bpython # noqa: F401
except ImportError:
raise ShellNotAvailableError("BPython shell not available.")
return True
def start(self) -> None:
try:
from bpython import embed
except ImportError:
raise ShellNotAvailableError("BPython shell not available.")
if self.prompt:
warnings.warn("Custom prompts not supported by BPythonShell.")
if self.output:
warnings.warn("Custom output templates not supported by BPythonShell.")
embed(banner=self.banner, locals_=self.context)
return None
class BPythonCursesShell(Shell):
"""The BPython Curses shell."""
def check_availability(self) -> bool:
try:
import bpython.cli # noqa: F401
except ImportError:
raise ShellNotAvailableError("BPython Curses shell not available.")
return True
def start(self) -> None:
try:
from bpython.cli import main
except ImportError:
raise ShellNotAvailableError("BPython Curses shell not available.")
if self.prompt:
warnings.warn("Custom prompts not supported by BPython Curses shell.")
if self.output:
warnings.warn(
"Custom output templates not supported by BPython Curses shell."
)
main(banner=self.banner, locals_=self.context, args=["-i", "-q"])
return None
class AutoShell(Shell):
"""Shell that runs PtIpython, PtPython, IPython, or BPython if available.
Falls back to built-in Python shell.
"""
# Shell classes in precedence order
SHELLS = [
PtIPythonShell,
PtPythonShell,
IPythonShell,
BPythonShell,
BPythonCursesShell,
PythonShell,
]
def __init__(self, context: Context, banner: str, **kwargs):
Shell.__init__(self, context, **kwargs)
self.kwargs = kwargs
self.banner = banner
def check_availability(self) -> bool:
return True
def start(self) -> None:
shell_args = {
"context": self.context,
"banner": self.banner,
"prompt": self.prompt,
"output": self.output,
"context_format": self.context_format,
}
shell_args.update(self.kwargs)
shell = None
for shell_class in self.SHELLS:
try:
shell = shell_class(**shell_args)
shell.check_availability()
except ShellNotAvailableError:
continue
else:
break
else:
raise ShellNotAvailableError("No available shell to run.")
return shell.start()
CONCHES: typing.List[str] = [
'"My conch told me to come save you guys."\n"Hooray for the magic conches!"',
'"All hail the Magic Conch!"',
'"Hooray for the magic conches!"',
'"Uh, hello there. Magic Conch, I was wondering... '
'should I have the spaghetti or the turkey?"',
'"This copyrighted conch is the cornerstone of our organization."',
'"Praise the Magic Conch!"',
'"the conch exploded into a thousand white fragments and ceased to exist."',
"\"S'right. It's a shell!\"",
'"Ralph felt a kind of affectionate reverence for the conch"',
'"Conch! Conch!"',
'"That\'s why you got the conch out of the water"',
'"the summons of the conch"',
'"Whoever holds the conch gets to speak."',
'"They\'ll come when they hear us--"',
'"We gotta drop the load!"',
'"Dude, we\'re falling right out the sky!!"',
(
'"Oh, Magic Conch Shell, what do we need to do to get '
'out of the Kelp Forest?"\n"Nothing."'
),
'"The shell knows all!"',
'"we must never question the wisdom of the Magic Conch."',
'"The Magic Conch! A club member!"',
'"The shell has spoken!"',
'"This copyrighted conch is the cornerstone of our organization."',
'"All right, Magic Conch... what do we do now?"',
'"Ohhh! The Magic Conch Shell! Ask it something! Ask it something!"',
]
def speak() -> str:
return random.choice(CONCHES)
class Config(dict):
"""A dict-like config object. Behaves like a normal dict except that
the ``context`` will always be converted from a list to a dict.
Defines the default configuration.
"""
def __init__(
self,
context: typing.Optional[Context] = None,
banner: typing.Optional[str] = None,
shell: typing.Type[Shell] = AutoShell,
prompt: typing.Optional[str] = None,
output: typing.Optional[str] = None,
context_format: str = "full",
**kwargs: typing.Any,
) -> None:
ctx = Config.transform_val(context) or {}
super().__init__(
context=ctx,
banner=banner,
shell=shell,
prompt=prompt,
output=output,
context_format=context_format,
**kwargs,
)
def __setitem__(self, key: typing.Any, value: typing.Any) -> None:
if key == "context":
value = Config.transform_val(value)
super().__setitem__(key, value)
@staticmethod
def transform_val(val: typing.Any) -> typing.Any:
if isinstance(val, (list, tuple)):
return context_list2dict(val)
return val
def update(self, d: typing.Mapping) -> None: # type: ignore
for key in d.keys():
# Shallow-merge context
if key == "context":
self["context"].update(Config.transform_val(d["context"]))
else:
self[key] = d[key]
SHELL_MAP: typing.Dict[str, typing.Type[Shell]] = {
"ipy": IPythonShell,
"ipython": IPythonShell,
"bpy": BPythonShell,
"bpython": BPythonShell,
"bpyc": BPythonCursesShell,
"bpython-curses": BPythonCursesShell,
"py": PythonShell,
"python": PythonShell,
"auto": AutoShell,
"ptpy": PtPythonShell,
"ptpython": PtPythonShell,
"ptipy": PtIPythonShell,
"ptipython": PtIPythonShell,
}
# _cfg and _config_registry are singletons that may be mutated in a .konchrc file
_cfg = Config()
_config_registry = {"default": _cfg}
def start(
context: typing.Optional[typing.Mapping] = None,
banner: typing.Optional[str] = None,
shell: typing.Type[Shell] = AutoShell,
prompt: typing.Optional[str] = None,
output: typing.Optional[str] = None,
context_format: str = "full",
**kwargs: typing.Any,
) -> None:
"""Start up the konch shell. Takes the same parameters as Shell.__init__.
"""
logger.debug(f"Using shell: {shell!r}")
if banner is None:
banner = speak()
# Default to global config
context_ = context or _cfg["context"]
banner_ = banner or _cfg["banner"]
if isinstance(shell, type) and issubclass(shell, Shell):
shell_ = shell
else:
shell_ = SHELL_MAP.get(shell or _cfg["shell"], _cfg["shell"])
prompt_ = prompt or _cfg["prompt"]
output_ = output or _cfg["output"]
context_format_ = context_format or _cfg["context_format"]
shell_(
context=context_,
banner=banner_,
prompt=prompt_,
output=output_,
context_format=context_format_,
**kwargs,
).start()
def config(config_dict: typing.Mapping) -> Config:
"""Configures the konch shell. This function should be called in a
.konchrc file.
:param dict config_dict: Dict that may contain 'context', 'banner', and/or
'shell' (default shell class to use).
"""
logger.debug(f"Updating with {config_dict}")
_cfg.update(config_dict)
return _cfg
def named_config(name: str, config_dict: typing.Mapping) -> None:
"""Adds a named config to the config registry. The first argument
may either be a string or a collection of strings.
This function should be called in a .konchrc file.
"""
names = (
name
if isinstance(name, Iterable) and not isinstance(name, (str, bytes))
else [name]
)
for each in names:
_config_registry[each] = Config(**config_dict)
def reset_config() -> Config:
global _cfg
_cfg = Config()
return _cfg
CONFIG_FILE = Path(".konchrc")
DEFAULT_CONFIG_FILE = Path.home() / ".konchrc.default"
SEPARATOR = f"\n{'*' * 46}\n"
def confirm(text: str, default: bool = False) -> bool:
"""Display a confirmation prompt."""
choices = "Y/n" if default else "y/N"
prompt = f"{style(text, bold=True)} [{choices}]: "
while 1:
try:
print(prompt, end="")
value = input("").lower().strip()
except (KeyboardInterrupt, EOFError):
sys.exit(1)
if value in ("y", "yes"):
rv = True
elif value in ("n", "no"):
rv = False
elif value == "":
rv = default
else:
print_error("Error: invalid input")
continue
break
return rv
def use_file(
filename: typing.Union[Path, str, None], trust: bool = False
) -> typing.Union[types.ModuleType, None]:
"""Load filename as a python file. Import ``filename`` and return it
as a module.
"""
config_file = filename or resolve_path(CONFIG_FILE)
def preview_unauthorized() -> None:
if not config_file:
return None
print(SEPARATOR, file=sys.stderr)
with Path(config_file).open("r", encoding="utf-8") as fp:
for line in fp:
print(line, end="", file=sys.stderr)
print(SEPARATOR, file=sys.stderr)
if config_file and not Path(config_file).exists():
print_error(f'"{filename}" not found.')
sys.exit(1)
if config_file and Path(config_file).exists():
if not trust:
with AuthFile.load() as authfile:
try:
authfile.check(Path(config_file))
except KonchrcChangedError:
print_error(f'"{config_file}" has changed since you last used it.')
preview_unauthorized()
if confirm("Would you like to authorize it?"):
authfile.allow(Path(config_file))
print()
else:
sys.exit(1)
except KonchrcNotAuthorizedError:
print_error(f'"{config_file}" is blocked.')
preview_unauthorized()
if confirm("Would you like to authorize it?"):
authfile.allow(Path(config_file))
print()
else:
sys.exit(1)
logger.info(f"Using {config_file}")
# Ensure that relative imports are possible
__ensure_directory_in_path(Path(config_file))
mod = None
try:
mod = imp.load_source("konchrc", str(config_file))
except UnboundLocalError: # File not found
pass
else:
return mod
if not config_file:
print_warning("No konch config file found.")
else:
print_warning(f'"{config_file}" not found.')
return None
def resolve_path(filename: Path) -> typing.Union[Path, None]:
"""Find a file by walking up parent directories until the file is found.
Return the absolute path of the file.
"""
current = Path.cwd()
# Stop search at home directory
sentinel_dir = Path.home().parent.resolve()
while current != sentinel_dir:
target = Path(current) / Path(filename)
if target.exists():
return target.resolve()
else:
current = current.parent.resolve()
return None
def get_editor() -> str:
for key in "KONCH_EDITOR", "VISUAL", "EDITOR":
ret = os.environ.get(key)
if ret:
return ret
if sys.platform.startswith("win"):
return "notepad"
for editor in "vim", "nano":
if os.system("which %s &> /dev/null" % editor) == 0:
return editor
return "vi"
def edit_file(
filename: typing.Optional[Path], editor: typing.Optional[str] = None
) -> None:
if not filename:
print_error("filename not passed.")
sys.exit(1)
editor = editor or get_editor()
try:
result = subprocess.Popen(f'{editor} "{filename}"', shell=True)
exit_code = result.wait()
if exit_code != 0:
print_error(f"{editor}: Editing failed!")
sys.exit(1)
except OSError as err:
print_error(f"{editor}: Editing failed: {err}")
sys.exit(1)
else:
with AuthFile.load() as authfile:
authfile.allow(filename)
INIT_TEMPLATE = """# vi: set ft=python :
import konch
import sys
import os
# Available options:
# "context", "banner", "shell", "prompt", "output",
# "context_format", "ipy_extensions", "ipy_autoreload",
# "ipy_colors", "ipy_highlighting_style", "ptpy_vi_mode"
# See: https://konch.readthedocs.io/en/latest/#configuration
konch.config({
"context": [
sys,
os,
]
})
def setup():
pass
def teardown():
pass
"""
def init_config(config_file: Path) -> typing.NoReturn:
if not config_file.exists():
print(f'Writing to "{config_file.resolve()}"...')
print(SEPARATOR)
print(INIT_TEMPLATE, end="")
print(SEPARATOR)
init_template = INIT_TEMPLATE
if DEFAULT_CONFIG_FILE.exists(): # use ~/.konchrc.default if it exists
with Path(DEFAULT_CONFIG_FILE).open("r") as fp:
init_template = fp.read()
with Path(config_file).open("w") as fp:
fp.write(init_template)
with AuthFile.load() as authfile:
authfile.allow(config_file)
relpath = _relpath(config_file)
is_default = relpath == Path(CONFIG_FILE)
edit_cmd = "konch edit" if is_default else f"konch edit {relpath}"
run_cmd = "konch" if is_default else f"konch -f {relpath}"
print(f"{style('Done!', GREEN)} ✨ 🐚 ✨")
print(f"To edit your config: `{style(edit_cmd, bold=True)}`")
print(f"To start the shell: `{style(run_cmd, bold=True)}`")
sys.exit(0)
else:
print_error(f'"{config_file}" already exists in this directory.')
sys.exit(1)
def edit_config(
config_file: typing.Optional[Path] = None, editor: typing.Optional[str] = None
) -> typing.NoReturn:
filename = config_file or resolve_path(CONFIG_FILE)
if not filename:
print_error('No ".konchrc" file found.')
styled_cmd = style("konch init", bold=True, file=sys.stderr)
print(f"Run `{styled_cmd}` to create it.", file=sys.stderr)
sys.exit(1)
if not filename.exists():
print_error(f'"{filename}" does not exist.')
relpath = _relpath(filename)
is_default = relpath == Path(CONFIG_FILE)
cmd = "konch init" if is_default else f"konch init {filename}"
styled_cmd = style(cmd, bold=True, file=sys.stderr)
print(f"Run `{styled_cmd}` to create it.", file=sys.stderr)
sys.exit(1)
print(f'Editing file: "{filename}"')
edit_file(filename, editor=editor)
sys.exit(0)
def allow_config(config_file: typing.Optional[Path] = None) -> typing.NoReturn:
filename: typing.Union[Path, None]
if config_file and config_file.is_dir():
filename = Path(config_file) / CONFIG_FILE
else:
filename = config_file or resolve_path(CONFIG_FILE)
if not filename:
print_error("No config file found.")
sys.exit(1)
with AuthFile.load() as authfile:
if authfile.check(filename, raise_error=False):
print_warning(f'"{filename}" is already authorized.')
else:
try:
print(f'Authorizing "{filename}"...')
authfile.allow(filename)
except FileNotFoundError:
print_error(f'"{filename}" does not exist.')
sys.exit(1)
print(f"{style('Done!', GREEN)} ✨ 🐚 ✨")
relpath = _relpath(filename)
cmd = "konch" if relpath == Path(CONFIG_FILE) else f"konch -f {relpath}"
print(f"You can now start a shell with `{style(cmd, bold=True)}`.")
sys.exit(0)
def deny_config(config_file: typing.Optional[Path] = None) -> typing.NoReturn:
filename: typing.Union[Path, None]
if config_file and config_file.is_dir():
filename = Path(config_file) / CONFIG_FILE
else:
filename = config_file or resolve_path(CONFIG_FILE)
if not filename:
print_error("No config file found.")
sys.exit(1)
print(f'Removing authorization for "{filename}"...')
with AuthFile.load() as authfile:
try:
authfile.deny(filename)
except FileNotFoundError:
print_error(f'"{filename}" does not exist.')
sys.exit(1)
else:
print(style("Done!", GREEN))
sys.exit(0)
def parse_args(argv: typing.Optional[typing.Sequence] = None) -> typing.Dict[str, str]:
"""Exposes the docopt command-line arguments parser.
Return a dictionary of arguments.
"""
return docopt(__doc__, argv=argv, version=__version__)
def main(argv: typing.Optional[typing.Sequence] = None) -> typing.NoReturn:
"""Main entry point for the konch CLI."""
args = parse_args(argv)
if args["--debug"]:
logging.basicConfig(
format="%(levelname)s %(filename)s: %(message)s", level=logging.DEBUG
)
logger.debug(args)
config_file: typing.Union[Path, None]
if args["init"]:
config_file = Path(args["<config_file>"] or CONFIG_FILE)
init_config(config_file)
else:
config_file = Path(args["<config_file>"]) if args["<config_file>"] else None
if args["edit"]:
edit_config(config_file)
elif args["allow"]:
allow_config(config_file)
elif args["deny"]:
deny_config(config_file)
mod = use_file(Path(args["--file"]) if args["--file"] else None)
if hasattr(mod, "setup"):
mod.setup() # type: ignore
if args["--name"]:
if args["--name"] not in _config_registry:
print_error(f'Invalid --name: "{args["--name"]}"')
sys.exit(1)
config_dict = _config_registry[args["--name"]]
logger.debug(f'Using named config: "{args["--name"]}"')
logger.debug(config_dict)
else:
config_dict = _cfg
# Allow default shell to be overriden by command-line argument
shell_name = args["--shell"]
if shell_name:
config_dict["shell"] = SHELL_MAP.get(shell_name.lower(), AutoShell)
logger.debug(f"Starting with config {config_dict}")
start(**config_dict)
if hasattr(mod, "teardown"):
mod.teardown() # type: ignore
sys.exit(0)
if __name__ == "__main__":
main()
|
sloria/konch | konch.py | confirm | python | def confirm(text: str, default: bool = False) -> bool:
choices = "Y/n" if default else "y/N"
prompt = f"{style(text, bold=True)} [{choices}]: "
while 1:
try:
print(prompt, end="")
value = input("").lower().strip()
except (KeyboardInterrupt, EOFError):
sys.exit(1)
if value in ("y", "yes"):
rv = True
elif value in ("n", "no"):
rv = False
elif value == "":
rv = default
else:
print_error("Error: invalid input")
continue
break
return rv | Display a confirmation prompt. | train | https://github.com/sloria/konch/blob/15160bd0a0cac967eeeab84794bd6cdd0b5b637d/konch.py#L875-L895 | [
"def style(\n text: str,\n fg: typing.Optional[int] = None,\n *,\n bold: bool = False,\n file: typing.IO = sys.stdout,\n) -> str:\n use_color = not os.environ.get(\"NO_COLOR\") and file.isatty()\n if use_color:\n parts = [\n fg and f\"\\033[{fg}m\",\n bold and f\"\\033[{BOLD}m\",\n text,\n f\"\\033[{RESET_ALL}m\",\n ]\n return \"\".join([e for e in parts if e])\n else:\n return text\n",
"def print_error(text: str) -> None:\n prefix = style(\"ERROR\", RED, file=sys.stderr)\n return sprint(f\"{prefix}: {text}\", file=sys.stderr)\n"
] | #!/usr/bin/env python3
"""konch: Customizes your Python shell.
Usage:
konch
konch init [<config_file>] [-d]
konch edit [<config_file>] [-d]
konch allow [<config_file>] [-d]
konch deny [<config_file>] [-d]
konch [--name=<name>] [--file=<file>] [--shell=<shell_name>] [-d]
Options:
-h --help Show this screen.
-v --version Show version.
init Creates a starter .konchrc file.
edit Edit your .konchrc file.
-n --name=<name> Named config to use.
-s --shell=<shell_name> Shell to use. Can be either "ipy" (IPython),
"bpy" (BPython), "bpyc" (BPython Curses),
"ptpy" (PtPython), "ptipy" (PtIPython),
"py" (built-in Python shell), or "auto".
Overrides the 'shell' option in .konchrc.
-f --file=<file> File path of konch config file to execute. If not provided,
konch will use the .konchrc file in the current
directory.
-d --debug Enable debugging/verbose mode.
Environment variables:
KONCH_AUTH_FILE: File where to store authorization data for config files.
Defaults to ~/.local/share/konch_auth.
KONCH_EDITOR: Editor command to use when running `konch edit`.
Falls back to $VISUAL then $EDITOR.
NO_COLOR: Disable ANSI colors.
"""
from collections.abc import Iterable
from pathlib import Path
import code
import hashlib
import imp
import json
import logging
import os
import random
import subprocess
import sys
import typing
import types
import warnings
from docopt import docopt
__version__ = "4.2.1"
logger = logging.getLogger(__name__)
class KonchError(Exception):
pass
class ShellNotAvailableError(KonchError):
pass
class KonchrcNotAuthorizedError(KonchError):
pass
class KonchrcChangedError(KonchrcNotAuthorizedError):
pass
class AuthFile:
def __init__(self, data: typing.Dict[str, str]) -> None:
self.data = data
def __repr__(self) -> str:
return f"AuthFile({self.data!r})"
@classmethod
def load(cls, path: typing.Optional[Path] = None) -> "AuthFile":
filepath = path or cls.get_path()
try:
with Path(filepath).open("r", encoding="utf-8") as fp:
data = json.load(fp)
except FileNotFoundError:
data = {}
except json.JSONDecodeError as error:
# File exists but is empty
if error.doc.strip() == "":
data = {}
else:
raise
return cls(data)
def allow(self, filepath: Path) -> None:
logger.debug(f"Authorizing {filepath}")
self.data[str(Path(filepath).resolve())] = self._hash_file(filepath)
def deny(self, filepath: Path) -> None:
if not filepath.exists():
raise FileNotFoundError(f"{filepath} not found")
try:
logger.debug(f"Removing authorization for {filepath}")
del self.data[str(filepath.resolve())]
except KeyError:
pass
def check(
self, filepath: typing.Union[Path, None], raise_error: bool = True
) -> bool:
if not filepath:
return False
if str(filepath.resolve()) not in self.data:
if raise_error:
raise KonchrcNotAuthorizedError
else:
return False
else:
file_hash = self._hash_file(filepath)
if file_hash != self.data[str(filepath.resolve())]:
if raise_error:
raise KonchrcChangedError
else:
return False
return True
def save(self) -> None:
filepath = self.get_path()
filepath.parent.mkdir(parents=True, exist_ok=True)
with Path(filepath).open("w", encoding="utf-8") as fp:
json.dump(self.data, fp)
def __enter__(self) -> "AuthFile":
return self
def __exit__(
self,
exc_type: typing.Type[Exception],
exc_value: Exception,
exc_traceback: types.TracebackType,
) -> None:
if not exc_type:
self.save()
@staticmethod
def get_path() -> Path:
if "KONCH_AUTH_FILE" in os.environ:
return Path(os.environ["KONCH_AUTH_FILE"])
elif "XDG_DATA_HOME" in os.environ:
return Path(os.environ["XDG_DATA_HOME"]) / "konch_auth"
else:
return Path.home() / ".local" / "share" / "konch_auth"
@staticmethod
def _hash_file(filepath: Path) -> str:
# https://stackoverflow.com/a/22058673/1157536
BUF_SIZE = 65536 # read in 64kb chunks
sha1 = hashlib.sha1()
with Path(filepath).open("rb") as f:
while True:
data = f.read(BUF_SIZE)
if not data:
break
sha1.update(data) # type: ignore
return sha1.hexdigest()
RED = 31
GREEN = 32
YELLOW = 33
BOLD = 1
RESET_ALL = 0
def style(
text: str,
fg: typing.Optional[int] = None,
*,
bold: bool = False,
file: typing.IO = sys.stdout,
) -> str:
use_color = not os.environ.get("NO_COLOR") and file.isatty()
if use_color:
parts = [
fg and f"\033[{fg}m",
bold and f"\033[{BOLD}m",
text,
f"\033[{RESET_ALL}m",
]
return "".join([e for e in parts if e])
else:
return text
def sprint(text: str, *args: typing.Any, **kwargs: typing.Any) -> None:
file = kwargs.pop("file", sys.stdout)
return print(style(text, file=file, *args, **kwargs), file=file)
def print_error(text: str) -> None:
prefix = style("ERROR", RED, file=sys.stderr)
return sprint(f"{prefix}: {text}", file=sys.stderr)
def print_warning(text: str) -> None:
prefix = style("WARNING", YELLOW, file=sys.stderr)
return sprint(f"{prefix}: {text}", file=sys.stderr)
Context = typing.Mapping[str, typing.Any]
Formatter = typing.Callable[[Context], str]
ContextFormat = typing.Union[str, Formatter]
def _full_formatter(context: Context) -> str:
line_format = "{name}: {obj!r}"
context_str = "\n".join(
[
line_format.format(name=name, obj=obj)
for name, obj in sorted(context.items(), key=lambda i: i[0].lower())
]
)
header = style("Context:", bold=True)
return f"\n{header}\n{context_str}"
def _short_formatter(context: Context) -> str:
context_str = ", ".join(sorted(context.keys(), key=str.lower))
header = style("Context:", bold=True)
return f"\n{header}\n{context_str}"
def _hide_formatter(context: Context) -> str:
return ""
CONTEXT_FORMATTERS: typing.Dict[str, Formatter] = {
"full": _full_formatter,
"short": _short_formatter,
"hide": _hide_formatter,
}
def format_context(
context: Context, formatter: typing.Union[str, Formatter] = "full"
) -> str:
"""Output the a context dictionary as a string."""
if not context:
return ""
if callable(formatter):
formatter_func = formatter
else:
if formatter in CONTEXT_FORMATTERS:
formatter_func = CONTEXT_FORMATTERS[formatter]
else:
raise ValueError(f'Invalid context format: "{formatter}"')
return formatter_func(context)
BANNER_TEMPLATE = """{version}
{text}
{context}
"""
def make_banner(
text: typing.Optional[str] = None,
context: typing.Optional[Context] = None,
banner_template: typing.Optional[str] = None,
context_format: ContextFormat = "full",
) -> str:
"""Generates a full banner with version info, the given text, and a
formatted list of context variables.
"""
banner_text = text or speak()
banner_template = banner_template or BANNER_TEMPLATE
ctx = format_context(context or {}, formatter=context_format)
out = banner_template.format(version=sys.version, text=banner_text, context=ctx)
return out
def context_list2dict(context_list: typing.Sequence[typing.Any]) -> Context:
"""Converts a list of objects (functions, classes, or modules) to a
dictionary mapping the object names to the objects.
"""
return {obj.__name__.split(".")[-1]: obj for obj in context_list}
def _relpath(p: Path) -> Path:
return p.resolve().relative_to(Path.cwd())
class Shell:
"""Base shell class.
:param dict context: Dictionary, list, or callable (that returns a `dict` or `list`)
that defines what variables will be available when the shell is run.
:param str banner: Banner text that appears on startup.
:param str prompt: Custom input prompt.
:param str output: Custom output prompt.
:param context_format: Formatter for the context dictionary in the banner.
Either 'full', 'short', 'hide', or a function that receives the context
dictionary and outputs a string.
"""
banner_template: str = BANNER_TEMPLATE
def __init__(
self,
context: Context,
banner: typing.Optional[str] = None,
prompt: typing.Optional[str] = None,
output: typing.Optional[str] = None,
context_format: ContextFormat = "full",
**kwargs: typing.Any,
) -> None:
self.context = context() if callable(context) else context
self.context_format = context_format
self.banner = make_banner(
banner,
self.context,
context_format=self.context_format,
banner_template=self.banner_template,
)
self.prompt = prompt
self.output = output
def check_availability(self) -> bool:
raise NotImplementedError
def start(self) -> None:
raise NotImplementedError
class PythonShell(Shell):
"""The built-in Python shell."""
def check_availability(self) -> bool:
return True
def start(self) -> None:
try:
import readline
except ImportError:
pass
else:
# We don't have to wrap the following import in a 'try', because
# we already know 'readline' was imported successfully.
import rlcompleter
readline.set_completer(rlcompleter.Completer(self.context).complete)
readline.parse_and_bind("tab:complete")
if self.prompt:
sys.ps1 = self.prompt
if self.output:
warnings.warn("Custom output templates not supported by PythonShell.")
code.interact(self.banner, local=self.context)
return None
def configure_ipython_prompt(
config, prompt: typing.Optional[str] = None, output: typing.Optional[str] = None
) -> None:
import IPython
if IPython.version_info[0] >= 5: # Custom prompt API changed in IPython 5.0
from pygments.token import Token
# https://ipython.readthedocs.io/en/stable/config/details.html#custom-prompts # noqa: B950
class CustomPrompt(IPython.terminal.prompts.Prompts):
def in_prompt_tokens(self, *args, **kwargs):
if prompt is None:
return super().in_prompt_tokens(*args, **kwargs)
if isinstance(prompt, (str, bytes)):
return [(Token.Prompt, prompt)]
else:
return prompt
def out_prompt_tokens(self, *args, **kwargs):
if output is None:
return super().out_prompt_tokens(*args, **kwargs)
if isinstance(output, (str, bytes)):
return [(Token.OutPrompt, output)]
else:
return prompt
config.TerminalInteractiveShell.prompts_class = CustomPrompt
else:
prompt_config = config.PromptManager
if prompt:
prompt_config.in_template = prompt
if output:
prompt_config.out_template = output
return None
class IPythonShell(Shell):
"""The IPython shell.
:param list ipy_extensions: List of IPython extension names to load upon startup.
:param bool ipy_autoreload: Whether to load and initialize the IPython autoreload
extension upon startup. Can also be an integer, which will be passed as
the argument to the %autoreload line magic.
:param kwargs: The same kwargs as `Shell.__init__`.
"""
def __init__(
self,
ipy_extensions: typing.Optional[typing.List[str]] = None,
ipy_autoreload: bool = False,
ipy_colors: typing.Optional[str] = None,
ipy_highlighting_style: typing.Optional[str] = None,
*args: typing.Any,
**kwargs: typing.Any,
):
self.ipy_extensions = ipy_extensions
self.ipy_autoreload = ipy_autoreload
self.ipy_colors = ipy_colors
self.ipy_highlighting_style = ipy_highlighting_style
Shell.__init__(self, *args, **kwargs)
@staticmethod
def init_autoreload(mode: int) -> None:
"""Load and initialize the IPython autoreload extension."""
from IPython.extensions import autoreload
ip = get_ipython() # type: ignore # noqa: F821
autoreload.load_ipython_extension(ip)
ip.magics_manager.magics["line"]["autoreload"](str(mode))
def check_availability(self) -> bool:
try:
import IPython # noqa: F401
except ImportError:
raise ShellNotAvailableError("IPython shell not available.")
return True
def start(self) -> None:
try:
from IPython import start_ipython
from IPython.utils import io
from traitlets.config.loader import Config as IPyConfig
except ImportError:
raise ShellNotAvailableError(
"IPython shell not available " "or IPython version not supported."
)
# Hack to show custom banner
# TerminalIPythonApp/start_app doesn't allow you to customize the
# banner directly, so we write it to stdout before starting the IPython app
io.stdout.write(self.banner)
# Pass exec_lines in order to start autoreload
if self.ipy_autoreload:
if not isinstance(self.ipy_autoreload, bool):
mode = self.ipy_autoreload
else:
mode = 2
logger.debug(f"Initializing IPython autoreload in mode {mode}")
exec_lines = [
"import konch as __konch",
f"__konch.IPythonShell.init_autoreload({mode})",
]
else:
exec_lines = []
ipy_config = IPyConfig()
if self.ipy_colors:
ipy_config.TerminalInteractiveShell.colors = self.ipy_colors
if self.ipy_highlighting_style:
ipy_config.TerminalInteractiveShell.highlighting_style = (
self.ipy_highlighting_style
)
configure_ipython_prompt(ipy_config, prompt=self.prompt, output=self.output)
# Use start_ipython rather than embed so that IPython is loaded in the "normal"
# way. See https://github.com/django/django/pull/512
start_ipython(
display_banner=False,
user_ns=self.context,
config=ipy_config,
extensions=self.ipy_extensions or [],
exec_lines=exec_lines,
argv=[],
)
return None
class PtPythonShell(Shell):
def __init__(self, ptpy_vi_mode: bool = False, *args, **kwargs):
self.ptpy_vi_mode = ptpy_vi_mode
Shell.__init__(self, *args, **kwargs)
def check_availability(self) -> bool:
try:
import ptpython # noqa: F401
except ImportError:
raise ShellNotAvailableError("PtPython shell not available.")
return True
def start(self) -> None:
try:
from ptpython.repl import embed, run_config
except ImportError:
raise ShellNotAvailableError("PtPython shell not available.")
print(self.banner)
config_dir = Path("~/.ptpython/").expanduser()
# Startup path
startup_paths = []
if "PYTHONSTARTUP" in os.environ:
startup_paths.append(os.environ["PYTHONSTARTUP"])
# Apply config file
def configure(repl):
path = config_dir / "config.py"
if path.exists():
run_config(repl, str(path))
embed(
globals=self.context,
history_filename=config_dir / "history",
vi_mode=self.ptpy_vi_mode,
startup_paths=startup_paths,
configure=configure,
)
return None
class PtIPythonShell(PtPythonShell):
banner_template: str = "{text}\n{context}"
def __init__(
self, ipy_extensions: typing.Optional[typing.List[str]] = None, *args, **kwargs
) -> None:
self.ipy_extensions = ipy_extensions or []
PtPythonShell.__init__(self, *args, **kwargs)
def check_availability(self) -> bool:
try:
import ptpython.ipython # noqa: F401
import IPython # noqa: F401
except ImportError:
raise ShellNotAvailableError("PtIPython shell not available.")
return True
def start(self) -> None:
try:
from ptpython.ipython import embed
from ptpython.repl import run_config
from IPython.terminal.ipapp import load_default_config
except ImportError:
raise ShellNotAvailableError("PtIPython shell not available.")
config_dir = Path("~/.ptpython/").expanduser()
# Apply config file
def configure(repl):
path = config_dir / "config.py"
if path.exists():
run_config(repl, str(path))
# Startup path
startup_paths = []
if "PYTHONSTARTUP" in os.environ:
startup_paths.append(os.environ["PYTHONSTARTUP"])
# exec scripts from startup paths
for path in startup_paths:
if Path(path).exists():
with Path(path).open("rb") as f:
code = compile(f.read(), path, "exec")
exec(code, self.context, self.context)
else:
print(f"File not found: {path}\n\n")
sys.exit(1)
ipy_config = load_default_config()
ipy_config.InteractiveShellEmbed = ipy_config.TerminalInteractiveShell
ipy_config["InteractiveShellApp"]["extensions"] = self.ipy_extensions
configure_ipython_prompt(ipy_config, prompt=self.prompt, output=self.output)
embed(
config=ipy_config,
configure=configure,
history_filename=config_dir / "history",
user_ns=self.context,
header=self.banner,
vi_mode=self.ptpy_vi_mode,
)
return None
class BPythonShell(Shell):
"""The BPython shell."""
def check_availability(self) -> bool:
try:
import bpython # noqa: F401
except ImportError:
raise ShellNotAvailableError("BPython shell not available.")
return True
def start(self) -> None:
try:
from bpython import embed
except ImportError:
raise ShellNotAvailableError("BPython shell not available.")
if self.prompt:
warnings.warn("Custom prompts not supported by BPythonShell.")
if self.output:
warnings.warn("Custom output templates not supported by BPythonShell.")
embed(banner=self.banner, locals_=self.context)
return None
class BPythonCursesShell(Shell):
"""The BPython Curses shell."""
def check_availability(self) -> bool:
try:
import bpython.cli # noqa: F401
except ImportError:
raise ShellNotAvailableError("BPython Curses shell not available.")
return True
def start(self) -> None:
try:
from bpython.cli import main
except ImportError:
raise ShellNotAvailableError("BPython Curses shell not available.")
if self.prompt:
warnings.warn("Custom prompts not supported by BPython Curses shell.")
if self.output:
warnings.warn(
"Custom output templates not supported by BPython Curses shell."
)
main(banner=self.banner, locals_=self.context, args=["-i", "-q"])
return None
class AutoShell(Shell):
"""Shell that runs PtIpython, PtPython, IPython, or BPython if available.
Falls back to built-in Python shell.
"""
# Shell classes in precedence order
SHELLS = [
PtIPythonShell,
PtPythonShell,
IPythonShell,
BPythonShell,
BPythonCursesShell,
PythonShell,
]
def __init__(self, context: Context, banner: str, **kwargs):
Shell.__init__(self, context, **kwargs)
self.kwargs = kwargs
self.banner = banner
def check_availability(self) -> bool:
return True
def start(self) -> None:
shell_args = {
"context": self.context,
"banner": self.banner,
"prompt": self.prompt,
"output": self.output,
"context_format": self.context_format,
}
shell_args.update(self.kwargs)
shell = None
for shell_class in self.SHELLS:
try:
shell = shell_class(**shell_args)
shell.check_availability()
except ShellNotAvailableError:
continue
else:
break
else:
raise ShellNotAvailableError("No available shell to run.")
return shell.start()
CONCHES: typing.List[str] = [
'"My conch told me to come save you guys."\n"Hooray for the magic conches!"',
'"All hail the Magic Conch!"',
'"Hooray for the magic conches!"',
'"Uh, hello there. Magic Conch, I was wondering... '
'should I have the spaghetti or the turkey?"',
'"This copyrighted conch is the cornerstone of our organization."',
'"Praise the Magic Conch!"',
'"the conch exploded into a thousand white fragments and ceased to exist."',
"\"S'right. It's a shell!\"",
'"Ralph felt a kind of affectionate reverence for the conch"',
'"Conch! Conch!"',
'"That\'s why you got the conch out of the water"',
'"the summons of the conch"',
'"Whoever holds the conch gets to speak."',
'"They\'ll come when they hear us--"',
'"We gotta drop the load!"',
'"Dude, we\'re falling right out the sky!!"',
(
'"Oh, Magic Conch Shell, what do we need to do to get '
'out of the Kelp Forest?"\n"Nothing."'
),
'"The shell knows all!"',
'"we must never question the wisdom of the Magic Conch."',
'"The Magic Conch! A club member!"',
'"The shell has spoken!"',
'"This copyrighted conch is the cornerstone of our organization."',
'"All right, Magic Conch... what do we do now?"',
'"Ohhh! The Magic Conch Shell! Ask it something! Ask it something!"',
]
def speak() -> str:
return random.choice(CONCHES)
class Config(dict):
"""A dict-like config object. Behaves like a normal dict except that
the ``context`` will always be converted from a list to a dict.
Defines the default configuration.
"""
def __init__(
self,
context: typing.Optional[Context] = None,
banner: typing.Optional[str] = None,
shell: typing.Type[Shell] = AutoShell,
prompt: typing.Optional[str] = None,
output: typing.Optional[str] = None,
context_format: str = "full",
**kwargs: typing.Any,
) -> None:
ctx = Config.transform_val(context) or {}
super().__init__(
context=ctx,
banner=banner,
shell=shell,
prompt=prompt,
output=output,
context_format=context_format,
**kwargs,
)
def __setitem__(self, key: typing.Any, value: typing.Any) -> None:
if key == "context":
value = Config.transform_val(value)
super().__setitem__(key, value)
@staticmethod
def transform_val(val: typing.Any) -> typing.Any:
if isinstance(val, (list, tuple)):
return context_list2dict(val)
return val
def update(self, d: typing.Mapping) -> None: # type: ignore
for key in d.keys():
# Shallow-merge context
if key == "context":
self["context"].update(Config.transform_val(d["context"]))
else:
self[key] = d[key]
SHELL_MAP: typing.Dict[str, typing.Type[Shell]] = {
"ipy": IPythonShell,
"ipython": IPythonShell,
"bpy": BPythonShell,
"bpython": BPythonShell,
"bpyc": BPythonCursesShell,
"bpython-curses": BPythonCursesShell,
"py": PythonShell,
"python": PythonShell,
"auto": AutoShell,
"ptpy": PtPythonShell,
"ptpython": PtPythonShell,
"ptipy": PtIPythonShell,
"ptipython": PtIPythonShell,
}
# _cfg and _config_registry are singletons that may be mutated in a .konchrc file
_cfg = Config()
_config_registry = {"default": _cfg}
def start(
context: typing.Optional[typing.Mapping] = None,
banner: typing.Optional[str] = None,
shell: typing.Type[Shell] = AutoShell,
prompt: typing.Optional[str] = None,
output: typing.Optional[str] = None,
context_format: str = "full",
**kwargs: typing.Any,
) -> None:
"""Start up the konch shell. Takes the same parameters as Shell.__init__.
"""
logger.debug(f"Using shell: {shell!r}")
if banner is None:
banner = speak()
# Default to global config
context_ = context or _cfg["context"]
banner_ = banner or _cfg["banner"]
if isinstance(shell, type) and issubclass(shell, Shell):
shell_ = shell
else:
shell_ = SHELL_MAP.get(shell or _cfg["shell"], _cfg["shell"])
prompt_ = prompt or _cfg["prompt"]
output_ = output or _cfg["output"]
context_format_ = context_format or _cfg["context_format"]
shell_(
context=context_,
banner=banner_,
prompt=prompt_,
output=output_,
context_format=context_format_,
**kwargs,
).start()
def config(config_dict: typing.Mapping) -> Config:
"""Configures the konch shell. This function should be called in a
.konchrc file.
:param dict config_dict: Dict that may contain 'context', 'banner', and/or
'shell' (default shell class to use).
"""
logger.debug(f"Updating with {config_dict}")
_cfg.update(config_dict)
return _cfg
def named_config(name: str, config_dict: typing.Mapping) -> None:
"""Adds a named config to the config registry. The first argument
may either be a string or a collection of strings.
This function should be called in a .konchrc file.
"""
names = (
name
if isinstance(name, Iterable) and not isinstance(name, (str, bytes))
else [name]
)
for each in names:
_config_registry[each] = Config(**config_dict)
def reset_config() -> Config:
global _cfg
_cfg = Config()
return _cfg
def __ensure_directory_in_path(filename: Path) -> None:
"""Ensures that a file's directory is in the Python path.
"""
directory = Path(filename).parent.resolve()
if directory not in sys.path:
logger.debug(f"Adding {directory} to sys.path")
sys.path.insert(0, str(directory))
CONFIG_FILE = Path(".konchrc")
DEFAULT_CONFIG_FILE = Path.home() / ".konchrc.default"
SEPARATOR = f"\n{'*' * 46}\n"
def use_file(
filename: typing.Union[Path, str, None], trust: bool = False
) -> typing.Union[types.ModuleType, None]:
"""Load filename as a python file. Import ``filename`` and return it
as a module.
"""
config_file = filename or resolve_path(CONFIG_FILE)
def preview_unauthorized() -> None:
if not config_file:
return None
print(SEPARATOR, file=sys.stderr)
with Path(config_file).open("r", encoding="utf-8") as fp:
for line in fp:
print(line, end="", file=sys.stderr)
print(SEPARATOR, file=sys.stderr)
if config_file and not Path(config_file).exists():
print_error(f'"{filename}" not found.')
sys.exit(1)
if config_file and Path(config_file).exists():
if not trust:
with AuthFile.load() as authfile:
try:
authfile.check(Path(config_file))
except KonchrcChangedError:
print_error(f'"{config_file}" has changed since you last used it.')
preview_unauthorized()
if confirm("Would you like to authorize it?"):
authfile.allow(Path(config_file))
print()
else:
sys.exit(1)
except KonchrcNotAuthorizedError:
print_error(f'"{config_file}" is blocked.')
preview_unauthorized()
if confirm("Would you like to authorize it?"):
authfile.allow(Path(config_file))
print()
else:
sys.exit(1)
logger.info(f"Using {config_file}")
# Ensure that relative imports are possible
__ensure_directory_in_path(Path(config_file))
mod = None
try:
mod = imp.load_source("konchrc", str(config_file))
except UnboundLocalError: # File not found
pass
else:
return mod
if not config_file:
print_warning("No konch config file found.")
else:
print_warning(f'"{config_file}" not found.')
return None
def resolve_path(filename: Path) -> typing.Union[Path, None]:
"""Find a file by walking up parent directories until the file is found.
Return the absolute path of the file.
"""
current = Path.cwd()
# Stop search at home directory
sentinel_dir = Path.home().parent.resolve()
while current != sentinel_dir:
target = Path(current) / Path(filename)
if target.exists():
return target.resolve()
else:
current = current.parent.resolve()
return None
def get_editor() -> str:
for key in "KONCH_EDITOR", "VISUAL", "EDITOR":
ret = os.environ.get(key)
if ret:
return ret
if sys.platform.startswith("win"):
return "notepad"
for editor in "vim", "nano":
if os.system("which %s &> /dev/null" % editor) == 0:
return editor
return "vi"
def edit_file(
filename: typing.Optional[Path], editor: typing.Optional[str] = None
) -> None:
if not filename:
print_error("filename not passed.")
sys.exit(1)
editor = editor or get_editor()
try:
result = subprocess.Popen(f'{editor} "{filename}"', shell=True)
exit_code = result.wait()
if exit_code != 0:
print_error(f"{editor}: Editing failed!")
sys.exit(1)
except OSError as err:
print_error(f"{editor}: Editing failed: {err}")
sys.exit(1)
else:
with AuthFile.load() as authfile:
authfile.allow(filename)
INIT_TEMPLATE = """# vi: set ft=python :
import konch
import sys
import os
# Available options:
# "context", "banner", "shell", "prompt", "output",
# "context_format", "ipy_extensions", "ipy_autoreload",
# "ipy_colors", "ipy_highlighting_style", "ptpy_vi_mode"
# See: https://konch.readthedocs.io/en/latest/#configuration
konch.config({
"context": [
sys,
os,
]
})
def setup():
pass
def teardown():
pass
"""
def init_config(config_file: Path) -> typing.NoReturn:
if not config_file.exists():
print(f'Writing to "{config_file.resolve()}"...')
print(SEPARATOR)
print(INIT_TEMPLATE, end="")
print(SEPARATOR)
init_template = INIT_TEMPLATE
if DEFAULT_CONFIG_FILE.exists(): # use ~/.konchrc.default if it exists
with Path(DEFAULT_CONFIG_FILE).open("r") as fp:
init_template = fp.read()
with Path(config_file).open("w") as fp:
fp.write(init_template)
with AuthFile.load() as authfile:
authfile.allow(config_file)
relpath = _relpath(config_file)
is_default = relpath == Path(CONFIG_FILE)
edit_cmd = "konch edit" if is_default else f"konch edit {relpath}"
run_cmd = "konch" if is_default else f"konch -f {relpath}"
print(f"{style('Done!', GREEN)} ✨ 🐚 ✨")
print(f"To edit your config: `{style(edit_cmd, bold=True)}`")
print(f"To start the shell: `{style(run_cmd, bold=True)}`")
sys.exit(0)
else:
print_error(f'"{config_file}" already exists in this directory.')
sys.exit(1)
def edit_config(
config_file: typing.Optional[Path] = None, editor: typing.Optional[str] = None
) -> typing.NoReturn:
filename = config_file or resolve_path(CONFIG_FILE)
if not filename:
print_error('No ".konchrc" file found.')
styled_cmd = style("konch init", bold=True, file=sys.stderr)
print(f"Run `{styled_cmd}` to create it.", file=sys.stderr)
sys.exit(1)
if not filename.exists():
print_error(f'"{filename}" does not exist.')
relpath = _relpath(filename)
is_default = relpath == Path(CONFIG_FILE)
cmd = "konch init" if is_default else f"konch init {filename}"
styled_cmd = style(cmd, bold=True, file=sys.stderr)
print(f"Run `{styled_cmd}` to create it.", file=sys.stderr)
sys.exit(1)
print(f'Editing file: "{filename}"')
edit_file(filename, editor=editor)
sys.exit(0)
def allow_config(config_file: typing.Optional[Path] = None) -> typing.NoReturn:
filename: typing.Union[Path, None]
if config_file and config_file.is_dir():
filename = Path(config_file) / CONFIG_FILE
else:
filename = config_file or resolve_path(CONFIG_FILE)
if not filename:
print_error("No config file found.")
sys.exit(1)
with AuthFile.load() as authfile:
if authfile.check(filename, raise_error=False):
print_warning(f'"{filename}" is already authorized.')
else:
try:
print(f'Authorizing "{filename}"...')
authfile.allow(filename)
except FileNotFoundError:
print_error(f'"{filename}" does not exist.')
sys.exit(1)
print(f"{style('Done!', GREEN)} ✨ 🐚 ✨")
relpath = _relpath(filename)
cmd = "konch" if relpath == Path(CONFIG_FILE) else f"konch -f {relpath}"
print(f"You can now start a shell with `{style(cmd, bold=True)}`.")
sys.exit(0)
def deny_config(config_file: typing.Optional[Path] = None) -> typing.NoReturn:
filename: typing.Union[Path, None]
if config_file and config_file.is_dir():
filename = Path(config_file) / CONFIG_FILE
else:
filename = config_file or resolve_path(CONFIG_FILE)
if not filename:
print_error("No config file found.")
sys.exit(1)
print(f'Removing authorization for "{filename}"...')
with AuthFile.load() as authfile:
try:
authfile.deny(filename)
except FileNotFoundError:
print_error(f'"{filename}" does not exist.')
sys.exit(1)
else:
print(style("Done!", GREEN))
sys.exit(0)
def parse_args(argv: typing.Optional[typing.Sequence] = None) -> typing.Dict[str, str]:
"""Exposes the docopt command-line arguments parser.
Return a dictionary of arguments.
"""
return docopt(__doc__, argv=argv, version=__version__)
def main(argv: typing.Optional[typing.Sequence] = None) -> typing.NoReturn:
"""Main entry point for the konch CLI."""
args = parse_args(argv)
if args["--debug"]:
logging.basicConfig(
format="%(levelname)s %(filename)s: %(message)s", level=logging.DEBUG
)
logger.debug(args)
config_file: typing.Union[Path, None]
if args["init"]:
config_file = Path(args["<config_file>"] or CONFIG_FILE)
init_config(config_file)
else:
config_file = Path(args["<config_file>"]) if args["<config_file>"] else None
if args["edit"]:
edit_config(config_file)
elif args["allow"]:
allow_config(config_file)
elif args["deny"]:
deny_config(config_file)
mod = use_file(Path(args["--file"]) if args["--file"] else None)
if hasattr(mod, "setup"):
mod.setup() # type: ignore
if args["--name"]:
if args["--name"] not in _config_registry:
print_error(f'Invalid --name: "{args["--name"]}"')
sys.exit(1)
config_dict = _config_registry[args["--name"]]
logger.debug(f'Using named config: "{args["--name"]}"')
logger.debug(config_dict)
else:
config_dict = _cfg
# Allow default shell to be overriden by command-line argument
shell_name = args["--shell"]
if shell_name:
config_dict["shell"] = SHELL_MAP.get(shell_name.lower(), AutoShell)
logger.debug(f"Starting with config {config_dict}")
start(**config_dict)
if hasattr(mod, "teardown"):
mod.teardown() # type: ignore
sys.exit(0)
if __name__ == "__main__":
main()
|
sloria/konch | konch.py | use_file | python | def use_file(
filename: typing.Union[Path, str, None], trust: bool = False
) -> typing.Union[types.ModuleType, None]:
config_file = filename or resolve_path(CONFIG_FILE)
def preview_unauthorized() -> None:
if not config_file:
return None
print(SEPARATOR, file=sys.stderr)
with Path(config_file).open("r", encoding="utf-8") as fp:
for line in fp:
print(line, end="", file=sys.stderr)
print(SEPARATOR, file=sys.stderr)
if config_file and not Path(config_file).exists():
print_error(f'"{filename}" not found.')
sys.exit(1)
if config_file and Path(config_file).exists():
if not trust:
with AuthFile.load() as authfile:
try:
authfile.check(Path(config_file))
except KonchrcChangedError:
print_error(f'"{config_file}" has changed since you last used it.')
preview_unauthorized()
if confirm("Would you like to authorize it?"):
authfile.allow(Path(config_file))
print()
else:
sys.exit(1)
except KonchrcNotAuthorizedError:
print_error(f'"{config_file}" is blocked.')
preview_unauthorized()
if confirm("Would you like to authorize it?"):
authfile.allow(Path(config_file))
print()
else:
sys.exit(1)
logger.info(f"Using {config_file}")
# Ensure that relative imports are possible
__ensure_directory_in_path(Path(config_file))
mod = None
try:
mod = imp.load_source("konchrc", str(config_file))
except UnboundLocalError: # File not found
pass
else:
return mod
if not config_file:
print_warning("No konch config file found.")
else:
print_warning(f'"{config_file}" not found.')
return None | Load filename as a python file. Import ``filename`` and return it
as a module. | train | https://github.com/sloria/konch/blob/15160bd0a0cac967eeeab84794bd6cdd0b5b637d/konch.py#L898-L954 | [
"def resolve_path(filename: Path) -> typing.Union[Path, None]:\n \"\"\"Find a file by walking up parent directories until the file is found.\n Return the absolute path of the file.\n \"\"\"\n current = Path.cwd()\n # Stop search at home directory\n sentinel_dir = Path.home().parent.resolve()\n while current != sentinel_dir:\n target = Path(current) / Path(filename)\n if target.exists():\n return target.resolve()\n else:\n current = current.parent.resolve()\n\n return None\n"
] | #!/usr/bin/env python3
"""konch: Customizes your Python shell.
Usage:
konch
konch init [<config_file>] [-d]
konch edit [<config_file>] [-d]
konch allow [<config_file>] [-d]
konch deny [<config_file>] [-d]
konch [--name=<name>] [--file=<file>] [--shell=<shell_name>] [-d]
Options:
-h --help Show this screen.
-v --version Show version.
init Creates a starter .konchrc file.
edit Edit your .konchrc file.
-n --name=<name> Named config to use.
-s --shell=<shell_name> Shell to use. Can be either "ipy" (IPython),
"bpy" (BPython), "bpyc" (BPython Curses),
"ptpy" (PtPython), "ptipy" (PtIPython),
"py" (built-in Python shell), or "auto".
Overrides the 'shell' option in .konchrc.
-f --file=<file> File path of konch config file to execute. If not provided,
konch will use the .konchrc file in the current
directory.
-d --debug Enable debugging/verbose mode.
Environment variables:
KONCH_AUTH_FILE: File where to store authorization data for config files.
Defaults to ~/.local/share/konch_auth.
KONCH_EDITOR: Editor command to use when running `konch edit`.
Falls back to $VISUAL then $EDITOR.
NO_COLOR: Disable ANSI colors.
"""
from collections.abc import Iterable
from pathlib import Path
import code
import hashlib
import imp
import json
import logging
import os
import random
import subprocess
import sys
import typing
import types
import warnings
from docopt import docopt
__version__ = "4.2.1"
logger = logging.getLogger(__name__)
class KonchError(Exception):
pass
class ShellNotAvailableError(KonchError):
pass
class KonchrcNotAuthorizedError(KonchError):
pass
class KonchrcChangedError(KonchrcNotAuthorizedError):
pass
class AuthFile:
def __init__(self, data: typing.Dict[str, str]) -> None:
self.data = data
def __repr__(self) -> str:
return f"AuthFile({self.data!r})"
@classmethod
def load(cls, path: typing.Optional[Path] = None) -> "AuthFile":
filepath = path or cls.get_path()
try:
with Path(filepath).open("r", encoding="utf-8") as fp:
data = json.load(fp)
except FileNotFoundError:
data = {}
except json.JSONDecodeError as error:
# File exists but is empty
if error.doc.strip() == "":
data = {}
else:
raise
return cls(data)
def allow(self, filepath: Path) -> None:
logger.debug(f"Authorizing {filepath}")
self.data[str(Path(filepath).resolve())] = self._hash_file(filepath)
def deny(self, filepath: Path) -> None:
if not filepath.exists():
raise FileNotFoundError(f"{filepath} not found")
try:
logger.debug(f"Removing authorization for {filepath}")
del self.data[str(filepath.resolve())]
except KeyError:
pass
def check(
self, filepath: typing.Union[Path, None], raise_error: bool = True
) -> bool:
if not filepath:
return False
if str(filepath.resolve()) not in self.data:
if raise_error:
raise KonchrcNotAuthorizedError
else:
return False
else:
file_hash = self._hash_file(filepath)
if file_hash != self.data[str(filepath.resolve())]:
if raise_error:
raise KonchrcChangedError
else:
return False
return True
def save(self) -> None:
filepath = self.get_path()
filepath.parent.mkdir(parents=True, exist_ok=True)
with Path(filepath).open("w", encoding="utf-8") as fp:
json.dump(self.data, fp)
def __enter__(self) -> "AuthFile":
return self
def __exit__(
self,
exc_type: typing.Type[Exception],
exc_value: Exception,
exc_traceback: types.TracebackType,
) -> None:
if not exc_type:
self.save()
@staticmethod
def get_path() -> Path:
if "KONCH_AUTH_FILE" in os.environ:
return Path(os.environ["KONCH_AUTH_FILE"])
elif "XDG_DATA_HOME" in os.environ:
return Path(os.environ["XDG_DATA_HOME"]) / "konch_auth"
else:
return Path.home() / ".local" / "share" / "konch_auth"
@staticmethod
def _hash_file(filepath: Path) -> str:
# https://stackoverflow.com/a/22058673/1157536
BUF_SIZE = 65536 # read in 64kb chunks
sha1 = hashlib.sha1()
with Path(filepath).open("rb") as f:
while True:
data = f.read(BUF_SIZE)
if not data:
break
sha1.update(data) # type: ignore
return sha1.hexdigest()
RED = 31
GREEN = 32
YELLOW = 33
BOLD = 1
RESET_ALL = 0
def style(
text: str,
fg: typing.Optional[int] = None,
*,
bold: bool = False,
file: typing.IO = sys.stdout,
) -> str:
use_color = not os.environ.get("NO_COLOR") and file.isatty()
if use_color:
parts = [
fg and f"\033[{fg}m",
bold and f"\033[{BOLD}m",
text,
f"\033[{RESET_ALL}m",
]
return "".join([e for e in parts if e])
else:
return text
def sprint(text: str, *args: typing.Any, **kwargs: typing.Any) -> None:
file = kwargs.pop("file", sys.stdout)
return print(style(text, file=file, *args, **kwargs), file=file)
def print_error(text: str) -> None:
prefix = style("ERROR", RED, file=sys.stderr)
return sprint(f"{prefix}: {text}", file=sys.stderr)
def print_warning(text: str) -> None:
prefix = style("WARNING", YELLOW, file=sys.stderr)
return sprint(f"{prefix}: {text}", file=sys.stderr)
Context = typing.Mapping[str, typing.Any]
Formatter = typing.Callable[[Context], str]
ContextFormat = typing.Union[str, Formatter]
def _full_formatter(context: Context) -> str:
line_format = "{name}: {obj!r}"
context_str = "\n".join(
[
line_format.format(name=name, obj=obj)
for name, obj in sorted(context.items(), key=lambda i: i[0].lower())
]
)
header = style("Context:", bold=True)
return f"\n{header}\n{context_str}"
def _short_formatter(context: Context) -> str:
context_str = ", ".join(sorted(context.keys(), key=str.lower))
header = style("Context:", bold=True)
return f"\n{header}\n{context_str}"
def _hide_formatter(context: Context) -> str:
return ""
CONTEXT_FORMATTERS: typing.Dict[str, Formatter] = {
"full": _full_formatter,
"short": _short_formatter,
"hide": _hide_formatter,
}
def format_context(
context: Context, formatter: typing.Union[str, Formatter] = "full"
) -> str:
"""Output the a context dictionary as a string."""
if not context:
return ""
if callable(formatter):
formatter_func = formatter
else:
if formatter in CONTEXT_FORMATTERS:
formatter_func = CONTEXT_FORMATTERS[formatter]
else:
raise ValueError(f'Invalid context format: "{formatter}"')
return formatter_func(context)
BANNER_TEMPLATE = """{version}
{text}
{context}
"""
def make_banner(
text: typing.Optional[str] = None,
context: typing.Optional[Context] = None,
banner_template: typing.Optional[str] = None,
context_format: ContextFormat = "full",
) -> str:
"""Generates a full banner with version info, the given text, and a
formatted list of context variables.
"""
banner_text = text or speak()
banner_template = banner_template or BANNER_TEMPLATE
ctx = format_context(context or {}, formatter=context_format)
out = banner_template.format(version=sys.version, text=banner_text, context=ctx)
return out
def context_list2dict(context_list: typing.Sequence[typing.Any]) -> Context:
"""Converts a list of objects (functions, classes, or modules) to a
dictionary mapping the object names to the objects.
"""
return {obj.__name__.split(".")[-1]: obj for obj in context_list}
def _relpath(p: Path) -> Path:
return p.resolve().relative_to(Path.cwd())
class Shell:
"""Base shell class.
:param dict context: Dictionary, list, or callable (that returns a `dict` or `list`)
that defines what variables will be available when the shell is run.
:param str banner: Banner text that appears on startup.
:param str prompt: Custom input prompt.
:param str output: Custom output prompt.
:param context_format: Formatter for the context dictionary in the banner.
Either 'full', 'short', 'hide', or a function that receives the context
dictionary and outputs a string.
"""
banner_template: str = BANNER_TEMPLATE
def __init__(
self,
context: Context,
banner: typing.Optional[str] = None,
prompt: typing.Optional[str] = None,
output: typing.Optional[str] = None,
context_format: ContextFormat = "full",
**kwargs: typing.Any,
) -> None:
self.context = context() if callable(context) else context
self.context_format = context_format
self.banner = make_banner(
banner,
self.context,
context_format=self.context_format,
banner_template=self.banner_template,
)
self.prompt = prompt
self.output = output
def check_availability(self) -> bool:
raise NotImplementedError
def start(self) -> None:
raise NotImplementedError
class PythonShell(Shell):
"""The built-in Python shell."""
def check_availability(self) -> bool:
return True
def start(self) -> None:
try:
import readline
except ImportError:
pass
else:
# We don't have to wrap the following import in a 'try', because
# we already know 'readline' was imported successfully.
import rlcompleter
readline.set_completer(rlcompleter.Completer(self.context).complete)
readline.parse_and_bind("tab:complete")
if self.prompt:
sys.ps1 = self.prompt
if self.output:
warnings.warn("Custom output templates not supported by PythonShell.")
code.interact(self.banner, local=self.context)
return None
def configure_ipython_prompt(
config, prompt: typing.Optional[str] = None, output: typing.Optional[str] = None
) -> None:
import IPython
if IPython.version_info[0] >= 5: # Custom prompt API changed in IPython 5.0
from pygments.token import Token
# https://ipython.readthedocs.io/en/stable/config/details.html#custom-prompts # noqa: B950
class CustomPrompt(IPython.terminal.prompts.Prompts):
def in_prompt_tokens(self, *args, **kwargs):
if prompt is None:
return super().in_prompt_tokens(*args, **kwargs)
if isinstance(prompt, (str, bytes)):
return [(Token.Prompt, prompt)]
else:
return prompt
def out_prompt_tokens(self, *args, **kwargs):
if output is None:
return super().out_prompt_tokens(*args, **kwargs)
if isinstance(output, (str, bytes)):
return [(Token.OutPrompt, output)]
else:
return prompt
config.TerminalInteractiveShell.prompts_class = CustomPrompt
else:
prompt_config = config.PromptManager
if prompt:
prompt_config.in_template = prompt
if output:
prompt_config.out_template = output
return None
class IPythonShell(Shell):
"""The IPython shell.
:param list ipy_extensions: List of IPython extension names to load upon startup.
:param bool ipy_autoreload: Whether to load and initialize the IPython autoreload
extension upon startup. Can also be an integer, which will be passed as
the argument to the %autoreload line magic.
:param kwargs: The same kwargs as `Shell.__init__`.
"""
def __init__(
self,
ipy_extensions: typing.Optional[typing.List[str]] = None,
ipy_autoreload: bool = False,
ipy_colors: typing.Optional[str] = None,
ipy_highlighting_style: typing.Optional[str] = None,
*args: typing.Any,
**kwargs: typing.Any,
):
self.ipy_extensions = ipy_extensions
self.ipy_autoreload = ipy_autoreload
self.ipy_colors = ipy_colors
self.ipy_highlighting_style = ipy_highlighting_style
Shell.__init__(self, *args, **kwargs)
@staticmethod
def init_autoreload(mode: int) -> None:
"""Load and initialize the IPython autoreload extension."""
from IPython.extensions import autoreload
ip = get_ipython() # type: ignore # noqa: F821
autoreload.load_ipython_extension(ip)
ip.magics_manager.magics["line"]["autoreload"](str(mode))
def check_availability(self) -> bool:
try:
import IPython # noqa: F401
except ImportError:
raise ShellNotAvailableError("IPython shell not available.")
return True
def start(self) -> None:
try:
from IPython import start_ipython
from IPython.utils import io
from traitlets.config.loader import Config as IPyConfig
except ImportError:
raise ShellNotAvailableError(
"IPython shell not available " "or IPython version not supported."
)
# Hack to show custom banner
# TerminalIPythonApp/start_app doesn't allow you to customize the
# banner directly, so we write it to stdout before starting the IPython app
io.stdout.write(self.banner)
# Pass exec_lines in order to start autoreload
if self.ipy_autoreload:
if not isinstance(self.ipy_autoreload, bool):
mode = self.ipy_autoreload
else:
mode = 2
logger.debug(f"Initializing IPython autoreload in mode {mode}")
exec_lines = [
"import konch as __konch",
f"__konch.IPythonShell.init_autoreload({mode})",
]
else:
exec_lines = []
ipy_config = IPyConfig()
if self.ipy_colors:
ipy_config.TerminalInteractiveShell.colors = self.ipy_colors
if self.ipy_highlighting_style:
ipy_config.TerminalInteractiveShell.highlighting_style = (
self.ipy_highlighting_style
)
configure_ipython_prompt(ipy_config, prompt=self.prompt, output=self.output)
# Use start_ipython rather than embed so that IPython is loaded in the "normal"
# way. See https://github.com/django/django/pull/512
start_ipython(
display_banner=False,
user_ns=self.context,
config=ipy_config,
extensions=self.ipy_extensions or [],
exec_lines=exec_lines,
argv=[],
)
return None
class PtPythonShell(Shell):
def __init__(self, ptpy_vi_mode: bool = False, *args, **kwargs):
self.ptpy_vi_mode = ptpy_vi_mode
Shell.__init__(self, *args, **kwargs)
def check_availability(self) -> bool:
try:
import ptpython # noqa: F401
except ImportError:
raise ShellNotAvailableError("PtPython shell not available.")
return True
def start(self) -> None:
try:
from ptpython.repl import embed, run_config
except ImportError:
raise ShellNotAvailableError("PtPython shell not available.")
print(self.banner)
config_dir = Path("~/.ptpython/").expanduser()
# Startup path
startup_paths = []
if "PYTHONSTARTUP" in os.environ:
startup_paths.append(os.environ["PYTHONSTARTUP"])
# Apply config file
def configure(repl):
path = config_dir / "config.py"
if path.exists():
run_config(repl, str(path))
embed(
globals=self.context,
history_filename=config_dir / "history",
vi_mode=self.ptpy_vi_mode,
startup_paths=startup_paths,
configure=configure,
)
return None
class PtIPythonShell(PtPythonShell):
banner_template: str = "{text}\n{context}"
def __init__(
self, ipy_extensions: typing.Optional[typing.List[str]] = None, *args, **kwargs
) -> None:
self.ipy_extensions = ipy_extensions or []
PtPythonShell.__init__(self, *args, **kwargs)
def check_availability(self) -> bool:
try:
import ptpython.ipython # noqa: F401
import IPython # noqa: F401
except ImportError:
raise ShellNotAvailableError("PtIPython shell not available.")
return True
def start(self) -> None:
try:
from ptpython.ipython import embed
from ptpython.repl import run_config
from IPython.terminal.ipapp import load_default_config
except ImportError:
raise ShellNotAvailableError("PtIPython shell not available.")
config_dir = Path("~/.ptpython/").expanduser()
# Apply config file
def configure(repl):
path = config_dir / "config.py"
if path.exists():
run_config(repl, str(path))
# Startup path
startup_paths = []
if "PYTHONSTARTUP" in os.environ:
startup_paths.append(os.environ["PYTHONSTARTUP"])
# exec scripts from startup paths
for path in startup_paths:
if Path(path).exists():
with Path(path).open("rb") as f:
code = compile(f.read(), path, "exec")
exec(code, self.context, self.context)
else:
print(f"File not found: {path}\n\n")
sys.exit(1)
ipy_config = load_default_config()
ipy_config.InteractiveShellEmbed = ipy_config.TerminalInteractiveShell
ipy_config["InteractiveShellApp"]["extensions"] = self.ipy_extensions
configure_ipython_prompt(ipy_config, prompt=self.prompt, output=self.output)
embed(
config=ipy_config,
configure=configure,
history_filename=config_dir / "history",
user_ns=self.context,
header=self.banner,
vi_mode=self.ptpy_vi_mode,
)
return None
class BPythonShell(Shell):
"""The BPython shell."""
def check_availability(self) -> bool:
try:
import bpython # noqa: F401
except ImportError:
raise ShellNotAvailableError("BPython shell not available.")
return True
def start(self) -> None:
try:
from bpython import embed
except ImportError:
raise ShellNotAvailableError("BPython shell not available.")
if self.prompt:
warnings.warn("Custom prompts not supported by BPythonShell.")
if self.output:
warnings.warn("Custom output templates not supported by BPythonShell.")
embed(banner=self.banner, locals_=self.context)
return None
class BPythonCursesShell(Shell):
"""The BPython Curses shell."""
def check_availability(self) -> bool:
try:
import bpython.cli # noqa: F401
except ImportError:
raise ShellNotAvailableError("BPython Curses shell not available.")
return True
def start(self) -> None:
try:
from bpython.cli import main
except ImportError:
raise ShellNotAvailableError("BPython Curses shell not available.")
if self.prompt:
warnings.warn("Custom prompts not supported by BPython Curses shell.")
if self.output:
warnings.warn(
"Custom output templates not supported by BPython Curses shell."
)
main(banner=self.banner, locals_=self.context, args=["-i", "-q"])
return None
class AutoShell(Shell):
"""Shell that runs PtIpython, PtPython, IPython, or BPython if available.
Falls back to built-in Python shell.
"""
# Shell classes in precedence order
SHELLS = [
PtIPythonShell,
PtPythonShell,
IPythonShell,
BPythonShell,
BPythonCursesShell,
PythonShell,
]
def __init__(self, context: Context, banner: str, **kwargs):
Shell.__init__(self, context, **kwargs)
self.kwargs = kwargs
self.banner = banner
def check_availability(self) -> bool:
return True
def start(self) -> None:
shell_args = {
"context": self.context,
"banner": self.banner,
"prompt": self.prompt,
"output": self.output,
"context_format": self.context_format,
}
shell_args.update(self.kwargs)
shell = None
for shell_class in self.SHELLS:
try:
shell = shell_class(**shell_args)
shell.check_availability()
except ShellNotAvailableError:
continue
else:
break
else:
raise ShellNotAvailableError("No available shell to run.")
return shell.start()
CONCHES: typing.List[str] = [
'"My conch told me to come save you guys."\n"Hooray for the magic conches!"',
'"All hail the Magic Conch!"',
'"Hooray for the magic conches!"',
'"Uh, hello there. Magic Conch, I was wondering... '
'should I have the spaghetti or the turkey?"',
'"This copyrighted conch is the cornerstone of our organization."',
'"Praise the Magic Conch!"',
'"the conch exploded into a thousand white fragments and ceased to exist."',
"\"S'right. It's a shell!\"",
'"Ralph felt a kind of affectionate reverence for the conch"',
'"Conch! Conch!"',
'"That\'s why you got the conch out of the water"',
'"the summons of the conch"',
'"Whoever holds the conch gets to speak."',
'"They\'ll come when they hear us--"',
'"We gotta drop the load!"',
'"Dude, we\'re falling right out the sky!!"',
(
'"Oh, Magic Conch Shell, what do we need to do to get '
'out of the Kelp Forest?"\n"Nothing."'
),
'"The shell knows all!"',
'"we must never question the wisdom of the Magic Conch."',
'"The Magic Conch! A club member!"',
'"The shell has spoken!"',
'"This copyrighted conch is the cornerstone of our organization."',
'"All right, Magic Conch... what do we do now?"',
'"Ohhh! The Magic Conch Shell! Ask it something! Ask it something!"',
]
def speak() -> str:
return random.choice(CONCHES)
class Config(dict):
"""A dict-like config object. Behaves like a normal dict except that
the ``context`` will always be converted from a list to a dict.
Defines the default configuration.
"""
def __init__(
self,
context: typing.Optional[Context] = None,
banner: typing.Optional[str] = None,
shell: typing.Type[Shell] = AutoShell,
prompt: typing.Optional[str] = None,
output: typing.Optional[str] = None,
context_format: str = "full",
**kwargs: typing.Any,
) -> None:
ctx = Config.transform_val(context) or {}
super().__init__(
context=ctx,
banner=banner,
shell=shell,
prompt=prompt,
output=output,
context_format=context_format,
**kwargs,
)
def __setitem__(self, key: typing.Any, value: typing.Any) -> None:
if key == "context":
value = Config.transform_val(value)
super().__setitem__(key, value)
@staticmethod
def transform_val(val: typing.Any) -> typing.Any:
if isinstance(val, (list, tuple)):
return context_list2dict(val)
return val
def update(self, d: typing.Mapping) -> None: # type: ignore
for key in d.keys():
# Shallow-merge context
if key == "context":
self["context"].update(Config.transform_val(d["context"]))
else:
self[key] = d[key]
SHELL_MAP: typing.Dict[str, typing.Type[Shell]] = {
"ipy": IPythonShell,
"ipython": IPythonShell,
"bpy": BPythonShell,
"bpython": BPythonShell,
"bpyc": BPythonCursesShell,
"bpython-curses": BPythonCursesShell,
"py": PythonShell,
"python": PythonShell,
"auto": AutoShell,
"ptpy": PtPythonShell,
"ptpython": PtPythonShell,
"ptipy": PtIPythonShell,
"ptipython": PtIPythonShell,
}
# _cfg and _config_registry are singletons that may be mutated in a .konchrc file
_cfg = Config()
_config_registry = {"default": _cfg}
def start(
context: typing.Optional[typing.Mapping] = None,
banner: typing.Optional[str] = None,
shell: typing.Type[Shell] = AutoShell,
prompt: typing.Optional[str] = None,
output: typing.Optional[str] = None,
context_format: str = "full",
**kwargs: typing.Any,
) -> None:
"""Start up the konch shell. Takes the same parameters as Shell.__init__.
"""
logger.debug(f"Using shell: {shell!r}")
if banner is None:
banner = speak()
# Default to global config
context_ = context or _cfg["context"]
banner_ = banner or _cfg["banner"]
if isinstance(shell, type) and issubclass(shell, Shell):
shell_ = shell
else:
shell_ = SHELL_MAP.get(shell or _cfg["shell"], _cfg["shell"])
prompt_ = prompt or _cfg["prompt"]
output_ = output or _cfg["output"]
context_format_ = context_format or _cfg["context_format"]
shell_(
context=context_,
banner=banner_,
prompt=prompt_,
output=output_,
context_format=context_format_,
**kwargs,
).start()
def config(config_dict: typing.Mapping) -> Config:
"""Configures the konch shell. This function should be called in a
.konchrc file.
:param dict config_dict: Dict that may contain 'context', 'banner', and/or
'shell' (default shell class to use).
"""
logger.debug(f"Updating with {config_dict}")
_cfg.update(config_dict)
return _cfg
def named_config(name: str, config_dict: typing.Mapping) -> None:
"""Adds a named config to the config registry. The first argument
may either be a string or a collection of strings.
This function should be called in a .konchrc file.
"""
names = (
name
if isinstance(name, Iterable) and not isinstance(name, (str, bytes))
else [name]
)
for each in names:
_config_registry[each] = Config(**config_dict)
def reset_config() -> Config:
global _cfg
_cfg = Config()
return _cfg
def __ensure_directory_in_path(filename: Path) -> None:
"""Ensures that a file's directory is in the Python path.
"""
directory = Path(filename).parent.resolve()
if directory not in sys.path:
logger.debug(f"Adding {directory} to sys.path")
sys.path.insert(0, str(directory))
CONFIG_FILE = Path(".konchrc")
DEFAULT_CONFIG_FILE = Path.home() / ".konchrc.default"
SEPARATOR = f"\n{'*' * 46}\n"
def confirm(text: str, default: bool = False) -> bool:
"""Display a confirmation prompt."""
choices = "Y/n" if default else "y/N"
prompt = f"{style(text, bold=True)} [{choices}]: "
while 1:
try:
print(prompt, end="")
value = input("").lower().strip()
except (KeyboardInterrupt, EOFError):
sys.exit(1)
if value in ("y", "yes"):
rv = True
elif value in ("n", "no"):
rv = False
elif value == "":
rv = default
else:
print_error("Error: invalid input")
continue
break
return rv
def resolve_path(filename: Path) -> typing.Union[Path, None]:
"""Find a file by walking up parent directories until the file is found.
Return the absolute path of the file.
"""
current = Path.cwd()
# Stop search at home directory
sentinel_dir = Path.home().parent.resolve()
while current != sentinel_dir:
target = Path(current) / Path(filename)
if target.exists():
return target.resolve()
else:
current = current.parent.resolve()
return None
def get_editor() -> str:
for key in "KONCH_EDITOR", "VISUAL", "EDITOR":
ret = os.environ.get(key)
if ret:
return ret
if sys.platform.startswith("win"):
return "notepad"
for editor in "vim", "nano":
if os.system("which %s &> /dev/null" % editor) == 0:
return editor
return "vi"
def edit_file(
filename: typing.Optional[Path], editor: typing.Optional[str] = None
) -> None:
if not filename:
print_error("filename not passed.")
sys.exit(1)
editor = editor or get_editor()
try:
result = subprocess.Popen(f'{editor} "{filename}"', shell=True)
exit_code = result.wait()
if exit_code != 0:
print_error(f"{editor}: Editing failed!")
sys.exit(1)
except OSError as err:
print_error(f"{editor}: Editing failed: {err}")
sys.exit(1)
else:
with AuthFile.load() as authfile:
authfile.allow(filename)
INIT_TEMPLATE = """# vi: set ft=python :
import konch
import sys
import os
# Available options:
# "context", "banner", "shell", "prompt", "output",
# "context_format", "ipy_extensions", "ipy_autoreload",
# "ipy_colors", "ipy_highlighting_style", "ptpy_vi_mode"
# See: https://konch.readthedocs.io/en/latest/#configuration
konch.config({
"context": [
sys,
os,
]
})
def setup():
pass
def teardown():
pass
"""
def init_config(config_file: Path) -> typing.NoReturn:
if not config_file.exists():
print(f'Writing to "{config_file.resolve()}"...')
print(SEPARATOR)
print(INIT_TEMPLATE, end="")
print(SEPARATOR)
init_template = INIT_TEMPLATE
if DEFAULT_CONFIG_FILE.exists(): # use ~/.konchrc.default if it exists
with Path(DEFAULT_CONFIG_FILE).open("r") as fp:
init_template = fp.read()
with Path(config_file).open("w") as fp:
fp.write(init_template)
with AuthFile.load() as authfile:
authfile.allow(config_file)
relpath = _relpath(config_file)
is_default = relpath == Path(CONFIG_FILE)
edit_cmd = "konch edit" if is_default else f"konch edit {relpath}"
run_cmd = "konch" if is_default else f"konch -f {relpath}"
print(f"{style('Done!', GREEN)} ✨ 🐚 ✨")
print(f"To edit your config: `{style(edit_cmd, bold=True)}`")
print(f"To start the shell: `{style(run_cmd, bold=True)}`")
sys.exit(0)
else:
print_error(f'"{config_file}" already exists in this directory.')
sys.exit(1)
def edit_config(
config_file: typing.Optional[Path] = None, editor: typing.Optional[str] = None
) -> typing.NoReturn:
filename = config_file or resolve_path(CONFIG_FILE)
if not filename:
print_error('No ".konchrc" file found.')
styled_cmd = style("konch init", bold=True, file=sys.stderr)
print(f"Run `{styled_cmd}` to create it.", file=sys.stderr)
sys.exit(1)
if not filename.exists():
print_error(f'"{filename}" does not exist.')
relpath = _relpath(filename)
is_default = relpath == Path(CONFIG_FILE)
cmd = "konch init" if is_default else f"konch init {filename}"
styled_cmd = style(cmd, bold=True, file=sys.stderr)
print(f"Run `{styled_cmd}` to create it.", file=sys.stderr)
sys.exit(1)
print(f'Editing file: "{filename}"')
edit_file(filename, editor=editor)
sys.exit(0)
def allow_config(config_file: typing.Optional[Path] = None) -> typing.NoReturn:
filename: typing.Union[Path, None]
if config_file and config_file.is_dir():
filename = Path(config_file) / CONFIG_FILE
else:
filename = config_file or resolve_path(CONFIG_FILE)
if not filename:
print_error("No config file found.")
sys.exit(1)
with AuthFile.load() as authfile:
if authfile.check(filename, raise_error=False):
print_warning(f'"{filename}" is already authorized.')
else:
try:
print(f'Authorizing "{filename}"...')
authfile.allow(filename)
except FileNotFoundError:
print_error(f'"{filename}" does not exist.')
sys.exit(1)
print(f"{style('Done!', GREEN)} ✨ 🐚 ✨")
relpath = _relpath(filename)
cmd = "konch" if relpath == Path(CONFIG_FILE) else f"konch -f {relpath}"
print(f"You can now start a shell with `{style(cmd, bold=True)}`.")
sys.exit(0)
def deny_config(config_file: typing.Optional[Path] = None) -> typing.NoReturn:
filename: typing.Union[Path, None]
if config_file and config_file.is_dir():
filename = Path(config_file) / CONFIG_FILE
else:
filename = config_file or resolve_path(CONFIG_FILE)
if not filename:
print_error("No config file found.")
sys.exit(1)
print(f'Removing authorization for "{filename}"...')
with AuthFile.load() as authfile:
try:
authfile.deny(filename)
except FileNotFoundError:
print_error(f'"{filename}" does not exist.')
sys.exit(1)
else:
print(style("Done!", GREEN))
sys.exit(0)
def parse_args(argv: typing.Optional[typing.Sequence] = None) -> typing.Dict[str, str]:
"""Exposes the docopt command-line arguments parser.
Return a dictionary of arguments.
"""
return docopt(__doc__, argv=argv, version=__version__)
def main(argv: typing.Optional[typing.Sequence] = None) -> typing.NoReturn:
"""Main entry point for the konch CLI."""
args = parse_args(argv)
if args["--debug"]:
logging.basicConfig(
format="%(levelname)s %(filename)s: %(message)s", level=logging.DEBUG
)
logger.debug(args)
config_file: typing.Union[Path, None]
if args["init"]:
config_file = Path(args["<config_file>"] or CONFIG_FILE)
init_config(config_file)
else:
config_file = Path(args["<config_file>"]) if args["<config_file>"] else None
if args["edit"]:
edit_config(config_file)
elif args["allow"]:
allow_config(config_file)
elif args["deny"]:
deny_config(config_file)
mod = use_file(Path(args["--file"]) if args["--file"] else None)
if hasattr(mod, "setup"):
mod.setup() # type: ignore
if args["--name"]:
if args["--name"] not in _config_registry:
print_error(f'Invalid --name: "{args["--name"]}"')
sys.exit(1)
config_dict = _config_registry[args["--name"]]
logger.debug(f'Using named config: "{args["--name"]}"')
logger.debug(config_dict)
else:
config_dict = _cfg
# Allow default shell to be overriden by command-line argument
shell_name = args["--shell"]
if shell_name:
config_dict["shell"] = SHELL_MAP.get(shell_name.lower(), AutoShell)
logger.debug(f"Starting with config {config_dict}")
start(**config_dict)
if hasattr(mod, "teardown"):
mod.teardown() # type: ignore
sys.exit(0)
if __name__ == "__main__":
main()
|
sloria/konch | konch.py | resolve_path | python | def resolve_path(filename: Path) -> typing.Union[Path, None]:
current = Path.cwd()
# Stop search at home directory
sentinel_dir = Path.home().parent.resolve()
while current != sentinel_dir:
target = Path(current) / Path(filename)
if target.exists():
return target.resolve()
else:
current = current.parent.resolve()
return None | Find a file by walking up parent directories until the file is found.
Return the absolute path of the file. | train | https://github.com/sloria/konch/blob/15160bd0a0cac967eeeab84794bd6cdd0b5b637d/konch.py#L957-L971 | null | #!/usr/bin/env python3
"""konch: Customizes your Python shell.
Usage:
konch
konch init [<config_file>] [-d]
konch edit [<config_file>] [-d]
konch allow [<config_file>] [-d]
konch deny [<config_file>] [-d]
konch [--name=<name>] [--file=<file>] [--shell=<shell_name>] [-d]
Options:
-h --help Show this screen.
-v --version Show version.
init Creates a starter .konchrc file.
edit Edit your .konchrc file.
-n --name=<name> Named config to use.
-s --shell=<shell_name> Shell to use. Can be either "ipy" (IPython),
"bpy" (BPython), "bpyc" (BPython Curses),
"ptpy" (PtPython), "ptipy" (PtIPython),
"py" (built-in Python shell), or "auto".
Overrides the 'shell' option in .konchrc.
-f --file=<file> File path of konch config file to execute. If not provided,
konch will use the .konchrc file in the current
directory.
-d --debug Enable debugging/verbose mode.
Environment variables:
KONCH_AUTH_FILE: File where to store authorization data for config files.
Defaults to ~/.local/share/konch_auth.
KONCH_EDITOR: Editor command to use when running `konch edit`.
Falls back to $VISUAL then $EDITOR.
NO_COLOR: Disable ANSI colors.
"""
from collections.abc import Iterable
from pathlib import Path
import code
import hashlib
import imp
import json
import logging
import os
import random
import subprocess
import sys
import typing
import types
import warnings
from docopt import docopt
__version__ = "4.2.1"
logger = logging.getLogger(__name__)
class KonchError(Exception):
pass
class ShellNotAvailableError(KonchError):
pass
class KonchrcNotAuthorizedError(KonchError):
pass
class KonchrcChangedError(KonchrcNotAuthorizedError):
pass
class AuthFile:
def __init__(self, data: typing.Dict[str, str]) -> None:
self.data = data
def __repr__(self) -> str:
return f"AuthFile({self.data!r})"
@classmethod
def load(cls, path: typing.Optional[Path] = None) -> "AuthFile":
filepath = path or cls.get_path()
try:
with Path(filepath).open("r", encoding="utf-8") as fp:
data = json.load(fp)
except FileNotFoundError:
data = {}
except json.JSONDecodeError as error:
# File exists but is empty
if error.doc.strip() == "":
data = {}
else:
raise
return cls(data)
def allow(self, filepath: Path) -> None:
logger.debug(f"Authorizing {filepath}")
self.data[str(Path(filepath).resolve())] = self._hash_file(filepath)
def deny(self, filepath: Path) -> None:
if not filepath.exists():
raise FileNotFoundError(f"{filepath} not found")
try:
logger.debug(f"Removing authorization for {filepath}")
del self.data[str(filepath.resolve())]
except KeyError:
pass
def check(
self, filepath: typing.Union[Path, None], raise_error: bool = True
) -> bool:
if not filepath:
return False
if str(filepath.resolve()) not in self.data:
if raise_error:
raise KonchrcNotAuthorizedError
else:
return False
else:
file_hash = self._hash_file(filepath)
if file_hash != self.data[str(filepath.resolve())]:
if raise_error:
raise KonchrcChangedError
else:
return False
return True
def save(self) -> None:
filepath = self.get_path()
filepath.parent.mkdir(parents=True, exist_ok=True)
with Path(filepath).open("w", encoding="utf-8") as fp:
json.dump(self.data, fp)
def __enter__(self) -> "AuthFile":
return self
def __exit__(
self,
exc_type: typing.Type[Exception],
exc_value: Exception,
exc_traceback: types.TracebackType,
) -> None:
if not exc_type:
self.save()
@staticmethod
def get_path() -> Path:
if "KONCH_AUTH_FILE" in os.environ:
return Path(os.environ["KONCH_AUTH_FILE"])
elif "XDG_DATA_HOME" in os.environ:
return Path(os.environ["XDG_DATA_HOME"]) / "konch_auth"
else:
return Path.home() / ".local" / "share" / "konch_auth"
@staticmethod
def _hash_file(filepath: Path) -> str:
# https://stackoverflow.com/a/22058673/1157536
BUF_SIZE = 65536 # read in 64kb chunks
sha1 = hashlib.sha1()
with Path(filepath).open("rb") as f:
while True:
data = f.read(BUF_SIZE)
if not data:
break
sha1.update(data) # type: ignore
return sha1.hexdigest()
RED = 31
GREEN = 32
YELLOW = 33
BOLD = 1
RESET_ALL = 0
def style(
text: str,
fg: typing.Optional[int] = None,
*,
bold: bool = False,
file: typing.IO = sys.stdout,
) -> str:
use_color = not os.environ.get("NO_COLOR") and file.isatty()
if use_color:
parts = [
fg and f"\033[{fg}m",
bold and f"\033[{BOLD}m",
text,
f"\033[{RESET_ALL}m",
]
return "".join([e for e in parts if e])
else:
return text
def sprint(text: str, *args: typing.Any, **kwargs: typing.Any) -> None:
file = kwargs.pop("file", sys.stdout)
return print(style(text, file=file, *args, **kwargs), file=file)
def print_error(text: str) -> None:
prefix = style("ERROR", RED, file=sys.stderr)
return sprint(f"{prefix}: {text}", file=sys.stderr)
def print_warning(text: str) -> None:
prefix = style("WARNING", YELLOW, file=sys.stderr)
return sprint(f"{prefix}: {text}", file=sys.stderr)
Context = typing.Mapping[str, typing.Any]
Formatter = typing.Callable[[Context], str]
ContextFormat = typing.Union[str, Formatter]
def _full_formatter(context: Context) -> str:
line_format = "{name}: {obj!r}"
context_str = "\n".join(
[
line_format.format(name=name, obj=obj)
for name, obj in sorted(context.items(), key=lambda i: i[0].lower())
]
)
header = style("Context:", bold=True)
return f"\n{header}\n{context_str}"
def _short_formatter(context: Context) -> str:
context_str = ", ".join(sorted(context.keys(), key=str.lower))
header = style("Context:", bold=True)
return f"\n{header}\n{context_str}"
def _hide_formatter(context: Context) -> str:
return ""
CONTEXT_FORMATTERS: typing.Dict[str, Formatter] = {
"full": _full_formatter,
"short": _short_formatter,
"hide": _hide_formatter,
}
def format_context(
context: Context, formatter: typing.Union[str, Formatter] = "full"
) -> str:
"""Output the a context dictionary as a string."""
if not context:
return ""
if callable(formatter):
formatter_func = formatter
else:
if formatter in CONTEXT_FORMATTERS:
formatter_func = CONTEXT_FORMATTERS[formatter]
else:
raise ValueError(f'Invalid context format: "{formatter}"')
return formatter_func(context)
BANNER_TEMPLATE = """{version}
{text}
{context}
"""
def make_banner(
text: typing.Optional[str] = None,
context: typing.Optional[Context] = None,
banner_template: typing.Optional[str] = None,
context_format: ContextFormat = "full",
) -> str:
"""Generates a full banner with version info, the given text, and a
formatted list of context variables.
"""
banner_text = text or speak()
banner_template = banner_template or BANNER_TEMPLATE
ctx = format_context(context or {}, formatter=context_format)
out = banner_template.format(version=sys.version, text=banner_text, context=ctx)
return out
def context_list2dict(context_list: typing.Sequence[typing.Any]) -> Context:
"""Converts a list of objects (functions, classes, or modules) to a
dictionary mapping the object names to the objects.
"""
return {obj.__name__.split(".")[-1]: obj for obj in context_list}
def _relpath(p: Path) -> Path:
return p.resolve().relative_to(Path.cwd())
class Shell:
"""Base shell class.
:param dict context: Dictionary, list, or callable (that returns a `dict` or `list`)
that defines what variables will be available when the shell is run.
:param str banner: Banner text that appears on startup.
:param str prompt: Custom input prompt.
:param str output: Custom output prompt.
:param context_format: Formatter for the context dictionary in the banner.
Either 'full', 'short', 'hide', or a function that receives the context
dictionary and outputs a string.
"""
banner_template: str = BANNER_TEMPLATE
def __init__(
self,
context: Context,
banner: typing.Optional[str] = None,
prompt: typing.Optional[str] = None,
output: typing.Optional[str] = None,
context_format: ContextFormat = "full",
**kwargs: typing.Any,
) -> None:
self.context = context() if callable(context) else context
self.context_format = context_format
self.banner = make_banner(
banner,
self.context,
context_format=self.context_format,
banner_template=self.banner_template,
)
self.prompt = prompt
self.output = output
def check_availability(self) -> bool:
raise NotImplementedError
def start(self) -> None:
raise NotImplementedError
class PythonShell(Shell):
"""The built-in Python shell."""
def check_availability(self) -> bool:
return True
def start(self) -> None:
try:
import readline
except ImportError:
pass
else:
# We don't have to wrap the following import in a 'try', because
# we already know 'readline' was imported successfully.
import rlcompleter
readline.set_completer(rlcompleter.Completer(self.context).complete)
readline.parse_and_bind("tab:complete")
if self.prompt:
sys.ps1 = self.prompt
if self.output:
warnings.warn("Custom output templates not supported by PythonShell.")
code.interact(self.banner, local=self.context)
return None
def configure_ipython_prompt(
config, prompt: typing.Optional[str] = None, output: typing.Optional[str] = None
) -> None:
import IPython
if IPython.version_info[0] >= 5: # Custom prompt API changed in IPython 5.0
from pygments.token import Token
# https://ipython.readthedocs.io/en/stable/config/details.html#custom-prompts # noqa: B950
class CustomPrompt(IPython.terminal.prompts.Prompts):
def in_prompt_tokens(self, *args, **kwargs):
if prompt is None:
return super().in_prompt_tokens(*args, **kwargs)
if isinstance(prompt, (str, bytes)):
return [(Token.Prompt, prompt)]
else:
return prompt
def out_prompt_tokens(self, *args, **kwargs):
if output is None:
return super().out_prompt_tokens(*args, **kwargs)
if isinstance(output, (str, bytes)):
return [(Token.OutPrompt, output)]
else:
return prompt
config.TerminalInteractiveShell.prompts_class = CustomPrompt
else:
prompt_config = config.PromptManager
if prompt:
prompt_config.in_template = prompt
if output:
prompt_config.out_template = output
return None
class IPythonShell(Shell):
"""The IPython shell.
:param list ipy_extensions: List of IPython extension names to load upon startup.
:param bool ipy_autoreload: Whether to load and initialize the IPython autoreload
extension upon startup. Can also be an integer, which will be passed as
the argument to the %autoreload line magic.
:param kwargs: The same kwargs as `Shell.__init__`.
"""
def __init__(
self,
ipy_extensions: typing.Optional[typing.List[str]] = None,
ipy_autoreload: bool = False,
ipy_colors: typing.Optional[str] = None,
ipy_highlighting_style: typing.Optional[str] = None,
*args: typing.Any,
**kwargs: typing.Any,
):
self.ipy_extensions = ipy_extensions
self.ipy_autoreload = ipy_autoreload
self.ipy_colors = ipy_colors
self.ipy_highlighting_style = ipy_highlighting_style
Shell.__init__(self, *args, **kwargs)
@staticmethod
def init_autoreload(mode: int) -> None:
"""Load and initialize the IPython autoreload extension."""
from IPython.extensions import autoreload
ip = get_ipython() # type: ignore # noqa: F821
autoreload.load_ipython_extension(ip)
ip.magics_manager.magics["line"]["autoreload"](str(mode))
def check_availability(self) -> bool:
try:
import IPython # noqa: F401
except ImportError:
raise ShellNotAvailableError("IPython shell not available.")
return True
def start(self) -> None:
try:
from IPython import start_ipython
from IPython.utils import io
from traitlets.config.loader import Config as IPyConfig
except ImportError:
raise ShellNotAvailableError(
"IPython shell not available " "or IPython version not supported."
)
# Hack to show custom banner
# TerminalIPythonApp/start_app doesn't allow you to customize the
# banner directly, so we write it to stdout before starting the IPython app
io.stdout.write(self.banner)
# Pass exec_lines in order to start autoreload
if self.ipy_autoreload:
if not isinstance(self.ipy_autoreload, bool):
mode = self.ipy_autoreload
else:
mode = 2
logger.debug(f"Initializing IPython autoreload in mode {mode}")
exec_lines = [
"import konch as __konch",
f"__konch.IPythonShell.init_autoreload({mode})",
]
else:
exec_lines = []
ipy_config = IPyConfig()
if self.ipy_colors:
ipy_config.TerminalInteractiveShell.colors = self.ipy_colors
if self.ipy_highlighting_style:
ipy_config.TerminalInteractiveShell.highlighting_style = (
self.ipy_highlighting_style
)
configure_ipython_prompt(ipy_config, prompt=self.prompt, output=self.output)
# Use start_ipython rather than embed so that IPython is loaded in the "normal"
# way. See https://github.com/django/django/pull/512
start_ipython(
display_banner=False,
user_ns=self.context,
config=ipy_config,
extensions=self.ipy_extensions or [],
exec_lines=exec_lines,
argv=[],
)
return None
class PtPythonShell(Shell):
def __init__(self, ptpy_vi_mode: bool = False, *args, **kwargs):
self.ptpy_vi_mode = ptpy_vi_mode
Shell.__init__(self, *args, **kwargs)
def check_availability(self) -> bool:
try:
import ptpython # noqa: F401
except ImportError:
raise ShellNotAvailableError("PtPython shell not available.")
return True
def start(self) -> None:
try:
from ptpython.repl import embed, run_config
except ImportError:
raise ShellNotAvailableError("PtPython shell not available.")
print(self.banner)
config_dir = Path("~/.ptpython/").expanduser()
# Startup path
startup_paths = []
if "PYTHONSTARTUP" in os.environ:
startup_paths.append(os.environ["PYTHONSTARTUP"])
# Apply config file
def configure(repl):
path = config_dir / "config.py"
if path.exists():
run_config(repl, str(path))
embed(
globals=self.context,
history_filename=config_dir / "history",
vi_mode=self.ptpy_vi_mode,
startup_paths=startup_paths,
configure=configure,
)
return None
class PtIPythonShell(PtPythonShell):
banner_template: str = "{text}\n{context}"
def __init__(
self, ipy_extensions: typing.Optional[typing.List[str]] = None, *args, **kwargs
) -> None:
self.ipy_extensions = ipy_extensions or []
PtPythonShell.__init__(self, *args, **kwargs)
def check_availability(self) -> bool:
try:
import ptpython.ipython # noqa: F401
import IPython # noqa: F401
except ImportError:
raise ShellNotAvailableError("PtIPython shell not available.")
return True
def start(self) -> None:
try:
from ptpython.ipython import embed
from ptpython.repl import run_config
from IPython.terminal.ipapp import load_default_config
except ImportError:
raise ShellNotAvailableError("PtIPython shell not available.")
config_dir = Path("~/.ptpython/").expanduser()
# Apply config file
def configure(repl):
path = config_dir / "config.py"
if path.exists():
run_config(repl, str(path))
# Startup path
startup_paths = []
if "PYTHONSTARTUP" in os.environ:
startup_paths.append(os.environ["PYTHONSTARTUP"])
# exec scripts from startup paths
for path in startup_paths:
if Path(path).exists():
with Path(path).open("rb") as f:
code = compile(f.read(), path, "exec")
exec(code, self.context, self.context)
else:
print(f"File not found: {path}\n\n")
sys.exit(1)
ipy_config = load_default_config()
ipy_config.InteractiveShellEmbed = ipy_config.TerminalInteractiveShell
ipy_config["InteractiveShellApp"]["extensions"] = self.ipy_extensions
configure_ipython_prompt(ipy_config, prompt=self.prompt, output=self.output)
embed(
config=ipy_config,
configure=configure,
history_filename=config_dir / "history",
user_ns=self.context,
header=self.banner,
vi_mode=self.ptpy_vi_mode,
)
return None
class BPythonShell(Shell):
"""The BPython shell."""
def check_availability(self) -> bool:
try:
import bpython # noqa: F401
except ImportError:
raise ShellNotAvailableError("BPython shell not available.")
return True
def start(self) -> None:
try:
from bpython import embed
except ImportError:
raise ShellNotAvailableError("BPython shell not available.")
if self.prompt:
warnings.warn("Custom prompts not supported by BPythonShell.")
if self.output:
warnings.warn("Custom output templates not supported by BPythonShell.")
embed(banner=self.banner, locals_=self.context)
return None
class BPythonCursesShell(Shell):
"""The BPython Curses shell."""
def check_availability(self) -> bool:
try:
import bpython.cli # noqa: F401
except ImportError:
raise ShellNotAvailableError("BPython Curses shell not available.")
return True
def start(self) -> None:
try:
from bpython.cli import main
except ImportError:
raise ShellNotAvailableError("BPython Curses shell not available.")
if self.prompt:
warnings.warn("Custom prompts not supported by BPython Curses shell.")
if self.output:
warnings.warn(
"Custom output templates not supported by BPython Curses shell."
)
main(banner=self.banner, locals_=self.context, args=["-i", "-q"])
return None
class AutoShell(Shell):
"""Shell that runs PtIpython, PtPython, IPython, or BPython if available.
Falls back to built-in Python shell.
"""
# Shell classes in precedence order
SHELLS = [
PtIPythonShell,
PtPythonShell,
IPythonShell,
BPythonShell,
BPythonCursesShell,
PythonShell,
]
def __init__(self, context: Context, banner: str, **kwargs):
Shell.__init__(self, context, **kwargs)
self.kwargs = kwargs
self.banner = banner
def check_availability(self) -> bool:
return True
def start(self) -> None:
shell_args = {
"context": self.context,
"banner": self.banner,
"prompt": self.prompt,
"output": self.output,
"context_format": self.context_format,
}
shell_args.update(self.kwargs)
shell = None
for shell_class in self.SHELLS:
try:
shell = shell_class(**shell_args)
shell.check_availability()
except ShellNotAvailableError:
continue
else:
break
else:
raise ShellNotAvailableError("No available shell to run.")
return shell.start()
CONCHES: typing.List[str] = [
'"My conch told me to come save you guys."\n"Hooray for the magic conches!"',
'"All hail the Magic Conch!"',
'"Hooray for the magic conches!"',
'"Uh, hello there. Magic Conch, I was wondering... '
'should I have the spaghetti or the turkey?"',
'"This copyrighted conch is the cornerstone of our organization."',
'"Praise the Magic Conch!"',
'"the conch exploded into a thousand white fragments and ceased to exist."',
"\"S'right. It's a shell!\"",
'"Ralph felt a kind of affectionate reverence for the conch"',
'"Conch! Conch!"',
'"That\'s why you got the conch out of the water"',
'"the summons of the conch"',
'"Whoever holds the conch gets to speak."',
'"They\'ll come when they hear us--"',
'"We gotta drop the load!"',
'"Dude, we\'re falling right out the sky!!"',
(
'"Oh, Magic Conch Shell, what do we need to do to get '
'out of the Kelp Forest?"\n"Nothing."'
),
'"The shell knows all!"',
'"we must never question the wisdom of the Magic Conch."',
'"The Magic Conch! A club member!"',
'"The shell has spoken!"',
'"This copyrighted conch is the cornerstone of our organization."',
'"All right, Magic Conch... what do we do now?"',
'"Ohhh! The Magic Conch Shell! Ask it something! Ask it something!"',
]
def speak() -> str:
return random.choice(CONCHES)
class Config(dict):
"""A dict-like config object. Behaves like a normal dict except that
the ``context`` will always be converted from a list to a dict.
Defines the default configuration.
"""
def __init__(
self,
context: typing.Optional[Context] = None,
banner: typing.Optional[str] = None,
shell: typing.Type[Shell] = AutoShell,
prompt: typing.Optional[str] = None,
output: typing.Optional[str] = None,
context_format: str = "full",
**kwargs: typing.Any,
) -> None:
ctx = Config.transform_val(context) or {}
super().__init__(
context=ctx,
banner=banner,
shell=shell,
prompt=prompt,
output=output,
context_format=context_format,
**kwargs,
)
def __setitem__(self, key: typing.Any, value: typing.Any) -> None:
if key == "context":
value = Config.transform_val(value)
super().__setitem__(key, value)
@staticmethod
def transform_val(val: typing.Any) -> typing.Any:
if isinstance(val, (list, tuple)):
return context_list2dict(val)
return val
def update(self, d: typing.Mapping) -> None: # type: ignore
for key in d.keys():
# Shallow-merge context
if key == "context":
self["context"].update(Config.transform_val(d["context"]))
else:
self[key] = d[key]
SHELL_MAP: typing.Dict[str, typing.Type[Shell]] = {
"ipy": IPythonShell,
"ipython": IPythonShell,
"bpy": BPythonShell,
"bpython": BPythonShell,
"bpyc": BPythonCursesShell,
"bpython-curses": BPythonCursesShell,
"py": PythonShell,
"python": PythonShell,
"auto": AutoShell,
"ptpy": PtPythonShell,
"ptpython": PtPythonShell,
"ptipy": PtIPythonShell,
"ptipython": PtIPythonShell,
}
# _cfg and _config_registry are singletons that may be mutated in a .konchrc file
_cfg = Config()
_config_registry = {"default": _cfg}
def start(
context: typing.Optional[typing.Mapping] = None,
banner: typing.Optional[str] = None,
shell: typing.Type[Shell] = AutoShell,
prompt: typing.Optional[str] = None,
output: typing.Optional[str] = None,
context_format: str = "full",
**kwargs: typing.Any,
) -> None:
"""Start up the konch shell. Takes the same parameters as Shell.__init__.
"""
logger.debug(f"Using shell: {shell!r}")
if banner is None:
banner = speak()
# Default to global config
context_ = context or _cfg["context"]
banner_ = banner or _cfg["banner"]
if isinstance(shell, type) and issubclass(shell, Shell):
shell_ = shell
else:
shell_ = SHELL_MAP.get(shell or _cfg["shell"], _cfg["shell"])
prompt_ = prompt or _cfg["prompt"]
output_ = output or _cfg["output"]
context_format_ = context_format or _cfg["context_format"]
shell_(
context=context_,
banner=banner_,
prompt=prompt_,
output=output_,
context_format=context_format_,
**kwargs,
).start()
def config(config_dict: typing.Mapping) -> Config:
"""Configures the konch shell. This function should be called in a
.konchrc file.
:param dict config_dict: Dict that may contain 'context', 'banner', and/or
'shell' (default shell class to use).
"""
logger.debug(f"Updating with {config_dict}")
_cfg.update(config_dict)
return _cfg
def named_config(name: str, config_dict: typing.Mapping) -> None:
"""Adds a named config to the config registry. The first argument
may either be a string or a collection of strings.
This function should be called in a .konchrc file.
"""
names = (
name
if isinstance(name, Iterable) and not isinstance(name, (str, bytes))
else [name]
)
for each in names:
_config_registry[each] = Config(**config_dict)
def reset_config() -> Config:
global _cfg
_cfg = Config()
return _cfg
def __ensure_directory_in_path(filename: Path) -> None:
"""Ensures that a file's directory is in the Python path.
"""
directory = Path(filename).parent.resolve()
if directory not in sys.path:
logger.debug(f"Adding {directory} to sys.path")
sys.path.insert(0, str(directory))
CONFIG_FILE = Path(".konchrc")
DEFAULT_CONFIG_FILE = Path.home() / ".konchrc.default"
SEPARATOR = f"\n{'*' * 46}\n"
def confirm(text: str, default: bool = False) -> bool:
"""Display a confirmation prompt."""
choices = "Y/n" if default else "y/N"
prompt = f"{style(text, bold=True)} [{choices}]: "
while 1:
try:
print(prompt, end="")
value = input("").lower().strip()
except (KeyboardInterrupt, EOFError):
sys.exit(1)
if value in ("y", "yes"):
rv = True
elif value in ("n", "no"):
rv = False
elif value == "":
rv = default
else:
print_error("Error: invalid input")
continue
break
return rv
def use_file(
filename: typing.Union[Path, str, None], trust: bool = False
) -> typing.Union[types.ModuleType, None]:
"""Load filename as a python file. Import ``filename`` and return it
as a module.
"""
config_file = filename or resolve_path(CONFIG_FILE)
def preview_unauthorized() -> None:
if not config_file:
return None
print(SEPARATOR, file=sys.stderr)
with Path(config_file).open("r", encoding="utf-8") as fp:
for line in fp:
print(line, end="", file=sys.stderr)
print(SEPARATOR, file=sys.stderr)
if config_file and not Path(config_file).exists():
print_error(f'"{filename}" not found.')
sys.exit(1)
if config_file and Path(config_file).exists():
if not trust:
with AuthFile.load() as authfile:
try:
authfile.check(Path(config_file))
except KonchrcChangedError:
print_error(f'"{config_file}" has changed since you last used it.')
preview_unauthorized()
if confirm("Would you like to authorize it?"):
authfile.allow(Path(config_file))
print()
else:
sys.exit(1)
except KonchrcNotAuthorizedError:
print_error(f'"{config_file}" is blocked.')
preview_unauthorized()
if confirm("Would you like to authorize it?"):
authfile.allow(Path(config_file))
print()
else:
sys.exit(1)
logger.info(f"Using {config_file}")
# Ensure that relative imports are possible
__ensure_directory_in_path(Path(config_file))
mod = None
try:
mod = imp.load_source("konchrc", str(config_file))
except UnboundLocalError: # File not found
pass
else:
return mod
if not config_file:
print_warning("No konch config file found.")
else:
print_warning(f'"{config_file}" not found.')
return None
def get_editor() -> str:
for key in "KONCH_EDITOR", "VISUAL", "EDITOR":
ret = os.environ.get(key)
if ret:
return ret
if sys.platform.startswith("win"):
return "notepad"
for editor in "vim", "nano":
if os.system("which %s &> /dev/null" % editor) == 0:
return editor
return "vi"
def edit_file(
filename: typing.Optional[Path], editor: typing.Optional[str] = None
) -> None:
if not filename:
print_error("filename not passed.")
sys.exit(1)
editor = editor or get_editor()
try:
result = subprocess.Popen(f'{editor} "{filename}"', shell=True)
exit_code = result.wait()
if exit_code != 0:
print_error(f"{editor}: Editing failed!")
sys.exit(1)
except OSError as err:
print_error(f"{editor}: Editing failed: {err}")
sys.exit(1)
else:
with AuthFile.load() as authfile:
authfile.allow(filename)
INIT_TEMPLATE = """# vi: set ft=python :
import konch
import sys
import os
# Available options:
# "context", "banner", "shell", "prompt", "output",
# "context_format", "ipy_extensions", "ipy_autoreload",
# "ipy_colors", "ipy_highlighting_style", "ptpy_vi_mode"
# See: https://konch.readthedocs.io/en/latest/#configuration
konch.config({
"context": [
sys,
os,
]
})
def setup():
pass
def teardown():
pass
"""
def init_config(config_file: Path) -> typing.NoReturn:
if not config_file.exists():
print(f'Writing to "{config_file.resolve()}"...')
print(SEPARATOR)
print(INIT_TEMPLATE, end="")
print(SEPARATOR)
init_template = INIT_TEMPLATE
if DEFAULT_CONFIG_FILE.exists(): # use ~/.konchrc.default if it exists
with Path(DEFAULT_CONFIG_FILE).open("r") as fp:
init_template = fp.read()
with Path(config_file).open("w") as fp:
fp.write(init_template)
with AuthFile.load() as authfile:
authfile.allow(config_file)
relpath = _relpath(config_file)
is_default = relpath == Path(CONFIG_FILE)
edit_cmd = "konch edit" if is_default else f"konch edit {relpath}"
run_cmd = "konch" if is_default else f"konch -f {relpath}"
print(f"{style('Done!', GREEN)} ✨ 🐚 ✨")
print(f"To edit your config: `{style(edit_cmd, bold=True)}`")
print(f"To start the shell: `{style(run_cmd, bold=True)}`")
sys.exit(0)
else:
print_error(f'"{config_file}" already exists in this directory.')
sys.exit(1)
def edit_config(
config_file: typing.Optional[Path] = None, editor: typing.Optional[str] = None
) -> typing.NoReturn:
filename = config_file or resolve_path(CONFIG_FILE)
if not filename:
print_error('No ".konchrc" file found.')
styled_cmd = style("konch init", bold=True, file=sys.stderr)
print(f"Run `{styled_cmd}` to create it.", file=sys.stderr)
sys.exit(1)
if not filename.exists():
print_error(f'"{filename}" does not exist.')
relpath = _relpath(filename)
is_default = relpath == Path(CONFIG_FILE)
cmd = "konch init" if is_default else f"konch init {filename}"
styled_cmd = style(cmd, bold=True, file=sys.stderr)
print(f"Run `{styled_cmd}` to create it.", file=sys.stderr)
sys.exit(1)
print(f'Editing file: "{filename}"')
edit_file(filename, editor=editor)
sys.exit(0)
def allow_config(config_file: typing.Optional[Path] = None) -> typing.NoReturn:
filename: typing.Union[Path, None]
if config_file and config_file.is_dir():
filename = Path(config_file) / CONFIG_FILE
else:
filename = config_file or resolve_path(CONFIG_FILE)
if not filename:
print_error("No config file found.")
sys.exit(1)
with AuthFile.load() as authfile:
if authfile.check(filename, raise_error=False):
print_warning(f'"{filename}" is already authorized.')
else:
try:
print(f'Authorizing "{filename}"...')
authfile.allow(filename)
except FileNotFoundError:
print_error(f'"{filename}" does not exist.')
sys.exit(1)
print(f"{style('Done!', GREEN)} ✨ 🐚 ✨")
relpath = _relpath(filename)
cmd = "konch" if relpath == Path(CONFIG_FILE) else f"konch -f {relpath}"
print(f"You can now start a shell with `{style(cmd, bold=True)}`.")
sys.exit(0)
def deny_config(config_file: typing.Optional[Path] = None) -> typing.NoReturn:
filename: typing.Union[Path, None]
if config_file and config_file.is_dir():
filename = Path(config_file) / CONFIG_FILE
else:
filename = config_file or resolve_path(CONFIG_FILE)
if not filename:
print_error("No config file found.")
sys.exit(1)
print(f'Removing authorization for "{filename}"...')
with AuthFile.load() as authfile:
try:
authfile.deny(filename)
except FileNotFoundError:
print_error(f'"{filename}" does not exist.')
sys.exit(1)
else:
print(style("Done!", GREEN))
sys.exit(0)
def parse_args(argv: typing.Optional[typing.Sequence] = None) -> typing.Dict[str, str]:
"""Exposes the docopt command-line arguments parser.
Return a dictionary of arguments.
"""
return docopt(__doc__, argv=argv, version=__version__)
def main(argv: typing.Optional[typing.Sequence] = None) -> typing.NoReturn:
"""Main entry point for the konch CLI."""
args = parse_args(argv)
if args["--debug"]:
logging.basicConfig(
format="%(levelname)s %(filename)s: %(message)s", level=logging.DEBUG
)
logger.debug(args)
config_file: typing.Union[Path, None]
if args["init"]:
config_file = Path(args["<config_file>"] or CONFIG_FILE)
init_config(config_file)
else:
config_file = Path(args["<config_file>"]) if args["<config_file>"] else None
if args["edit"]:
edit_config(config_file)
elif args["allow"]:
allow_config(config_file)
elif args["deny"]:
deny_config(config_file)
mod = use_file(Path(args["--file"]) if args["--file"] else None)
if hasattr(mod, "setup"):
mod.setup() # type: ignore
if args["--name"]:
if args["--name"] not in _config_registry:
print_error(f'Invalid --name: "{args["--name"]}"')
sys.exit(1)
config_dict = _config_registry[args["--name"]]
logger.debug(f'Using named config: "{args["--name"]}"')
logger.debug(config_dict)
else:
config_dict = _cfg
# Allow default shell to be overriden by command-line argument
shell_name = args["--shell"]
if shell_name:
config_dict["shell"] = SHELL_MAP.get(shell_name.lower(), AutoShell)
logger.debug(f"Starting with config {config_dict}")
start(**config_dict)
if hasattr(mod, "teardown"):
mod.teardown() # type: ignore
sys.exit(0)
if __name__ == "__main__":
main()
|
sloria/konch | konch.py | parse_args | python | def parse_args(argv: typing.Optional[typing.Sequence] = None) -> typing.Dict[str, str]:
return docopt(__doc__, argv=argv, version=__version__) | Exposes the docopt command-line arguments parser.
Return a dictionary of arguments. | train | https://github.com/sloria/konch/blob/15160bd0a0cac967eeeab84794bd6cdd0b5b637d/konch.py#L1132-L1136 | [
"def docopt(doc, argv=None, help=True, version=None, options_first=False):\n \"\"\"Parse `argv` based on command-line interface described in `doc`.\n\n `docopt` creates your command-line interface based on its\n description that you pass as `doc`. Such description can contain\n --options, <positional-argument>, commands, which could be\n [optional], (required), (mutually | exclusive) or repeated...\n\n Parameters\n ----------\n doc : str\n Description of your command-line interface.\n argv : list of str, optional\n Argument vector to be parsed. sys.argv[1:] is used if not\n provided.\n help : bool (default: True)\n Set to False to disable automatic help on -h or --help\n options.\n version : any object\n If passed, the object will be printed if --version is in\n `argv`.\n options_first : bool (default: False)\n Set to True to require options precede positional arguments,\n i.e. to forbid options and positional arguments intermix.\n\n Returns\n -------\n args : dict\n A dictionary, where keys are names of command-line elements\n such as e.g. \"--verbose\" and \"<path>\", and values are the\n parsed values of those elements.\n\n Example\n -------\n >>> from docopt import docopt\n >>> doc = '''\n ... Usage:\n ... my_program tcp <host> <port> [--timeout=<seconds>]\n ... my_program serial <port> [--baud=<n>] [--timeout=<seconds>]\n ... my_program (-h | --help | --version)\n ...\n ... Options:\n ... -h, --help Show this screen and exit.\n ... --baud=<n> Baudrate [default: 9600]\n ... '''\n >>> argv = ['tcp', '127.0.0.1', '80', '--timeout', '30']\n >>> docopt(doc, argv)\n {'--baud': '9600',\n '--help': False,\n '--timeout': '30',\n '--version': False,\n '<host>': '127.0.0.1',\n '<port>': '80',\n 'serial': False,\n 'tcp': True}\n\n See also\n --------\n * For video introduction see http://docopt.org\n * Full documentation is available in README.rst as well as online\n at https://github.com/docopt/docopt#readme\n\n \"\"\"\n argv = sys.argv[1:] if argv is None else argv\n\n usage_sections = parse_section('usage:', doc)\n if len(usage_sections) == 0:\n raise DocoptLanguageError('\"usage:\" (case-insensitive) not found.')\n if len(usage_sections) > 1:\n raise DocoptLanguageError('More than one \"usage:\" (case-insensitive).')\n DocoptExit.usage = usage_sections[0]\n\n options = parse_defaults(doc)\n pattern = parse_pattern(formal_usage(DocoptExit.usage), options)\n # [default] syntax for argument is disabled\n #for a in pattern.flat(Argument):\n # same_name = [d for d in arguments if d.name == a.name]\n # if same_name:\n # a.value = same_name[0].value\n argv = parse_argv(Tokens(argv), list(options), options_first)\n pattern_options = set(pattern.flat(Option))\n for options_shortcut in pattern.flat(OptionsShortcut):\n doc_options = parse_defaults(doc)\n options_shortcut.children = list(set(doc_options) - pattern_options)\n #if any_options:\n # options_shortcut.children += [Option(o.short, o.long, o.argcount)\n # for o in argv if type(o) is Option]\n extras(help, version, argv, doc)\n matched, left, collected = pattern.fix().match(argv)\n if matched and left == []: # better error message if left?\n return Dict((a.name, a.value) for a in (pattern.flat() + collected))\n raise DocoptExit()\n"
] | #!/usr/bin/env python3
"""konch: Customizes your Python shell.
Usage:
konch
konch init [<config_file>] [-d]
konch edit [<config_file>] [-d]
konch allow [<config_file>] [-d]
konch deny [<config_file>] [-d]
konch [--name=<name>] [--file=<file>] [--shell=<shell_name>] [-d]
Options:
-h --help Show this screen.
-v --version Show version.
init Creates a starter .konchrc file.
edit Edit your .konchrc file.
-n --name=<name> Named config to use.
-s --shell=<shell_name> Shell to use. Can be either "ipy" (IPython),
"bpy" (BPython), "bpyc" (BPython Curses),
"ptpy" (PtPython), "ptipy" (PtIPython),
"py" (built-in Python shell), or "auto".
Overrides the 'shell' option in .konchrc.
-f --file=<file> File path of konch config file to execute. If not provided,
konch will use the .konchrc file in the current
directory.
-d --debug Enable debugging/verbose mode.
Environment variables:
KONCH_AUTH_FILE: File where to store authorization data for config files.
Defaults to ~/.local/share/konch_auth.
KONCH_EDITOR: Editor command to use when running `konch edit`.
Falls back to $VISUAL then $EDITOR.
NO_COLOR: Disable ANSI colors.
"""
from collections.abc import Iterable
from pathlib import Path
import code
import hashlib
import imp
import json
import logging
import os
import random
import subprocess
import sys
import typing
import types
import warnings
from docopt import docopt
__version__ = "4.2.1"
logger = logging.getLogger(__name__)
class KonchError(Exception):
pass
class ShellNotAvailableError(KonchError):
pass
class KonchrcNotAuthorizedError(KonchError):
pass
class KonchrcChangedError(KonchrcNotAuthorizedError):
pass
class AuthFile:
def __init__(self, data: typing.Dict[str, str]) -> None:
self.data = data
def __repr__(self) -> str:
return f"AuthFile({self.data!r})"
@classmethod
def load(cls, path: typing.Optional[Path] = None) -> "AuthFile":
filepath = path or cls.get_path()
try:
with Path(filepath).open("r", encoding="utf-8") as fp:
data = json.load(fp)
except FileNotFoundError:
data = {}
except json.JSONDecodeError as error:
# File exists but is empty
if error.doc.strip() == "":
data = {}
else:
raise
return cls(data)
def allow(self, filepath: Path) -> None:
logger.debug(f"Authorizing {filepath}")
self.data[str(Path(filepath).resolve())] = self._hash_file(filepath)
def deny(self, filepath: Path) -> None:
if not filepath.exists():
raise FileNotFoundError(f"{filepath} not found")
try:
logger.debug(f"Removing authorization for {filepath}")
del self.data[str(filepath.resolve())]
except KeyError:
pass
def check(
self, filepath: typing.Union[Path, None], raise_error: bool = True
) -> bool:
if not filepath:
return False
if str(filepath.resolve()) not in self.data:
if raise_error:
raise KonchrcNotAuthorizedError
else:
return False
else:
file_hash = self._hash_file(filepath)
if file_hash != self.data[str(filepath.resolve())]:
if raise_error:
raise KonchrcChangedError
else:
return False
return True
def save(self) -> None:
filepath = self.get_path()
filepath.parent.mkdir(parents=True, exist_ok=True)
with Path(filepath).open("w", encoding="utf-8") as fp:
json.dump(self.data, fp)
def __enter__(self) -> "AuthFile":
return self
def __exit__(
self,
exc_type: typing.Type[Exception],
exc_value: Exception,
exc_traceback: types.TracebackType,
) -> None:
if not exc_type:
self.save()
@staticmethod
def get_path() -> Path:
if "KONCH_AUTH_FILE" in os.environ:
return Path(os.environ["KONCH_AUTH_FILE"])
elif "XDG_DATA_HOME" in os.environ:
return Path(os.environ["XDG_DATA_HOME"]) / "konch_auth"
else:
return Path.home() / ".local" / "share" / "konch_auth"
@staticmethod
def _hash_file(filepath: Path) -> str:
# https://stackoverflow.com/a/22058673/1157536
BUF_SIZE = 65536 # read in 64kb chunks
sha1 = hashlib.sha1()
with Path(filepath).open("rb") as f:
while True:
data = f.read(BUF_SIZE)
if not data:
break
sha1.update(data) # type: ignore
return sha1.hexdigest()
RED = 31
GREEN = 32
YELLOW = 33
BOLD = 1
RESET_ALL = 0
def style(
text: str,
fg: typing.Optional[int] = None,
*,
bold: bool = False,
file: typing.IO = sys.stdout,
) -> str:
use_color = not os.environ.get("NO_COLOR") and file.isatty()
if use_color:
parts = [
fg and f"\033[{fg}m",
bold and f"\033[{BOLD}m",
text,
f"\033[{RESET_ALL}m",
]
return "".join([e for e in parts if e])
else:
return text
def sprint(text: str, *args: typing.Any, **kwargs: typing.Any) -> None:
file = kwargs.pop("file", sys.stdout)
return print(style(text, file=file, *args, **kwargs), file=file)
def print_error(text: str) -> None:
prefix = style("ERROR", RED, file=sys.stderr)
return sprint(f"{prefix}: {text}", file=sys.stderr)
def print_warning(text: str) -> None:
prefix = style("WARNING", YELLOW, file=sys.stderr)
return sprint(f"{prefix}: {text}", file=sys.stderr)
Context = typing.Mapping[str, typing.Any]
Formatter = typing.Callable[[Context], str]
ContextFormat = typing.Union[str, Formatter]
def _full_formatter(context: Context) -> str:
line_format = "{name}: {obj!r}"
context_str = "\n".join(
[
line_format.format(name=name, obj=obj)
for name, obj in sorted(context.items(), key=lambda i: i[0].lower())
]
)
header = style("Context:", bold=True)
return f"\n{header}\n{context_str}"
def _short_formatter(context: Context) -> str:
context_str = ", ".join(sorted(context.keys(), key=str.lower))
header = style("Context:", bold=True)
return f"\n{header}\n{context_str}"
def _hide_formatter(context: Context) -> str:
return ""
CONTEXT_FORMATTERS: typing.Dict[str, Formatter] = {
"full": _full_formatter,
"short": _short_formatter,
"hide": _hide_formatter,
}
def format_context(
context: Context, formatter: typing.Union[str, Formatter] = "full"
) -> str:
"""Output the a context dictionary as a string."""
if not context:
return ""
if callable(formatter):
formatter_func = formatter
else:
if formatter in CONTEXT_FORMATTERS:
formatter_func = CONTEXT_FORMATTERS[formatter]
else:
raise ValueError(f'Invalid context format: "{formatter}"')
return formatter_func(context)
BANNER_TEMPLATE = """{version}
{text}
{context}
"""
def make_banner(
text: typing.Optional[str] = None,
context: typing.Optional[Context] = None,
banner_template: typing.Optional[str] = None,
context_format: ContextFormat = "full",
) -> str:
"""Generates a full banner with version info, the given text, and a
formatted list of context variables.
"""
banner_text = text or speak()
banner_template = banner_template or BANNER_TEMPLATE
ctx = format_context(context or {}, formatter=context_format)
out = banner_template.format(version=sys.version, text=banner_text, context=ctx)
return out
def context_list2dict(context_list: typing.Sequence[typing.Any]) -> Context:
"""Converts a list of objects (functions, classes, or modules) to a
dictionary mapping the object names to the objects.
"""
return {obj.__name__.split(".")[-1]: obj for obj in context_list}
def _relpath(p: Path) -> Path:
return p.resolve().relative_to(Path.cwd())
class Shell:
"""Base shell class.
:param dict context: Dictionary, list, or callable (that returns a `dict` or `list`)
that defines what variables will be available when the shell is run.
:param str banner: Banner text that appears on startup.
:param str prompt: Custom input prompt.
:param str output: Custom output prompt.
:param context_format: Formatter for the context dictionary in the banner.
Either 'full', 'short', 'hide', or a function that receives the context
dictionary and outputs a string.
"""
banner_template: str = BANNER_TEMPLATE
def __init__(
self,
context: Context,
banner: typing.Optional[str] = None,
prompt: typing.Optional[str] = None,
output: typing.Optional[str] = None,
context_format: ContextFormat = "full",
**kwargs: typing.Any,
) -> None:
self.context = context() if callable(context) else context
self.context_format = context_format
self.banner = make_banner(
banner,
self.context,
context_format=self.context_format,
banner_template=self.banner_template,
)
self.prompt = prompt
self.output = output
def check_availability(self) -> bool:
raise NotImplementedError
def start(self) -> None:
raise NotImplementedError
class PythonShell(Shell):
"""The built-in Python shell."""
def check_availability(self) -> bool:
return True
def start(self) -> None:
try:
import readline
except ImportError:
pass
else:
# We don't have to wrap the following import in a 'try', because
# we already know 'readline' was imported successfully.
import rlcompleter
readline.set_completer(rlcompleter.Completer(self.context).complete)
readline.parse_and_bind("tab:complete")
if self.prompt:
sys.ps1 = self.prompt
if self.output:
warnings.warn("Custom output templates not supported by PythonShell.")
code.interact(self.banner, local=self.context)
return None
def configure_ipython_prompt(
config, prompt: typing.Optional[str] = None, output: typing.Optional[str] = None
) -> None:
import IPython
if IPython.version_info[0] >= 5: # Custom prompt API changed in IPython 5.0
from pygments.token import Token
# https://ipython.readthedocs.io/en/stable/config/details.html#custom-prompts # noqa: B950
class CustomPrompt(IPython.terminal.prompts.Prompts):
def in_prompt_tokens(self, *args, **kwargs):
if prompt is None:
return super().in_prompt_tokens(*args, **kwargs)
if isinstance(prompt, (str, bytes)):
return [(Token.Prompt, prompt)]
else:
return prompt
def out_prompt_tokens(self, *args, **kwargs):
if output is None:
return super().out_prompt_tokens(*args, **kwargs)
if isinstance(output, (str, bytes)):
return [(Token.OutPrompt, output)]
else:
return prompt
config.TerminalInteractiveShell.prompts_class = CustomPrompt
else:
prompt_config = config.PromptManager
if prompt:
prompt_config.in_template = prompt
if output:
prompt_config.out_template = output
return None
class IPythonShell(Shell):
"""The IPython shell.
:param list ipy_extensions: List of IPython extension names to load upon startup.
:param bool ipy_autoreload: Whether to load and initialize the IPython autoreload
extension upon startup. Can also be an integer, which will be passed as
the argument to the %autoreload line magic.
:param kwargs: The same kwargs as `Shell.__init__`.
"""
def __init__(
self,
ipy_extensions: typing.Optional[typing.List[str]] = None,
ipy_autoreload: bool = False,
ipy_colors: typing.Optional[str] = None,
ipy_highlighting_style: typing.Optional[str] = None,
*args: typing.Any,
**kwargs: typing.Any,
):
self.ipy_extensions = ipy_extensions
self.ipy_autoreload = ipy_autoreload
self.ipy_colors = ipy_colors
self.ipy_highlighting_style = ipy_highlighting_style
Shell.__init__(self, *args, **kwargs)
@staticmethod
def init_autoreload(mode: int) -> None:
"""Load and initialize the IPython autoreload extension."""
from IPython.extensions import autoreload
ip = get_ipython() # type: ignore # noqa: F821
autoreload.load_ipython_extension(ip)
ip.magics_manager.magics["line"]["autoreload"](str(mode))
def check_availability(self) -> bool:
try:
import IPython # noqa: F401
except ImportError:
raise ShellNotAvailableError("IPython shell not available.")
return True
def start(self) -> None:
try:
from IPython import start_ipython
from IPython.utils import io
from traitlets.config.loader import Config as IPyConfig
except ImportError:
raise ShellNotAvailableError(
"IPython shell not available " "or IPython version not supported."
)
# Hack to show custom banner
# TerminalIPythonApp/start_app doesn't allow you to customize the
# banner directly, so we write it to stdout before starting the IPython app
io.stdout.write(self.banner)
# Pass exec_lines in order to start autoreload
if self.ipy_autoreload:
if not isinstance(self.ipy_autoreload, bool):
mode = self.ipy_autoreload
else:
mode = 2
logger.debug(f"Initializing IPython autoreload in mode {mode}")
exec_lines = [
"import konch as __konch",
f"__konch.IPythonShell.init_autoreload({mode})",
]
else:
exec_lines = []
ipy_config = IPyConfig()
if self.ipy_colors:
ipy_config.TerminalInteractiveShell.colors = self.ipy_colors
if self.ipy_highlighting_style:
ipy_config.TerminalInteractiveShell.highlighting_style = (
self.ipy_highlighting_style
)
configure_ipython_prompt(ipy_config, prompt=self.prompt, output=self.output)
# Use start_ipython rather than embed so that IPython is loaded in the "normal"
# way. See https://github.com/django/django/pull/512
start_ipython(
display_banner=False,
user_ns=self.context,
config=ipy_config,
extensions=self.ipy_extensions or [],
exec_lines=exec_lines,
argv=[],
)
return None
class PtPythonShell(Shell):
def __init__(self, ptpy_vi_mode: bool = False, *args, **kwargs):
self.ptpy_vi_mode = ptpy_vi_mode
Shell.__init__(self, *args, **kwargs)
def check_availability(self) -> bool:
try:
import ptpython # noqa: F401
except ImportError:
raise ShellNotAvailableError("PtPython shell not available.")
return True
def start(self) -> None:
try:
from ptpython.repl import embed, run_config
except ImportError:
raise ShellNotAvailableError("PtPython shell not available.")
print(self.banner)
config_dir = Path("~/.ptpython/").expanduser()
# Startup path
startup_paths = []
if "PYTHONSTARTUP" in os.environ:
startup_paths.append(os.environ["PYTHONSTARTUP"])
# Apply config file
def configure(repl):
path = config_dir / "config.py"
if path.exists():
run_config(repl, str(path))
embed(
globals=self.context,
history_filename=config_dir / "history",
vi_mode=self.ptpy_vi_mode,
startup_paths=startup_paths,
configure=configure,
)
return None
class PtIPythonShell(PtPythonShell):
banner_template: str = "{text}\n{context}"
def __init__(
self, ipy_extensions: typing.Optional[typing.List[str]] = None, *args, **kwargs
) -> None:
self.ipy_extensions = ipy_extensions or []
PtPythonShell.__init__(self, *args, **kwargs)
def check_availability(self) -> bool:
try:
import ptpython.ipython # noqa: F401
import IPython # noqa: F401
except ImportError:
raise ShellNotAvailableError("PtIPython shell not available.")
return True
def start(self) -> None:
try:
from ptpython.ipython import embed
from ptpython.repl import run_config
from IPython.terminal.ipapp import load_default_config
except ImportError:
raise ShellNotAvailableError("PtIPython shell not available.")
config_dir = Path("~/.ptpython/").expanduser()
# Apply config file
def configure(repl):
path = config_dir / "config.py"
if path.exists():
run_config(repl, str(path))
# Startup path
startup_paths = []
if "PYTHONSTARTUP" in os.environ:
startup_paths.append(os.environ["PYTHONSTARTUP"])
# exec scripts from startup paths
for path in startup_paths:
if Path(path).exists():
with Path(path).open("rb") as f:
code = compile(f.read(), path, "exec")
exec(code, self.context, self.context)
else:
print(f"File not found: {path}\n\n")
sys.exit(1)
ipy_config = load_default_config()
ipy_config.InteractiveShellEmbed = ipy_config.TerminalInteractiveShell
ipy_config["InteractiveShellApp"]["extensions"] = self.ipy_extensions
configure_ipython_prompt(ipy_config, prompt=self.prompt, output=self.output)
embed(
config=ipy_config,
configure=configure,
history_filename=config_dir / "history",
user_ns=self.context,
header=self.banner,
vi_mode=self.ptpy_vi_mode,
)
return None
class BPythonShell(Shell):
"""The BPython shell."""
def check_availability(self) -> bool:
try:
import bpython # noqa: F401
except ImportError:
raise ShellNotAvailableError("BPython shell not available.")
return True
def start(self) -> None:
try:
from bpython import embed
except ImportError:
raise ShellNotAvailableError("BPython shell not available.")
if self.prompt:
warnings.warn("Custom prompts not supported by BPythonShell.")
if self.output:
warnings.warn("Custom output templates not supported by BPythonShell.")
embed(banner=self.banner, locals_=self.context)
return None
class BPythonCursesShell(Shell):
"""The BPython Curses shell."""
def check_availability(self) -> bool:
try:
import bpython.cli # noqa: F401
except ImportError:
raise ShellNotAvailableError("BPython Curses shell not available.")
return True
def start(self) -> None:
try:
from bpython.cli import main
except ImportError:
raise ShellNotAvailableError("BPython Curses shell not available.")
if self.prompt:
warnings.warn("Custom prompts not supported by BPython Curses shell.")
if self.output:
warnings.warn(
"Custom output templates not supported by BPython Curses shell."
)
main(banner=self.banner, locals_=self.context, args=["-i", "-q"])
return None
class AutoShell(Shell):
"""Shell that runs PtIpython, PtPython, IPython, or BPython if available.
Falls back to built-in Python shell.
"""
# Shell classes in precedence order
SHELLS = [
PtIPythonShell,
PtPythonShell,
IPythonShell,
BPythonShell,
BPythonCursesShell,
PythonShell,
]
def __init__(self, context: Context, banner: str, **kwargs):
Shell.__init__(self, context, **kwargs)
self.kwargs = kwargs
self.banner = banner
def check_availability(self) -> bool:
return True
def start(self) -> None:
shell_args = {
"context": self.context,
"banner": self.banner,
"prompt": self.prompt,
"output": self.output,
"context_format": self.context_format,
}
shell_args.update(self.kwargs)
shell = None
for shell_class in self.SHELLS:
try:
shell = shell_class(**shell_args)
shell.check_availability()
except ShellNotAvailableError:
continue
else:
break
else:
raise ShellNotAvailableError("No available shell to run.")
return shell.start()
CONCHES: typing.List[str] = [
'"My conch told me to come save you guys."\n"Hooray for the magic conches!"',
'"All hail the Magic Conch!"',
'"Hooray for the magic conches!"',
'"Uh, hello there. Magic Conch, I was wondering... '
'should I have the spaghetti or the turkey?"',
'"This copyrighted conch is the cornerstone of our organization."',
'"Praise the Magic Conch!"',
'"the conch exploded into a thousand white fragments and ceased to exist."',
"\"S'right. It's a shell!\"",
'"Ralph felt a kind of affectionate reverence for the conch"',
'"Conch! Conch!"',
'"That\'s why you got the conch out of the water"',
'"the summons of the conch"',
'"Whoever holds the conch gets to speak."',
'"They\'ll come when they hear us--"',
'"We gotta drop the load!"',
'"Dude, we\'re falling right out the sky!!"',
(
'"Oh, Magic Conch Shell, what do we need to do to get '
'out of the Kelp Forest?"\n"Nothing."'
),
'"The shell knows all!"',
'"we must never question the wisdom of the Magic Conch."',
'"The Magic Conch! A club member!"',
'"The shell has spoken!"',
'"This copyrighted conch is the cornerstone of our organization."',
'"All right, Magic Conch... what do we do now?"',
'"Ohhh! The Magic Conch Shell! Ask it something! Ask it something!"',
]
def speak() -> str:
return random.choice(CONCHES)
class Config(dict):
"""A dict-like config object. Behaves like a normal dict except that
the ``context`` will always be converted from a list to a dict.
Defines the default configuration.
"""
def __init__(
self,
context: typing.Optional[Context] = None,
banner: typing.Optional[str] = None,
shell: typing.Type[Shell] = AutoShell,
prompt: typing.Optional[str] = None,
output: typing.Optional[str] = None,
context_format: str = "full",
**kwargs: typing.Any,
) -> None:
ctx = Config.transform_val(context) or {}
super().__init__(
context=ctx,
banner=banner,
shell=shell,
prompt=prompt,
output=output,
context_format=context_format,
**kwargs,
)
def __setitem__(self, key: typing.Any, value: typing.Any) -> None:
if key == "context":
value = Config.transform_val(value)
super().__setitem__(key, value)
@staticmethod
def transform_val(val: typing.Any) -> typing.Any:
if isinstance(val, (list, tuple)):
return context_list2dict(val)
return val
def update(self, d: typing.Mapping) -> None: # type: ignore
for key in d.keys():
# Shallow-merge context
if key == "context":
self["context"].update(Config.transform_val(d["context"]))
else:
self[key] = d[key]
SHELL_MAP: typing.Dict[str, typing.Type[Shell]] = {
"ipy": IPythonShell,
"ipython": IPythonShell,
"bpy": BPythonShell,
"bpython": BPythonShell,
"bpyc": BPythonCursesShell,
"bpython-curses": BPythonCursesShell,
"py": PythonShell,
"python": PythonShell,
"auto": AutoShell,
"ptpy": PtPythonShell,
"ptpython": PtPythonShell,
"ptipy": PtIPythonShell,
"ptipython": PtIPythonShell,
}
# _cfg and _config_registry are singletons that may be mutated in a .konchrc file
_cfg = Config()
_config_registry = {"default": _cfg}
def start(
context: typing.Optional[typing.Mapping] = None,
banner: typing.Optional[str] = None,
shell: typing.Type[Shell] = AutoShell,
prompt: typing.Optional[str] = None,
output: typing.Optional[str] = None,
context_format: str = "full",
**kwargs: typing.Any,
) -> None:
"""Start up the konch shell. Takes the same parameters as Shell.__init__.
"""
logger.debug(f"Using shell: {shell!r}")
if banner is None:
banner = speak()
# Default to global config
context_ = context or _cfg["context"]
banner_ = banner or _cfg["banner"]
if isinstance(shell, type) and issubclass(shell, Shell):
shell_ = shell
else:
shell_ = SHELL_MAP.get(shell or _cfg["shell"], _cfg["shell"])
prompt_ = prompt or _cfg["prompt"]
output_ = output or _cfg["output"]
context_format_ = context_format or _cfg["context_format"]
shell_(
context=context_,
banner=banner_,
prompt=prompt_,
output=output_,
context_format=context_format_,
**kwargs,
).start()
def config(config_dict: typing.Mapping) -> Config:
"""Configures the konch shell. This function should be called in a
.konchrc file.
:param dict config_dict: Dict that may contain 'context', 'banner', and/or
'shell' (default shell class to use).
"""
logger.debug(f"Updating with {config_dict}")
_cfg.update(config_dict)
return _cfg
def named_config(name: str, config_dict: typing.Mapping) -> None:
"""Adds a named config to the config registry. The first argument
may either be a string or a collection of strings.
This function should be called in a .konchrc file.
"""
names = (
name
if isinstance(name, Iterable) and not isinstance(name, (str, bytes))
else [name]
)
for each in names:
_config_registry[each] = Config(**config_dict)
def reset_config() -> Config:
global _cfg
_cfg = Config()
return _cfg
def __ensure_directory_in_path(filename: Path) -> None:
"""Ensures that a file's directory is in the Python path.
"""
directory = Path(filename).parent.resolve()
if directory not in sys.path:
logger.debug(f"Adding {directory} to sys.path")
sys.path.insert(0, str(directory))
CONFIG_FILE = Path(".konchrc")
DEFAULT_CONFIG_FILE = Path.home() / ".konchrc.default"
SEPARATOR = f"\n{'*' * 46}\n"
def confirm(text: str, default: bool = False) -> bool:
"""Display a confirmation prompt."""
choices = "Y/n" if default else "y/N"
prompt = f"{style(text, bold=True)} [{choices}]: "
while 1:
try:
print(prompt, end="")
value = input("").lower().strip()
except (KeyboardInterrupt, EOFError):
sys.exit(1)
if value in ("y", "yes"):
rv = True
elif value in ("n", "no"):
rv = False
elif value == "":
rv = default
else:
print_error("Error: invalid input")
continue
break
return rv
def use_file(
filename: typing.Union[Path, str, None], trust: bool = False
) -> typing.Union[types.ModuleType, None]:
"""Load filename as a python file. Import ``filename`` and return it
as a module.
"""
config_file = filename or resolve_path(CONFIG_FILE)
def preview_unauthorized() -> None:
if not config_file:
return None
print(SEPARATOR, file=sys.stderr)
with Path(config_file).open("r", encoding="utf-8") as fp:
for line in fp:
print(line, end="", file=sys.stderr)
print(SEPARATOR, file=sys.stderr)
if config_file and not Path(config_file).exists():
print_error(f'"{filename}" not found.')
sys.exit(1)
if config_file and Path(config_file).exists():
if not trust:
with AuthFile.load() as authfile:
try:
authfile.check(Path(config_file))
except KonchrcChangedError:
print_error(f'"{config_file}" has changed since you last used it.')
preview_unauthorized()
if confirm("Would you like to authorize it?"):
authfile.allow(Path(config_file))
print()
else:
sys.exit(1)
except KonchrcNotAuthorizedError:
print_error(f'"{config_file}" is blocked.')
preview_unauthorized()
if confirm("Would you like to authorize it?"):
authfile.allow(Path(config_file))
print()
else:
sys.exit(1)
logger.info(f"Using {config_file}")
# Ensure that relative imports are possible
__ensure_directory_in_path(Path(config_file))
mod = None
try:
mod = imp.load_source("konchrc", str(config_file))
except UnboundLocalError: # File not found
pass
else:
return mod
if not config_file:
print_warning("No konch config file found.")
else:
print_warning(f'"{config_file}" not found.')
return None
def resolve_path(filename: Path) -> typing.Union[Path, None]:
"""Find a file by walking up parent directories until the file is found.
Return the absolute path of the file.
"""
current = Path.cwd()
# Stop search at home directory
sentinel_dir = Path.home().parent.resolve()
while current != sentinel_dir:
target = Path(current) / Path(filename)
if target.exists():
return target.resolve()
else:
current = current.parent.resolve()
return None
def get_editor() -> str:
for key in "KONCH_EDITOR", "VISUAL", "EDITOR":
ret = os.environ.get(key)
if ret:
return ret
if sys.platform.startswith("win"):
return "notepad"
for editor in "vim", "nano":
if os.system("which %s &> /dev/null" % editor) == 0:
return editor
return "vi"
def edit_file(
filename: typing.Optional[Path], editor: typing.Optional[str] = None
) -> None:
if not filename:
print_error("filename not passed.")
sys.exit(1)
editor = editor or get_editor()
try:
result = subprocess.Popen(f'{editor} "{filename}"', shell=True)
exit_code = result.wait()
if exit_code != 0:
print_error(f"{editor}: Editing failed!")
sys.exit(1)
except OSError as err:
print_error(f"{editor}: Editing failed: {err}")
sys.exit(1)
else:
with AuthFile.load() as authfile:
authfile.allow(filename)
INIT_TEMPLATE = """# vi: set ft=python :
import konch
import sys
import os
# Available options:
# "context", "banner", "shell", "prompt", "output",
# "context_format", "ipy_extensions", "ipy_autoreload",
# "ipy_colors", "ipy_highlighting_style", "ptpy_vi_mode"
# See: https://konch.readthedocs.io/en/latest/#configuration
konch.config({
"context": [
sys,
os,
]
})
def setup():
pass
def teardown():
pass
"""
def init_config(config_file: Path) -> typing.NoReturn:
if not config_file.exists():
print(f'Writing to "{config_file.resolve()}"...')
print(SEPARATOR)
print(INIT_TEMPLATE, end="")
print(SEPARATOR)
init_template = INIT_TEMPLATE
if DEFAULT_CONFIG_FILE.exists(): # use ~/.konchrc.default if it exists
with Path(DEFAULT_CONFIG_FILE).open("r") as fp:
init_template = fp.read()
with Path(config_file).open("w") as fp:
fp.write(init_template)
with AuthFile.load() as authfile:
authfile.allow(config_file)
relpath = _relpath(config_file)
is_default = relpath == Path(CONFIG_FILE)
edit_cmd = "konch edit" if is_default else f"konch edit {relpath}"
run_cmd = "konch" if is_default else f"konch -f {relpath}"
print(f"{style('Done!', GREEN)} ✨ 🐚 ✨")
print(f"To edit your config: `{style(edit_cmd, bold=True)}`")
print(f"To start the shell: `{style(run_cmd, bold=True)}`")
sys.exit(0)
else:
print_error(f'"{config_file}" already exists in this directory.')
sys.exit(1)
def edit_config(
config_file: typing.Optional[Path] = None, editor: typing.Optional[str] = None
) -> typing.NoReturn:
filename = config_file or resolve_path(CONFIG_FILE)
if not filename:
print_error('No ".konchrc" file found.')
styled_cmd = style("konch init", bold=True, file=sys.stderr)
print(f"Run `{styled_cmd}` to create it.", file=sys.stderr)
sys.exit(1)
if not filename.exists():
print_error(f'"{filename}" does not exist.')
relpath = _relpath(filename)
is_default = relpath == Path(CONFIG_FILE)
cmd = "konch init" if is_default else f"konch init {filename}"
styled_cmd = style(cmd, bold=True, file=sys.stderr)
print(f"Run `{styled_cmd}` to create it.", file=sys.stderr)
sys.exit(1)
print(f'Editing file: "{filename}"')
edit_file(filename, editor=editor)
sys.exit(0)
def allow_config(config_file: typing.Optional[Path] = None) -> typing.NoReturn:
filename: typing.Union[Path, None]
if config_file and config_file.is_dir():
filename = Path(config_file) / CONFIG_FILE
else:
filename = config_file or resolve_path(CONFIG_FILE)
if not filename:
print_error("No config file found.")
sys.exit(1)
with AuthFile.load() as authfile:
if authfile.check(filename, raise_error=False):
print_warning(f'"{filename}" is already authorized.')
else:
try:
print(f'Authorizing "{filename}"...')
authfile.allow(filename)
except FileNotFoundError:
print_error(f'"{filename}" does not exist.')
sys.exit(1)
print(f"{style('Done!', GREEN)} ✨ 🐚 ✨")
relpath = _relpath(filename)
cmd = "konch" if relpath == Path(CONFIG_FILE) else f"konch -f {relpath}"
print(f"You can now start a shell with `{style(cmd, bold=True)}`.")
sys.exit(0)
def deny_config(config_file: typing.Optional[Path] = None) -> typing.NoReturn:
filename: typing.Union[Path, None]
if config_file and config_file.is_dir():
filename = Path(config_file) / CONFIG_FILE
else:
filename = config_file or resolve_path(CONFIG_FILE)
if not filename:
print_error("No config file found.")
sys.exit(1)
print(f'Removing authorization for "{filename}"...')
with AuthFile.load() as authfile:
try:
authfile.deny(filename)
except FileNotFoundError:
print_error(f'"{filename}" does not exist.')
sys.exit(1)
else:
print(style("Done!", GREEN))
sys.exit(0)
def main(argv: typing.Optional[typing.Sequence] = None) -> typing.NoReturn:
"""Main entry point for the konch CLI."""
args = parse_args(argv)
if args["--debug"]:
logging.basicConfig(
format="%(levelname)s %(filename)s: %(message)s", level=logging.DEBUG
)
logger.debug(args)
config_file: typing.Union[Path, None]
if args["init"]:
config_file = Path(args["<config_file>"] or CONFIG_FILE)
init_config(config_file)
else:
config_file = Path(args["<config_file>"]) if args["<config_file>"] else None
if args["edit"]:
edit_config(config_file)
elif args["allow"]:
allow_config(config_file)
elif args["deny"]:
deny_config(config_file)
mod = use_file(Path(args["--file"]) if args["--file"] else None)
if hasattr(mod, "setup"):
mod.setup() # type: ignore
if args["--name"]:
if args["--name"] not in _config_registry:
print_error(f'Invalid --name: "{args["--name"]}"')
sys.exit(1)
config_dict = _config_registry[args["--name"]]
logger.debug(f'Using named config: "{args["--name"]}"')
logger.debug(config_dict)
else:
config_dict = _cfg
# Allow default shell to be overriden by command-line argument
shell_name = args["--shell"]
if shell_name:
config_dict["shell"] = SHELL_MAP.get(shell_name.lower(), AutoShell)
logger.debug(f"Starting with config {config_dict}")
start(**config_dict)
if hasattr(mod, "teardown"):
mod.teardown() # type: ignore
sys.exit(0)
if __name__ == "__main__":
main()
|
sloria/konch | konch.py | main | python | def main(argv: typing.Optional[typing.Sequence] = None) -> typing.NoReturn:
args = parse_args(argv)
if args["--debug"]:
logging.basicConfig(
format="%(levelname)s %(filename)s: %(message)s", level=logging.DEBUG
)
logger.debug(args)
config_file: typing.Union[Path, None]
if args["init"]:
config_file = Path(args["<config_file>"] or CONFIG_FILE)
init_config(config_file)
else:
config_file = Path(args["<config_file>"]) if args["<config_file>"] else None
if args["edit"]:
edit_config(config_file)
elif args["allow"]:
allow_config(config_file)
elif args["deny"]:
deny_config(config_file)
mod = use_file(Path(args["--file"]) if args["--file"] else None)
if hasattr(mod, "setup"):
mod.setup() # type: ignore
if args["--name"]:
if args["--name"] not in _config_registry:
print_error(f'Invalid --name: "{args["--name"]}"')
sys.exit(1)
config_dict = _config_registry[args["--name"]]
logger.debug(f'Using named config: "{args["--name"]}"')
logger.debug(config_dict)
else:
config_dict = _cfg
# Allow default shell to be overriden by command-line argument
shell_name = args["--shell"]
if shell_name:
config_dict["shell"] = SHELL_MAP.get(shell_name.lower(), AutoShell)
logger.debug(f"Starting with config {config_dict}")
start(**config_dict)
if hasattr(mod, "teardown"):
mod.teardown() # type: ignore
sys.exit(0) | Main entry point for the konch CLI. | train | https://github.com/sloria/konch/blob/15160bd0a0cac967eeeab84794bd6cdd0b5b637d/konch.py#L1139-L1184 | [
"def start(\n context: typing.Optional[typing.Mapping] = None,\n banner: typing.Optional[str] = None,\n shell: typing.Type[Shell] = AutoShell,\n prompt: typing.Optional[str] = None,\n output: typing.Optional[str] = None,\n context_format: str = \"full\",\n **kwargs: typing.Any,\n) -> None:\n \"\"\"Start up the konch shell. Takes the same parameters as Shell.__init__.\n \"\"\"\n logger.debug(f\"Using shell: {shell!r}\")\n if banner is None:\n banner = speak()\n # Default to global config\n context_ = context or _cfg[\"context\"]\n banner_ = banner or _cfg[\"banner\"]\n if isinstance(shell, type) and issubclass(shell, Shell):\n shell_ = shell\n else:\n shell_ = SHELL_MAP.get(shell or _cfg[\"shell\"], _cfg[\"shell\"])\n prompt_ = prompt or _cfg[\"prompt\"]\n output_ = output or _cfg[\"output\"]\n context_format_ = context_format or _cfg[\"context_format\"]\n shell_(\n context=context_,\n banner=banner_,\n prompt=prompt_,\n output=output_,\n context_format=context_format_,\n **kwargs,\n ).start()\n",
"def parse_args(argv: typing.Optional[typing.Sequence] = None) -> typing.Dict[str, str]:\n \"\"\"Exposes the docopt command-line arguments parser.\n Return a dictionary of arguments.\n \"\"\"\n return docopt(__doc__, argv=argv, version=__version__)\n",
"def print_error(text: str) -> None:\n prefix = style(\"ERROR\", RED, file=sys.stderr)\n return sprint(f\"{prefix}: {text}\", file=sys.stderr)\n",
"def use_file(\n filename: typing.Union[Path, str, None], trust: bool = False\n) -> typing.Union[types.ModuleType, None]:\n \"\"\"Load filename as a python file. Import ``filename`` and return it\n as a module.\n \"\"\"\n config_file = filename or resolve_path(CONFIG_FILE)\n\n def preview_unauthorized() -> None:\n if not config_file:\n return None\n print(SEPARATOR, file=sys.stderr)\n with Path(config_file).open(\"r\", encoding=\"utf-8\") as fp:\n for line in fp:\n print(line, end=\"\", file=sys.stderr)\n print(SEPARATOR, file=sys.stderr)\n\n if config_file and not Path(config_file).exists():\n print_error(f'\"{filename}\" not found.')\n sys.exit(1)\n if config_file and Path(config_file).exists():\n if not trust:\n with AuthFile.load() as authfile:\n try:\n authfile.check(Path(config_file))\n except KonchrcChangedError:\n print_error(f'\"{config_file}\" has changed since you last used it.')\n preview_unauthorized()\n if confirm(\"Would you like to authorize it?\"):\n authfile.allow(Path(config_file))\n print()\n else:\n sys.exit(1)\n except KonchrcNotAuthorizedError:\n print_error(f'\"{config_file}\" is blocked.')\n preview_unauthorized()\n if confirm(\"Would you like to authorize it?\"):\n authfile.allow(Path(config_file))\n print()\n else:\n sys.exit(1)\n\n logger.info(f\"Using {config_file}\")\n # Ensure that relative imports are possible\n __ensure_directory_in_path(Path(config_file))\n mod = None\n try:\n mod = imp.load_source(\"konchrc\", str(config_file))\n except UnboundLocalError: # File not found\n pass\n else:\n return mod\n if not config_file:\n print_warning(\"No konch config file found.\")\n else:\n print_warning(f'\"{config_file}\" not found.')\n return None\n",
"def init_config(config_file: Path) -> typing.NoReturn:\n if not config_file.exists():\n print(f'Writing to \"{config_file.resolve()}\"...')\n print(SEPARATOR)\n print(INIT_TEMPLATE, end=\"\")\n print(SEPARATOR)\n init_template = INIT_TEMPLATE\n if DEFAULT_CONFIG_FILE.exists(): # use ~/.konchrc.default if it exists\n with Path(DEFAULT_CONFIG_FILE).open(\"r\") as fp:\n init_template = fp.read()\n with Path(config_file).open(\"w\") as fp:\n fp.write(init_template)\n with AuthFile.load() as authfile:\n authfile.allow(config_file)\n\n relpath = _relpath(config_file)\n is_default = relpath == Path(CONFIG_FILE)\n edit_cmd = \"konch edit\" if is_default else f\"konch edit {relpath}\"\n run_cmd = \"konch\" if is_default else f\"konch -f {relpath}\"\n print(f\"{style('Done!', GREEN)} ✨ 🐚 ✨\")\n print(f\"To edit your config: `{style(edit_cmd, bold=True)}`\")\n print(f\"To start the shell: `{style(run_cmd, bold=True)}`\")\n sys.exit(0)\n else:\n print_error(f'\"{config_file}\" already exists in this directory.')\n sys.exit(1)\n",
"def edit_config(\n config_file: typing.Optional[Path] = None, editor: typing.Optional[str] = None\n) -> typing.NoReturn:\n filename = config_file or resolve_path(CONFIG_FILE)\n if not filename:\n print_error('No \".konchrc\" file found.')\n styled_cmd = style(\"konch init\", bold=True, file=sys.stderr)\n print(f\"Run `{styled_cmd}` to create it.\", file=sys.stderr)\n sys.exit(1)\n if not filename.exists():\n print_error(f'\"{filename}\" does not exist.')\n relpath = _relpath(filename)\n is_default = relpath == Path(CONFIG_FILE)\n cmd = \"konch init\" if is_default else f\"konch init {filename}\"\n styled_cmd = style(cmd, bold=True, file=sys.stderr)\n print(f\"Run `{styled_cmd}` to create it.\", file=sys.stderr)\n sys.exit(1)\n print(f'Editing file: \"{filename}\"')\n edit_file(filename, editor=editor)\n sys.exit(0)\n",
"def allow_config(config_file: typing.Optional[Path] = None) -> typing.NoReturn:\n filename: typing.Union[Path, None]\n if config_file and config_file.is_dir():\n filename = Path(config_file) / CONFIG_FILE\n else:\n filename = config_file or resolve_path(CONFIG_FILE)\n if not filename:\n print_error(\"No config file found.\")\n sys.exit(1)\n with AuthFile.load() as authfile:\n if authfile.check(filename, raise_error=False):\n print_warning(f'\"{filename}\" is already authorized.')\n else:\n try:\n print(f'Authorizing \"{filename}\"...')\n authfile.allow(filename)\n except FileNotFoundError:\n print_error(f'\"{filename}\" does not exist.')\n sys.exit(1)\n print(f\"{style('Done!', GREEN)} ✨ 🐚 ✨\")\n relpath = _relpath(filename)\n cmd = \"konch\" if relpath == Path(CONFIG_FILE) else f\"konch -f {relpath}\"\n print(f\"You can now start a shell with `{style(cmd, bold=True)}`.\")\n sys.exit(0)\n",
"def deny_config(config_file: typing.Optional[Path] = None) -> typing.NoReturn:\n filename: typing.Union[Path, None]\n if config_file and config_file.is_dir():\n filename = Path(config_file) / CONFIG_FILE\n else:\n filename = config_file or resolve_path(CONFIG_FILE)\n if not filename:\n print_error(\"No config file found.\")\n sys.exit(1)\n print(f'Removing authorization for \"{filename}\"...')\n with AuthFile.load() as authfile:\n try:\n authfile.deny(filename)\n except FileNotFoundError:\n print_error(f'\"{filename}\" does not exist.')\n sys.exit(1)\n else:\n print(style(\"Done!\", GREEN))\n sys.exit(0)\n"
] | #!/usr/bin/env python3
"""konch: Customizes your Python shell.
Usage:
konch
konch init [<config_file>] [-d]
konch edit [<config_file>] [-d]
konch allow [<config_file>] [-d]
konch deny [<config_file>] [-d]
konch [--name=<name>] [--file=<file>] [--shell=<shell_name>] [-d]
Options:
-h --help Show this screen.
-v --version Show version.
init Creates a starter .konchrc file.
edit Edit your .konchrc file.
-n --name=<name> Named config to use.
-s --shell=<shell_name> Shell to use. Can be either "ipy" (IPython),
"bpy" (BPython), "bpyc" (BPython Curses),
"ptpy" (PtPython), "ptipy" (PtIPython),
"py" (built-in Python shell), or "auto".
Overrides the 'shell' option in .konchrc.
-f --file=<file> File path of konch config file to execute. If not provided,
konch will use the .konchrc file in the current
directory.
-d --debug Enable debugging/verbose mode.
Environment variables:
KONCH_AUTH_FILE: File where to store authorization data for config files.
Defaults to ~/.local/share/konch_auth.
KONCH_EDITOR: Editor command to use when running `konch edit`.
Falls back to $VISUAL then $EDITOR.
NO_COLOR: Disable ANSI colors.
"""
from collections.abc import Iterable
from pathlib import Path
import code
import hashlib
import imp
import json
import logging
import os
import random
import subprocess
import sys
import typing
import types
import warnings
from docopt import docopt
__version__ = "4.2.1"
logger = logging.getLogger(__name__)
class KonchError(Exception):
pass
class ShellNotAvailableError(KonchError):
pass
class KonchrcNotAuthorizedError(KonchError):
pass
class KonchrcChangedError(KonchrcNotAuthorizedError):
pass
class AuthFile:
def __init__(self, data: typing.Dict[str, str]) -> None:
self.data = data
def __repr__(self) -> str:
return f"AuthFile({self.data!r})"
@classmethod
def load(cls, path: typing.Optional[Path] = None) -> "AuthFile":
filepath = path or cls.get_path()
try:
with Path(filepath).open("r", encoding="utf-8") as fp:
data = json.load(fp)
except FileNotFoundError:
data = {}
except json.JSONDecodeError as error:
# File exists but is empty
if error.doc.strip() == "":
data = {}
else:
raise
return cls(data)
def allow(self, filepath: Path) -> None:
logger.debug(f"Authorizing {filepath}")
self.data[str(Path(filepath).resolve())] = self._hash_file(filepath)
def deny(self, filepath: Path) -> None:
if not filepath.exists():
raise FileNotFoundError(f"{filepath} not found")
try:
logger.debug(f"Removing authorization for {filepath}")
del self.data[str(filepath.resolve())]
except KeyError:
pass
def check(
self, filepath: typing.Union[Path, None], raise_error: bool = True
) -> bool:
if not filepath:
return False
if str(filepath.resolve()) not in self.data:
if raise_error:
raise KonchrcNotAuthorizedError
else:
return False
else:
file_hash = self._hash_file(filepath)
if file_hash != self.data[str(filepath.resolve())]:
if raise_error:
raise KonchrcChangedError
else:
return False
return True
def save(self) -> None:
filepath = self.get_path()
filepath.parent.mkdir(parents=True, exist_ok=True)
with Path(filepath).open("w", encoding="utf-8") as fp:
json.dump(self.data, fp)
def __enter__(self) -> "AuthFile":
return self
def __exit__(
self,
exc_type: typing.Type[Exception],
exc_value: Exception,
exc_traceback: types.TracebackType,
) -> None:
if not exc_type:
self.save()
@staticmethod
def get_path() -> Path:
if "KONCH_AUTH_FILE" in os.environ:
return Path(os.environ["KONCH_AUTH_FILE"])
elif "XDG_DATA_HOME" in os.environ:
return Path(os.environ["XDG_DATA_HOME"]) / "konch_auth"
else:
return Path.home() / ".local" / "share" / "konch_auth"
@staticmethod
def _hash_file(filepath: Path) -> str:
# https://stackoverflow.com/a/22058673/1157536
BUF_SIZE = 65536 # read in 64kb chunks
sha1 = hashlib.sha1()
with Path(filepath).open("rb") as f:
while True:
data = f.read(BUF_SIZE)
if not data:
break
sha1.update(data) # type: ignore
return sha1.hexdigest()
RED = 31
GREEN = 32
YELLOW = 33
BOLD = 1
RESET_ALL = 0
def style(
text: str,
fg: typing.Optional[int] = None,
*,
bold: bool = False,
file: typing.IO = sys.stdout,
) -> str:
use_color = not os.environ.get("NO_COLOR") and file.isatty()
if use_color:
parts = [
fg and f"\033[{fg}m",
bold and f"\033[{BOLD}m",
text,
f"\033[{RESET_ALL}m",
]
return "".join([e for e in parts if e])
else:
return text
def sprint(text: str, *args: typing.Any, **kwargs: typing.Any) -> None:
file = kwargs.pop("file", sys.stdout)
return print(style(text, file=file, *args, **kwargs), file=file)
def print_error(text: str) -> None:
prefix = style("ERROR", RED, file=sys.stderr)
return sprint(f"{prefix}: {text}", file=sys.stderr)
def print_warning(text: str) -> None:
prefix = style("WARNING", YELLOW, file=sys.stderr)
return sprint(f"{prefix}: {text}", file=sys.stderr)
Context = typing.Mapping[str, typing.Any]
Formatter = typing.Callable[[Context], str]
ContextFormat = typing.Union[str, Formatter]
def _full_formatter(context: Context) -> str:
line_format = "{name}: {obj!r}"
context_str = "\n".join(
[
line_format.format(name=name, obj=obj)
for name, obj in sorted(context.items(), key=lambda i: i[0].lower())
]
)
header = style("Context:", bold=True)
return f"\n{header}\n{context_str}"
def _short_formatter(context: Context) -> str:
context_str = ", ".join(sorted(context.keys(), key=str.lower))
header = style("Context:", bold=True)
return f"\n{header}\n{context_str}"
def _hide_formatter(context: Context) -> str:
return ""
CONTEXT_FORMATTERS: typing.Dict[str, Formatter] = {
"full": _full_formatter,
"short": _short_formatter,
"hide": _hide_formatter,
}
def format_context(
context: Context, formatter: typing.Union[str, Formatter] = "full"
) -> str:
"""Output the a context dictionary as a string."""
if not context:
return ""
if callable(formatter):
formatter_func = formatter
else:
if formatter in CONTEXT_FORMATTERS:
formatter_func = CONTEXT_FORMATTERS[formatter]
else:
raise ValueError(f'Invalid context format: "{formatter}"')
return formatter_func(context)
BANNER_TEMPLATE = """{version}
{text}
{context}
"""
def make_banner(
text: typing.Optional[str] = None,
context: typing.Optional[Context] = None,
banner_template: typing.Optional[str] = None,
context_format: ContextFormat = "full",
) -> str:
"""Generates a full banner with version info, the given text, and a
formatted list of context variables.
"""
banner_text = text or speak()
banner_template = banner_template or BANNER_TEMPLATE
ctx = format_context(context or {}, formatter=context_format)
out = banner_template.format(version=sys.version, text=banner_text, context=ctx)
return out
def context_list2dict(context_list: typing.Sequence[typing.Any]) -> Context:
"""Converts a list of objects (functions, classes, or modules) to a
dictionary mapping the object names to the objects.
"""
return {obj.__name__.split(".")[-1]: obj for obj in context_list}
def _relpath(p: Path) -> Path:
return p.resolve().relative_to(Path.cwd())
class Shell:
"""Base shell class.
:param dict context: Dictionary, list, or callable (that returns a `dict` or `list`)
that defines what variables will be available when the shell is run.
:param str banner: Banner text that appears on startup.
:param str prompt: Custom input prompt.
:param str output: Custom output prompt.
:param context_format: Formatter for the context dictionary in the banner.
Either 'full', 'short', 'hide', or a function that receives the context
dictionary and outputs a string.
"""
banner_template: str = BANNER_TEMPLATE
def __init__(
self,
context: Context,
banner: typing.Optional[str] = None,
prompt: typing.Optional[str] = None,
output: typing.Optional[str] = None,
context_format: ContextFormat = "full",
**kwargs: typing.Any,
) -> None:
self.context = context() if callable(context) else context
self.context_format = context_format
self.banner = make_banner(
banner,
self.context,
context_format=self.context_format,
banner_template=self.banner_template,
)
self.prompt = prompt
self.output = output
def check_availability(self) -> bool:
raise NotImplementedError
def start(self) -> None:
raise NotImplementedError
class PythonShell(Shell):
"""The built-in Python shell."""
def check_availability(self) -> bool:
return True
def start(self) -> None:
try:
import readline
except ImportError:
pass
else:
# We don't have to wrap the following import in a 'try', because
# we already know 'readline' was imported successfully.
import rlcompleter
readline.set_completer(rlcompleter.Completer(self.context).complete)
readline.parse_and_bind("tab:complete")
if self.prompt:
sys.ps1 = self.prompt
if self.output:
warnings.warn("Custom output templates not supported by PythonShell.")
code.interact(self.banner, local=self.context)
return None
def configure_ipython_prompt(
config, prompt: typing.Optional[str] = None, output: typing.Optional[str] = None
) -> None:
import IPython
if IPython.version_info[0] >= 5: # Custom prompt API changed in IPython 5.0
from pygments.token import Token
# https://ipython.readthedocs.io/en/stable/config/details.html#custom-prompts # noqa: B950
class CustomPrompt(IPython.terminal.prompts.Prompts):
def in_prompt_tokens(self, *args, **kwargs):
if prompt is None:
return super().in_prompt_tokens(*args, **kwargs)
if isinstance(prompt, (str, bytes)):
return [(Token.Prompt, prompt)]
else:
return prompt
def out_prompt_tokens(self, *args, **kwargs):
if output is None:
return super().out_prompt_tokens(*args, **kwargs)
if isinstance(output, (str, bytes)):
return [(Token.OutPrompt, output)]
else:
return prompt
config.TerminalInteractiveShell.prompts_class = CustomPrompt
else:
prompt_config = config.PromptManager
if prompt:
prompt_config.in_template = prompt
if output:
prompt_config.out_template = output
return None
class IPythonShell(Shell):
"""The IPython shell.
:param list ipy_extensions: List of IPython extension names to load upon startup.
:param bool ipy_autoreload: Whether to load and initialize the IPython autoreload
extension upon startup. Can also be an integer, which will be passed as
the argument to the %autoreload line magic.
:param kwargs: The same kwargs as `Shell.__init__`.
"""
def __init__(
self,
ipy_extensions: typing.Optional[typing.List[str]] = None,
ipy_autoreload: bool = False,
ipy_colors: typing.Optional[str] = None,
ipy_highlighting_style: typing.Optional[str] = None,
*args: typing.Any,
**kwargs: typing.Any,
):
self.ipy_extensions = ipy_extensions
self.ipy_autoreload = ipy_autoreload
self.ipy_colors = ipy_colors
self.ipy_highlighting_style = ipy_highlighting_style
Shell.__init__(self, *args, **kwargs)
@staticmethod
def init_autoreload(mode: int) -> None:
"""Load and initialize the IPython autoreload extension."""
from IPython.extensions import autoreload
ip = get_ipython() # type: ignore # noqa: F821
autoreload.load_ipython_extension(ip)
ip.magics_manager.magics["line"]["autoreload"](str(mode))
def check_availability(self) -> bool:
try:
import IPython # noqa: F401
except ImportError:
raise ShellNotAvailableError("IPython shell not available.")
return True
def start(self) -> None:
try:
from IPython import start_ipython
from IPython.utils import io
from traitlets.config.loader import Config as IPyConfig
except ImportError:
raise ShellNotAvailableError(
"IPython shell not available " "or IPython version not supported."
)
# Hack to show custom banner
# TerminalIPythonApp/start_app doesn't allow you to customize the
# banner directly, so we write it to stdout before starting the IPython app
io.stdout.write(self.banner)
# Pass exec_lines in order to start autoreload
if self.ipy_autoreload:
if not isinstance(self.ipy_autoreload, bool):
mode = self.ipy_autoreload
else:
mode = 2
logger.debug(f"Initializing IPython autoreload in mode {mode}")
exec_lines = [
"import konch as __konch",
f"__konch.IPythonShell.init_autoreload({mode})",
]
else:
exec_lines = []
ipy_config = IPyConfig()
if self.ipy_colors:
ipy_config.TerminalInteractiveShell.colors = self.ipy_colors
if self.ipy_highlighting_style:
ipy_config.TerminalInteractiveShell.highlighting_style = (
self.ipy_highlighting_style
)
configure_ipython_prompt(ipy_config, prompt=self.prompt, output=self.output)
# Use start_ipython rather than embed so that IPython is loaded in the "normal"
# way. See https://github.com/django/django/pull/512
start_ipython(
display_banner=False,
user_ns=self.context,
config=ipy_config,
extensions=self.ipy_extensions or [],
exec_lines=exec_lines,
argv=[],
)
return None
class PtPythonShell(Shell):
def __init__(self, ptpy_vi_mode: bool = False, *args, **kwargs):
self.ptpy_vi_mode = ptpy_vi_mode
Shell.__init__(self, *args, **kwargs)
def check_availability(self) -> bool:
try:
import ptpython # noqa: F401
except ImportError:
raise ShellNotAvailableError("PtPython shell not available.")
return True
def start(self) -> None:
try:
from ptpython.repl import embed, run_config
except ImportError:
raise ShellNotAvailableError("PtPython shell not available.")
print(self.banner)
config_dir = Path("~/.ptpython/").expanduser()
# Startup path
startup_paths = []
if "PYTHONSTARTUP" in os.environ:
startup_paths.append(os.environ["PYTHONSTARTUP"])
# Apply config file
def configure(repl):
path = config_dir / "config.py"
if path.exists():
run_config(repl, str(path))
embed(
globals=self.context,
history_filename=config_dir / "history",
vi_mode=self.ptpy_vi_mode,
startup_paths=startup_paths,
configure=configure,
)
return None
class PtIPythonShell(PtPythonShell):
banner_template: str = "{text}\n{context}"
def __init__(
self, ipy_extensions: typing.Optional[typing.List[str]] = None, *args, **kwargs
) -> None:
self.ipy_extensions = ipy_extensions or []
PtPythonShell.__init__(self, *args, **kwargs)
def check_availability(self) -> bool:
try:
import ptpython.ipython # noqa: F401
import IPython # noqa: F401
except ImportError:
raise ShellNotAvailableError("PtIPython shell not available.")
return True
def start(self) -> None:
try:
from ptpython.ipython import embed
from ptpython.repl import run_config
from IPython.terminal.ipapp import load_default_config
except ImportError:
raise ShellNotAvailableError("PtIPython shell not available.")
config_dir = Path("~/.ptpython/").expanduser()
# Apply config file
def configure(repl):
path = config_dir / "config.py"
if path.exists():
run_config(repl, str(path))
# Startup path
startup_paths = []
if "PYTHONSTARTUP" in os.environ:
startup_paths.append(os.environ["PYTHONSTARTUP"])
# exec scripts from startup paths
for path in startup_paths:
if Path(path).exists():
with Path(path).open("rb") as f:
code = compile(f.read(), path, "exec")
exec(code, self.context, self.context)
else:
print(f"File not found: {path}\n\n")
sys.exit(1)
ipy_config = load_default_config()
ipy_config.InteractiveShellEmbed = ipy_config.TerminalInteractiveShell
ipy_config["InteractiveShellApp"]["extensions"] = self.ipy_extensions
configure_ipython_prompt(ipy_config, prompt=self.prompt, output=self.output)
embed(
config=ipy_config,
configure=configure,
history_filename=config_dir / "history",
user_ns=self.context,
header=self.banner,
vi_mode=self.ptpy_vi_mode,
)
return None
class BPythonShell(Shell):
"""The BPython shell."""
def check_availability(self) -> bool:
try:
import bpython # noqa: F401
except ImportError:
raise ShellNotAvailableError("BPython shell not available.")
return True
def start(self) -> None:
try:
from bpython import embed
except ImportError:
raise ShellNotAvailableError("BPython shell not available.")
if self.prompt:
warnings.warn("Custom prompts not supported by BPythonShell.")
if self.output:
warnings.warn("Custom output templates not supported by BPythonShell.")
embed(banner=self.banner, locals_=self.context)
return None
class BPythonCursesShell(Shell):
"""The BPython Curses shell."""
def check_availability(self) -> bool:
try:
import bpython.cli # noqa: F401
except ImportError:
raise ShellNotAvailableError("BPython Curses shell not available.")
return True
def start(self) -> None:
try:
from bpython.cli import main
except ImportError:
raise ShellNotAvailableError("BPython Curses shell not available.")
if self.prompt:
warnings.warn("Custom prompts not supported by BPython Curses shell.")
if self.output:
warnings.warn(
"Custom output templates not supported by BPython Curses shell."
)
main(banner=self.banner, locals_=self.context, args=["-i", "-q"])
return None
class AutoShell(Shell):
"""Shell that runs PtIpython, PtPython, IPython, or BPython if available.
Falls back to built-in Python shell.
"""
# Shell classes in precedence order
SHELLS = [
PtIPythonShell,
PtPythonShell,
IPythonShell,
BPythonShell,
BPythonCursesShell,
PythonShell,
]
def __init__(self, context: Context, banner: str, **kwargs):
Shell.__init__(self, context, **kwargs)
self.kwargs = kwargs
self.banner = banner
def check_availability(self) -> bool:
return True
def start(self) -> None:
shell_args = {
"context": self.context,
"banner": self.banner,
"prompt": self.prompt,
"output": self.output,
"context_format": self.context_format,
}
shell_args.update(self.kwargs)
shell = None
for shell_class in self.SHELLS:
try:
shell = shell_class(**shell_args)
shell.check_availability()
except ShellNotAvailableError:
continue
else:
break
else:
raise ShellNotAvailableError("No available shell to run.")
return shell.start()
CONCHES: typing.List[str] = [
'"My conch told me to come save you guys."\n"Hooray for the magic conches!"',
'"All hail the Magic Conch!"',
'"Hooray for the magic conches!"',
'"Uh, hello there. Magic Conch, I was wondering... '
'should I have the spaghetti or the turkey?"',
'"This copyrighted conch is the cornerstone of our organization."',
'"Praise the Magic Conch!"',
'"the conch exploded into a thousand white fragments and ceased to exist."',
"\"S'right. It's a shell!\"",
'"Ralph felt a kind of affectionate reverence for the conch"',
'"Conch! Conch!"',
'"That\'s why you got the conch out of the water"',
'"the summons of the conch"',
'"Whoever holds the conch gets to speak."',
'"They\'ll come when they hear us--"',
'"We gotta drop the load!"',
'"Dude, we\'re falling right out the sky!!"',
(
'"Oh, Magic Conch Shell, what do we need to do to get '
'out of the Kelp Forest?"\n"Nothing."'
),
'"The shell knows all!"',
'"we must never question the wisdom of the Magic Conch."',
'"The Magic Conch! A club member!"',
'"The shell has spoken!"',
'"This copyrighted conch is the cornerstone of our organization."',
'"All right, Magic Conch... what do we do now?"',
'"Ohhh! The Magic Conch Shell! Ask it something! Ask it something!"',
]
def speak() -> str:
return random.choice(CONCHES)
class Config(dict):
"""A dict-like config object. Behaves like a normal dict except that
the ``context`` will always be converted from a list to a dict.
Defines the default configuration.
"""
def __init__(
self,
context: typing.Optional[Context] = None,
banner: typing.Optional[str] = None,
shell: typing.Type[Shell] = AutoShell,
prompt: typing.Optional[str] = None,
output: typing.Optional[str] = None,
context_format: str = "full",
**kwargs: typing.Any,
) -> None:
ctx = Config.transform_val(context) or {}
super().__init__(
context=ctx,
banner=banner,
shell=shell,
prompt=prompt,
output=output,
context_format=context_format,
**kwargs,
)
def __setitem__(self, key: typing.Any, value: typing.Any) -> None:
if key == "context":
value = Config.transform_val(value)
super().__setitem__(key, value)
@staticmethod
def transform_val(val: typing.Any) -> typing.Any:
if isinstance(val, (list, tuple)):
return context_list2dict(val)
return val
def update(self, d: typing.Mapping) -> None: # type: ignore
for key in d.keys():
# Shallow-merge context
if key == "context":
self["context"].update(Config.transform_val(d["context"]))
else:
self[key] = d[key]
SHELL_MAP: typing.Dict[str, typing.Type[Shell]] = {
"ipy": IPythonShell,
"ipython": IPythonShell,
"bpy": BPythonShell,
"bpython": BPythonShell,
"bpyc": BPythonCursesShell,
"bpython-curses": BPythonCursesShell,
"py": PythonShell,
"python": PythonShell,
"auto": AutoShell,
"ptpy": PtPythonShell,
"ptpython": PtPythonShell,
"ptipy": PtIPythonShell,
"ptipython": PtIPythonShell,
}
# _cfg and _config_registry are singletons that may be mutated in a .konchrc file
_cfg = Config()
_config_registry = {"default": _cfg}
def start(
context: typing.Optional[typing.Mapping] = None,
banner: typing.Optional[str] = None,
shell: typing.Type[Shell] = AutoShell,
prompt: typing.Optional[str] = None,
output: typing.Optional[str] = None,
context_format: str = "full",
**kwargs: typing.Any,
) -> None:
"""Start up the konch shell. Takes the same parameters as Shell.__init__.
"""
logger.debug(f"Using shell: {shell!r}")
if banner is None:
banner = speak()
# Default to global config
context_ = context or _cfg["context"]
banner_ = banner or _cfg["banner"]
if isinstance(shell, type) and issubclass(shell, Shell):
shell_ = shell
else:
shell_ = SHELL_MAP.get(shell or _cfg["shell"], _cfg["shell"])
prompt_ = prompt or _cfg["prompt"]
output_ = output or _cfg["output"]
context_format_ = context_format or _cfg["context_format"]
shell_(
context=context_,
banner=banner_,
prompt=prompt_,
output=output_,
context_format=context_format_,
**kwargs,
).start()
def config(config_dict: typing.Mapping) -> Config:
"""Configures the konch shell. This function should be called in a
.konchrc file.
:param dict config_dict: Dict that may contain 'context', 'banner', and/or
'shell' (default shell class to use).
"""
logger.debug(f"Updating with {config_dict}")
_cfg.update(config_dict)
return _cfg
def named_config(name: str, config_dict: typing.Mapping) -> None:
"""Adds a named config to the config registry. The first argument
may either be a string or a collection of strings.
This function should be called in a .konchrc file.
"""
names = (
name
if isinstance(name, Iterable) and not isinstance(name, (str, bytes))
else [name]
)
for each in names:
_config_registry[each] = Config(**config_dict)
def reset_config() -> Config:
global _cfg
_cfg = Config()
return _cfg
def __ensure_directory_in_path(filename: Path) -> None:
"""Ensures that a file's directory is in the Python path.
"""
directory = Path(filename).parent.resolve()
if directory not in sys.path:
logger.debug(f"Adding {directory} to sys.path")
sys.path.insert(0, str(directory))
CONFIG_FILE = Path(".konchrc")
DEFAULT_CONFIG_FILE = Path.home() / ".konchrc.default"
SEPARATOR = f"\n{'*' * 46}\n"
def confirm(text: str, default: bool = False) -> bool:
"""Display a confirmation prompt."""
choices = "Y/n" if default else "y/N"
prompt = f"{style(text, bold=True)} [{choices}]: "
while 1:
try:
print(prompt, end="")
value = input("").lower().strip()
except (KeyboardInterrupt, EOFError):
sys.exit(1)
if value in ("y", "yes"):
rv = True
elif value in ("n", "no"):
rv = False
elif value == "":
rv = default
else:
print_error("Error: invalid input")
continue
break
return rv
def use_file(
filename: typing.Union[Path, str, None], trust: bool = False
) -> typing.Union[types.ModuleType, None]:
"""Load filename as a python file. Import ``filename`` and return it
as a module.
"""
config_file = filename or resolve_path(CONFIG_FILE)
def preview_unauthorized() -> None:
if not config_file:
return None
print(SEPARATOR, file=sys.stderr)
with Path(config_file).open("r", encoding="utf-8") as fp:
for line in fp:
print(line, end="", file=sys.stderr)
print(SEPARATOR, file=sys.stderr)
if config_file and not Path(config_file).exists():
print_error(f'"{filename}" not found.')
sys.exit(1)
if config_file and Path(config_file).exists():
if not trust:
with AuthFile.load() as authfile:
try:
authfile.check(Path(config_file))
except KonchrcChangedError:
print_error(f'"{config_file}" has changed since you last used it.')
preview_unauthorized()
if confirm("Would you like to authorize it?"):
authfile.allow(Path(config_file))
print()
else:
sys.exit(1)
except KonchrcNotAuthorizedError:
print_error(f'"{config_file}" is blocked.')
preview_unauthorized()
if confirm("Would you like to authorize it?"):
authfile.allow(Path(config_file))
print()
else:
sys.exit(1)
logger.info(f"Using {config_file}")
# Ensure that relative imports are possible
__ensure_directory_in_path(Path(config_file))
mod = None
try:
mod = imp.load_source("konchrc", str(config_file))
except UnboundLocalError: # File not found
pass
else:
return mod
if not config_file:
print_warning("No konch config file found.")
else:
print_warning(f'"{config_file}" not found.')
return None
def resolve_path(filename: Path) -> typing.Union[Path, None]:
"""Find a file by walking up parent directories until the file is found.
Return the absolute path of the file.
"""
current = Path.cwd()
# Stop search at home directory
sentinel_dir = Path.home().parent.resolve()
while current != sentinel_dir:
target = Path(current) / Path(filename)
if target.exists():
return target.resolve()
else:
current = current.parent.resolve()
return None
def get_editor() -> str:
for key in "KONCH_EDITOR", "VISUAL", "EDITOR":
ret = os.environ.get(key)
if ret:
return ret
if sys.platform.startswith("win"):
return "notepad"
for editor in "vim", "nano":
if os.system("which %s &> /dev/null" % editor) == 0:
return editor
return "vi"
def edit_file(
filename: typing.Optional[Path], editor: typing.Optional[str] = None
) -> None:
if not filename:
print_error("filename not passed.")
sys.exit(1)
editor = editor or get_editor()
try:
result = subprocess.Popen(f'{editor} "{filename}"', shell=True)
exit_code = result.wait()
if exit_code != 0:
print_error(f"{editor}: Editing failed!")
sys.exit(1)
except OSError as err:
print_error(f"{editor}: Editing failed: {err}")
sys.exit(1)
else:
with AuthFile.load() as authfile:
authfile.allow(filename)
INIT_TEMPLATE = """# vi: set ft=python :
import konch
import sys
import os
# Available options:
# "context", "banner", "shell", "prompt", "output",
# "context_format", "ipy_extensions", "ipy_autoreload",
# "ipy_colors", "ipy_highlighting_style", "ptpy_vi_mode"
# See: https://konch.readthedocs.io/en/latest/#configuration
konch.config({
"context": [
sys,
os,
]
})
def setup():
pass
def teardown():
pass
"""
def init_config(config_file: Path) -> typing.NoReturn:
if not config_file.exists():
print(f'Writing to "{config_file.resolve()}"...')
print(SEPARATOR)
print(INIT_TEMPLATE, end="")
print(SEPARATOR)
init_template = INIT_TEMPLATE
if DEFAULT_CONFIG_FILE.exists(): # use ~/.konchrc.default if it exists
with Path(DEFAULT_CONFIG_FILE).open("r") as fp:
init_template = fp.read()
with Path(config_file).open("w") as fp:
fp.write(init_template)
with AuthFile.load() as authfile:
authfile.allow(config_file)
relpath = _relpath(config_file)
is_default = relpath == Path(CONFIG_FILE)
edit_cmd = "konch edit" if is_default else f"konch edit {relpath}"
run_cmd = "konch" if is_default else f"konch -f {relpath}"
print(f"{style('Done!', GREEN)} ✨ 🐚 ✨")
print(f"To edit your config: `{style(edit_cmd, bold=True)}`")
print(f"To start the shell: `{style(run_cmd, bold=True)}`")
sys.exit(0)
else:
print_error(f'"{config_file}" already exists in this directory.')
sys.exit(1)
def edit_config(
config_file: typing.Optional[Path] = None, editor: typing.Optional[str] = None
) -> typing.NoReturn:
filename = config_file or resolve_path(CONFIG_FILE)
if not filename:
print_error('No ".konchrc" file found.')
styled_cmd = style("konch init", bold=True, file=sys.stderr)
print(f"Run `{styled_cmd}` to create it.", file=sys.stderr)
sys.exit(1)
if not filename.exists():
print_error(f'"{filename}" does not exist.')
relpath = _relpath(filename)
is_default = relpath == Path(CONFIG_FILE)
cmd = "konch init" if is_default else f"konch init {filename}"
styled_cmd = style(cmd, bold=True, file=sys.stderr)
print(f"Run `{styled_cmd}` to create it.", file=sys.stderr)
sys.exit(1)
print(f'Editing file: "{filename}"')
edit_file(filename, editor=editor)
sys.exit(0)
def allow_config(config_file: typing.Optional[Path] = None) -> typing.NoReturn:
filename: typing.Union[Path, None]
if config_file and config_file.is_dir():
filename = Path(config_file) / CONFIG_FILE
else:
filename = config_file or resolve_path(CONFIG_FILE)
if not filename:
print_error("No config file found.")
sys.exit(1)
with AuthFile.load() as authfile:
if authfile.check(filename, raise_error=False):
print_warning(f'"{filename}" is already authorized.')
else:
try:
print(f'Authorizing "{filename}"...')
authfile.allow(filename)
except FileNotFoundError:
print_error(f'"{filename}" does not exist.')
sys.exit(1)
print(f"{style('Done!', GREEN)} ✨ 🐚 ✨")
relpath = _relpath(filename)
cmd = "konch" if relpath == Path(CONFIG_FILE) else f"konch -f {relpath}"
print(f"You can now start a shell with `{style(cmd, bold=True)}`.")
sys.exit(0)
def deny_config(config_file: typing.Optional[Path] = None) -> typing.NoReturn:
filename: typing.Union[Path, None]
if config_file and config_file.is_dir():
filename = Path(config_file) / CONFIG_FILE
else:
filename = config_file or resolve_path(CONFIG_FILE)
if not filename:
print_error("No config file found.")
sys.exit(1)
print(f'Removing authorization for "{filename}"...')
with AuthFile.load() as authfile:
try:
authfile.deny(filename)
except FileNotFoundError:
print_error(f'"{filename}" does not exist.')
sys.exit(1)
else:
print(style("Done!", GREEN))
sys.exit(0)
def parse_args(argv: typing.Optional[typing.Sequence] = None) -> typing.Dict[str, str]:
"""Exposes the docopt command-line arguments parser.
Return a dictionary of arguments.
"""
return docopt(__doc__, argv=argv, version=__version__)
if __name__ == "__main__":
main()
|
sloria/konch | konch.py | IPythonShell.init_autoreload | python | def init_autoreload(mode: int) -> None:
from IPython.extensions import autoreload
ip = get_ipython() # type: ignore # noqa: F821
autoreload.load_ipython_extension(ip)
ip.magics_manager.magics["line"]["autoreload"](str(mode)) | Load and initialize the IPython autoreload extension. | train | https://github.com/sloria/konch/blob/15160bd0a0cac967eeeab84794bd6cdd0b5b637d/konch.py#L427-L433 | null | class IPythonShell(Shell):
"""The IPython shell.
:param list ipy_extensions: List of IPython extension names to load upon startup.
:param bool ipy_autoreload: Whether to load and initialize the IPython autoreload
extension upon startup. Can also be an integer, which will be passed as
the argument to the %autoreload line magic.
:param kwargs: The same kwargs as `Shell.__init__`.
"""
def __init__(
self,
ipy_extensions: typing.Optional[typing.List[str]] = None,
ipy_autoreload: bool = False,
ipy_colors: typing.Optional[str] = None,
ipy_highlighting_style: typing.Optional[str] = None,
*args: typing.Any,
**kwargs: typing.Any,
):
self.ipy_extensions = ipy_extensions
self.ipy_autoreload = ipy_autoreload
self.ipy_colors = ipy_colors
self.ipy_highlighting_style = ipy_highlighting_style
Shell.__init__(self, *args, **kwargs)
@staticmethod
def check_availability(self) -> bool:
try:
import IPython # noqa: F401
except ImportError:
raise ShellNotAvailableError("IPython shell not available.")
return True
def start(self) -> None:
try:
from IPython import start_ipython
from IPython.utils import io
from traitlets.config.loader import Config as IPyConfig
except ImportError:
raise ShellNotAvailableError(
"IPython shell not available " "or IPython version not supported."
)
# Hack to show custom banner
# TerminalIPythonApp/start_app doesn't allow you to customize the
# banner directly, so we write it to stdout before starting the IPython app
io.stdout.write(self.banner)
# Pass exec_lines in order to start autoreload
if self.ipy_autoreload:
if not isinstance(self.ipy_autoreload, bool):
mode = self.ipy_autoreload
else:
mode = 2
logger.debug(f"Initializing IPython autoreload in mode {mode}")
exec_lines = [
"import konch as __konch",
f"__konch.IPythonShell.init_autoreload({mode})",
]
else:
exec_lines = []
ipy_config = IPyConfig()
if self.ipy_colors:
ipy_config.TerminalInteractiveShell.colors = self.ipy_colors
if self.ipy_highlighting_style:
ipy_config.TerminalInteractiveShell.highlighting_style = (
self.ipy_highlighting_style
)
configure_ipython_prompt(ipy_config, prompt=self.prompt, output=self.output)
# Use start_ipython rather than embed so that IPython is loaded in the "normal"
# way. See https://github.com/django/django/pull/512
start_ipython(
display_banner=False,
user_ns=self.context,
config=ipy_config,
extensions=self.ipy_extensions or [],
exec_lines=exec_lines,
argv=[],
)
return None
|
GiulioRossetti/ndlib | ndlib/models/opinions/CognitiveOpDynModel.py | CognitiveOpDynModel.set_initial_status | python | def set_initial_status(self, configuration=None):
super(CognitiveOpDynModel, self).set_initial_status(configuration)
# set node status
for node in self.status:
self.status[node] = np.random.random_sample()
self.initial_status = self.status.copy()
# set new node parameters
self.params['nodes']['cognitive'] = {}
# first correct the input model parameters and retreive T_range, B_range and R_distribution
T_range = (self.params['model']['T_range_min'], self.params['model']['T_range_max'])
if self.params['model']['T_range_min'] > self.params['model']['T_range_max']:
T_range = (self.params['model']['T_range_max'], self.params['model']['T_range_min'])
B_range = (self.params['model']['B_range_min'], self.params['model']['B_range_max'])
if self.params['model']['B_range_min'] > self.params['model']['B_range_max']:
B_range = (self.params['model']['B_range_max'], self.params['model']['B_range_min'])
s = float(self.params['model']['R_fraction_negative'] + self.params['model']['R_fraction_neutral'] +
self.params['model']['R_fraction_positive'])
R_distribution = (self.params['model']['R_fraction_negative']/s, self.params['model']['R_fraction_neutral']/s,
self.params['model']['R_fraction_positive']/s)
# then sample parameters from the ranges and distribution
for node in self.graph.nodes():
R_prob = np.random.random_sample()
if R_prob < R_distribution[0]:
R = -1
elif R_prob < (R_distribution[0] + R_distribution[1]):
R = 0
else:
R = 1
# R, B and T parameters in a tuple
self.params['nodes']['cognitive'][node] = (R,
B_range[0] + (B_range[1] - B_range[0])*np.random.random_sample(),
T_range[0] + (T_range[1] - T_range[0])*np.random.random_sample()) | Override behaviour of methods in class DiffusionModel.
Overwrites initial status using random real values.
Generates random node profiles. | train | https://github.com/GiulioRossetti/ndlib/blob/23ecf50c0f76ff2714471071ab9ecb600f4a9832/ndlib/models/opinions/CognitiveOpDynModel.py#L92-L133 | [
"def set_initial_status(self, configuration):\n \"\"\"\n Set the initial model configuration\n\n :param configuration: a ```ndlib.models.ModelConfig.Configuration``` object\n \"\"\"\n\n self.__validate_configuration(configuration)\n\n nodes_cfg = configuration.get_nodes_configuration()\n # Set additional node information\n\n for param, node_to_value in future.utils.iteritems(nodes_cfg):\n if len(node_to_value) < len(self.graph.nodes()):\n raise ConfigurationException({\"message\": \"Not all nodes have a configuration specified\"})\n\n self.params['nodes'][param] = node_to_value\n\n edges_cfg = configuration.get_edges_configuration()\n # Set additional edges information\n for param, edge_to_values in future.utils.iteritems(edges_cfg):\n if len(edge_to_values) == len(self.graph.edges()):\n self.params['edges'][param] = {}\n for e in edge_to_values:\n self.params['edges'][param][e] = edge_to_values[e]\n\n # Set initial status\n model_status = configuration.get_model_configuration()\n\n for param, nodes in future.utils.iteritems(model_status):\n self.params['status'][param] = nodes\n for node in nodes:\n self.status[node] = self.available_statuses[param]\n\n # Set model additional information\n model_params = configuration.get_model_parameters()\n for param, val in future.utils.iteritems(model_params):\n self.params['model'][param] = val\n\n # Handle initial infection\n if 'Infected' not in self.params['status']:\n if 'percentage_infected' in self.params['model']:\n number_of_initial_infected = len(self.graph.nodes()) * float(self.params['model']['percentage_infected'])\n if number_of_initial_infected < 1:\n warnings.warn('Graph with less than 100 nodes: a single node will be set as infected')\n number_of_initial_infected = 1\n\n available_nodes = [n for n in self.status if self.status[n] == 0]\n sampled_nodes = np.random.choice(available_nodes, int(number_of_initial_infected), replace=False)\n for k in sampled_nodes:\n self.status[k] = self.available_statuses['Infected']\n\n self.initial_status = self.status\n"
] | class CognitiveOpDynModel(DiffusionModel):
"""
Model Parameters to be specified via ModelConfig
:param I: external information value in [0,1]
:param T_range_min: the minimum of the range of initial values for T. Range [0,1].
:param T_range_max: the maximum of the range of initial values for T. Range [0,1].
:param B_range_min: the minimum of the range of initial values for B. Range [0,1]
:param B_range_max: the maximum of the range of initial values for B. Range [0,1].
:param R_fraction_negative: fraction of individuals having the node parameter R=-1.
:param R_fraction_positive: fraction of individuals having the node parameter R=1
:param R_fraction_neutral: fraction of individuals having the node parameter R=0
The following relation should hold: R_fraction_negative+R_fraction_neutral+R_fraction_positive=1.
To achieve this, the fractions selected will be normalised to sum 1.
Node states are continuous values in [0,1].
The initial state is generated randomly uniformly from the domain defined by model parameters.
"""
def __init__(self, graph):
"""
Model Constructor
:param graph: A networkx graph object
"""
super(self.__class__, self).__init__(graph)
self.discrete_state = False
self.available_statuses = {
"Infected": 0
}
self.parameters = {
"model": {
"I": {
"descr": "External information",
"range": [0, 1],
"optional": False
},
"T_range_min": {
"descr": "Minimum of the range of initial values for T",
"range": [0, 1],
"optional": False
},
"T_range_max": {
"descr": "Maximum of the range of initial values for T",
"range": [0, 1],
"optional": False
},
"B_range_min": {
"descr": "Minimum of the range of initial values for B",
"range": [0, 1],
"optional": False
},
"B_range_max": {
"descr": "Maximum of the range of initial values for B",
"range": [0, 1],
"optional": False
},
"R_fraction_negative": {
"descr": "Fraction of nodes having R=-1",
"range": [0, 1],
"optional": False
},
"R_fraction_neutral": {
"descr": "Fraction of nodes having R=0",
"range": [0, 1],
"optional": False
},
"R_fraction_positive": {
"descr": "Fraction of nodes having R=1",
"range": [0, 1],
"optional": False
}
},
"nodes": {},
"edges": {}
}
self.name = "Cognitive Opinion Dynamics"
def clean_initial_status(self, valid_status=None):
for n, s in future.utils.iteritems(self.status):
if s > 1 or s < 0:
self.status[n] = 0
def iteration(self, node_status=True):
"""
Execute a single model iteration
:return: Iteration_id, Incremental node status (dictionary node->status)
"""
# One iteration changes the opinion of all agents using the following procedure:
# - first all agents communicate with institutional information I using a deffuant like rule
# - then random pairs of agents are selected to interact (N pairs)
# - interaction depends on state of agents but also internal cognitive structure
self.clean_initial_status(None)
actual_status = {node: nstatus for node, nstatus in future.utils.iteritems(self.status)}
if self.actual_iteration == 0:
self.actual_iteration += 1
delta, node_count, status_delta = self.status_delta(self.status)
if node_status:
return {"iteration": 0, "status": self.status.copy(),
"node_count": node_count.copy(), "status_delta": status_delta.copy()}
else:
return {"iteration": 0, "status": {},
"node_count": node_count.copy(), "status_delta": status_delta.copy()}
# first interact with I
I = self.params['model']['I']
for node in self.graph.nodes():
T = self.params['nodes']['cognitive'][node][2]
R = self.params['nodes']['cognitive'][node][0]
actual_status[node] = actual_status[node] + T * (I - actual_status[node])
if R == 1:
actual_status[node] = 0.5 * (1 + actual_status[node])
if R == -1:
actual_status[node] *= 0.5
# then interact with peers
for i in range(0, self.graph.number_of_nodes()):
# select a random node
n1 = list(self.graph.nodes)[np.random.randint(0, self.graph.number_of_nodes())]
# select all of the nodes neighbours (no digraph possible)
neighbours = list(self.graph.neighbors(n1))
if len(neighbours) == 0:
continue
# select second node - a random neighbour
n2 = neighbours[np.random.randint(0, len(neighbours))]
# update status of n1 and n2
p1 = pow(actual_status[n1], 1.0 / self.params['nodes']['cognitive'][n1][1])
p2 = pow(actual_status[n2], 1.0 / self.params['nodes']['cognitive'][n2][1])
oldn1 = self.status[n1]
if np.random.random_sample() < p2: # if node 2 talks, node 1 gets changed
T1 = self.params['nodes']['cognitive'][n1][2]
R1 = self.params['nodes']['cognitive'][n1][0]
actual_status[n1] += (1 - T1) * (actual_status[n2] - actual_status[n1])
if R1 == 1:
actual_status[n1] = 0.5 * (1 + actual_status[n1])
if R1 == -1:
actual_status[n1] *= 0.5
if np.random.random_sample() < p1: # if node 1 talks, node 2 gets changed
T2 = self.params['nodes']['cognitive'][n2][2]
R2 = self.params['nodes']['cognitive'][n2][0]
actual_status[n2] += (1 - T2) * (oldn1 - actual_status[n2])
if R2 == 1:
actual_status[n2] = 0.5 * (1 + actual_status[n2])
if R2 == -1:
actual_status[n2] *= 0.5
delta, node_count, status_delta = self.status_delta(actual_status)
self.status = actual_status
self.actual_iteration += 1
if node_status:
return {"iteration": self.actual_iteration - 1, "status": delta.copy(),
"node_count": node_count.copy(), "status_delta": status_delta.copy()}
else:
return {"iteration": self.actual_iteration - 1, "status": {},
"node_count": node_count.copy(), "status_delta": status_delta.copy()}
|
GiulioRossetti/ndlib | ndlib/models/opinions/CognitiveOpDynModel.py | CognitiveOpDynModel.iteration | python | def iteration(self, node_status=True):
# One iteration changes the opinion of all agents using the following procedure:
# - first all agents communicate with institutional information I using a deffuant like rule
# - then random pairs of agents are selected to interact (N pairs)
# - interaction depends on state of agents but also internal cognitive structure
self.clean_initial_status(None)
actual_status = {node: nstatus for node, nstatus in future.utils.iteritems(self.status)}
if self.actual_iteration == 0:
self.actual_iteration += 1
delta, node_count, status_delta = self.status_delta(self.status)
if node_status:
return {"iteration": 0, "status": self.status.copy(),
"node_count": node_count.copy(), "status_delta": status_delta.copy()}
else:
return {"iteration": 0, "status": {},
"node_count": node_count.copy(), "status_delta": status_delta.copy()}
# first interact with I
I = self.params['model']['I']
for node in self.graph.nodes():
T = self.params['nodes']['cognitive'][node][2]
R = self.params['nodes']['cognitive'][node][0]
actual_status[node] = actual_status[node] + T * (I - actual_status[node])
if R == 1:
actual_status[node] = 0.5 * (1 + actual_status[node])
if R == -1:
actual_status[node] *= 0.5
# then interact with peers
for i in range(0, self.graph.number_of_nodes()):
# select a random node
n1 = list(self.graph.nodes)[np.random.randint(0, self.graph.number_of_nodes())]
# select all of the nodes neighbours (no digraph possible)
neighbours = list(self.graph.neighbors(n1))
if len(neighbours) == 0:
continue
# select second node - a random neighbour
n2 = neighbours[np.random.randint(0, len(neighbours))]
# update status of n1 and n2
p1 = pow(actual_status[n1], 1.0 / self.params['nodes']['cognitive'][n1][1])
p2 = pow(actual_status[n2], 1.0 / self.params['nodes']['cognitive'][n2][1])
oldn1 = self.status[n1]
if np.random.random_sample() < p2: # if node 2 talks, node 1 gets changed
T1 = self.params['nodes']['cognitive'][n1][2]
R1 = self.params['nodes']['cognitive'][n1][0]
actual_status[n1] += (1 - T1) * (actual_status[n2] - actual_status[n1])
if R1 == 1:
actual_status[n1] = 0.5 * (1 + actual_status[n1])
if R1 == -1:
actual_status[n1] *= 0.5
if np.random.random_sample() < p1: # if node 1 talks, node 2 gets changed
T2 = self.params['nodes']['cognitive'][n2][2]
R2 = self.params['nodes']['cognitive'][n2][0]
actual_status[n2] += (1 - T2) * (oldn1 - actual_status[n2])
if R2 == 1:
actual_status[n2] = 0.5 * (1 + actual_status[n2])
if R2 == -1:
actual_status[n2] *= 0.5
delta, node_count, status_delta = self.status_delta(actual_status)
self.status = actual_status
self.actual_iteration += 1
if node_status:
return {"iteration": self.actual_iteration - 1, "status": delta.copy(),
"node_count": node_count.copy(), "status_delta": status_delta.copy()}
else:
return {"iteration": self.actual_iteration - 1, "status": {},
"node_count": node_count.copy(), "status_delta": status_delta.copy()} | Execute a single model iteration
:return: Iteration_id, Incremental node status (dictionary node->status) | train | https://github.com/GiulioRossetti/ndlib/blob/23ecf50c0f76ff2714471071ab9ecb600f4a9832/ndlib/models/opinions/CognitiveOpDynModel.py#L140-L220 | [
"def clean_initial_status(self, valid_status=None):\n for n, s in future.utils.iteritems(self.status):\n if s > 1 or s < 0:\n self.status[n] = 0\n",
"def status_delta(self, actual_status):\n \"\"\"\n Compute the point-to-point variations for each status w.r.t. the previous system configuration\n\n :param actual_status: the actual simulation status\n :return: node that have changed their statuses (dictionary status->nodes),\n count of actual nodes per status (dictionary status->node count),\n delta of nodes per status w.r.t the previous configuration (dictionary status->delta)\n \"\"\"\n actual_status_count = {}\n old_status_count = {}\n delta = {}\n for n, v in future.utils.iteritems(self.status):\n if v != actual_status[n]:\n delta[n] = actual_status[n]\n\n for st in self.available_statuses.values():\n actual_status_count[st] = len([x for x in actual_status if actual_status[x] == st])\n old_status_count[st] = len([x for x in self.status if self.status[x] == st])\n\n status_delta = {st: actual_status_count[st] - old_status_count[st] for st in actual_status_count}\n\n return delta, actual_status_count, status_delta\n"
] | class CognitiveOpDynModel(DiffusionModel):
"""
Model Parameters to be specified via ModelConfig
:param I: external information value in [0,1]
:param T_range_min: the minimum of the range of initial values for T. Range [0,1].
:param T_range_max: the maximum of the range of initial values for T. Range [0,1].
:param B_range_min: the minimum of the range of initial values for B. Range [0,1]
:param B_range_max: the maximum of the range of initial values for B. Range [0,1].
:param R_fraction_negative: fraction of individuals having the node parameter R=-1.
:param R_fraction_positive: fraction of individuals having the node parameter R=1
:param R_fraction_neutral: fraction of individuals having the node parameter R=0
The following relation should hold: R_fraction_negative+R_fraction_neutral+R_fraction_positive=1.
To achieve this, the fractions selected will be normalised to sum 1.
Node states are continuous values in [0,1].
The initial state is generated randomly uniformly from the domain defined by model parameters.
"""
def __init__(self, graph):
"""
Model Constructor
:param graph: A networkx graph object
"""
super(self.__class__, self).__init__(graph)
self.discrete_state = False
self.available_statuses = {
"Infected": 0
}
self.parameters = {
"model": {
"I": {
"descr": "External information",
"range": [0, 1],
"optional": False
},
"T_range_min": {
"descr": "Minimum of the range of initial values for T",
"range": [0, 1],
"optional": False
},
"T_range_max": {
"descr": "Maximum of the range of initial values for T",
"range": [0, 1],
"optional": False
},
"B_range_min": {
"descr": "Minimum of the range of initial values for B",
"range": [0, 1],
"optional": False
},
"B_range_max": {
"descr": "Maximum of the range of initial values for B",
"range": [0, 1],
"optional": False
},
"R_fraction_negative": {
"descr": "Fraction of nodes having R=-1",
"range": [0, 1],
"optional": False
},
"R_fraction_neutral": {
"descr": "Fraction of nodes having R=0",
"range": [0, 1],
"optional": False
},
"R_fraction_positive": {
"descr": "Fraction of nodes having R=1",
"range": [0, 1],
"optional": False
}
},
"nodes": {},
"edges": {}
}
self.name = "Cognitive Opinion Dynamics"
def set_initial_status(self, configuration=None):
"""
Override behaviour of methods in class DiffusionModel.
Overwrites initial status using random real values.
Generates random node profiles.
"""
super(CognitiveOpDynModel, self).set_initial_status(configuration)
# set node status
for node in self.status:
self.status[node] = np.random.random_sample()
self.initial_status = self.status.copy()
# set new node parameters
self.params['nodes']['cognitive'] = {}
# first correct the input model parameters and retreive T_range, B_range and R_distribution
T_range = (self.params['model']['T_range_min'], self.params['model']['T_range_max'])
if self.params['model']['T_range_min'] > self.params['model']['T_range_max']:
T_range = (self.params['model']['T_range_max'], self.params['model']['T_range_min'])
B_range = (self.params['model']['B_range_min'], self.params['model']['B_range_max'])
if self.params['model']['B_range_min'] > self.params['model']['B_range_max']:
B_range = (self.params['model']['B_range_max'], self.params['model']['B_range_min'])
s = float(self.params['model']['R_fraction_negative'] + self.params['model']['R_fraction_neutral'] +
self.params['model']['R_fraction_positive'])
R_distribution = (self.params['model']['R_fraction_negative']/s, self.params['model']['R_fraction_neutral']/s,
self.params['model']['R_fraction_positive']/s)
# then sample parameters from the ranges and distribution
for node in self.graph.nodes():
R_prob = np.random.random_sample()
if R_prob < R_distribution[0]:
R = -1
elif R_prob < (R_distribution[0] + R_distribution[1]):
R = 0
else:
R = 1
# R, B and T parameters in a tuple
self.params['nodes']['cognitive'][node] = (R,
B_range[0] + (B_range[1] - B_range[0])*np.random.random_sample(),
T_range[0] + (T_range[1] - T_range[0])*np.random.random_sample())
def clean_initial_status(self, valid_status=None):
for n, s in future.utils.iteritems(self.status):
if s > 1 or s < 0:
self.status[n] = 0
|
GiulioRossetti/ndlib | ndlib/models/epidemics/GeneralisedThresholdModel.py | GeneralisedThresholdModel.iteration | python | def iteration(self, node_status=True):
self.clean_initial_status(self.available_statuses.values())
actual_status = {node: nstatus for node, nstatus in future.utils.iteritems(self.status)}
if self.actual_iteration == 0:
self.actual_iteration += 1
self.params['model']['queue'] = dict()
return 0, actual_status
gamma = float(self.params['model']['mu']) * float(self.actual_iteration) / float(self.params['model']['tau'])
list_node = self.graph.nodes()
start = min(list_node)
stop = max(list_node)
number_node_susceptible = len(self.graph.nodes()) - sum(self.status.values())
while gamma >= 1 and number_node_susceptible >= 1:
random_index = random.randrange(start, stop+1, 1)
if random_index in list_node and actual_status[random_index] == 0:
actual_status[random_index] = 1
gamma -= 1
number_node_susceptible -= 1
for u in self.graph.nodes():
if actual_status[u] == 1:
continue
neighbors = list(self.graph.neighbors(u))
if isinstance(self.graph, nx.DiGraph):
neighbors = list(self.graph.predecessors(u))
infected = 0
for v in neighbors:
infected += self.status[v]
if len(neighbors) > 0:
infected_ratio = float(infected)/len(neighbors)
if infected_ratio >= self.params['nodes']['threshold'][u]:
if u not in self.inqueue:
self.queue.put((self.actual_iteration, u))
self.inqueue[u] = None
while not self.queue.empty():
next = self.queue.queue[0]
if self.actual_iteration - next[0] >= self.params['model']['tau']:
self.queue.get()
else:
break
delta = self.status_delta(actual_status)
self.status = actual_status
self.actual_iteration += 1
return self.actual_iteration - 1, delta | Execute a single model iteration
:return: Iteration_id, Incremental node status (dictionary node->status) | train | https://github.com/GiulioRossetti/ndlib/blob/23ecf50c0f76ff2714471071ab9ecb600f4a9832/ndlib/models/epidemics/GeneralisedThresholdModel.py#L58-L115 | [
"def clean_initial_status(self, valid_status=None):\n \"\"\"\n Check the consistency of initial status\n :param valid_status: valid node configurations\n \"\"\"\n for n, s in future.utils.iteritems(self.status):\n if s not in valid_status:\n self.status[n] = 0\n"
] | class GeneralisedThresholdModel(DiffusionModel):
"""
Node Parameters to be specified via ModelConfig
:param threshold: The node threshold. If not specified otherwise a value of 0.1 is assumed for all nodes.
"""
def __init__(self, graph):
"""
Model Constructor
:param graph: A networkx graph object
"""
super(self.__class__, self).__init__(graph)
self.available_statuses = {
"Susceptible": 0,
"Infected": 1
}
self.parameters = {
"model": {
"tau": {
"descr": "Adoption threshold rate",
"range": [0, float("inf")],
"optional": False},
"mu": {
"descr": "Exogenous timescale",
"range": [0, float("inf")],
"optional": False},
},
"nodes": {
"threshold": {
"descr": "Node threshold",
"range": [0, 1],
"optional": True,
"default": 0.1
}
},
"edges": {},
}
self.queue = queue.PriorityQueue()
self.inqueue = defaultdict(int)
self.name = "GeneralisedThresholdModel"
|
GiulioRossetti/ndlib | ndlib/models/ModelConfig.py | Configuration.add_node_configuration | python | def add_node_configuration(self, param_name, node_id, param_value):
if param_name not in self.config['nodes']:
self.config['nodes'][param_name] = {node_id: param_value}
else:
self.config['nodes'][param_name][node_id] = param_value | Set a parameter for a given node
:param param_name: parameter identifier (as specified by the chosen model)
:param node_id: node identifier
:param param_value: parameter value | train | https://github.com/GiulioRossetti/ndlib/blob/23ecf50c0f76ff2714471071ab9ecb600f4a9832/ndlib/models/ModelConfig.py#L72-L83 | null | class Configuration(object):
"""
Configuration Object
"""
def __init__(self):
self.config = {
'nodes': {},
'edges': {},
'model': {},
'status': {}
}
def get_nodes_configuration(self):
"""
Nodes configurations
:return: dictionary that link each node to its attributes
"""
return self.config['nodes']
def get_edges_configuration(self):
"""
Edges configurations
:return: dictionary that link each edge to its attributes
"""
return self.config['edges']
def get_model_parameters(self):
"""
Model parameters
:return: dictionary describes the specified model parameters
"""
return self.config['model']
def get_model_configuration(self):
"""
Initial configuration
:return: initial nodes status (if specified)
"""
return self.config['status']
def add_model_parameter(self, param_name, param_value):
"""
Set a Model Parameter
:param param_name: parameter identifier (as specified by the chosen model)
:param param_value: parameter value
"""
self.config['model'][param_name] = param_value
def add_model_initial_configuration(self, status_name, nodes):
"""
Set initial status for a set of nodes
:param status_name: status to be set (as specified by the chosen model)
:param nodes: list of affected nodes
"""
self.config['status'][status_name] = nodes
def add_node_set_configuration(self, param_name, node_to_value):
"""
Set Nodes parameter
:param param_name: parameter identifier (as specified by the chosen model)
:param node_to_value: dictionary mapping each node a parameter value
"""
for nid, val in future.utils.iteritems(node_to_value):
self.add_node_configuration(param_name, nid, val)
def add_edge_configuration(self, param_name, edge, param_value):
"""
Set a parameter for a given edge
:param param_name: parameter identifier (as specified by the chosen model)
:param edge: edge identifier
:param param_value: parameter value
"""
if param_name not in self.config['edges']:
self.config['edges'][param_name] = {edge: param_value}
else:
self.config['edges'][param_name][edge] = param_value
def add_edge_set_configuration(self, param_name, edge_to_value):
"""
Set Edges parameter
:param param_name: parameter identifier (as specified by the chosen model)
:param edge_to_value: dictionary mapping each edge a parameter value
"""
for edge, val in future.utils.iteritems(edge_to_value):
self.add_edge_configuration(param_name, edge, val)
|
GiulioRossetti/ndlib | ndlib/models/ModelConfig.py | Configuration.add_node_set_configuration | python | def add_node_set_configuration(self, param_name, node_to_value):
for nid, val in future.utils.iteritems(node_to_value):
self.add_node_configuration(param_name, nid, val) | Set Nodes parameter
:param param_name: parameter identifier (as specified by the chosen model)
:param node_to_value: dictionary mapping each node a parameter value | train | https://github.com/GiulioRossetti/ndlib/blob/23ecf50c0f76ff2714471071ab9ecb600f4a9832/ndlib/models/ModelConfig.py#L85-L93 | [
"def add_node_configuration(self, param_name, node_id, param_value):\n \"\"\"\n Set a parameter for a given node\n\n :param param_name: parameter identifier (as specified by the chosen model)\n :param node_id: node identifier\n :param param_value: parameter value\n \"\"\"\n if param_name not in self.config['nodes']:\n self.config['nodes'][param_name] = {node_id: param_value}\n else:\n self.config['nodes'][param_name][node_id] = param_value\n"
] | class Configuration(object):
"""
Configuration Object
"""
def __init__(self):
self.config = {
'nodes': {},
'edges': {},
'model': {},
'status': {}
}
def get_nodes_configuration(self):
"""
Nodes configurations
:return: dictionary that link each node to its attributes
"""
return self.config['nodes']
def get_edges_configuration(self):
"""
Edges configurations
:return: dictionary that link each edge to its attributes
"""
return self.config['edges']
def get_model_parameters(self):
"""
Model parameters
:return: dictionary describes the specified model parameters
"""
return self.config['model']
def get_model_configuration(self):
"""
Initial configuration
:return: initial nodes status (if specified)
"""
return self.config['status']
def add_model_parameter(self, param_name, param_value):
"""
Set a Model Parameter
:param param_name: parameter identifier (as specified by the chosen model)
:param param_value: parameter value
"""
self.config['model'][param_name] = param_value
def add_model_initial_configuration(self, status_name, nodes):
"""
Set initial status for a set of nodes
:param status_name: status to be set (as specified by the chosen model)
:param nodes: list of affected nodes
"""
self.config['status'][status_name] = nodes
def add_node_configuration(self, param_name, node_id, param_value):
"""
Set a parameter for a given node
:param param_name: parameter identifier (as specified by the chosen model)
:param node_id: node identifier
:param param_value: parameter value
"""
if param_name not in self.config['nodes']:
self.config['nodes'][param_name] = {node_id: param_value}
else:
self.config['nodes'][param_name][node_id] = param_value
def add_edge_configuration(self, param_name, edge, param_value):
"""
Set a parameter for a given edge
:param param_name: parameter identifier (as specified by the chosen model)
:param edge: edge identifier
:param param_value: parameter value
"""
if param_name not in self.config['edges']:
self.config['edges'][param_name] = {edge: param_value}
else:
self.config['edges'][param_name][edge] = param_value
def add_edge_set_configuration(self, param_name, edge_to_value):
"""
Set Edges parameter
:param param_name: parameter identifier (as specified by the chosen model)
:param edge_to_value: dictionary mapping each edge a parameter value
"""
for edge, val in future.utils.iteritems(edge_to_value):
self.add_edge_configuration(param_name, edge, val)
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.