Skip to content

Commit 25ae330

Browse files
committed
refactor: moved some more imports that are only used in the commands
in their respective files. Also fixed some imports
1 parent a59e41a commit 25ae330

File tree

15 files changed

+186
-172
lines changed

15 files changed

+186
-172
lines changed

beets/ui/__init__.py

Lines changed: 1 addition & 68 deletions
Original file line numberDiff line numberDiff line change
@@ -1111,76 +1111,9 @@ def show_model_changes(
11111111
return bool(changes)
11121112

11131113

1114-
def show_path_changes(path_changes):
1115-
"""Given a list of tuples (source, destination) that indicate the
1116-
path changes, log the changes as INFO-level output to the beets log.
1117-
The output is guaranteed to be unicode.
1118-
1119-
Every pair is shown on a single line if the terminal width permits it,
1120-
else it is split over two lines. E.g.,
1121-
1122-
Source -> Destination
1123-
1124-
vs.
1125-
1126-
Source
1127-
-> Destination
1128-
"""
1129-
sources, destinations = zip(*path_changes)
1130-
1131-
# Ensure unicode output
1132-
sources = list(map(util.displayable_path, sources))
1133-
destinations = list(map(util.displayable_path, destinations))
1134-
1135-
# Calculate widths for terminal split
1136-
col_width = (term_width() - len(" -> ")) // 2
1137-
max_width = len(max(sources + destinations, key=len))
1138-
1139-
if max_width > col_width:
1140-
# Print every change over two lines
1141-
for source, dest in zip(sources, destinations):
1142-
color_source, color_dest = colordiff(source, dest)
1143-
print_(f"{color_source} \n -> {color_dest}")
1144-
else:
1145-
# Print every change on a single line, and add a header
1146-
title_pad = max_width - len("Source ") + len(" -> ")
1147-
1148-
print_(f"Source {' ' * title_pad} Destination")
1149-
for source, dest in zip(sources, destinations):
1150-
pad = max_width - len(source)
1151-
color_source, color_dest = colordiff(source, dest)
1152-
print_(f"{color_source} {' ' * pad} -> {color_dest}")
1153-
1154-
11551114
# Helper functions for option parsing.
11561115

11571116

1158-
def _store_dict(option, opt_str, value, parser):
1159-
"""Custom action callback to parse options which have ``key=value``
1160-
pairs as values. All such pairs passed for this option are
1161-
aggregated into a dictionary.
1162-
"""
1163-
dest = option.dest
1164-
option_values = getattr(parser.values, dest, None)
1165-
1166-
if option_values is None:
1167-
# This is the first supplied ``key=value`` pair of option.
1168-
# Initialize empty dictionary and get a reference to it.
1169-
setattr(parser.values, dest, {})
1170-
option_values = getattr(parser.values, dest)
1171-
1172-
try:
1173-
key, value = value.split("=", 1)
1174-
if not (key and value):
1175-
raise ValueError
1176-
except ValueError:
1177-
raise UserError(
1178-
f"supplied argument `{value}' is not of the form `key=value'"
1179-
)
1180-
1181-
option_values[key] = value
1182-
1183-
11841117
class CommonOptionsParser(optparse.OptionParser):
11851118
"""Offers a simple way to add common formatting options.
11861119
@@ -1666,7 +1599,7 @@ def parse_csl_callback(
16661599
and subargs[0] == "config"
16671600
and ("-e" in subargs or "--edit" in subargs)
16681601
):
1669-
from beets.ui.commands import config_edit
1602+
from beets.ui.commands.config import config_edit
16701603

16711604
return config_edit()
16721605

beets/ui/commands/__init__.py

Lines changed: 15 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -32,6 +32,21 @@
3232
from .version import version_cmd
3333
from .write import write_cmd
3434

35+
36+
def __getattr__(name: str):
37+
"""Handle deprecated imports."""
38+
return deprecate_imports(
39+
old_module=__name__,
40+
new_module_by_name={
41+
"TerminalImportSession": "beets.ui.commands.import_.session",
42+
"PromptChoice": "beets.ui.commands.import_.session",
43+
# TODO: We might want to add more deprecated imports here
44+
},
45+
name=name,
46+
version="3.0.0",
47+
)
48+
49+
3550
# The list of default subcommands. This is populated with Subcommand
3651
# objects that can be fed to a SubcommandsOptionParser.
3752
default_commands = [

beets/ui/commands/_utils.py

Lines changed: 0 additions & 67 deletions
This file was deleted.

beets/ui/commands/completion.py

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -48,7 +48,7 @@ def completion_script(commands):
4848
completion data for.
4949
"""
5050
base_script = os.path.join(
51-
os.path.dirname(__file__), "../completion_base.sh"
51+
os.path.dirname(__file__), "./completion_base.sh"
5252
)
5353
with open(base_script) as base_script:
5454
yield base_script.read()

beets/ui/commands/config.py

Lines changed: 5 additions & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -2,7 +2,8 @@
22

33
import os
44

5-
from beets import config, ui, util
5+
from beets import config, ui
6+
from beets.util import displayable_path, editor_command, interactive_open
67

78

89
def config_func(lib, opts, args):
@@ -25,7 +26,7 @@ def config_func(lib, opts, args):
2526
filenames.insert(0, user_path)
2627

2728
for filename in filenames:
28-
ui.print_(util.displayable_path(filename))
29+
ui.print_(displayable_path(filename))
2930

3031
# Open in editor.
3132
elif opts.edit:
@@ -45,11 +46,11 @@ def config_edit():
4546
An empty config file is created if no existing config file exists.
4647
"""
4748
path = config.user_config_path()
48-
editor = util.editor_command()
49+
editor = editor_command()
4950
try:
5051
if not os.path.isfile(path):
5152
open(path, "w+").close()
52-
util.interactive_open([path], editor)
53+
interactive_open([path], editor)
5354
except OSError as exc:
5455
message = f"Could not edit configuration: {exc}"
5556
if not editor:

beets/ui/commands/import_/__init__.py

Lines changed: 62 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -5,13 +5,47 @@
55
from beets import config, logging, plugins, ui
66
from beets.util import displayable_path, normpath, syspath
77

8-
from .._utils import parse_logfiles
98
from .session import TerminalImportSession
109

1110
# Global logger.
1211
log = logging.getLogger("beets")
1312

1413

14+
def paths_from_logfile(path):
15+
"""Parse the logfile and yield skipped paths to pass to the `import`
16+
command.
17+
"""
18+
with open(path, encoding="utf-8") as fp:
19+
for i, line in enumerate(fp, start=1):
20+
verb, sep, paths = line.rstrip("\n").partition(" ")
21+
if not sep:
22+
raise ValueError(f"line {i} is invalid")
23+
24+
# Ignore informational lines that don't need to be re-imported.
25+
if verb in {"import", "duplicate-keep", "duplicate-replace"}:
26+
continue
27+
28+
if verb not in {"asis", "skip", "duplicate-skip"}:
29+
raise ValueError(f"line {i} contains unknown verb {verb}")
30+
31+
yield os.path.commonpath(paths.split("; "))
32+
33+
34+
def parse_logfiles(logfiles):
35+
"""Parse all `logfiles` and yield paths from it."""
36+
for logfile in logfiles:
37+
try:
38+
yield from paths_from_logfile(syspath(normpath(logfile)))
39+
except ValueError as err:
40+
raise ui.UserError(
41+
f"malformed logfile {displayable_path(logfile)}: {err}"
42+
) from err
43+
except OSError as err:
44+
raise ui.UserError(
45+
f"unreadable logfile {displayable_path(logfile)}: {err}"
46+
) from err
47+
48+
1549
def import_files(lib, paths: list[bytes], query):
1650
"""Import the files in the given list of paths or matching the
1751
query.
@@ -97,6 +131,32 @@ def import_func(lib, opts, args: list[str]):
97131
import_files(lib, byte_paths, query)
98132

99133

134+
def _store_dict(option, opt_str, value, parser):
135+
"""Custom action callback to parse options which have ``key=value``
136+
pairs as values. All such pairs passed for this option are
137+
aggregated into a dictionary.
138+
"""
139+
dest = option.dest
140+
option_values = getattr(parser.values, dest, None)
141+
142+
if option_values is None:
143+
# This is the first supplied ``key=value`` pair of option.
144+
# Initialize empty dictionary and get a reference to it.
145+
setattr(parser.values, dest, {})
146+
option_values = getattr(parser.values, dest)
147+
148+
try:
149+
key, value = value.split("=", 1)
150+
if not (key and value):
151+
raise ValueError
152+
except ValueError:
153+
raise ui.UserError(
154+
f"supplied argument `{value}' is not of the form `key=value'"
155+
)
156+
157+
option_values[key] = value
158+
159+
100160
import_cmd = ui.Subcommand(
101161
"import", help="import new music", aliases=("imp", "im")
102162
)
@@ -274,7 +334,7 @@ def import_func(lib, opts, args: list[str]):
274334
"--set",
275335
dest="set_fields",
276336
action="callback",
277-
callback=ui._store_dict,
337+
callback=_store_dict,
278338
metavar="FIELD=VALUE",
279339
help="set the given fields to the supplied values",
280340
)

beets/ui/commands/import_/display.py

Lines changed: 1 addition & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -2,16 +2,13 @@
22
from collections.abc import Sequence
33
from functools import cached_property
44

5-
from beets import autotag, config, logging, ui
5+
from beets import autotag, config, ui
66
from beets.autotag import hooks
77
from beets.util import displayable_path
88
from beets.util.units import human_seconds_short
99

1010
VARIOUS_ARTISTS = "Various Artists"
1111

12-
# Global logger.
13-
log = logging.getLogger("beets")
14-
1512

1613
class ChangeRepresentation:
1714
"""Keeps track of all information needed to generate a (colored) text

beets/ui/commands/import_/session.py

Lines changed: 5 additions & 6 deletions
Original file line numberDiff line numberDiff line change
@@ -6,7 +6,6 @@
66
from beets.autotag import Recommendation
77
from beets.util import displayable_path
88
from beets.util.units import human_bytes, human_seconds_short
9-
from beetsplug.bareasc import print_
109

1110
from .display import (
1211
disambig_string,
@@ -415,8 +414,8 @@ def choose_candidate(
415414
if singleton:
416415
ui.print_("No matching recordings found.")
417416
else:
418-
print_(f"No matching release found for {itemcount} tracks.")
419-
print_(
417+
ui.print_(f"No matching release found for {itemcount} tracks.")
418+
ui.print_(
420419
"For help, see: "
421420
"https://beets.readthedocs.org/en/latest/faq.html#nomatch"
422421
)
@@ -461,17 +460,17 @@ def choose_candidate(
461460
else:
462461
metadata = ui.colorize("text_highlight_minor", metadata)
463462
line1 = [index, distance, metadata]
464-
print_(f" {' '.join(line1)}")
463+
ui.print_(f" {' '.join(line1)}")
465464

466465
# Penalties.
467466
penalties = penalty_string(match.distance, 3)
468467
if penalties:
469-
print_(f"{' ' * 13}{penalties}")
468+
ui.print_(f"{' ' * 13}{penalties}")
470469

471470
# Disambiguation
472471
disambig = disambig_string(match.info)
473472
if disambig:
474-
print_(f"{' ' * 13}{disambig}")
473+
ui.print_(f"{' ' * 13}{disambig}")
475474

476475
# Ask the user for a choice.
477476
sel = ui.input_options(choice_opts, numrange=(1, len(candidates)))

beets/ui/commands/modify.py

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -3,7 +3,7 @@
33
from beets import library, ui
44
from beets.util import functemplate
55

6-
from ._utils import do_query
6+
from .utils import do_query
77

88

99
def modify_items(lib, mods, dels, query, write, move, album, confirm, inherit):

0 commit comments

Comments
 (0)