Salome HOME
sat source: Adding the application environment when getting sources of a 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
22 import src
23 import prepare
24
25 # Define all possible option for patch command :  sat patch <options>
26 parser = src.options.Options()
27 parser.add_option('p', 'products', 'list2', 'products',
28     _('products from which to get the sources. This option can be'
29     ' passed several time to get the sources of several products.'))
30
31 def get_source_for_dev(config, product_info, source_dir, logger, pad):
32     '''The method called if the product is in development mode
33     
34     :param config Config: The global configuration
35     :param product_info Config: The configuration specific to 
36                                the product to be prepared
37     :param source_dir Path: The Path instance corresponding to the 
38                             directory where to put the sources
39     :param logger Logger: The logger instance to use for the display and logging
40     :param pad int: The gap to apply for the terminal display
41     :return: True if it succeed, else False
42     :rtype: boolean
43     '''
44        
45     # Call the function corresponding to get the sources with True checkout
46     retcode = get_product_sources(config, 
47                                  product_info, 
48                                  True, 
49                                  source_dir,
50                                  logger, 
51                                  pad, 
52                                  checkout=True)
53     logger.write("\n", 3, False)
54     # +2 because product name is followed by ': '
55     logger.write(" " * (pad+2), 3, False) 
56     
57     logger.write('dev: %s ... ' % 
58                  src.printcolors.printcInfo(product_info.source_dir), 3, False)
59     logger.flush()
60     
61     return retcode
62
63 def get_source_from_git(product_info,
64                         source_dir,
65                         logger,
66                         pad,
67                         is_dev=False,
68                         environ = None):
69     '''The method called if the product is to be get in git mode
70     
71     :param product_info Config: The configuration specific to 
72                                the product to be prepared
73     :param source_dir Path: The Path instance corresponding to the 
74                             directory where to put the sources
75     :param logger Logger: The logger instance to use for the display and logging
76     :param pad int: The gap to apply for the terminal display
77     :param is_dev boolean: True if the product is in development mode
78     :param environ src.environment.Environ: The environment to source when
79                                                 extracting.
80     :return: True if it succeed, else False
81     :rtype: boolean
82     '''
83     # The str to display
84     coflag = 'git'
85
86     # Get the repository address. (from repo_dev key if the product is 
87     # in dev mode.
88     if is_dev and 'repo_dev' in product_info.git_info:
89         coflag = src.printcolors.printcHighlight(coflag.upper())
90         repo_git = product_info.git_info.repo_dev    
91     else:
92         repo_git = product_info.git_info.repo    
93         
94     # Display informations
95     logger.write('%s:%s' % (coflag, src.printcolors.printcInfo(repo_git)), 3, 
96                  False)
97     logger.write(' ' * (pad + 50 - len(repo_git)), 3, False)
98     logger.write(' tag:%s' % src.printcolors.printcInfo(
99                                                     product_info.git_info.tag), 
100                  3,
101                  False)
102     logger.write(' %s. ' % ('.' * (10 - len(product_info.git_info.tag))), 3, 
103                  False)
104     logger.flush()
105     logger.write('\n', 5, False)
106     # Call the system function that do the extraction in git mode
107     retcode = src.system.git_extract(repo_git,
108                                  product_info.git_info.tag,
109                                  source_dir, logger, environ)
110     return retcode
111
112 def get_source_from_archive(product_info, source_dir, logger):
113     '''The method called if the product is to be get in archive mode
114     
115     :param product_info Config: The configuration specific to 
116                                the product to be prepared
117     :param source_dir Path: The Path instance corresponding to the 
118                             directory where to put the sources
119     :param logger Logger: The logger instance to use for the display and logging
120     :return: True if it succeed, else False
121     :rtype: boolean
122     '''
123     # check archive exists
124     if not os.path.exists(product_info.archive_info.archive_name):
125         raise src.SatException(_("Archive not found: '%s'") % 
126                                product_info.archive_info.archive_name)
127
128     logger.write('arc:%s ... ' % 
129                  src.printcolors.printcInfo(product_info.archive_info.archive_name),
130                  3, 
131                  False)
132     logger.flush()
133     # Call the system function that do the extraction in archive mode
134     retcode, NameExtractedDirectory = src.system.archive_extract(
135                                     product_info.archive_info.archive_name,
136                                     source_dir.dir(), logger)
137     
138     # Rename the source directory if 
139     # it does not match with product_info.source_dir
140     if (NameExtractedDirectory.replace('/', '') != 
141             os.path.basename(product_info.source_dir)):
142         shutil.move(os.path.join(os.path.dirname(product_info.source_dir), 
143                                  NameExtractedDirectory), 
144                     product_info.source_dir)
145     
146     return retcode
147
148 def get_source_from_cvs(user,
149                         product_info,
150                         source_dir,
151                         checkout,
152                         logger,
153                         pad,
154                         environ = None):
155     '''The method called if the product is to be get in cvs mode
156     
157     :param user str: The user to use in for the cvs command
158     :param product_info Config: The configuration specific to 
159                                the product to be prepared
160     :param source_dir Path: The Path instance corresponding to the 
161                             directory where to put the sources
162     :param checkout boolean: If True, get the source in checkout mode
163     :param logger Logger: The logger instance to use for the display and logging
164     :param pad int: The gap to apply for the terminal display
165     :param environ src.environment.Environ: The environment to source when
166                                                 extracting.
167     :return: True if it succeed, else False
168     :rtype: boolean
169     '''
170     # Get the protocol to use in the command
171     if "protocol" in product_info.cvs_info:
172         protocol = product_info.cvs_info.protocol
173     else:
174         protocol = "pserver"
175     
176     # Construct the line to display
177     if "protocol" in product_info.cvs_info:
178         cvs_line = "%s:%s@%s:%s" % \
179             (protocol, user, product_info.cvs_info.server, 
180              product_info.cvs_info.product_base)
181     else:
182         cvs_line = "%s / %s" % (product_info.cvs_info.server, 
183                                 product_info.cvs_info.product_base)
184
185     coflag = 'cvs'
186     if checkout: coflag = src.printcolors.printcHighlight(coflag.upper())
187
188     logger.write('%s:%s' % (coflag, src.printcolors.printcInfo(cvs_line)), 
189                  3, 
190                  False)
191     logger.write(' ' * (pad + 50 - len(cvs_line)), 3, False)
192     logger.write(' src:%s' % 
193                  src.printcolors.printcInfo(product_info.cvs_info.source), 
194                  3, 
195                  False)
196     logger.write(' ' * (pad + 1 - len(product_info.cvs_info.source)), 3, False)
197     logger.write(' tag:%s' % 
198                     src.printcolors.printcInfo(product_info.cvs_info.tag), 
199                  3, 
200                  False)
201     # at least one '.' is visible
202     logger.write(' %s. ' % ('.' * (10 - len(product_info.cvs_info.tag))), 
203                  3, 
204                  False) 
205     logger.flush()
206     logger.write('\n', 5, False)
207
208     # Call the system function that do the extraction in cvs mode
209     retcode = src.system.cvs_extract(protocol, user,
210                                  product_info.cvs_info.server,
211                                  product_info.cvs_info.product_base,
212                                  product_info.cvs_info.tag,
213                                  product_info.cvs_info.source,
214                                  source_dir, logger, checkout, environ)
215     return retcode
216
217 def get_source_from_svn(user,
218                         product_info,
219                         source_dir,
220                         checkout,
221                         logger,
222                         environ = None):
223     '''The method called if the product is to be get in svn mode
224     
225     :param user str: The user to use in for the svn command
226     :param product_info Config: The configuration specific to 
227                                the product to be prepared
228     :param source_dir Path: The Path instance corresponding to the 
229                             directory where to put the sources
230     :param checkout boolean: If True, get the source in checkout mode
231     :param logger Logger: The logger instance to use for the display and logging
232     :param environ src.environment.Environ: The environment to source when
233                                                 extracting.
234     :return: True if it succeed, else False
235     :rtype: boolean
236     '''
237     coflag = 'svn'
238     if checkout: coflag = src.printcolors.printcHighlight(coflag.upper())
239
240     logger.write('%s:%s ... ' % (coflag, 
241                                  src.printcolors.printcInfo(
242                                             product_info.svn_info.repo)), 
243                  3, 
244                  False)
245     logger.flush()
246     logger.write('\n', 5, False)
247     # Call the system function that do the extraction in svn mode
248     retcode = src.system.svn_extract(user, 
249                                      product_info.svn_info.repo, 
250                                      product_info.svn_info.tag,
251                                      source_dir, 
252                                      logger, 
253                                      checkout,
254                                      environ)
255     return retcode
256
257 def get_product_sources(config, 
258                        product_info, 
259                        is_dev, 
260                        source_dir,
261                        logger, 
262                        pad, 
263                        checkout=False):
264     '''Get the product sources.
265     
266     :param config Config: The global configuration
267     :param product_info Config: The configuration specific to 
268                                the product to be prepared
269     :param is_dev boolean: True if the product is in development mode
270     :param source_dir Path: The Path instance corresponding to the 
271                             directory where to put the sources
272     :param logger Logger: The logger instance to use for the display and logging
273     :param pad int: The gap to apply for the terminal display
274     :param checkout boolean: If True, get the source in checkout mode
275     :return: True if it succeed, else False
276     :rtype: boolean
277     '''
278     
279     # Get the application environment
280     logger.write(_("Set the application environment\n"), 5)
281     env_appli = src.environment.SalomeEnviron(config,
282                                       src.environment.Environ(dict(os.environ)))
283     env_appli.set_application_env(logger)
284     
285     # Call the right function to get sources regarding the product settings
286     if not checkout and is_dev:
287         return get_source_for_dev(config, 
288                                    product_info, 
289                                    source_dir, 
290                                    logger, 
291                                    pad)
292
293     if product_info.get_source == "git":
294         return get_source_from_git(product_info, source_dir, logger, pad, 
295                                     is_dev,env_appli)
296
297     if product_info.get_source == "archive":
298         return get_source_from_archive(product_info, source_dir, logger)
299     
300     if product_info.get_source == "cvs":
301         cvs_user = config.USER.cvs_user
302         return get_source_from_cvs(cvs_user, 
303                                     product_info, 
304                                     source_dir, 
305                                     checkout, 
306                                     logger,
307                                     pad,
308                                     env_appli)
309
310     if product_info.get_source == "svn":
311         svn_user = config.USER.svn_user
312         return get_source_from_svn(svn_user, product_info, source_dir, 
313                                     checkout,
314                                     logger,
315                                     env_appli)
316
317     if product_info.get_source == "native":
318         # skip
319         logger.write('%s  ' % src.printcolors.printc(src.OK_STATUS),
320                      3,
321                      False)
322         msg = _('INFORMATION : Not doing anything because the product'
323                 ' is of type "native".\n')
324         logger.write(msg, 3)
325         return True        
326
327     if product_info.get_source == "fixed":
328         # skip
329         logger.write('%s  ' % src.printcolors.printc(src.OK_STATUS),
330                      3,
331                      False)
332         msg = _('INFORMATION : Not doing anything because the product'
333                 ' is of type "fixed".\n')
334         logger.write(msg, 3)
335         return True  
336
337     # if the get_source is not in [git, archive, cvs, svn, fixed, native]
338     logger.write(_("Unknown get source method \"%(get)s\" for product %(product)s") % \
339         { 'get': product_info.get_source, 'product': product_info.name }, 3, False)
340     logger.write(" ... ", 3, False)
341     logger.flush()
342     return False
343
344 def get_all_product_sources(config, products, logger):
345     '''Get all the product sources.
346     
347     :param config Config: The global configuration
348     :param products List: The list of tuples (product name, product informations)
349     :param logger Logger: The logger instance to be used for the logging
350     :return: the tuple (number of success, dictionary product_name/success_fail)
351     :rtype: (int,dict)
352     '''
353
354     # Initialize the variables that will count the fails and success
355     results = dict()
356     good_result = 0
357
358     # Get the maximum name length in order to format the terminal display
359     max_product_name_len = 1
360     if len(products) > 0:
361         max_product_name_len = max(map(lambda l: len(l), products[0])) + 4
362     
363     # The loop on all the products from which to get the sources
364     for product_name, product_info in products:
365         # get product name, product informations and the directory where to put
366         # the sources
367         if (not (src.product.product_is_fixed(product_info) or 
368                  src.product.product_is_native(product_info))):
369             source_dir = src.Path(product_info.source_dir)
370         else:
371             source_dir = src.Path('')
372
373         # display and log
374         logger.write('%s: ' % src.printcolors.printcLabel(product_name), 3)
375         logger.write(' ' * (max_product_name_len - len(product_name)), 3, False)
376         logger.write("\n", 4, False)
377         
378         # Remove the existing source directory if 
379         # the product is not in development mode
380         is_dev = src.product.product_is_dev(product_info)
381         if source_dir.exists():
382             logger.write('%s  ' % src.printcolors.printc(src.OK_STATUS),
383                          3,
384                          False)
385             msg = _("INFORMATION : Not doing anything because the source"
386                     " directory already exists.\n")
387             logger.write(msg, 3)
388             good_result = good_result + 1
389             # Do not get the sources and go to next product
390             continue
391
392         # Call to the function that get the sources for one product
393         retcode = get_product_sources(config, 
394                                      product_info, 
395                                      is_dev, 
396                                      source_dir,
397                                      logger, 
398                                      max_product_name_len, 
399                                      checkout=False)
400         
401         '''
402         if 'no_rpath' in product_info.keys():
403             if product_info.no_rpath:
404                 hack_no_rpath(config, product_info, logger)
405         '''
406         
407         # Check that the sources are correctly get using the files to be tested
408         # in product information
409         if retcode:
410             check_OK, wrong_path = check_sources(product_info, logger)
411             if not check_OK:
412                 # Print the missing file path
413                 msg = _("The required file %s does not exists. " % wrong_path)
414                 logger.write(src.printcolors.printcError("\nERROR: ") + msg, 3)
415                 retcode = False
416
417         # show results
418         results[product_name] = retcode
419         if retcode:
420             # The case where it succeed
421             
422             
423             res = src.OK_STATUS
424             good_result = good_result + 1
425         else:
426             # The case where it failed
427             res = src.KO_STATUS
428         
429         # print the result
430         if not(src.product.product_is_fixed(product_info) or 
431                src.product.product_is_native(product_info)):
432             logger.write('%s\n' % src.printcolors.printc(res), 3, False)
433
434     return good_result, results
435
436 def check_sources(product_info, logger):
437     '''Check that the sources are correctly get, using the files to be tested
438        in product information
439     
440     :param product_info Config: The configuration specific to 
441                                 the product to be prepared
442     :return: True if the files exists (or no files to test is provided).
443     :rtype: boolean
444     '''
445     # Get the files to test if there is any
446     if ("present_files" in product_info and 
447         "source" in product_info.present_files):
448         l_files_to_be_tested = product_info.present_files.source
449         for file_path in l_files_to_be_tested:
450             # The path to test is the source directory 
451             # of the product joined the file path provided
452             path_to_test = os.path.join(product_info.source_dir, file_path)
453             logger.write(_("\nTesting existence of file: \n"), 5)
454             logger.write(path_to_test, 5)
455             if not os.path.exists(path_to_test):
456                 return False, path_to_test
457             logger.write(src.printcolors.printcSuccess(" OK\n"), 5)
458     return True, ""
459
460 def description():
461     '''method that is called when salomeTools is called with --help option.
462     
463     :return: The text to display for the source command description.
464     :rtype: str
465     '''
466     return _("The source command gets the sources of the application products "
467              "from cvs, git, an archive or a directory..")
468   
469 def run(args, runner, logger):
470     '''method that is called when salomeTools is called with source parameter.
471     '''
472     # Parse the options
473     (options, args) = parser.parse_args(args)
474     
475     # check that the command has been called with an application
476     src.check_config_has_application( runner.cfg )
477
478     # Print some informations
479     logger.write(_('Getting sources of the application %s\n') % 
480                 src.printcolors.printcLabel(runner.cfg.VARS.application), 1)
481     src.printcolors.print_value(logger, 'workdir', 
482                                 runner.cfg.APPLICATION.workdir, 2)
483     logger.write("\n", 2, False)
484        
485     # Get the products list with products informations regarding the options
486     products_infos = prepare.get_products_list(options, runner.cfg, logger)
487     
488     # Call to the function that gets all the sources
489     good_result, results = get_all_product_sources(runner.cfg, 
490                                                   products_infos,
491                                                   logger)
492
493     # Display the results (how much passed, how much failed, etc...)
494     status = src.OK_STATUS
495     details = []
496
497     logger.write("\n", 2, False)
498     if good_result == len(products_infos):
499         res_count = "%d / %d" % (good_result, good_result)
500     else:
501         status = src.KO_STATUS
502         res_count = "%d / %d" % (good_result, len(products_infos))
503
504         for product in results:
505             if results[product] == 0 or results[product] is None:
506                 details.append(product)
507
508     result = len(products_infos) - good_result
509
510     # write results
511     logger.write(_("Getting sources of the application:"), 1)
512     logger.write(" " + src.printcolors.printc(status), 1, False)
513     logger.write(" (%s)\n" % res_count, 1, False)
514
515     if len(details) > 0:
516         logger.write(_("Following sources haven't been get:\n"), 2)
517         logger.write(" ".join(details), 2)
518         logger.write("\n", 2, False)
519
520     return result