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