PageRenderTime 47ms CodeModel.GetById 20ms RepoModel.GetById 0ms app.codeStats 0ms

/env/Lib/site-packages/wx-2.8-msw-unicode/wx/tools/Editra/src/ebmlib/fileutil.py

https://bitbucket.org/beqa/nvdadependencyvirtualenvironment
Python | 297 lines | 254 code | 9 blank | 34 comment | 9 complexity | f18b096cc69b30cb782453084db9ebd8 MD5 | raw file
  1. ###############################################################################
  2. # Name: fileutil.py #
  3. # Purpose: File Management Utilities. #
  4. # Author: Cody Precord <cprecord@editra.org> #
  5. # Copyright: (c) 2009 Cody Precord <staff@editra.org> #
  6. # Licence: wxWindows Licence #
  7. ###############################################################################
  8. """
  9. Editra Business Model Library: File Utilities
  10. Utility functions for managing and working with files.
  11. """
  12. __author__ = "Cody Precord <cprecord@editra.org>"
  13. __svnid__ = "$Id: fileutil.py 67396 2011-04-05 20:01:01Z CJP $"
  14. __revision__ = "$Revision: 67396 $"
  15. __all__ = [ 'GetAbsPath', 'GetFileExtension', 'GetFileModTime', 'GetFileName',
  16. 'GetFileSize', 'GetPathName', 'GetPathFromURI', 'GetUniqueName',
  17. 'IsLink', 'MakeNewFile', 'MakeNewFolder', 'PathExists',
  18. 'ResolveRealPath', 'IsExecutable', 'Which', 'ComparePaths']
  19. #-----------------------------------------------------------------------------#
  20. # Imports
  21. import os
  22. import platform
  23. import urllib2
  24. import stat
  25. UNIX = WIN = False
  26. if platform.system().lower() in ['windows', 'microsoft']:
  27. WIN = True
  28. try:
  29. # Check for if win32 extensions are available
  30. import win32com.client as win32client
  31. except ImportError:
  32. win32client = None
  33. try:
  34. # Check for win32api
  35. import win32api
  36. except ImportError:
  37. win32api = None
  38. else:
  39. UNIX = True
  40. #-----------------------------------------------------------------------------#
  41. def uri2path(func):
  42. """Decorator method to convert path arguments that may be uri's to
  43. real file system paths. Arg 0 must be a file path or uri.
  44. """
  45. def WrapURI(*args, **kwargs):
  46. args = list(args)
  47. args[0] = GetPathFromURI(args[0])
  48. return func(*args, **kwargs)
  49. WrapURI.__name__ = func.__name__
  50. WrapURI.__doc__ = func.__doc__
  51. return WrapURI
  52. #-----------------------------------------------------------------------------#
  53. def ComparePaths(path1, path2):
  54. """Determine whether the two given paths are equivalent
  55. @param path1: unicode
  56. @param path2: unicode
  57. @return: bool
  58. """
  59. path1 = GetAbsPath(path1)
  60. path2 = GetAbsPath(path2)
  61. if WIN:
  62. path1 = path1.lower()
  63. path2 = path2.lower()
  64. return path1 == path2
  65. @uri2path
  66. def GetAbsPath(path):
  67. """Get the absolute path of a file of a file.
  68. @param path: string
  69. @return: string
  70. @note: on windows if win32api is available short notation paths will be
  71. converted to the proper long name.
  72. """
  73. rpath = os.path.abspath(path)
  74. # Resolve short path notation on Windows when possible
  75. if WIN and win32api is not None and u"~" in rpath:
  76. try:
  77. rpath = win32api.GetLongPathNameW(rpath)
  78. except Exception:
  79. # Ignore errors from win32api calls
  80. pass
  81. return rpath
  82. def GetFileExtension(file_str):
  83. """Gets last atom at end of string as extension if
  84. no extension whole string is returned
  85. @param file_str: path or file name to get extension from
  86. """
  87. return file_str.split('.')[-1]
  88. def GetFileModTime(file_name):
  89. """Returns the time that the given file was last modified on
  90. @param file_name: path of file to get mtime of
  91. """
  92. try:
  93. mod_time = os.path.getmtime(file_name)
  94. except (OSError, EnvironmentError):
  95. mod_time = 0
  96. return mod_time
  97. def GetFileName(path):
  98. """Gets last atom on end of string as filename
  99. @param path: full path to get filename from
  100. """
  101. return os.path.split(path)[-1]
  102. @uri2path
  103. def GetFileSize(path):
  104. """Get the size of the file at a given path
  105. @param path: Path to file
  106. @return: long
  107. """
  108. try:
  109. return os.stat(path)[stat.ST_SIZE]
  110. except:
  111. return 0
  112. def GetPathFromURI(path):
  113. """Get a local path from a file:// uri
  114. @return: normalized path
  115. """
  116. if path.startswith(u"file:"):
  117. path = path.replace(u"file:", u"")
  118. path = path.lstrip(u"/")
  119. if platform.system().lower() in ('windows', 'microsoft'):
  120. path = path.replace(u"/", u"\\")
  121. if len(path) >= 2 and path[1] != u':':
  122. # A valid windows file uri should start with the drive
  123. # letter. If not make the assumption that it should be
  124. # the C: drive.
  125. path = u"C:\\\\" + path
  126. else:
  127. path = u"/" + path
  128. path = urllib2.unquote(path)
  129. return path
  130. @uri2path
  131. def GetPathName(path):
  132. """Gets the path minus filename
  133. @param path: full path to get base of
  134. """
  135. return os.path.split(path)[0]
  136. @uri2path
  137. def IsLink(path):
  138. """Is the file a link
  139. @return: bool
  140. """
  141. if WIN:
  142. return path.endswith(".lnk") or os.path.islink(path)
  143. else:
  144. return os.path.islink(path)
  145. @uri2path
  146. def PathExists(path):
  147. """Does the path exist.
  148. @param path: file path or uri
  149. @return: bool
  150. """
  151. return os.path.exists(path)
  152. @uri2path
  153. def IsExecutable(path):
  154. """Is the file at the given path an executable file
  155. @param path: file path
  156. @return: bool
  157. """
  158. return os.path.isfile(path) and os.access(path, os.X_OK)
  159. @uri2path
  160. def ResolveRealPath(link):
  161. """Return the real path of the link file
  162. @param link: path of link file
  163. @return: string
  164. """
  165. assert IsLink(link), "ResolveRealPath expects a link file!"
  166. realpath = link
  167. if WIN and win32client is not None:
  168. shell = win32client.Dispatch("WScript.Shell")
  169. shortcut = shell.CreateShortCut(link)
  170. realpath = shortcut.Targetpath
  171. else:
  172. realpath = os.path.realpath(link)
  173. return realpath
  174. def Which(program):
  175. """Find the path of the given executable
  176. @param program: executable name (i.e 'python')
  177. @return: executable path or None
  178. """
  179. # Check local directory first
  180. if IsExecutable(program):
  181. return program
  182. else:
  183. # Start looking on the $PATH
  184. for path in os.environ["PATH"].split(os.pathsep):
  185. exe_file = os.path.join(path, program)
  186. if IsExecutable(exe_file):
  187. return exe_file
  188. return None
  189. #-----------------------------------------------------------------------------#
  190. def GetUniqueName(path, name):
  191. """Make a file name that will be unique in case a file of the
  192. same name already exists at that path.
  193. @param path: Root path to folder of files destination
  194. @param name: desired file name base
  195. @return: string
  196. """
  197. tmpname = os.path.join(path, name)
  198. if os.path.exists(tmpname):
  199. if '.' not in name:
  200. ext = ''
  201. fbase = name
  202. else:
  203. ext = '.' + name.split('.')[-1]
  204. fbase = name[:-1 * len(ext)]
  205. inc = len([x for x in os.listdir(path) if x.startswith(fbase)])
  206. tmpname = os.path.join(path, "%s-%d%s" % (fbase, inc, ext))
  207. while os.path.exists(tmpname):
  208. inc = inc + 1
  209. tmpname = os.path.join(path, "%s-%d%s" % (fbase, inc, ext))
  210. return tmpname
  211. #-----------------------------------------------------------------------------#
  212. def MakeNewFile(path, name):
  213. """Make a new file at the given path with the given name.
  214. If the file already exists, the given name will be changed to
  215. a unique name in the form of name + -NUMBER + .extension
  216. @param path: path to directory to create file in
  217. @param name: desired name of file
  218. @return: Tuple of (success?, Path of new file OR Error message)
  219. """
  220. if not os.path.isdir(path):
  221. path = os.path.dirname(path)
  222. fname = GetUniqueName(path, name)
  223. try:
  224. open(fname, 'w').close()
  225. except (IOError, OSError), msg:
  226. return (False, str(msg))
  227. return (True, fname)
  228. def MakeNewFolder(path, name):
  229. """Make a new folder at the given path with the given name.
  230. If the folder already exists, the given name will be changed to
  231. a unique name in the form of name + -NUMBER.
  232. @param path: path to create folder on
  233. @param name: desired name for folder
  234. @return: Tuple of (success?, new dirname OR Error message)
  235. """
  236. if not os.path.isdir(path):
  237. path = os.path.dirname(path)
  238. folder = GetUniqueName(path, name)
  239. try:
  240. os.mkdir(folder)
  241. except (OSError, IOError), msg:
  242. return (False, str(msg))
  243. return (True, folder)