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