Skip to content

Commit

Permalink
style(optional): apply basic ruff linting and formatting
Browse files Browse the repository at this point in the history
  • Loading branch information
JacobCoffee committed Jul 22, 2024
1 parent bc58d1c commit cedf0b9
Show file tree
Hide file tree
Showing 11 changed files with 3,468 additions and 2,665 deletions.
106 changes: 35 additions & 71 deletions code/planet-cache.py
Original file line number Diff line number Diff line change
@@ -1,64 +1,41 @@
#!/usr/bin/env python3
"""Planet cache tool.
"""Planet cache tool."""

"""

__authors__ = [ "Scott James Remnant <[email protected]>",
"Jeff Waugh <[email protected]>" ]
__authors__ = ["Scott James Remnant <[email protected]>", "Jeff Waugh <[email protected]>"]
__license__ = "Python"


import configparser
import dbm
import os
import sys
import time
import dbm
import configparser

import planet


def usage():
print("Usage: planet-cache [options] CACHEFILE [ITEMID]...")
print()
print("Examine and modify information in the Planet cache.")
print()
print("Channel Commands:")
print(" -C, --channel Display known information on the channel")
print(" -L, --list List items in the channel")
print(" -K, --keys List all keys found in channel items")
print()
print("Item Commands (need ITEMID):")
print(" -I, --item Display known information about the item(s)")
print(" -H, --hide Mark the item(s) as hidden")
print(" -U, --unhide Mark the item(s) as not hidden")
print()
print("Other Options:")
print(" -h, --help Display this help message and exit")
def usage() -> None:
sys.exit(0)

def usage_error(msg, *args):
print(msg, " ".join(args), file=sys.stderr)
print("Perhaps you need --help ?", file=sys.stderr)

def usage_error(msg, *args) -> None:
sys.exit(1)

def print_keys(item, title):

def print_keys(item, title) -> None:
keys = item.keys()
keys.sort()
key_len = max([ len(k) for k in keys ])
max([len(k) for k in keys])

print(title + ":")
for key in keys:
if item.key_type(key) == item.DATE:
value = time.strftime(planet.TIMEFMT_ISO, item[key])
else:
value = str(item[key])
print(" %-*s %s" % (key_len, key, fit_str(value, 74 - key_len)))
time.strftime(planet.TIMEFMT_ISO, item[key]) if item.key_type(key) == item.DATE else str(item[key])


def fit_str(string, length):
if len(string) <= length:
return string
else:
return string[:length-4] + " ..."
return string[: length - 4] + " ..."


if __name__ == "__main__":
Expand All @@ -69,44 +46,43 @@ def fit_str(string, length):
command = None

for arg in sys.argv[1:]:
if arg == "-h" or arg == "--help":
if arg in ("-h", "--help"):
usage()
elif arg == "-C" or arg == "--channel":
elif arg in ("-C", "--channel"):
if command is not None:
usage_error("Only one command option may be supplied")
command = "channel"
elif arg == "-L" or arg == "--list":
elif arg in ("-L", "--list"):
if command is not None:
usage_error("Only one command option may be supplied")
command = "list"
elif arg == "-K" or arg == "--keys":
elif arg in ("-K", "--keys"):
if command is not None:
usage_error("Only one command option may be supplied")
command = "keys"
elif arg == "-I" or arg == "--item":
elif arg in ("-I", "--item"):
if command is not None:
usage_error("Only one command option may be supplied")
command = "item"
want_ids = 1
elif arg == "-H" or arg == "--hide":
elif arg in ("-H", "--hide"):
if command is not None:
usage_error("Only one command option may be supplied")
command = "hide"
want_ids = 1
elif arg == "-U" or arg == "--unhide":
elif arg in ("-U", "--unhide"):
if command is not None:
usage_error("Only one command option may be supplied")
command = "unhide"
want_ids = 1
elif arg.startswith("-"):
usage_error("Unknown option:", arg)
elif cache_file is None:
cache_file = arg
elif want_ids:
ids.append(arg)
else:
if cache_file is None:
cache_file = arg
elif want_ids:
ids.append(arg)
else:
usage_error("Unexpected extra argument:", arg)
usage_error("Unexpected extra argument:", arg)

if cache_file is None:
usage_error("Missing expected cache filename")
Expand All @@ -115,13 +91,11 @@ def fit_str(string, length):

# Open the cache file directly to get the URL it represents
try:
with dbm.open(cache_file, 'r') as db:
url = db[b"url"].decode('utf-8')
except dbm.error as e:
print(f"{cache_file}: {str(e)}", file=sys.stderr)
with dbm.open(cache_file, "r") as db:
url = db[b"url"].decode("utf-8")
except dbm.error:
sys.exit(1)
except KeyError:
print(f"{cache_file}: Probably not a cache file", file=sys.stderr)
sys.exit(1)

# Now do it the right way :-)
Expand All @@ -131,7 +105,6 @@ def fit_str(string, length):

for item_id in ids:
if not channel.has_item(item_id):
print(item_id + ": Not in channel", file=sys.stderr)
sys.exit(1)

# Do the user's bidding
Expand All @@ -141,51 +114,42 @@ def fit_str(string, length):
elif command == "item":
for item_id in ids:
item = channel.get_item(item_id)
print_keys(item, "Item Keys for %s" % item_id)
print_keys(item, f"Item Keys for {item_id}")

elif command == "list":
print("Items in Channel:")
for item in channel.items(hidden=1, sorted=1):
print(" " + item.id)
print(" " + time.strftime(planet.TIMEFMT_ISO, item.date))
if hasattr(item, "title"):
print(" " + fit_str(item.title, 70))
pass
if hasattr(item, "hidden"):
print(" (hidden)")
pass

elif command == "keys":
keys = {}
for item in channel.items():
for key in item.keys():
for key in item:
keys[key] = 1

keys = sorted(keys.keys())

print("Keys used in Channel:")
for key in keys:
print(" " + key)
print()

print("Use --item to output values of particular items.")
pass

elif command == "hide":
for item_id in ids:
item = channel.get_item(item_id)
if hasattr(item, "hidden"):
print(item_id + ": Already hidden.")
pass
else:
item.hidden = "yes"

channel.cache_write()
print("Done.")

elif command == "unhide":
for item_id in ids:
item = channel.get_item(item_id)
if hasattr(item, "hidden"):
del item.hidden
else:
print(item_id + ": Not hidden.")
pass

channel.cache_write()
print("Done.")
62 changes: 22 additions & 40 deletions code/planet.py
Original file line number Diff line number Diff line change
Expand Up @@ -9,66 +9,56 @@
Requires Python 2.1, recommends 2.3.
"""

__authors__ = [ "Scott James Remnant <[email protected]>",
"Jeff Waugh <[email protected]>" ]
__authors__ = ["Scott James Remnant <[email protected]>", "Jeff Waugh <[email protected]>"]
__license__ = "Python"


import os
import sys
import configparser
import locale
import os
import socket
import configparser
import sys
from urllib.parse import urljoin

import planet


# Default configuration file path
CONFIG_FILE = "config.ini"

# Defaults for the [Planet] config section
PLANET_NAME = "Unconfigured Planet"
PLANET_LINK = "Unconfigured Planet"
PLANET_FEED = None
OWNER_NAME = "Anonymous Coward"
OWNER_NAME = "Anonymous Coward"
OWNER_EMAIL = ""
LOG_LEVEL = "WARNING"
FEED_TIMEOUT = 20 # seconds
LOG_LEVEL = "WARNING"
FEED_TIMEOUT = 20 # seconds

# Default template file list
TEMPLATE_FILES = "examples/basic/planet.html.tmpl"



def config_get(config, section, option, default=None, raw=0, vars=None):
"""Get a value from the configuration, with a default."""
if config.has_option(section, option):
return config.get(section, option, raw=raw, vars=None)
else:
return default

def main():

def main() -> None:
config_file = CONFIG_FILE
offline = 0
verbose = 0

for arg in sys.argv[1:]:
if arg == "-h" or arg == "--help":
print("Usage: planet [options] [CONFIGFILE]")
print()
print("Options:")
print(" -v, --verbose DEBUG level logging during update")
print(" -o, --offline Update the Planet from the cache only")
print(" -h, --help Display this help message and exit")
print()
if arg in ("-h", "--help"):
sys.exit(0)
elif arg == "-v" or arg == "--verbose":
elif arg in ("-v", "--verbose"):
verbose = 1
elif arg == "-o" or arg == "--offline":
elif arg in ("-o", "--offline"):
offline = 1
elif arg.startswith("-"):
print("Unknown option:", arg, file=sys.stderr)
sys.exit(1)
else:
config_file = arg
Expand All @@ -77,28 +67,23 @@ def main():
config = configparser()
config.read(config_file)
if not config.has_section("Planet"):
print("Configuration missing [Planet] section.", file=sys.stderr)
sys.exit(1)

# Read the [Planet] config section
planet_name = config_get(config, "Planet", "name", PLANET_NAME)
planet_link = config_get(config, "Planet", "link", PLANET_LINK)
planet_feed = config_get(config, "Planet", "feed", PLANET_FEED)
owner_name = config_get(config, "Planet", "owner_name", OWNER_NAME)
planet_name = config_get(config, "Planet", "name", PLANET_NAME)
planet_link = config_get(config, "Planet", "link", PLANET_LINK)
planet_feed = config_get(config, "Planet", "feed", PLANET_FEED)
owner_name = config_get(config, "Planet", "owner_name", OWNER_NAME)
owner_email = config_get(config, "Planet", "owner_email", OWNER_EMAIL)
if verbose:
log_level = "DEBUG"
else:
log_level = config_get(config, "Planet", "log_level", LOG_LEVEL)
feed_timeout = config_get(config, "Planet", "feed_timeout", FEED_TIMEOUT)
template_files = config_get(config, "Planet", "template_files",
TEMPLATE_FILES).split(" ")
log_level = "DEBUG" if verbose else config_get(config, "Planet", "log_level", LOG_LEVEL)
feed_timeout = config_get(config, "Planet", "feed_timeout", FEED_TIMEOUT)
template_files = config_get(config, "Planet", "template_files", TEMPLATE_FILES).split(" ")

# Default feed to the first feed for which there is a template
if not planet_feed:
for template_file in template_files:
name = os.path.splitext(os.path.basename(template_file))[0]
if name.find('atom')>=0 or name.find('rss')>=0:
if name.find("atom") >= 0 or name.find("rss") >= 0:
planet_feed = urljoin(planet_link, name)
break

Expand All @@ -107,7 +92,7 @@ def main():
# The user can specify more than one locale (separated by ":") as
# fallbacks.
locale_ok = False
for user_locale in config.get("Planet", "locale").split(':'):
for user_locale in config.get("Planet", "locale").split(":"):
user_locale = user_locale.strip()
try:
locale.setlocale(locale.LC_ALL, user_locale)
Expand All @@ -117,7 +102,6 @@ def main():
locale_ok = True
break
if not locale_ok:
print("Unsupported locale setting.", file=sys.stderr)
sys.exit(1)

# Activate logging
Expand All @@ -144,10 +128,8 @@ def main():
my_planet = planet.Planet(config)
my_planet.run(planet_name, planet_link, template_files, offline)

my_planet.generate_all_files(template_files, planet_name,
planet_link, planet_feed, owner_name, owner_email)
my_planet.generate_all_files(template_files, planet_name, planet_link, planet_feed, owner_name, owner_email)


if __name__ == "__main__":
main()

Loading

0 comments on commit cedf0b9

Please sign in to comment.