CoolFace
Datasetpublic

SciCodePile/SciCode-Domain-Code

DATA1: Domain-Specific Code Dataset Dataset Overview DATA1 is a large-scale domain-specific code dataset focusing on code samples from interdisciplinary fields such as biology, chemistry, materials science, and related areas. The dataset is collected and organized from GitHub repositories, covering 178 different domain topics with over 1.1 billion lines of code. Dataset Statistics Total Datasets: 178 CSV files Total Data Size: ~115 GB Total Lines… See the full description on the dataset page: https://huggingface.co/datasets/SciCodePile/SciCode-Domain-Code.

sourceHugging Faceapache-2.0updated 6mo agoView on Hugging Face
4likes2.4kdownloads
dataset_Biophysics.csv73442 linesDownload Raw Back to data
1"keyword","repo_name","file_path","file_extension","file_size","line_count","content","language"
2"Biophysics","tritemio/pycorrelate","setup.py",".py","1272","45","#!/usr/bin/env python3# -*- coding: utf-8 -*-4 5""""""The setup script.""""""6 7from setuptools import setup, find_packages8import versioneer9 10with open('README.rst') as readme_file:11    readme = readme_file.read()12 13with open('HISTORY.rst') as history_file:14    history = history_file.read()15 16requirements = [17    'numpy',18    'numba',19]20 21setup(22    name='pycorrelate',23    version=versioneer.get_version(),24    cmdclass=versioneer.get_cmdclass(),25    description=""Fast and accurate timestamps correlation in python."",26    long_description=readme + '\n\n' + history,27    author=""Antonino Ingargiola"",28    author_email='tritemio@gmail.com',29    url='https://github.com/tritemio/pycorrelate',30    packages=find_packages(include=['pycorrelate']),31    include_package_data=True,32    install_requires=requirements,33    license=""GNU General Public License v3"",34    zip_safe=False,35    keywords='pycorrelate',36    classifiers=[37        'Development Status :: 2 - Pre-Alpha',38        'Intended Audience :: Developers',39        'License :: OSI Approved :: GNU General Public License v3 (GPLv3)',40        'Natural Language :: English',41        'Programming Language :: Python :: 3',42        'Programming Language :: Python :: 3.5',43        'Programming Language :: Python :: 3.6',44    ],45)46","Python"
47"Biophysics","tritemio/pycorrelate","versioneer.py",".py","68611","1823","48# Version: 0.1849 50""""""The Versioneer - like a rocketeer, but for versions.51 52The Versioneer53==============54 55* like a rocketeer, but for versions!56* https://github.com/warner/python-versioneer57* Brian Warner58* License: Public Domain59* Compatible With: python2.6, 2.7, 3.2, 3.3, 3.4, 3.5, 3.6, and pypy60* [![Latest Version]61(https://pypip.in/version/versioneer/badge.svg?style=flat)62](https://pypi.python.org/pypi/versioneer/)63* [![Build Status]64(https://travis-ci.org/warner/python-versioneer.png?branch=master)65](https://travis-ci.org/warner/python-versioneer)66 67This is a tool for managing a recorded version number in distutils-based68python projects. The goal is to remove the tedious and error-prone ""update69the embedded version string"" step from your release process. Making a new70release should be as easy as recording a new tag in your version-control71system, and maybe making new tarballs.72 73 74## Quick Install75 76* `pip install versioneer` to somewhere to your $PATH77* add a `[versioneer]` section to your setup.cfg (see below)78* run `versioneer install` in your source tree, commit the results79 80## Version Identifiers81 82Source trees come from a variety of places:83 84* a version-control system checkout (mostly used by developers)85* a nightly tarball, produced by build automation86* a snapshot tarball, produced by a web-based VCS browser, like github's87  ""tarball from tag"" feature88* a release tarball, produced by ""setup.py sdist"", distributed through PyPI89 90Within each source tree, the version identifier (either a string or a number,91this tool is format-agnostic) can come from a variety of places:92 93* ask the VCS tool itself, e.g. ""git describe"" (for checkouts), which knows94  about recent ""tags"" and an absolute revision-id95* the name of the directory into which the tarball was unpacked96* an expanded VCS keyword ($Id$, etc)97* a `_version.py` created by some earlier build step98 99For released software, the version identifier is closely related to a VCS100tag. Some projects use tag names that include more than just the version101string (e.g. ""myproject-1.2"" instead of just ""1.2""), in which case the tool102needs to strip the tag prefix to extract the version identifier. For103unreleased software (between tags), the version identifier should provide104enough information to help developers recreate the same tree, while also105giving them an idea of roughly how old the tree is (after version 1.2, before106version 1.3). Many VCS systems can report a description that captures this,107for example `git describe --tags --dirty --always` reports things like108""0.7-1-g574ab98-dirty"" to indicate that the checkout is one revision past the1090.7 tag, has a unique revision id of ""574ab98"", and is ""dirty"" (it has110uncommitted changes.111 112The version identifier is used for multiple purposes:113 114* to allow the module to self-identify its version: `myproject.__version__`115* to choose a name and prefix for a 'setup.py sdist' tarball116 117## Theory of Operation118 119Versioneer works by adding a special `_version.py` file into your source120tree, where your `__init__.py` can import it. This `_version.py` knows how to121dynamically ask the VCS tool for version information at import time.122 123`_version.py` also contains `$Revision$` markers, and the installation124process marks `_version.py` to have this marker rewritten with a tag name125during the `git archive` command. As a result, generated tarballs will126contain enough information to get the proper version.127 128To allow `setup.py` to compute a version too, a `versioneer.py` is added to129the top level of your source tree, next to `setup.py` and the `setup.cfg`130that configures it. This overrides several distutils/setuptools commands to131compute the version when invoked, and changes `setup.py build` and `setup.py132sdist` to replace `_version.py` with a small static file that contains just133the generated version data.134 135## Installation136 137See [INSTALL.md](./INSTALL.md) for detailed installation instructions.138 139## Version-String Flavors140 141Code which uses Versioneer can learn about its version string at runtime by142importing `_version` from your main `__init__.py` file and running the143`get_versions()` function. From the ""outside"" (e.g. in `setup.py`), you can144import the top-level `versioneer.py` and run `get_versions()`.145 146Both functions return a dictionary with different flavors of version147information:148 149* `['version']`: A condensed version string, rendered using the selected150  style. This is the most commonly used value for the project's version151  string. The default ""pep440"" style yields strings like `0.11`,152  `0.11+2.g1076c97`, or `0.11+2.g1076c97.dirty`. See the ""Styles"" section153  below for alternative styles.154 155* `['full-revisionid']`: detailed revision identifier. For Git, this is the156  full SHA1 commit id, e.g. ""1076c978a8d3cfc70f408fe5974aa6c092c949ac"".157 158* `['date']`: Date and time of the latest `HEAD` commit. For Git, it is the159  commit date in ISO 8601 format. This will be None if the date is not160  available.161 162* `['dirty']`: a boolean, True if the tree has uncommitted changes. Note that163  this is only accurate if run in a VCS checkout, otherwise it is likely to164  be False or None165 166* `['error']`: if the version string could not be computed, this will be set167  to a string describing the problem, otherwise it will be None. It may be168  useful to throw an exception in setup.py if this is set, to avoid e.g.169  creating tarballs with a version string of ""unknown"".170 171Some variants are more useful than others. Including `full-revisionid` in a172bug report should allow developers to reconstruct the exact code being tested173(or indicate the presence of local changes that should be shared with the174developers). `version` is suitable for display in an ""about"" box or a CLI175`--version` output: it can be easily compared against release notes and lists176of bugs fixed in various releases.177 178The installer adds the following text to your `__init__.py` to place a basic179version in `YOURPROJECT.__version__`:180 181    from ._version import get_versions182    __version__ = get_versions()['version']183    del get_versions184 185## Styles186 187The setup.cfg `style=` configuration controls how the VCS information is188rendered into a version string.189 190The default style, ""pep440"", produces a PEP440-compliant string, equal to the191un-prefixed tag name for actual releases, and containing an additional ""local192version"" section with more detail for in-between builds. For Git, this is193TAG[+DISTANCE.gHEX[.dirty]] , using information from `git describe --tags194--dirty --always`. For example ""0.11+2.g1076c97.dirty"" indicates that the195tree is like the ""1076c97"" commit but has uncommitted changes ("".dirty""), and196that this commit is two revisions (""+2"") beyond the ""0.11"" tag. For released197software (exactly equal to a known tag), the identifier will only contain the198stripped tag, e.g. ""0.11"".199 200Other styles are available. See [details.md](details.md) in the Versioneer201source tree for descriptions.202 203## Debugging204 205Versioneer tries to avoid fatal errors: if something goes wrong, it will tend206to return a version of ""0+unknown"". To investigate the problem, run `setup.py207version`, which will run the version-lookup code in a verbose mode, and will208display the full contents of `get_versions()` (including the `error` string,209which may help identify what went wrong).210 211## Known Limitations212 213Some situations are known to cause problems for Versioneer. This details the214most significant ones. More can be found on Github215[issues page](https://github.com/warner/python-versioneer/issues).216 217### Subprojects218 219Versioneer has limited support for source trees in which `setup.py` is not in220the root directory (e.g. `setup.py` and `.git/` are *not* siblings). The are221two common reasons why `setup.py` might not be in the root:222 223* Source trees which contain multiple subprojects, such as224  [Buildbot](https://github.com/buildbot/buildbot), which contains both225  ""master"" and ""slave"" subprojects, each with their own `setup.py`,226  `setup.cfg`, and `tox.ini`. Projects like these produce multiple PyPI227  distributions (and upload multiple independently-installable tarballs).228* Source trees whose main purpose is to contain a C library, but which also229  provide bindings to Python (and perhaps other langauges) in subdirectories.230 231Versioneer will look for `.git` in parent directories, and most operations232should get the right version string. However `pip` and `setuptools` have bugs233and implementation details which frequently cause `pip install .` from a234subproject directory to fail to find a correct version string (so it usually235defaults to `0+unknown`).236 237`pip install --editable .` should work correctly. `setup.py install` might238work too.239 240Pip-8.1.1 is known to have this problem, but hopefully it will get fixed in241some later version.242 243[Bug #38](https://github.com/warner/python-versioneer/issues/38) is tracking244this issue. The discussion in245[PR #61](https://github.com/warner/python-versioneer/pull/61) describes the246issue from the Versioneer side in more detail.247[pip PR#3176](https://github.com/pypa/pip/pull/3176) and248[pip PR#3615](https://github.com/pypa/pip/pull/3615) contain work to improve249pip to let Versioneer work correctly.250 251Versioneer-0.16 and earlier only looked for a `.git` directory next to the252`setup.cfg`, so subprojects were completely unsupported with those releases.253 254### Editable installs with setuptools <= 18.5255 256`setup.py develop` and `pip install --editable .` allow you to install a257project into a virtualenv once, then continue editing the source code (and258test) without re-installing after every change.259 260""Entry-point scripts"" (`setup(entry_points={""console_scripts"": ..})`) are a261convenient way to specify executable scripts that should be installed along262with the python package.263 264These both work as expected when using modern setuptools. When using265setuptools-18.5 or earlier, however, certain operations will cause266`pkg_resources.DistributionNotFound` errors when running the entrypoint267script, which must be resolved by re-installing the package. This happens268when the install happens with one version, then the egg_info data is269regenerated while a different version is checked out. Many setup.py commands270cause egg_info to be rebuilt (including `sdist`, `wheel`, and installing into271a different virtualenv), so this can be surprising.272 273[Bug #83](https://github.com/warner/python-versioneer/issues/83) describes274this one, but upgrading to a newer version of setuptools should probably275resolve it.276 277### Unicode version strings278 279While Versioneer works (and is continually tested) with both Python 2 and280Python 3, it is not entirely consistent with bytes-vs-unicode distinctions.281Newer releases probably generate unicode version strings on py2. It's not282clear that this is wrong, but it may be surprising for applications when then283write these strings to a network connection or include them in bytes-oriented284APIs like cryptographic checksums.285 286[Bug #71](https://github.com/warner/python-versioneer/issues/71) investigates287this question.288 289 290## Updating Versioneer291 292To upgrade your project to a new release of Versioneer, do the following:293 294* install the new Versioneer (`pip install -U versioneer` or equivalent)295* edit `setup.cfg`, if necessary, to include any new configuration settings296  indicated by the release notes. See [UPGRADING](./UPGRADING.md) for details.297* re-run `versioneer install` in your source tree, to replace298  `SRC/_version.py`299* commit any changed files300 301## Future Directions302 303This tool is designed to make it easily extended to other version-control304systems: all VCS-specific components are in separate directories like305src/git/ . The top-level `versioneer.py` script is assembled from these306components by running make-versioneer.py . In the future, make-versioneer.py307will take a VCS name as an argument, and will construct a version of308`versioneer.py` that is specific to the given VCS. It might also take the309configuration arguments that are currently provided manually during310installation by editing setup.py . Alternatively, it might go the other311direction and include code from all supported VCS systems, reducing the312number of intermediate scripts.313 314 315## License316 317To make Versioneer easier to embed, all its code is dedicated to the public318domain. The `_version.py` that it creates is also in the public domain.319Specifically, both are released under the Creative Commons ""Public Domain320Dedication"" license (CC0-1.0), as described in321https://creativecommons.org/publicdomain/zero/1.0/ .322 323""""""324 325from __future__ import print_function326try:327    import configparser328except ImportError:329    import ConfigParser as configparser330import errno331import json332import os333import re334import subprocess335import sys336 337 338class VersioneerConfig:339    """"""Container for Versioneer configuration parameters.""""""340 341 342def get_root():343    """"""Get the project root directory.344 345    We require that all commands are run from the project root, i.e. the346    directory that contains setup.py, setup.cfg, and versioneer.py .347    """"""348    root = os.path.realpath(os.path.abspath(os.getcwd()))349    setup_py = os.path.join(root, ""setup.py"")350    versioneer_py = os.path.join(root, ""versioneer.py"")351    if not (os.path.exists(setup_py) or os.path.exists(versioneer_py)):352        # allow 'python path/to/setup.py COMMAND'353        root = os.path.dirname(os.path.realpath(os.path.abspath(sys.argv[0])))354        setup_py = os.path.join(root, ""setup.py"")355        versioneer_py = os.path.join(root, ""versioneer.py"")356    if not (os.path.exists(setup_py) or os.path.exists(versioneer_py)):357        err = (""Versioneer was unable to run the project root directory. ""358               ""Versioneer requires setup.py to be executed from ""359               ""its immediate directory (like 'python setup.py COMMAND'), ""360               ""or in a way that lets it use sys.argv[0] to find the root ""361               ""(like 'python path/to/setup.py COMMAND')."")362        raise VersioneerBadRootError(err)363    try:364        # Certain runtime workflows (setup.py install/develop in a setuptools365        # tree) execute all dependencies in a single python process, so366        # ""versioneer"" may be imported multiple times, and python's shared367        # module-import table will cache the first one. So we can't use368        # os.path.dirname(__file__), as that will find whichever369        # versioneer.py was first imported, even in later projects.370        me = os.path.realpath(os.path.abspath(__file__))371        me_dir = os.path.normcase(os.path.splitext(me)[0])372        vsr_dir = os.path.normcase(os.path.splitext(versioneer_py)[0])373        if me_dir != vsr_dir:374            print(""Warning: build in %s is using versioneer.py from %s""375                  % (os.path.dirname(me), versioneer_py))376    except NameError:377        pass378    return root379 380 381def get_config_from_root(root):382    """"""Read the project setup.cfg file to determine Versioneer config.""""""383    # This might raise EnvironmentError (if setup.cfg is missing), or384    # configparser.NoSectionError (if it lacks a [versioneer] section), or385    # configparser.NoOptionError (if it lacks ""VCS=""). See the docstring at386    # the top of versioneer.py for instructions on writing your setup.cfg .387    setup_cfg = os.path.join(root, ""setup.cfg"")388    parser = configparser.SafeConfigParser()389    with open(setup_cfg, ""r"") as f:390        parser.readfp(f)391    VCS = parser.get(""versioneer"", ""VCS"")  # mandatory392 393    def get(parser, name):394        if parser.has_option(""versioneer"", name):395            return parser.get(""versioneer"", name)396        return None397    cfg = VersioneerConfig()398    cfg.VCS = VCS399    cfg.style = get(parser, ""style"") or """"400    cfg.versionfile_source = get(parser, ""versionfile_source"")401    cfg.versionfile_build = get(parser, ""versionfile_build"")402    cfg.tag_prefix = get(parser, ""tag_prefix"")403    if cfg.tag_prefix in (""''"", '""""'):404        cfg.tag_prefix = """"405    cfg.parentdir_prefix = get(parser, ""parentdir_prefix"")406    cfg.verbose = get(parser, ""verbose"")407    return cfg408 409 410class NotThisMethod(Exception):411    """"""Exception raised if a method is not valid for the current scenario.""""""412 413 414# these dictionaries contain VCS-specific tools415LONG_VERSION_PY = {}416HANDLERS = {}417 418 419def register_vcs_handler(vcs, method):  # decorator420    """"""Decorator to mark a method as the handler for a particular VCS.""""""421    def decorate(f):422        """"""Store f in HANDLERS[vcs][method].""""""423        if vcs not in HANDLERS:424            HANDLERS[vcs] = {}425        HANDLERS[vcs][method] = f426        return f427    return decorate428 429 430def run_command(commands, args, cwd=None, verbose=False, hide_stderr=False,431                env=None):432    """"""Call the given command(s).""""""433    assert isinstance(commands, list)434    p = None435    for c in commands:436        try:437            dispcmd = str([c] + args)438            # remember shell=False, so use git.cmd on windows, not just git439            p = subprocess.Popen([c] + args, cwd=cwd, env=env,440                                 stdout=subprocess.PIPE,441                                 stderr=(subprocess.PIPE if hide_stderr442                                         else None))443            break444        except EnvironmentError:445            e = sys.exc_info()[1]446            if e.errno == errno.ENOENT:447                continue448            if verbose:449                print(""unable to run %s"" % dispcmd)450                print(e)451            return None, None452    else:453        if verbose:454            print(""unable to find command, tried %s"" % (commands,))455        return None, None456    stdout = p.communicate()[0].strip()457    if sys.version_info[0] >= 3:458        stdout = stdout.decode()459    if p.returncode != 0:460        if verbose:461            print(""unable to run %s (error)"" % dispcmd)462            print(""stdout was %s"" % stdout)463        return None, p.returncode464    return stdout, p.returncode465 466 467LONG_VERSION_PY['git'] = '''468# This file helps to compute a version number in source trees obtained from469# git-archive tarball (such as those provided by githubs download-from-tag470# feature). Distribution tarballs (built by setup.py sdist) and build471# directories (produced by setup.py build) will contain a much shorter file472# that just contains the computed version number.473 474# This file is released into the public domain. Generated by475# versioneer-0.18 (https://github.com/warner/python-versioneer)476 477""""""Git implementation of _version.py.""""""478 479import errno480import os481import re482import subprocess483import sys484 485 486def get_keywords():487    """"""Get the keywords needed to look up the version information.""""""488    # these strings will be replaced by git during git-archive.489    # setup.py/versioneer.py will grep for the variable names, so they must490    # each be defined on a line of their own. _version.py will just call491    # get_keywords().492    git_refnames = ""%(DOLLAR)sFormat:%%d%(DOLLAR)s""493    git_full = ""%(DOLLAR)sFormat:%%H%(DOLLAR)s""494    git_date = ""%(DOLLAR)sFormat:%%ci%(DOLLAR)s""495    keywords = {""refnames"": git_refnames, ""full"": git_full, ""date"": git_date}496    return keywords497 498 499class VersioneerConfig:500    """"""Container for Versioneer configuration parameters.""""""501 502 503def get_config():504    """"""Create, populate and return the VersioneerConfig() object.""""""505    # these strings are filled in when 'setup.py versioneer' creates506    # _version.py507    cfg = VersioneerConfig()508    cfg.VCS = ""git""509    cfg.style = ""%(STYLE)s""510    cfg.tag_prefix = ""%(TAG_PREFIX)s""511    cfg.parentdir_prefix = ""%(PARENTDIR_PREFIX)s""512    cfg.versionfile_source = ""%(VERSIONFILE_SOURCE)s""513    cfg.verbose = False514    return cfg515 516 517class NotThisMethod(Exception):518    """"""Exception raised if a method is not valid for the current scenario.""""""519 520 521LONG_VERSION_PY = {}522HANDLERS = {}523 524 525def register_vcs_handler(vcs, method):  # decorator526    """"""Decorator to mark a method as the handler for a particular VCS.""""""527    def decorate(f):528        """"""Store f in HANDLERS[vcs][method].""""""529        if vcs not in HANDLERS:530            HANDLERS[vcs] = {}531        HANDLERS[vcs][method] = f532        return f533    return decorate534 535 536def run_command(commands, args, cwd=None, verbose=False, hide_stderr=False,537                env=None):538    """"""Call the given command(s).""""""539    assert isinstance(commands, list)540    p = None541    for c in commands:542        try:543            dispcmd = str([c] + args)544            # remember shell=False, so use git.cmd on windows, not just git545            p = subprocess.Popen([c] + args, cwd=cwd, env=env,546                                 stdout=subprocess.PIPE,547                                 stderr=(subprocess.PIPE if hide_stderr548                                         else None))549            break550        except EnvironmentError:551            e = sys.exc_info()[1]552            if e.errno == errno.ENOENT:553                continue554            if verbose:555                print(""unable to run %%s"" %% dispcmd)556                print(e)557            return None, None558    else:559        if verbose:560            print(""unable to find command, tried %%s"" %% (commands,))561        return None, None562    stdout = p.communicate()[0].strip()563    if sys.version_info[0] >= 3:564        stdout = stdout.decode()565    if p.returncode != 0:566        if verbose:567            print(""unable to run %%s (error)"" %% dispcmd)568            print(""stdout was %%s"" %% stdout)569        return None, p.returncode570    return stdout, p.returncode571 572 573def versions_from_parentdir(parentdir_prefix, root, verbose):574    """"""Try to determine the version from the parent directory name.575 576    Source tarballs conventionally unpack into a directory that includes both577    the project name and a version string. We will also support searching up578    two directory levels for an appropriately named parent directory579    """"""580    rootdirs = []581 582    for i in range(3):583        dirname = os.path.basename(root)584        if dirname.startswith(parentdir_prefix):585            return {""version"": dirname[len(parentdir_prefix):],586                    ""full-revisionid"": None,587                    ""dirty"": False, ""error"": None, ""date"": None}588        else:589            rootdirs.append(root)590            root = os.path.dirname(root)  # up a level591 592    if verbose:593        print(""Tried directories %%s but none started with prefix %%s"" %%594              (str(rootdirs), parentdir_prefix))595    raise NotThisMethod(""rootdir doesn't start with parentdir_prefix"")596 597 598@register_vcs_handler(""git"", ""get_keywords"")599def git_get_keywords(versionfile_abs):600    """"""Extract version information from the given file.""""""601    # the code embedded in _version.py can just fetch the value of these602    # keywords. When used from setup.py, we don't want to import _version.py,603    # so we do it with a regexp instead. This function is not used from604    # _version.py.605    keywords = {}606    try:607        f = open(versionfile_abs, ""r"")608        for line in f.readlines():609            if line.strip().startswith(""git_refnames =""):610                mo = re.search(r'=\s*""(.*)""', line)611                if mo:612                    keywords[""refnames""] = mo.group(1)613            if line.strip().startswith(""git_full =""):614                mo = re.search(r'=\s*""(.*)""', line)615                if mo:616                    keywords[""full""] = mo.group(1)617            if line.strip().startswith(""git_date =""):618                mo = re.search(r'=\s*""(.*)""', line)619                if mo:620                    keywords[""date""] = mo.group(1)621        f.close()622    except EnvironmentError:623        pass624    return keywords625 626 627@register_vcs_handler(""git"", ""keywords"")628def git_versions_from_keywords(keywords, tag_prefix, verbose):629    """"""Get version information from git keywords.""""""630    if not keywords:631        raise NotThisMethod(""no keywords at all, weird"")632    date = keywords.get(""date"")633    if date is not None:634        # git-2.2.0 added ""%%cI"", which expands to an ISO-8601 -compliant635        # datestamp. However we prefer ""%%ci"" (which expands to an ""ISO-8601636        # -like"" string, which we must then edit to make compliant), because637        # it's been around since git-1.5.3, and it's too difficult to638        # discover which version we're using, or to work around using an639        # older one.640        date = date.strip().replace("" "", ""T"", 1).replace("" "", """", 1)641    refnames = keywords[""refnames""].strip()642    if refnames.startswith(""$Format""):643        if verbose:644            print(""keywords are unexpanded, not using"")645        raise NotThisMethod(""unexpanded keywords, not a git-archive tarball"")646    refs = set([r.strip() for r in refnames.strip(""()"").split("","")])647    # starting in git-1.8.3, tags are listed as ""tag: foo-1.0"" instead of648    # just ""foo-1.0"". If we see a ""tag: "" prefix, prefer those.649    TAG = ""tag: ""650    tags = set([r[len(TAG):] for r in refs if r.startswith(TAG)])651    if not tags:652        # Either we're using git < 1.8.3, or there really are no tags. We use653        # a heuristic: assume all version tags have a digit. The old git %%d654        # expansion behaves like git log --decorate=short and strips out the655        # refs/heads/ and refs/tags/ prefixes that would let us distinguish656        # between branches and tags. By ignoring refnames without digits, we657        # filter out many common branch names like ""release"" and658        # ""stabilization"", as well as ""HEAD"" and ""master"".659        tags = set([r for r in refs if re.search(r'\d', r)])660        if verbose:661            print(""discarding '%%s', no digits"" %% "","".join(refs - tags))662    if verbose:663        print(""likely tags: %%s"" %% "","".join(sorted(tags)))664    for ref in sorted(tags):665        # sorting will prefer e.g. ""2.0"" over ""2.0rc1""666        if ref.startswith(tag_prefix):667            r = ref[len(tag_prefix):]668            if verbose:669                print(""picking %%s"" %% r)670            return {""version"": r,671                    ""full-revisionid"": keywords[""full""].strip(),672                    ""dirty"": False, ""error"": None,673                    ""date"": date}674    # no suitable tags, so version is ""0+unknown"", but full hex is still there675    if verbose:676        print(""no suitable tags, using unknown + full revision id"")677    return {""version"": ""0+unknown"",678            ""full-revisionid"": keywords[""full""].strip(),679            ""dirty"": False, ""error"": ""no suitable tags"", ""date"": None}680 681 682@register_vcs_handler(""git"", ""pieces_from_vcs"")683def git_pieces_from_vcs(tag_prefix, root, verbose, run_command=run_command):684    """"""Get version from 'git describe' in the root of the source tree.685 686    This only gets called if the git-archive 'subst' keywords were *not*687    expanded, and _version.py hasn't already been rewritten with a short688    version string, meaning we're inside a checked out source tree.689    """"""690    GITS = [""git""]691    if sys.platform == ""win32"":692        GITS = [""git.cmd"", ""git.exe""]693 694    out, rc = run_command(GITS, [""rev-parse"", ""--git-dir""], cwd=root,695                          hide_stderr=True)696    if rc != 0:697        if verbose:698            print(""Directory %%s not under git control"" %% root)699        raise NotThisMethod(""'git rev-parse --git-dir' returned error"")700 701    # if there is a tag matching tag_prefix, this yields TAG-NUM-gHEX[-dirty]702    # if there isn't one, this yields HEX[-dirty] (no NUM)703    describe_out, rc = run_command(GITS, [""describe"", ""--tags"", ""--dirty"",704                                          ""--always"", ""--long"",705                                          ""--match"", ""%%s*"" %% tag_prefix],706                                   cwd=root)707    # --long was added in git-1.5.5708    if describe_out is None:709        raise NotThisMethod(""'git describe' failed"")710    describe_out = describe_out.strip()711    full_out, rc = run_command(GITS, [""rev-parse"", ""HEAD""], cwd=root)712    if full_out is None:713        raise NotThisMethod(""'git rev-parse' failed"")714    full_out = full_out.strip()715 716    pieces = {}717    pieces[""long""] = full_out718    pieces[""short""] = full_out[:7]  # maybe improved later719    pieces[""error""] = None720 721    # parse describe_out. It will be like TAG-NUM-gHEX[-dirty] or HEX[-dirty]722    # TAG might have hyphens.723    git_describe = describe_out724 725    # look for -dirty suffix726    dirty = git_describe.endswith(""-dirty"")727    pieces[""dirty""] = dirty728    if dirty:729        git_describe = git_describe[:git_describe.rindex(""-dirty"")]730 731    # now we have TAG-NUM-gHEX or HEX732 733    if ""-"" in git_describe:734        # TAG-NUM-gHEX735        mo = re.search(r'^(.+)-(\d+)-g([0-9a-f]+)$', git_describe)736        if not mo:737            # unparseable. Maybe git-describe is misbehaving?738            pieces[""error""] = (""unable to parse git-describe output: '%%s'""739                               %% describe_out)740            return pieces741 742        # tag743        full_tag = mo.group(1)744        if not full_tag.startswith(tag_prefix):745            if verbose:746                fmt = ""tag '%%s' doesn't start with prefix '%%s'""747                print(fmt %% (full_tag, tag_prefix))748            pieces[""error""] = (""tag '%%s' doesn't start with prefix '%%s'""749                               %% (full_tag, tag_prefix))750            return pieces751        pieces[""closest-tag""] = full_tag[len(tag_prefix):]752 753        # distance: number of commits since tag754        pieces[""distance""] = int(mo.group(2))755 756        # commit: short hex revision ID757        pieces[""short""] = mo.group(3)758 759    else:760        # HEX: no tags761        pieces[""closest-tag""] = None762        count_out, rc = run_command(GITS, [""rev-list"", ""HEAD"", ""--count""],763                                    cwd=root)764        pieces[""distance""] = int(count_out)  # total number of commits765 766    # commit date: see ISO-8601 comment in git_versions_from_keywords()767    date = run_command(GITS, [""show"", ""-s"", ""--format=%%ci"", ""HEAD""],768                       cwd=root)[0].strip()769    pieces[""date""] = date.strip().replace("" "", ""T"", 1).replace("" "", """", 1)770 771    return pieces772 773 774def plus_or_dot(pieces):775    """"""Return a + if we don't already have one, else return a .""""""776    if ""+"" in pieces.get(""closest-tag"", """"):777        return "".""778    return ""+""779 780 781def render_pep440(pieces):782    """"""Build up version string, with post-release ""local version identifier"".783 784    Our goal: TAG[+DISTANCE.gHEX[.dirty]] . Note that if you785    get a tagged build and then dirty it, you'll get TAG+0.gHEX.dirty786 787    Exceptions:788    1: no tags. git_describe was just HEX. 0+untagged.DISTANCE.gHEX[.dirty]789    """"""790    if pieces[""closest-tag""]:791        rendered = pieces[""closest-tag""]792        if pieces[""distance""] or pieces[""dirty""]:793            rendered += plus_or_dot(pieces)794            rendered += ""%%d.g%%s"" %% (pieces[""distance""], pieces[""short""])795            if pieces[""dirty""]:796                rendered += "".dirty""797    else:798        # exception #1799        rendered = ""0+untagged.%%d.g%%s"" %% (pieces[""distance""],800                                          pieces[""short""])801        if pieces[""dirty""]:802            rendered += "".dirty""803    return rendered804 805 806def render_pep440_pre(pieces):807    """"""TAG[.post.devDISTANCE] -- No -dirty.808 809    Exceptions:810    1: no tags. 0.post.devDISTANCE811    """"""812    if pieces[""closest-tag""]:813        rendered = pieces[""closest-tag""]814        if pieces[""distance""]:815            rendered += "".post.dev%%d"" %% pieces[""distance""]816    else:817        # exception #1818        rendered = ""0.post.dev%%d"" %% pieces[""distance""]819    return rendered820 821 822def render_pep440_post(pieces):823    """"""TAG[.postDISTANCE[.dev0]+gHEX] .824 825    The "".dev0"" means dirty. Note that .dev0 sorts backwards826    (a dirty tree will appear ""older"" than the corresponding clean one),827    but you shouldn't be releasing software with -dirty anyways.828 829    Exceptions:830    1: no tags. 0.postDISTANCE[.dev0]831    """"""832    if pieces[""closest-tag""]:833        rendered = pieces[""closest-tag""]834        if pieces[""distance""] or pieces[""dirty""]:835            rendered += "".post%%d"" %% pieces[""distance""]836            if pieces[""dirty""]:837                rendered += "".dev0""838            rendered += plus_or_dot(pieces)839            rendered += ""g%%s"" %% pieces[""short""]840    else:841        # exception #1842        rendered = ""0.post%%d"" %% pieces[""distance""]843        if pieces[""dirty""]:844            rendered += "".dev0""845        rendered += ""+g%%s"" %% pieces[""short""]846    return rendered847 848 849def render_pep440_old(pieces):850    """"""TAG[.postDISTANCE[.dev0]] .851 852    The "".dev0"" means dirty.853 854    Eexceptions:855    1: no tags. 0.postDISTANCE[.dev0]856    """"""857    if pieces[""closest-tag""]:858        rendered = pieces[""closest-tag""]859        if pieces[""distance""] or pieces[""dirty""]:860            rendered += "".post%%d"" %% pieces[""distance""]861            if pieces[""dirty""]:862                rendered += "".dev0""863    else:864        # exception #1865        rendered = ""0.post%%d"" %% pieces[""distance""]866        if pieces[""dirty""]:867            rendered += "".dev0""868    return rendered869 870 871def render_git_describe(pieces):872    """"""TAG[-DISTANCE-gHEX][-dirty].873 874    Like 'git describe --tags --dirty --always'.875 876    Exceptions:877    1: no tags. HEX[-dirty]  (note: no 'g' prefix)878    """"""879    if pieces[""closest-tag""]:880        rendered = pieces[""closest-tag""]881        if pieces[""distance""]:882            rendered += ""-%%d-g%%s"" %% (pieces[""distance""], pieces[""short""])883    else:884        # exception #1885        rendered = pieces[""short""]886    if pieces[""dirty""]:887        rendered += ""-dirty""888    return rendered889 890 891def render_git_describe_long(pieces):892    """"""TAG-DISTANCE-gHEX[-dirty].893 894    Like 'git describe --tags --dirty --always -long'.895    The distance/hash is unconditional.896 897    Exceptions:898    1: no tags. HEX[-dirty]  (note: no 'g' prefix)899    """"""900    if pieces[""closest-tag""]:901        rendered = pieces[""closest-tag""]902        rendered += ""-%%d-g%%s"" %% (pieces[""distance""], pieces[""short""])903    else:904        # exception #1905        rendered = pieces[""short""]906    if pieces[""dirty""]:907        rendered += ""-dirty""908    return rendered909 910 911def render(pieces, style):912    """"""Render the given version pieces into the requested style.""""""913    if pieces[""error""]:914        return {""version"": ""unknown"",915                ""full-revisionid"": pieces.get(""long""),916                ""dirty"": None,917                ""error"": pieces[""error""],918                ""date"": None}919 920    if not style or style == ""default"":921        style = ""pep440""  # the default922 923    if style == ""pep440"":924        rendered = render_pep440(pieces)925    elif style == ""pep440-pre"":926        rendered = render_pep440_pre(pieces)927    elif style == ""pep440-post"":928        rendered = render_pep440_post(pieces)929    elif style == ""pep440-old"":930        rendered = render_pep440_old(pieces)931    elif style == ""git-describe"":932        rendered = render_git_describe(pieces)933    elif style == ""git-describe-long"":934        rendered = render_git_describe_long(pieces)935    else:936        raise ValueError(""unknown style '%%s'"" %% style)937 938    return {""version"": rendered, ""full-revisionid"": pieces[""long""],939            ""dirty"": pieces[""dirty""], ""error"": None,940            ""date"": pieces.get(""date"")}941 942 943def get_versions():944    """"""Get version information or return default if unable to do so.""""""945    # I am in _version.py, which lives at ROOT/VERSIONFILE_SOURCE. If we have946    # __file__, we can work backwards from there to the root. Some947    # py2exe/bbfreeze/non-CPython implementations don't do __file__, in which948    # case we can only use expanded keywords.949 950    cfg = get_config()951    verbose = cfg.verbose952 953    try:954        return git_versions_from_keywords(get_keywords(), cfg.tag_prefix,955                                          verbose)956    except NotThisMethod:957        pass958 959    try:960        root = os.path.realpath(__file__)961        # versionfile_source is the relative path from the top of the source962        # tree (where the .git directory might live) to this file. Invert963        # this to find the root from __file__.964        for i in cfg.versionfile_source.split('/'):965            root = os.path.dirname(root)966    except NameError:967        return {""version"": ""0+unknown"", ""full-revisionid"": None,968                ""dirty"": None,969                ""error"": ""unable to find root of source tree"",970                ""date"": None}971 972    try:973        pieces = git_pieces_from_vcs(cfg.tag_prefix, root, verbose)974        return render(pieces, cfg.style)975    except NotThisMethod:976        pass977 978    try:979        if cfg.parentdir_prefix:980            return versions_from_parentdir(cfg.parentdir_prefix, root, verbose)981    except NotThisMethod:982        pass983 984    return {""version"": ""0+unknown"", ""full-revisionid"": None,985            ""dirty"": None,986            ""error"": ""unable to compute version"", ""date"": None}987'''988 989 990@register_vcs_handler(""git"", ""get_keywords"")991def git_get_keywords(versionfile_abs):992    """"""Extract version information from the given file.""""""993    # the code embedded in _version.py can just fetch the value of these994    # keywords. When used from setup.py, we don't want to import _version.py,995    # so we do it with a regexp instead. This function is not used from996    # _version.py.997    keywords = {}998    try:999        f = open(versionfile_abs, ""r"")1000        for line in f.readlines():1001            if line.strip().startswith(""git_refnames =""):1002                mo = re.search(r'=\s*""(.*)""', line)1003                if mo:1004                    keywords[""refnames""] = mo.group(1)1005            if line.strip().startswith(""git_full =""):1006                mo = re.search(r'=\s*""(.*)""', line)1007                if mo:1008                    keywords[""full""] = mo.group(1)1009            if line.strip().startswith(""git_date =""):1010                mo = re.search(r'=\s*""(.*)""', line)1011                if mo:1012                    keywords[""date""] = mo.group(1)1013        f.close()1014    except EnvironmentError:1015        pass1016    return keywords1017 1018 1019@register_vcs_handler(""git"", ""keywords"")1020def git_versions_from_keywords(keywords, tag_prefix, verbose):1021    """"""Get version information from git keywords.""""""1022    if not keywords:1023        raise NotThisMethod(""no keywords at all, weird"")1024    date = keywords.get(""date"")1025    if date is not None:1026        # git-2.2.0 added ""%cI"", which expands to an ISO-8601 -compliant1027        # datestamp. However we prefer ""%ci"" (which expands to an ""ISO-86011028        # -like"" string, which we must then edit to make compliant), because1029        # it's been around since git-1.5.3, and it's too difficult to1030        # discover which version we're using, or to work around using an1031        # older one.1032        date = date.strip().replace("" "", ""T"", 1).replace("" "", """", 1)1033    refnames = keywords[""refnames""].strip()1034    if refnames.startswith(""$Format""):1035        if verbose:1036            print(""keywords are unexpanded, not using"")1037        raise NotThisMethod(""unexpanded keywords, not a git-archive tarball"")1038    refs = set([r.strip() for r in refnames.strip(""()"").split("","")])1039    # starting in git-1.8.3, tags are listed as ""tag: foo-1.0"" instead of1040    # just ""foo-1.0"". If we see a ""tag: "" prefix, prefer those.1041    TAG = ""tag: ""1042    tags = set([r[len(TAG):] for r in refs if r.startswith(TAG)])1043    if not tags:1044        # Either we're using git < 1.8.3, or there really are no tags. We use1045        # a heuristic: assume all version tags have a digit. The old git %d1046        # expansion behaves like git log --decorate=short and strips out the1047        # refs/heads/ and refs/tags/ prefixes that would let us distinguish1048        # between branches and tags. By ignoring refnames without digits, we1049        # filter out many common branch names like ""release"" and1050        # ""stabilization"", as well as ""HEAD"" and ""master"".1051        tags = set([r for r in refs if re.search(r'\d', r)])1052        if verbose:1053            print(""discarding '%s', no digits"" % "","".join(refs - tags))1054    if verbose:1055        print(""likely tags: %s"" % "","".join(sorted(tags)))1056    for ref in sorted(tags):1057        # sorting will prefer e.g. ""2.0"" over ""2.0rc1""1058        if ref.startswith(tag_prefix):1059            r = ref[len(tag_prefix):]1060            if verbose:1061                print(""picking %s"" % r)1062            return {""version"": r,1063                    ""full-revisionid"": keywords[""full""].strip(),1064                    ""dirty"": False, ""error"": None,1065                    ""date"": date}1066    # no suitable tags, so version is ""0+unknown"", but full hex is still there1067    if verbose:1068        print(""no suitable tags, using unknown + full revision id"")1069    return {""version"": ""0+unknown"",1070            ""full-revisionid"": keywords[""full""].strip(),1071            ""dirty"": False, ""error"": ""no suitable tags"", ""date"": None}1072 1073 1074@register_vcs_handler(""git"", ""pieces_from_vcs"")1075def git_pieces_from_vcs(tag_prefix, root, verbose, run_command=run_command):1076    """"""Get version from 'git describe' in the root of the source tree.1077 1078    This only gets called if the git-archive 'subst' keywords were *not*1079    expanded, and _version.py hasn't already been rewritten with a short1080    version string, meaning we're inside a checked out source tree.1081    """"""1082    GITS = [""git""]1083    if sys.platform == ""win32"":1084        GITS = [""git.cmd"", ""git.exe""]1085 1086    out, rc = run_command(GITS, [""rev-parse"", ""--git-dir""], cwd=root,1087                          hide_stderr=True)1088    if rc != 0:1089        if verbose:1090            print(""Directory %s not under git control"" % root)1091        raise NotThisMethod(""'git rev-parse --git-dir' returned error"")1092 1093    # if there is a tag matching tag_prefix, this yields TAG-NUM-gHEX[-dirty]1094    # if there isn't one, this yields HEX[-dirty] (no NUM)1095    describe_out, rc = run_command(GITS, [""describe"", ""--tags"", ""--dirty"",1096                                          ""--always"", ""--long"",1097                                          ""--match"", ""%s*"" % tag_prefix],1098                                   cwd=root)1099    # --long was added in git-1.5.51100    if describe_out is None:1101        raise NotThisMethod(""'git describe' failed"")1102    describe_out = describe_out.strip()1103    full_out, rc = run_command(GITS, [""rev-parse"", ""HEAD""], cwd=root)1104    if full_out is None:1105        raise NotThisMethod(""'git rev-parse' failed"")1106    full_out = full_out.strip()1107 1108    pieces = {}1109    pieces[""long""] = full_out1110    pieces[""short""] = full_out[:7]  # maybe improved later1111    pieces[""error""] = None1112 1113    # parse describe_out. It will be like TAG-NUM-gHEX[-dirty] or HEX[-dirty]1114    # TAG might have hyphens.1115    git_describe = describe_out1116 1117    # look for -dirty suffix1118    dirty = git_describe.endswith(""-dirty"")1119    pieces[""dirty""] = dirty1120    if dirty:1121        git_describe = git_describe[:git_describe.rindex(""-dirty"")]1122 1123    # now we have TAG-NUM-gHEX or HEX1124 1125    if ""-"" in git_describe:1126        # TAG-NUM-gHEX1127        mo = re.search(r'^(.+)-(\d+)-g([0-9a-f]+)$', git_describe)1128        if not mo:1129            # unparseable. Maybe git-describe is misbehaving?1130            pieces[""error""] = (""unable to parse git-describe output: '%s'""1131                               % describe_out)1132            return pieces1133 1134        # tag1135        full_tag = mo.group(1)1136        if not full_tag.startswith(tag_prefix):1137            if verbose:1138                fmt = ""tag '%s' doesn't start with prefix '%s'""1139                print(fmt % (full_tag, tag_prefix))1140            pieces[""error""] = (""tag '%s' doesn't start with prefix '%s'""1141                               % (full_tag, tag_prefix))1142            return pieces1143        pieces[""closest-tag""] = full_tag[len(tag_prefix):]1144 1145        # distance: number of commits since tag1146        pieces[""distance""] = int(mo.group(2))1147 1148        # commit: short hex revision ID1149        pieces[""short""] = mo.group(3)1150 1151    else:1152        # HEX: no tags1153        pieces[""closest-tag""] = None1154        count_out, rc = run_command(GITS, [""rev-list"", ""HEAD"", ""--count""],1155                                    cwd=root)1156        pieces[""distance""] = int(count_out)  # total number of commits1157 1158    # commit date: see ISO-8601 comment in git_versions_from_keywords()1159    date = run_command(GITS, [""show"", ""-s"", ""--format=%ci"", ""HEAD""],1160                       cwd=root)[0].strip()1161    pieces[""date""] = date.strip().replace("" "", ""T"", 1).replace("" "", """", 1)1162 1163    return pieces1164 1165 1166def do_vcs_install(manifest_in, versionfile_source, ipy):1167    """"""Git-specific installation logic for Versioneer.1168 1169    For Git, this means creating/changing .gitattributes to mark _version.py1170    for export-subst keyword substitution.1171    """"""1172    GITS = [""git""]1173    if sys.platform == ""win32"":1174        GITS = [""git.cmd"", ""git.exe""]1175    files = [manifest_in, versionfile_source]1176    if ipy:1177        files.append(ipy)1178    try:1179        me = __file__1180        if me.endswith("".pyc"") or me.endswith("".pyo""):1181            me = os.path.splitext(me)[0] + "".py""1182        versioneer_file = os.path.relpath(me)1183    except NameError:1184        versioneer_file = ""versioneer.py""1185    files.append(versioneer_file)1186    present = False1187    try:1188        f = open("".gitattributes"", ""r"")1189        for line in f.readlines():1190            if line.strip().startswith(versionfile_source):1191                if ""export-subst"" in line.strip().split()[1:]:1192                    present = True1193        f.close()1194    except EnvironmentError:1195        pass1196    if not present:1197        f = open("".gitattributes"", ""a+"")1198        f.write(""%s export-subst\n"" % versionfile_source)1199        f.close()1200        files.append("".gitattributes"")

Showing the first 1,200 of 73442 lines. Download the file for the rest.