oliverthered

InkscapeExtensionUpgrade.py

Nov 11th, 2020
106
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Python 1.93 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.         with open(source, 'r') as fin:
  36.        
  37.             fd, name = mkstemp()
  38.            
  39.             with open(name, 'w') as fout:
  40.            
  41.                 for line in fin:
  42.                     out = line
  43.                     for pattern, replace in self.searchReplace:
  44.                         out = re.sub(pattern, replace, out)
  45.                     fout.write(out)
  46.                     fout.writelines(fin.readlines())
  47.  
  48.             os.close(fd)
  49.        
  50.         shutil.move(name, source)
  51.  
  52.  
  53. upgrader = UpgradeExtension()
  54. if len(sys.argv) == 2:
  55.     upgrader.upgrade(sys.argv[1])
  56. quit()
Advertisement
Add Comment
Please, Sign In to add comment