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 # display the available logs
150 for i, (__, file_name) in enumerate(sorted(l_time_file)):
151 str_indice = src.printcolors.printcLabel("%2d" % (i+1))
153 my_stat = os.stat(os.path.join(product_log_dir, file_name))
154 opt.append(str(datetime.datetime.fromtimestamp(my_stat[stat.ST_MTIME])))
156 opt.append("(%8.2f)" % (my_stat[stat.ST_SIZE] / 1024.0))
157 logger.write(" %-35s" % " ".join(opt), 1, False)
158 logger.write("%s: %-30s\n" % (str_indice, file_name), 1, False)
163 x = ask_value(len(files))
165 log_file_path = os.path.join(product_log_dir, files[x-1])
166 src.system.show_in_editor(config.USER.editor, log_file_path, logger)
169 '''Ask for an int n. 0<n<nb
171 :param nb int: The maximum value of the value to be returned by the user.
172 :return: the value entered by the user. Return -1 if it is not as expected
177 rep = input(_("Which one (enter or 0 to quit)? "))
178 # Verify it is on the right range
191 '''method that is called when salomeTools is called with --help option.
193 :return: The text to display for the log command description.
196 return _("Gives access to the logs produced by the salomeTools commands.\n"
197 "\nexample:\nsat log")
199 def run(args, runner, logger):
200 '''method that is called when salomeTools is called with log parameter.
203 (options, args) = parser.parse_args(args)
205 # get the log directory.
206 logDir = runner.cfg.USER.log_dir
209 nb_files_log_dir = len(glob.glob(os.path.join(logDir, "*")))
210 info = [("log directory", logDir),
211 ("number of log files", nb_files_log_dir)]
212 src.print_info(logger, info)
214 # If the clean options is invoked,
215 # do nothing but deleting the concerned files.
217 nbClean = options.clean
218 # get the list of files to remove
219 lLogs = src.logger.list_log_file(logDir,
220 src.logger.log_all_command_file_expression)
221 nbLogFiles = len(lLogs)
222 # Delete all if the invoked number is bigger than the number of log files
223 if nbClean > nbLogFiles:
225 # Get the list to delete and do the removing
226 lLogsToDelete = sorted(lLogs)[:nbClean]
227 for filePath, __, __, __, __, __, __ in lLogsToDelete:
228 # remove the xml log file
229 remove_log_file(filePath, logger)
230 # remove also the corresponding txt file in OUT directory
231 txtFilePath = os.path.join(os.path.dirname(filePath),
233 os.path.basename(filePath)[:-len('.xml')] + '.txt')
234 remove_log_file(txtFilePath, logger)
235 # remove also the corresponding pyconf (do not exist 2016-06)
236 # file in OUT directory
237 pyconfFilePath = os.path.join(os.path.dirname(filePath),
239 os.path.basename(filePath)[:-len('.xml')] + '.pyconf')
240 remove_log_file(pyconfFilePath, logger)
243 logger.write(src.printcolors.printcSuccess("OK\n"))
244 logger.write("%i logs deleted.\n" % nbClean)
247 # determine the commands to show in the hat log
248 notShownCommands = list(runner.cfg.INTERNAL.log.not_shown_commands)
250 notShownCommands = []
252 # Find the stylesheets Directory and files
253 xslDir = os.path.join(runner.cfg.VARS.srcDir, 'xsl')
254 xslCommand = os.path.join(xslDir, "command.xsl")
255 xslHat = os.path.join(xslDir, "hat.xsl")
256 xsltest = os.path.join(xslDir, "test.xsl")
257 imgLogo = os.path.join(xslDir, "LOGO-SAT.png")
259 # copy the stylesheets in the log directory
260 shutil.copy2(xslCommand, logDir)
261 shutil.copy2(xslHat, logDir)
262 src.ensure_path_exists(os.path.join(logDir, "TEST"))
263 shutil.copy2(xsltest, os.path.join(logDir, "TEST"))
264 shutil.copy2(imgLogo, logDir)
266 # If the last option is invoked, just, show the last log file
267 if options.last_terminal:
268 src.check_config_has_application(runner.cfg)
269 log_dirs = os.listdir(os.path.join(runner.cfg.APPLICATION.workdir,
271 show_last_logs(logger, runner.cfg, log_dirs)
274 # If the last option is invoked, just, show the last log file
276 lastLogFilePath = get_last_log_file(logDir,
277 notShownCommands + ["config"])
279 # Show the log corresponding to the selected command call
280 print_log_command_in_terminal(lastLogFilePath, logger)
282 # open the log xml file in the user editor
283 src.system.show_in_editor(runner.cfg.USER.browser,
284 lastLogFilePath, logger)
287 # If the user asks for a terminal display
289 # Parse the log directory in order to find
290 # all the files corresponding to the commands
291 lLogs = src.logger.list_log_file(logDir,
292 src.logger.log_macro_command_file_expression)
294 for filePath, __, date, __, hour, cmd, __ in lLogs:
295 showLog, cmdAppli, __ = src.logger.show_command_log(filePath, cmd,
296 runner.cfg.VARS.application, notShownCommands)
298 lLogsFiltered.append((filePath, date, hour, cmd, cmdAppli))
300 lLogsFiltered = sorted(lLogsFiltered)
301 nb_logs = len(lLogsFiltered)
303 # loop on all files and print it with date, time and command name
304 for __, date, hour, cmd, cmdAppli in lLogsFiltered:
305 num = src.printcolors.printcLabel("%2d" % (nb_logs - index))
306 logger.write("%s: %13s %s %s %s\n" %
307 (num, cmd, date, hour, cmdAppli), 1, False)
310 # ask the user what for what command he wants to be displayed
313 x = ask_value(nb_logs)
315 index = len(lLogsFiltered) - int(x)
316 # Show the log corresponding to the selected command call
317 print_log_command_in_terminal(lLogsFiltered[index][0], logger)
322 # Create or update the hat xml that gives access to all the commands log files
323 logger.write(_("Generating the hat log file (can be long) ... "), 3)
324 xmlHatFilePath = os.path.join(logDir, 'hat.xml')
325 src.logger.update_hat_xml(runner.cfg.USER.log_dir,
326 application = runner.cfg.VARS.application,
327 notShownCommands = notShownCommands)
328 logger.write(src.printcolors.printc("OK"), 3)
329 logger.write("\n", 3)
331 # open the hat xml in the user editor
332 if not options.no_browser:
333 logger.write(_("\nOpening the log file\n"), 3)
334 src.system.show_in_editor(runner.cfg.USER.browser, xmlHatFilePath, logger)