diff --git a/mved b/mved index f05cd88..c9ea918 100755 --- a/mved +++ b/mved @@ -14,7 +14,7 @@ from time import sleep version = '1.2' -LICENSE="""\ +LICENSE = """\ Copyright 2003-2005 Stefan Sperling Copyright 2004 by Neels Janosch Hofmeyr @@ -36,7 +36,7 @@ OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. """ -DIRECTIONS="""\ +DIRECTIONS = """\ - Directions - * mved loads a list of filenames into your favourite text editor. You can then edit the filenames conveniently. @@ -54,12 +54,12 @@ mved is based on an idea by Neels Janosch Hofmeyr [http://binarchy.net/bergmann/] """ editor = getenv('EDITOR') -if not editor: +if not editor: editor = getenv('VISUAL') -if not editor: - editor = '/usr/bin/vi' # enter default editor here +if not editor: + editor = '/usr/bin/vi' # enter default editor here -USAGE="""\ +USAGE = """\ Usage: mved [options] [file1 file2 ...] Options: -h, --help Print detailed help and license. @@ -75,29 +75,32 @@ def giveup(message): stderr.write('ERROR: %s\n' % message) exit(1) + def warn(message): """ print a warning message to stderr. """ stderr.write('WARNING: %s\n' % message) -def usage(long = 0): + +def usage(long=0): """ print usage information. """ - print 'mved %s - an editor-focused multiple file move utility' % version - if long: - print LICENSE - print DIRECTIONS - print USAGE + print('mved %s - an editor-focused multiple file move utility' % version) + if long: + print(LICENSE) + print(DIRECTIONS) + print(USAGE) + def getoptions(): """ get options. returns a list of all non-option arguments. """ global editor, force try: - options, args = getopt(argv[1:], 'he:f', ['help', 'editor=','force']) - except GetoptError, e: + options, args = getopt(argv[1:], 'he:f', ['help', 'editor=', 'force']) + except GetoptError as e: giveup(str(e) + ", try 'mved --help' for more information.") - + for opt, arg in options: if opt in ('-h', '--help'): - usage(long = 1) + usage(long=1) exit(0) if opt in ('-e', '--editor'): editor = arg @@ -105,62 +108,61 @@ def getoptions(): force = 1 return args + def edit(oldnames): """ let user edit a list of filenames. returns a list containing the new filenames. """ - def discardempty(list): """ returns a clone of list with empty elements removed. """ out = [] for item in list: - if item: + if item: out.append(item) return out tmpfd, tmpfilename = mkstemp() try: for name in oldnames: - write(tmpfd, '%s\n' % name) + write(tmpfd, ('%s\n' % name).encode()) fsync(tmpfd) - except IOError, e: + except IOError as e: giveup("%s: %s", (tmpfilename, str(e))) - + # warn user if EDITOR is not an absolute path if editor != abspath(editor): warn("EDITOR (" + editor \ + ") is not an absolute path. This is a security risk.\n") ret = system('%s %s' % (editor, tmpfilename)) - if ret == 0: # editor exited gracefully + if ret == 0: # editor exited gracefully try: # on OSX, we need to reopen the file to pick up changes: close(tmpfd) with open(tmpfilename) as newfile: newnames = newfile.readlines() del newfile - #newnames = readlines(tmpfd) + #newnames = readlines(tmpfd) remove(tmpfilename) - except OSError, e: + except OSError as e: giveup("%s: %s", (tmpfilename, str(e))) - except IOError, e: + except IOError as e: giveup("%s: %s", (tmpfilename, str(e))) for i in range(len(newnames)): newnames[i] = newnames[i].strip('\n') - newnames = discardempty(newnames) # throw out empty lines - - if len(newnames) == len(oldnames): + newnames = discardempty(newnames) # throw out empty lines + + if len(newnames) == len(oldnames): return newnames else: giveup('Numbers of new and old filenames differ.') else: try: remove(tmpfilename) - except IOError, e: + except IOError as e: warn("Could not remove %s: %s", (tmpfilename, str(e))) giveup('Editor exited ungracefully.') - def readlines(fd): """ returns a list of all lines in file descriptor fd. """ out = [] @@ -173,13 +175,15 @@ def readlines(fd): break if ch != '\n': str += ch - elif str: + elif str: out.append(str) str = '' - return out + return out + class ExistenceChecker: "layer to decouple filename existence checking from the Renamer." + def exists(self, filename): return self.isfile(filename) or self.isdir(filename) @@ -188,16 +192,16 @@ class ExistenceChecker: def isdir(self, dirname): return isdir(dirname) - + class Renamer: "manages the connections between the RenamingNode items." null = -1 - + def __init__(self): self.list = [] self.existencechecker = ExistenceChecker() - + def size(self): return len(self.list) @@ -209,30 +213,30 @@ class Renamer: # print "creating %s " % fromfile self.list.append(RenamingNode(fromfile)) fromindex = self.findfileindex(fromfile) - - toindex=self.findfileindex(tofile) + + toindex = self.findfileindex(tofile) if toindex == Renamer.null: # print "creating %s" % tofile self.list.append(RenamingNode(tofile)) toindex = self.findfileindex(tofile) if self.list[fromindex].tofile != Renamer.null: - giveup("file name appears twice as source: %s" - % self.list[fromindex].filename) + giveup("file name appears twice as source: %s" % + self.list[fromindex].filename) if self.list[toindex].fromfile != Renamer.null: - giveup("file name appears twice as destination: %s" - % self.list[toindex].filename) - + giveup("file name appears twice as destination: %s" % + self.list[toindex].filename) + self.list[toindex].fromfile = self.list[fromindex] self.list[fromindex].tofile = self.list[toindex] - - def findfileindex(self,filename): + + def findfileindex(self, filename): for x in range(len(self.list)): if self.list[x].filename == filename: return x return Renamer.null - + def renamingsequence(self): self.sequence = [] while len(self.list) > 0: @@ -240,13 +244,13 @@ class Renamer: for i in self.list: i.seen = 0 - + for x in range(len(self.list)): if self.list[x].fromfile != Renamer.null: again = 1 self.execute(self.list[x]) break - + if again == 0: break return self.sequence @@ -259,7 +263,7 @@ class Renamer: self.setfromfile(tofile, Renamer.null) of.tofile = tofile tofile.fromfile = of - + def setfromfile(self, of, fromfile): if of.fromfile != Renamer.null: of.fromfile.tofile = Renamer.null @@ -268,13 +272,13 @@ class Renamer: self.settofile(fromfile, Renamer.null) of.fromfile = fromfile fromfile.tofile = of - + def remove(self, file): self.setfromfile(file, Renamer.null) self.settofile(file, Renamer.null) self.list.remove(file) - def execute(self,to): + def execute(self, to): # print "running execute('%s', '%s')" % (frm.filename, to.filename) if to == Renamer.null: @@ -298,21 +302,21 @@ class Renamer: self.list.append(tempNode) self.settofile(tempNode, wasto) - return # re-iterate + return # re-iterate # 'now' is now the last renaming in its chain (now.tofile == null) # run down the renamings starting with `now' while now.fromfile != Renamer.null: now = now.fromfile # print "moving %s ==> %s" (now.filename, now.tofile.filename) - self.sequence.append(SequenceNode(now.filename, - now.tofile.filename)) + self.sequence.append( + SequenceNode(now.filename, now.tofile.filename)) self.remove(now.tofile) - + def checkrenamings(self, force): errors = "" for i in self.list: - + if force == 0 and i.fromfile != Renamer.null \ and i.tofile == Renamer.null \ and self.existencechecker.exists(i.filename): @@ -322,74 +326,80 @@ class Renamer: if i.tofile != Renamer.null \ and (not self.existencechecker.exists(i.filename)): - + errors += "\n ** file does not exist: %s (%s -> %s)" \ % (i.filename, i.filename, i.tofile.filename) - if errors != "": - giveup("nothing renamed because of the following conflicts: " - + errors + "\n(check out option -f, --force)") + giveup("nothing renamed because of the following conflicts: " + + errors + "\n(check out option -f, --force)") class RenamingNode: "saves renamings for a certain filename in both directions." + def __init__(self, filename): self.fromfile = Renamer.null self.tofile = Renamer.null self.filename = filename self.seen = 0 + class SequenceNode: "a node of a list returned by Renamer.renamingsequence()" + def __init__(self, frm, to): self.frm = frm self.to = to + def symlinkvimbug(): tmpdir = getenv('TMPDIR') if not tmpdir: return if islink(tmpdir) and 'vim' in editor: - warn("TMPDIR (" + tmpdir + ") is a symlink, and your editor is vim.\n" -+ "mved may behave as if you hadn't changed a single filename.\n" -+ "The cause of this bug is unkown. A workaround is to either make sure\n" -+ "that TMPDIR is not a symlink, or using another editor, e.g. by aliasing\n" -+ "mved as 'mved -e '.\n") + warn( + "TMPDIR (" + tmpdir + ") is a symlink, and your editor is vim.\n" + + "mved may behave as if you hadn't changed a single filename.\n" + + "The cause of this bug is unkown. A workaround is to either make sure\n" + + + "that TMPDIR is not a symlink, or using another editor, e.g. by aliasing\n" + + "mved as 'mved -e '.\n") for i in range(9, 0, -1): stdout.write("Continuing in %i seconds\r" % i) stdout.flush() sleep(1) - + + if __name__ == '__main__': if len(argv[1:]) < 1: usage() exit(1) - oldnames = getoptions() # getoptions returns all non-option args + oldnames = getoptions() # getoptions returns all non-option args symlinkvimbug() - + force = 0 ignore = [] for i in range(len(oldnames)): if not (isfile(oldnames[i]) or isdir(oldnames[i])): - warn('Ignoring %s: No such file or directory.' % oldnames[i]) - ignore.append(i) + warn('Ignoring %s: No such file or directory.' % oldnames[i]) + ignore.append(i) for i in ignore: - del oldnames[i]; + del oldnames[i] if not oldnames: giveup('No files to rename.') newnames = edit(oldnames) - + dochange = 0 dontchange = 0 renamer = Renamer() exists = ExistenceChecker() renamer.existencechecker = exists - + for new, old in zip(newnames, oldnames): if old != new: renamer.add(old, new) @@ -397,39 +407,38 @@ if __name__ == '__main__': else: dontchange += 1 - if dochange == 1: + if dochange == 1: msg = '1 filename changes, ' - else: + else: msg = '%i filenames change, ' % dochange - if dontchange == 1: + if dontchange == 1: msg += '1 does not' - else: + else: msg += '%i do not' % dontchange - print msg - + print(msg) + renamer.checkrenamings(force) sequence = renamer.renamingsequence() for i in sequence: try: - print "moving %s -> %s " % (i.frm, i.to) + print("moving %s -> %s " % (i.frm, i.to)) if force == 0 and exists.exists(i.to): sched = "" for i in sequence: sched += "\n%s -> %s" % (i.frm, i.to) - print "error detected. moving schedule was: %s " % sched + print("error detected. moving schedule was: %s " % sched) giveup("will not overwrite %s\n** RENAMING INTERRUPTED **" \ % i.to) rename(i.frm, expanduser(i.to)) - except OSError, e: + except OSError as e: sched = "" for i in sequence: sched += "\n%s -> %s" % (i.frm, i.to) - print "error detected. moving schedule was: %s" % sched + print("error detected. moving schedule was: %s" % sched) giveup("Could not rename %s to %s: %s\n** RENAMING INTERRUPTED **" \ % (i.frm, i.to, str(e))) - - exit(0) + exit(0) # vim: expandtab shiftwidth=4