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