fscommands.py 7.3 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267
  1. """Project file system commands.
  2. This modules implements file system operations used by rope. Different
  3. version control systems can be supported by implementing the interface
  4. provided by `FileSystemCommands` class. See `SubversionCommands` and
  5. `MercurialCommands` for example.
  6. """
  7. import os
  8. import shutil
  9. import subprocess
  10. def create_fscommands(root):
  11. dirlist = os.listdir(root)
  12. commands = {'.hg': MercurialCommands,
  13. '.svn': SubversionCommands,
  14. '.git': GITCommands,
  15. '_svn': SubversionCommands,
  16. '_darcs': DarcsCommands}
  17. for key in commands:
  18. if key in dirlist:
  19. try:
  20. return commands[key](root)
  21. except (ImportError, OSError):
  22. pass
  23. return FileSystemCommands()
  24. class FileSystemCommands(object):
  25. def create_file(self, path):
  26. open(path, 'w').close()
  27. def create_folder(self, path):
  28. os.mkdir(path)
  29. def move(self, path, new_location):
  30. shutil.move(path, new_location)
  31. def remove(self, path):
  32. if os.path.isfile(path):
  33. os.remove(path)
  34. else:
  35. shutil.rmtree(path)
  36. def write(self, path, data):
  37. file_ = open(path, 'wb')
  38. try:
  39. file_.write(data)
  40. finally:
  41. file_.close()
  42. class SubversionCommands(object):
  43. def __init__(self, *args):
  44. self.normal_actions = FileSystemCommands()
  45. import pysvn
  46. self.client = pysvn.Client()
  47. def create_file(self, path):
  48. self.normal_actions.create_file(path)
  49. self.client.add(path, force=True)
  50. def create_folder(self, path):
  51. self.normal_actions.create_folder(path)
  52. self.client.add(path, force=True)
  53. def move(self, path, new_location):
  54. self.client.move(path, new_location, force=True)
  55. def remove(self, path):
  56. self.client.remove(path, force=True)
  57. def write(self, path, data):
  58. self.normal_actions.write(path, data)
  59. class MercurialCommands(object):
  60. def __init__(self, root):
  61. self.hg = self._import_mercurial()
  62. self.normal_actions = FileSystemCommands()
  63. try:
  64. self.ui = self.hg.ui.ui(
  65. verbose=False, debug=False, quiet=True,
  66. interactive=False, traceback=False, report_untrusted=False)
  67. except:
  68. self.ui = self.hg.ui.ui()
  69. self.ui.setconfig('ui', 'interactive', 'no')
  70. self.ui.setconfig('ui', 'debug', 'no')
  71. self.ui.setconfig('ui', 'traceback', 'no')
  72. self.ui.setconfig('ui', 'verbose', 'no')
  73. self.ui.setconfig('ui', 'report_untrusted', 'no')
  74. self.ui.setconfig('ui', 'quiet', 'yes')
  75. self.repo = self.hg.hg.repository(self.ui, root)
  76. def _import_mercurial(self):
  77. import mercurial.commands
  78. import mercurial.hg
  79. import mercurial.ui
  80. return mercurial
  81. def create_file(self, path):
  82. self.normal_actions.create_file(path)
  83. self.hg.commands.add(self.ui, self.repo, path)
  84. def create_folder(self, path):
  85. self.normal_actions.create_folder(path)
  86. def move(self, path, new_location):
  87. self.hg.commands.rename(self.ui, self.repo, path,
  88. new_location, after=False)
  89. def remove(self, path):
  90. self.hg.commands.remove(self.ui, self.repo, path)
  91. def write(self, path, data):
  92. self.normal_actions.write(path, data)
  93. class GITCommands(object):
  94. def __init__(self, root):
  95. self.root = root
  96. self._do(['version'])
  97. self.normal_actions = FileSystemCommands()
  98. def create_file(self, path):
  99. self.normal_actions.create_file(path)
  100. self._do(['add', self._in_dir(path)])
  101. def create_folder(self, path):
  102. self.normal_actions.create_folder(path)
  103. def move(self, path, new_location):
  104. self._do(['mv', self._in_dir(path), self._in_dir(new_location)])
  105. def remove(self, path):
  106. self._do(['rm', self._in_dir(path)])
  107. def write(self, path, data):
  108. # XXX: should we use ``git add``?
  109. self.normal_actions.write(path, data)
  110. def _do(self, args):
  111. _execute(['git'] + args, cwd=self.root)
  112. def _in_dir(self, path):
  113. if path.startswith(self.root):
  114. return path[len(self.root) + 1:]
  115. return self.root
  116. class DarcsCommands(object):
  117. def __init__(self, root):
  118. self.root = root
  119. self.normal_actions = FileSystemCommands()
  120. def create_file(self, path):
  121. self.normal_actions.create_file(path)
  122. self._do(['add', path])
  123. def create_folder(self, path):
  124. self.normal_actions.create_folder(path)
  125. self._do(['add', path])
  126. def move(self, path, new_location):
  127. self._do(['mv', path, new_location])
  128. def remove(self, path):
  129. self.normal_actions.remove(path)
  130. def write(self, path, data):
  131. self.normal_actions.write(path, data)
  132. def _do(self, args):
  133. _execute(['darcs'] + args, cwd=self.root)
  134. def _execute(args, cwd=None):
  135. process = subprocess.Popen(args, cwd=cwd, stdout=subprocess.PIPE)
  136. process.wait()
  137. return process.returncode
  138. def unicode_to_file_data(contents, encoding=None):
  139. if not isinstance(contents, unicode):
  140. return contents
  141. if encoding is None:
  142. encoding = read_str_coding(contents)
  143. if encoding is not None:
  144. return contents.encode(encoding)
  145. try:
  146. return contents.encode()
  147. except UnicodeEncodeError:
  148. return contents.encode('utf-8')
  149. def file_data_to_unicode(data, encoding=None):
  150. result = _decode_data(data, encoding)
  151. if '\r' in result:
  152. result = result.replace('\r\n', '\n').replace('\r', '\n')
  153. return result
  154. def _decode_data(data, encoding):
  155. if isinstance(data, unicode):
  156. return data
  157. if encoding is None:
  158. encoding = read_str_coding(data)
  159. if encoding is None:
  160. # there is no encoding tip, we need to guess.
  161. # PEP263 says that "encoding not explicitly defined" means it is ascii,
  162. # but we will use utf8 instead since utf8 fully covers ascii and btw is
  163. # the only non-latin sane encoding.
  164. encoding = 'utf-8'
  165. try:
  166. return data.decode(encoding)
  167. except (UnicodeError, LookupError):
  168. # fallback to latin1: it should never fail
  169. return data.decode('latin1')
  170. def read_file_coding(path):
  171. file = open(path, 'b')
  172. count = 0
  173. result = []
  174. buffsize = 10
  175. while True:
  176. current = file.read(10)
  177. if not current:
  178. break
  179. count += current.count('\n')
  180. result.append(current)
  181. file.close()
  182. return _find_coding(''.join(result))
  183. def read_str_coding(source):
  184. try:
  185. first = source.index('\n') + 1
  186. second = source.index('\n', first) + 1
  187. except ValueError:
  188. second = len(source)
  189. return _find_coding(source[:second])
  190. def _find_coding(text):
  191. coding = 'coding'
  192. try:
  193. start = text.index(coding) + len(coding)
  194. if text[start] not in '=:':
  195. return
  196. start += 1
  197. while start < len(text) and text[start].isspace():
  198. start += 1
  199. end = start
  200. while end < len(text):
  201. c = text[end]
  202. if not c.isalnum() and c not in '-_':
  203. break
  204. end += 1
  205. return text[start:end]
  206. except ValueError:
  207. pass