oliverthered

InkscapeExtensionUpgrade.py

Nov 11th, 2020
98
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Python 2.07 KB | None | 0 0
  1. import re
  2. import os
  3. import sys
  4. import shutil
  5. from tempfile import mkstemp
  6. import subprocess
  7.  
  8. # *************************************************************
  9. # The inkscape extension
  10. # *************************************************************
  11. class UpgradeExtension():
  12.     def __init__(self):
  13.         self.searchReplace = [
  14.         ["^([\\b]*)str[\\s]","type=\\1str"],
  15.         ["OptionParser.add_option","arg_parser.add_argument"],
  16.         ["action=\"store\"[\\b]*[,]?[\\s]*",""],
  17.         [",[\\b]*,",","],
  18.         ["type=\"inkbool\"","type=inkex.Boolean"],
  19.         ["^([\\b]*)print (.+)","\\1print\\(\\2\\)"],
  20.         ["type=\"(.*)\"","type=\\1"],
  21.         ["type=string","type=str"],
  22.         ["isinstance\\((.*)\\.tag, basestring\\)","isinstance\\(\\1\\.tag, str\\)"],
  23.         ["isinstance\\((.*)\\.tag, unicode\\)","isinstance\\(\\1\\.tag, str\\)"],
  24.         ["isinstance\\((.*)\\.tag, stdout\\)","isinstance\\(\\1\\.tag, sys.stdout.buffer\\)"]]
  25.  
  26.     #TODO: Get rid of dest and intead create a bakup and just replace the origional,
  27.     # or just replace the oriugional and assume that the user already has a source copy.
  28.     # probably a good idea to have a warn prompt first.
  29.     def upgrade(self, source):
  30.         """Upgrades a Inkscape 4.x extension to a 1.x one
  31.    
  32.        Args:
  33.            source  (str): input filename, source will be over written.        
  34.        """
  35.         subprocess.call(["2to3","-w","-f","all","-f","buffer","-f","idioms","-f","set_literal","-f","ws_comma", source])
  36.        
  37.         with open(source, 'r') as fin:
  38.        
  39.             fd, name = mkstemp()
  40.            
  41.             with open(name, 'w') as fout:
  42.            
  43.                 for line in fin:
  44.                     out = line
  45.                     for pattern, replace in self.searchReplace:
  46.                         out = re.sub(pattern, replace, out)
  47.                     fout.write(out)
  48.                     fout.writelines(fin.readlines())
  49.  
  50.             os.close(fd)
  51.        
  52.         shutil.move(name, source)
  53.  
  54.  
  55. upgrader = UpgradeExtension()
  56. if len(sys.argv) == 2:
  57.     upgrader.upgrade(sys.argv[1])
  58. quit()
Advertisement
Add Comment
Please, Sign In to add comment