Salome HOME
sat package: remove the .pyconf file in the root directory of
[tools/sat.git] / commands / job.py
1 #!/usr/bin/env python
2 #-*- coding:utf-8 -*-
3 #  Copyright (C) 2010-2012  CEA/DEN
4 #
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.
9 #
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.
14 #
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
18
19 import os
20
21 import src
22 import salomeTools
23
24 # Define all possible option for the make command :  sat make <options>
25 parser = src.options.Options()
26 parser.add_option('j', 'jobs_config', 'string', 'jobs_cfg', 
27                   _('Mandatory: The name of the config file that contains'
28                   ' the jobs configuration'))
29 parser.add_option('', 'name', 'string', 'job',
30     _('Mandatory: The job name from which to execute commands.'), "")
31
32 def description():
33     '''method that is called when salomeTools is called with --help option.
34     
35     :return: The text to display for the job command description.
36     :rtype: str
37     '''
38     return _("Executes the commands of the job defined"
39              " in the jobs configuration file\n\nexample:\nsat job "
40              "--jobs_config my_jobs --name my_job")
41   
42 def run(args, runner, logger):
43     '''method that is called when salomeTools is called with job parameter.
44     '''
45     
46     # Parse the options
47     (options, args) = parser.parse_args(args)
48          
49     l_cfg_dir = runner.cfg.PATHS.JOBPATH
50     
51     # Make sure the jobs_config option has been called
52     if not options.jobs_cfg:
53         message = _("The option --jobs_config is required\n")      
54         logger.write(src.printcolors.printcError(message))
55         return 1
56     
57     # Make sure the name option has been called
58     if not options.job:
59         message = _("The option --name is required\n")      
60         logger.write(src.printcolors.printcError(message))
61         return 1
62     
63     # Find the file in the directories
64     found = False
65     for cfg_dir in l_cfg_dir:
66         file_jobs_cfg = os.path.join(cfg_dir, options.jobs_cfg)
67         if not file_jobs_cfg.endswith('.pyconf'):
68             file_jobs_cfg += '.pyconf'
69         
70         if not os.path.exists(file_jobs_cfg):
71             continue
72         else:
73             found = True
74             break
75     
76     if not found:
77         msg = _("The file configuration %(name_file)s was not found."
78                 "\nUse the --list option to get the possible files.")
79         src.printcolors.printcError(msg)
80         return 1
81     
82     info = [
83     (_("Platform"), runner.cfg.VARS.dist),
84     (_("File containing the jobs configuration"), file_jobs_cfg)
85     ]
86     src.print_info(logger, info)
87     
88     # Read the config that is in the file
89     config_jobs = src.read_config_from_a_file(file_jobs_cfg)
90     
91     # Find the job and its commands
92     found = False
93     for job in config_jobs.jobs:
94         if job.name == options.job:
95             commands = job.commands
96             found = True
97             break
98     if not found:
99         msg = _("Impossible to find the job \"%(job_name)s\" in "
100                 "%(jobs_config_file)s" % {"job_name" : options.job,
101                                           "jobs_config_file" : file_jobs_cfg})
102         logger.write(src.printcolors.printcError(msg) + "\n")
103         return 1
104     
105     # Find the maximum length of the commands in order to format the display
106     len_max_command = max([len(cmd) for cmd in commands])
107     
108     # Loop over the commands and execute it
109     res = 0
110     nb_pass = 0
111     for command in commands:
112         specific_option = False
113         # Determine if it is a sat command or a shell command
114         cmd_exe = command.split(" ")[0] # first part
115         if cmd_exe == "sat":
116             # use the salomeTools parser to get the options of the command
117             sat_parser = salomeTools.parser
118             input_parser = src.remove_item_from_list(command.split(' ')[1:], "")
119             (options, argus) = sat_parser.parse_args(input_parser)
120             # Verify if there is a changed option
121             for attr in dir(options):
122                 if attr.startswith("__"):
123                     continue
124                 if options.__getattr__(attr) != None:
125                     specific_option = True
126             sat_command_name = argus[0]
127             end_cmd = " ".join(argus[1:])
128         else:
129             sat_command_name = "shell"
130             end_cmd = ["--command", command]
131         # Do not change the options if no option was called in the command
132         if not(specific_option):
133             options = None
134
135         # Get dynamically the command function to call
136         sat_command = runner.__getattr__(sat_command_name)
137
138         logger.write("Executing " + 
139                      src.printcolors.printcLabel(command) + " ", 3)
140         logger.write("." * (len_max_command - len(command)) + " ", 3)
141         logger.flush()
142         
143         error = ""
144         stack = ""
145         # Execute the command
146         code = sat_command(end_cmd,
147                            options = options,
148                            batch = True,
149                            verbose = 0,
150                            logger_add_link = logger)
151             
152         # Print the status of the command
153         if code == 0:
154             nb_pass += 1
155             logger.write('%s\n' % src.printcolors.printc(src.OK_STATUS), 3)
156         else:
157             if sat_command_name != "test":
158                 res = 1
159             logger.write('%s %s\n' % (src.printcolors.printc(src.KO_STATUS),
160                                       error), 3)
161             if len(stack) > 0:
162                 logger.write('stack: %s\n' % stack, 3)
163     
164     # Print the final state
165     if res == 0:
166         final_status = "OK"
167     else:
168         final_status = "KO"
169    
170     logger.write(_("\nCommands: %(status)s (%(valid_result)d/%(nb_products)d)\n") % \
171         { 'status': src.printcolors.printc(final_status), 
172           'valid_result': nb_pass,
173           'nb_products': len(commands) }, 3)
174     
175     return res