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