line_endings.py 2.0 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576
  1. """ Functions for converting from DOS to UNIX line endings
  2. """
  3. from __future__ import division, absolute_import, print_function
  4. import sys, re, os
  5. def dos2unix(file):
  6. "Replace CRLF with LF in argument files. Print names of changed files."
  7. if os.path.isdir(file):
  8. print(file, "Directory!")
  9. return
  10. data = open(file, "rb").read()
  11. if '\0' in data:
  12. print(file, "Binary!")
  13. return
  14. newdata = re.sub("\r\n", "\n", data)
  15. if newdata != data:
  16. print('dos2unix:', file)
  17. f = open(file, "wb")
  18. f.write(newdata)
  19. f.close()
  20. return file
  21. else:
  22. print(file, 'ok')
  23. def dos2unix_one_dir(modified_files, dir_name, file_names):
  24. for file in file_names:
  25. full_path = os.path.join(dir_name, file)
  26. file = dos2unix(full_path)
  27. if file is not None:
  28. modified_files.append(file)
  29. def dos2unix_dir(dir_name):
  30. modified_files = []
  31. os.path.walk(dir_name, dos2unix_one_dir, modified_files)
  32. return modified_files
  33. #----------------------------------
  34. def unix2dos(file):
  35. "Replace LF with CRLF in argument files. Print names of changed files."
  36. if os.path.isdir(file):
  37. print(file, "Directory!")
  38. return
  39. data = open(file, "rb").read()
  40. if '\0' in data:
  41. print(file, "Binary!")
  42. return
  43. newdata = re.sub("\r\n", "\n", data)
  44. newdata = re.sub("\n", "\r\n", newdata)
  45. if newdata != data:
  46. print('unix2dos:', file)
  47. f = open(file, "wb")
  48. f.write(newdata)
  49. f.close()
  50. return file
  51. else:
  52. print(file, 'ok')
  53. def unix2dos_one_dir(modified_files, dir_name, file_names):
  54. for file in file_names:
  55. full_path = os.path.join(dir_name, file)
  56. unix2dos(full_path)
  57. if file is not None:
  58. modified_files.append(file)
  59. def unix2dos_dir(dir_name):
  60. modified_files = []
  61. os.path.walk(dir_name, unix2dos_one_dir, modified_files)
  62. return modified_files
  63. if __name__ == "__main__":
  64. dos2unix_dir(sys.argv[1])