Salome HOME
Add completion mechanism
[tools/sat.git] / commands / log.py
1 #!/usr/bin/env python
2 #-*- coding:utf-8 -*-
3
4 import os
5 import shutil
6 import re
7
8 # Compatibility python 2/3 for input function
9 # input stays input for python 3 and input = raw_input for python 2
10 try: 
11     input = raw_input
12 except NameError: 
13     pass
14
15 import src
16
17 # Define all possible option for log command :  sat log <options>
18 parser = src.options.Options()
19 parser.add_option('t', 'terminal', 'boolean', 'terminal', "Terminal log.")
20 parser.add_option('l', 'last', 'boolean', 'last', "Show the log of the last "
21                   "launched command.")
22 parser.add_option('f', 'full', 'boolean', 'full', "Show the logs of ALL "
23                   "launched commands.")
24 parser.add_option('c', 'clean', 'int', 'clean', "Erase the n most ancient "
25                   "log files.")
26
27 def get_last_log_file(logDir, notShownCommands):
28     '''Used in case of last option. Get the last log command file path.
29     
30     :param logDir str: The directory where to search the log files
31     :param notShownCommands list: the list of commands to ignore
32     :return: the path to the last log file
33     :rtype: str
34     '''
35     last = (_, 0)
36     for fileName in os.listdir(logDir):
37         # YYYYMMDD_HHMMSS_namecmd.xml
38         sExpr = src.logger.logCommandFileExpression
39         oExpr = re.compile(sExpr)
40         if oExpr.search(fileName):
41             # get date and hour and format it
42             date_hour_cmd = fileName.split('_')
43             datehour = date_hour_cmd[0] + date_hour_cmd[1]
44             cmd = date_hour_cmd[2][:-len('.xml')]
45             if cmd in notShownCommands:
46                 continue
47             if int(datehour) > last[1]:
48                 last = (fileName, int(datehour))
49     return os.path.join(logDir, last[0])
50
51 def remove_log_file(filePath, logger):
52     '''if it exists, print a warning and remove the input file
53     
54     :param filePath: the path of the file to delete
55     :param logger Logger: the logger instance to use for the print 
56     '''
57     if os.path.exists(filePath):
58         logger.write(src.printcolors.printcWarning("Removing ")
59                      + filePath + "\n", 5)
60         os.remove(filePath)
61
62 def print_log_command_in_terminal(filePath, logger):
63     '''Print the contain of filePath. It contains a command log in xml format.
64     
65     :param filePath: The command xml file from which extract the commands 
66                      context and traces
67     :param logger Logger: the logging instance to use in order to print.  
68     '''
69     logger.write(_("Reading ") + src.printcolors.printcHeader(filePath) + "\n", 5)
70     # Instantiate the ReadXmlFile class that reads xml files
71     xmlRead = src.xmlManager.ReadXmlFile(filePath)
72     # Get the attributes containing the context (user, OS, time, etc..)
73     dAttrText = xmlRead.get_attrib('Site')
74     # format dAttrText and print the context
75     lAttrText = []
76     for attrib in dAttrText:
77         lAttrText.append((attrib, dAttrText[attrib]))
78     logger.write("\n", 1)
79     src.print_info(logger, lAttrText)
80     # Get the traces
81     command_traces = xmlRead.get_node_text('Log')
82     # Print it if there is any
83     if command_traces:
84         logger.write(src.printcolors.printcHeader(
85                                     _("Here are the command traces :\n")), 1)
86         logger.write(command_traces, 1)
87         logger.write("\n", 1)
88
89 def ask_value(nb):
90     '''Ask for an int n. 0<n<nb
91     
92     :param nb int: The maximum value of the value to be returned by the user.
93     :return: the value entered by the user. Return -1 if it is not as expected
94     :rtype: int
95     '''
96     try:
97         # ask for a value
98         rep = input(_("Which one (enter or 0 to quit)? "))
99         # Verify it is on the right range
100         if len(rep) == 0:
101             x = 0
102         else:
103             x = int(rep)
104             if x > nb:
105                 x = -1
106     except:
107         x = -1
108     
109     return x
110
111 def description():
112     '''method that is called when salomeTools is called with --help option.
113     
114     :return: The text to display for the log command description.
115     :rtype: str
116     '''
117     return _("Gives access to the logs produced by the salomeTools commands.")    
118
119 def run(args, runner, logger):
120     '''method that is called when salomeTools is called with log parameter.
121     '''
122     # Parse the options
123     (options, args) = parser.parse_args(args)
124
125     # get the log directory. 
126     # If there is an application, it is in cfg.APPLICATION.out_dir, 
127     # else in user directory
128     logDir = runner.cfg.SITE.log.log_dir
129
130     # If the clean options is invoked, 
131     # do nothing but deleting the concerned files.
132     if options.clean:
133         nbClean = options.clean
134         # get the list of files to remove
135         lLogs = src.logger.list_log_file(logDir, 
136                                          src.logger.logCommandFileExpression)
137         nbLogFiles = len(lLogs)
138         # Delete all if the invoked number is bigger than the number of log files
139         if nbClean > nbLogFiles:
140             nbClean = nbLogFiles
141         # Get the list to delete and do the removing
142         lLogsToDelete = sorted(lLogs)[:nbClean]
143         for filePath, _, _, _, _, _ in lLogsToDelete:
144             # remove the xml log file
145             remove_log_file(filePath, logger)
146             # remove also the corresponding txt file in OUT directory
147             txtFilePath = os.path.join(os.path.dirname(filePath), 
148                             'OUT', 
149                             os.path.basename(filePath)[:-len('.xml')] + '.txt')
150             remove_log_file(txtFilePath, logger)
151             # remove also the corresponding pyconf file in OUT directory
152             pyconfFilePath = os.path.join(os.path.dirname(filePath), 
153                             'OUT', 
154                             os.path.basename(filePath)[:-len('.xml')] + '.pyconf')
155             remove_log_file(pyconfFilePath, logger)
156
157         
158         logger.write(src.printcolors.printcSuccess("OK\n"))
159         logger.write("%i logs deleted.\n" % nbClean)
160         return 0 
161
162     # determine the commands to show in the hat log
163     notShownCommands = runner.cfg.INTERNAL.log.not_shown_commands
164     if options.full:
165         notShownCommands = []
166
167     # Find the stylesheets Directory and files
168     xslDir = os.path.join(runner.cfg.VARS.srcDir, 'xsl')
169     xslCommand = os.path.join(xslDir, "command.xsl")
170     xslHat = os.path.join(xslDir, "hat.xsl")
171     imgLogo = os.path.join(xslDir, "LOGO-SAT.png")
172     
173     # copy the stylesheets in the log directory
174     shutil.copy2(xslCommand, logDir)
175     shutil.copy2(xslHat, logDir)
176     shutil.copy2(imgLogo, logDir)
177
178     # If the last option is invoked, just, show the last log file
179     if options.last:
180         lastLogFilePath = get_last_log_file(logDir, notShownCommands)        
181         if options.terminal:
182             # Show the log corresponding to the selected command call
183             print_log_command_in_terminal(lastLogFilePath, logger)
184         else:
185             # open the log xml file in the user editor
186             src.system.show_in_editor(runner.cfg.USER.browser, 
187                                       lastLogFilePath, logger)
188         return 0
189
190     # If the user asks for a terminal display
191     if options.terminal:
192         # Parse the log directory in order to find 
193         # all the files corresponding to the commands
194         lLogs = src.logger.list_log_file(logDir, 
195                                          src.logger.logCommandFileExpression)
196         lLogsFiltered = []
197         for filePath, _, date, _, hour, cmd in lLogs:
198             showLog, cmdAppli = src.logger.show_command_log(filePath, cmd, 
199                                 runner.cfg.VARS.application, notShownCommands)
200             if showLog:
201                 lLogsFiltered.append((filePath, date, hour, cmd, cmdAppli))
202             
203         lLogsFiltered = sorted(lLogsFiltered)
204         nb_logs = len(lLogsFiltered)
205         index = 0
206         # loop on all files and print it with date, time and command name 
207         for _, date, hour, cmd, cmdAppli in lLogsFiltered:          
208             num = src.printcolors.printcLabel("%2d" % (nb_logs - index))
209             logger.write("%s: %13s %s %s %s\n" % 
210                          (num, cmd, date, hour, cmdAppli), 1, False)
211             index += 1
212         
213         # ask the user what for what command he wants to be displayed
214         x = -1
215         while (x < 0):
216             x = ask_value(nb_logs)
217             if x > 0:
218                 index = len(lLogsFiltered) - int(x)
219                 # Show the log corresponding to the selected command call
220                 print_log_command_in_terminal(lLogsFiltered[index][0], logger)                
221                 x = 0
222         
223         return 0
224                     
225     # Create or update the hat xml that gives access to all the commands log files
226     xmlHatFilePath = os.path.join(logDir, 'hat.xml')
227     src.logger.update_hat_xml(runner.cfg.SITE.log.log_dir, 
228                               application = runner.cfg.VARS.application, 
229                               notShownCommands = notShownCommands)
230     
231     # open the hat xml in the user editor
232     src.system.show_in_editor(runner.cfg.USER.browser, xmlHatFilePath, logger)
233     return 0