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