Skip to content

Commit

Permalink
lint (freebsd#52)
Browse files Browse the repository at this point in the history
reduce flake8 warnings
  • Loading branch information
dgeo authored Nov 29, 2024
1 parent 32ba869 commit e59af55
Show file tree
Hide file tree
Showing 14 changed files with 44 additions and 38 deletions.
12 changes: 9 additions & 3 deletions flake8.sh
Original file line number Diff line number Diff line change
Expand Up @@ -6,23 +6,29 @@ find ./iocage_cli ./iocage_lib -name \*.py -exec flake8 --max-line-length=100 --
num_errors_after=`cat ${tmpafter} | wc -l`
echo "Current Error Count: ${num_errors_after}"

# get current branch/tag
cur=$(git status -sb | awk '/^## [^H]/{print $2}')
[ -z "${cur}" ] && cur=$(git branch -q | awk '/^\* .*/{gsub("\)$","",$NF);print $NF}')

# Get new tags from remote
git fetch --tags --quiet
# Get latest tag name
last_release=$(git describe --tags `git rev-list --tags --max-count=1`)

echo "Comparing with last stable release: ${last_release}"
git checkout ${last_release}
git checkout -q ${last_release}

tmpbefore=$(mktemp)
find ./iocage_cli ./iocage_lib -name \*.py -exec flake8 --max-line-length=100 --ignore=E127,E203,W503,F811,W504 {} + > ${tmpbefore}
num_errors_before=`cat ${tmpbefore} | wc -l`
echo "${last_release}'s Error Count: ${num_errors_before}"

# The number may be lower then the last release, but that doesn't tell them that they're not higher than they should be.
num_errors_adjusted=$((num_errors_before-num_errors_after))
num_errors_adjusted=$((num_errors_before - num_errors_after))

[ -n "${cur}" ] && git checkout -q ${cur}

if [ ${num_errors_adjusted} != 0 ] && [ ${num_errors_adjusted} != ${num_errors_before} ]; then
if [ ${num_errors_adjusted} != 0 ] && [ ${num_errors_adjusted} -gt ${num_errors_before} ]; then
echo "New Flake8 errors were introduced:"
diff -u ${tmpbefore} ${tmpafter}
exit 1
Expand Down
2 changes: 1 addition & 1 deletion iocage_cli/list.py
Original file line number Diff line number Diff line change
Expand Up @@ -93,7 +93,7 @@ def cli(dataset_type, header, _long, remote, http, plugins, _sort, quick,
else:
ioc_common.logit({
"level": "INFO",
"message": "\t".join(map(str,item))
"message": "\t".join(map(str, item))
})
else:
ioc_common.logit({"level": "INFO", "message": _list})
2 changes: 1 addition & 1 deletion iocage_cli/snaplist.py
Original file line number Diff line number Diff line change
Expand Up @@ -50,7 +50,7 @@ def cli(header, jail, _long, _sort):
cols.extend(["NAME", "CREATED", "RSIZE", "USED"])
table.header(cols)
# We get an infinite float otherwise.
table.set_cols_dtype(["t"]*len(cols))
table.set_cols_dtype(["t"] * len(cols))
table.add_rows(snap_list, header=False)
ioc_common.logit({
"level" : "INFO",
Expand Down
10 changes: 5 additions & 5 deletions iocage_cli/snapremove.py
Original file line number Diff line number Diff line change
Expand Up @@ -34,14 +34,14 @@
@click.option("--name", "-n", help="The snapshot name. This will be what comes"
" after @", required=True)
@click.option("--force", "-f", is_flag=True, default=False,
help="Force removal (required for -n ALL)")
help="Force removal (required for -n ALL)")
def cli(jail, name, force):
"""Removes a snapshot from a user supplied jail."""
if name == 'ALL' and not force:
ioc_common.logit({
"level": "EXCEPTION",
"message": 'Usage: iocage snapremove [OPTIONS] JAILS...\n'
'\nError: Mass snapshot deletion requires "force" (-f).'
})
"level": "EXCEPTION",
"message": 'Usage: iocage snapremove [OPTIONS] JAILS...\n'
'\nError: Mass snapshot deletion requires "force" (-f).'
})
skip_jails = jail != 'ALL'
ioc.IOCage(jail=jail, skip_jails=skip_jails).snap_remove(name)
2 changes: 1 addition & 1 deletion iocage_cli/update.py
Original file line number Diff line number Diff line change
Expand Up @@ -42,7 +42,7 @@
"--server", "-s", default="download.freebsd.org",
help="Server to fetch from."
)
@click.option(
@click.option(
"--verify/--noverify", "-V/-NV", default=True,
help="Enable or disable verifying SSL cert for HTTP fetching."
)
Expand Down
1 change: 0 additions & 1 deletion iocage_lib/ioc_check.py
Original file line number Diff line number Diff line change
Expand Up @@ -132,4 +132,3 @@ def __check_datasets__(self):
f"exec={prop} (should be on)"
},
_callback=self.callback)

4 changes: 2 additions & 2 deletions iocage_lib/ioc_common.py
Original file line number Diff line number Diff line change
Expand Up @@ -1021,9 +1021,9 @@ def gen_nat_ip(ip_prefix):
inuse = get_used_ips()

for i in range(256):
for l in range(1, 256, 4):
for j in range(1, 256, 4):
network = ipaddress.IPv4Network(
f'{ip_prefix}.{i}.{l}/30', strict=False
f'{ip_prefix}.{i}.{j}/30', strict=False
)
pair = [_ip.exploded for _ip in network.hosts()]

Expand Down
2 changes: 1 addition & 1 deletion iocage_lib/ioc_create.py
Original file line number Diff line number Diff line change
Expand Up @@ -958,7 +958,7 @@ def create_install_packages(self, jail_uuid, location,
iocage_lib.ioc_common.consume_and_log(
_exec,
callback=self.callback,
log=not(self.silent)
log=not (self.silent)
)
except iocage_lib.ioc_exceptions.CommandFailed as e:
nonempty_lines = [line.rstrip() for line in e.message if line.rstrip()]
Expand Down
2 changes: 1 addition & 1 deletion iocage_lib/ioc_json.py
Original file line number Diff line number Diff line change
Expand Up @@ -976,7 +976,7 @@ def check_jail_config(self, conf):
# the best case here is to parse fstab entries and determine
# which release is being used and check it for freebsd-version
fstab = iocage_lib.ioc_fstab.IOCFstab(host_hostuuid, 'list')
fstab.__validate_fstab__([l[1] for l in fstab.fstab], 'all')
fstab.__validate_fstab__([i[1] for i in fstab.fstab], 'all')
for index, fstab_entry in fstab.fstab_list():
if fstab_entry[1].rstrip('/') == os.path.join(
freebsd_version_path, 'bin'
Expand Down
2 changes: 1 addition & 1 deletion iocage_lib/ioc_plugin.py
Original file line number Diff line number Diff line change
Expand Up @@ -1232,7 +1232,7 @@ def __update_pkg_remove__(self, jid):
iocage_lib.ioc_common.consume_and_log(
_exec,
callback=self.callback,
log=not(self.silent)
log=not (self.silent)
)
except iocage_lib.ioc_exceptions.CommandFailed as e:
self.__rollback_jail__(name="update")
Expand Down
6 changes: 3 additions & 3 deletions iocage_lib/ioc_start.py
Original file line number Diff line number Diff line change
Expand Up @@ -1462,9 +1462,9 @@ def __check_dhcp_or_accept_rtadv__(self, ipv4, enable):
entries = {
k: v.replace("'", '').replace('"', '')
for k, v in map(
lambda l: [e.strip() for e in l.strip().split('=', 1)],
lambda j: [e.strip() for e in j.strip().split('=', 1)],
filter(
lambda l: not l.strip().startswith('#') and '=' in l, f.readlines()
lambda j: not j.strip().startswith('#') and '=' in j, f.readlines()
)
)
}
Expand Down Expand Up @@ -1498,7 +1498,7 @@ def __check_rtsold__(self):
su.run(
[
'sysrc', '-f', f'{self.path}/root/etc/rc.conf',
f'rtsold_enable=YES'
'rtsold_enable=YES'
],
stdout=su.PIPE
)
Expand Down
13 changes: 7 additions & 6 deletions iocage_lib/ioc_upgrade.py
Original file line number Diff line number Diff line change
Expand Up @@ -79,15 +79,16 @@ def __init__(self,
'HOME': '/',
'TERM': 'xterm-256color'
}
for envvar in [ 'HTTP_PROXY','HTTPS_PROXY','HTTP_PROXY_AUTH','NO_PROXY' ]:
for envvar in ['HTTP_PROXY', 'HTTPS_PROXY', 'HTTP_PROXY_AUTH', 'NO_PROXY']:
if os.environ.get(envvar, '') != '':
upgrade_env[envvar] = os.environ.get(envvar)
self.upgrade_env[envvar] = os.environ.get(envvar)

self.callback = callback

# symbolic link created on fetch by freebsd-update
bd_hash = hashlib.sha256((self.path + '\n').encode('utf-8')).hexdigest()
self.freebsd_install_link = os.path.join(self.path,
self.freebsd_install_link = os.path.join(
self.path,
'var/db/freebsd-update', bd_hash + '-install')

def upgrade_jail(self):
Expand All @@ -108,7 +109,7 @@ def upgrade_jail(self):
tmp = None
try:
fetched_update = f"{self.iocroot}/releases/{self.new_release}" \
f"/root/usr/sbin/freebsd-update"
f"/root/usr/sbin/freebsd-update"
if os.path.isfile(fetched_update):
fbsd_update = fetched_update
else:
Expand Down Expand Up @@ -163,14 +164,14 @@ def upgrade_jail(self):
silent=self.silent
)

for _ in range(50): # up to 50 invocations to prevent runaway
for _ in range(50): # up to 50 invocations to prevent runaway
if os.path.islink(self.freebsd_install_link):
self.__upgrade_install__(fbsd_update)
else:
break

if os.path.islink(self.freebsd_install_link):
msg = f'Upgrade failed, freebsd-update won\'t finish!'
msg = 'Upgrade failed, freebsd-update won\'t finish!'
iocage_lib.ioc_common.logit(
{
'level': 'EXCEPTION',
Expand Down
22 changes: 11 additions & 11 deletions iocage_lib/iocage.py
Original file line number Diff line number Diff line change
Expand Up @@ -1655,15 +1655,15 @@ def snap_list_all(self, long, _sort):
self.jail = jail
snap_list.extend(
[[jail, *snap] for snap in self.snap_list(long, _sort)]
)
)
sort = ioc_common.ioc_sort("snaplist", _sort, data=snap_list)
snap_list.sort(key=sort)
return snap_list

def snap_list(self, long=True, _sort="created"):
"""Gathers a list of snapshots and returns it"""
if self._all:
return self.snap_list_all(long=long, _sort=_sort)
return self.snap_list_all(long=long, _sort=_sort)
uuid, path = self.__check_jail_existence__()
conf = ioc_json.IOCJson(path, silent=self.silent).json_get_value('all')
snap_list = []
Expand Down Expand Up @@ -2190,16 +2190,16 @@ def debug(self, directory):

def _get_cloned_datasets(self):
return {
d.properties.get('origin', "").replace('/root@', '@')
for d in Dataset(
os.path.join(self.pool, 'iocage')
).get_dependents(depth=3)
}
d.properties.get('origin', "").replace('/root@', '@')
for d in Dataset(
os.path.join(self.pool, 'iocage')
).get_dependents(depth=3)
}

def snap_remove_all(self, snapshot):
self._all = False
cloned_datasets=self._get_cloned_datasets()
cloned_datasets = self._get_cloned_datasets()

for jail in self.jails:
self.jail = jail
self.snap_remove(snapshot, cloned_datasets=cloned_datasets)
Expand All @@ -2215,8 +2215,8 @@ def snap_remove(self, snapshot, cloned_datasets=None):
for snapshot, *_ in reversed(self.snap_list()):
if snapshot in cloned_datasets:
ioc_common.logit({
'level': 'WARNING',
'message': f"Skipped snapshot {snapshot}: used by clones."
'level': 'WARNING',
'message': f"Skipped snapshot {snapshot}: used by clones."
})
elif snapshot.rsplit('@', 1)[0].endswith('/root'):
# Deleting here would result in trying to delete
Expand Down
2 changes: 1 addition & 1 deletion iocage_lib/pools.py
Original file line number Diff line number Diff line change
Expand Up @@ -35,7 +35,7 @@ def health(self):
def activate_pool(self):
if self.health != 'ONLINE':
raise PoolNotActivated(
f'Please check pool status, it should be ONLINE'
'Please check pool status, it should be ONLINE'
)

Dataset(self.name).set_property(IOCAGE_POOL_PROP, 'yes')
Expand Down

0 comments on commit e59af55

Please sign in to comment.