oliverthered

InkscapeExtensionUpgrade.py

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