Skip to content

Commit

Permalink
Big config handling changes
Browse files Browse the repository at this point in the history
Pass expanded config dict to `parser.set_defaults()` rather than merging two dicts.

Comes with small changes to config formatting, mostly var names.

Session file untested.
  • Loading branch information
Evolution0 committed Jul 14, 2024
1 parent d454199 commit c624a92
Show file tree
Hide file tree
Showing 3 changed files with 32 additions and 45 deletions.
10 changes: 2 additions & 8 deletions bandcamp_dl/__main__.py
Original file line number Diff line number Diff line change
Expand Up @@ -79,7 +79,8 @@ def main():
logger = logging.getLogger(logging_handle)

# TODO: Its possible to break bandcamp-dl temporarily by simply erasing a line in the config, catch this and warn.
conf = config.init_config(arguments)
arguments = config.init_config(parser)
logger.debug(f"Config/Args: {arguments}")
if not arguments.URL:
parser.print_usage()
sys.stderr.write(f"{os.path.basename(sys.argv[0])}: error: the following arguments are "
Expand All @@ -92,17 +93,12 @@ def main():
setattr(arguments, arg, val)
bandcamp = Bandcamp()

# TODO: Its possible to break bandcamp-dl temporarily by simply erasing a line in the config,
# catch this and warn.

if arguments.artist and arguments.album:
urls = Bandcamp.generate_album_url(arguments.artist, arguments.album, "album")
elif arguments.artist and arguments.track:
urls = Bandcamp.generate_album_url(arguments.artist, arguments.track, "track")
elif arguments.artist:
urls = Bandcamp.get_full_discography(arguments.artist, "music")


else:
urls = arguments.URL

Expand All @@ -115,8 +111,6 @@ def main():

for album in album_list:
logger.debug(f" Album data:\n\t{album}")

for album in album_list:
if arguments.full_album and not album['full']:
print("Full album not available. Skipping ", album['title'], " ...")
# Remove not-full albums BUT continue with the rest of the albums.
Expand Down
1 change: 1 addition & 0 deletions bandcamp_dl/bandcampdownloader.py
Original file line number Diff line number Diff line change
Expand Up @@ -65,6 +65,7 @@ def template_to_path(self, track: dict, ascii_only, ok_chars, space_char, keep_s
"""
self.logger.debug(" Generating filepath/trackname..")
path = self.config.template
self.logger.debug(f"\n\tTemplate: {path}")

def slugify_preset(content):
slugged = slugify.slugify(content, ok=ok_chars, only_ascii=ascii_only,
Expand Down
66 changes: 29 additions & 37 deletions bandcamp_dl/config.py
Original file line number Diff line number Diff line change
@@ -1,3 +1,4 @@
import argparse
import ast
import json
import logging
Expand All @@ -9,6 +10,23 @@
OK_CHARS = '-_~'
SPACE_CHAR = '-'
USER_HOME = os.path.expanduser('~')
DEFAULT_CONFIG = {
"base_dir": USER_HOME,
"template": TEMPLATE,
"overwrite": False,
"no_art": False,
"embed_art": False,
"embed_lyrics": False,
"group": False,
"no_slugify": False,
"ok_chars": OK_CHARS,
"space_char": SPACE_CHAR,
"ascii_only": False,
"keep_spaces": False,
"keep_upper": False,
"no_confirm": False,
"debug": False
}

if os.name == "posix":
# Reasoning: https://www.freedesktop.org/wiki/Software/xdg-user-dirs/
Expand All @@ -18,68 +36,42 @@
config_dir = ".bandcamp-dl"

config_path = f"{USER_HOME}/{config_dir}/bandcamp-dl.json"
first_run = True

logger = logging.getLogger("bandcamp-dl").getChild("Config")


def merge(dict_1, dict_2):
"""Merge two dictionaries.
Values that evaluate to true take priority over falsy values.
`dict_1` takes priority over `dict_2`.
"""
return dict(
(str(key), dict_1.__dict__.get(key) or dict_2.get(key))
for key in set(dict_2) | set(dict_1.__dict__)
)


def init_config(arguments) -> json or dict:
def init_config(parser) -> json or dict:
"""Create and populate a default config, otherwise load it"""
if os.path.isfile(config_path):
logger.debug("Config exists, loading...")
with open(config_path, "r") as config_file:
config = json.load(config_file)
config_json = json.load(config_file)
parser.set_defaults(**config_json)
config = arguments = parser.parse_args()
first_run = False
else:
first_run = True
if os.path.exists(f"{USER_HOME}/{config_dir}") is False:
logger.debug("Config dir doesn't exist, creating...")
os.mkdir(f"{USER_HOME}/{config_dir}")
first_run = True
with open(config_path, "w") as config_file:
# Where config defaults are set/added
config = {"base-dir": USER_HOME,
"template": TEMPLATE,
"overwrite": False,
"no-art": False,
"embed-art": False,
"embed-lyrics": False,
"group": False,
"no-slugify": False,
"ok-chars": OK_CHARS,
"space-char": SPACE_CHAR,
"ascii-only": False,
"keep-spaces": False,
"keep-upper": False,
"no-confirm": False,
"debug": False}
config = dict(DEFAULT_CONFIG)
config_json = json.dumps(config, indent=4)
logger.debug("Creating config file...")
config_file.write(config_json)
parser.set_defaults(**config)
config = arguments = parser.parse_args()

# TODO: Replace all this shuffling around values with a dict comprehension if possible !!!!
# TODO: Session file should override config, as its essentially replaying manually set args
session_file = f"{config['--base-dir']}/{__version__}.not.finished"
session_file = f"{arguments.base_dir}/{__version__}.not.finished"

if os.path.isfile(session_file) and arguments.URL is None:
with open(session_file, "r") as f:
arguments = ast.literal_eval(f.readline())
parser.set_defaults(**json.load(f))
# We don't call parse_args here as we want the session file to overwrite everything
elif first_run is False:
with open(session_file, "w") as f:
f.write("".join(str(vars(arguments))))

config = merge(arguments, config)

return config

0 comments on commit c624a92

Please sign in to comment.