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