Salome HOME
83c037a03467924f8ef897e51b8b5d7ed0a83b73
[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 import re
22
23 import src
24 import prepare
25 import src.debug as DBG
26
27 # Define all possible option for patch command :  sat patch <options>
28 parser = src.options.Options()
29 parser.add_option('p', 'products', 'list2', 'products',
30     _('Optional: products from which to get the sources. This option can be'
31     ' passed several time to get the sources of several products.'))
32 parser.add_option('', 'properties', 'string', 'properties',
33     _('Optional: Filter the products by their properties.\n\tSyntax: '
34       '--properties <property>:<value>'))
35
36 def get_source_for_dev(config, product_info, source_dir, logger, pad):
37     '''The method called if the product is in development mode
38     
39     :param config Config: The global configuration
40     :param product_info Config: The configuration specific to 
41                                the product to be prepared
42     :param source_dir Path: The Path instance corresponding to the 
43                             directory where to put the sources
44     :param logger Logger: The logger instance to use for the display and logging
45     :param pad int: The gap to apply for the terminal display
46     :return: True if it succeed, else False
47     :rtype: boolean
48     '''
49        
50     # Call the function corresponding to get the sources with True checkout
51     retcode = get_product_sources(config, 
52                                  product_info, 
53                                  True, 
54                                  source_dir,
55                                  logger, 
56                                  pad, 
57                                  checkout=True)
58     logger.write("\n", 3, False)
59     # +2 because product name is followed by ': '
60     logger.write(" " * (pad+2), 3, False) 
61     
62     logger.write('dev: %s ... ' % 
63                  src.printcolors.printcInfo(product_info.source_dir), 3, False)
64     logger.flush()
65     
66     return retcode
67
68 def get_source_from_git(product_info,
69                         source_dir,
70                         logger,
71                         pad,
72                         is_dev=False,
73                         environ = None):
74     '''The method called if the product is to be get in git mode
75     
76     :param product_info Config: The configuration specific to 
77                                the product to be prepared
78     :param source_dir Path: The Path instance corresponding to the 
79                             directory where to put the sources
80     :param logger Logger: The logger instance to use for the display and logging
81     :param pad int: The gap to apply for the terminal display
82     :param is_dev boolean: True if the product is in development mode
83     :param environ src.environment.Environ: The environment to source when
84                                                 extracting.
85     :return: True if it succeed, else False
86     :rtype: boolean
87     '''
88     # The str to display
89     coflag = 'git'
90
91     # Get the repository address. (from repo_dev key if the product is 
92     # in dev mode.
93     if is_dev and 'repo_dev' in product_info.git_info:
94         coflag = src.printcolors.printcHighlight(coflag.upper())
95         repo_git = product_info.git_info.repo_dev    
96     else:
97         repo_git = product_info.git_info.repo    
98         
99     # Display informations
100     logger.write('%s:%s' % (coflag, src.printcolors.printcInfo(repo_git)), 3, 
101                  False)
102     logger.write(' ' * (pad + 50 - len(repo_git)), 3, False)
103     logger.write(' tag:%s' % src.printcolors.printcInfo(
104                                                     product_info.git_info.tag), 
105                  3,
106                  False)
107     logger.write(' %s. ' % ('.' * (10 - len(product_info.git_info.tag))), 3, 
108                  False)
109     logger.flush()
110     logger.write('\n', 5, False)
111
112     sub_dir = None
113     if not is_dev and "sub_dir" in product_info.git_info:
114         sub_dir = product_info.git_info.sub_dir
115
116     if sub_dir  is None:
117       # Call the system function that do the extraction in git mode
118       retcode = src.system.git_extract(repo_git,
119                                    product_info.git_info.tag,
120                                    source_dir, logger, environ)
121     else:
122       # Call the system function that do the extraction of a sub_dir in git mode
123       logger.write("sub_dir:%s " % sub_dir, 3)
124       retcode = src.system.git_extract_sub_dir(repo_git,
125                                    product_info.git_info.tag,
126                                    source_dir, sub_dir, logger, environ)
127
128
129     return retcode
130
131 def get_source_from_archive(product_info, source_dir, logger):
132     '''The method called if the product is to be get in archive mode
133     
134     :param product_info Config: The configuration specific to 
135                                the product to be prepared
136     :param source_dir Path: The Path instance corresponding to the 
137                             directory where to put the sources
138     :param logger Logger: The logger instance to use for the display and logging
139     :return: True if it succeed, else False
140     :rtype: boolean
141     '''
142     # check archive exists
143     if not os.path.exists(product_info.archive_info.archive_name):
144         raise src.SatException(_("Archive not found in config.PATHS.ARCHIVEPATH: '%s'") % 
145                                product_info.archive_info.archive_name)
146
147     logger.write('arc:%s ... ' % 
148                  src.printcolors.printcInfo(product_info.archive_info.archive_name),
149                  3, 
150                  False)
151     logger.flush()
152     # Call the system function that do the extraction in archive mode
153     retcode, NameExtractedDirectory = src.system.archive_extract(
154                                     product_info.archive_info.archive_name,
155                                     source_dir.dir(), logger)
156     
157     # Rename the source directory if 
158     # it does not match with product_info.source_dir
159     if (NameExtractedDirectory.replace('/', '') != 
160             os.path.basename(product_info.source_dir)):
161         shutil.move(os.path.join(os.path.dirname(product_info.source_dir), 
162                                  NameExtractedDirectory), 
163                     product_info.source_dir)
164     
165     return retcode
166
167 def get_source_from_dir(product_info, source_dir, logger):
168     
169     if "dir_info" not in product_info:
170         msg = _("Error: you must put a dir_info section"
171                 " in the file %s.pyconf" % product_info.name)
172         logger.write("\n%s\n" % src.printcolors.printcError(msg), 1)
173         return False
174
175     if "dir" not in product_info.dir_info:
176         msg = _("Error: you must put a dir in the dir_info section"
177                 " in the file %s.pyconf" % product_info.name)
178         logger.write("\n%s\n" % src.printcolors.printcError(msg), 1)
179         return False
180
181     # check that source exists
182     if not os.path.exists(product_info.dir_info.dir):
183         msg = _("Error: the dir %s defined in the file"
184                 " %s.pyconf does not exists" % (product_info.dir_info.dir,
185                                                 product_info.name))
186         logger.write("\n%s\n" % src.printcolors.printcError(msg), 1)
187         return False
188     
189     logger.write('DIR: %s ... ' % src.printcolors.printcInfo(
190                                            product_info.dir_info.dir), 3)
191     logger.flush()
192
193     retcode = src.Path(product_info.dir_info.dir).copy(source_dir)
194     
195     return retcode
196     
197 def get_source_from_cvs(user,
198                         product_info,
199                         source_dir,
200                         checkout,
201                         logger,
202                         pad,
203                         environ = None):
204     '''The method called if the product is to be get in cvs mode
205     
206     :param user str: The user to use in for the cvs command
207     :param product_info Config: The configuration specific to 
208                                the product to be prepared
209     :param source_dir Path: The Path instance corresponding to the 
210                             directory where to put the sources
211     :param checkout boolean: If True, get the source in checkout mode
212     :param logger Logger: The logger instance to use for the display and logging
213     :param pad int: The gap to apply for the terminal display
214     :param environ src.environment.Environ: The environment to source when
215                                                 extracting.
216     :return: True if it succeed, else False
217     :rtype: boolean
218     '''
219     # Get the protocol to use in the command
220     if "protocol" in product_info.cvs_info:
221         protocol = product_info.cvs_info.protocol
222     else:
223         protocol = "pserver"
224     
225     # Construct the line to display
226     if "protocol" in product_info.cvs_info:
227         cvs_line = "%s:%s@%s:%s" % \
228             (protocol, user, product_info.cvs_info.server, 
229              product_info.cvs_info.product_base)
230     else:
231         cvs_line = "%s / %s" % (product_info.cvs_info.server, 
232                                 product_info.cvs_info.product_base)
233
234     coflag = 'cvs'
235     if checkout: coflag = src.printcolors.printcHighlight(coflag.upper())
236
237     logger.write('%s:%s' % (coflag, src.printcolors.printcInfo(cvs_line)), 
238                  3, 
239                  False)
240     logger.write(' ' * (pad + 50 - len(cvs_line)), 3, False)
241     logger.write(' src:%s' % 
242                  src.printcolors.printcInfo(product_info.cvs_info.source), 
243                  3, 
244                  False)
245     logger.write(' ' * (pad + 1 - len(product_info.cvs_info.source)), 3, False)
246     logger.write(' tag:%s' % 
247                     src.printcolors.printcInfo(product_info.cvs_info.tag), 
248                  3, 
249                  False)
250     # at least one '.' is visible
251     logger.write(' %s. ' % ('.' * (10 - len(product_info.cvs_info.tag))), 
252                  3, 
253                  False) 
254     logger.flush()
255     logger.write('\n', 5, False)
256
257     # Call the system function that do the extraction in cvs mode
258     retcode = src.system.cvs_extract(protocol, user,
259                                  product_info.cvs_info.server,
260                                  product_info.cvs_info.product_base,
261                                  product_info.cvs_info.tag,
262                                  product_info.cvs_info.source,
263                                  source_dir, logger, checkout, environ)
264     return retcode
265
266 def get_source_from_svn(user,
267                         product_info,
268                         source_dir,
269                         checkout,
270                         logger,
271                         environ = None):
272     '''The method called if the product is to be get in svn mode
273     
274     :param user str: The user to use in for the svn command
275     :param product_info Config: The configuration specific to 
276                                the product to be prepared
277     :param source_dir Path: The Path instance corresponding to the 
278                             directory where to put the sources
279     :param checkout boolean: If True, get the source in checkout mode
280     :param logger Logger: The logger instance to use for the display and logging
281     :param environ src.environment.Environ: The environment to source when
282                                                 extracting.
283     :return: True if it succeed, else False
284     :rtype: boolean
285     '''
286     coflag = 'svn'
287     if checkout: coflag = src.printcolors.printcHighlight(coflag.upper())
288
289     logger.write('%s:%s ... ' % (coflag, 
290                                  src.printcolors.printcInfo(
291                                             product_info.svn_info.repo)), 
292                  3, 
293                  False)
294     logger.flush()
295     logger.write('\n', 5, False)
296     # Call the system function that do the extraction in svn mode
297     retcode = src.system.svn_extract(user, 
298                                      product_info.svn_info.repo, 
299                                      product_info.svn_info.tag,
300                                      source_dir, 
301                                      logger, 
302                                      checkout,
303                                      environ)
304     return retcode
305
306 def get_product_sources(config, 
307                        product_info, 
308                        is_dev, 
309                        source_dir,
310                        logger, 
311                        pad, 
312                        checkout=False):
313     '''Get the product sources.
314     
315     :param config Config: The global configuration
316     :param product_info Config: The configuration specific to 
317                                the product to be prepared
318     :param is_dev boolean: True if the product is in development mode
319     :param source_dir Path: The Path instance corresponding to the 
320                             directory where to put the sources
321     :param logger Logger: The logger instance to use for the display and logging
322     :param pad int: The gap to apply for the terminal display
323     :param checkout boolean: If True, get the source in checkout mode
324     :return: True if it succeed, else False
325     :rtype: boolean
326     '''
327     
328     # Get the application environment
329     logger.write(_("Set the application environment\n"), 5)
330     env_appli = src.environment.SalomeEnviron(config,
331                                       src.environment.Environ(dict(os.environ)))
332     env_appli.set_application_env(logger)
333     
334     # Call the right function to get sources regarding the product settings
335     if not checkout and is_dev:
336         return get_source_for_dev(config, 
337                                    product_info, 
338                                    source_dir, 
339                                    logger, 
340                                    pad)
341
342     if product_info.get_source == "git":
343         return get_source_from_git(product_info, source_dir, logger, pad, 
344                                     is_dev,env_appli)
345
346     if product_info.get_source == "archive":
347         return get_source_from_archive(product_info, source_dir, logger)
348
349     if product_info.get_source == "dir":
350         return get_source_from_dir(product_info, source_dir, logger)
351     
352     if product_info.get_source == "cvs":
353         cvs_user = config.USER.cvs_user
354         return get_source_from_cvs(cvs_user, 
355                                     product_info, 
356                                     source_dir, 
357                                     checkout, 
358                                     logger,
359                                     pad,
360                                     env_appli)
361
362     if product_info.get_source == "svn":
363         svn_user = config.USER.svn_user
364         return get_source_from_svn(svn_user, product_info, source_dir, 
365                                     checkout,
366                                     logger,
367                                     env_appli)
368
369     if product_info.get_source == "native":
370         # skip
371         logger.write('%s  ' % src.printcolors.printc(src.OK_STATUS),
372                      3,
373                      False)
374         msg = _('INFORMATION : Not doing anything because the product'
375                 ' is of type "native".\n')
376         logger.write(msg, 3)
377         return True        
378
379     if product_info.get_source == "fixed":
380         # skip
381         logger.write('%s  ' % src.printcolors.printc(src.OK_STATUS),
382                      3,
383                      False)
384         msg = _('INFORMATION : Not doing anything because the product'
385                 ' is of type "fixed".\n')
386         logger.write(msg, 3)
387         return True  
388
389     # if the get_source is not in [git, archive, cvs, svn, fixed, native]
390     logger.write(_("Unknown get source method \"%(get)s\" for product %(product)s") % \
391         { 'get': product_info.get_source, 'product': product_info.name }, 3, False)
392     logger.write(" ... ", 3, False)
393     logger.flush()
394     return False
395
396 def get_all_product_sources(config, products, logger):
397     '''Get all the product sources.
398     
399     :param config Config: The global configuration
400     :param products List: The list of tuples (product name, product informations)
401     :param logger Logger: The logger instance to be used for the logging
402     :return: the tuple (number of success, dictionary product_name/success_fail)
403     :rtype: (int,dict)
404     '''
405
406     # Initialize the variables that will count the fails and success
407     results = dict()
408     good_result = 0
409
410     # Get the maximum name length in order to format the terminal display
411     max_product_name_len = 1
412     if len(products) > 0:
413         max_product_name_len = max(map(lambda l: len(l), products[0])) + 4
414     
415     # The loop on all the products from which to get the sources
416     # DBG.write("source.get_all_product_sources config id", id(config), True)
417     for product_name, product_info in products:
418         # get product name, product informations and the directory where to put
419         # the sources
420         if (not (src.product.product_is_fixed(product_info) or 
421                  src.product.product_is_native(product_info))):
422             source_dir = src.Path(product_info.source_dir)
423         else:
424             source_dir = src.Path('')
425
426         # display and log
427         logger.write('%s: ' % src.printcolors.printcLabel(product_name), 3)
428         logger.write(' ' * (max_product_name_len - len(product_name)), 3, False)
429         logger.write("\n", 4, False)
430         
431         # Remove the existing source directory if 
432         # the product is not in development mode
433         is_dev = src.product.product_is_dev(product_info)
434         if source_dir.exists():
435             logger.write('%s  ' % src.printcolors.printc(src.OK_STATUS), 3, False)
436             msg = _("INFO : Not doing anything because the source directory already exists:\n    %s\n") % source_dir
437             logger.write(msg, 3)
438             good_result = good_result + 1
439             # Do not get the sources and go to next product
440             continue
441
442         # Call to the function that get the sources for one product
443         retcode = get_product_sources(config, 
444                                      product_info, 
445                                      is_dev, 
446                                      source_dir,
447                                      logger, 
448                                      max_product_name_len, 
449                                      checkout=False)
450         
451         '''
452         if 'no_rpath' in product_info.keys():
453             if product_info.no_rpath:
454                 hack_no_rpath(config, product_info, logger)
455         '''
456         
457         # Check that the sources are correctly get using the files to be tested
458         # in product information
459         if retcode:
460             check_OK, wrong_path = check_sources(product_info, logger)
461             if not check_OK:
462                 # Print the missing file path
463                 msg = _("The required file %s does not exists. " % wrong_path)
464                 logger.write(src.printcolors.printcError("\nERROR: ") + msg, 3)
465                 retcode = False
466
467         # show results
468         results[product_name] = retcode
469         if retcode:
470             # The case where it succeed
471             res = src.OK_STATUS
472             good_result = good_result + 1
473         else:
474             # The case where it failed
475             res = src.KO_STATUS
476         
477         # print the result
478         if not(src.product.product_is_fixed(product_info) or 
479                src.product.product_is_native(product_info)):
480             logger.write('%s\n' % src.printcolors.printc(res), 3, False)
481
482     return good_result, results
483
484 def check_sources(product_info, logger):
485     '''Check that the sources are correctly get, using the files to be tested
486        in product information
487     
488     :param product_info Config: The configuration specific to 
489                                 the product to be prepared
490     :return: True if the files exists (or no files to test is provided).
491     :rtype: boolean
492     '''
493     # Get the files to test if there is any
494     if ("present_files" in product_info and 
495         "source" in product_info.present_files):
496         l_files_to_be_tested = product_info.present_files.source
497         for file_path in l_files_to_be_tested:
498             # The path to test is the source directory 
499             # of the product joined the file path provided
500             path_to_test = os.path.join(product_info.source_dir, file_path)
501             logger.write(_("\nTesting existence of file: \n"), 5)
502             logger.write(path_to_test, 5)
503             if not os.path.exists(path_to_test):
504                 return False, path_to_test
505             logger.write(src.printcolors.printcSuccess(" OK\n"), 5)
506     return True, ""
507
508 def description():
509     '''method that is called when salomeTools is called with --help option.
510     
511     :return: The text to display for the source command description.
512     :rtype: str
513     '''
514     return _("The source command gets the sources of the application products "
515              "from cvs, git or an archive.\n\nexample:"
516              "\nsat source SALOME-master --products KERNEL,GUI")
517   
518 def run(args, runner, logger):
519     '''method that is called when salomeTools is called with source parameter.
520     '''
521     DBG.write("source.run()", args)
522     # Parse the options
523     (options, args) = parser.parse_args(args)
524     
525     # check that the command has been called with an application
526     src.check_config_has_application( runner.cfg )
527
528     # Verify the --properties option
529     if options.properties:
530         oExpr = re.compile(prepare.PROPERTY_EXPRESSION)
531         if not oExpr.search(options.properties):
532             msg = _('WARNING: the "--properties" options must have the '
533                     'following syntax:\n--properties <property>:<value>')
534             logger.write(src.printcolors.printcWarning(msg), 1)
535             logger.write("\n", 1)
536             options.properties = None
537
538     # Print some informations
539     logger.write(_('Getting sources of the application %s\n') % 
540                 src.printcolors.printcLabel(runner.cfg.VARS.application), 1)
541     src.printcolors.print_value(logger, 'workdir', 
542                                 runner.cfg.APPLICATION.workdir, 2)
543     logger.write("\n", 2, False)
544        
545     # Get the products list with products informations regarding the options
546     products_infos = prepare.get_products_list(options, runner.cfg, logger)
547     
548     # Call to the function that gets all the sources
549     good_result, results = get_all_product_sources(runner.cfg, 
550                                                   products_infos,
551                                                   logger)
552
553     # Display the results (how much passed, how much failed, etc...)
554     status = src.OK_STATUS
555     details = []
556
557     logger.write("\n", 2, False)
558     if good_result == len(products_infos):
559         res_count = "%d / %d" % (good_result, good_result)
560     else:
561         status = src.KO_STATUS
562         res_count = "%d / %d" % (good_result, len(products_infos))
563
564         for product in results:
565             if results[product] == 0 or results[product] is None:
566                 details.append(product)
567
568     result = len(products_infos) - good_result
569
570     # write results
571     logger.write(_("Getting sources of the application:"), 1)
572     logger.write(" " + src.printcolors.printc(status), 1, False)
573     logger.write(" (%s)\n" % res_count, 1, False)
574
575     if len(details) > 0:
576         logger.write(_("Following sources haven't been get:\n"), 2)
577         logger.write(" ".join(details), 2)
578         logger.write("\n", 2, False)
579
580     return result