Salome HOME
Fix: add missing import gettext as _
[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 from gettext import gettext as _
21
22 import src
23 import source
24 import src.debug as DBG
25
26 # Define all possible option for patch command :  sat patch <options>
27 parser = src.options.Options()
28 parser.add_option(
29     "p",
30     "products",
31     "list2",
32     "products",
33     _(
34         "Optional: products from which to get the sources. This option accepts a comma separated list."
35     ),
36 )
37
38
39 def update_source_for_dev(config, product_info, source_dir, logger, pad):
40     """The method called if the product is in development mode
41
42     :param config Config: The global configuration
43     :param product_info Config: The configuration specific to
44                                the product to be prepared
45     :param source_dir Path: The Path instance corresponding to the
46                             directory where to put the sources
47     :param logger Logger: The logger instance to use for the display and logging
48     :param pad int: The gap to apply for the terminal display
49     :return: True if it succeed, else False
50     :rtype: boolean
51     """
52
53     # Call the function corresponding to get the sources with True checkout
54     retcode = update_product_sources(
55         config, product_info, True, source_dir, logger, pad, checkout=True
56     )
57     logger.write("\n", 3, False)
58     # +2 because product name is followed by ': '
59     logger.write(" " * (pad + 2), 3, False)
60
61     logger.write(
62         "dev: %s ... " % src.printcolors.printcInfo(product_info.source_dir), 3, False
63     )
64     logger.flush()
65
66     return retcode
67
68
69 def update_source_from_git(
70     config, product_info, source_dir, logger, pad, is_dev=False, environ=None
71 ):
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 (
91         "APPLICATION" in config
92         and "properties" in config.APPLICATION
93         and "repo_dev" in config.APPLICATION.properties
94         and config.APPLICATION.properties.repo_dev == "yes"
95     ):
96         use_repo_dev = True
97
98     # Get the repository address.
99     # If the application has the repo_dev property
100     # Or if the product is in dev mode
101     # Then we use repo_dev if the key exists
102     if (is_dev or use_repo_dev) and "repo_dev" in product_info.git_info:
103         coflag = src.printcolors.printcHighlight(coflag.upper())
104         repo_git = product_info.git_info.repo_dev
105     else:
106         repo_git = product_info.git_info.repo
107
108     # Display informations
109     logger.write("%s:%s" % (coflag, src.printcolors.printcInfo(repo_git)), 3, False)
110     logger.write(" " * (pad + 50 - len(repo_git)), 3, False)
111     logger.write(
112         " tag:%s" % src.printcolors.printcInfo(product_info.git_info.tag), 3, False
113     )
114     logger.write(" %s. " % ("." * (10 - len(product_info.git_info.tag))), 3, False)
115     logger.flush()
116     logger.write("\n", 5, False)
117
118     git_options = ""
119     if "git_options" in product_info.git_info:
120         git_options = product_info.git_info.git_options
121
122     # Call the system function that do the checkout in git mode
123     retcode = src.system.git_checkout(
124         product_info.git_info.tag,
125         git_options,
126         source_dir,
127         logger,
128         environ,
129     )
130     if not retcode:
131         logger.write(
132             r"""
133 Error, %(repo)s could not checkout %(branch)s. Please check you don't
134 have uncommited work and branch or tag %(branch)s exists."""
135             % {"repo": repo_git, "branch": product_info.git_info.tag}
136         )
137         raise Exception()
138
139     # Call the system function that do the checkout in git mode
140     retcode = src.system.git_pull(
141         repo_git,
142         product_info.git_info.tag,
143         git_options,
144         source_dir,
145         logger,
146         environ,
147     )
148     if not retcode:
149         logger.write(
150             r"""
151 Error, %(repo)s could not pull branch %(branch)s. Please check that your branch
152 has not diverged from repo."""
153             % {"repo": repo_git, "branch": product_info.git_info.tag}
154         )
155         raise Exception()
156     return retcode
157
158
159 def update_product_sources(
160     config, product_info, is_dev, source_dir, logger, pad, checkout=False
161 ):
162     """Get the product sources.
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 is_dev boolean: True if the product is in development mode
168     :param source_dir Path: The Path instance corresponding to the
169                             directory where to put the sources
170     :param logger Logger: The logger instance to use for the display and logging
171     :param pad int: The gap to apply for the terminal display
172     :param checkout boolean: If True, get the source in checkout mode
173     :return: True if it succeed, else False
174     :rtype: boolean
175     """
176
177     # Get the application environment
178     logger.write(_("Set the application environment\n"), 5)
179     env_appli = src.environment.SalomeEnviron(
180         config, src.environment.Environ(dict(os.environ))
181     )
182     env_appli.set_application_env(logger)
183
184     # Call the right function to get sources regarding the product settings
185     if not checkout and is_dev:
186         return source.get_source_for_dev(config, product_info, source_dir, logger, pad)
187
188     if product_info.get_source == "git":
189         return update_source_from_git(
190             config, product_info, source_dir, logger, pad, is_dev, env_appli
191         )
192
193     if product_info.get_source == "archive":
194         return source.get_source_from_archive(config, product_info, source_dir, logger)
195
196     if product_info.get_source == "dir":
197         return source.get_source_from_dir(product_info, source_dir, logger)
198
199     if product_info.get_source == "cvs":
200         cvs_user = config.USER.cvs_user
201         return source.get_source_from_cvs(
202             cvs_user, product_info, source_dir, checkout, logger, pad, env_appli
203         )
204
205     if product_info.get_source == "svn":
206         svn_user = config.USER.svn_user
207         return source.get_source_from_svn(
208             svn_user, product_info, source_dir, checkout, logger, env_appli
209         )
210
211     if product_info.get_source == "native":
212         # for native products we check the corresponding system packages are installed
213         logger.write("Native : Checking system packages are installed\n", 3)
214         check_cmd = src.system.get_pkg_check_cmd(
215             config.VARS.dist_name
216         )  # (either rmp or apt)
217         run_pkg, build_pkg = src.product.check_system_dep(
218             config.VARS.dist, check_cmd, product_info
219         )
220         result = True
221         for pkg in run_pkg:
222             logger.write(" - " + pkg + " : " + run_pkg[pkg] + "\n", 1)
223             if "KO" in run_pkg[pkg]:
224                 result = False
225         for pkg in build_pkg:
226             logger.write(" - " + pkg + " : " + build_pkg[pkg] + "\n", 1)
227             if "KO" in build_pkg[pkg]:
228                 result = False
229         if not result:
230             logger.error(
231                 "some system dependencies are missing, please install them with "
232                 + check_cmd[0]
233             )
234         return result
235
236     if product_info.get_source == "fixed":
237         # skip
238         logger.write("%s  " % src.printcolors.printc(src.OK_STATUS), 3, False)
239         msg = "FIXED : %s\n" % product_info.install_dir
240
241         if not os.path.isdir(product_info.install_dir):
242             logger.warning(
243                 "The fixed path do not exixts!! Please check it : %s\n"
244                 % product_info.install_dir
245             )
246         else:
247             logger.write(msg, 3)
248         return True
249
250     # if the get_source is not in [git, archive, cvs, svn, fixed, native]
251     logger.write(
252         _('Unknown get source method "%(get)s" for product %(product)s')
253         % {"get": product_info.get_source, "product": product_info.name},
254         3,
255         False,
256     )
257     logger.write(" ... ", 3, False)
258     logger.flush()
259     return False
260
261
262 def update_all_product_sources(config, products, logger):
263     """Update/get all the product sources.
264
265     :param config Config: The global configuration
266     :param products List: The list of tuples (product name, product informations)
267     :param logger Logger: The logger instance to be used for the logging
268     :return: the tuple (number of success, dictionary product_name/success_fail)
269     :rtype: (int,dict)
270     """
271
272     # Initialize the variables that will count the fails and success
273     results = dict()
274     good_result = 0
275
276     # Get the maximum name length in order to format the terminal display
277     max_product_name_len = 1
278     if len(products) > 0:
279         max_product_name_len = max(map(lambda lgth: len(lgth), products[0])) + 4
280
281     # The loop on all the products from which to get the sources
282     # DBG.write("source.get_all_product_sources config id", id(config), True)
283     for product_name, product_info in products:
284         # get product name, product informations and the directory where to put
285         # the sources
286         if not (
287             src.product.product_is_fixed(product_info)
288             or src.product.product_is_native(product_info)
289         ):
290             source_dir = src.Path(product_info.source_dir)
291         else:
292             source_dir = src.Path("")
293
294         # display and log
295         logger.write("%s: " % src.printcolors.printcLabel(product_name), 3)
296         logger.write(" " * (max_product_name_len - len(product_name)), 3, False)
297         logger.write("\n", 4, False)
298
299         is_dev = src.product.product_is_dev(product_info)
300         # Call to the function that get the sources for one product
301         retcode = update_product_sources(
302             config,
303             product_info,
304             is_dev,
305             source_dir,
306             logger,
307             max_product_name_len,
308             checkout=False,
309         )
310
311         # Check that the sources are correctly get using the files to be tested
312         # in product information
313         if retcode:
314             check_OK, wrong_path = check_sources(product_info, logger)
315             if not check_OK:
316                 # Print the missing file path
317                 msg = _("The required file %s does not exists. " % wrong_path)
318                 logger.write(src.printcolors.printcError("\nERROR: ") + msg, 3)
319                 retcode = False
320
321         # show results
322         results[product_name] = retcode
323         if retcode:
324             # The case where it succeed
325             res = src.OK_STATUS
326             good_result = good_result + 1
327         else:
328             # The case where it failed
329             res = src.KO_STATUS
330
331         # print the result
332         if not (
333             src.product.product_is_fixed(product_info)
334             or src.product.product_is_native(product_info)
335         ):
336             logger.write("%s\n" % src.printcolors.printc(res), 3, False)
337
338     return good_result, results
339
340
341 def check_sources(product_info, logger):
342     """Check that the sources are correctly get, using the files to be tested
343        in product information
344
345     :param product_info Config: The configuration specific to
346                                 the product to be prepared
347     :return: True if the files exists (or no files to test is provided).
348     :rtype: boolean
349     """
350     # Get the files to test if there is any
351     if "present_files" in product_info and "source" in product_info.present_files:
352         l_files_to_be_tested = product_info.present_files.source
353         for file_path in l_files_to_be_tested:
354             # The path to test is the source directory
355             # of the product joined the file path provided
356             path_to_test = os.path.join(product_info.source_dir, file_path)
357             logger.write(_("\nTesting existence of file: \n"), 5)
358             logger.write(path_to_test, 5)
359             if not os.path.exists(path_to_test):
360                 return False, path_to_test
361             logger.write(src.printcolors.printcSuccess(" OK\n"), 5)
362     return True, ""
363
364
365 def description():
366     """method that is called when salomeTools is called with --help option.
367
368     :return: The text to display for the source command description.
369     :rtype: str
370     """
371     return _(
372         "The source command gets the sources of the application products "
373         "from cvs, git or an archive.\n\nexample:"
374         "\nsat source SALOME-master --products KERNEL,GUI"
375     )
376
377
378 def run(args, runner, logger):
379     """method that is called when salomeTools is called with source parameter."""
380     DBG.write("source.run()", args)
381     # Parse the options
382     (options, args) = parser.parse_args(args)
383
384     # check that the command has been called with an application
385     src.check_config_has_application(runner.cfg)
386
387     # Print some informations
388     logger.write(
389         _("Getting sources of the application %s\n")
390         % src.printcolors.printcLabel(runner.cfg.VARS.application),
391         1,
392     )
393     src.printcolors.print_value(logger, "workdir", runner.cfg.APPLICATION.workdir, 2)
394     logger.write("\n", 2, False)
395
396     # Get the products list with products informations regarding the options
397     products_infos = src.product.get_products_list(options, runner.cfg, logger)
398
399     # Call to the function that gets all the sources
400     good_result, results = update_all_product_sources(runner.cfg, products_infos, logger)
401
402     # Display the results (how much passed, how much failed, etc...)
403     status = src.OK_STATUS
404     details = []
405
406     logger.write("\n", 2, False)
407     if good_result == len(products_infos):
408         res_count = "%d / %d" % (good_result, good_result)
409     else:
410         status = src.KO_STATUS
411         res_count = "%d / %d" % (good_result, len(products_infos))
412
413         for product in results:
414             if results[product] == 0 or results[product] is None:
415                 details.append(product)
416
417     result = len(products_infos) - good_result
418
419     # write results
420     logger.write(_("Getting sources of the application:"), 1)
421     logger.write(" " + src.printcolors.printc(status), 1, False)
422     logger.write(" (%s)\n" % res_count, 1, False)
423
424     if len(details) > 0:
425         logger.write(_("Following sources haven't been get:\n"), 2)
426         logger.write(" ".join(details), 2)
427         logger.write("\n", 2, False)
428
429     return result