Advertisement
Guest User

Untitled

a guest
Jul 25th, 2016
56
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 3.60 KB | None | 0 0
  1. # coding: utf-8
  2.  
  3. import re as _re
  4. import sys as _sys
  5. import os
  6.  
  7.  
  8.  
  9. class WinSafeFileCreateError(Exception):
  10. pass
  11.  
  12.  
  13. class WinSafeFileCreate(object):
  14. """
  15. Creates and returns the absolute path of the file given a relative or
  16. absolute path for windows systems.
  17. If any error occurs during path-processing, raises `WinSafeFileCreateError`
  18. """
  19. def __init__(self,_path):
  20. self.started_at = os.path.abspath(os.getcwd())
  21. dr,fo,fi = WinSafeFileCreate.get_all_paths(_path)
  22. dr,fo,fi = WinSafeFileCreate.validate_paths(dr,fo,fi)
  23. #if dr:
  24. # self.final_path = dr+":\\"
  25. #else:
  26. # self.final_path = ''
  27. #for i in fo:
  28. # self.final_path+=(i+"\\")
  29. #self.final_path+=fi
  30. #print "FP:>",self.final_path
  31. self.final_file_abspath = WinSafeFileCreate.process_paths(dr,fo,fi, self.started_at)
  32.  
  33. def __str__(self):
  34. return self.final_file_abspath
  35.  
  36. @staticmethod
  37. def get_all_paths(p):
  38. dr = None
  39. fo = []
  40. fi = None
  41.  
  42. if len(p)>3:
  43. if p[1:3] in [':/',':\\'] and _re.match(r'^[a-zA-Z]$',p[0]): #starts with drive
  44. if os.path.exists(p[:2]): # if drive exists
  45. dr = p[0]
  46. for i in _re.split('[\\\/]+|\\+|\/+', p[2:]):
  47. fo.append(i)
  48. else: # if drive does not exist
  49. raise WinSafeFileCreateError('\"'+p[:2]+'\" does not exists on this system.')
  50. else:
  51. ps = _re.split('[\\\/]+|\\+|\/+', p)
  52. if len(ps)<=1:
  53. fi = p.split(':')[0]
  54. else:
  55. for i in ps:
  56. fo.append(i)
  57. else:
  58. fi = p.split(':')[0]
  59. if folders:
  60. fi = fo.pop() # last fo element will be considered as filename
  61. return (dr, fo, fi)
  62.  
  63. @staticmethod
  64. def validate_paths(dr,fo,fi):
  65. creatable = []
  66. for i in fo:
  67. if _re.match('^.*[\?\\\/\<\>\:\|\"\*]+.*$',i):
  68. raise WinSafeFileCreateError("Folder \""+i+"\" contains invalid character.")
  69. else:
  70. if not _re.match('^\.+$', i):
  71. creatable.append(i.lstrip('. ').rstrip('. '))
  72. else:
  73. creatable.append(i)
  74.  
  75. if _re.match('^.*[\?\\\/\<\>\:\|\"\*]+.*$',fi):
  76. raise WinSafeFileCreateError("Filename \""+fi+"\" contains invalid character.")
  77. else:
  78. fi = fi.lstrip('. ').rstrip('. ')
  79.  
  80. return (dr,creatable,fi)
  81.  
  82. @staticmethod
  83. def process_paths(dr,fo,fi,s):
  84. if dr: # if paths include directory
  85. os.chdir(dr+":")
  86. while len(os.getcwd())>3: # while not at the root folder of our drive
  87. os.chdir("..") # keep going back
  88. for i in fo:
  89. if i=='':
  90. continue
  91. elif i=='.':
  92. continue
  93. elif i=='..':
  94. os.chdir('..')
  95. elif _re.match(r'^\.{2,}$',i):
  96. continue
  97. else:
  98. try:
  99. os.chdir(i)
  100. except WindowsError as e:
  101. try:
  102. os.mkdir(i)
  103. except:
  104. os.chdir(s)
  105. raise WinSafeFileCreateError('Not enough permission to create folder: '+i)
  106. os.chdir(i)
  107. except:
  108. os.chdir(s)
  109. raise WinSafeFileCreateError('Unknown error occurred while processing paths.')
  110. try:
  111. open(fi,'w+').close()
  112. final_file_abspath = os.path.abspath(fi)
  113. os.chdir(s)
  114. return final_file_abspath
  115. except:
  116. os.chdir(s)
  117. raise WinSafeFileCreateError('Not enough permission to create file: '+fi)
  118.  
  119. win_test_paths = [
  120. './/.../fkdf/dkfd.jpg',
  121. 'CD:/fdkjiuero/elr/.jps',
  122. 'S:\\\\\\\\erker/dfl\\////k.ls',
  123. './........./.................../../\\\\\\\\\\\\\\\\\\\\\\\\\\\\pterte.jpg',
  124. '|:',
  125. 'C:/fuckyou'
  126. ]
  127. for i in win_test_paths:
  128. try:
  129. print WinSafeFileCreate(i)
  130. except WinSafeFileCreateError as e:
  131. print e
  132. continue
  133.  
  134. __all__ = ['WinSafeFileCreate']
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement