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