/Util/IronPython/Lib/iptest/file_util.py

https://github.com/kumaryu/IronLanguages-main · Python · 203 lines · 158 code · 26 blank · 19 comment · 40 complexity · 1914a323d589988eb7316ec5f6a09316 MD5 · raw file

  1. #####################################################################################
  2. #
  3. # Copyright (c) Microsoft Corporation. All rights reserved.
  4. #
  5. # This source code is subject to terms and conditions of the Microsoft Public License. A
  6. # copy of the license can be found in the License.html file at the root of this distribution. If
  7. # you cannot locate the Microsoft Public License, please send an email to
  8. # ironpy@microsoft.com. By using this source code in any fashion, you are agreeing to be bound
  9. # by the terms of the Microsoft Public License.
  10. #
  11. # You must not remove this notice, or any other, from this software.
  12. #
  13. #
  14. #####################################################################################
  15. ## BE PLATFORM NETURAL
  16. import nt
  17. import sys
  18. colon = ':'
  19. separator = '\\'
  20. def create_new_file(filename):
  21. f = file(filename, "w")
  22. f.close()
  23. def append_string_to_file(filename, *lines):
  24. f = file(filename, "a")
  25. for x in lines:
  26. f.writelines(x + "\n")
  27. f.close()
  28. def directory_exists(path):
  29. if sys.platform=="win32":
  30. return nt.access(path, nt.F_OK)
  31. else:
  32. try:
  33. nt.stat(path)
  34. return True
  35. except:
  36. return False
  37. def file_exists(file):
  38. if sys.platform=="win32":
  39. return nt.access(file, nt.F_OK)
  40. else:
  41. try:
  42. nt.stat(file)
  43. return True
  44. except:
  45. return False
  46. def file_exists_in_path(file):
  47. full_path = [nt.environ[x] for x in nt.environ.keys() if x.lower() == "path"]
  48. if len(full_path)==0:
  49. return False
  50. else:
  51. full_path = full_path[0]
  52. for path in [nt.getcwd()] + full_path.split(";"):
  53. path = path.lstrip().rstrip()
  54. if file_exists(path + "\\" + file) == True:
  55. return True
  56. return False
  57. # need consider .. and . later
  58. def fullpath(path):
  59. if colon not in path:
  60. return nt.getcwd() + separator + path
  61. elif sys.platform!="win32":
  62. from System.IO.Path import GetFullPath
  63. return GetFullPath(path)
  64. else:
  65. return path
  66. def path_combine(*paths):
  67. l = len(paths)
  68. p = ''
  69. for x in paths[:-1]:
  70. if len(x)==0 or x[-1] == separator:
  71. p += x
  72. else:
  73. p += x + separator
  74. return p + paths[-1]
  75. def get_full_dir_name(path):
  76. """removes ~# from short file names"""
  77. if sys.platform == "win32": return path
  78. import System
  79. return System.IO.DirectoryInfo(path).FullName
  80. def ensure_directory_present(path):
  81. path = fullpath(path)
  82. p = ''
  83. for x in path.split(separator):
  84. p += x + separator
  85. if not directory_exists(p):
  86. nt.mkdir(p)
  87. def write_to_file(filename, content=''):
  88. filename = fullpath(filename)
  89. pos = filename.rfind(separator)
  90. try:
  91. ensure_directory_present(filename[:pos])
  92. f = file(filename, 'w')
  93. f.write(content)
  94. f.close()
  95. except:
  96. raise AssertionError, 'unable to write to file'
  97. def delete_files(*files):
  98. for f in files:
  99. try: nt.remove(f)
  100. except: pass
  101. def get_parent_directory(path, levels=1):
  102. while levels:
  103. pos = path[:-1].rfind(separator)
  104. if pos < 0:
  105. return ""
  106. path = path[:pos]
  107. levels -= 1
  108. return path
  109. def samefile(file1, file2):
  110. return fullpath(file1).lower() == fullpath(file2).lower()
  111. def filecopy(oldpath, newpath):
  112. if samefile(oldpath, newpath):
  113. raise AssertionError, "%s and %s are same" % (oldpath, newpath)
  114. of, nf = None, None
  115. try:
  116. of = file(oldpath, 'rb')
  117. nf = file(newpath, 'wb')
  118. while True:
  119. b = of.read(1024 * 16)
  120. if not b:
  121. break
  122. nf.write(b)
  123. finally:
  124. if of: of.close()
  125. if nf: nf.close()
  126. def clean_directory(path):
  127. for f in nt.listdir(path):
  128. try:
  129. nt.unlink(path_combine(path, f))
  130. except:
  131. pass
  132. def get_directory_name(file):
  133. file = fullpath(file)
  134. pos = file.rfind(separator)
  135. return file[:pos]
  136. def find_peverify():
  137. if sys.platform <> 'cli': return None
  138. import System
  139. for d in System.Environment.GetEnvironmentVariable("PATH").split(';'):
  140. file = path_combine(d, "peverify.exe")
  141. if file_exists(file):
  142. return file
  143. print """
  144. #################################################
  145. # peverify.exe not found. Test will fail. #
  146. #################################################
  147. """
  148. return None
  149. def get_mod_names(filename):
  150. '''
  151. Returns a list of all Python modules and subpackages in the same location
  152. as filename w/o their ".py" extension.
  153. '''
  154. directory = filename
  155. if file_exists(filename):
  156. directory = get_directory_name(filename)
  157. else:
  158. raise Exception("%s does not exist!" % (str(filename)))
  159. #Only look at files with the .py extension and directories.
  160. ret_val = [x.rsplit(".py")[0] for x in nt.listdir(directory) if (x.endswith(".py") or "." not in x) \
  161. and x.lower()!="__init__.py"]
  162. return ret_val
  163. def delete_all_f(module_name):
  164. module = sys.modules[module_name]
  165. for x in dir(module):
  166. if x.startswith('_f_'):
  167. fn = getattr(module, x)
  168. if isinstance(fn, str):
  169. try: nt.unlink(fn)
  170. except: pass