From 3b1bd242d09bfc5e8d3070138e76999f2b510e22 Mon Sep 17 00:00:00 2001 From: JoeLametta Date: Sat, 6 Jan 2018 08:00:00 +0000 Subject: [PATCH] Convert docstrings to reStructuredText This commit also includes: - whitespace / code formatting fixes - slight syntax related changes: except , e -> except as e - 3 pointless instructions instances have been rewritten [sorted] (spotted by semi-automatic check) The unrelated changes shouldn't have any real impact on whipper's behaviour. --- setup.py | 2 +- whipper/command/basecommand.py | 4 +- whipper/command/cd.py | 4 +- whipper/command/debug.py | 14 +- whipper/command/main.py | 18 +- whipper/command/offset.py | 12 +- whipper/common/accurip.py | 68 ++++--- whipper/common/cache.py | 57 +++--- whipper/common/common.py | 105 ++++++----- whipper/common/config.py | 26 ++- whipper/common/mbngs.py | 84 ++++++--- whipper/common/path.py | 18 +- whipper/common/program.py | 200 +++++++++++++------- whipper/common/renamer.py | 62 +++--- whipper/common/task.py | 32 ++-- whipper/extern/asyncsub.py | 6 +- whipper/extern/task/task.py | 191 +++++++++++-------- whipper/image/cue.py | 51 ++--- whipper/image/image.py | 63 ++++--- whipper/image/table.py | 281 ++++++++++++++++------------ whipper/image/toc.py | 95 ++++++---- whipper/program/cdparanoia.py | 168 +++++++++-------- whipper/program/cdrdao.py | 46 +++-- whipper/program/flac.py | 12 +- whipper/program/sox.py | 9 +- whipper/program/soxi.py | 22 ++- whipper/program/utils.py | 21 ++- whipper/result/logger.py | 31 ++- whipper/result/result.py | 75 ++++---- whipper/test/common.py | 15 +- whipper/test/test_common_accurip.py | 2 +- whipper/test/test_common_mbngs.py | 15 +- 32 files changed, 1078 insertions(+), 731 deletions(-) diff --git a/setup.py b/setup.py index 9262a8de..910b2eaf 100644 --- a/setup.py +++ b/setup.py @@ -13,6 +13,6 @@ entry_points={ 'console_scripts': [ 'whipper = whipper.command.main:main' - ] + ] } ) diff --git a/whipper/command/basecommand.py b/whipper/command/basecommand.py index 379a23b4..091fb40c 100644 --- a/whipper/command/basecommand.py +++ b/whipper/command/basecommand.py @@ -26,8 +26,7 @@ class BaseCommand(): - """ - A base command class for whipper commands. + """A base command class for whipper commands. Creates an argparse.ArgumentParser. Override add_arguments() and handle_arguments() to register @@ -46,6 +45,7 @@ class BaseCommand(): arguments, the current options namespace, and the full command path name. """ + device_option = False no_add_help = False # for rip.main.Whipper formatter_class = argparse.RawDescriptionHelpFormatter diff --git a/whipper/command/cd.py b/whipper/command/cd.py index d7b11ec8..2cebd2a2 100644 --- a/whipper/command/cd.py +++ b/whipper/command/cd.py @@ -175,7 +175,7 @@ def do(self): try: self.program.result.cdparanoiaDefeatsCache = \ self.config.getDefeatsCache(*info) - except KeyError, e: + except KeyError as e: logger.debug('Got key error: %r' % (e, )) self.program.result.artist = self.program.metadata \ and self.program.metadata.artist \ @@ -414,7 +414,7 @@ def _ripIfNotRipped(number): len(self.itable.tracks), extra)) break - except Exception, e: + except Exception as e: logger.debug('Got exception %r on try %d', e, tries) diff --git a/whipper/command/debug.py b/whipper/command/debug.py index f5970dde..5b6ec6ea 100644 --- a/whipper/command/debug.py +++ b/whipper/command/debug.py @@ -118,9 +118,9 @@ class ResultCache(BaseCommand): description = summary subcommands = { - 'cue': RCCue, + 'cue': RCCue, 'list': RCList, - 'log': RCLog, + 'log': RCLog, } @@ -291,10 +291,10 @@ class Debug(BaseCommand): description = "debug internals" subcommands = { - 'checksum': Checksum, - 'encode': Encode, - 'tag': Tag, + 'checksum': Checksum, + 'encode': Encode, + 'tag': Tag, 'musicbrainzngs': MusicBrainzNGS, - 'resultcache': ResultCache, - 'version': Version, + 'resultcache': ResultCache, + 'version': Version, } diff --git a/whipper/command/main.py b/whipper/command/main.py index 04530c30..33abe82f 100644 --- a/whipper/command/main.py +++ b/whipper/command/main.py @@ -38,20 +38,20 @@ def main(): try: cmd = Whipper(sys.argv[1:], os.path.basename(sys.argv[0]), None) ret = cmd.do() - except SystemError, e: + except SystemError as e: sys.stderr.write('whipper: error: %s\n' % e) if (type(e) is common.EjectError and cmd.options.eject in ('failure', 'always')): eject_device(e.device) return 255 - except RuntimeError, e: + except RuntimeError as e: print(e) return 1 except KeyboardInterrupt: return 2 - except ImportError, e: + except ImportError as e: raise - except task.TaskException, e: + except task.TaskException as e: if isinstance(e.exception, ImportError): raise ImportError(e.exception) elif isinstance(e.exception, common.MissingDependencyException): @@ -80,11 +80,11 @@ class Whipper(BaseCommand): no_add_help = True subcommands = { 'accurip': accurip.AccuRip, - 'cd': cd.CD, - 'debug': debug.Debug, - 'drive': drive.Drive, - 'offset': offset.Offset, - 'image': image.Image + 'cd': cd.CD, + 'debug': debug.Debug, + 'drive': drive.Drive, + 'offset': offset.Offset, + 'image': image.Image } def add_arguments(self): diff --git a/whipper/command/offset.py b/whipper/command/offset.py index 77585ee4..a87e4c51 100644 --- a/whipper/command/offset.py +++ b/whipper/command/offset.py @@ -119,7 +119,7 @@ def match(archecksums, track, responses): sys.stdout.write('Trying read offset %d ...\n' % offset) try: archecksums = self._arcs(runner, table, 1, offset) - except task.TaskException, e: + except task.TaskException as e: # let MissingDependency fall through if isinstance(e.exception, @@ -152,7 +152,7 @@ def match(archecksums, track, responses): for track in range(2, (len(table.tracks) + 1) - 1): try: archecksums = self._arcs(runner, table, track, offset) - except task.TaskException, e: + except task.TaskException as e: if isinstance(e.exception, cdparanoia.FileSizeError): sys.stdout.write( 'WARNING: cannot rip with offset %d...\n' % @@ -195,11 +195,11 @@ def _arcs(self, runner, table, track, offset): runner.run(t) v1 = arc.accuraterip_checksum( - path, track, len(table.tracks), wave=True, v2=False - ) + path, track, len(table.tracks), wave=True, v2=False + ) v2 = arc.accuraterip_checksum( - path, track, len(table.tracks), wave=True, v2=True - ) + path, track, len(table.tracks), wave=True, v2=True + ) os.unlink(path) return ("%08x" % v1, "%08x" % v2) diff --git a/whipper/common/accurip.py b/whipper/common/accurip.py index 0c6c1ebe..839287e8 100644 --- a/whipper/common/accurip.py +++ b/whipper/common/accurip.py @@ -41,7 +41,8 @@ class EntryNotFound(Exception): class _AccurateRipResponse(object): - """ + """I represent an AccurateRip response with its metadata. + An AccurateRip response contains a collection of metadata identifying a particular digital audio compact disc. @@ -52,14 +53,14 @@ class _AccurateRipResponse(object): the disc index, which excludes any audio hidden in track pre-gaps (such as HTOA). + The checksums and confidences arrays are indexed by relative track + position, so track 1 will have array index 0, track 2 will have array + index 1, and so forth. HTOA and other hidden tracks are not included. + The response is stored as a packed binary structure. """ + def __init__(self, data): - """ - The checksums and confidences arrays are indexed by relative track - position, so track 1 will have array index 0, track 2 will have array - index 1, and so forth. HTOA and other hidden tracks are not included. - """ self.num_tracks = struct.unpack("B", data[0])[0] self.discId1 = "%08x" % struct.unpack(". -""" -Handles communication with the MusicBrainz server using NGS. -""" +"""Handles communication with the MusicBrainz server using NGS.""" import urllib2 @@ -54,15 +52,38 @@ class TrackMetadata(object): class DiscMetadata(object): + """I represent all relevant disc metadata information found in MBz. + + :cvar artist: artist(s) name. + :vartype artist: + :cvar sortName: album artist sort name. + :vartype sortName: + :cvar title: title of the disc (with disambiguation). + :vartype title: + :cvar various: + :vartype various: + :cvar tracks: + :vartype tracks: + :cvar release: earliest release date, in YYYY-MM-DD. + :vartype release: unicode + :cvar releaseTitle: title of the release (without disambiguation). + :vartype releaseTitle: + :cvar releaseType: + :vartype releaseType: + :cvar mbid: + :vartype mbid: + :cvar mbidArtist: + :vartype mbidArtist: + :cvar url: + :vartype url: + :cvar catalogNumber: + :vartype catalogNumber: + :cvar barcode: + :vartype barcode: + :ivar tracks: + :vartype tracks: """ - @param artist: artist(s) name - @param sortName: album artist sort name - @param release: earliest release date, in YYYY-MM-DD - @type release: unicode - @param title: title of the disc (with disambiguation) - @param releaseTitle: title of the release (without disambiguation) - @type tracks: C{list} of L{TrackMetadata} - """ + artist = None sortName = None title = None @@ -112,10 +133,7 @@ def _record(record, which, name, what): class _Credit(list): - """ - I am a representation of an artist-credit in MusicBrainz for a disc - or track. - """ + """Representation of an artist-credit in MusicBrainz for a disc/track.""" def joiner(self, attributeGetter, joinString=None): res = [] @@ -144,12 +162,19 @@ def getIds(self): def _getMetadata(releaseShort, release, discid, country=None): - """ - @type release: C{dict} - @param release: a release dict as returned in the value for key release - from get_release_by_id - - @rtype: L{DiscMetadata} or None + """Get disc's metadata using MusicBrainz. + + :param releaseShort: + :type releaseShort: + :param release: a release dict as returned in the value for key release + from get_release_by_id. + :type release: C{dict} + :param discid: + :type discid: + :param country: (Default value = None). + :type country: + :returns: + :rtype: L{DiscMetadata} or None """ logger.debug('getMetadata for release id %r', release['id']) @@ -256,15 +281,18 @@ def _getMetadata(releaseShort, release, discid, country=None): def musicbrainz(discid, country=None, record=False): - """ - Based on a MusicBrainz disc id, get a list of DiscMetadata objects - for the given disc id. + """Get a list of DiscMetadata objects for the given MusicBrainz disc id. Example disc id: Mj48G109whzEmAbPBoGvd4KyCS4- - @type discid: str - - @rtype: list of L{DiscMetadata} + :param discid: + :type discid: str + :param country: (Default value = None). + :type country: + :param record: (Default value = False). + :type record: + :returns: + :rtype: list of L{DiscMetadata} """ logger.debug('looking up results for discid %r', discid) import musicbrainzngs @@ -274,7 +302,7 @@ def musicbrainz(discid, country=None, record=False): try: result = musicbrainzngs.get_releases_by_discid( discid, includes=["artists", "recordings", "release-groups"]) - except musicbrainzngs.ResponseError, e: + except musicbrainzngs.ResponseError as e: if isinstance(e.cause, urllib2.HTTPError): if e.cause.code == 404: raise NotFoundException(e) diff --git a/whipper/common/path.py b/whipper/common/path.py index a5d0eb4b..5d3a4354 100644 --- a/whipper/common/path.py +++ b/whipper/common/path.py @@ -22,17 +22,19 @@ class PathFilter(object): - """ - I filter path components for safe storage on file systems. + """I filter path components for safe storage on file systems. + + :ivar slashes: whether to convert slashes to dashes. + :vartype slashes: + :ivar quotes: whether to normalize quotes. + :vartype quotes: + :ivar fat: whether to strip characters illegal on FAT filesystems. + :vartype fat: + :ivar special: whether to strip special characters. + :vartype special: """ def __init__(self, slashes=True, quotes=True, fat=True, special=False): - """ - @param slashes: whether to convert slashes to dashes - @param quotes: whether to normalize quotes - @param fat: whether to strip characters illegal on FAT filesystems - @param special: whether to strip special characters - """ self._slashes = slashes self._quotes = quotes self._fat = fat diff --git a/whipper/common/program.py b/whipper/common/program.py index 1537229f..3e6fee1c 100644 --- a/whipper/common/program.py +++ b/whipper/common/program.py @@ -18,9 +18,7 @@ # You should have received a copy of the GNU General Public License # along with whipper. If not, see . -""" -Common functionality and class for all programs using whipper. -""" +"""Common functionality and class for all programs using whipper.""" import musicbrainzngs import re @@ -41,15 +39,26 @@ class Program: - """ - I maintain program state and functionality. - - @ivar metadata: - @type metadata: L{mbngs.DiscMetadata} - @ivar result: the rip's result - @type result: L{result.RipResult} - @type outdir: unicode - @type config: L{whipper.common.config.Config} + """I maintain program state and functionality. + + :cvar cuePath: + :vartype cuePath: + :cvar logPath: + :vartype logPath: + :cvar metadata: + :vartype metadata: L{mbngs.DiscMetadata} + :cvar outdir: + :vartype outdir: unicode + :cvar result: the rip's result + :vartype result: L{result.RipResult} + :ivar config: + :vartype config: + :ivar record: whether to record results of API calls for playback. + :vartype record: + :param stdout: (Default value = sys.stdout). + :type stdout: + :ivar cache: + :vartype cache: """ cuePath = None @@ -61,9 +70,6 @@ class Program: _stdout = None def __init__(self, config, record=False, stdout=sys.stdout): - """ - @param record: whether to record results of API calls for playback. - """ self._record = record self._cache = cache.ResultCache() self._stdout = stdout @@ -90,11 +96,18 @@ def setWorkingDirectory(self, workingDirectory): os.chdir(workingDirectory) def getFastToc(self, runner, toc_pickle, device): - """ - Retrieve the normal TOC table from a toc pickle or the drive. + """Retrieve the normal TOC table from a toc pickle or the drive. + Also retrieves the cdrdao version - @rtype: tuple of L{table.Table}, str + :param runner: + :type runner: + :param toc_pickle: + :type toc_pickle: + :param device: + :type device: + :returns: + :rtype: tuple of L{table.Table}, str """ def function(r, t): r.run(t) @@ -114,10 +127,20 @@ def function(r, t): return toc def getTable(self, runner, cddbdiscid, mbdiscid, device, offset): - """ - Retrieve the Table either from the cache or the drive. - - @rtype: L{table.Table} + """Retrieve the Table either from the cache or the drive. + + :param runner: + :type runner: + :param cddbdiscid: + :type cddbdiscid: + :param mbdiscid: + :type mbdiscid: + :param device: + :type device: + :param offset: + :type offset: + :returns: + :rtype: L{table.Table} """ tcache = cache.TableCache() ptable = tcache.get(cddbdiscid, mbdiscid) @@ -154,11 +177,15 @@ def getTable(self, runner, cddbdiscid, mbdiscid, device, offset): return itable def getRipResult(self, cddbdiscid): - """ - Retrieve the persistable RipResult either from our cache (from a - previous, possibly aborted rip), or return a new one. + """Retrieve the persistable RipResult. + + RipResult is either retrieved from our cache (from a previous, + possibly aborted rip), or return a new one. - @rtype: L{result.RipResult} + :param cddbdiscid: + :type cddbdiscid: + :returns: + :rtype: L{result.RipResult} """ assert self.result is None @@ -171,7 +198,7 @@ def saveRipResult(self): self._presult.persist() def addDisambiguation(self, template_part, metadata): - "Add disambiguation to template path part string." + """Add disambiguation to template path part string.""" if metadata.catalogNumber: template_part += ' (%s)' % metadata.catalogNumber elif metadata.barcode: @@ -179,29 +206,40 @@ def addDisambiguation(self, template_part, metadata): return template_part def getPath(self, outdir, template, mbdiscid, metadata, track_number=None): - """ - Return disc or track path relative to outdir according to - template. Track paths do not include extension. + """Return disc or track path relative to outdir according to template. + + Track paths do not include extension. Tracks are named according to the track template, filling in the variables and adding the file extension. Variables exclusive to the track template are: - - %t: track number - - %a: track artist - - %n: track title - - %s: track sort name + * %t: track number. + * %a: track artist. + * %n: track title. + * %s: track sort name. Disc files (.cue, .log, .m3u) are named according to the disc template, filling in the variables and adding the file extension. Variables for both disc and track template are: - - %A: album artist - - %S: album sort name - - %d: disc title - - %y: release year - - %r: release type, lowercase - - %R: Release type, normal case - - %x: audio extension, lowercase - - %X: audio extension, uppercase + * %A: album artist. + * %S: album sort name. + * %d: disc title. + * %y: release year. + * %r: release type, lowercase. + * %R: Release type, normal case. + * %x: audio extension, lowercase. + * %X: audio extension, uppercase. + + :param outdir: + :type outdir: + :param template: + :type template: + :param mbdiscid: + :type mbdiscid: + :param metadata: + :type metadata: + :param track_number: (Default value = None) + :type track_number: """ assert type(outdir) is unicode, "%r is not unicode" % outdir assert type(template) is unicode, "%r is not unicode" % template @@ -249,10 +287,12 @@ def getPath(self, outdir, template, mbdiscid, metadata, track_number=None): return os.path.join(outdir, template % v) def getCDDB(self, cddbdiscid): - """ - @param cddbdiscid: list of id, tracks, offsets, seconds + """Query CDDB using the given cddbdiscid to find the disc title. - @rtype: str + :param cddbdiscid: list of id, tracks, offsets, seconds. + :type cddbdiscid: + :returns: + :rtype: str """ # FIXME: convert to nonblocking? import CDDB @@ -262,7 +302,7 @@ def getCDDB(self, cddbdiscid): if code == 200: return md['title'] - except IOError, e: + except IOError as e: # FIXME: for some reason errno is a str ? if e.errno == 'socket error': self._stdout.write("Warning: network error: %r\n" % (e, )) @@ -273,8 +313,18 @@ def getCDDB(self, cddbdiscid): def getMusicBrainz(self, ittoc, mbdiscid, release=None, country=None, prompt=False): - """ - @type ittoc: L{whipper.image.table.Table} + """Look up disc on MusicBrainz and get the relevant metadata. + + :param ittoc: + :type ittoc: L{whipper.image.table.Table} + :param mbdiscid: + :type mbdiscid: + :param release: (Default value = None) + :type release: + :param country: (Default value = None) + :type country: + :param prompt: (Default value = False) + :type prompt: """ # look up disc on MusicBrainz self._stdout.write('Disc duration: %s, %d audio tracks\n' % ( @@ -293,13 +343,13 @@ def getMusicBrainz(self, ittoc, mbdiscid, release=None, country=None, country=country, record=self._record) break - except mbngs.NotFoundException, e: + except mbngs.NotFoundException as e: logger.warning("release not found: %r" % (e, )) break - except musicbrainzngs.NetworkError, e: + except musicbrainzngs.NetworkError as e: logger.warning("network error: %r" % (e, )) break - except mbngs.MusicBrainzException, e: + except mbngs.MusicBrainzException as e: logger.warning("musicbrainz exception: %r" % (e, )) time.sleep(5) continue @@ -406,13 +456,12 @@ def getMusicBrainz(self, ittoc, mbdiscid, release=None, country=None, return ret def getTagList(self, number): - """ - Based on the metadata, get a dict of tags for the given track. + """Based on the metadata, get a dict of tags for the given track. - @param number: track number (0 for HTOA) - @type number: int - - @rtype: dict + :param number: track number (0 for HTOA). + :type number: int + :returns: + :rtype: dict """ trackArtist = u'Unknown Artist' albumArtist = u'Unknown Artist' @@ -434,7 +483,7 @@ def getTagList(self, number): title = track.title mbidTrack = track.mbid mbidTrackArtist = track.mbidArtist - except IndexError, e: + except IndexError as e: print 'ERROR: no track %d found, %r' % (number, e) raise else: @@ -467,10 +516,9 @@ def getTagList(self, number): return tags def getHTOA(self): - """ - Check if we have hidden track one audio. + """Check if we have hidden track one audio. - @returns: tuple of (start, stop), or None + :returns: tuple of (start, stop), or None. """ track = self.result.table.tracks[0] try: @@ -488,7 +536,7 @@ def verifyTrack(self, runner, trackResult): try: runner.run(t) - except task.TaskException, e: + except task.TaskException as e: if isinstance(e.exception, common.MissingFrames): logger.warning('missing frames for %r' % trackResult.filename) return False @@ -503,12 +551,25 @@ def verifyTrack(self, runner, trackResult): def ripTrack(self, runner, trackResult, offset, device, taglist, overread, what=None): - """ + """. + Ripping the track may change the track's filename as stored in trackResult. - @param trackResult: the object to store information in. - @type trackResult: L{result.TrackResult} + :param trackResult: the object to store information in. + :type trackResult: L{result.TrackResult} + :param runner: + :type runner: + :param offset: + :type offset: + :param device: + :type device: + :param taglist: + :type taglist: + :param overread: + :type overread: + :param what: (Default value = None) + :type what: """ if trackResult.number == 0: start, stop = self.getHTOA() @@ -558,14 +619,19 @@ def retagImage(self, runner, taglists): runner.run(t) def verifyImage(self, runner, table): - """ - verify table against accuraterip and cue_path track lengths + """Verify table against accuraterip and cue_path track lengths. + Verify our image against the given AccurateRip responses. Needs an initialized self.result. Will set accurip and friends on each TrackResult. Populates self.result.tracks with above TrackResults. + + :param runner: + :type runner: + :param table: + :type table: """ cueImage = image.Image(self.cuePath) # assigns track lengths diff --git a/whipper/common/renamer.py b/whipper/common/renamer.py index 8db09a44..f1f9afd0 100644 --- a/whipper/common/renamer.py +++ b/whipper/common/renamer.py @@ -21,9 +21,7 @@ import os import tempfile -""" -Rename files on file system and inside metafiles in a resumable way. -""" +"""Rename files on file system and inside metafiles in a resumable way.""" class Operator(object): @@ -36,14 +34,16 @@ def __init__(self, statePath, key): self._resuming = False def addOperation(self, operation): - """ - Add an operation. + """Add an operation. + + :param operation: + :type operation: """ self._todo.append(operation) def load(self): - """ - Load state from the given state path using the given key. + """Load state from the given state path using the given key. + Verifies the state. """ todo = os.path.join(self._statePath, self._key + '.todo') @@ -68,9 +68,7 @@ def load(self): self._resuming = True def save(self): - """ - Saves the state to the given state path using the given key. - """ + """Save the state to the given state path using the given key.""" # only save todo first time todo = os.path.join(self._statePath, self._key + '.todo') if not os.path.exists(todo): @@ -89,9 +87,7 @@ def save(self): handle.write('%s %s\n' % (name, data)) def start(self): - """ - Execute the operations - """ + """Execute the operations.""" def next(self): operation = self._todo[len(self._done)] @@ -108,52 +104,50 @@ def next(self): class FileRenamer(Operator): def addRename(self, source, destination): - """ - Add a rename operation. + """Add a rename operation. - @param source: source filename - @type source: str - @param destination: destination filename - @type destination: str + :param source: source filename. + :type source: str + :param destination: destination filename. + :type destination: str """ class Operation(object): def verify(self): - """ - Check if the operation will succeed in the current conditions. + """Check if the operation will succeed in the current conditions. + Consider this a pre-flight check. Does not eliminate the need to handle errors as they happen. """ def do(self): - """ - Perform the operation. - """ + """Perform the operation.""" pass def redo(self): - """ - Perform the operation, without knowing if it already has been - (partly) performed. + """Perform the operation. + + Without knowing if it already has been (partly) performed. """ self.do() def serialize(self): - """ - Serialize the operation. - The return value should bu usable with L{deserialize} + """Serialize the operation. - @rtype: str + The return value should be usable with L{deserialize}. + + :returns: + :rtype: str """ def deserialize(cls, data): - """ - Deserialize the operation with the given operation data. + """Deserialize the operation with the given operation data. - @type data: str + :param data: + :type data: str """ raise NotImplementedError deserialize = classmethod(deserialize) diff --git a/whipper/common/task.py b/whipper/common/task.py index 50766b01..38254889 100644 --- a/whipper/common/task.py +++ b/whipper/common/task.py @@ -25,9 +25,7 @@ class LoggableMultiSeparateTask(task.MultiSeparateTask): class PopenTask(task.Task): - """ - I am a task that runs a command using Popen. - """ + """I am a task that runs a command using Popen.""" logCategory = 'PopenTask' bufsize = 1024 @@ -44,7 +42,7 @@ def start(self, runner): stdout=subprocess.PIPE, stderr=subprocess.PIPE, close_fds=True, cwd=self.cwd) - except OSError, e: + except OSError as e: import errno if e.errno == errno.ENOENT: self.commandMissing() @@ -88,7 +86,7 @@ def _read(self, runner): return self._done() - except Exception, e: + except Exception as e: logger.debug('exception during _read(): %r', str(e)) self.setException(e) self.stop() @@ -118,31 +116,29 @@ def abort(self): # self.stop() def readbytesout(self, bytes): - """ - Called when bytes have been read from stdout. + """Call when bytes have been read from stdout. + + :param bytes: + :type bytes: """ pass def readbyteserr(self, bytes): - """ - Called when bytes have been read from stderr. + """Call when bytes have been read from stderr. + + :param bytes: + :type bytes: """ pass def done(self): - """ - Called when the command completed successfully. - """ + """Call when the command completed successfully.""" pass def failed(self): - """ - Called when the command failed. - """ + """Call when the command failed.""" pass def commandMissing(self): - """ - Called when the command is missing. - """ + """Call when the command is missing.""" pass diff --git a/whipper/extern/asyncsub.py b/whipper/extern/asyncsub.py index 6587f549..836934a7 100644 --- a/whipper/extern/asyncsub.py +++ b/whipper/extern/asyncsub.py @@ -53,7 +53,7 @@ def send(self, input): (errCode, written) = WriteFile(x, input) except ValueError: return self._close('stdin') - except (subprocess.pywintypes.error, Exception), why: + except (subprocess.pywintypes.error, Exception) as why: if why[0] in (109, errno.ESHUTDOWN): return self._close('stdin') raise @@ -74,7 +74,7 @@ def _recv(self, which, maxsize): (errCode, read) = ReadFile(x, nAvail, None) except ValueError: return self._close(which) - except (subprocess.pywintypes.error, Exception), why: + except (subprocess.pywintypes.error, Exception) as why: if why[0] in (109, errno.ESHUTDOWN): return self._close(which) raise @@ -94,7 +94,7 @@ def send(self, input): try: written = os.write(self.stdin.fileno(), input) - except OSError, why: + except OSError as why: if why[0] == errno.EPIPE: # broken pipe return self._close('stdin') raise diff --git a/whipper/extern/task/task.py b/whipper/extern/task/task.py index 9c40dd56..563b8561 100644 --- a/whipper/extern/task/task.py +++ b/whipper/extern/task/task.py @@ -24,9 +24,7 @@ class TaskException(Exception): - """ - I wrap an exception that happened during task execution. - """ + """I wrap an exception that happened during task execution.""" exception = None # original exception @@ -39,9 +37,16 @@ def __init__(self, exception, message=None): def _getExceptionMessage(exception, frame=-1, filename=None): - """ - Return a short message based on an exception, useful for debugging. + """Return a short message based on an exception, useful for debugging. + Tries to find where the exception was triggered. + + :param exception: + :type exception: + :param frame: (Default value = -1) + :type frame: + :param filename: (Default value = None) + :type filename: """ import traceback @@ -66,9 +71,7 @@ def _getExceptionMessage(exception, frame=-1, filename=None): class LogStub(object): - """ - I am a stub for a log interface. - """ + """I am a stub for a log interface.""" # log stubs def log(self, message, *args): @@ -88,19 +91,22 @@ def error(self, message, *args): class Task(LogStub): - """ - I wrap a task in an asynchronous interface. + """I wrap a task in an asynchronous interface. + I can be listened to for starting, stopping, description changes and progress updates. I communicate an error by setting self.exception to an exception and - stopping myself from running. - The listener can then handle the Task.exception. - - @ivar description: what am I doing - @ivar exception: set if an exception happened during the task - execution. Will be raised through run() at the end. + stopping myself from running. The listener can then handle the + Task.exception. + + :cvar description: what am I doing. + :vartype description: + :cvar exception: set if an exception happened during the task + execution. Will be raised through run() at the end. + :vartype exception: """ + logCategory = 'Task' description = 'I am doing something.' @@ -117,8 +123,7 @@ class Task(LogStub): # subclass methods def start(self, runner): - """ - Start the task. + """Start the task. Subclasses should chain up to me at the beginning. @@ -128,6 +133,9 @@ def start(self, runner): If start doesn't raise an exception, the task should run until complete, or setException and stop(). + + :param runner: + :type runner: """ self.debug('starting') self.setProgress(self.progress) @@ -136,8 +144,8 @@ def start(self, runner): self._notifyListeners('started') def stop(self): - """ - Stop the task. + """Stop the task. + Also resets the runner on the task. Subclasses should chain up to me at the end. @@ -159,9 +167,12 @@ def stop(self): # base class methods def setProgress(self, value): - """ - Notify about progress changes bigger than the increment. + """Notify about progress changes bigger than the increment. + Called by subclass implementations as the task progresses. + + :param value: + :type value: """ if (value - self.progress > self.increment or value >= 1.0 or value == 0.0): @@ -176,9 +187,12 @@ def setDescription(self, description): # FIXME: unify? def setExceptionAndTraceback(self, exception): - """ - Call this to set a synthetically created exception (and not one - that was actually raised and caught) + """Call this to set a synthetically created exception. + + Not an exception that was actually raised and caught. + + :param exception: + :type exception: """ import traceback @@ -201,8 +215,10 @@ def setExceptionAndTraceback(self, exception): setAndRaiseException = setExceptionAndTraceback def setException(self, exception): - """ - Call this to set a caught exception on the task. + """Call this to set a caught exception on the task. + + :param exception: + :type exception: """ import traceback @@ -221,10 +237,12 @@ def schedule(self, delta, callable, *args, **kwargs): self.runner.schedule(self, delta, callable, *args, **kwargs) def addListener(self, listener): - """ - Add a listener for task status changes. + """Add a listener for task status changes. Listeners should implement started, stopped, and progressed. + + :param listener: + :type listener: """ self.debug('Adding listener %r', listener) if not self._listeners: @@ -237,43 +255,53 @@ def _notifyListeners(self, methodName, *args, **kwargs): method = getattr(l, methodName) try: method(self, *args, **kwargs) - except Exception, e: + except Exception as e: self.setException(e) # FIXME: should this become a real interface, like in zope ? class ITaskListener(object): - """ - I am an interface for objects listening to tasks. - """ + """I am an interface for objects listening to tasks.""" + # listener callbacks def progressed(self, task, value): - """ - Implement me to be informed about progress. + """Implement me to be informed about progress. - @type value: float - @param value: progress, from 0.0 to 1.0 + :param value: progress, from 0.0 to 1.0. + :type value: float + :param task: + :type task: """ + pass def described(self, task, description): - """ - Implement me to be informed about description changes. + """Implement me to be informed about description changes. - @type description: str - @param description: description + :param description: + :type description: str + :param task: + :type task: """ + pass def started(self, task): + """Implement me to be informed about the task starting. + + :param task: + :type task: """ - Implement me to be informed about the task starting. - """ + pass def stopped(self, task): - """ - Implement me to be informed about the task stopping. + """Implement me to be informed about the task stopping. + If the task had an error, task.exception will be set. + + :param task: + :type task: """ + pass # this is a Dummy task that can be used to test if this works at all @@ -293,11 +321,10 @@ def _wind(self): class BaseMultiTask(Task, ITaskListener): - """ - I perform multiple tasks. + """I perform multiple tasks. - @ivar tasks: the tasks to run - @type tasks: list of L{Task} + :cvar tasks: the tasks to run. + :vartype tasks: list of L{Task} """ description = 'Doing various tasks' @@ -308,21 +335,23 @@ def __init__(self): self._task = 0 def addTask(self, task): - """ - Add a task. + """Add a task. - @type task: L{Task} + :param task: + :type task: L{Task} """ if self.tasks is None: self.tasks = [] self.tasks.append(task) def start(self, runner): - """ - Start tasks. + """Start tasks. Tasks can still be added while running. For example, a first task can determine how many additional tasks to run. + + :param runner: + :type runner: """ Task.start(self, runner) @@ -334,9 +363,7 @@ def start(self, runner): self.next() def next(self): - """ - Start the next task. - """ + """Start the next task.""" try: # start next task task = self.tasks[self._task] @@ -349,7 +376,7 @@ def next(self): task.start(self.runner) self.debug('BaseMultiTask.next(): started task %d of %d: %r', self._task, len(self.tasks), task) - except Exception, e: + except Exception as e: self.setException(e) self.debug('Got exception during next: %r', self.exceptionMessage) self.stop() @@ -363,9 +390,12 @@ def progressed(self, task, value): pass def stopped(self, task): - """ - Subclasses should chain up to me at the end of their implementation. + """Subclasses should chain up to me at the end of their implementation. + They should fall through to chaining up if there is an exception. + + :param task: + :type task: """ self.log('BaseMultiTask.stopped: task %r (%d of %d)', task, self.tasks.index(task) + 1, len(self.tasks)) @@ -388,10 +418,11 @@ def stopped(self, task): class MultiSeparateTask(BaseMultiTask): - """ - I perform multiple tasks. + """I perform multiple tasks. + I track progress of each individual task, going back to 0 for each task. """ + description = 'Doing various tasks separately' def start(self, runner): @@ -414,8 +445,8 @@ def described(self, description): class MultiCombinedTask(BaseMultiTask): - """ - I perform multiple tasks. + """I perform multiple tasks. + I track progress as a combined progress on all tasks on task granularity. """ @@ -433,37 +464,41 @@ def stopped(self, task): class TaskRunner(LogStub): - """ - I am a base class for task runners. + """I am a base class for task runners. + Task runners should be reusable. """ + logCategory = 'TaskRunner' def run(self, task): - """ - Run the given task. + """Run the given task. - @type task: Task + :param task: + :type task: Task """ raise NotImplementedError # methods for tasks to call def schedule(self, delta, callable, *args, **kwargs): - """ - Schedule a single future call. + """Schedule a single future call. Subclasses should implement this. - @type delta: float - @param delta: time in the future to schedule call for, in seconds. + :param delta: time in the future to schedule call for, in seconds. + :type delta: float + :param callable: + :type callable: + :param args: + :type args: + :param kwargs: + :type kwargs: """ raise NotImplementedError class SyncRunner(TaskRunner, ITaskListener): - """ - I run the task synchronously in a gobject MainLoop. - """ + """I run the task synchronously in a gobject MainLoop.""" def __init__(self, verbose=True): self._verbose = verbose @@ -502,7 +537,7 @@ def _startWrap(self, task): try: self.debug('start task %r' % task) task.start(self) - except Exception, e: + except Exception as e: # getExceptionMessage uses global exception state that doesn't # hang around, so store the message task.setException(e) @@ -516,7 +551,7 @@ def c(): callable, args, kwargs) callable(*args, **kwargs) return False - except Exception, e: + except Exception as e: self.debug('exception when calling scheduled callable %r', callable) task.setException(e) diff --git a/whipper/image/cue.py b/whipper/image/cue.py index 24a1e522..a43e5fc1 100644 --- a/whipper/image/cue.py +++ b/whipper/image/cue.py @@ -18,10 +18,9 @@ # You should have received a copy of the GNU General Public License # along with whipper. If not, see . -""" -Reading .cue files +"""Reading .cue files. -See http://digitalx.org/cuesheetsyntax.php +.. seealso:: http://digitalx.org/cuesheetsyntax.php """ import re @@ -59,18 +58,25 @@ class CueFile(object): + """I represent a .cue file as an object. + + :cvar logCategory: + :vartype logCategory: + :ivar path: + :vartype path: + :ivar rems: + :vartype rems: + :ivar messages: + :vartype messages: + :ivar leadout: + :vartype leadout: + :ivar table: the index table. + :vartype table: L{table.Table} """ - I represent a .cue file as an object. - @type table: L{table.Table} - @ivar table: the index table. - """ logCategory = 'CueFile' def __init__(self, path): - """ - @type path: unicode - """ assert type(path) is unicode, "%r is not unicode" % path self._path = path @@ -151,10 +157,12 @@ def parse(self): continue def message(self, number, message): - """ - Add a message about a given line in the cue file. + """Add a message about a given line in the cue file. - @param number: line number, counting from 0. + :param number: line number, counting from 0. + :type number: + :param message: + :type message: """ self._messages.append((number + 1, message)) @@ -179,23 +187,24 @@ def getTrackLength(self, track): return -1 def getRealPath(self, path): - """ - Translate the .cue's FILE to an existing path. + """Translate the .cue's FILE to an existing path. - @type path: unicode + :param path: + :type path: unicode """ return common.getRealPath(self._path, path) class File: - """ - I represent a FILE line in a cue file. + """I represent a FILE line in a cue file. + + :ivar path: + :vartype path: + :ivar format: + :vartype format: """ def __init__(self, path, format): - """ - @type path: unicode - """ assert type(path) is unicode, "%r is not unicode" % path self.path = path diff --git a/whipper/image/image.py b/whipper/image/image.py index 95549611..a154f2a3 100644 --- a/whipper/image/image.py +++ b/whipper/image/image.py @@ -18,10 +18,6 @@ # You should have received a copy of the GNU General Public License # along with whipper. If not, see . -""" -Wrap on-disk CD images based on the .cue file. -""" - import os from whipper.common import encode @@ -35,17 +31,23 @@ class Image(object): + """Wrap on-disk CD images based on the .cue file. + + :ivar path: .cue path. + :vartype path: unicode + :ivar cue: + :vartype cue: + :ivar offsets: + :vartype offsets: + :ivar lengths: + :vartype lengths: + :ivar table: the Table of Contents for this image. + :vartype table: L{table.Table} """ - @ivar table: The Table of Contents for this image. - @type table: L{table.Table} - """ + logCategory = 'Image' def __init__(self, path): - """ - @type path: unicode - @param path: .cue path - """ assert type(path) is unicode, "%r is not unicode" % path self._path = path @@ -57,19 +59,22 @@ def __init__(self, path): self.table = None def getRealPath(self, path): - """ - Translate the .cue's FILE to an existing path. + """Translate the .cue's FILE to an existing path. - @param path: .cue path + :param path: .cue path. + :type path: """ assert type(path) is unicode, "%r is not unicode" % path return self.cue.getRealPath(path) def setup(self, runner): - """ - Do initial setup, like figuring out track lengths, and - constructing the Table of Contents. + """Do initial setup. + + Like figuring out track lengths and constructing the Table of Contents. + + :param runner: + :type runner: """ logger.debug('setup image start') verify = ImageVerifyTask(self) @@ -108,8 +113,18 @@ def setup(self, runner): class ImageVerifyTask(task.MultiSeparateTask): - """ - I verify a disk image and get the necessary track lengths. + """I verify a disk image and get the necessary track lengths. + + :cvar logCategory: + :vartype logCategory: + :cvar description: + :vartype description: + :cvar lengths: + :vartype lengths: + :ivar image: + :vartype image: + :ivar tasks: + :vartype tasks: """ logCategory = 'ImageVerifyTask' @@ -173,8 +188,14 @@ def stop(self): class ImageEncodeTask(task.MultiSeparateTask): - """ - I encode a disk image to a different format. + """I encode a disk image to a different format. + + :ivar image: + :vartype image: + :ivar tasks: + :vartype tasks: + :ivar lengths: + :vartype lengths: """ description = "Encoding tracks" diff --git a/whipper/image/table.py b/whipper/image/table.py index 77617812..9cde73fa 100644 --- a/whipper/image/table.py +++ b/whipper/image/table.py @@ -18,9 +18,7 @@ # You should have received a copy of the GNU General Public License # along with whipper. If not, see . -""" -Wrap Table of Contents. -""" +"""Wrap Table of Contents.""" import copy import urllib @@ -53,20 +51,22 @@ class Track: - """ - I represent a track entry in an Table. - - @ivar number: track number (1-based) - @type number: int - @ivar audio: whether the track is audio - @type audio: bool - @type indexes: dict of number -> L{Index} - @ivar isrc: ISRC code (12 alphanumeric characters) - @type isrc: str - @ivar cdtext: dictionary of CD Text information; see L{CDTEXT_KEYS}. - @type cdtext: str -> unicode - @ivar pre_emphasis: whether track is pre-emphasised - @type pre_emphasis: bool + """I represent a track entry in an Table. + + :cvar number: track number (1-based). + :vartype number: int + :cvar audio: whether the track is audio. + :vartype audio: bool + :cvar indexes: + :vartype indexes: dict of number -> L{Index} + :cvar isrc: ISRC code (12 alphanumeric characters). + :vartype isrc: str + :cvar cdtext: dictionary of CD Text information; see L{CDTEXT_KEYS}. + :vartype cdtext: str -> unicode + :cvar session: + :vartype session: + :cvar pre_emphasis: whether track is pre-emphasised. + :vartype pre_emphasis: bool """ number = None @@ -88,8 +88,18 @@ def __init__(self, number, audio=True, session=None): def index(self, number, absolute=None, path=None, relative=None, counter=None): - """ - @type path: unicode or None + """Index constructor. + + :param number: + :type number: + :param absolute: (Default value = None) + :type absolute: + :param path: (Default value = None) + :type path: unicode or None + :param relative: (Default value = None) + :type relative: + :param counter: (Default value = None) + :type counter: """ if path is not None: assert type(path) is unicode, "%r is not unicode" % path @@ -101,24 +111,20 @@ def getIndex(self, number): return self.indexes[number] def getFirstIndex(self): - """ - Get the first chronological index for this track. + """Get the first chronological index for this track. Typically this is INDEX 01; but it could be INDEX 00 if there's a pre-gap. """ - indexes = self.indexes.keys() - indexes.sort() + indexes = sorted(self.indexes.keys()) return self.indexes[indexes[0]] def getLastIndex(self): - indexes = self.indexes.keys() - indexes.sort() + indexes = sorted(self.indexes.keys()) return self.indexes[indexes[-1]] def getPregap(self): - """ - Returns the length of the pregap for this track. + """Compute the length of the pregap for this track. The pregap is 0 if there is no index 0, and the difference between index 1 and index 0 if there is. @@ -130,11 +136,21 @@ def getPregap(self): class Index: - """ - @ivar counter: counter for the index source; distinguishes between + """I represent an index for the given source. + + :cvar number: + :vartype number: + :cvar absolute: + :vartype absolute: + :cvar path: + :vartype path: unicode or None + :cvar relative: + :vartype relative: + :cvar counter: counter for the index source; distinguishes between the matching FILE lines in .cue files for example - @type path: unicode or None + :vartype counter: """ + number = None absolute = None path = None @@ -159,14 +175,18 @@ def __repr__(self): class Table(object): - """ - I represent a table of indexes on a CD. - - @ivar tracks: tracks on this CD - @type tracks: list of L{Track} - @ivar catalog: catalog number - @type catalog: str - @type cdtext: dict of str -> str + """I represent a table of indexes on a CD. + + :cvar tracks: tracks on this CD. + :vartype tracks: list of L{Track} + :cvar leadout: + :vartype leadout: + :cvar catalog: catalog number. + :vartype catalog: str + :cvar cdtext: + :vartype cdtext: dict of str -> str + :cvar mbdiscid: + :vartype mbdiscid: """ tracks = None # list of Track @@ -193,23 +213,23 @@ def unpickled(self): logger.debug('set logName') def getTrackStart(self, number): - """ - @param number: the track number, 1-based - @type number: int + """Get the start of the given track number's index 1, in CD frames. - @returns: the start of the given track number's index 1, in CD frames - @rtype: int + :param number: the track number, 1-based. + :type number: int + :returns: the start of the given track number's index 1, in CD frames. + :rtype: int """ track = self.tracks[number - 1] return track.getIndex(1).absolute def getTrackEnd(self, number): - """ - @param number: the track number, 1-based - @type number: int + """Get the end of the given track number. - @returns: the end of the given track number (ie index 1 of next track) - @rtype: int + :param number: the track number, 1-based. + :type number: int + :returns: the end of the given track number (ie index 1 of next track). + :rtype: int """ # default to end of disc end = self.leadout - 1 @@ -228,25 +248,28 @@ def getTrackEnd(self, number): return end def getTrackLength(self, number): - """ - @param number: the track number, 1-based - @type number: int + """Get the length if the given track number, in cd frames. - @returns: the length of the given track number, in CD frames - @rtype: int + :param number: the track number, 1-based. + :type number: int + :returns: the length of the given track number, in CD frames. + :rtype: int """ return self.getTrackEnd(number) - self.getTrackStart(number) + 1 def getAudioTracks(self): - """ - @returns: the number of audio tracks on the CD - @rtype: int + """Get the number of audio tracks on the CD. + + :returns: the number of audio tracks on the CD. + :rtype: int """ return len([t for t in self.tracks if t.audio]) def hasDataTracks(self): - """ - @returns: whether this disc contains data tracks + """Tell wheter the disc contains data tracks. + + :returns: whether this disc contains data tracks + :rtype: bool """ return len([t for t in self.tracks if not t.audio]) > 0 @@ -259,16 +282,16 @@ def _cddbSum(self, i): return ret def getCDDBValues(self): - """ - Get all CDDB values needed to calculate disc id and lookup URL. + """Get all CDDB values needed to calculate disc id and lookup URL. This includes: - - CDDB disc id - - number of audio tracks - - offset of index 1 of each track - - length of disc in seconds (including data track) + * CDDB disc id. + * number of audio tracks. + * offset of index 1 of each track. + * length of disc in seconds (including data track). - @rtype: list of int + :returns: + :rtype: list of int """ result = [] @@ -320,21 +343,19 @@ def getCDDBValues(self): return result def getCDDBDiscId(self): - """ - Calculate the CDDB disc ID. + """Calculate the CDDB disc ID. - @rtype: str - @returns: the 8-character hexadecimal disc ID + :returns: the 8-character hexadecimal disc ID. + :rtype: str """ values = self.getCDDBValues() return "%08x" % values[0] def getMusicBrainzDiscId(self): - """ - Calculate the MusicBrainz disc ID. + """Calculate the MusicBrainz disc ID. - @rtype: str - @returns: the 28-character base64-encoded disc ID + :returns: the 28-character base64-encoded disc ID. + :rtype: str """ if self.mbdiscid: logger.debug('getMusicBrainzDiscId: returning cached %r' @@ -405,10 +426,13 @@ def getMusicBrainzSubmitURL(self): 'https', host, '/cdtoc/attach', '', query, '')) def getFrameLength(self, data=False): - """ - Get the length in frames (excluding HTOA) + """Get the length in frames (excluding HTOA). - @param data: whether to include the data tracks in the length + :param data: whether to include the data tracks in the length + (Default value = False) + :type data: + :returns: + :rtype: """ # the 'real' leadout, not offset by 150 frames if data: @@ -423,22 +447,20 @@ def getFrameLength(self, data=False): return durationFrames def duration(self): - """ - Get the duration in ms for all audio tracks (excluding HTOA). - """ + """Get the duration in ms for all audio tracks (excluding HTOA).""" return int(self.getFrameLength() * 1000.0 / common.FRAMES_PER_SECOND) def _getMusicBrainzValues(self): - """ - Get all MusicBrainz values needed to calculate disc id and submit URL. + """Get all MusicBrainz values needed to compute disc id and submit URL. This includes: - - track number of first track - - number of audio tracks - - leadout of disc - - offset of index 1 of each track + * track number of first track. + * number of audio tracks. + * leadout of disc. + * offset of index 1 of each track. - @rtype: list of int + :returns: + :rtype: list of int """ # MusicBrainz disc id does not take into account data tracks @@ -476,14 +498,16 @@ def _getMusicBrainzValues(self): return result def cue(self, cuePath='', program='whipper'): - """ - @param cuePath: path to the cue file to be written. If empty, - will treat paths as if in current directory. - + """Dump our internal representation to a .cue file content. - Dump our internal representation to a .cue file content. - - @rtype: C{unicode} + :param cuePath: path to the cue file to be written. If empty, + will treat paths as if in current directory. + (Default value = '') + :type cuePath: + :param program: (Default value = 'whipper') + :type program: + :returns: + :rtype: C{unicode} """ logger.debug('generating .cue for cuePath %r', cuePath) @@ -543,8 +567,7 @@ def writeFile(path): if not track.audio: continue - indexes = track.indexes.keys() - indexes.sort() + indexes = sorted(track.indexes.keys()) wroteTrack = False @@ -596,7 +619,7 @@ def writeFile(path): # handle any other INDEX 00 after its TRACK lines.append(" INDEX " "%02d %s" % (0, common.framesToMSF( - index00.relative))) + index00.relative))) if number > 0: # index 00 is output after TRACK up above @@ -611,8 +634,8 @@ def writeFile(path): # methods that modify the table def clearFiles(self): - """ - Clear all file backings. + """Clear all file backings. + Resets indexes paths and relative offsets. """ # FIXME: do a loop over track indexes better, with a pythonic @@ -634,15 +657,23 @@ def clearFiles(self): break def setFile(self, track, index, path, length, counter=None): - """ - Sets the given file as the source from the given index on. + """Set the given file as the source from the given index on. + Will loop over all indexes that fall within the given length, to adjust the path. Assumes all indexes have an absolute offset and will raise if not. - @type track: C{int} - @type index: C{int} + :param track: + :type track: C{int} + :param index: + :type index: C{int} + :param path: + :type path: + :param length: + :type length: + :param counter: (Default value = None) + :type counter: """ logger.debug('setFile: track %d, index %d, path %r, ' 'length %r, counter %r', track, index, path, length, @@ -670,8 +701,8 @@ def setFile(self, track, index, path, length, counter=None): break def absolutize(self): - """ - Calculate absolute offsets on indexes as much as possible. + """Calculate absolute offsets on indexes as much as possible. + Only possible for as long as tracks draw from the same file. """ t = self.tracks[0].number @@ -708,12 +739,14 @@ def absolutize(self): break def merge(self, other, session=2): - """ - Merges the given table at the end. - The other table is assumed to be from an additional session, + """Merge the given table at the end. + The other table is assumed to be from an additional session. - @type other: L{Table} + :param other: + :type other: L{Table} + :param session: (Default value = 2) + :type session: """ gap = self._getSessionGap(session) @@ -758,14 +791,15 @@ def _getSessionGap(self, session): # lookups def getNextTrackIndex(self, track, index): - """ - Return the next track and index. - - @param track: track number, 1-based + """Return the next track and index. - @raises IndexError: on last index - - @rtype: tuple of (int, int) + :param track: track number, 1-based. + :type track: + :param index: + :type index: + :raises IndexError: on last index. + :returns: + :rtype: tuple of (int, int) """ t = self.tracks[track - 1] indexes = t.indexes.keys() @@ -787,9 +821,9 @@ def getNextTrackIndex(self, track, index): # various tests for types of Table def hasTOC(self): - """ - Check if the Table has a complete TOC. - a TOC is a list of all tracks and their Index 01, with absolute + """Check if the Table has a complete TOC. + + A TOC is a list of all tracks and their Index 01, with absolute offsets, as well as the leadout. """ if not self.leadout: @@ -807,9 +841,10 @@ def hasTOC(self): return True def accuraterip_ids(self): - """ - returns both AccurateRip disc ids as a tuple of 8-char - hexadecimal strings (discid1, discid2) + """Compute both AccurateRip disc ids. + + The ids are returned as a tuple of 8-char hexadecimal + strings (discid1, discid2). """ # AccurateRip does not take into account data tracks, # but does count the data track to determine the leadout offset @@ -842,9 +877,7 @@ def accuraterip_path(self): ) def canCue(self): - """ - Check if this table can be used to generate a .cue file - """ + """Check if this table can be used to generate a .cue file.""" if not self.hasTOC(): logger.debug('No TOC, cannot cue') return False diff --git a/whipper/image/toc.py b/whipper/image/toc.py index aaf77ba1..54c8ada4 100644 --- a/whipper/image/toc.py +++ b/whipper/image/toc.py @@ -18,10 +18,9 @@ # You should have received a copy of the GNU General Public License # along with whipper. If not, see . -""" -Reading .toc files +"""Reading .toc files. -The .toc file format is described in the man page of cdrdao +The .toc file format is described in the man page of cdrdao. """ import re @@ -93,29 +92,40 @@ class Sources: - """ - I represent the list of sources used in the .toc file. + """I represent the list of sources used in the .toc file. + Each SILENCE and each FILE is a source. If the filename for FILE doesn't change, the counter is not increased. + + ivar sources: + vartype sources: """ def __init__(self): self._sources = [] def append(self, counter, offset, source): - """ - @param counter: the source counter; updates for each different - data source (silence or different file path) - @type counter: int - @param offset: the absolute disc offset where this source starts + """Append tuple containing source information to sources. + + This method also logs the event. + + :param counter: the source counter; updates for each different + data source (silence or different file path). + :type counter: int + :param offset: the absolute disc offset where this source starts. + :type offset: + :param source: + :type source: """ logger.debug('Appending source, counter %d, abs offset %d, ' 'source %r' % (counter, offset, source)) self._sources.append((counter, offset, source)) def get(self, offset): - """ - Retrieve the source used at the given offset. + """Retrieve the source used at the given offset. + + :param offset: + :type offset: """ for i, (c, o, s) in enumerate(self._sources): if offset < o: @@ -124,8 +134,10 @@ def get(self, offset): return self._sources[-1] def getCounterStart(self, counter): - """ - Retrieve the absolute offset of the first source for this counter + """Retrieve the absolute offset of the first source for this counter. + + :param counter: + :type counter: """ for i, (c, o, s) in enumerate(self._sources): if c == counter: @@ -135,11 +147,21 @@ def getCounterStart(self, counter): class TocFile(object): + """I represent a .toc file. + + :ivar path: + :vartype path: unicode + :ivar messages: + :vartype messages: + :ivar table: + :vartype table: + :ivar logName: + :vartype logName: + :ivar sources: + :vartype sources: + """ def __init__(self, path): - """ - @type path: unicode - """ assert type(path) is unicode, "%r is not unicode" % path self._path = path self._messages = [] @@ -378,17 +400,22 @@ def parse(self): logger.debug('parse: leadout: %r', self.table.leadout) def message(self, number, message): - """ - Add a message about a given line in the cue file. + """Add a message about a given line in the cue file. - @param number: line number, counting from 0. + :param number: line number, counting from 0. + :type number: + :param message: + :type message: """ self._messages.append((number + 1, message)) def getTrackLength(self, track): - """ - Returns the length of the given track, from its INDEX 01 to the next - track's INDEX 01 + """Compute the length of the given track. + + The lenght is computed from its INDEX 01 to the next track's INDEX 01. + + :param track: + :type track: """ # returns track length in frames, or -1 if can't be determined and # complete file should be assumed @@ -410,26 +437,26 @@ def getTrackLength(self, track): return -1 def getRealPath(self, path): - """ - Translate the .toc's FILE to an existing path. + """Translate the .toc's FILE to an existing path. - @type path: unicode + :param path: + :type path: unicode """ return common.getRealPath(self._path, path) class File: - """ - I represent a FILE line in a .toc file. + """I represent a FILE line in a .toc file. + + :ivar path: + :vartype path: C{unicode} + :ivar start: starting point for the track in this file, in frames. + :vartype start: C{int} + :ivar length: length for the track in this file, in frames. + :vartype length: """ def __init__(self, path, start, length): - """ - @type path: C{unicode} - @type start: C{int} - @param start: starting point for the track in this file, in frames - @param length: length for the track in this file, in frames - """ assert type(path) is unicode, "%r is not unicode" % path self.path = path diff --git a/whipper/program/cdparanoia.py b/whipper/program/cdparanoia.py index 66338a35..54a12b15 100644 --- a/whipper/program/cdparanoia.py +++ b/whipper/program/cdparanoia.py @@ -37,13 +37,10 @@ class FileSizeError(Exception): + """The given path does not have the expected size.""" message = None - """ - The given path does not have the expected size. - """ - def __init__(self, path, message): self.args = (path, message) self.path = path @@ -51,9 +48,7 @@ def __init__(self, path, message): class ReturnCodeError(Exception): - """ - The program had a non-zero return code. - """ + """The program had a non-zero return code.""" def __init__(self, returncode): self.args = (returncode, ) @@ -79,6 +74,22 @@ class ChecksumException(Exception): class ProgressParser: + """Parse cdparanoia's output information. + + :cvar read: + :vartype read: + :cvar wrote: + :vartype wrote: + :cvar errors: + :vartype errors: + :ivar reads: + :vartype reads: + :ivar start: first frame to rip. + :vartype start: int + :ivar stop: last frame to rip (inclusive). + :vartype stop: int + """ + read = 0 # last [read] frame wrote = 0 # last [wrote] frame errors = 0 # count of number of scsi errors @@ -87,12 +98,6 @@ class ProgressParser: reads = 0 # total number of reads def __init__(self, start, stop): - """ - @param start: first frame to rip - @type start: int - @param stop: last frame to rip (inclusive) - @type stop: int - """ self.start = start self.stop = stop @@ -102,8 +107,10 @@ def __init__(self, start, stop): self._reads = {} # read count for each sector def parse(self, line): - """ - Parse a line. + """Parse a line. + + :param line: + :type line: """ m = _PROGRESS_RE.search(line) if m: @@ -184,9 +191,12 @@ def _parse_wrote(self, wordOffset): self.wrote = frameOffset def getTrackQuality(self): - """ - Each frame gets read twice. + """Each frame gets read twice. + More than two reads for a frame reduce track quality. + + :returns: + :rtype: float or int """ frames = self.stop - self.start + 1 # + 1 since stop is inclusive reads = self.reads @@ -203,10 +213,35 @@ def getTrackQuality(self): # FIXME: handle errors class ReadTrackTask(task.Task): - """ - I am a task that reads a track using cdparanoia. - - @ivar reads: how many reads were done to rip the track + """I am a task that reads a track using cdparanoia. + + :cvar description: + :vartype description: + :cvar quality: + :cvar speed: + :cvar duration: + :ivar path: where to store the ripped track. + :vartype path: unicode + :ivar table: table of contents of CD. + :vartype table: L{table.Table} + :ivar start: first frame to rip. + :vartype start: int + :ivar stop: last frame to rip (inclusive); >= start. + :vartype stop: int + :ivar offset: read offset, in samples. + :vartype offset: int + :ivar parser: + :vartype parser: + :ivar device: the device to rip from. + :vartype device: str + :ivar start_time: + :vartype start_time: + :ivar overread: + :vartype overread: + :ivar buffer: + :vartype buffer: + :ivar errors: + :vartype errors: """ description = "Reading track" @@ -218,26 +253,6 @@ class ReadTrackTask(task.Task): def __init__(self, path, table, start, stop, overread, offset=0, device=None, action="Reading", what="track"): - """ - Read the given track. - - @param path: where to store the ripped track - @type path: unicode - @param table: table of contents of CD - @type table: L{table.Table} - @param start: first frame to rip - @type start: int - @param stop: last frame to rip (inclusive); >= start - @type stop: int - @param offset: read offset, in samples - @type offset: int - @param device: the device to rip from - @type device: str - @param action: a string representing the action; e.g. Read/Verify - @type action: str - @param what: a string representing what's being read; e.g. Track - @type what: str - """ assert type(path) is unicode, "%r is not unicode" % path self.path = path @@ -299,7 +314,7 @@ def start(self, runner): stdout=subprocess.PIPE, stderr=subprocess.PIPE, close_fds=True) - except OSError, e: + except OSError as e: import errno if e.errno == errno.ENOENT: raise common.MissingDependencyException('cdparanoia') @@ -398,24 +413,45 @@ def _done(self): class ReadVerifyTrackTask(task.MultiSeparateTask): - """ - I am a task that reads and verifies a track using cdparanoia. + """I am a task that reads and verifies a track using cdparanoia. + I also encode the track. The path where the file is stored can be changed if necessary, for example if the file name is too long. - @ivar path: the path where the file is to be stored. - @ivar checksum: the checksum of the track; set if they match. - @ivar testchecksum: the test checksum of the track. - @ivar copychecksum: the copy checksum of the track. - @ivar testspeed: the test speed of the track, as a multiple of - track duration. - @ivar copyspeed: the copy speed of the track, as a multiple of - track duration. - @ivar testduration: the test duration of the track, in seconds. - @ivar copyduration: the copy duration of the track, in seconds. - @ivar peak: the peak level of the track + :cvar checksum: the checksum of the track; set if they match. + :vartype checksum: + :cvar testchecksum: the test checksum of the track. + :vartype testchecksum: + :cvar copychecksum: the copy checksum of the track. + :vartype copychecksum: + :cvar peak: the peak level of the track + :vartype peak: + :cvar quality: + :vartype quality: + :cvar testspeed: the test speed of the track, as a multiple of + track duration. + :vartype testspeed: + :cvar copyspeed: the copy speed of the track, as a multiple of + track duration. + :vartype copyspeed: + :cvar testduration: the test duration of the track, in seconds. + :vartype testduration: + :cvar copyduration: the copy duration of the track, in seconds. + :vartype copyduration: + :ivar path: the path where the file is to be stored. + :vartype path: str + :ivar table: table of contents of CD. + :vartype table: L{table.Table} + :ivar stop: last frame to rip (inclusive). + :vartype stop: int + :ivar offset: read offset, in samples. + :vartype offset: int + :ivar device: the device to rip from. + :vartype device: str + :ivar taglist: a dict of tags. + :vartype taglist: dict """ checksum = None @@ -433,22 +469,6 @@ class ReadVerifyTrackTask(task.MultiSeparateTask): def __init__(self, path, table, start, stop, overread, offset=0, device=None, taglist=None, what="track"): - """ - @param path: where to store the ripped track - @type path: str - @param table: table of contents of CD - @type table: L{table.Table} - @param start: first frame to rip - @type start: int - @param stop: last frame to rip (inclusive) - @type stop: int - @param offset: read offset, in samples - @type offset: int - @param device: the device to rip from - @type device: str - @param taglist: a dict of tags - @type taglist: dict - """ task.MultiSeparateTask.__init__(self) logger.debug('Creating read and verify task on %r', path) @@ -478,7 +498,7 @@ def __init__(self, path, table, start, stop, overread, offset=0, try: tmpoutpath = path + u'.part' open(tmpoutpath, 'wb').close() - except IOError, e: + except IOError as e: if errno.ENAMETOOLONG != e.errno: raise path = common.shrinkPath(path) @@ -540,7 +560,7 @@ def stop(self): try: logger.debug('Moving to final path %r', self.path) os.rename(self._tmppath, self.path) - except Exception, e: + except Exception as e: logger.debug('Exception while moving to final ' 'path %r: %r', self.path, str(e)) self.exception = e @@ -548,7 +568,7 @@ def stop(self): os.unlink(self._tmppath) else: logger.debug('stop: exception %r', self.exception) - except Exception, e: + except Exception as e: print 'WARNING: unhandled exception %r' % (e, ) task.MultiSeparateTask.stop(self) diff --git a/whipper/program/cdrdao.py b/whipper/program/cdrdao.py index e0da15c1..8d2b92fd 100644 --- a/whipper/program/cdrdao.py +++ b/whipper/program/cdrdao.py @@ -13,8 +13,14 @@ def read_toc(device, fast_toc=False): - """ - Return cdrdao-generated table of contents for 'device'. + """Get the cd's toc using cdrdao and parse it. + + :param device: optical disk drive. + :type device: + :param fast_toc: enable cdrdao's fast-toc option? (Default value = False) + :type fast_toc: bool + :returns: + :rtype: TocFile """ # cdrdao MUST be passed a non-existing filename as its last argument # to write the TOC to; it does not support writing to stdout or @@ -48,8 +54,12 @@ def read_toc(device, fast_toc=False): def DetectCdr(device): - """ - Return whether cdrdao detects a CD-R for 'device'. + """Check if inserted disk is a CD-R. + + :param device: optical disk drive. + :type device: + :returns: False if inserted disk is not a CD-R, True otherwise. + :rtype: bool """ cmd = [CDRDAO, 'disk-info', '-v1', '--device', device] logger.debug("executing %r", cmd) @@ -61,8 +71,10 @@ def DetectCdr(device): def version(): - """ - Return cdrdao version as a string. + """Detect cdrdao's version. + + :returns: + :rtype: """ cdrdao = Popen(CDRDAO, stderr=PIPE) out, err = cdrdao.communicate() @@ -80,21 +92,31 @@ def version(): def ReadTOCTask(device): - """ - stopgap morituri-insanity compatibility layer + """Stopgap morituri-insanity compatibility layer. + + :param device: optical disk drive. + :type device: + :returns: + :rtype: TocFile """ return read_toc(device, fast_toc=True) def ReadTableTask(device): - """ - stopgap morituri-insanity compatibility layer + """Stopgap morituri-insanity compatibility layer. + + :param device: optical disk drive. + :type device: + :returns: + :rtype: TocFile """ return read_toc(device) def getCDRDAOVersion(): - """ - stopgap morituri-insanity compatibility layer + """Stopgap morituri-insanity compatibility layer. + + :returns: + :rtype: """ return version() diff --git a/whipper/program/flac.py b/whipper/program/flac.py index 0f388395..13aeb119 100644 --- a/whipper/program/flac.py +++ b/whipper/program/flac.py @@ -5,9 +5,15 @@ def encode(infile, outfile): - """ - Encodes infile to outfile, with flac. - Uses '-f' because whipper already creates the file. + """Encode infile to outfile, with flac. + + Uses ``-f`` because whipper already creates the file. + + :param infile: full path to input audio track. + :type infile: str + :param outfile: full path to output audio track. + :type outfile: str + :raises CalledProcessError: if the flac encoder returns non-zero. """ try: # TODO: Replace with Popen so that we can catch stderr and write it to diff --git a/whipper/program/sox.py b/whipper/program/sox.py index 3956ec30..057071f7 100644 --- a/whipper/program/sox.py +++ b/whipper/program/sox.py @@ -8,11 +8,12 @@ def peak_level(track_path): - """ - Accepts a path to a sox-decodable audio file. + """Accept a path to a sox-decodable audio file. - Returns track peak level from sox ('maximum amplitude') as a float. - Returns None on error. + :param track_path: full path to audio track. + :type track_path: str + :returns: track peak level from sox ('maximum amplitude') or None on error. + :rtype: float or None """ if not os.path.exists(track_path): logger.warning("SoX peak detection failed: file not found") diff --git a/whipper/program/soxi.py b/whipper/program/soxi.py index 567b2663..63e1d351 100644 --- a/whipper/program/soxi.py +++ b/whipper/program/soxi.py @@ -10,19 +10,29 @@ class AudioLengthTask(ctask.PopenTask): + """Calculate the length of a track in audio samples. + + :cvar logCategory: + :vartype logCategory: + :cvar description: + :vartype description: + :cvar length: length of the decoded audio file, in audio samples. + :vartype length: int or None + :ivar logName: + :vartype logName: + :ivar command: + :vartype command: + :ivar error: + :vartype error: + :ivar output: + :vartype output: """ - I calculate the length of a track in audio samples. - @ivar length: length of the decoded audio file, in audio samples. - """ logCategory = 'AudioLengthTask' description = 'Getting length of audio track' length = None def __init__(self, path): - """ - @type path: unicode - """ assert type(path) is unicode, "%r is not unicode" % path self.logName = os.path.basename(path).encode('utf-8') diff --git a/whipper/program/utils.py b/whipper/program/utils.py index d5bec2c0..70ac15d7 100644 --- a/whipper/program/utils.py +++ b/whipper/program/utils.py @@ -5,27 +5,34 @@ def eject_device(device): - """ - Eject the given device. + """Eject the given device. + + :param device: optical disk drive. + :type device: """ logger.debug("ejecting device %s", device) os.system('eject %s' % device) def load_device(device): - """ - Load the given device. + """Load the given device. + + :param device: optical disk drive. + :type device: """ logger.debug("loading (eject -t) device %s", device) os.system('eject -t %s' % device) def unmount_device(device): - """ - Unmount the given device if it is mounted, as happens with automounted - data tracks. + """Unmount the given device if it is mounted. + + Data tracks are usually automounted. If the given device is a symlink, the target will be checked. + + :param device: optical disk drive. + :type device: """ device = os.path.realpath(device) logger.debug('possibly unmount real path %r' % device) diff --git a/whipper/result/logger.py b/whipper/result/logger.py index e5eaabc3..e8c4bb16 100644 --- a/whipper/result/logger.py +++ b/whipper/result/logger.py @@ -14,14 +14,28 @@ class WhipperLogger(result.Logger): _errors = False def log(self, ripResult, epoch=time.time()): - """Returns big str: logfile joined text lines""" - + """Join all logfile lines in a single str. + + :param ripResult: + :type ripResult: + :param epoch: rip time since the epoch (Default value = time.time()). + :type epoch: float + :returns: logfile report + :rtype: str + """ lines = self.logRip(ripResult, epoch=epoch) return "\n".join(lines) def logRip(self, ripResult, epoch): - """Returns logfile lines list""" - + """Generate logfile as a list of str lines. + + :param ripResult: + :type ripResult: + :param epoch: rip time since the epoch. + :type epoch: float + :returns: + :rtype: str + """ lines = [] # Ripper version @@ -156,8 +170,15 @@ def logRip(self, ripResult, epoch): return lines def trackLog(self, trackResult): - """Returns Tracks section lines: data picked from trackResult""" + """Generate tracks section lines. + + Tracks information are mostly taken from ``trackResult``. + :param trackResult: + :type trackResult: + :returns: tracks section lines. + :rtype: list + """ lines = [] # Track number diff --git a/whipper/result/result.py b/whipper/result/result.py index f56d91e3..f0e0df43 100644 --- a/whipper/result/result.py +++ b/whipper/result/result.py @@ -23,6 +23,15 @@ class TrackResult: + """I hold information about the rip result of a track. + + * *CRC:* calculated 4 byte AccurateRip CRC. + * *DBCRC:* 4 byte AccurateRip CRC from the AR database. + * *DBConfidence:* confidence for the matched AccurateRip DB CRC. + * *DBMaxConfidence:* track's maximum confidence in the AccurateRip DB. + * *DBMaxConfidenceCRC:* maximum confidence CRC. + """ + number = None filename = None pregap = 0 # in frames @@ -40,14 +49,6 @@ class TrackResult: classVersion = 3 def __init__(self): - """ - CRC: calculated 4 byte AccurateRip CRC - DBCRC: 4 byte AccurateRip CRC from the AR database - DBConfidence: confidence for the matched AccurateRip DB CRC - - DBMaxConfidence: track's maximum confidence in the AccurateRip DB - DBMaxConfidenceCRC: maximum confidence CRC - """ self.AR = { 'v1': { 'CRC': None, @@ -65,20 +66,24 @@ def __init__(self): class RipResult: - """ - I hold information about the result for rips. - I can be used to write log files. - - @ivar offset: sample read offset - @ivar table: the full index table - @type table: L{whipper.image.table.Table} + """I hold information about the result for rips. - @ivar vendor: vendor of the CD drive - @ivar model: model of the CD drive - @ivar release: release of the CD drive + I can be used to write log files. - @ivar cdrdaoVersion: version of cdrdao used for the rip - @ivar cdparanoiaVersion: version of cdparanoia used for the rip + :cvar offset: sample read offset. + :vartype offset: + :cvar table: the full index table. + :vartype table: L{whipper.image.table.Table} + :cvar vendor: vendor of the CD drive. + :vartype vendor: + :cvar model: model of the CD drive. + :vartype model: + :cvar release: release of the CD drive. + :vartype release: + :cvar cdrdaoVersion: version of cdrdao used for the rip. + :vartype cdrdaoVersion: + :cvar cdparanoiaVersion: version of cdparanoia used for the rip. + :vartype cdparanoiaVersion: """ offset = 0 @@ -103,11 +108,10 @@ def __init__(self): self.tracks = [] def getTrackResult(self, number): - """ - @param number: the track number (0 for HTOA) + """Get the TrackResult for the given track number. - @type number: int - @rtype: L{TrackResult} + :param number: the track number (0 for HTOA) + :type number: int """ for t in self.tracks: if t.number == number: @@ -117,19 +121,16 @@ def getTrackResult(self, number): class Logger(object): - """ - I log the result of a rip. - """ + """I log the result of a rip.""" def log(self, ripResult, epoch=time.time()): - """ - Create a log from the given ripresult. + """Create a log from the given ripresult. - @param epoch: when the log file gets generated - @type epoch: float - @type ripResult: L{RipResult} - - @rtype: str + :param epoch: when the log file gets generated + (Default value = time.time()) + :type epoch: float + :param ripResult: + :type ripResult: """ raise NotImplementedError @@ -146,11 +147,7 @@ def load(self): def getLoggers(): - """ - Get all logger plugins with entry point 'whipper.logger'. - - @rtype: dict of C{str} -> C{Logger} - """ + """Get all logger plugins with entry point ``whipper.logger``.""" d = {} pluggables = list(pkg_resources.iter_entry_points("whipper.logger")) diff --git a/whipper/test/common.py b/whipper/test/common.py index 1c3ef200..fa56eb49 100644 --- a/whipper/test/common.py +++ b/whipper/test/common.py @@ -49,9 +49,9 @@ class TestCase(unittest.TestCase): def failUnlessRaises(self, exception, f, *args, **kwargs): try: result = f(*args, **kwargs) - except exception, inst: + except exception as inst: return inst - except exception, e: + except exception as e: raise Exception('%s raised instead of %s:\n %s' % (sys.exec_info()[0], exception.__name__, str(e)) ) @@ -63,9 +63,14 @@ def failUnlessRaises(self, exception, f, *args, **kwargs): assertRaises = failUnlessRaises def readCue(self, name): - """ - Read a .cue file, and replace the version comment with the current - version so we can use it in comparisons. + """Read a cue file and replace its version number with the current one. + + The version number is replaced to use the cue file in comparisons. + + :param name: cuesheet filename (without path). + :type name: str + :returns: the cuesheet with version number replaced. + :rtype: str """ cuefile = os.path.join(os.path.dirname(__file__), name) ret = open(cuefile).read().decode('utf-8') diff --git a/whipper/test/test_common_accurip.py b/whipper/test/test_common_accurip.py index 316ab93d..cbcd97c2 100644 --- a/whipper/test/test_common_accurip.py +++ b/whipper/test/test_common_accurip.py @@ -110,7 +110,7 @@ def setUpClass(cls): def setUp(self): self.result = RipResult() - for n in range(1, 2+1): + for n in range(1, 2 + 1): track = TrackResult() track.number = n self.result.tracks.append(track) diff --git a/whipper/test/test_common_mbngs.py b/whipper/test/test_common_mbngs.py index a3b2f2a6..ae30cabf 100644 --- a/whipper/test/test_common_mbngs.py +++ b/whipper/test/test_common_mbngs.py @@ -116,11 +116,9 @@ def testMalaInCuba(self): ) def testNorthernGateway(self): - """ - check the received metadata for artists tagged with [unknown] - and artists tagged with an alias in MusicBrainz + """Check MBz metadata for artists tagged with: [unknown] / an alias. - see https://github.com/JoeLametta/whipper/issues/155 + .. seealso:: https://github.com/JoeLametta/whipper/issues/156 """ filename = 'whipper.release.38b05c7d-65fe-4dc0-9c10-33a391b86703.json' path = os.path.join(os.path.dirname(__file__), filename) @@ -157,9 +155,12 @@ def testNorthernGateway(self): ) def testNenaAndKimWildSingle(self): - """ - check the received metadata for artists that differ between - named on release and named in recording + """Check MBz metadata for artists with different names. + + An artist can have different names on MusicBrainz like: + *artist in MusicBrainz*, *artist as credited*. + + .. seealso:: https://github.com/JoeLametta/whipper/issues/156 """ filename = 'whipper.release.f484a9fc-db21-4106-9408-bcd105c90047.json' path = os.path.join(os.path.dirname(__file__), filename)