Salome HOME
Add prepare command
[tools/sat.git] / commands / source.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 import shutil
21
22 import src
23
24 # Define all possible option for log command :  sat log <options>
25 parser = src.options.Options()
26 parser.add_option('m', 'module', 'list2', 'modules',
27     _('modules from which to get the sources. This option can be'
28     ' passed several time to get the sources of several modules.'))
29 parser.add_option('', 'no_sample', 'boolean', 'no_sample', 
30     _("do not get sources from sample modules."))
31 parser.add_option('f', 'force', 'boolean', 'force', 
32     _("force to get the sources of the modules in development mode."))
33
34 def get_sources_for_dev(config, module_info, source_dir, force, logger, pad):
35     '''The method called if the module is in development mode
36     
37     :param config Config: The global configuration
38     :param module_info Config: The configuration specific to 
39                                the module to be prepared
40     :param source_dir Path: The Path instance corresponding to the 
41                             directory where to put the sources
42     :param force boolean: True if the --force option was invoked
43     :param logger Logger: The logger instance to use for the display and logging
44     :param pad int: The gap to apply for the terminal display
45     :return: True if it succeed, else False
46     :rtype: boolean
47     '''
48     retcode = 'N\A'
49     # if the module source directory does not exist,
50     # get it in checkout mode, else, do not do anything
51     # unless the force option is invoked
52     if not os.path.exists(module_info.source_dir) or force:
53         # Call the function corresponding to get the sources with True checkout
54         retcode = get_module_sources(config, 
55                                      module_info, 
56                                      True, 
57                                      source_dir,
58                                      force, 
59                                      logger, 
60                                      pad, 
61                                      checkout=True)
62         logger.write("\n", 3, False)
63         # +2 because module name is followed by ': '
64         logger.write(" " * (pad+2), 3, False) 
65     
66     logger.write('dev: %s ... ' % 
67                  src.printcolors.printcInfo(module_info.source_dir), 3, False)
68     logger.flush()
69     
70     return retcode
71
72 def get_sources_from_git(module_info, source_dir, logger, pad, is_dev=False):
73     '''The method called if the module is to be get in git mode
74     
75     :param module_info Config: The configuration specific to 
76                                the module to be prepared
77     :param source_dir Path: The Path instance corresponding to the 
78                             directory where to put the sources
79     :param logger Logger: The logger instance to use for the display and logging
80     :param pad int: The gap to apply for the terminal display
81     :param is_dev boolean: True if the module is in development mode
82     :return: True if it succeed, else False
83     :rtype: boolean
84     '''
85     # The str to display
86     coflag = 'git'
87
88     # Get the repository address. (from repo_dev key if the module is 
89     # in dev mode.
90     if is_dev and 'repo_dev' in module_info.git_info:
91         coflag = src.printcolors.printcHighlight(coflag.upper())
92         repo_git = module_info.git_info.repo_dev    
93     else:
94         repo_git = module_info.git_info.repo    
95         
96     # Display informations
97     logger.write('%s:%s' % (coflag, src.printcolors.printcInfo(repo_git)), 3, 
98                  False)
99     logger.write(' ' * (pad + 50 - len(repo_git)), 3, False)
100     logger.write(' tag:%s' % src.printcolors.printcInfo(
101                                                     module_info.git_info.tag), 
102                  3,
103                  False)
104     logger.write(' %s. ' % ('.' * (10 - len(module_info.git_info.tag))), 3, 
105                  False)
106     logger.flush()
107     logger.write('\n', 5, False)
108     # Call the system function that do the extraction in git mode
109     retcode = src.system.git_extract(repo_git,
110                                  module_info.git_info.tag,
111                                  source_dir, logger)
112     return retcode
113
114 def get_sources_from_archive(module_info, source_dir, logger):
115     '''The method called if the module is to be get in archive mode
116     
117     :param module_info Config: The configuration specific to 
118                                the module to be prepared
119     :param source_dir Path: The Path instance corresponding to the 
120                             directory where to put the sources
121     :param logger Logger: The logger instance to use for the display and logging
122     :return: True if it succeed, else False
123     :rtype: boolean
124     '''
125     # check archive exists
126     if not os.path.exists(module_info.archive_info.archive_name):
127         raise src.SatException(_("Archive not found: '%s'") % 
128                                module_info.archive_info.archive_name)
129
130     logger.write('arc:%s ... ' % 
131                  src.printcolors.printcInfo(module_info.archive_info.archive_name),
132                  3, 
133                  False)
134     logger.flush()
135     # Call the system function that do the extraction in archive mode
136     retcode, NameExtractedDirectory = src.system.archive_extract(
137                                     module_info.archive_info.archive_name,
138                                     source_dir.dir(), logger)
139     
140     # Rename the source directory if 
141     # it does not match with module_info.source_dir
142     if (NameExtractedDirectory.replace('/', '') != 
143             os.path.basename(module_info.source_dir)):
144         shutil.move(os.path.join(os.path.dirname(module_info.source_dir), 
145                                  NameExtractedDirectory), 
146                     module_info.source_dir)
147     
148     return retcode
149
150 def get_sources_from_cvs(user, module_info, source_dir, checkout, logger, pad):
151     '''The method called if the module is to be get in cvs mode
152     
153     :param user str: The user to use in for the cvs command
154     :param module_info Config: The configuration specific to 
155                                the module to be prepared
156     :param source_dir Path: The Path instance corresponding to the 
157                             directory where to put the sources
158     :param checkout boolean: If True, get the source in checkout mode
159     :param logger Logger: The logger instance to use for the display and logging
160     :param pad int: The gap to apply for the terminal display
161     :return: True if it succeed, else False
162     :rtype: boolean
163     '''
164     # Get the protocol to use in the command
165     if "protocol" in module_info.cvs_info:
166         protocol = module_info.cvs_info.protocol
167     else:
168         protocol = "pserver"
169     
170     # Construct the line to display
171     if "protocol" in module_info.cvs_info:
172         cvs_line = "%s:%s@%s:%s" % \
173             (protocol, user, module_info.cvs_info.server, 
174              module_info.cvs_info.module_base)
175     else:
176         cvs_line = "%s / %s" % (module_info.cvs_info.server, 
177                                 module_info.cvs_info.module_base)
178
179     coflag = 'cvs'
180     if checkout: coflag = src.printcolors.printcHighlight(coflag.upper())
181
182     logger.write('%s:%s' % (coflag, src.printcolors.printcInfo(cvs_line)), 
183                  3, 
184                  False)
185     logger.write(' ' * (pad + 50 - len(cvs_line)), 3, False)
186     logger.write(' src:%s' % 
187                  src.printcolors.printcInfo(module_info.cvs_info.source), 
188                  3, 
189                  False)
190     logger.write(' ' * (pad + 1 - len(module_info.cvs_info.source)), 3, False)
191     logger.write(' tag:%s' % 
192                     src.printcolors.printcInfo(module_info.cvs_info.tag), 
193                  3, 
194                  False)
195     # at least one '.' is visible
196     logger.write(' %s. ' % ('.' * (10 - len(module_info.cvs_info.tag))), 
197                  3, 
198                  False) 
199     logger.flush()
200     logger.write('\n', 5, False)
201
202     # Call the system function that do the extraction in cvs mode
203     retcode = src.system.cvs_extract(protocol, user,
204                                  module_info.cvs_info.server,
205                                  module_info.cvs_info.module_base,
206                                  module_info.cvs_info.tag,
207                                  module_info.cvs_info.source,
208                                  source_dir, logger, checkout)
209     return retcode
210
211 def get_sources_from_svn(user, module_info, source_dir, checkout, logger):
212     '''The method called if the module is to be get in svn mode
213     
214     :param user str: The user to use in for the svn command
215     :param module_info Config: The configuration specific to 
216                                the module to be prepared
217     :param source_dir Path: The Path instance corresponding to the 
218                             directory where to put the sources
219     :param checkout boolean: If True, get the source in checkout mode
220     :param logger Logger: The logger instance to use for the display and logging
221     :return: True if it succeed, else False
222     :rtype: boolean
223     '''
224     coflag = 'svn'
225     if checkout: coflag = src.printcolors.printcHighlight(coflag.upper())
226
227     logger.write('%s:%s ... ' % (coflag, 
228                                  src.printcolors.printcInfo(
229                                             module_info.svn_info.repo)), 
230                  3, 
231                  False)
232     logger.flush()
233     logger.write('\n', 5, False)
234     # Call the system function that do the extraction in svn mode
235     retcode = src.system.svn_extract(user, 
236                                      module_info.svn_info.repo, 
237                                      module_info.svn_info.tag,
238                                      source_dir, 
239                                      logger, 
240                                      checkout)
241     return retcode
242
243 def get_sources_from_dir(module_info, source_dir, logger):
244     '''The method called if the module is to be get in dir mode
245     
246     :param module_info Config: The configuration specific to 
247                                the module to be prepared
248     :param source_dir Path: The Path instance corresponding to the 
249                             directory where to put the sources
250     :param logger Logger: The logger instance to use for the display and logging
251     :return: True if it succeed, else False
252     :rtype: boolean
253     '''
254     # Check if it is a symlink?
255     use_link = ('symlink' in module_info.dir_info and 
256                 module_info.dir_info.symlink)
257     dirflag = 'dir'
258     if use_link: dirflag = 'lnk'
259
260     # check that source exists if it is not a symlink
261     if (not use_link) and (not os.path.exists(module_info.dir_info.dir)):
262         raise src.SatException(_("Source directory not found: '%s'") % 
263                                module_info.dir_info.dir)
264
265     logger.write('%s:%s ... ' % 
266                  (dirflag, src.printcolors.printcInfo(module_info.dir_info.dir)),
267                  3, 
268                  False)
269     logger.flush()
270
271     if use_link:
272         retcode = src.Path(source_dir).symlink(module_info.dir_info.dir)
273     else:
274         retcode = src.Path(module_info.dir_info.dir).copy(source_dir)
275
276     return retcode
277
278 def get_module_sources(config, 
279                        module_info, 
280                        is_dev, 
281                        source_dir,
282                        force,
283                        logger, 
284                        pad, 
285                        checkout=False):
286     '''Get the module sources.
287     
288     :param config Config: The global configuration
289     :param module_info Config: The configuration specific to 
290                                the module to be prepared
291     :param is_dev boolean: True if the module is in development mode
292     :param source_dir Path: The Path instance corresponding to the 
293                             directory where to put the sources
294     :param force boolean: True if the --force option was invoked
295     :param logger Logger: The logger instance to use for the display and logging
296     :param pad int: The gap to apply for the terminal display
297     :param checkout boolean: If True, get the source in checkout mode
298     :return: True if it succeed, else False
299     :rtype: boolean
300     '''
301     if not checkout and is_dev:
302         return get_sources_for_dev(config, 
303                                    module_info, 
304                                    source_dir, 
305                                    force, 
306                                    logger, 
307                                    pad)
308
309     if module_info.get_method == "git":
310         return get_sources_from_git(module_info, source_dir, logger, pad, 
311                                     is_dev)
312
313     if module_info.get_method == "archive":
314         return get_sources_from_archive(module_info, source_dir, logger)
315     
316     if module_info.get_method == "cvs":
317         cvs_user = config.USER.cvs_user
318         return get_sources_from_cvs(cvs_user, 
319                                     module_info, 
320                                     source_dir, 
321                                     checkout, 
322                                     logger,
323                                     pad)
324
325     if module_info.get_method == "svn":
326         svn_user = config.USER.svn_user
327         return get_sources_from_svn(svn_user, module_info, source_dir, 
328                                     checkout,
329                                     logger)
330    
331     if module_info.get_method == "dir":
332         return get_sources_from_dir(module_info, source_dir, logger)
333     
334     if len(module_info.get_method) == 0:
335         # skip
336         logger.write('%s ...' % _("ignored"), 3, False)
337         return True
338
339     # if the get_method is not in [git, archive, cvs, svn, dir]
340     logger.write(_("Unknown get_mehtod %(get)s for module %(module)s") % \
341         { 'get': module_info.get_method, 'module': module_info.name }, 3, False)
342     logger.write(" ... ", 3, False)
343     logger.flush()
344     return False
345
346 def get_all_module_sources(config, modules, force, logger):
347     '''Get all the module sources.
348     
349     :param config Config: The global configuration
350     :param modules List: The list of tuples (module name, module informations)
351     :param force boolean: True if the --force option was invoked
352     :param logger Logger: The logger instance to be used for the logging
353     :return: the tuple (number of success, dictionary module_name/success_fail)
354     :rtype: (int,dict)
355     '''
356
357     # Initialize the variables that will count the fails and success
358     results = dict()
359     good_result = 0
360
361     # Get the maximum name length in order to format the terminal display
362     max_module_name_len = 1
363     if len(modules) > 0:
364         max_module_name_len = max(map(lambda l: len(l), modules[0])) + 4
365     
366     # The loop on all the modules from which to get the sources
367     for module_name, module_info in modules:
368         # get module name, module informations and the directory where to put
369         # the sources
370         source_dir = src.Path(module_info.source_dir)
371
372         # display and log
373         logger.write('%s: ' % src.printcolors.printcLabel(module_name), 3)
374         logger.write(' ' * (max_module_name_len - len(module_name)), 3, False)
375         logger.write("\n", 4, False)
376         
377         # Remove the existing source directory if 
378         # the module is not in development mode 
379         is_dev = ("dev_modules" in config.APPLICATION and 
380                   module_name in config.APPLICATION.dev_modules)
381         if source_dir.exists() and not is_dev:
382             logger.write("  " + _('remove %s') % source_dir, 4)
383             logger.write("\n  ", 4, False)
384             source_dir.rm()
385
386         # Call to the function that get the sources for one module
387         retcode = get_module_sources(config, 
388                                      module_info, 
389                                      is_dev, 
390                                      source_dir,
391                                      force, 
392                                      logger, 
393                                      max_module_name_len, 
394                                      checkout=False)
395         
396         '''
397         if 'no_rpath' in module_info.keys():
398             if module_info.no_rpath:
399                 hack_no_rpath(config, module_info, logger)
400         '''
401
402         # show results
403         results[module_name] = retcode
404         if retcode == 'N\A':
405             # The case where the module was not prepared because it is 
406             # in development mode
407             res =(src.printcolors.printc(src.OK_STATUS) + 
408                     src.printcolors.printcWarning(_(
409                                     ' source directory already exists')))
410             good_result = good_result + 1
411         elif retcode:
412             # The case where it succeed
413             res = src.OK_STATUS
414             good_result = good_result + 1
415         else:
416             # The case where it failed
417             res = src.KO_STATUS
418         
419         # print the result
420         logger.write('%s\n' % src.printcolors.printc(res), 3, False)
421
422     return good_result, results
423
424 def description():
425     '''method that is called when salomeTools is called with --help option.
426     
427     :return: The text to display for the source command description.
428     :rtype: str
429     '''
430     return _("The source command gets the sources of the application modules "
431              "from cvs, git, an archive or a directory..")
432   
433 def run(args, runner, logger):
434     '''method that is called when salomeTools is called with source parameter.
435     '''
436     # Parse the options
437     (options, args) = parser.parse_args(args)
438     
439     # check that the command has been called with an application
440     src.check_config_has_application( runner.cfg )
441
442     # Print some informations
443     logger.write(_('Getting sources of the application %s\n') % 
444                 src.printcolors.printcLabel(runner.cfg.VARS.application), 1)
445     src.printcolors.print_value(logger, 'out_dir', 
446                                 runner.cfg.APPLICATION.out_dir, 2)
447     logger.write("\n", 2, False)
448     
449     # Get the force option if it was passed
450     force = options.force
451     if force:
452         msg = _("Warning: the --force option has effect only "
453                 "on modules in development mode\n\n")
454         logger.write(src.printcolors.printcWarning(msg))
455     
456     # Get the modules to be prepared, regarding the options
457     if options.modules is None:
458         # No options, get all modules sources
459         modules = runner.cfg.APPLICATION.modules
460     else:
461         # if option --modules, check that all modules of the command line
462         # are present in the application.
463         modules = options.modules
464         for m in modules:
465             if m not in runner.cfg.APPLICATION.modules:
466                 raise src.SatException(_("Module %(module)s "
467                             "not defined in application %(application)s") %
468                 { 'module': m, 'application': runner.cfg.VARS.application} )
469     
470     # Construct the list of tuple containing 
471     # the modules name and their definition
472     modules_infos = src.module.get_modules_infos(modules, runner.cfg)
473
474     # if the --no_sample option is invoked, suppress the sample modules from 
475     # the list
476     if options.no_sample:
477         
478         lmodules_sample = [m for m in modules_infos if src.module.module_is_sample(m[1])]
479         
480         modules_infos = [m for m in modules_infos if m not in lmodules_sample]
481
482         if len(lmodules_sample) > 0:
483             logger.write(src.printcolors.printcWarning(_("Ignoring the following sample modules:\n")), 1)
484         for i, module in enumerate(lmodules_sample):
485             end_text = ', '
486             if i+1 == len(lmodules_sample):
487                 end_text = '\n'
488                 
489             logger.write(module[0] + end_text, 1)
490
491     # Call to the function that gets all the sources
492     good_result, results = get_all_module_sources(runner.cfg, 
493                                                   modules_infos,
494                                                   force,
495                                                   logger)
496
497     # Display the results (how much passed, how much failed, etc...)
498     status = src.OK_STATUS
499     details = []
500
501     logger.write("\n", 2, False)
502     if good_result == len(modules_infos):
503         res_count = "%d / %d" % (good_result, good_result)
504     else:
505         status = src.KO_STATUS
506         res_count = "%d / %d" % (good_result, len(modules))
507
508         for module in results:
509             if results[module] == 0 or results[module] is None:
510                 details.append(module)
511
512     result = len(modules_infos) - good_result
513
514     # write results
515     logger.write(_("Getting sources of the application:"), 1)
516     logger.write(" " + src.printcolors.printc(status), 1, False)
517     logger.write(" (%s)\n" % res_count, 1, False)
518
519     if len(details) > 0:
520         logger.write(_("Following sources haven't been get:\n"), 2)
521         logger.write(" ".join(details), 2)
522         logger.write("\n", 2, False)
523
524     return result