Salome HOME
Change titles for command log stylesheets
[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 os.path.exists(filePath):
53         logger.write(src.printcolors.printcWarning("Removing ")
54                      + filePath + "\n", 5)
55         os.remove(filePath)
56
57 def print_log_command_in_terminal(filePath, logger):
58     '''Print the contain of filePath. It contains a command log in xml format.
59     
60     :param filePath: The command xml file from which extract the commands 
61                      context and traces
62     :param logger Logger: the logging instance to use in order to print.  
63     '''
64     logger.write(_("Reading ") + src.printcolors.printcHeader(filePath) + "\n", 5)
65     # Instantiate the ReadXmlFile class that reads xml files
66     xmlRead = src.xmlManager.ReadXmlFile(filePath)
67     # Get the attributes containing the context (user, OS, time, etc..)
68     dAttrText = xmlRead.get_attrib('Site')
69     # format dAttrText and print the context
70     lAttrText = []
71     for attrib in dAttrText:
72         lAttrText.append((attrib, dAttrText[attrib]))
73     logger.write("\n", 1)
74     src.print_info(logger, lAttrText)
75     # Get the traces
76     command_traces = xmlRead.get_node_text('Log')
77     # Print it if there is any
78     if command_traces:
79         logger.write(src.printcolors.printcHeader(
80                                     _("Here are the command traces :\n")), 1)
81         logger.write(command_traces, 1)
82         logger.write("\n", 1)
83
84 def ask_value(nb):
85     '''Ask for an int n. 0<n<nb
86     
87     :param nb int: The maximum value of the value to be returned by the user.
88     :return: the value entered by the user. Return -1 if it is not as expected
89     :rtype: int
90     '''
91     try:
92         # ask for a value
93         rep = input(_("Which one (enter or 0 to quit)? "))
94         # Verify it is on the right range
95         if len(rep) == 0:
96             x = 0
97         else:
98             x = int(rep)
99             if x > nb:
100                 x = -1
101     except:
102         x = -1
103     
104     return x
105
106 def description():
107     '''method that is called when salomeTools is called with --help option.
108     
109     :return: The text to display for the log command description.
110     :rtype: str
111     '''
112     return _("Gives access to the logs produced by the salomeTools commands.")    
113
114 def run(args, runner, logger):
115     '''method that is called when salomeTools is called with log parameter.
116     '''
117     # Parse the options
118     (options, args) = parser.parse_args(args)
119
120     # get the log directory. 
121     # If there is an application, it is in cfg.APPLICATION.out_dir, 
122     # else in user directory
123     logDir = runner.cfg.SITE.log.logDir
124
125     # If the clean options is invoked, 
126     # do nothing but deleting the concerned files.
127     if options.clean:
128         nbClean = options.clean
129         # get the list of files to remove
130         lLogs = src.logger.list_log_file(logDir, 
131                                          src.logger.logCommandFileExpression)
132         nbLogFiles = len(lLogs)
133         # Delete all if the invoked number is bigger than the number of log files
134         if nbClean > nbLogFiles:
135             nbClean = nbLogFiles
136         # Get the list to delete and do the removing
137         lLogsToDelete = sorted(lLogs)[:nbClean]
138         for filePath, _, _, _, _, _ in lLogsToDelete:
139             # remove the xml log file
140             remove_log_file(filePath, logger)
141             # remove also the corresponding txt file in OUT directory
142             txtFilePath = os.path.join(os.path.dirname(filePath), 
143                             'OUT', 
144                             os.path.basename(filePath)[:-len('.xml')] + '.txt')
145             remove_log_file(txtFilePath, logger)
146             # remove also the corresponding pyconf file in OUT directory
147             pyconfFilePath = os.path.join(os.path.dirname(filePath), 
148                             'OUT', 
149                             os.path.basename(filePath)[:-len('.xml')] + '.pyconf')
150             remove_log_file(pyconfFilePath, logger)
151
152         
153         logger.write(src.printcolors.printcSuccess("OK\n"))
154         logger.write("%i logs deleted.\n" % nbClean)
155         return 0 
156
157     # determine the commands to show in the hat log
158     notShownCommands = runner.cfg.INTERNAL.log.notShownCommands
159     if options.full:
160         notShownCommands = []
161
162     # Find the stylesheets Directory and files
163     xslDir = os.path.join(runner.cfg.VARS.srcDir, 'xsl')
164     xslCommand = os.path.join(xslDir, "command.xsl")
165     xslHat = os.path.join(xslDir, "hat.xsl")
166     imgLogo = os.path.join(xslDir, "LOGO-SAT.png")
167     
168     # copy the stylesheets in the log directory
169     shutil.copy2(xslCommand, logDir)
170     shutil.copy2(xslHat, logDir)
171     shutil.copy2(imgLogo, logDir)
172
173     # If the last option is invoked, just, show the last log file
174     if options.last:
175         lastLogFilePath = get_last_log_file(logDir, notShownCommands)        
176         if options.terminal:
177             # Show the log corresponding to the selected command call
178             print_log_command_in_terminal(lastLogFilePath, logger)
179         else:
180             # open the log xml file in the user editor
181             src.system.show_in_editor(runner.cfg.USER.browser, 
182                                       lastLogFilePath, logger)
183         return 0
184
185     # If the user asks for a terminal display
186     if options.terminal:
187         # Parse the log directory in order to find 
188         # all the files corresponding to the commands
189         lLogs = src.logger.list_log_file(logDir, 
190                                          src.logger.logCommandFileExpression)
191         lLogsFiltered = []
192         for filePath, _, date, _, hour, cmd in lLogs:
193             showLog, cmdAppli = src.logger.show_command_log(filePath, cmd, 
194                                 runner.cfg.VARS.application, notShownCommands)
195             if showLog:
196                 lLogsFiltered.append((filePath, date, hour, cmd, cmdAppli))
197             
198         lLogsFiltered = sorted(lLogsFiltered)
199         nb_logs = len(lLogsFiltered)
200         index = 0
201         # loop on all files and print it with date, time and command name 
202         for _, date, hour, cmd, cmdAppli in lLogsFiltered:          
203             num = src.printcolors.printcLabel("%2d" % (nb_logs - index))
204             logger.write("%s: %13s %s %s %s\n" % 
205                          (num, cmd, date, hour, cmdAppli), 1, False)
206             index += 1
207         
208         # ask the user what for what command he wants to be displayed
209         x = -1
210         while (x < 0):
211             x = ask_value(nb_logs)
212             if x > 0:
213                 index = len(lLogsFiltered) - int(x)
214                 # Show the log corresponding to the selected command call
215                 print_log_command_in_terminal(lLogsFiltered[index][0], logger)                
216                 x = 0
217         
218         return 0
219                     
220     # Create or update the hat xml that gives access to all the commands log files
221     xmlHatFilePath = os.path.join(logDir, 'hat.xml')
222     src.logger.update_hat_xml(runner.cfg.SITE.log.logDir, 
223                               application = runner.cfg.VARS.application, 
224                               notShownCommands = notShownCommands)
225     
226     # open the hat xml in the user editor
227     src.system.show_in_editor(runner.cfg.USER.browser, xmlHatFilePath, logger)
228     return 0