fixing pep8 problems for test verify tox job
[integration/test.git] / tools / robot_check / tidytool.py
1 import difflib
2 import os
3 import sys
4 import stat
5 import robot.tidy
6
7
8 def Error(FileSpec, Message):
9     global ErrorsReported
10     print "File", FileSpec + ":", Message
11     ErrorsReported = True
12
13
14 def traverse_and_process(DirList, Processor):
15     """Traverse the directory and process all .robot files found"""
16     Stack = []
17     for Dir in DirList:
18         if Dir[-1] == "/":
19             Dir = Dir[:-1]
20         Stack.append(Dir)
21     while len(Stack) > 0:
22         Dir = Stack.pop() + "/"
23         try:
24             List = os.listdir(Dir)
25         except (IOError, OSError), e:
26             Error(Dir, "Directory not accessible: " + str(e))
27             continue
28         for Item in List:
29             Spec = Dir + Item
30             Stat = os.stat(Spec)
31             if stat.S_ISDIR(Stat.st_mode):
32                 Stack.append(Spec)
33             elif Item.endswith(".robot"):
34                 Processor(Spec)
35
36
37 def check_quietly(FileSpec):
38     try:
39         Data = open(FileSpec).read()
40     except (IOError, OSError), e:
41         Error(FileSpec, "Not accessible: " + str(e))
42         return
43     try:
44         Data = Data.decode("utf8")
45     except:
46         Error(FileSpec, "Has invalid UTF8 data")
47         return
48     TidyTool = robot.tidy.Tidy()
49     CleanedData = TidyTool.file(FileSpec)
50     if Data != CleanedData:
51         Error(FileSpec, "Found to be untidy")
52
53
54 def check(FileSpec):
55     Index = FileSpec.rfind("/")
56     FileName = FileSpec
57     if Index >= 0:
58         FileName = FileSpec[Index + 1:]
59     sys.stdout.write("  " + FileName + "\r")
60     sys.stdout.flush()
61     check_quietly(FileSpec)
62     sys.stdout.write(" " * (2 + len(FileName)) + "\r")
63
64
65 def tidy(FileSpec):
66     print "Processing file:", FileSpec
67     TidyTool = robot.tidy.Tidy()
68     try:
69         CleanedData = TidyTool.file(FileSpec)
70         CleanedData = CleanedData.encode("utf8")
71         open(FileSpec, "w").write(CleanedData)
72     except (IOError, OSError), e:
73         Error(FileSpec, "Not accessible: " + str(e))
74
75
76 def diff(FileSpec):
77     TidyTool = robot.tidy.Tidy()
78     try:
79         ActualLines = open(FileSpec, 'U').readlines()
80         CleanedData = TidyTool.file(FileSpec)
81         # Unified diff wants list of lines, and split on newline creates empty line at the end.
82         CleanedLines = [line + '\n' for line in CleanedData.encode("utf8").split('\n')[:-1]]
83         DiffText = "".join(tuple(difflib.unified_diff(ActualLines, CleanedLines, n=10)))
84         # TODO: If the last line does not contain \n, the output is ugly. Can we fix that without causing confsion?
85         if DiffText:
86             Error(FileSpec, "Tidy requires the following diff:\n" + DiffText)
87     except (IOError, OSError), e:
88         Error(FileSpec, "Not accessible: " + str(e))
89
90
91 # TODO: Refactor the command line argument parsing to use argparse. Since I
92 #       wanted to just quickly make this tool to get rid of manual robot.tidy
93 #       runs I did not have time to create polished argparse based command
94 #       line argument parsing code. Remember also to update the convenience
95 #       scripts.
96
97
98 def usage():
99     print "Usage:\ttidytool.py <command>k <dir1> [<dir2> <dir3> ...]"
100     print
101     print "where <command> is one of these:"
102     print
103     print "check\tCheck that the Robot test data is tidy."
104     print "quiet\tCheck quietly that the Robot test data is tidy."
105     print "tidy\tTidy the Robot test data."
106     print
107     print "The program traverses the specified directories, searching for"
108     print "Robot test data (.robot files) and performing the specified"
109     print "command on them."
110
111
112 if __name__ == "__main__":
113     if len(sys.argv) < 2:
114         usage()
115         raise SystemExit
116     Command = sys.argv[1]
117     DirList = sys.argv[2:]
118     if Command == "check":
119         Processor = check
120     elif Command == "quiet":
121         Processor = check_quietly
122     elif Command == "tidy":
123         Processor = tidy
124     elif Command == "diff":
125         Processor = diff
126     else:
127         print "Unrecognized command:", Command
128         sys.exit(1)
129     ErrorsReported = False
130     traverse_and_process(DirList, Processor)
131     if ErrorsReported:
132         print "tidytool run FAILED !!!"
133         sys.exit(1)