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