<commit_before># -*- coding: utf-8 -*-
"""ghrelease

Usage:
    ghrelease --version
    ghrelease [options] list <reponame>
    ghrelease [options] create --tag=TAG [--name=RELEASE_NAME] [--body=FILE] [--draft | --prerelease] <reponame>
    ghrelease [options] open (--tag=TAG | --latest) <reponame>

Options:
    -h --help           show this help
    -u --user=USER      github login name
    -p --password=<PASSWORD>  github password
    --password-env=ENV  read password from system environment [default: GHRELEASE_PASS]
    --user-env=ENV      read user name from system environment [default: GHRELEASE_USER]
    --owner=OWNER       github owner [defaults to the user name]
    --debug             debug logging
    -v, --verbose       print more text
"""
from docopt import docopt

import sys
import logging
import github3
import webbrowser

from .log import t
from .log import error
from .log import logger
from .log import verbose

from .cred import get_credentials


__version__ = "0.1"

def get_repo(gh, owner, reponame):
    repo = gh.repository(owner, reponame)
    if repo is None:
        error(10, "repository not found: " + reponame)

    return repo

def print_release(release):
    name = release.name or "<no name>"
    m = u"%s (%s) @ %s" % (name, release.tag_name, release.html_url)
    if release.prerelease:
        print t.yellow("PRERELEASE"),
    elif release.draft:
        print t.blue("DRAFT     "),
    else:
        print t.green("RELEASE   "),

    print m.encode("utf-8")

def list_releases(gh, owner, reponame):
    repo = get_repo(gh, owner, reponame)

    verbose("Listing releases of repository `%s`:" % reponame)

    for nr, release in enumerate(repo.iter_releases()):
        print_release(release)

def get_latest_release(repo):
    return repo.iter_releases(number=1).next()

def get_release(repo, tag_name):
    for release in repo.iter_releases():
        if release.tag_name == tag_name:
            return release

def open_release(gh, owner, reponame, tag=None, latest=False):
    if not tag:
        latest = True

    repo = get_repo(gh, owner, reponame)

    if latest:
        release = get_latest_release(repo)
    else:
        release = get_release(repo, tag)

    if not release:
        error(11, "No such release found.")

    webbrowser.open(release.html_url)


def create_release(gh, owner, reponame, tag, name=None, body_file=None, draft=None, prerelease=None):
    repo = get_repo(gh, owner, reponame)

    body = None
    if body_file:
        with file(body_file, "r") as f:
            body = f.read()

    release = repo.create_release(
        tag,
        name=name,
        body=body,
        draft=draft,
        prerelease=prerelease)

    verbose("Release created:")
    print_release(release)


def main():
    arguments = docopt(__doc__, version="ghrelease v%s" % __version__)

    if arguments["--debug"]:
        logging.basicConfig(
            level=logging.DEBUG,
            format="%(asctime)s [%(levelname)-7s] [line %(lineno)d] %(name)s: %(message)s",
            stream=sys.stderr)
        logger.setLevel(logging.DEBUG)<commit_msg>Added docstrings.<commit_after># -*- coding: utf-8 -*-
"""ghrelease

Usage:
    ghrelease --version
    ghrelease [options] list <reponame>
    ghrelease [options] create --tag=TAG [--name=RELEASE_NAME] [--body=FILE] [--draft | --prerelease] <reponame>
    ghrelease [options] open (--tag=TAG | --latest) <reponame>

Options:
    -h --help           show this help
    -u --user=USER      github login name
    -p --password=PASS  github password
    --password-env=ENV  read password from system environment [default: GHRELEASE_PASS]
    --user-env=ENV      read user name from system environment [default: GHRELEASE_USER]
    --owner=OWNER       github owner [defaults to the user name]
    --debug             debug logging
    -v, --verbose       print more text
"""
from docopt import docopt

import sys
import logging
import github3
import webbrowser

from .log import t
from .log import error
from .log import logger
from .log import verbose

from .cred import get_credentials


__version__ = "0.1"

def get_repo(gh, owner, reponame):
    """get_repo(gh, owner, reponame) -> repo

    Get a repo and error out if no repo found.

    @param gh:          the gh api handle
    @param owner:       the owner of the repo
    @param reponame:    the repository name
    @returns:           repository object
    """
    repo = gh.repository(owner, reponame)
    if repo is None:
        error(10, "repository not found: " + reponame)

    return repo

def print_release(release):
    """print_release(release) -> None

    Simple helper to pretty-print a release.

    @param release:     a github3 release object
    """
    name = release.name or "<no name>"
    m = u"%s (%s) @ %s" % (name, release.tag_name, release.html_url)
    if release.prerelease:
        print t.yellow("PRERELEASE"),
    elif release.draft:
        print t.blue("DRAFT     "),
    else:
        print t.green("RELEASE   "),

    print m.encode("utf-8")

def list_releases(gh, owner, reponame):
    """list_releases(gh, owner, reponame) -> None

    List releases command.  Loop through all releases and pretty-print
    them.

    @param gh:          the gh api handle
    @param owner:       the owner of the repo
    @param reponame:    the repository name
    """
    repo = get_repo(gh, owner, reponame)

    verbose("Listing releases of repository `%s`:" % reponame)

    for nr, release in enumerate(repo.iter_releases()):
        print_release(release)

def get_latest_release(repo):
    """get_latest_release(repo) -> release

    Fetch the latest release from the given repo and
    return it.

    @param repo:        github3 repository object
    @returns:           github3 release object or None
    """
    return repo.iter_releases(number=1).next()

def get_release(repo, tag_name):
    """get_release(repo, tag_name) -> release

    Fetch the release tagged with the given tag and
    return it.

    @param repo:        github3 repository object
    @returns:           github3 release object or None
    """
    for release in repo.iter_releases():
        if release.tag_name == tag_name:
            return release

def open_release(gh, owner, reponame, tag=None):
    """open_release(gh, owner, reponame, tag) -> None

    Open command -- find the specified release and open it's
    web page.  If the tag is not specified, the latest release
    is opened.

    @param gh:          the gh api handle
    @param owner:       the owner of the repo
    @param reponame:    the repository name
    @param tag:         the tag or None
    """

    repo = get_repo(gh, owner, reponame)

    if not tag:
        release = get_latest_release(repo)
    else:
        release = get_release(repo, tag)

    if not release:
        error(11, "No such release found.")

    webbrowser.open(release.html_url)


def create_release(gh, owner, reponame, tag, name=None, body_file=None,
                   draft=None, prerelease=None):
    """create_release(gh, wwner, reponame, tag, ...) -> None

    Create release command.  Creates a new release for the given repository
    and tag.  The tag must exist.

    If `body_file` is specified, it is taken as a file name to read the release
    body text (release notes) from.

    @param gh:          the gh api handle
    @param owner:       the owner of the repo
    @param reponame:    the repository name
    @param tag:         the tag name
    @param name:        a name for the release (optional)
    @param body_file:   a name of a file to read the release body text from (optional)
    @param draft:       is this release a draft?  (defaults to False)
    @param prerelease:  is this release a prerelease?  (defaults to False)
    """
    repo = get_repo(gh, owner, reponame)

    body = None
    if body_file:
        with file(body_file, "r") as f:
            body = f.read()

    release = repo.create_release(
        tag,
        name=name,
        body=body,
        draft=draft,
        prerelease=prerelease)

    verbose("Release created:")
    print_release(release)


def main():
    arguments = docopt(__doc__, version="ghrelease v%s" % __version__)

    if arguments["--debug"]:
        logging.basicConfig(
            level=logging.DEBUG,
            format="%(asctime)s [%(levelname)-7s] [line %(lineno)d] %(name)s: %(message)s",
            stream=sys.stderr)
        logger.setLevel(logging.DEBUG)
{'fraction_non_alphanumeric': 0.10704591053936031, 'fraction_numerical': 0.0031865927062433613, 'mean_word_length': 2.5785472972972974, 'pattern_counts': {'":': 0, '<': 12, '<?xml version=': 0, '>': 19, 'https://': 0, 'lorem ipsum': 0, 'www.': 0, 'xml': 0}, 'pii_count': 0, 'substrings_counts': 0, 'word_list_counts': {'cursed_substrings.json': 0, 'profanity_word_list.json': 0, 'sexual_word_list.json': 0, 'zh_pornsignals.json': 0}}
{'dir': 'git-commits-cleaned', 'id': '4007199', 'n_tokens_mistral': 2691, 'n_tokens_neox': 2539, 'n_words': 832}