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