Skip to content

Commit

Permalink
Run black over the codebase
Browse files Browse the repository at this point in the history
  • Loading branch information
craigds committed Mar 25, 2020
1 parent c8a3fe5 commit 5e363cc
Show file tree
Hide file tree
Showing 34 changed files with 1,474 additions and 825 deletions.
2 changes: 1 addition & 1 deletion platforms/sno_cli.py
Original file line number Diff line number Diff line change
@@ -1,4 +1,4 @@
import sno.cli

if __name__ == '__main__':
if __name__ == "__main__":
sno.cli.cli()
20 changes: 8 additions & 12 deletions setup.py
Original file line number Diff line number Diff line change
@@ -1,23 +1,19 @@
import os
from setuptools import setup, find_packages

with open(os.path.join('sno', 'VERSION')) as version_file:
with open(os.path.join("sno", "VERSION")) as version_file:
version = version_file.read().strip()

setup(
name='sno',
name="sno",
version=version,
description='Distributed version-control for datasets',
url='http://github.com/koordinates/sno',
author='Koordinates Limited & Sno Contributors',
author_email='support@koordinates.com',
license='GPLv2 with linking exception',
description="Distributed version-control for datasets",
url="http://github.com/koordinates/sno",
author="Koordinates Limited & Sno Contributors",
author_email="support@koordinates.com",
license="GPLv2 with linking exception",
packages=find_packages(),
include_package_data=True,
zip_safe=False,
entry_points={
'console_scripts': [
'sno = sno.cli:cli',
],
},
entry_points={"console_scripts": ["sno = sno.cli:cli",],},
)
38 changes: 18 additions & 20 deletions sno/__init__.py
Original file line number Diff line number Diff line change
@@ -1,49 +1,47 @@
__all__ = ('is_frozen', 'is_linux', 'is_darwin', 'spatialite_path', 'prefix')
__all__ = ("is_frozen", "is_linux", "is_darwin", "spatialite_path", "prefix")

import os
import platform
import sys

is_frozen = getattr(sys, 'frozen', None) and hasattr(sys, '_MEIPASS')
is_darwin = (platform.system() == "Darwin")
is_linux = (platform.system() == "Linux")
libsuffix = 'dylib' if is_darwin else 'so'
is_frozen = getattr(sys, "frozen", None) and hasattr(sys, "_MEIPASS")
is_darwin = platform.system() == "Darwin"
is_linux = platform.system() == "Linux"
libsuffix = "dylib" if is_darwin else "so"

# sys.prefix is correctly set by virtualenv (development) & PyInstaller (release)
prefix = os.path.abspath(sys.prefix)

# Rtree / Libspatialindex
os.environ['SPATIALINDEX_C_LIBRARY'] = os.path.join(
prefix,
"" if is_frozen else "lib",
f"libspatialindex_c.{libsuffix}"
os.environ["SPATIALINDEX_C_LIBRARY"] = os.path.join(
prefix, "" if is_frozen else "lib", f"libspatialindex_c.{libsuffix}"
)

spatialite_path = os.path.join(
prefix,
"" if is_frozen else "lib",
f"mod_spatialite"
)
spatialite_path = os.path.join(prefix, "" if is_frozen else "lib", f"mod_spatialite")

# Git
# https://git-scm.com/book/en/v2/Git-Internals-Environment-Variables
os.environ['GIT_EXEC_PATH'] = os.path.join(prefix, 'libexec', 'git-core')
os.environ['GIT_TEMPLATE_DIR'] = os.path.join(prefix, 'share', 'git-core', 'templates')
os.environ['PREFIX'] = prefix
os.environ['PATH'] = prefix + os.pathsep + os.path.join(prefix, 'bin') + os.pathsep + os.environ['PATH']
os.environ["GIT_EXEC_PATH"] = os.path.join(prefix, "libexec", "git-core")
os.environ["GIT_TEMPLATE_DIR"] = os.path.join(prefix, "share", "git-core", "templates")
os.environ["PREFIX"] = prefix
os.environ["PATH"] = (
prefix + os.pathsep + os.path.join(prefix, "bin") + os.pathsep + os.environ["PATH"]
)

# GDAL Data
os.environ['GDAL_DATA'] = os.path.join(prefix, 'share', 'gdal')
os.environ['PROJ_DATA'] = os.path.join(prefix, 'share', 'proj')
os.environ["GDAL_DATA"] = os.path.join(prefix, "share", "gdal")
os.environ["PROJ_DATA"] = os.path.join(prefix, "share", "proj")

# GDAL Error Handling
from osgeo import gdal, ogr

gdal.UseExceptions()
ogr.UseExceptions()

# Libgit2 TLS CA Certificates
import certifi
import pygit2

try:
# this doesn't work on all platforms/security backends (eg. Security.Framework on macOS)
pygit2.settings.ssl_cert_file = certifi.where()
Expand Down
20 changes: 12 additions & 8 deletions sno/checkout.py
Original file line number Diff line number Diff line change
Expand Up @@ -109,7 +109,11 @@ def checkout_new(repo_structure, path, *, datasets=None, commit=None):
@click.command()
@click.pass_context
@click.option("--create", "-c", help="Create a new branch")
@click.option("--force-create", "-C", help="Similar to --create except that if <new-branch> already exists, it will be reset to <start-point>")
@click.option(
"--force-create",
"-C",
help="Similar to --create except that if <new-branch> already exists, it will be reset to <start-point>",
)
@click.option("--discard-changes", is_flag=True, help="Discard local changes")
@click.argument("refish", default=None, required=False)
def switch(ctx, create, force_create, discard_changes, refish):
Expand Down Expand Up @@ -177,9 +181,7 @@ def switch(ctx, create, force_create, discard_changes, refish):
try:
branch = repo.branches[refish]
except KeyError:
raise click.BadParameter(
f"Branch '{refish}' not found."
)
raise click.BadParameter(f"Branch '{refish}' not found.")

commit = branch.peel(pygit2.Commit)
head_ref = branch.name
Expand All @@ -198,12 +200,14 @@ def switch(ctx, create, force_create, discard_changes, refish):
@click.command()
@click.pass_context
@click.option(
"--source", "-s",
"--source",
"-s",
help=(
"Restore the working tree files with the content from the given tree. "
"It is common to specify the source tree by naming a commit, branch or "
"tag associated with it."),
default="HEAD"
"tag associated with it."
),
default="HEAD",
)
@click.argument("pathspec", nargs=-1)
def restore(ctx, source, pathspec):
Expand All @@ -228,7 +232,7 @@ def restore(ctx, source, pathspec):
repo_structure,
force=True,
update_meta=(head_commit.id == commit.id),
paths=pathspec
paths=pathspec,
)


Expand Down
58 changes: 40 additions & 18 deletions sno/cli.py
Original file line number Diff line number Diff line change
Expand Up @@ -10,7 +10,19 @@
import pygit2

from . import core # noqa
from . import checkout, clone, commit, diff, init, fsck, merge, pull, status, query, upgrade
from . import (
checkout,
clone,
commit,
diff,
init,
fsck,
merge,
pull,
status,
query,
upgrade,
)
from .context import Context


Expand All @@ -23,31 +35,39 @@ def print_version(ctx, param, value):
import rtree

import sno
with open(os.path.join(os.path.split(sno.__file__)[0], 'VERSION')) as version_file:

with open(os.path.join(os.path.split(sno.__file__)[0], "VERSION")) as version_file:
version = version_file.read().strip()

click.echo(f"Sno v{version}, Copyright (c) Sno Contributors")

git_version = subprocess.check_output(["git", "--version"]).decode('ascii').strip().split()[-1]
git_version = (
subprocess.check_output(["git", "--version"])
.decode("ascii")
.strip()
.split()[-1]
)

sidx_version = rtree.index.__c_api_version__.decode('ascii')
sidx_version = rtree.index.__c_api_version__.decode("ascii")

db = apsw.Connection(':memory:')
db = apsw.Connection(":memory:")
dbcur = db.cursor()
db.enableloadextension(True)
dbcur.execute("SELECT load_extension(?)", (sno.spatialite_path,))
spatialite_version = dbcur.execute("SELECT spatialite_version();").fetchone()[0]

click.echo((
f"≫ GDAL v{osgeo._gdal.__version__}\n"
f"≫ PyGit2 v{pygit2.__version__}; "
f"Libgit2 v{pygit2.LIBGIT2_VERSION}; "
f"Git v{git_version}\n"
f"≫ APSW v{apsw.apswversion()}; "
f"SQLite v{apsw.sqlitelibversion()}; "
f"SpatiaLite v{spatialite_version}\n"
f"≫ SpatialIndex v{sidx_version}"
))
click.echo(
(
f"≫ GDAL v{osgeo._gdal.__version__}\n"
f"≫ PyGit2 v{pygit2.__version__}; "
f"Libgit2 v{pygit2.LIBGIT2_VERSION}; "
f"Git v{git_version}\n"
f"≫ APSW v{apsw.apswversion()}; "
f"SQLite v{apsw.sqlitelibversion()}; "
f"SpatiaLite v{spatialite_version}\n"
f"≫ SpatialIndex v{sidx_version}"
)
)

ctx.exit()

Expand All @@ -69,7 +89,7 @@ def print_version(ctx, param, value):
is_eager=True,
help="Show version information and exit.",
)
@click.option('-v', '--verbose', count=True, help="Repeat for more verbosity")
@click.option("-v", "--verbose", count=True, help="Repeat for more verbosity")
@click.pass_context
def cli(ctx, repo_dir, verbose):
ctx.ensure_object(Context)
Expand Down Expand Up @@ -175,10 +195,12 @@ def branch(ctx, args):
# git's branch protection behaviour doesn't apply if it's a bare repository
# attempt to apply it here.
sargs = set(args)
if sargs & {'-d', '--delete', '-D'}:
if sargs & {"-d", "--delete", "-D"}:
branch = repo.head.shorthand
if branch in sargs:
raise click.ClickException(f"Cannot delete the branch '{branch}' which you are currently on.")
raise click.ClickException(
f"Cannot delete the branch '{branch}' which you are currently on."
)

_execvp("git", ["git", "-C", repo_path, "branch"] + list(args))

Expand Down
34 changes: 24 additions & 10 deletions sno/clone.py
Original file line number Diff line number Diff line change
Expand Up @@ -11,22 +11,36 @@

@click.command()
@click.pass_context
@click.option("--checkout/--no-checkout", "do_checkout", is_flag=True, default=True, help="Whether to checkout a working copy in the repository")
@click.option(
"--checkout/--no-checkout",
"do_checkout",
is_flag=True,
default=True,
help="Whether to checkout a working copy in the repository",
)
@click.argument("url", nargs=1)
@click.argument("directory", type=click.Path(exists=False, file_okay=False, writable=True), required=False)
@click.argument(
"directory",
type=click.Path(exists=False, file_okay=False, writable=True),
required=False,
)
def clone(ctx, do_checkout, url, directory):
""" Clone a repository into a new directory """
repo_path = Path(directory or os.path.split(url)[1])

# we use subprocess because it deals with credentials much better & consistently than we can do at the moment.
# pygit2.clone_repository() works fine except for that
subprocess.check_call([
"git", "clone",
"--bare",
"--config", "remote.origin.fetch=+refs/heads/*:refs/remotes/origin/*",
url,
repo_path.resolve()
])
subprocess.check_call(
[
"git",
"clone",
"--bare",
"--config",
"remote.origin.fetch=+refs/heads/*:refs/remotes/origin/*",
url,
repo_path.resolve(),
]
)

repo = pygit2.Repository(str(repo_path.resolve()))
head_ref = repo.head.shorthand # master
Expand All @@ -37,7 +51,7 @@ def clone(ctx, do_checkout, url, directory):
# Checkout a working copy
wc_path = f"{repo_path.stem}.gpkg"

click.echo(f'Checkout to {wc_path} as GPKG ...')
click.echo(f"Checkout to {wc_path} as GPKG ...")

checkout.checkout_new(
repo_structure=RepositoryStructure(repo),
Expand Down
8 changes: 6 additions & 2 deletions sno/context.py
Original file line number Diff line number Diff line change
Expand Up @@ -41,7 +41,11 @@ def repo(self):

if not self._repo or not self._repo.is_bare:
if self.has_repo_path:
raise click.BadParameter("Not an existing repository", param_hint="--repo")
raise click.BadParameter(
"Not an existing repository", param_hint="--repo"
)
else:
raise click.UsageError("Current directory is not an existing repository")
raise click.UsageError(
"Current directory is not an existing repository"
)
return self._repo
22 changes: 11 additions & 11 deletions sno/core.py
Original file line number Diff line number Diff line change
Expand Up @@ -4,7 +4,7 @@
from click import ClickException


def walk_tree(top, path='', topdown=True):
def walk_tree(top, path="", topdown=True):
"""
Corollary of os.walk() for git Tree objects:
Expand Down Expand Up @@ -41,7 +41,7 @@ def walk_tree(top, path='', topdown=True):
blob_names = []

for entry in top:
is_tree = (entry.type == pygit2.GIT_OBJ_TREE)
is_tree = entry.type == pygit2.GIT_OBJ_TREE

if is_tree:
subtree_names.append(entry.name)
Expand All @@ -54,12 +54,12 @@ def walk_tree(top, path='', topdown=True):
yield top, path, subtree_names, blob_names
for name in subtree_names:
subtree_path = os.path.join(path, name)
subtree = (top / name)
subtree = top / name
yield from walk_tree(subtree, subtree_path, topdown=topdown)
else:
for name in subtree_names:
subtree_path = os.path.join(path, name)
subtree = (top / name)
subtree = top / name
yield from walk_tree(subtree, subtree_path, topdown=topdown)
yield top, path, subtree_names, blob_names

Expand All @@ -80,23 +80,23 @@ def check_git_user(repo=None):
cfg = {}

try:
user_email = cfg['user.email']
user_name = cfg['user.name']
user_email = cfg["user.email"]
user_name = cfg["user.name"]
if user_email and user_name:
return (user_email, user_name)
except KeyError:
pass

msg = [
'Please tell me who you are.',
'\nRun',
"Please tell me who you are.",
"\nRun",
'\n git config --global user.email "you@example.com"',
' git config --global user.name "Your Name"',
'\nto set your account\'s default identity.',
"\nto set your account's default identity.",
]
if repo:
msg.append('Omit --global to set the identity only in this repository.')
msg.append("Omit --global to set the identity only in this repository.")

msg.append('\n(sno uses the same credentials and configuration as git)')
msg.append("\n(sno uses the same credentials and configuration as git)")

raise ClickException("\n".join(msg))
Loading

0 comments on commit 5e363cc

Please sign in to comment.