3 # Copyright (C) 2010-2012 CEA/DEN
5 # This library is free software; you can redistribute it and/or
6 # modify it under the terms of the GNU Lesser General Public
7 # License as published by the Free Software Foundation; either
8 # version 2.1 of the License.
10 # This library is distributed in the hope that it will be useful,
11 # but WITHOUT ANY WARRANTY; without even the implied warranty of
12 # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
13 # Lesser General Public License for more details.
15 # You should have received a copy of the GNU Lesser General Public
16 # License along with this library; if not, write to the Free Software
17 # Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
26 # Compatibility python 2/3 for input function
27 # input stays input for python 3 and input = raw_input for python 2
35 # Define all possible option for log command : sat log <options>
36 parser = src.options.Options()
37 parser.add_option('t', 'terminal', 'boolean', 'terminal', "Optional: "
39 parser.add_option('l', 'last', 'boolean', 'last', "Show the log of the last "
40 "Optional: launched command.")
41 parser.add_option('', 'last_terminal', 'boolean', 'last_terminal', "Show the "
42 "log of the last compilations"
43 "Optional: launched command.")
44 parser.add_option('f', 'full', 'boolean', 'full', "Optional: Show the logs of "
45 "ALL the launched commands.")
46 parser.add_option('c', 'clean', 'int', 'clean', "Optional: Erase the n most "
48 parser.add_option('n', 'no_browser', 'boolean', 'no_browser', "Optional: Do not"
49 " launch the browser at the end of the command. Only update "
52 def get_last_log_file(logDir, notShownCommands):
53 '''Used in case of last option. Get the last log command file path.
55 :param logDir str: The directory where to search the log files
56 :param notShownCommands list: the list of commands to ignore
57 :return: the path to the last log file
61 for fileName in os.listdir(logDir):
62 # YYYYMMDD_HHMMSS_namecmd.xml
63 sExpr = src.logger.log_macro_command_file_expression
64 oExpr = re.compile(sExpr)
65 if oExpr.search(fileName):
66 # get date and hour and format it
67 date_hour_cmd = fileName.split('_')
68 datehour = date_hour_cmd[0] + date_hour_cmd[1]
69 cmd = date_hour_cmd[2]
70 if cmd in notShownCommands:
72 if int(datehour) > last[1]:
73 last = (fileName, int(datehour))
74 return os.path.join(logDir, last[0])
76 def remove_log_file(filePath, logger):
77 '''if it exists, print a warning and remove the input file
79 :param filePath: the path of the file to delete
80 :param logger Logger: the logger instance to use for the print
82 if os.path.exists(filePath):
83 logger.write(src.printcolors.printcWarning("Removing ")
87 def print_log_command_in_terminal(filePath, logger):
88 '''Print the contain of filePath. It contains a command log in xml format.
90 :param filePath: The command xml file from which extract the commands
92 :param logger Logger: the logging instance to use in order to print.
94 logger.write(_("Reading ") + src.printcolors.printcHeader(filePath) + "\n", 5)
95 # Instantiate the ReadXmlFile class that reads xml files
96 xmlRead = src.xmlManager.ReadXmlFile(filePath)
97 # Get the attributes containing the context (user, OS, time, etc..)
98 dAttrText = xmlRead.get_attrib('Site')
99 # format dAttrText and print the context
101 for attrib in dAttrText:
102 lAttrText.append((attrib, dAttrText[attrib]))
103 logger.write("\n", 1)
104 src.print_info(logger, lAttrText)
106 command_traces = xmlRead.get_node_text('Log')
107 # Print it if there is any
109 logger.write(src.printcolors.printcHeader(
110 _("Here are the command traces :\n")), 1)
111 logger.write(command_traces, 1)
112 logger.write("\n", 1)
114 def show_last_logs(logger, config, log_dirs):
115 """Show last compilation logs"""
116 log_dir = os.path.join(config.APPLICATION.workdir, 'LOGS')
120 col_size = (nb / nb_cols) + 1
121 for index in range(0, col_size):
122 for i in range(0, nb_cols):
123 k = index + i * col_size
126 str_indice = src.printcolors.printcLabel("%2d" % (k+1))
128 logger.write("%s: %-30s" % (str_indice, log_name), 1, False)
129 logger.write("\n", 1, False)
136 product_log_dir = os.path.join(log_dir, log_dirs[x-1])
137 show_product_last_logs(logger, config, product_log_dir)
139 def show_product_last_logs(logger, config, product_log_dir):
140 """Show last compilation logs of a product"""
141 files = os.listdir(product_log_dir)
142 # sort the files chronologically
144 for file_n in os.listdir(product_log_dir):
145 my_stat = os.stat(os.path.join(product_log_dir, file_n))
147 (datetime.datetime.fromtimestamp(my_stat[stat.ST_MTIME]), file_n))
149 for i, (__, file_name) in enumerate(sorted(l_time_file)):
150 str_indice = src.printcolors.printcLabel("%2d" % (i+1))
152 my_stat = os.stat(os.path.join(product_log_dir, file_name))
153 opt.append(str(datetime.datetime.fromtimestamp(my_stat[stat.ST_MTIME])))
155 opt.append("(%8.2f)" % (my_stat[stat.ST_SIZE] / 1024.0))
156 logger.write(" %-35s" % " ".join(opt), 1, False)
157 logger.write("%s: %-30s\n" % (str_indice, file_name), 1, False)
162 x = ask_value(len(files))
164 log_file_path = os.path.join(product_log_dir, files[x-1])
165 src.system.show_in_editor(config.USER.editor, log_file_path, logger)
168 '''Ask for an int n. 0<n<nb
170 :param nb int: The maximum value of the value to be returned by the user.
171 :return: the value entered by the user. Return -1 if it is not as expected
176 rep = input(_("Which one (enter or 0 to quit)? "))
177 # Verify it is on the right range
190 '''method that is called when salomeTools is called with --help option.
192 :return: The text to display for the log command description.
195 return _("Gives access to the logs produced by the salomeTools commands.\n"
196 "\nexample:\nsat log")
198 def run(args, runner, logger):
199 '''method that is called when salomeTools is called with log parameter.
202 (options, args) = parser.parse_args(args)
204 # get the log directory.
205 logDir = runner.cfg.USER.log_dir
208 nb_files_log_dir = len(glob.glob(os.path.join(logDir, "*")))
209 info = [("log directory", logDir),
210 ("number of log files", nb_files_log_dir)]
211 src.print_info(logger, info)
213 # If the clean options is invoked,
214 # do nothing but deleting the concerned files.
216 nbClean = options.clean
217 # get the list of files to remove
218 lLogs = src.logger.list_log_file(logDir,
219 src.logger.log_all_command_file_expression)
220 nbLogFiles = len(lLogs)
221 # Delete all if the invoked number is bigger than the number of log files
222 if nbClean > nbLogFiles:
224 # Get the list to delete and do the removing
225 lLogsToDelete = sorted(lLogs)[:nbClean]
226 for filePath, __, __, __, __, __, __ in lLogsToDelete:
227 # remove the xml log file
228 remove_log_file(filePath, logger)
229 # remove also the corresponding txt file in OUT directory
230 txtFilePath = os.path.join(os.path.dirname(filePath),
232 os.path.basename(filePath)[:-len('.xml')] + '.txt')
233 remove_log_file(txtFilePath, logger)
234 # remove also the corresponding pyconf (do not exist 2016-06)
235 # file in OUT directory
236 pyconfFilePath = os.path.join(os.path.dirname(filePath),
238 os.path.basename(filePath)[:-len('.xml')] + '.pyconf')
239 remove_log_file(pyconfFilePath, logger)
242 logger.write(src.printcolors.printcSuccess("OK\n"))
243 logger.write("%i logs deleted.\n" % nbClean)
246 # determine the commands to show in the hat log
247 notShownCommands = list(runner.cfg.INTERNAL.log.not_shown_commands)
249 notShownCommands = []
251 # Find the stylesheets Directory and files
252 xslDir = os.path.join(runner.cfg.VARS.srcDir, 'xsl')
253 xslCommand = os.path.join(xslDir, "command.xsl")
254 xslHat = os.path.join(xslDir, "hat.xsl")
255 xsltest = os.path.join(xslDir, "test.xsl")
256 imgLogo = os.path.join(xslDir, "LOGO-SAT.png")
258 # copy the stylesheets in the log directory
259 shutil.copy2(xslCommand, logDir)
260 shutil.copy2(xslHat, logDir)
261 src.ensure_path_exists(os.path.join(logDir, "TEST"))
262 shutil.copy2(xsltest, os.path.join(logDir, "TEST"))
263 shutil.copy2(imgLogo, logDir)
265 # If the last option is invoked, just, show the last log file
266 if options.last_terminal:
267 log_dirs = os.listdir(os.path.join(runner.cfg.APPLICATION.workdir,
269 show_last_logs(logger, runner.cfg, log_dirs)
272 # If the last option is invoked, just, show the last log file
274 lastLogFilePath = get_last_log_file(logDir,
275 notShownCommands + ["config"])
277 # Show the log corresponding to the selected command call
278 print_log_command_in_terminal(lastLogFilePath, logger)
280 # open the log xml file in the user editor
281 src.system.show_in_editor(runner.cfg.USER.browser,
282 lastLogFilePath, logger)
285 # If the user asks for a terminal display
287 # Parse the log directory in order to find
288 # all the files corresponding to the commands
289 lLogs = src.logger.list_log_file(logDir,
290 src.logger.log_macro_command_file_expression)
292 for filePath, __, date, __, hour, cmd, __ in lLogs:
293 showLog, cmdAppli, __ = src.logger.show_command_log(filePath, cmd,
294 runner.cfg.VARS.application, notShownCommands)
296 lLogsFiltered.append((filePath, date, hour, cmd, cmdAppli))
298 lLogsFiltered = sorted(lLogsFiltered)
299 nb_logs = len(lLogsFiltered)
301 # loop on all files and print it with date, time and command name
302 for __, date, hour, cmd, cmdAppli in lLogsFiltered:
303 num = src.printcolors.printcLabel("%2d" % (nb_logs - index))
304 logger.write("%s: %13s %s %s %s\n" %
305 (num, cmd, date, hour, cmdAppli), 1, False)
308 # ask the user what for what command he wants to be displayed
311 x = ask_value(nb_logs)
313 index = len(lLogsFiltered) - int(x)
314 # Show the log corresponding to the selected command call
315 print_log_command_in_terminal(lLogsFiltered[index][0], logger)
320 # Create or update the hat xml that gives access to all the commands log files
321 logger.write(_("Generating the hat log file (can be long) ... "), 3)
322 xmlHatFilePath = os.path.join(logDir, 'hat.xml')
323 src.logger.update_hat_xml(runner.cfg.USER.log_dir,
324 application = runner.cfg.VARS.application,
325 notShownCommands = notShownCommands)
326 logger.write(src.printcolors.printc("OK"), 3)
327 logger.write("\n", 3)
329 # open the hat xml in the user editor
330 if not options.no_browser:
331 logger.write(_("\nOpening the log file\n"), 3)
332 src.system.show_in_editor(runner.cfg.USER.browser, xmlHatFilePath, logger)