Skip to content

Commit

Permalink
Run flake8 via pre-commit and resolve findings with the help of black (
Browse files Browse the repository at this point in the history
…#125)

* Add black+flake8 to pre-commit

* Apply black

* Handle flake8 findings

* news
  • Loading branch information
dbast authored Apr 24, 2023
1 parent b0199ae commit 2ec702e
Show file tree
Hide file tree
Showing 22 changed files with 344 additions and 257 deletions.
9 changes: 9 additions & 0 deletions .pre-commit-config.yaml
Original file line number Diff line number Diff line change
Expand Up @@ -23,3 +23,12 @@ repos:
rev: 5.12.0
hooks:
- id: isort
- repo: https://github.com/psf/black
rev: 23.1.0
hooks:
- id: black
args: [--skip-string-normalization]
- repo: https://github.com/pycqa/flake8
rev: 6.0.0
hooks:
- id: flake8
17 changes: 12 additions & 5 deletions menuinst/_legacy/__init__.py
Original file line number Diff line number Diff line change
Expand Up @@ -68,15 +68,22 @@ def install(path, remove=False, prefix=None, recursing=False, root_prefix=None):
retcode = 1
try:
if not recursing:
retcode = runAsAdmin([join(root_prefix, 'python'), '-c',
"import menuinst; menuinst.install(%r, %r, %r, %r, %r)" % (
path, bool(remove), prefix, True, root_prefix)])
retcode = runAsAdmin(
[
join(root_prefix, 'python'),
'-c',
"import menuinst; menuinst.install(%r, %r, %r, %r, %r)"
% (path, bool(remove), prefix, True, root_prefix),
]
)
except OSError:
pass

if retcode != 0:
logging.warn("Insufficient permissions to write menu folder. "
"Falling back to user location")
logging.warn(
"Insufficient permissions to write menu folder. "
"Falling back to user location"
)
_install(path, remove, prefix, mode='user', root_prefix=root_prefix)
else:
_install(path, remove, prefix, mode='user', root_prefix=root_prefix)
14 changes: 4 additions & 10 deletions menuinst/_legacy/main.py
Original file line number Diff line number Diff line change
Expand Up @@ -9,19 +9,13 @@
def main():
from optparse import OptionParser

p = OptionParser(
usage="usage: %prog [options] MENU_FILE",
description="install a menu item")
p = OptionParser(usage="usage: %prog [options] MENU_FILE", description="install a menu item")

p.add_option('-p', '--prefix',
action="store",
default=DEFAULT_PREFIX)
p.add_option('-p', '--prefix', action="store", default=DEFAULT_PREFIX)

p.add_option('--remove',
action="store_true")
p.add_option('--remove', action="store_true")

p.add_option('--version',
action="store_true")
p.add_option('--version', action="store_true")

opts, args = p.parse_args()

Expand Down
2 changes: 1 addition & 1 deletion menuinst/_legacy/utils.py
Original file line number Diff line number Diff line change
Expand Up @@ -6,7 +6,7 @@
def rm_empty_dir(path):
try:
os.rmdir(path)
except OSError: # directory might not exist or not be empty
except OSError: # directory might not exist or not be empty
pass


Expand Down
59 changes: 38 additions & 21 deletions menuinst/_legacy/win32.py
Original file line number Diff line number Diff line change
Expand Up @@ -66,8 +66,6 @@ def ensure_pad(name, pad="_"):


def to_unicode(var, codec=locale.getpreferredencoding()):
if sys.version_info[0] < 3 and isinstance(var, unicode):
return var
if not codec:
codec = "utf-8"
if hasattr(var, "decode"):
Expand All @@ -79,7 +77,7 @@ def to_bytes(var, codec=locale.getpreferredencoding()):
if isinstance(var, bytes):
return var
if not codec:
codec="utf-8"
codec = "utf-8"
if hasattr(var, "encode"):
var = var.encode(codec)
return var
Expand All @@ -106,22 +104,31 @@ def substitute_env_variables(text, dir):
(u'${PREFIX}', env_prefix),
(u'${ROOT_PREFIX}', root_prefix),
(u'${DISTRIBUTION_NAME}', os.path.split(root_prefix)[-1].capitalize()),
(u'${PYTHON_SCRIPTS}',
os.path.normpath(join(env_prefix, u'Scripts')).replace(u"\\", u"/")),
(
u'${PYTHON_SCRIPTS}',
os.path.normpath(join(env_prefix, u'Scripts')).replace(u"\\", u"/"),
),
(u'${MENU_DIR}', join(env_prefix, u'Menu')),
(u'${PERSONALDIR}', dir['documents']),
(u'${USERPROFILE}', dir['profile']),
(u'${ENV_NAME}', env_name),
(u'${PY_VER}', u'%d' % (py_major_ver)),
(u'${PLATFORM}', u"(%s-bit)" % py_bitness),
):
):
if b:
text = text.replace(a, b)
return text


class Menu(object):
def __init__(self, name, prefix=unicode_root_prefix, env_name=u"", mode=None, root_prefix=unicode_root_prefix):
def __init__(
self,
name,
prefix=unicode_root_prefix,
env_name=u"",
mode=None,
root_prefix=unicode_root_prefix,
):
"""
Prefix is the system prefix to be used -- this is needed since
there is the possibility of a different Python's packages being managed.
Expand All @@ -130,9 +137,13 @@ def __init__(self, name, prefix=unicode_root_prefix, env_name=u"", mode=None, ro
# bytestrings passed in need to become unicode
self.prefix = to_unicode(prefix)
self.root_prefix = to_unicode(root_prefix)
used_mode = mode if mode else ('user' if exists(join(self.prefix, u'.nonadmin')) else 'system')
logger.debug("Menu: name: '%s', prefix: '%s', env_name: '%s', mode: '%s', used_mode: '%s', root_prefix: '%s'"
% (name, self.prefix, env_name, mode, used_mode, root_prefix))
used_mode = (
mode if mode else ('user' if exists(join(self.prefix, u'.nonadmin')) else 'system')
)
logger.debug(
"Menu: name: '%s', prefix: '%s', env_name: '%s', mode: '%s', used_mode: '%s', root_prefix: '%s'" # noqa
% (name, self.prefix, env_name, mode, used_mode, root_prefix)
)
try:
self.set_dir(name, self.prefix, env_name, used_mode, root_prefix)
except WindowsError:
Expand All @@ -141,11 +152,13 @@ def __init__(self, name, prefix=unicode_root_prefix, env_name=u"", mode=None, ro
# required. If the process isn't elevated, we get the
# WindowsError
if 'user' in dirs_src and used_mode == 'system':
logger.warn("Insufficient permissions to write menu folder. "
"Falling back to user location")
logger.warn(
"Insufficient permissions to write menu folder. "
"Falling back to user location"
)
try:
self.set_dir(name, self.prefix, env_name, 'user')
except:
except: # noqa
pass
else:
logger.fatal("Unable to create AllUsers menu folder")
Expand Down Expand Up @@ -194,9 +207,11 @@ def quote_args(args):
# cmd.exe /K or /C expects a single string argument and requires
# doubled-up quotes when any sub-arguments have spaces:
# https://stackoverflow.com/a/6378038/3257826
if (len(args) > 2 and ("CMD.EXE" in args[0].upper() or "%COMSPEC%" in args[0].upper())
and (args[1].upper() == '/K' or args[1].upper() == '/C')
and any(' ' in arg for arg in args[2:])
if (
len(args) > 2
and ("CMD.EXE" in args[0].upper() or "%COMSPEC%" in args[0].upper())
and (args[1].upper() == '/K' or args[1].upper() == '/C')
and any(' ' in arg for arg in args[2:])
):
args = [
ensure_pad(args[0], '"'), # cmd.exe
Expand All @@ -222,11 +237,11 @@ def create(self, remove=False):
fix_win_slashes = [0]
prefix = self.menu.prefix.replace('/', '\\')
unicode_root_prefix = self.menu.root_prefix.replace('/', '\\')
root_py = join(unicode_root_prefix, u"python.exe")
root_py = join(unicode_root_prefix, u"python.exe")
root_pyw = join(unicode_root_prefix, u"pythonw.exe")
env_py = join(prefix, u"python.exe")
env_py = join(prefix, u"python.exe")
env_pyw = join(prefix, u"pythonw.exe")
cwp_py = [root_py, join(unicode_root_prefix, u'cwp.py'), prefix, env_py]
cwp_py = [root_py, join(unicode_root_prefix, u'cwp.py'), prefix, env_py]
cwp_pyw = [root_pyw, join(unicode_root_prefix, u'cwp.py'), prefix, env_pyw]
if "pywscript" in self.shortcut:
args = cwp_pyw
Expand All @@ -241,7 +256,7 @@ def create(self, remove=False):
elif "script" in self.shortcut:
# It is unclear whether running through cwp.py is what we want here. In
# the long term I would rather this was made an explicit choice.
args = [root_py, join(unicode_root_prefix, u'cwp.py'), prefix]
args = [root_py, join(unicode_root_prefix, u'cwp.py'), prefix]
fix_win_slashes = [len(args)]
args += self.shortcut["script"].split()
extend_script_args(args, self.shortcut)
Expand Down Expand Up @@ -287,7 +302,9 @@ def create(self, remove=False):
if self.shortcut.get('quicklaunch') and 'quicklaunch' in self.menu.dir:
dst_dirs.append(self.menu.dir['quicklaunch'])

name_suffix = " ({})".format(self.menu.dir['env_name']) if self.menu.dir['env_name'] else ""
name_suffix = (
" ({})".format(self.menu.dir['env_name']) if self.menu.dir['env_name'] else ""
)
for dst_dir in dst_dirs:
name = substitute_env_variables(self.shortcut['name'], self.menu.dir)
dst = join(dst_dir, name + name_suffix + '.lnk')
Expand Down
13 changes: 7 additions & 6 deletions menuinst/_schema.py
Original file line number Diff line number Diff line change
Expand Up @@ -2,6 +2,8 @@
Generate JSON schemas from pydantic models
"""

# flake8: noqa

import json
from logging import getLogger
from pathlib import Path
Expand Down Expand Up @@ -252,7 +254,9 @@ class CFBundleDocumentTypesModel(BaseModel):
.. entitlements: https://developer.apple.com/documentation/bundleresources/entitlements
"""
link_in_bundle: Optional[Dict[constr(min_length=1), constr(regex=r"^(?!\/)(?!\.\./).*")]] = None
link_in_bundle: Optional[
Dict[constr(min_length=1), constr(regex=r"^(?!\/)(?!\.\./).*")]
] = None
"""
Paths that should be symlinked into the shortcut app bundle.
It takes a mapping of source to destination paths. Destination paths must be
Expand Down Expand Up @@ -346,10 +350,7 @@ def dump_schema_to_json(write=True):
def dump_default_to_json(write=True):
here = Path(__file__).parent
default_item = MenuItem(
name="REQUIRED",
description="REQUIRED",
command=["REQUIRED"],
platforms={}
name="REQUIRED", description="REQUIRED", command=["REQUIRED"], platforms={}
).dict()
default_item["platforms"] = {
"win": Windows().dict(),
Expand All @@ -362,7 +363,7 @@ def dump_default_to_json(write=True):
**{
"$id": "https://schemas.conda.io/menuinst-1.schema.json",
"$schema": "https://json-schema.org/draft-07/schema",
}
},
).dict()
for platform_value in default["menu_items"][0]["platforms"].values():
for key in list(platform_value.keys()):
Expand Down
13 changes: 7 additions & 6 deletions menuinst/platforms/base.py
Original file line number Diff line number Diff line change
Expand Up @@ -147,11 +147,15 @@ def placeholders(self) -> Dict[str, str]:
"MENU_ITEM_LOCATION": str(self.location),
}

def render_key(self, key: str, slug: bool = False, extra: Optional[Dict[str, str]] = None) -> Any:
def render_key(
self, key: str, slug: bool = False, extra: Optional[Dict[str, str]] = None
) -> Any:
value = self.metadata.get(key)
return self.render(value, slug=slug, extra=extra)

def render(self, value: Any, slug: bool = False, extra: Optional[Dict[str, str]] = None) -> Any:
def render(
self, value: Any, slug: bool = False, extra: Optional[Dict[str, str]] = None
) -> Any:
if value in (None, True, False):
return value
kwargs = {
Expand All @@ -161,10 +165,7 @@ def render(self, value: Any, slug: bool = False, extra: Optional[Dict[str, str]]
if isinstance(value, str):
return self.menu.render(value, **kwargs)
if hasattr(value, "items"):
return {
key: self.menu.render(value, **kwargs)
for key, value in value.items()
}
return {key: self.menu.render(value, **kwargs) for key, value in value.items()}
return [self.menu.render(item, **kwargs) for item in value]

def _precreate(self):
Expand Down
10 changes: 7 additions & 3 deletions menuinst/platforms/linux.py
Original file line number Diff line number Diff line change
Expand Up @@ -21,13 +21,15 @@ class LinuxMenu(Menu):
menuinst will populate the relevant XML config and create a .directory entry
"""

_system_config_directory = Path("/etc/xdg/")
_system_data_directory = Path("/usr/share")
_system_data_directory = Path("/usr/share")

def __init__(self, *args, **kwargs):
super().__init__(*args, **kwargs)
if self.mode == "system":
self.config_directory = self._system_config_directory
self.data_directory =self._system_data_directory
self.data_directory = self._system_data_directory
else:
self.config_directory = Path(
os.environ.get("XDG_CONFIG_HOME", "~/.config")
Expand All @@ -37,7 +39,9 @@ def __init__(self, *args, **kwargs):
).expanduser()

# XML Config paths
self.system_menu_config_location = self._system_config_directory / "menus" / "applications.menu"
self.system_menu_config_location = (
self._system_config_directory / "menus" / "applications.menu"
)
self.menu_config_location = self.config_directory / "menus" / "applications.menu"
# .desktop / .directory paths
self.directory_entry_location = (
Expand Down
2 changes: 1 addition & 1 deletion menuinst/platforms/osx.py
Original file line number Diff line number Diff line change
Expand Up @@ -226,6 +226,6 @@ def _sign_with_entitlements(self):
"--deep",
"--entitlements",
entitlements_path,
self.location
self.location,
]
)
6 changes: 4 additions & 2 deletions menuinst/platforms/win.py
Original file line number Diff line number Diff line change
Expand Up @@ -91,7 +91,9 @@ def _conda_exe_path_candidates(self):
self.base_prefix / "bin" / "micromamba.exe",
)

def render(self, value: Any, slug: bool = False, extra: Optional[Dict[str, str]] = None) -> Any:
def render(
self, value: Any, slug: bool = False, extra: Optional[Dict[str, str]] = None
) -> Any:
"""
We extend the render method here to replace forward slashes with backslashes.
We ONLY do it if the string does not start with /, because it might
Expand Down Expand Up @@ -367,7 +369,7 @@ def _unregister_file_extensions(self):
unregister_file_extension(ext, identifier, mode=self.parent.mode)

def _register_url_protocols(self):
"See https://learn.microsoft.com/en-us/previous-versions/windows/internet-explorer/ie-developer/platform-apis/aa767914(v=vs.85)"
"See https://learn.microsoft.com/en-us/previous-versions/windows/internet-explorer/ie-developer/platform-apis/aa767914(v=vs.85)" # noqa
protocols = self.metadata["url_protocols"]
if not protocols:
return
Expand Down
Loading

0 comments on commit 2ec702e

Please sign in to comment.