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