1
- #!/usr/bin/env python
1
+ #!/usr/bin/env python3
2
2
# encoding: utf-8
3
-
3
+ """Format the ill-formatted code."""
4
4
## ==============================================
5
5
## GOAL : Format code, Update headers
6
6
## ==============================================
12
12
import sys
13
13
import datetime
14
14
import subprocess
15
- import distutils .spawn
16
15
16
+ from functools import reduce
17
+
18
+ # Following is done so that we can import from ../helpers.py
19
+ sys .path .append (
20
+ os .path .abspath (os .path .dirname (__file__ )).replace ('/formatting' , '' )
21
+ )
22
+ from helpers import CLANG_FORMAT , PELOTON_DIR , CLANG_FORMAT_FILE , LOG ,\
23
+ clang_format
17
24
18
25
## ==============================================
19
26
## CONFIGURATION
22
29
# NOTE: absolute path to peloton directory is calculated from current directory
23
30
# directory structure: peloton/scripts/formatting/<this_file>
24
31
# PELOTON_DIR needs to be redefined if the directory structure is changed
25
- CODE_SOURCE_DIR = os .path .abspath (os .path .dirname (__file__ ))
26
- PELOTON_DIR = reduce (os .path .join , [CODE_SOURCE_DIR , os .path .pardir , os .path .pardir ])
27
32
28
33
#other directory paths used are relative to peloton_dir
29
34
PELOTON_SRC_DIR = os .path .join (PELOTON_DIR , "src" )
34
39
DEFAULT_DIRS .append (PELOTON_SRC_DIR )
35
40
DEFAULT_DIRS .append (PELOTON_TESTS_DIR )
36
41
37
- CLANG_FORMAT = None
38
- CLANG_FORMAT_FILE = os .path .join (PELOTON_DIR , ".clang-format" )
39
-
40
42
## ==============================================
41
43
## HEADER CONFIGURATION
42
44
## ==============================================
43
45
44
46
#header framework, dynamic information will be added inside function
45
- header_comment_line_1 = "//===----------------------------------------------------------------------===//\n "
47
+ header_comment_line_1 = "//===----------------------------------------------------------------------===//\n "
46
48
header_comment_line_1 += "//\n "
47
49
header_comment_line_1 += "// Peloton\n "
48
50
header_comment_line_2 = "//\n "
56
58
57
59
header_comment_1 = header_comment_line_1 + header_comment_line_2
58
60
header_comment_3 = header_comment_line_4
59
- header_comment_5 = header_comment_line_6 + header_comment_line_7 + header_comment_line_8 \
60
- + header_comment_line_9
61
+ header_comment_5 = header_comment_line_6 + header_comment_line_7 \
62
+ + header_comment_line_8 + header_comment_line_9
61
63
62
64
#regular expresseion used to track header
63
- header_regex = re .compile ("((\/\/===-*===\/\/\n (\/\/.*\n )*\/\/===-*===\/\/[\n ]*)\n \n )*" )
64
-
65
- ## ==============================================
66
- ## LOGGING CONFIGURATION
67
- ## ==============================================
68
-
69
- LOG = logging .getLogger (__name__ )
70
- LOG_handler = logging .StreamHandler ()
71
- LOG_formatter = logging .Formatter (
72
- fmt = '%(asctime)s [%(funcName)s:%(lineno)03d] %(levelname)-5s: %(message)s' ,
73
- datefmt = '%m-%d-%Y %H:%M:%S'
74
- )
75
- LOG_handler .setFormatter (LOG_formatter )
76
- LOG .addHandler (LOG_handler )
77
- LOG .setLevel (logging .INFO )
65
+ HEADER_REGEX = re .compile (r"((\/\/===-*===\/\/\n(\/\/.*\n)*\/\/===-*===\/\/[\n]*)\n\n)*" )
78
66
79
67
## ==============================================
80
68
## UTILITY FUNCTION DEFINITIONS
81
69
## ==============================================
82
70
83
- #format the file passed as argument
84
- def format_file (file_path , update_header , clang_format_code ):
85
71
72
+ def format_file (file_path , update_header , clang_format_code ):
73
+ """Formats the file passed as argument."""
86
74
file_name = os .path .basename (file_path )
87
75
abs_path = os .path .abspath (file_path )
88
- rel_path_from_peloton_dir = os .path .relpath (abs_path ,PELOTON_DIR )
76
+ rel_path_from_peloton_dir = os .path .relpath (abs_path , PELOTON_DIR )
89
77
90
- with open (file_path , "r+" ) as fd :
91
- file_data = fd .read ()
78
+ with open (file_path , "r+" ) as file :
79
+ file_data = file .read ()
92
80
93
81
if update_header :
94
82
# strip old header if it exists
95
- header_match = header_regex .match (file_data )
83
+ header_match = HEADER_REGEX .match (file_data )
96
84
if not header_match is None :
97
- LOG .info ("Strip header from %s" , file_name )
98
- header_comment = header_match .group ()
99
- LOG .debug ("Header comment : %s" , header_comment )
100
- file_data = file_data .replace (header_comment ,"" )
101
-
85
+ LOG .info ("Strip header from %s" , file_name )
86
+ header_comment = header_match .group ()
87
+ LOG .debug ("Header comment : %s" , header_comment )
88
+ file_data = file_data .replace (header_comment ,"" )
89
+
102
90
# add new header
103
91
LOG .info ("Add header to %s" , file_name )
104
92
header_comment_2 = header_comment_line_3 + file_name + "\n "
105
- header_comment_4 = header_comment_line_5 + rel_path_from_peloton_dir + "\n "
106
- header_comment = header_comment_1 + header_comment_2 + header_comment_3 \
107
- + header_comment_4 + header_comment_5
93
+ header_comment_4 = header_comment_line_5 \
94
+ + rel_path_from_peloton_dir + "\n "
95
+ header_comment = header_comment_1 + header_comment_2 \
96
+ + header_comment_3 + header_comment_4 \
97
+ + header_comment_5
108
98
#print header_comment
109
99
110
100
file_data = header_comment + file_data
111
101
112
- fd .seek (0 ,0 )
113
- fd .truncate ()
114
- fd .write (file_data )
102
+ file .seek (0 , 0 )
103
+ file .truncate ()
104
+ file .write (file_data )
115
105
116
106
elif clang_format_code :
117
- if CLANG_FORMAT is None :
118
- LOG .error ("clang-format seems not installed" )
119
- exit ("clang-format seems not installed" )
120
-
121
- formatting_command = CLANG_FORMAT + " -style=file -i " + file_path
122
- LOG .info (formatting_command )
123
- subprocess .call ([CLANG_FORMAT , "-style=file" , "-i" , file_path ])
107
+ clang_format (file_path )
124
108
125
109
#END WITH
126
-
127
- fd .close ()
128
110
#END FORMAT__FILE(FILE_NAME)
129
111
130
112
131
- #format all the files in the dir passed as argument
132
113
def format_dir (dir_path , update_header , clang_format_code ):
133
- for subdir , dirs , files in os .walk (dir_path ):
114
+ """Formats all the files in the dir passed as argument."""
115
+ for subdir , _ , files in os .walk (dir_path ): # _ is for directories.
134
116
for file in files :
135
117
#print os.path.join(subdir, file)
136
118
file_path = subdir + os .path .sep + file
@@ -142,53 +124,66 @@ def format_dir(dir_path, update_header, clang_format_code):
142
124
#END FOR [os.walk]
143
125
#END ADD_HEADERS_DIR(DIR_PATH)
144
126
145
- #find clang-format executable
146
- def find_clangformat ():
147
- global CLANG_FORMAT
148
- #check for possible clang-format versions
149
- for exe in ["clang-format" , "clang-format-3.6" , "clang-format-3.7" , "clang-format-3.8" ]:
150
- path = distutils .spawn .find_executable (exe )
151
- if not path is None :
152
- CLANG_FORMAT = path
153
- return
154
-
155
127
156
128
## ==============================================
157
129
## Main Function
158
130
## ==============================================
159
131
160
132
if __name__ == '__main__' :
161
133
162
- parser = argparse .ArgumentParser (description = 'Update headers and/or format source code' )
163
-
164
- parser .add_argument ("-u" , "--update-header" , help = 'Action: Update existing headers or add new ones' , action = 'store_true' )
165
- parser .add_argument ("-c" , "--clang-format-code" , help = 'Action: Apply clang-format to source code' , action = 'store_true' )
166
- parser .add_argument ("-f" , "--staged-files" , help = 'Action: Apply the selected action(s) to all staged files (git)' , action = 'store_true' )
167
- parser .add_argument ('paths' , metavar = 'PATH' , type = str , nargs = '*' ,
168
- help = 'Files or directories to (recursively) apply the actions to' )
169
-
170
- args = parser .parse_args ()
171
-
172
- find_clangformat ()
173
-
174
- if args .staged_files :
175
- targets = [os .path .abspath (os .path .join (PELOTON_DIR , f )) for f in subprocess .check_output (["git" , "diff" , "--name-only" , "HEAD" , "--cached" , "--diff-filter=d" ]).split ()]
176
- if not targets :
177
- LOG .error ("no staged files or not calling from a repository -- exiting" )
134
+ PARSER = argparse .ArgumentParser (
135
+ description = 'Update headers and/or format source code'
136
+ )
137
+
138
+ PARSER .add_argument (
139
+ "-u" , "--update-header" ,
140
+ help = 'Action: Update existing headers or add new ones' ,
141
+ action = 'store_true'
142
+ )
143
+ PARSER .add_argument (
144
+ "-c" , "--clang-format-code" ,
145
+ help = 'Action: Apply clang-format to source code' ,
146
+ action = 'store_true'
147
+ )
148
+ PARSER .add_argument (
149
+ "-f" , "--staged-files" ,
150
+ help = 'Action: Apply the selected action(s) to all staged files (git)' ,
151
+ action = 'store_true'
152
+ )
153
+ PARSER .add_argument (
154
+ 'paths' , metavar = 'PATH' , type = str , nargs = '*' ,
155
+ help = 'Files or directories to (recursively) apply the actions to'
156
+ )
157
+
158
+ ARGS = PARSER .parse_args ()
159
+
160
+ if ARGS .staged_files :
161
+ PELOTON_DIR_bytes = bytes (PELOTON_DIR , 'utf-8' )
162
+ TARGETS = [
163
+ str (os .path .abspath (os .path .join (PELOTON_DIR_bytes , f )), 'utf-8' ) \
164
+ for f in subprocess .check_output (
165
+ ["git" , "diff" , "--name-only" , "HEAD" , "--cached" ,
166
+ "--diff-filter=d"
167
+ ]
168
+ ).split ()]
169
+
170
+ if not TARGETS :
171
+ LOG .error (
172
+ "no staged files or not calling from a repository -- exiting"
173
+ )
178
174
sys .exit ("no staged files or not calling from a repository" )
179
- elif not args .paths :
175
+ elif not ARGS .paths :
180
176
LOG .error ("no files or directories given -- exiting" )
181
177
sys .exit ("no files or directories given" )
182
178
else :
183
- targets = args .paths
184
-
185
- for x in targets :
179
+ TARGETS = ARGS .paths
180
+
181
+ for x in TARGETS :
186
182
if os .path .isfile (x ):
187
- LOG .info ("Scanning file: " + x )
188
- format_file (x , args .update_header , args .clang_format_code )
183
+ LOG .info ("Scanning file: %s" , x )
184
+ format_file (x , ARGS .update_header , ARGS .clang_format_code )
189
185
elif os .path .isdir (x ):
190
- LOG .info ("Scanning directory " + x )
191
- format_dir (x , args .update_header , args .clang_format_code )
186
+ LOG .info ("Scanning directory %s" , x )
187
+ format_dir (x , ARGS .update_header , ARGS .clang_format_code )
192
188
## FOR
193
189
## IF
194
-
0 commit comments