• Home
  • Line#
  • Scopes#
  • Navigate#
  • Raw
  • Download
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
16"""Change comments style of source files from // to /** */"""
17
18import re
19import sys
20
21
22if len(sys.argv) < 2:
23  print("Please provide at least one source file name as argument.")
24  sys.exit()
25
26for file_name in sys.argv[1:]:
27
28  print("Modifying format of {file} comments in place...".format(
29      file=file_name,
30  ))
31
32
33  # Input
34
35  with open(file_name, "r") as input_file:
36    lines = input_file.readlines()
37
38  def peek():
39    return lines[0]
40
41  def read_line():
42    return lines.pop(0)
43
44  def more_input_available():
45    return lines
46
47
48  # Output
49
50  output_lines = []
51
52  def write(line):
53    output_lines.append(line)
54
55  def flush_output():
56    with open(file_name, "w") as output_file:
57      for line in output_lines:
58        output_file.write(line)
59
60
61  # Pattern matching
62
63  comment_regex = r'^(\s*)//\s(.*)$'
64
65  def is_comment(line):
66    return re.search(comment_regex, line)
67
68  def isnt_comment(line):
69    return not is_comment(line)
70
71  def next_line(predicate):
72    return more_input_available() and predicate(peek())
73
74
75  # Transformation
76
77  def indentation_of(line):
78    match = re.search(comment_regex, line)
79    return match.group(1)
80
81  def content(line):
82    match = re.search(comment_regex, line)
83    return match.group(2)
84
85  def format_as_block(comment_block):
86    if len(comment_block) == 0:
87      return []
88
89    indent = indentation_of(comment_block[0])
90
91    if len(comment_block) == 1:
92      return [indent + "/** " + content(comment_block[0]) + " */\n"]
93
94    block = ["/**"] + [" * " + content(line) for line in comment_block] + [" */"]
95    return [indent + line.rstrip() + "\n" for line in block]
96
97
98  # Main algorithm
99
100  while more_input_available():
101    while next_line(isnt_comment):
102      write(read_line())
103
104    comment_block = []
105    # Get all lines in the same comment block. We could restrict the indentation
106    # to be the same as the first line of the block, but it's probably ok.
107    while (next_line(is_comment)):
108      comment_block.append(read_line())
109
110    for line in format_as_block(comment_block):
111      write(line)
112
113  flush_output()
114