Skip to content

Commit

Permalink
apply black
Browse files Browse the repository at this point in the history
  • Loading branch information
bouttier committed Mar 24, 2022
1 parent 0eab6d6 commit ccbf60c
Show file tree
Hide file tree
Showing 10 changed files with 910 additions and 722 deletions.
60 changes: 31 additions & 29 deletions setup.py
Original file line number Diff line number Diff line change
Expand Up @@ -3,51 +3,53 @@


root_dir = Path(__file__).absolute().parent
with (root_dir / 'VERSION').open() as f:
with (root_dir / "VERSION").open() as f:
version = f.read()
with (root_dir / 'README.md').open() as f:
with (root_dir / "README.md").open() as f:
long_description = f.read()
with (root_dir / 'requirements.in').open() as f:
with (root_dir / "requirements.in").open() as f:
requirements = f.read().splitlines()


setuptools.setup(
name='utils-flask-sqlalchemy',
name="utils-flask-sqlalchemy",
version=version,
description="Python lib of tools for Flask and SQLAlchemy",
long_description=long_description,
long_description_content_type='text/markdown',
maintainer='Parcs nationaux des Écrins et des Cévennes',
maintainer_email='[email protected]',
url='https://github.com/PnX-SI/Utils-Flask-SQLAlchemy',
packages=setuptools.find_packages('src'),
package_dir={'': 'src'},
long_description_content_type="text/markdown",
maintainer="Parcs nationaux des Écrins et des Cévennes",
maintainer_email="[email protected]",
url="https://github.com/PnX-SI/Utils-Flask-SQLAlchemy",
packages=setuptools.find_packages("src"),
package_dir={"": "src"},
install_requires=requirements,
extras_require={
'tests': [
'pytest',
'geoalchemy2',
'shapely',
'jsonschema',
'flask-marshmallow',
'marshmallow-sqlalchemy',
"tests": [
"pytest",
"geoalchemy2",
"shapely",
"jsonschema",
"flask-marshmallow",
"marshmallow-sqlalchemy",
],
},
entry_points={
'alembic': [
'migrations = utils_flask_sqla.migrations:versions',
"alembic": [
"migrations = utils_flask_sqla.migrations:versions",
],
'pytest11': [
'sqla = utils_flask_sqla.tests.plugin',
"pytest11": [
"sqla = utils_flask_sqla.tests.plugin",
],
'flask.commands': [
'db = utils_flask_sqla.commands:db_cli',
"flask.commands": [
"db = utils_flask_sqla.commands:db_cli",
],
},
classifiers=['Development Status :: 1 - Planning',
'Intended Audience :: Developers',
'Natural Language :: English',
'Programming Language :: Python :: 3',
'License :: OSI Approved :: GNU Affero General Public License v3',
'Operating System :: OS Independent'],
classifiers=[
"Development Status :: 1 - Planning",
"Intended Audience :: Developers",
"Natural Language :: English",
"Programming Language :: Python :: 3",
"License :: OSI Approved :: GNU Affero General Public License v3",
"Operating System :: OS Independent",
],
)
160 changes: 87 additions & 73 deletions src/utils_flask_sqla/commands.py
Original file line number Diff line number Diff line change
Expand Up @@ -13,54 +13,59 @@


def box_drowing(up, down, left, right):
if not up and not down and not left and not right:
return '─'
elif up and not down and not left and not right:
return '┸'
elif not up and down and not left and not right:
return '┰'
elif up and down and not left and not right:
return '┃'
elif up and not down and left and not right:
return '┛'
elif up and not down and not left and right:
return '┗'
elif not up and not down and left and right:
return '━'
elif not up and down and left and not right:
return '┓'
elif not up and down and not left and right:
return '┏'
elif up and down and not left and right:
return '┣'
elif up and down and left and not right:
return '┫'
elif up and not down and left and right:
return '┻'
elif not up and down and left and right:
return '┳'
elif up and down and left and right:
return '╋'
if not up and not down and not left and not right:
return "─"
elif up and not down and not left and not right:
return "┸"
elif not up and down and not left and not right:
return "┰"
elif up and down and not left and not right:
return "┃"
elif up and not down and left and not right:
return "┛"
elif up and not down and not left and right:
return "┗"
elif not up and not down and left and right:
return "━"
elif not up and down and left and not right:
return "┓"
elif not up and down and not left and right:
return "┏"
elif up and down and not left and right:
return "┣"
elif up and down and left and not right:
return "┫"
elif up and not down and left and right:
return "┻"
elif not up and down and left and right:
return "┳"
elif up and down and left and right:
return "╋"
else:
raise Exception("Unexpected box drowing symbol")


@db_cli.command()
@click.option('-d', '--directory', default=None,
help=('Migration script directory (default is "migrations")'))
@click.option('--sql', is_flag=True,
help=('Don\'t emit SQL to database - dump to standard output '
'instead'))
@click.option('--tag', default=None,
help=('Arbitrary "tag" name - can be used by custom env.py '
'scripts'))
@click.option('-x', '--x-arg', multiple=True,
help='Additional arguments consumed by custom env.py scripts')
@click.option(
"-d",
"--directory",
default=None,
help=('Migration script directory (default is "migrations")'),
)
@click.option(
"--sql", is_flag=True, help=("Don't emit SQL to database - dump to standard output " "instead")
)
@click.option(
"--tag", default=None, help=('Arbitrary "tag" name - can be used by custom env.py ' "scripts")
)
@click.option(
"-x", "--x-arg", multiple=True, help="Additional arguments consumed by custom env.py scripts"
)
@with_appcontext
def autoupgrade(directory, sql, tag, x_arg):
"""Upgrade all branches to head."""
db = current_app.extensions['sqlalchemy'].db
migrate = current_app.extensions['migrate'].migrate
db = current_app.extensions["sqlalchemy"].db
migrate = current_app.extensions["migrate"].migrate
config = migrate.get_config(directory, x_arg)
script = ScriptDirectory.from_config(config)
heads = set(script.get_heads())
Expand All @@ -69,36 +74,41 @@ def autoupgrade(directory, sql, tag, x_arg):
# get_current_heads does not return implicit revision through dependecies, get_all_current does
current_heads = set(map(lambda rev: rev.revision, script.get_all_current(current_heads)))
for head in current_heads - heads:
revision = head + '@head'
revision = head + "@head"
flask_migrate.upgrade(directory, revision, sql, tag, x_arg)


@db_cli.command()
@click.option('-d', '--directory', default=None,
help=('Migration script directory (default is "migrations")'))
@click.option('-x', '--x-arg', multiple=True,
help='Additional arguments consumed by custom env.py scripts')
@click.argument('branches', nargs=-1)
@click.option(
"-d",
"--directory",
default=None,
help=('Migration script directory (default is "migrations")'),
)
@click.option(
"-x", "--x-arg", multiple=True, help="Additional arguments consumed by custom env.py scripts"
)
@click.argument("branches", nargs=-1)
@with_appcontext
def status(directory, x_arg, branches):
"""Show all revisions sorted by branches."""
db = current_app.extensions['sqlalchemy'].db
migrate = current_app.extensions['migrate'].migrate
db = current_app.extensions["sqlalchemy"].db
migrate = current_app.extensions["migrate"].migrate

config = migrate.get_config(directory, x_arg)
script = ScriptDirectory.from_config(config)
migration_context = MigrationContext.configure(db.session.connection())

current_heads = migration_context.get_current_heads()
applied_rev = set(script.iterate_revisions(current_heads, 'base'))
applied_rev = set(script.iterate_revisions(current_heads, "base"))

bases = [ script.get_revision(base) for base in script.get_bases() ]
heads = [ script.get_revision(head) for head in script.get_heads() ]
bases = [script.get_revision(base) for base in script.get_bases()]
heads = [script.get_revision(head) for head in script.get_heads()]

outdated = False
for branch_base in sorted(bases, key=lambda rev: next(iter(rev.branch_labels))):
output = StringIO()
branch, = branch_base.branch_labels
(branch,) = branch_base.branch_labels
if branches and branch not in branches:
continue
levels = defaultdict(set)
Expand All @@ -116,13 +126,11 @@ def status(directory, x_arg, branches):
down_revisions = [rev.down_revision]
else:
down_revisions = []
down_revisions = [ script.get_revision(r) for r in down_revisions ]
down_revisions = [script.get_revision(r) for r in down_revisions]

next_revisions = [ script.get_revision(r) for r in rev.nextrev ]
next_revisions = [script.get_revision(r) for r in rev.nextrev]

if (rev.is_merge_point
and (not seen.issuperset(down_revisions)
or rev in todo)):
if rev.is_merge_point and (not seen.issuperset(down_revisions) or rev in todo):
continue
seen.add(rev)

Expand All @@ -139,38 +147,44 @@ def status(directory, x_arg, branches):
all_levels = list(chain(down_levels, next_levels))
min_level = min(all_levels, default=0)
max_level = max(all_levels, default=0)
symbol = ''
symbol = ""
for i in range(max_level + 1):
if i < min_level:
symbol += ' '
symbol += " "
else:
symbol += box_drowing(
up = i in down_levels,
down = i in next_levels,
left = i > min_level,
right = i < max_level,
up=i in down_levels,
down=i in next_levels,
left=i > min_level,
right=i < max_level,
)

check = 'x' if rev in applied_rev else ' '
check = "x" if rev in applied_rev else " "
if branch_base in applied_rev and rev in applied_rev:
fg = 'white'
fg = "white"
elif branch_base in applied_rev:
outdated = True
branch_outdated = True
fg = 'red'
fg = "red"
else:
fg = None
print(click.style(f" [{check}] {symbol} {rev.revision} {rev.doc}", fg=fg), file=output)
print(
click.style(f" [{check}] {symbol} {rev.revision} {rev.doc}", fg=fg), file=output
)

if branch_base in applied_rev:
fg = 'white'
mark = ' '
mark += click.style('×', fg='red') if branch_outdated else click.style('✓', fg='green')
fg = "white"
mark = " "
mark += click.style("×", fg="red") if branch_outdated else click.style("✓", fg="green")
else:
fg = None
mark = ''
click.echo(click.style(f"[{branch}", bold=True, fg=fg) + mark + click.style("]", bold=True, fg=fg))
mark = ""
click.echo(
click.style(f"[{branch}", bold=True, fg=fg) + mark + click.style("]", bold=True, fg=fg)
)
click.echo(output.getvalue(), nl=False)

if outdated:
click.secho("Some branches are outdated, you can upgrade with 'autoupgrade' sub-command.", fg="red")
click.secho(
"Some branches are outdated, you can upgrade with 'autoupgrade' sub-command.", fg="red"
)
17 changes: 5 additions & 12 deletions src/utils_flask_sqla/errors.py
Original file line number Diff line number Diff line change
Expand Up @@ -4,22 +4,15 @@ def __init__(self, message, status_code=500):
self.message = message
self.status_code = status_code
raised_error = self.__class__.__name__
log_message = "Raise: {}, {}".format(
raised_error,
message
)
log_message = "Raise: {}, {}".format(raised_error, message)

def to_dict(self):
return {
'message': self.message,
'status_code': self.status_code,
'raisedError': self.__class__.__name__
"message": self.message,
"status_code": self.status_code,
"raisedError": self.__class__.__name__,
}

def __str__(self):
message = "Error {}, Message: {}, raised error: {}"
return message.format(
self.status_code,
self.message,
self.__class__.__name__
)
return message.format(self.status_code, self.message, self.__class__.__name__)
Loading

0 comments on commit ccbf60c

Please sign in to comment.