Make Song.parse() take the file content instead of a file name

This commit is contained in:
Raoul Snyman 2021-07-30 14:32:53 -07:00
parent 61b1cda0f6
commit 80e74a77d4

View File

@ -190,33 +190,33 @@ class Song(object):
def __init__(self, filename=None): def __init__(self, filename=None):
self.filename = filename self.filename = filename
if self.filename: if self.filename:
self.parse(self.filename) with open(filename) as song_file:
self.parse(song_file.read())
def parse(self, filename): def parse(self, text):
self.metadata = Metadata() self.metadata = Metadata()
self.verses = [] self.verses = []
self.verse_order = [] self.verse_order = []
with open(filename) as song_file: is_verse = False
is_verse = False current_verse = None
current_verse = None for line_number, line in enumerate(text.splitlines()):
for line_number, line in enumerate(song_file): if Directive.is_directive(line):
if Directive.is_directive(line): self.metadata.add(Directive(line))
self.metadata.add(Directive(line)) elif Verse.is_start_of_verse(line):
elif Verse.is_start_of_verse(line): is_verse = True
is_verse = True current_verse = Verse.parse(line)
current_verse = Verse.parse(line) self.verse_order.append(current_verse)
self.verse_order.append(current_verse) elif Verse.is_end_of_verse(line):
elif Verse.is_end_of_verse(line): if not Verse.is_end_of_verse(line, current_verse.type_):
if not Verse.is_end_of_verse(line, current_verse.type_): raise MismatchedVerseType(line_number, current_verse.type_)
raise MismatchedVerseType(line_number, current_verse.type_) self.verses.append(current_verse)
self.verses.append(current_verse) is_verse = False
is_verse = False current_verse = None
current_verse = None elif is_verse:
elif is_verse: current_verse.add_line(line.strip())
current_verse.add_line(line.strip()) elif Verse.is_chorus_marker(line):
elif Verse.is_chorus_marker(line): chorus_name = Verse.get_chorus_from_marker(line)
chorus_name = Verse.get_chorus_from_marker(line) for verse in self.verses[::-1]:
for verse in self.verses[::-1]: if verse.title == chorus_name or verse.type_ == "chorus":
if verse.title == chorus_name or verse.type_ == "chorus": self.verse_order.append(verse)
self.verse_order.append(verse) break
break