Gitlab Community Edition Instance

Commit 26c0678e authored by mhellka's avatar mhellka
Browse files

Fix all flake8 warnings (including serious ones)

parent 9c2287d4
......@@ -13,4 +13,7 @@ docs: venv $(DOCS_ALL) $(SRC_ALL)
dist: venv $(SRC_ALL)
venv/bin/python setup.py sdist bdist_wheel
_PHONY: venv docs dist
lint: venv
venv/bin/flake8 src/
_PHONY: venv docs dist lint
import sys
import pycdstar3.cli
def main():
return pycdstar3.cli.main(*sys.argv[1:])
if __name__ == '__main__':
sys.exit(main() or 0)
......@@ -33,7 +33,7 @@ subparsers = parser.add_subparsers(title="available commands",
printer = Printer(level=0, file=sys.stderr)
def main(*args):
def main(*args): # noqa: C901
# Load and register all built-in commands
for name in BUILDIN_COMMANDS:
importlib.import_module(".commands." + name, __name__).register(subparsers)
......
......@@ -60,7 +60,6 @@ class FileProgress:
pbar.close()
class Printer:
""" Helper class to print to stderr based on verbosity levels."""
__slots__ = ("verbosity", "quiet", "file")
......
"""
Manage access control lists (ACL)
"""
import os
from pycdstar3.client import FormUpdate
from pycdstar3.cli import printer
......
......@@ -13,15 +13,16 @@ def register(subparsers):
parser.add_argument("-%", "-p", "--progress", action="store_true",
help="Show progress bar for large files or slow downloads")
parser.add_argument("--resume", action="store_true",
help="If a <DST>.part file exists, try to resume an interrupted download. "
"Also, keep the *.part file on any errors.")
help="If a <DST>.part file exists, try to resume an"
" interrupted download. Also, keep the *.part file"
" on any errors.")
parser.add_argument("-f", "--force", action="store_true", help="Overwrite local files without asking")
parser.add_argument("SRC", help="File identifier")
parser.add_argument("DST", nargs="?", help="Destination filename, directory or '-' for stdout. (default: '-')")
parser.set_defaults(main=get)
def get(ctx, args):
def get(ctx, args): # noqa: C901
client, vault, archive, file = ctx.resolve(args.SRC)
resume = args.resume
progress = args.progress
......@@ -66,9 +67,11 @@ def get(ctx, args):
from tqdm import tqdm
pbar = tqdm(total=size+offset, initial=offset, unit='b', unit_scale=True, unit_divisor=1024, dynamic_ncols=True,
file=printer.file)
def write(chunk):
pbar.update(len(chunk))
out.write(chunk)
def close():
pbar.close()
out.close()
......@@ -87,7 +90,7 @@ def get(ctx, args):
printer.v("Done!", file, vault, archive, hbytes(size + offset))
except (KeyboardInterrupt, Exception) as e:
except (KeyboardInterrupt, Exception):
if close:
close()
if partfile and os.path.exists(partfile) and not resume:
......@@ -96,6 +99,4 @@ def get(ctx, args):
except OSError:
printer("Failed to delete partial download: {}", partfile)
raise
raise
......@@ -39,7 +39,7 @@ def command(ctx, args):
elif args.auth:
auth = ("basic", args.auth)
else:
method = ask("Auth method (basic or token)", "basic", r"^(basic|token)$");
method = ask("Auth method (basic or token)", "basic", r"^(basic|token)$")
if method == "basic":
auth = (method, ask("Username") + ":" + ask("Password"))
else:
......@@ -69,4 +69,4 @@ def ask(q, default=None, rx=None):
if rx and not re.match(rx, val):
print("This does not look right. Try again...")
continue
return val
\ No newline at end of file
return val
......@@ -13,7 +13,9 @@ def register(subparsers):
parser.add_argument("-n", "--dry-run", action="store_true",
help="Do not upload anything, just print what would have been uploaded")
parser.add_argument("--flat", action="store_true",
help="Strip all directory names from the local path and store all files into the root path (e.g. ./path/to/file.txt would be uploaded as /file.txt)")
help="Strip all directory names from the local path and store"
" all files into the root path (e.g. ./path/to/file.txt"
" would be uploaded as /file.txt)")
parser.add_argument("-x", "--exclude", metavar="GLOB", action="append",
help="Exclude files by glob pattern")
parser.add_argument("-i", "--include", metavar="GLOB", action="append",
......@@ -43,7 +45,7 @@ def findfiles(flist, include_hidden=False):
raise CliError("Not a file: " + entry)
def command(ctx, args):
def command(ctx, args): # noqa: C901
client, vault, archive, rfile = ctx.resolve(args.TARGET)
inc = [compile_glob(rule).match for rule in args.include or []]
exc = [compile_glob(rule).match for rule in args.exclude or []]
......
import os
import urllib.parse
from contextlib import contextmanager
from typing import Tuple, Optional
from pycdstar3.cli import printer, CliError
......@@ -57,7 +56,8 @@ class CliContext:
oref = ref
if ref.startswith("http://") or ref.startswith("https://"):
url, v3, rest = ref.partition("/v3/")
if not v3: raise ValueError("Not a CDSTAR url: " + oref)
if not v3:
raise ValueError("Not a CDSTAR url: " + oref)
client = self.connect(url + v3)
ref = '/' + rest
else:
......@@ -124,7 +124,7 @@ class Config:
def __getitem__(self, item):
try:
return self.data[item]
except KeyError as e:
except KeyError:
raise KeyError("Missing config field: " + item)
def __contains__(self, item):
......
......@@ -278,12 +278,12 @@ class FormUpdate:
:param type: Mime-type of the upload.
:return: self
"""
if not target.startswith("/"):
raise ValueError("Upload target filename MUST start with '/'")
if not name.startswith("/"):
name = "/" + name
if isinstance(src, str):
self.fields.append((target, (os.path.basename(src), open(src, "rb"), type)))
self.fields.append((name, (os.path.basename(src), open(src, "rb"), type)))
elif hasattr(src, 'fileno') or hasattr(src, 'getvalue'):
self.fields.append((target, (os.path.basename(src), src, type)))
self.fields.append((name, (os.path.basename(src), src, type)))
else:
raise ValueError("Source must be a file path (str), byte buffer or opened file")
return self
......@@ -308,8 +308,8 @@ class FormUpdate:
"""
attr = "meta:" + field
if target:
attr += ":/" + target.lstrip("/")
if file:
attr += ":/" + file.lstrip("/")
if values:
for val in values:
......
Supports Markdown
0% or .
You are about to add 0 people to the discussion. Proceed with caution.
Finish editing this message first!
Please register or to comment