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