INSTRUCTION
stringlengths
1
8.43k
RESPONSE
stringlengths
75
104k
write FILENAME Write a local copy of FILENAME using FILENAME_tweaks for local tweaks.
def write_main(argv): """ write FILENAME Write a local copy of FILENAME using FILENAME_tweaks for local tweaks. """ if len(argv) != 1: print("Please provide the name of a file to write.") return 1 filename = argv[0] resource_name = "files/" + filename tweaks_name = a...
Amend a filename with a suffix.
def amend_filename(filename, amend): """Amend a filename with a suffix. amend_filename("foo.txt", "_tweak") --> "foo_tweak.txt" """ base, ext = os.path.splitext(filename) amended_name = base + amend + ext return amended_name
check FILENAME Check that FILENAME has not been edited since writing.
def check_main(argv): """ check FILENAME Check that FILENAME has not been edited since writing. """ if len(argv) != 1: print("Please provide the name of a file to check.") return 1 filename = argv[0] if os.path.exists(filename): print(u"Checking existing copy of...
Merge tweaks into a main config file.
def merge_configs(main, tweaks): """Merge tweaks into a main config file.""" for section in tweaks.sections(): for option in tweaks.options(section): value = tweaks.get(section, option) if option.endswith("+"): option = option[:-1] value = main.get...
u Write text to the file.
def write(self, text, hashline=b"# {}"): u""" Write `text` to the file. Writes the text to the file, with a final line checksumming the contents. The entire file must be written with one `.write()` call. The last line is written with the `hashline` format string, which can ...
Check if the file still has its original contents.
def validate(self): """ Check if the file still has its original contents. Returns True if the file is unchanged, False if it has been tampered with. """ with open(self.filename, "rb") as f: text = f.read() start_last_line = text.rfind(b"\n", 0, -1)...
Check that a checker s visitors are correctly named.
def check_visitors(cls): """Check that a checker's visitors are correctly named. A checker has methods named visit_NODETYPE, but it's easy to mis-name a visit method, and it will never be called. This decorator checks the class to see that all of its visitors are named after an existing node class...
Make a reasonable class name for a class node.
def usable_class_name(node): """Make a reasonable class name for a class node.""" name = node.qname() for prefix in ["__builtin__.", "builtins.", "."]: if name.startswith(prefix): name = name[len(prefix):] return name
Parse the pylint output - format = parseable lines into PylintError tuples.
def parse_pylint_output(pylint_output): """ Parse the pylint output-format=parseable lines into PylintError tuples. """ for line in pylint_output: if not line.strip(): continue if line[0:5] in ("-"*5, "*"*5): continue parsed = PYLINT_PARSEABLE_REGEX.sear...
Format a list of error_names into a pylint: disable = line.
def format_pylint_disables(error_names, tag=True): """ Format a list of error_names into a 'pylint: disable=' line. """ tag_str = "lint-amnesty, " if tag else "" if error_names: return u" # {tag}pylint: disable={disabled}".format( disabled=", ".join(sorted(error_names)), ...
Yield any modified versions of line needed to address the errors in errors.
def fix_pylint(line, errors): """ Yield any modified versions of ``line`` needed to address the errors in ``errors``. """ if not errors: yield line return current = PYLINT_EXCEPTION_REGEX.search(line) if current: original_errors = {disable.strip() for disable in current....
Add # pylint: disable clauses to add exceptions to all existing pylint errors in a codebase.
def pylint_amnesty(pylint_output): """ Add ``# pylint: disable`` clauses to add exceptions to all existing pylint errors in a codebase. """ errors = defaultdict(lambda: defaultdict(set)) for pylint_error in parse_pylint_output(pylint_output): errors[pylint_error.filename][pylint_error.linenu...
The edx_lint command entry point.
def main(argv=None): """The edx_lint command entry point.""" if argv is None: argv = sys.argv[1:] if not argv or argv[0] == "help": show_help() return 0 elif argv[0] == "check": return check_main(argv[1:]) elif argv[0] == "list": return list_main(argv[1:]) ...
Print the help string for the edx_lint command.
def show_help(): """Print the help string for the edx_lint command.""" print("""\ Manage local config files from masters in edx_lint. Commands: """) for cmd in [write_main, check_main, list_main]: print(cmd.__doc__.lstrip("\n"))
Parse an HTML JSON form submission as per the W3C Draft spec An implementation of The application/ json encoding algorithm http:// www. w3. org/ TR/ html - json - forms/
def parse_json_form(dictionary, prefix=''): """ Parse an HTML JSON form submission as per the W3C Draft spec An implementation of "The application/json encoding algorithm" http://www.w3.org/TR/html-json-forms/ """ # Step 1: Initialize output object output = {} for name, value in get_all_...
Parse a string as a JSON path An implementation of steps to parse a JSON encoding path http:// www. w3. org/ TR/ html - json - forms/ #dfn - steps - to - parse - a - json - encoding - path
def parse_json_path(path): """ Parse a string as a JSON path An implementation of "steps to parse a JSON encoding path" http://www.w3.org/TR/html-json-forms/#dfn-steps-to-parse-a-json-encoding-path """ # Steps 1, 2, 3 original_path = path steps = [] # Step 11 (Failure) failed =...
Apply a JSON value to a context object An implementation of steps to set a JSON encoding value http:// www. w3. org/ TR/ html - json - forms/ #dfn - steps - to - set - a - json - encoding - value
def set_json_value(context, step, current_value, entry_value, is_file): """ Apply a JSON value to a context object An implementation of "steps to set a JSON encoding value" http://www.w3.org/TR/html-json-forms/#dfn-steps-to-set-a-json-encoding-value """ # TODO: handle is_file # Add empty v...
Mimic JavaScript Object/ Array behavior by allowing access to nonexistent indexes.
def get_value(obj, key, default=None): """ Mimic JavaScript Object/Array behavior by allowing access to nonexistent indexes. """ if isinstance(obj, dict): return obj.get(key, default) elif isinstance(obj, list): try: return obj[key] except IndexError: ...
Convert Undefined array entries to None ( null )
def clean_undefined(obj): """ Convert Undefined array entries to None (null) """ if isinstance(obj, list): return [ None if isinstance(item, Undefined) else item for item in obj ] if isinstance(obj, dict): for key in obj: obj[key] = clean_u...
Replace empty form values with None since the is_html_input () check in Field won t work after we convert to JSON. ( FIXME: What about allow_blank = True? )
def clean_empty_string(obj): """ Replace empty form values with None, since the is_html_input() check in Field won't work after we convert to JSON. (FIXME: What about allow_blank=True?) """ if obj == '': return None if isinstance(obj, list): return [ None if item ...
dict. items () but with a separate row for each value in a MultiValueDict
def get_all_items(obj): """ dict.items() but with a separate row for each value in a MultiValueDict """ if hasattr(obj, 'getlist'): items = [] for key in obj: for value in obj.getlist(key): items.append((key, value)) return items else: retu...
Create a transformation class object
def trans_new(name, transform, inverse, breaks=None, minor_breaks=None, _format=None, domain=(-np.inf, np.inf), doc='', **kwargs): """ Create a transformation class object Parameters ---------- name : str Name of the transformation transform : callable ``f(x)...
Create a log transform class for * base *
def log_trans(base=None, **kwargs): """ Create a log transform class for *base* Parameters ---------- base : float Base for the logarithm. If None, then the natural log is used. kwargs : dict Keyword arguments passed onto :func:`trans_new`. Should not include ...
Create a exponential transform class for * base *
def exp_trans(base=None, **kwargs): """ Create a exponential transform class for *base* This is inverse of the log transform. Parameters ---------- base : float Base of the logarithm kwargs : dict Keyword arguments passed onto :func:`trans_new`. Should not include ...
Boxcox Transformation
def boxcox_trans(p, **kwargs): """ Boxcox Transformation Parameters ---------- p : float Power parameter, commonly denoted by lower-case lambda in formulae kwargs : dict Keyword arguments passed onto :func:`trans_new`. Should not include the `transform` o...
Probability Transformation
def probability_trans(distribution, *args, **kwargs): """ Probability Transformation Parameters ---------- distribution : str Name of the distribution. Valid distributions are listed at :mod:`scipy.stats`. Any of the continuous or discrete distributions. args : tuple ...
Return a trans object
def gettrans(t): """ Return a trans object Parameters ---------- t : str | callable | type | trans name of transformation function Returns ------- out : trans """ obj = t # Make sure trans object is instantiated if isinstance(obj, str): name = '{}_trans'...
Calculate breaks in data space and return them in transformed space.
def breaks(self, limits): """ Calculate breaks in data space and return them in transformed space. Expects limits to be in *transform space*, this is the same space as that where the domain is specified. This method wraps around :meth:`breaks_` to ensure ...
Transform from date to a numerical format
def transform(x): """ Transform from date to a numerical format """ try: x = date2num(x) except AttributeError: # numpy datetime64 # This is not ideal because the operations do not # preserve the np.datetime64 type. May be need ...
Transform from Timeddelta to numerical format
def transform(x): """ Transform from Timeddelta to numerical format """ # microseconds try: x = np.array([_x.total_seconds()*10**6 for _x in x]) except TypeError: x = x.total_seconds()*10**6 return x
Transform to Timedelta from numerical format
def inverse(x): """ Transform to Timedelta from numerical format """ try: x = [datetime.timedelta(microseconds=i) for i in x] except TypeError: x = datetime.timedelta(microseconds=x) return x
Transform from Timeddelta to numerical format
def transform(x): """ Transform from Timeddelta to numerical format """ # nanoseconds try: x = np.array([_x.value for _x in x]) except TypeError: x = x.value return x
Transform to Timedelta from numerical format
def inverse(x): """ Transform to Timedelta from numerical format """ try: x = [pd.Timedelta(int(i)) for i in x] except TypeError: x = pd.Timedelta(int(x)) return x
Rescale numeric vector to have specified minimum and maximum.
def rescale(x, to=(0, 1), _from=None): """ Rescale numeric vector to have specified minimum and maximum. Parameters ---------- x : array_like | numeric 1D vector of values to manipulate. to : tuple output range (numeric vector of length two) _from : tuple input range...
Rescale numeric vector to have specified minimum midpoint and maximum.
def rescale_mid(x, to=(0, 1), _from=None, mid=0): """ Rescale numeric vector to have specified minimum, midpoint, and maximum. Parameters ---------- x : array_like | numeric 1D vector of values to manipulate. to : tuple output range (numeric vector of length two) _from :...
Rescale numeric vector to have specified maximum.
def rescale_max(x, to=(0, 1), _from=None): """ Rescale numeric vector to have specified maximum. Parameters ---------- x : array_like | numeric 1D vector of values to manipulate. to : tuple output range (numeric vector of length two) _from : tuple input range (numeri...
Truncate infinite values to a range.
def squish_infinite(x, range=(0, 1)): """ Truncate infinite values to a range. Parameters ---------- x : array_like Values that should have infinities squished. range : tuple The range onto which to squish the infinites. Must be of size 2. Returns ------- ou...
Squish values into range.
def squish(x, range=(0, 1), only_finite=True): """ Squish values into range. Parameters ---------- x : array_like Values that should have out of range values squished. range : tuple The range onto which to squish the values. only_finite: boolean When true, only squis...
Convert any values outside of range to a ** NULL ** type object.
def censor(x, range=(0, 1), only_finite=True): """ Convert any values outside of range to a **NULL** type object. Parameters ---------- x : array_like Values to manipulate range : tuple (min, max) giving desired output range only_finite : bool If True (the default), ...
Censor any values outside of range with None
def _censor_with(x, range, value=None): """ Censor any values outside of range with ``None`` """ return [val if range[0] <= val <= range[1] else value for val in x]
Determine if range of vector is close to zero.
def zero_range(x, tol=np.finfo(float).eps * 100): """ Determine if range of vector is close to zero. Parameters ---------- x : array_like | numeric Value(s) to check. If it is an array_like, it should be of length 2. tol : float Tolerance. Default tolerance is the `machi...
Expand a range with a multiplicative or additive constant
def expand_range(range, mul=0, add=0, zero_width=1): """ Expand a range with a multiplicative or additive constant Parameters ---------- range : tuple Range of data. Size 2. mul : int | float Multiplicative constant add : int | float | timedelta Additive constant ...
Expand a range with a multiplicative or additive constants
def expand_range_distinct(range, expand=(0, 0, 0, 0), zero_width=1): """ Expand a range with a multiplicative or additive constants Similar to :func:`expand_range` but both sides of the range expanded using different constants Parameters ---------- range : tuple Range of data. Size...
Append 2 extra breaks at either end of major
def _extend_breaks(self, major): """ Append 2 extra breaks at either end of major If breaks of transform space are non-equidistant, :func:`minor_breaks` add minor breaks beyond the first and last major breaks. The solutions is to extend those breaks (in transformed space...
Determine good units for representing a sequence of timedeltas
def best_units(self, sequence): """ Determine good units for representing a sequence of timedeltas """ # Read # [(0.9, 's'), # (9, 'm)] # as, break ranges between 0.9 seconds (inclusive) # and 9 minutes are represented in seconds. And so on. t...
Minimum and Maximum to use for computing breaks
def scaled_limits(self): """ Minimum and Maximum to use for computing breaks """ _min = self.limits[0]/self.factor _max = self.limits[1]/self.factor return _min, _max
Convert sequence of numerics to timedelta
def numeric_to_timedelta(self, numerics): """ Convert sequence of numerics to timedelta """ if self.package == 'pandas': return [self.type(int(x*self.factor), units='ns') for x in numerics] else: return [self.type(seconds=x*self.factor)...
Convert timedelta to a number corresponding to the appropriate units. The appropriate units are those determined with the object is initialised.
def to_numeric(self, td): """ Convert timedelta to a number corresponding to the appropriate units. The appropriate units are those determined with the object is initialised. """ if self.package == 'pandas': return td.value/NANOSECONDS[self.units] else...
Round to multiple of any number.
def round_any(x, accuracy, f=np.round): """ Round to multiple of any number. """ if not hasattr(x, 'dtype'): x = np.asarray(x) return f(x / accuracy) * accuracy
Return the minimum and maximum of x
def min_max(x, na_rm=False, finite=True): """ Return the minimum and maximum of x Parameters ---------- x : array_like Sequence na_rm : bool Whether to remove ``nan`` values. finite : bool Whether to consider only finite values. Returns ------- out : tup...
Return a vector of the positions of ( first ) matches of its first argument in its second.
def match(v1, v2, nomatch=-1, incomparables=None, start=0): """ Return a vector of the positions of (first) matches of its first argument in its second. Parameters ---------- v1: array_like Values to be matched v2: array_like Values to be matched against nomatch: int ...
Return the precision of x
def precision(x): """ Return the precision of x Parameters ---------- x : array_like | numeric Value(s) whose for which to compute the precision. Returns ------- out : numeric The precision of ``x`` or that the values in ``x``. Notes ----- The precision is ...
Sort elements of multiple types
def multitype_sort(a): """ Sort elements of multiple types x is assumed to contain elements of different types, such that plain sort would raise a `TypeError`. Parameters ---------- a : array-like Array of items to be sorted Returns ------- out : list Items sor...
Return nearest long integer to x
def nearest_int(x): """ Return nearest long integer to x """ if x == 0: return np.int64(0) elif x > 0: return np.int64(x + 0.5) else: return np.int64(x - 0.5)
Check if value is close to an integer
def is_close_to_int(x): """ Check if value is close to an integer Parameters ---------- x : float Numeric value to check Returns ------- out : bool """ if not np.isfinite(x): return False return abs(x - nearest_int(x)) < 1e-10
Return true if range is approximately in same order of magnitude
def same_log10_order_of_magnitude(x, delta=0.1): """ Return true if range is approximately in same order of magnitude For example these sequences are in the same order of magnitude: - [1, 8, 5] # [1, 10) - [35, 20, 80] # [10 100) - [232, 730] # [100, 1000) Parameters ...
Helper to format and tidy up
def _format(formatter, x): """ Helper to format and tidy up """ # For MPL to play nice formatter.create_dummy_axis() # For sensible decimal places formatter.set_locs([val for val in x if ~np.isnan(val)]) try: oom = int(formatter.orderOfMagnitude) except AttributeError: ...
Make all labels uniform in format and remove redundant zeros for labels in exponential format.
def _tidyup_labels(self, labels): """ Make all labels uniform in format and remove redundant zeros for labels in exponential format. Parameters ---------- labels : list-like Labels to be tidied. Returns ------- out : list-like ...
Get a set of evenly spaced colors in HLS hue space.
def hls_palette(n_colors=6, h=.01, l=.6, s=.65): """ Get a set of evenly spaced colors in HLS hue space. h, l, and s should be between 0 and 1 Parameters ---------- n_colors : int number of colors in the palette h : float first hue l : float lightness s : f...
Get a set of evenly spaced colors in HUSL hue space.
def husl_palette(n_colors=6, h=.01, s=.9, l=.65): """ Get a set of evenly spaced colors in HUSL hue space. h, s, and l should be between 0 and 1 Parameters ---------- n_colors : int number of colors in the palette h : float first hue s : float saturation l ...
Point area palette ( continuous ).
def area_pal(range=(1, 6)): """ Point area palette (continuous). Parameters ---------- range : tuple Numeric vector of length two, giving range of possible sizes. Should be greater than 0. Returns ------- out : function Palette function that takes a sequence of ...
Point area palette ( continuous ) with area proportional to value.
def abs_area(max): """ Point area palette (continuous), with area proportional to value. Parameters ---------- max : float A number representing the maximum size Returns ------- out : function Palette function that takes a sequence of values in the range ``[0, 1...
Utility for creating continuous grey scale palette
def grey_pal(start=0.2, end=0.8): """ Utility for creating continuous grey scale palette Parameters ---------- start : float grey value at low end of palette end : float grey value at high end of palette Returns ------- out : function Continuous color palett...
Utility for making hue palettes for color schemes.
def hue_pal(h=.01, l=.6, s=.65, color_space='hls'): """ Utility for making hue palettes for color schemes. Parameters ---------- h : float first hue. In the [0, 1] range l : float lightness. In the [0, 1] range s : float saturation. In the [0, 1] range color_spac...
Utility for making a brewer palette
def brewer_pal(type='seq', palette=1): """ Utility for making a brewer palette Parameters ---------- type : 'sequential' | 'qualitative' | 'diverging' Type of palette. Sequential, Qualitative or Diverging. The following abbreviations may be used, ``seq``, ``qual`` or ``div``...
Map values in the range [ 0 1 ] onto colors
def ratios_to_colors(values, colormap): """ Map values in the range [0, 1] onto colors Parameters ---------- values : array_like | float Numeric(s) in the range [0, 1] colormap : cmap Matplotlib colormap to use for the mapping Returns ------- out : list | float ...
Create a n color gradient palette
def gradient_n_pal(colors, values=None, name='gradientn'): """ Create a n color gradient palette Parameters ---------- colors : list list of colors values : list, optional list of points in the range [0, 1] at which to place each color. Must be the same size as `...
Create a continuous palette using an MPL colormap
def cmap_pal(name=None, lut=None): """ Create a continuous palette using an MPL colormap Parameters ---------- name : str Name of colormap lut : None | int This is the number of entries desired in the lookup table. Default is ``None``, leave it up Matplotlib. Return...
Create a discrete palette using an MPL Listed colormap
def cmap_d_pal(name=None, lut=None): """ Create a discrete palette using an MPL Listed colormap Parameters ---------- name : str Name of colormap lut : None | int This is the number of entries desired in the lookup table. Default is ``None``, leave it up Matplotlib. ...
Create a palette that desaturate a color by some proportion
def desaturate_pal(color, prop, reverse=False): """ Create a palette that desaturate a color by some proportion Parameters ---------- color : matplotlib color hex, rgb-tuple, or html color name prop : float saturation channel of color will be multiplied by this value ...
Create a palette from a list of values
def manual_pal(values): """ Create a palette from a list of values Parameters ---------- values : sequence Values that will be returned by the palette function. Returns ------- out : function A function palette that takes a single :class:`int` parameter ``n`` an...
Utility for creating continuous palette from the cubehelix system.
def cubehelix_pal(start=0, rot=.4, gamma=1.0, hue=0.8, light=.85, dark=.15, reverse=False): """ Utility for creating continuous palette from the cubehelix system. This produces a colormap with linearly-decreasing (or increasing) brightness. That means that information will be preserve...
Scale data continuously
def apply(cls, x, palette, na_value=None, trans=None): """ Scale data continuously Parameters ---------- x : array_like Continuous values to scale palette : callable ``f(x)`` Palette to use na_value : object Value to use for mi...
Train a continuous scale
def train(cls, new_data, old=None): """ Train a continuous scale Parameters ---------- new_data : array_like New values old : array_like Old range. Most likely a tuple of length 2. Returns ------- out : tuple L...
Map values to a continuous palette
def map(cls, x, palette, limits, na_value=None, oob=censor): """ Map values to a continuous palette Parameters ---------- x : array_like Continuous values to scale palette : callable ``f(x)`` palette to use na_value : object Va...
Train a continuous scale
def train(cls, new_data, old=None, drop=False, na_rm=False): """ Train a continuous scale Parameters ---------- new_data : array_like New values old : array_like Old range. List of values known to the scale. drop : bool Whether...
Map values to a discrete palette
def map(cls, x, palette, limits, na_value=None): """ Map values to a discrete palette Parameters ---------- palette : callable ``f(x)`` palette to use x : array_like Continuous values to scale na_value : object Value to use for...
Register a parser for a attribute type.
def parse(type: Type): """ Register a parser for a attribute type. Parsers will be used to parse `str` type objects from either the commandline arguments or environment variables. Args: type: the type the decorated function will be responsible for pa...
Used to patch cookiecutter s run_hook function.
def _patched_run_hook(hook_name, project_dir, context): """Used to patch cookiecutter's ``run_hook`` function. This patched version ensures that the temple.yaml file is created before any cookiecutter hooks are executed """ if hook_name == 'post_gen_project': with temple.utils.cd(project_di...
Uses cookiecutter to generate files for the project.
def _generate_files(repo_dir, config, template, version): """Uses cookiecutter to generate files for the project. Monkeypatches cookiecutter's "run_hook" to ensure that the temple.yaml file is generated before any hooks run. This is important to ensure that hooks can also perform any actions involving ...
Sets up a new project from a template
def setup(template, version=None): """Sets up a new project from a template Note that the `temple.constants.TEMPLE_ENV_VAR` is set to 'setup' during the duration of this function. Args: template (str): The git SSH path to a template version (str, optional): The version of the template ...
Parses Github s link header for pagination.
def _parse_link_header(headers): """Parses Github's link header for pagination. TODO eventually use a github client for this """ links = {} if 'link' in headers: link_headers = headers['link'].split(', ') for link_header in link_headers: (url, rel) = link_header.split(';...
Performs a Github API code search
def _code_search(query, github_user=None): """Performs a Github API code search Args: query (str): The query sent to Github's code search github_user (str, optional): The Github user being searched in the query string Returns: dict: A dictionary of repository information keyed on t...
Lists all temple templates and packages associated with those templates
def ls(github_user, template=None): """Lists all temple templates and packages associated with those templates If ``template`` is None, returns the available templates for the configured Github org. If ``template`` is a Github path to a template, returns all projects spun up with that template. ...
Update package with latest template. Must be inside of the project folder to run.
def update(check, enter_parameters, version): """ Update package with latest template. Must be inside of the project folder to run. Using "-e" will prompt for re-entering the template parameters again even if the project is up to date. Use "-v" to update to a particular version of a template. ...
List packages created with temple. Enter a github user or organization to list all templates under the user or org. Using a template path as the second argument will list all projects that have been started with that template.
def ls(github_user, template, long_format): """ List packages created with temple. Enter a github user or organization to list all templates under the user or org. Using a template path as the second argument will list all projects that have been started with that template. Use "-l" to print th...
Switch a project s template to a different template.
def switch(template, version): """ Switch a project's template to a different template. """ temple.update.update(new_template=template, new_version=version)
Returns True if inside a git repo False otherwise
def _in_git_repo(): """Returns True if inside a git repo, False otherwise""" ret = temple.utils.shell('git rev-parse', stderr=subprocess.DEVNULL, check=False) return ret.returncode == 0
Return True if the target branch exists.
def _has_branch(branch): """Return True if the target branch exists.""" ret = temple.utils.shell('git rev-parse --verify {}'.format(branch), stderr=subprocess.DEVNULL, stdout=subprocess.DEVNULL, check=False) return ret.re...
Raises ExistingBranchError if the specified branch exists.
def not_has_branch(branch): """Raises `ExistingBranchError` if the specified branch exists.""" if _has_branch(branch): msg = 'Cannot proceed while {} branch exists; remove and try again.'.format(branch) raise temple.exceptions.ExistingBranchError(msg)
Raises InvalidEnvironmentError when one isnt set
def has_env_vars(*env_vars): """Raises `InvalidEnvironmentError` when one isnt set""" for env_var in env_vars: if not os.environ.get(env_var): msg = ( 'Must set {} environment variable. View docs for setting up environment at {}' ).format(env_var, temple.constants...
Raises InvalidTempleProjectError if repository is not a temple project
def is_temple_project(): """Raises `InvalidTempleProjectError` if repository is not a temple project""" if not os.path.exists(temple.constants.TEMPLE_CONFIG_FILE): msg = 'No {} file found in repository.'.format(temple.constants.TEMPLE_CONFIG_FILE) raise temple.exceptions.InvalidTempleProjectErro...
Determine the current git branch
def _get_current_branch(): """Determine the current git branch""" result = temple.utils.shell('git rev-parse --abbrev-ref HEAD', stdout=subprocess.PIPE) return result.stdout.decode('utf8').strip()
Cleans up temporary resources
def clean(): """Cleans up temporary resources Tries to clean up: 1. The temporary update branch used during ``temple update`` 2. The primary update branch used during ``temple update`` """ temple.check.in_git_repo() current_branch = _get_current_branch() update_branch = temple.constan...
Given an old version and new version check if the cookiecutter. json files have changed
def _cookiecutter_configs_have_changed(template, old_version, new_version): """Given an old version and new version, check if the cookiecutter.json files have changed When the cookiecutter.json files change, it means the user will need to be prompted for new context Args: template (str): The g...
Apply a template to a temporary directory and then copy results to target.
def _apply_template(template, target, *, checkout, extra_context): """Apply a template to a temporary directory and then copy results to target.""" with tempfile.TemporaryDirectory() as tempdir: repo_dir = cc_main.cookiecutter( template, checkout=checkout, no_input=Tr...
Checks if a temple project is up to date with the repo
def up_to_date(version=None): """Checks if a temple project is up to date with the repo Note that the `temple.constants.TEMPLE_ENV_VAR` is set to 'update' for the duration of this function. Args: version (str, optional): Update against this git SHA or branch of the template Returns: ...
Given two templates and their respective versions return True if a new cookiecutter config needs to be obtained from the user
def _needs_new_cc_config_for_update(old_template, old_version, new_template, new_version): """ Given two templates and their respective versions, return True if a new cookiecutter config needs to be obtained from the user """ if old_template != new_template: return True else: ret...
Updates the temple project to the latest template
def update(old_template=None, old_version=None, new_template=None, new_version=None, enter_parameters=False): """Updates the temple project to the latest template Proceeeds in the following steps: 1. Ensure we are inside the project repository 2. Obtain the latest version of the package tem...
Runs a subprocess shell with check = True by default
def shell(cmd, check=True, stdin=None, stdout=None, stderr=None): """Runs a subprocess shell with check=True by default""" return subprocess.run(cmd, shell=True, check=check, stdin=stdin, stdout=stdout, stderr=stderr)