Exemplo n.º 1
0
def init(path=".", bare=False):
    """Create a new git repository.

    :param path: Path to repository.
    :param bare: Whether to create a bare repository.
    :return: A Repo instance
    """
    if not os.path.exists(path):
        os.mkdir(path)

    if bare:
        return Repo.init_bare(path)
    else:
        return Repo.init(path)
Exemplo n.º 2
0
def open_repo_closing(path_or_repo):
    """Open an argument that can be a repository or a path for a repository.
    returns a context manager that will close the repo on exit if the argument
    is a path, else does nothing if the argument is a repo.
    """
    if isinstance(path_or_repo, BaseRepo):
        return _noop_context_manager(path_or_repo)
    return closing(Repo(path_or_repo))
Exemplo n.º 3
0
 def open_repository(self, path):
     logger.debug("opening repository at %s", path)
     abspath = os.path.abspath(os.path.join(self.root, path)) + os.sep
     normcase_abspath = os.path.normcase(abspath)
     normcase_root = os.path.normcase(self.root)
     if not normcase_abspath.startswith(normcase_root):
         raise NotGitRepository("Path %r not inside root %r" %
                                (path, self.root))
     return Repo(abspath)
Exemplo n.º 4
0
def get_git_commit(path, verbose=False):
    env_commit = os.environ.get(GIT_ENV)
    if env_commit:
        return env_commit
    try:
        repo = Repo.discover(path)
        commit = repo.head().decode("utf-8")
        return commit
    except Exception as ex:
        if verbose:
            logger.warning("Failed to get GIT version of %s: %s", path, ex)
        return None
Exemplo n.º 5
0
def read_submodule_head(path):
    """Read the head commit of a submodule.

    :param path: path to the submodule
    :return: HEAD sha, None if not a valid head/repository
    """
    from dbnd._vendor.dulwich.errors import NotGitRepository
    from dbnd._vendor.dulwich.repo import Repo

    # Repo currently expects a "str", so decode if necessary.
    # TODO(jelmer): Perhaps move this into Repo() ?
    if not isinstance(path, str):
        path = path.decode(sys.getfilesystemencoding())
    try:
        repo = Repo(path)
    except NotGitRepository:
        return None
    try:
        return repo.head()
    except KeyError:
        return None
Exemplo n.º 6
0
def is_git_dirty(path=None, verbose=False):
    try:
        repo = Repo.discover(path)
        status = porcelain.status(repo.path)
        is_dirty = any([
            status.staged["add"],
            status.staged["delete"],
            status.staged["modify"],
            len(status.unstaged),
            len(status.untracked),
        ])
        return is_dirty
    except Exception as ex:
        if verbose:
            logger.warning("Failed to get GIT status %s: %s", path, ex)
        return None
Exemplo n.º 7
0
def main(argv=sys.argv):
    """Entry point for starting an HTTP git server."""
    import optparse

    parser = optparse.OptionParser()
    parser.add_option(
        "-l",
        "--listen_address",
        dest="listen_address",
        default="localhost",
        help="Binding IP address.",
    )
    parser.add_option(
        "-p", "--port", dest="port", type=int, default=8000, help="Port to listen on."
    )
    options, args = parser.parse_args(argv)

    if len(args) > 1:
        gitdir = args[1]
    else:
        gitdir = os.getcwd()

    log_utils.default_logging_config()
    backend = DictBackend({"/": Repo(gitdir)})
    app = make_wsgi_chain(backend)
    server = make_server(
        options.listen_address,
        options.port,
        app,
        handler_class=WSGIRequestHandlerLogger,
        server_class=WSGIServerLogger,
    )
    logger.info(
        "Listening for HTTP connections on %s:%d", options.listen_address, options.port
    )
    server.serve_forever()
Exemplo n.º 8
0
def clone(source,
          target=None,
          bare=False,
          checkout=None,
          errstream=default_bytes_err_stream,
          outstream=None,
          origin=b"origin",
          depth=None,
          **kwargs):
    """Clone a local or remote git repository.

    :param source: Path or URL for source repository
    :param target: Path to target repository (optional)
    :param bare: Whether or not to create a bare repository
    :param checkout: Whether or not to check-out HEAD after cloning
    :param errstream: Optional stream to write progress to
    :param outstream: Optional stream to write progress to (deprecated)
    :param origin: Name of remote from the repository used to clone
    :param depth: Depth to fetch at
    :return: The new repository
    """
    # TODO(jelmer): This code overlaps quite a bit with Repo.clone
    if outstream is not None:
        import warnings

        warnings.warn(
            "outstream= has been deprecated in favour of errstream=.",
            DeprecationWarning,
            stacklevel=3,
        )
        errstream = outstream

    if checkout is None:
        checkout = not bare
    if checkout and bare:
        raise ValueError("checkout and bare are incompatible")

    if target is None:
        target = source.split("/")[-1]

    if not os.path.exists(target):
        os.mkdir(target)

    if bare:
        r = Repo.init_bare(target)
    else:
        r = Repo.init(target)

    reflog_message = b"clone: from " + source.encode("utf-8")
    try:
        fetch_result = fetch(r,
                             source,
                             origin,
                             errstream=errstream,
                             message=reflog_message,
                             depth=depth,
                             **kwargs)
        target_config = r.get_config()
        if not isinstance(source, bytes):
            source = source.encode(DEFAULT_ENCODING)
        target_config.set((b"remote", origin), b"url", source)
        target_config.set(
            (b"remote", origin),
            b"fetch",
            b"+refs/heads/*:refs/remotes/" + origin + b"/*",
        )
        target_config.write_to_path()
        # TODO(jelmer): Support symref capability,
        # https://github.com/jelmer/dulwich/issues/485
        try:
            head = r[fetch_result[b"HEAD"]]
        except KeyError:
            head = None
        else:
            r[b"HEAD"] = head.id
        if checkout and not bare and head is not None:
            errstream.write(b"Checking out " + head.id + b"\n")
            r.reset_index(head.tree)
    except BaseException:
        r.close()
        raise

    return r
Exemplo n.º 9
0
def open_repo(path_or_repo):
    """Open an argument that can be a repository or a path for a repository."""
    if isinstance(path_or_repo, BaseRepo):
        return path_or_repo
    return Repo(path_or_repo)