Salome HOME
'sat log' : --last option implementation
[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 import src
9
10 # Define all possible option for log command :  sat log <options>
11 parser = src.options.Options()
12 parser.add_option('t', 'terminal', 'boolean', 'terminal', "Terminal log.")
13 parser.add_option('l', 'last', 'boolean', 'last', "Show the log of the last launched command.")
14 parser.add_option('f', 'full', 'boolean', 'full', "Show the logs of ALL launched commands.")
15 parser.add_option('c', 'clean', 'int', 'clean', "Erase the n most ancient log files.")
16
17 def getLastLogFile(logDir, notShownCommands):
18     last = (_, 0)
19     for fileName in os.listdir(logDir):
20         # YYYYMMDD_HHMMSS_namecmd.xml
21         sExpr = "^[0-9]{8}_+[0-9]{6}_+.*\.xml$"
22         oExpr = re.compile(sExpr)
23         if oExpr.search(fileName):
24             # get date and hour and format it
25             date_hour_cmd = fileName.split('_')
26             datehour = date_hour_cmd[0] + date_hour_cmd[1]
27             cmd = date_hour_cmd[2][:-len('.xml')]
28             if cmd in notShownCommands:
29                 continue
30             if int(datehour) > last[1]:
31                 last = (fileName, int(datehour))
32     return os.path.join(logDir, last[0])
33
34 def show_log_command_in_terminal(filePath, logger):
35     '''Print the contain of filePath. It contains a command log in xml format.
36     
37     :param filePath: The command xml file from which extract the commands context and traces
38     :logger Logger: the logging instance to use in order to print.  
39     '''
40     # Instantiate the readXmlFile class that reads xml files
41     xmlRead = src.xmlManager.readXmlFile(filePath)
42     # Get the attributes containing the context (user, OS, time, etc..)
43     dAttrText = xmlRead.get_attrib('Site')
44     
45     # format dAttrText and print the context
46     lAttrText = []
47     for attrib in dAttrText:
48         lAttrText.append((attrib, dAttrText[attrib]))
49     logger.write("\n", 1)
50     src.print_info(logger, lAttrText)
51     # Get the traces
52     command_traces = xmlRead.get_node_text('Log')
53     # Print it if there is any
54     if command_traces:
55         logger.write(_("Here are the command traces :\n"), 1)
56         logger.write(command_traces, 1)
57         logger.write("\n", 1)
58
59 def ask_value(nb):
60     '''Ask for an int n. 0<n<nb
61     
62     :param nb int: The maximum value of the value to be returned by the user.
63     :return: the value entered by the user. Return -1 if it is not as expected
64     :rtype: int
65     '''
66     try:
67         # ask for a value
68         rep = raw_input(_("Which one (enter or 0 to quit)? "))
69         # Verify it is on the right range
70         if len(rep) == 0:
71             x = 0
72         else:
73             x = int(rep)
74             if x > nb:
75                 x = -1
76     except:
77         x = -1
78     
79     return x
80
81 def description():
82     '''method that is called when salomeTools is called with --help option.
83     
84     :return: The text to display for the log command description.
85     :rtype: str
86     '''
87     return _("Gives access to logs of salomeTools.")    
88
89 def run(args, runner, logger):
90     '''method that is called when salomeTools is called with log parameter.
91     '''
92     # Parse the options
93     (options, args) = parser.parse_args(args)
94
95     # get the log directory. If there is an application, it is in cfg.APPLICATION.out_dir, else in user directory
96     logDir = runner.cfg.SITE.log.logDir
97
98     # If the user asks for a terminal display
99     if options.terminal:
100         # Parse the log directory in order to find all the files corresponding to the commands
101         lLogs = []
102         for fileName in os.listdir(logDir):
103             sExpr = "^[0-9]{8}_+[0-9]{6}_+.*.xml$"
104             oExpr = re.compile(sExpr)
105             if oExpr.search(fileName):
106                 lLogs.append(fileName)
107         lLogs = sorted(lLogs)
108         nb_logs = len(lLogs)
109         index = 0
110         # loop on all files and print it with date, time and command name 
111         for t in lLogs:
112             date_hour_cmd = t.split('_')
113             date_not_formated = date_hour_cmd[0]
114             date = "%s/%s/%s" % (date_not_formated[6:8], date_not_formated[4:6], date_not_formated[0:4] )
115             hour_not_formated = date_hour_cmd[1]
116             hour = "%s:%s:%s" % (hour_not_formated[0:2], hour_not_formated[2:4], hour_not_formated[4:6])
117             cmd = date_hour_cmd[2][:-len('.xml')]
118             
119             num = src.printcolors.printcLabel("%2d" % (nb_logs - index))
120             logger.write("%s: %13s %s %s\n" % (num, cmd, date, hour), 1, False)
121             index += 1
122         
123         # ask the user what for what command he wants to be displayed
124         x = -1
125         while (x < 0):
126             x = ask_value(nb_logs)
127             if x > 0:
128                 index = len(lLogs) - int(x)
129                 # Show the log corresponding to the selected command call
130                 show_log_command_in_terminal(os.path.join(logDir, lLogs[index]), logger)                
131                 x = 0
132         
133         return 0
134                     
135     
136     # Find the stylesheets Directory and files
137     xslDir = os.path.join(runner.cfg.VARS.srcDir, 'xsl')
138     xslCommand = os.path.join(xslDir, "command.xsl")
139     xslHat = os.path.join(xslDir, "hat.xsl")
140     imgLogo = os.path.join(xslDir, "LOGO-SAT.png")
141     
142     # copy the stylesheets in the log directory
143     shutil.copy2(xslCommand, logDir)
144     shutil.copy2(xslHat, logDir)
145     shutil.copy2(imgLogo, logDir)
146
147     # determine the commands to show in the hat log
148     notShownCommands = runner.cfg.INTERNAL.log.notShownCommands
149     if options.full:
150         notShownCommands = []
151
152     # If the last option is invoked, just, show the last log file
153     if options.last:
154         lastLogFilePath = getLastLogFile(logDir, notShownCommands)
155         # open the log xml file in the user editor
156         src.system.show_in_editor(runner.cfg.USER.browser, lastLogFilePath, logger)
157         return 0
158
159     # Create or update the hat xml that gives access to all the commands log files
160     xmlHatFilePath = os.path.join(logDir, 'hat.xml')
161     src.xmlManager.update_hat_xml(runner.cfg.SITE.log.logDir, application = runner.cfg.VARS.application, notShownCommands = notShownCommands)
162     
163     # open the hat xml in the user editor
164     src.system.show_in_editor(runner.cfg.USER.browser, xmlHatFilePath, logger)
165     return 0