Debian Codegraph @

src/objective-c/change-comments.py

raw
1 #!/usr/bin/env python2.7
2 # Copyright 2015 gRPC authors.
3 #
4 # Licensed under the Apache License, Version 2.0 (the "License");
5 # you may not use this file except in compliance with the License.
6 # You may obtain a copy of the License at
7 #
8 # http://www.apache.org/licenses/LICENSE-2.0
9 #
10 # Unless required by applicable law or agreed to in writing, software
11 # distributed under the License is distributed on an "AS IS" BASIS,
12 # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13 # See the License for the specific language governing permissions and
14 # limitations under the License.
15 """Change comments style of source files from // to /** */"""
16
17 import re
18 import sys
19
20 if len(sys.argv) < 2:
21 print("Please provide at least one source file name as argument.")
22 sys.exit()
23
24 for file_name in sys.argv[1:]:
25
26 print("Modifying format of {file} comments in place...".format(
27 file=file_name,))
28
29 # Input
30
31 with open(file_name, "r") as input_file:
32 lines = input_file.readlines()
33
34 def peek():
35 return lines[0]
36
37 def read_line():
38 return lines.pop(0)
39
40 def more_input_available():
41 return lines
42
43 # Output
44
45 output_lines = []
46
47 def write(line):
48 output_lines.append(line)
49
50 def flush_output():
51 with open(file_name, "w") as output_file:
52 for line in output_lines:
53 output_file.write(line)
54
55 # Pattern matching
56
57 comment_regex = r'^(\s*)//\s(.*)$'
58
59 def is_comment(line):
60 return re.search(comment_regex, line)
61
62 def isnt_comment(line):
63 return not is_comment(line)
64
65 def next_line(predicate):
66 return more_input_available() and predicate(peek())
67
68 # Transformation
69
70 def indentation_of(line):
71 match = re.search(comment_regex, line)
72 return match.group(1)
73
74 def content(line):
75 match = re.search(comment_regex, line)
76 return match.group(2)
77
78 def format_as_block(comment_block):
79 if len(comment_block) == 0:
80 return []
81
82 indent = indentation_of(comment_block[0])
83
84 if len(comment_block) == 1:
85 return [indent + "/** " + content(comment_block[0]) + " */\n"]
86
87 block = ["/**"] + [" * " + content(line) for line in comment_block
88 ] + [" */"]
89 return [indent + line.rstrip() + "\n" for line in block]
90
91 # Main algorithm
92
93 while more_input_available():
94 while next_line(isnt_comment):
95 write(read_line())
96
97 comment_block = []
98 # Get all lines in the same comment block. We could restrict the indentation
99 # to be the same as the first line of the block, but it's probably ok.
100 while (next_line(is_comment)):
101 comment_block.append(read_line())
102
103 for line in format_as_block(comment_block):
104 write(line)
105
106 flush_output()