Salome HOME
Ajout d'un mode ftp pour les archives de prérequis
[tools/sat.git] / commands / source.py
1 #!/usr/bin/env python
2 #-*- coding:utf-8 -*-
3 #  Copyright (C) 2010-2012  CEA/DEN
4 #
5 #  This library is free software; you can redistribute it and/or
6 #  modify it under the terms of the GNU Lesser General Public
7 #  License as published by the Free Software Foundation; either
8 #  version 2.1 of the License.
9 #
10 #  This library is distributed in the hope that it will be useful,
11 #  but WITHOUT ANY WARRANTY; without even the implied warranty of
12 #  MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
13 #  Lesser General Public License for more details.
14 #
15 #  You should have received a copy of the GNU Lesser General Public
16 #  License along with this library; if not, write to the Free Software
17 #  Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA  02111-1307 USA
18
19 import os
20 import shutil
21 import re
22
23 import src
24 import prepare
25 import src.debug as DBG
26
27 # Define all possible option for patch command :  sat patch <options>
28 parser = src.options.Options()
29 parser.add_option('p', 'products', 'list2', 'products',
30     _('Optional: products from which to get the sources. This option accepts a comma separated list.'))
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
108     sub_dir = None
109
110     # what do we do with git tree structure and history
111     if is_dev and "sub_dir" in product_info.git_info:
112         logger.error("dev mode for product is incompatible with 'sub_dir' option")
113         return False
114
115     if not is_dev and "sub_dir" in product_info.git_info:
116         sub_dir = product_info.git_info.sub_dir
117
118     if sub_dir  is None:
119       # Call the system function that do the extraction in git mode
120       retcode = src.system.git_extract(repo_git,
121                                    product_info.git_info.tag,
122                                    source_dir, logger, environ)
123     else:
124       # Call the system function that do the extraction of a sub_dir in git mode
125       logger.write("sub_dir:%s " % sub_dir, 3)
126       retcode = src.system.git_extract_sub_dir(repo_git,
127                                    product_info.git_info.tag,
128                                    source_dir, sub_dir, logger, environ)
129
130
131     return retcode
132
133 def get_source_from_archive(config, product_info, source_dir, logger):
134     '''The method called if the product is to be get in archive mode
135     
136     :param config Config: The global configuration
137     :param product_info Config: The configuration specific to 
138                                the product to be prepared
139     :param source_dir Path: The Path instance corresponding to the 
140                             directory where to put the sources
141     :param logger Logger: The logger instance to use for the display and logging
142     :return: True if it succeed, else False
143     :rtype: boolean
144     '''
145     # check archive exists
146     if not os.path.exists(product_info.archive_info.archive_name):
147         # The archive is not found on local file system (ARCHIVEPATH)
148         # We try ftp!
149         logger.write("\n   The archive is not found on local file system, we try ftp\n", 3)
150         ret=src.find_file_in_ftppath(product_info.archive_info.archive_name, 
151                                      config.PATHS.ARCHIVEFTP, config.LOCAL.archive_dir, logger)
152         if ret:
153             # archive was found on ftp and stored in ret
154             product_info.archive_info.archive_name=ret
155         else:
156             raise src.SatException(_("Archive not found in ARCHIVEPATH, nor on ARCHIVEFTP: '%s'") % 
157                                    product_info.archive_info.archive_name)
158
159     logger.write('arc:%s ... ' % 
160                  src.printcolors.printcInfo(product_info.archive_info.archive_name),
161                  3, 
162                  False)
163     logger.flush()
164     # Call the system function that do the extraction in archive mode
165     retcode, NameExtractedDirectory = src.system.archive_extract(
166                                     product_info.archive_info.archive_name,
167                                     source_dir.dir(), logger)
168     
169     # Rename the source directory if 
170     # it does not match with product_info.source_dir
171     if (NameExtractedDirectory.replace('/', '') != 
172             os.path.basename(product_info.source_dir)):
173         shutil.move(os.path.join(os.path.dirname(product_info.source_dir), 
174                                  NameExtractedDirectory), 
175                     product_info.source_dir)
176     
177     return retcode
178
179 def get_source_from_dir(product_info, source_dir, logger):
180     
181     if "dir_info" not in product_info:
182         msg = _("Error: you must put a dir_info section"
183                 " in the file %s.pyconf" % product_info.name)
184         logger.write("\n%s\n" % src.printcolors.printcError(msg), 1)
185         return False
186
187     if "dir" not in product_info.dir_info:
188         msg = _("Error: you must put a dir in the dir_info section"
189                 " in the file %s.pyconf" % product_info.name)
190         logger.write("\n%s\n" % src.printcolors.printcError(msg), 1)
191         return False
192
193     # check that source exists
194     if not os.path.exists(product_info.dir_info.dir):
195         msg = _("Error: the dir %s defined in the file"
196                 " %s.pyconf does not exists" % (product_info.dir_info.dir,
197                                                 product_info.name))
198         logger.write("\n%s\n" % src.printcolors.printcError(msg), 1)
199         return False
200     
201     logger.write('DIR: %s ... ' % src.printcolors.printcInfo(
202                                            product_info.dir_info.dir), 3)
203     logger.flush()
204
205     retcode = src.Path(product_info.dir_info.dir).copy(source_dir)
206     
207     return retcode
208     
209 def get_source_from_cvs(user,
210                         product_info,
211                         source_dir,
212                         checkout,
213                         logger,
214                         pad,
215                         environ = None):
216     '''The method called if the product is to be get in cvs mode
217     
218     :param user str: The user to use in for the cvs command
219     :param product_info Config: The configuration specific to 
220                                the product to be prepared
221     :param source_dir Path: The Path instance corresponding to the 
222                             directory where to put the sources
223     :param checkout boolean: If True, get the source in checkout mode
224     :param logger Logger: The logger instance to use for the display and logging
225     :param pad int: The gap to apply for the terminal display
226     :param environ src.environment.Environ: The environment to source when
227                                                 extracting.
228     :return: True if it succeed, else False
229     :rtype: boolean
230     '''
231     # Get the protocol to use in the command
232     if "protocol" in product_info.cvs_info:
233         protocol = product_info.cvs_info.protocol
234     else:
235         protocol = "pserver"
236     
237     # Construct the line to display
238     if "protocol" in product_info.cvs_info:
239         cvs_line = "%s:%s@%s:%s" % \
240             (protocol, user, product_info.cvs_info.server, 
241              product_info.cvs_info.product_base)
242     else:
243         cvs_line = "%s / %s" % (product_info.cvs_info.server, 
244                                 product_info.cvs_info.product_base)
245
246     coflag = 'cvs'
247     if checkout: coflag = src.printcolors.printcHighlight(coflag.upper())
248
249     logger.write('%s:%s' % (coflag, src.printcolors.printcInfo(cvs_line)), 
250                  3, 
251                  False)
252     logger.write(' ' * (pad + 50 - len(cvs_line)), 3, False)
253     logger.write(' src:%s' % 
254                  src.printcolors.printcInfo(product_info.cvs_info.source), 
255                  3, 
256                  False)
257     logger.write(' ' * (pad + 1 - len(product_info.cvs_info.source)), 3, False)
258     logger.write(' tag:%s' % 
259                     src.printcolors.printcInfo(product_info.cvs_info.tag), 
260                  3, 
261                  False)
262     # at least one '.' is visible
263     logger.write(' %s. ' % ('.' * (10 - len(product_info.cvs_info.tag))), 
264                  3, 
265                  False) 
266     logger.flush()
267     logger.write('\n', 5, False)
268
269     # Call the system function that do the extraction in cvs mode
270     retcode = src.system.cvs_extract(protocol, user,
271                                  product_info.cvs_info.server,
272                                  product_info.cvs_info.product_base,
273                                  product_info.cvs_info.tag,
274                                  product_info.cvs_info.source,
275                                  source_dir, logger, checkout, environ)
276     return retcode
277
278 def get_source_from_svn(user,
279                         product_info,
280                         source_dir,
281                         checkout,
282                         logger,
283                         environ = None):
284     '''The method called if the product is to be get in svn mode
285     
286     :param user str: The user to use in for the svn command
287     :param product_info Config: The configuration specific to 
288                                the product to be prepared
289     :param source_dir Path: The Path instance corresponding to the 
290                             directory where to put the sources
291     :param checkout boolean: If True, get the source in checkout mode
292     :param logger Logger: The logger instance to use for the display and logging
293     :param environ src.environment.Environ: The environment to source when
294                                                 extracting.
295     :return: True if it succeed, else False
296     :rtype: boolean
297     '''
298     coflag = 'svn'
299     if checkout: coflag = src.printcolors.printcHighlight(coflag.upper())
300
301     logger.write('%s:%s ... ' % (coflag, 
302                                  src.printcolors.printcInfo(
303                                             product_info.svn_info.repo)), 
304                  3, 
305                  False)
306     logger.flush()
307     logger.write('\n', 5, False)
308     # Call the system function that do the extraction in svn mode
309     retcode = src.system.svn_extract(user, 
310                                      product_info.svn_info.repo, 
311                                      product_info.svn_info.tag,
312                                      source_dir, 
313                                      logger, 
314                                      checkout,
315                                      environ)
316     return retcode
317
318 def get_product_sources(config, 
319                        product_info, 
320                        is_dev, 
321                        source_dir,
322                        logger, 
323                        pad, 
324                        checkout=False):
325     '''Get the product sources.
326     
327     :param config Config: The global configuration
328     :param product_info Config: The configuration specific to 
329                                the product to be prepared
330     :param is_dev boolean: True if the product is in development mode
331     :param source_dir Path: The Path instance corresponding to the 
332                             directory where to put the sources
333     :param logger Logger: The logger instance to use for the display and logging
334     :param pad int: The gap to apply for the terminal display
335     :param checkout boolean: If True, get the source in checkout mode
336     :return: True if it succeed, else False
337     :rtype: boolean
338     '''
339     
340     # Get the application environment
341     logger.write(_("Set the application environment\n"), 5)
342     env_appli = src.environment.SalomeEnviron(config,
343                                       src.environment.Environ(dict(os.environ)))
344     env_appli.set_application_env(logger)
345     
346     # Call the right function to get sources regarding the product settings
347     if not checkout and is_dev:
348         return get_source_for_dev(config, 
349                                    product_info, 
350                                    source_dir, 
351                                    logger, 
352                                    pad)
353
354     if product_info.get_source == "git":
355         return get_source_from_git(product_info, source_dir, logger, pad, 
356                                     is_dev,env_appli)
357
358     if product_info.get_source == "archive":
359         return get_source_from_archive(config, product_info, source_dir, logger)
360
361     if product_info.get_source == "dir":
362         return get_source_from_dir(product_info, source_dir, logger)
363     
364     if product_info.get_source == "cvs":
365         cvs_user = config.USER.cvs_user
366         return get_source_from_cvs(cvs_user, 
367                                     product_info, 
368                                     source_dir, 
369                                     checkout, 
370                                     logger,
371                                     pad,
372                                     env_appli)
373
374     if product_info.get_source == "svn":
375         svn_user = config.USER.svn_user
376         return get_source_from_svn(svn_user, product_info, source_dir, 
377                                     checkout,
378                                     logger,
379                                     env_appli)
380
381     if product_info.get_source == "native":
382         # skip
383         logger.write('%s  ' % src.printcolors.printc(src.OK_STATUS),
384                      3,
385                      False)
386         msg = _('INFORMATION : Not doing anything because the product'
387                 ' is of type "native".\n')
388         logger.write(msg, 3)
389         return True        
390
391     if product_info.get_source == "fixed":
392         # skip
393         logger.write('%s  ' % src.printcolors.printc(src.OK_STATUS),
394                      3,
395                      False)
396         msg = _('INFORMATION : Not doing anything because the product'
397                 ' is of type "fixed".\n')
398         logger.write(msg, 3)
399         return True  
400
401     # if the get_source is not in [git, archive, cvs, svn, fixed, native]
402     logger.write(_("Unknown get source method \"%(get)s\" for product %(product)s") % \
403         { 'get': product_info.get_source, 'product': product_info.name }, 3, False)
404     logger.write(" ... ", 3, False)
405     logger.flush()
406     return False
407
408 def get_all_product_sources(config, products, logger):
409     '''Get all the product sources.
410     
411     :param config Config: The global configuration
412     :param products List: The list of tuples (product name, product informations)
413     :param logger Logger: The logger instance to be used for the logging
414     :return: the tuple (number of success, dictionary product_name/success_fail)
415     :rtype: (int,dict)
416     '''
417
418     # Initialize the variables that will count the fails and success
419     results = dict()
420     good_result = 0
421
422     # Get the maximum name length in order to format the terminal display
423     max_product_name_len = 1
424     if len(products) > 0:
425         max_product_name_len = max(map(lambda l: len(l), products[0])) + 4
426     
427     # The loop on all the products from which to get the sources
428     # DBG.write("source.get_all_product_sources config id", id(config), True)
429     for product_name, product_info in products:
430         # get product name, product informations and the directory where to put
431         # the sources
432         if (not (src.product.product_is_fixed(product_info) or 
433                  src.product.product_is_native(product_info))):
434             source_dir = src.Path(product_info.source_dir)
435         else:
436             source_dir = src.Path('')
437
438         # display and log
439         logger.write('%s: ' % src.printcolors.printcLabel(product_name), 3)
440         logger.write(' ' * (max_product_name_len - len(product_name)), 3, False)
441         logger.write("\n", 4, False)
442         
443         # Remove the existing source directory if 
444         # the product is not in development mode
445         is_dev = src.product.product_is_dev(product_info)
446         if source_dir.exists():
447             logger.write('%s  ' % src.printcolors.printc(src.OK_STATUS), 3, False)
448             msg = _("INFO : Not doing anything because the source directory already exists:\n    %s\n") % source_dir
449             logger.write(msg, 3)
450             good_result = good_result + 1
451             # Do not get the sources and go to next product
452             continue
453
454         # Call to the function that get the sources for one product
455         retcode = get_product_sources(config, 
456                                      product_info, 
457                                      is_dev, 
458                                      source_dir,
459                                      logger, 
460                                      max_product_name_len, 
461                                      checkout=False)
462         
463         '''
464         if 'no_rpath' in product_info.keys():
465             if product_info.no_rpath:
466                 hack_no_rpath(config, product_info, logger)
467         '''
468         
469         # Check that the sources are correctly get using the files to be tested
470         # in product information
471         if retcode:
472             check_OK, wrong_path = check_sources(product_info, logger)
473             if not check_OK:
474                 # Print the missing file path
475                 msg = _("The required file %s does not exists. " % wrong_path)
476                 logger.write(src.printcolors.printcError("\nERROR: ") + msg, 3)
477                 retcode = False
478
479         # show results
480         results[product_name] = retcode
481         if retcode:
482             # The case where it succeed
483             res = src.OK_STATUS
484             good_result = good_result + 1
485         else:
486             # The case where it failed
487             res = src.KO_STATUS
488         
489         # print the result
490         if not(src.product.product_is_fixed(product_info) or 
491                src.product.product_is_native(product_info)):
492             logger.write('%s\n' % src.printcolors.printc(res), 3, False)
493
494     return good_result, results
495
496 def check_sources(product_info, logger):
497     '''Check that the sources are correctly get, using the files to be tested
498        in product information
499     
500     :param product_info Config: The configuration specific to 
501                                 the product to be prepared
502     :return: True if the files exists (or no files to test is provided).
503     :rtype: boolean
504     '''
505     # Get the files to test if there is any
506     if ("present_files" in product_info and 
507         "source" in product_info.present_files):
508         l_files_to_be_tested = product_info.present_files.source
509         for file_path in l_files_to_be_tested:
510             # The path to test is the source directory 
511             # of the product joined the file path provided
512             path_to_test = os.path.join(product_info.source_dir, file_path)
513             logger.write(_("\nTesting existence of file: \n"), 5)
514             logger.write(path_to_test, 5)
515             if not os.path.exists(path_to_test):
516                 return False, path_to_test
517             logger.write(src.printcolors.printcSuccess(" OK\n"), 5)
518     return True, ""
519
520 def description():
521     '''method that is called when salomeTools is called with --help option.
522     
523     :return: The text to display for the source command description.
524     :rtype: str
525     '''
526     return _("The source command gets the sources of the application products "
527              "from cvs, git or an archive.\n\nexample:"
528              "\nsat source SALOME-master --products KERNEL,GUI")
529   
530 def run(args, runner, logger):
531     '''method that is called when salomeTools is called with source parameter.
532     '''
533     DBG.write("source.run()", args)
534     # Parse the options
535     (options, args) = parser.parse_args(args)
536     
537     # check that the command has been called with an application
538     src.check_config_has_application( runner.cfg )
539
540     # Print some informations
541     logger.write(_('Getting sources of the application %s\n') % 
542                 src.printcolors.printcLabel(runner.cfg.VARS.application), 1)
543     src.printcolors.print_value(logger, 'workdir', 
544                                 runner.cfg.APPLICATION.workdir, 2)
545     logger.write("\n", 2, False)
546        
547     # Get the products list with products informations regarding the options
548     products_infos = src.product.get_products_list(options, runner.cfg, logger)
549     
550     # Call to the function that gets all the sources
551     good_result, results = get_all_product_sources(runner.cfg, 
552                                                   products_infos,
553                                                   logger)
554
555     # Display the results (how much passed, how much failed, etc...)
556     status = src.OK_STATUS
557     details = []
558
559     logger.write("\n", 2, False)
560     if good_result == len(products_infos):
561         res_count = "%d / %d" % (good_result, good_result)
562     else:
563         status = src.KO_STATUS
564         res_count = "%d / %d" % (good_result, len(products_infos))
565
566         for product in results:
567             if results[product] == 0 or results[product] is None:
568                 details.append(product)
569
570     result = len(products_infos) - good_result
571
572     # write results
573     logger.write(_("Getting sources of the application:"), 1)
574     logger.write(" " + src.printcolors.printc(status), 1, False)
575     logger.write(" (%s)\n" % res_count, 1, False)
576
577     if len(details) > 0:
578         logger.write(_("Following sources haven't been get:\n"), 2)
579         logger.write(" ".join(details), 2)
580         logger.write("\n", 2, False)
581
582     return result