Skip to content

Commit

Permalink
Add rewrite meta debug output
Browse files Browse the repository at this point in the history
  • Loading branch information
Josef-Friedrich committed Jan 26, 2024
1 parent 8551cdd commit 7fc3681
Show file tree
Hide file tree
Showing 6 changed files with 87 additions and 53 deletions.
25 changes: 21 additions & 4 deletions mscxyz/cli.py
Original file line number Diff line number Diff line change
Expand Up @@ -659,8 +659,8 @@ def __print_error(error: Exception) -> None:

print(
"{}: {}; message: {}".format(
utils.color("Error", "white", "on_red"),
utils.color(error.__class__.__name__, "red"),
utils.colorize("Error", "white", "on_red"),
utils.colorize(error.__class__.__name__, "red"),
msg,
)
)
Expand Down Expand Up @@ -761,6 +761,23 @@ def list_styles(version: int) -> None:

# meta

manipulate_meta: bool = False

if (
args.meta_metatag
or args.meta_vbox
or args.meta_combined
or args.meta_set
or args.meta_clean
or args.meta_dist
or args.meta_dist
or args.meta_delete
or args.meta_sync
):
manipulate_meta = True
# to get score.fields.pre
score.fields

if args.meta_metatag:
for a in args.meta_metatag:
field = a[0]
Expand Down Expand Up @@ -822,8 +839,8 @@ def list_styles(version: int) -> None:
if args.meta_log:
score.meta.write_to_log_file(args.meta_log[0], args.meta_log[1])

# post: dict[str, str] = score.meta.interface.export_to_dict()
# score.meta.show(pre, post)
if manipulate_meta:
score.fields.diff(args)

if args.rename_rename:
rename(score)
Expand Down
85 changes: 43 additions & 42 deletions mscxyz/fields.py
Original file line number Diff line number Diff line change
Expand Up @@ -10,6 +10,8 @@
from typing import Any, Mapping, Union

from mscxyz.meta import FormatStringNoFieldError, UnmatchedFormatStringError
from mscxyz.settings import DefaultArguments
from mscxyz.utils import Color, colorize

if typing.TYPE_CHECKING:
from mscxyz.score import Score
Expand All @@ -34,6 +36,12 @@ class Field:
attr_path: str
"""``meta.title`` accesses ``score.meta.title``"""

verbosity: int = 1
"""Verbosity level indicating if the field should be displayed in the debug output."""

color: Color = "white"
"""The color of the field in the debug output."""


class FieldsManager:
score: "Score"
Expand Down Expand Up @@ -169,61 +177,74 @@ class FieldsManager:
description="The MuseScore version as a floating point number, "
"for example ``2.03``, ``3.01`` or ``4.20``.",
attr_path="version",
verbosity=2,
),
Field(
name="version_major",
description="The major MuseScore version, for example ``2``, ``3`` or ``4``.",
attr_path="version_major",
verbosity=2,
),
Field(
name="path",
description="The absolute path of the MuseScore file, for example ``/home/xyz/score.mscz``.",
attr_path="path",
verbosity=2,
),
Field(
name="backup_file",
description="The absolute path of the backup file. "
"The string ``_bak`` is appended to the file name before the extension.",
attr_path="backup_file",
verbosity=3,
),
Field(
name="json_file",
description="The absolute path of the JSON file in which the metadata can be exported.",
attr_path="json_file",
verbosity=3,
),
Field(
name="dirname",
description="The name of the containing directory of the MuseScore file, for "
"example: ``/home/xyz/score_files``.",
attr_path="dirname",
verbosity=2,
),
Field(
name="filename",
description="The filename of the MuseScore file, for example:"
"``score.mscz``.",
attr_path="filename",
verbosity=2,
),
Field(
name="basename",
description="The basename of the score file, for example: ``score``.",
attr_path="basename",
verbosity=2,
),
Field(
name="extension",
description="The extension (``mscx`` or ``mscz``) of the score file.",
attr_path="extension",
verbosity=2,
),
)

__fields_by_name: dict[str, Field]

pre: dict[str, FieldValue]
"""The state of the field values at initialization, stored as a dictionary."""

def __init__(self, score: "Score") -> None:
self.score = score
self.__fields_by_name = {}
for field in self.fields:
if field.name in self.__fields_by_name:
raise Exception("Duplicate field name")
self.__fields_by_name[field.name] = field
self.pre = self.export_to_dict()

@property
def names(self) -> tuple[str, ...]:
Expand Down Expand Up @@ -253,48 +274,28 @@ def set(self, name: str, value: Any) -> None:
raise Exception(f"Cannot set attribute {field.attr_path}")
setattr(obj, last, value)

def show(self, pre: dict[str, str], post: dict[str, str]) -> None:
pass
# args = get_args()

# fields = list(self.interface.fields)

# if args.general_verbose < 1:
# fields.remove("readonly_abspath")
# fields.remove("readonly_dirname")
# fields.remove("readonly_extension")
# fields.remove("readonly_filename")
# fields.remove("readonly_relpath")

# if args.general_verbose < 2:
# fields.remove("readonly_relpath_backup")

# for field in fields:
# field_color: utils.Color
# if (
# args.general_verbose == 0
# and (field in pre and pre[field] or field in post and post[field])
# ) or args.general_verbose > 0:
# if re.match(r"^combined_", field):
# field_color = "green"
# elif re.match(r"^metatag_", field):
# field_color = "blue"
# elif re.match(r"^readonly_", field):
# field_color = "red"
# elif re.match(r"^vbox_", field):
# field_color = "cyan"
# else:
# field_color = "white"

# line: list[str] = []
# if pre[field]:
# line.append("“{}”".format(pre[field]))

# if pre[field] != post[field]:
# line.append("->")
# line.append(utils.color("“{}”".format(post[field]), "yellow"))

# print("{}: {}".format(utils.color(field, field_color), " ".join(line)))
def diff(self, args: DefaultArguments) -> None:
if args.general_verbose == 0:
return
pre = self.pre

post = self.export_to_dict()

for name in self.names:
if name in pre and pre[name] or name in post and post[name]:
field = self.get_field(name)
if field.verbosity < args.general_verbose:
continue

line: list[str] = []
if pre[name]:
line.append(f"“{pre[name]}”")

if pre[name] != post[name]:
line.append("->")
line.append(colorize(f"“{post[name]}”", "yellow"))

print(f"{colorize(name, field.color)}: {' '.join(line)}")

def export_to_dict(self) -> dict[str, FieldValue]:
output: dict[str, FieldValue] = {}
Expand Down
6 changes: 4 additions & 2 deletions mscxyz/meta.py
Original file line number Diff line number Diff line change
Expand Up @@ -955,9 +955,11 @@ def show(self, pre: dict[str, str], post: dict[str, str]) -> None:

if pre[field] != post[field]:
line.append("->")
line.append(utils.color("“{}”".format(post[field]), "yellow"))
line.append(utils.colorize("“{}”".format(post[field]), "yellow"))

print("{}: {}".format(utils.color(field, field_color), " ".join(line)))
print(
"{}: {}".format(utils.colorize(field, field_color), " ".join(line))
)

def export_json(self) -> Path:
"""
Expand Down
8 changes: 4 additions & 4 deletions mscxyz/rename.py
Original file line number Diff line number Diff line change
Expand Up @@ -13,7 +13,7 @@
from mscxyz.fields import FieldsExport
from mscxyz.score import Score
from mscxyz.settings import get_args
from mscxyz.utils import color
from mscxyz.utils import colorize


def create_dir(path: str) -> None:
Expand Down Expand Up @@ -51,7 +51,7 @@ def apply_format_string(fields: FieldsExport) -> str:


def show(old: str, new: str) -> None:
print("{} -> {}".format(color(old, "yellow"), color(new, "green")))
print("{} -> {}".format(colorize(old, "yellow"), colorize(new, "green")))


def get_checksum(filename: str) -> str:
Expand All @@ -75,7 +75,7 @@ def rename(score: Score) -> Score:
skips: list[str] = args.rename_skip.split(",")
for skip in skips:
if skip not in meta_values:
print(color("Field “{}” is empty! Skipping".format(skip), "red"))
print(colorize("Field “{}” is empty! Skipping".format(skip), "red"))
return score

if args.rename_target:
Expand All @@ -93,7 +93,7 @@ def rename(score: Score) -> Score:
target = target_format.format(counter_format)
if get_checksum(str(score.path)) == get_checksum(target):
print(
color(
colorize(
"The file “{}” with the same checksum (sha1) "
"already exists in the target path “{}”!".format(
str(score.path), target
Expand Down
2 changes: 1 addition & 1 deletion mscxyz/utils.py
Original file line number Diff line number Diff line change
Expand Up @@ -216,7 +216,7 @@ def to(self, unit: Unit) -> float:
]


def color(
def colorize(
text: str, color: Optional[Color] = None, on_color: Optional[Highlight] = None
) -> str:
"""Wrapper function around ``termcolor.colored()`` to easily turn off and
Expand Down
14 changes: 14 additions & 0 deletions tests/test_cli.py
Original file line number Diff line number Diff line change
Expand Up @@ -49,6 +49,20 @@ def test_args_general_rename(self) -> None:
assert args.rename_target is None


class TestVerbosity:
def test_0(self) -> None:
args = parser.parse_args([])
assert args.general_verbose == 0

def test_1(self) -> None:
args = parser.parse_args(["-v"])
assert args.general_verbose == 1

def test_2(self) -> None:
args = parser.parse_args(["-vv"])
assert args.general_verbose == 2


class TestCommandlineInterface:
def test_help_short(self) -> None:
with pytest.raises(SystemExit) as e:
Expand Down

0 comments on commit 7fc3681

Please sign in to comment.