]> SALOME platform Git repositories - tools/sat.git/blob - src/system.py
Salome HOME
4c2838a313174dc743908eef38de262daa442df3
[tools/sat.git] / src / system.py
1 #!/usr/bin/env python
2 #-*- coding:utf-8 -*-
3 #  Copyright (C) 2010-2013  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 '''
20 In this file : all functions that do a system call, 
21 like open a browser or an editor, or call a git command
22 '''
23
24 import subprocess
25 import os
26 import tarfile
27
28 import debug as DBG
29 import utilsSat as UTS
30
31 from . import printcolors
32
33 def show_in_editor(editor, filePath, logger):
34     '''open filePath using editor.
35     
36     :param editor str: The editor to use.
37     :param filePath str: The path to the file to open.
38     '''
39     # default editor is vi
40     if editor is None or len(editor) == 0:
41         editor = 'vi'
42     
43     if '%s' not in editor:
44         editor += ' %s'
45
46     try:
47         # launch cmd using subprocess.Popen
48         cmd = editor % filePath
49         logger.write('Launched command:\n' + cmd + '\n', 5)
50         p = subprocess.Popen(cmd, shell=True)
51         p.communicate()
52     except:
53         logger.write(printcolors.printcError(_("Unable to edit file %s\n") 
54                                              % filePath), 1)
55
56
57 def git_extract(from_what, tag, where, logger, environment=None):
58   '''Extracts sources from a git repository.
59
60   :param from_what str: The remote git repository.
61   :param tag str: The tag.
62   :param where str: The path where to extract.
63   :param logger Logger: The logger instance to use.
64   :param environment src.environment.Environ: The environment to source when extracting.
65   :return: True if the extraction is successful
66   :rtype: boolean
67   '''
68   DBG.write("git_extract", [from_what, tag, str(where)])
69   if not where.exists():
70     where.make()
71   if tag == "master" or tag == "HEAD":
72     command = "git clone %(remote)s %(where)s" % \
73               {'remote': from_what, 'tag': tag, 'where': str(where)}
74   else:
75     # NOTICE: this command only works with recent version of git
76     #         because --work-tree does not work with an absolute path
77     where_git = os.path.join(str(where), ".git")
78     command = "rmdir %(where)s && git clone %(remote)s %(where)s && " + \
79               "git --git-dir=%(where_git)s --work-tree=%(where)s checkout %(tag)s"
80     command = command % {'remote': from_what,
81                          'tag': tag,
82                          'where': str(where),
83                          'where_git': where_git}
84
85   logger.write(command + "\n", 5)
86
87   logger.logTxtFile.write("\n" + command + "\n")
88   logger.logTxtFile.flush()
89   res = subprocess.call(command,
90                         cwd=str(where.dir()),
91                         env=environment.environ.environ,
92                         shell=True,
93                         stdout=logger.logTxtFile,
94                         stderr=subprocess.STDOUT)
95   return (res == 0)
96
97
98 def git_extract_sub_dir(from_what, tag, where, sub_dir, logger, environment=None):
99   '''Extracts sources from a subtree sub_dir of a git repository.
100
101   :param from_what str: The remote git repository.
102   :param tag str: The tag.
103   :param where str: The path where to extract.
104   :param sub_dir str: The relative path of subtree to extract.
105   :param logger Logger: The logger instance to use.
106   :param environment src.environment.Environ: The environment to source when extracting.
107   :return: True if the extraction is successful
108   :rtype: boolean
109   '''
110   strWhere = str(where)
111   tmpWhere = strWhere + '_tmp'
112   parentWhere = os.path.dirname(strWhere)
113   if not os.path.exists(parentWhere):
114     logger.error("not existing directory: %s" % parentWhere)
115     return False
116   if os.path.isdir(strWhere):
117     logger.error("do not override existing directory: %s" % strWhere)
118     return False
119   aDict = {'remote': from_what,
120            'tag': tag,
121            'sub_dir': sub_dir,
122            'where': strWhere,
123            'parentWhere': parentWhere,
124            'tmpWhere': tmpWhere,
125            }
126   DBG.write("git_extract_sub_dir", aDict)
127
128   cmd = r"""
129 export tmpDir=%(tmpWhere)s && \
130 rm -rf $tmpDir && \
131 git clone %(remote)s $tmpDir && \
132 cd $tmpDir && \
133 git checkout %(tag)s && \
134 mv %(sub_dir)s %(where)s && \
135 git log -1 > %(where)s/README_git_log.txt && \
136 rm -rf $tmpDir
137 """ % aDict
138   DBG.write("cmd", cmd)
139   rc = UTS.Popen(cmd, cwd=parentWhere, env=environment.environ.environ, logger=logger)
140   return rc.isOk()
141
142
143 def archive_extract(from_what, where, logger):
144     '''Extracts sources from an archive.
145     
146     :param from_what str: The path to the archive.
147     :param where str: The path where to extract.
148     :param logger Logger: The logger instance to use.
149     :return: True if the extraction is successful
150     :rtype: boolean
151     '''
152     try:
153         archive = tarfile.open(from_what)
154         for i in archive.getmembers():
155             archive.extract(i, path=str(where))
156         return True, os.path.commonprefix(archive.getnames())
157     except Exception as exc:
158         logger.write("archive_extract: %s\n" % exc)
159         return False, None
160
161 def cvs_extract(protocol, user, server, base, tag, product, where,
162                 logger, checkout=False, environment=None):
163     '''Extracts sources from a cvs repository.
164     
165     :param protocol str: The cvs protocol.
166     :param user str: The user to be used.
167     :param server str: The remote cvs server.
168     :param base str: .
169     :param tag str: The tag.
170     :param product str: The product.
171     :param where str: The path where to extract.
172     :param logger Logger: The logger instance to use.
173     :param checkout boolean: If true use checkout cvs.
174     :param environment src.environment.Environ: The environment to source when
175                                                 extracting.
176     :return: True if the extraction is successful
177     :rtype: boolean
178     '''
179
180     opttag = ''
181     if tag is not None and len(tag) > 0:
182         opttag = '-r ' + tag
183
184     cmd = 'export'
185     if checkout:
186         cmd = 'checkout'
187     elif len(opttag) == 0:
188         opttag = '-DNOW'
189     
190     if len(protocol) > 0:
191         root = "%s@%s:%s" % (user, server, base)
192         command = "cvs -d :%(protocol)s:%(root)s %(command)s -d %(where)s %(tag)s %(product)s" % \
193             { 'protocol': protocol, 'root': root, 'where': str(where.base()),
194               'tag': opttag, 'product': product, 'command': cmd }
195     else:
196         command = "cvs -d %(root)s %(command)s -d %(where)s %(tag)s %(base)s/%(product)s" % \
197             { 'root': server, 'base': base, 'where': str(where.base()),
198               'tag': opttag, 'product': product, 'command': cmd }
199
200     logger.write(command + "\n", 5)
201
202     if not where.dir().exists():
203         where.dir().make()
204
205     logger.logTxtFile.write("\n" + command + "\n")
206     logger.logTxtFile.flush()        
207     res = subprocess.call(command,
208                           cwd=str(where.dir()),
209                           env=environment.environ.environ,
210                           shell=True,
211                           stdout=logger.logTxtFile,
212                           stderr=subprocess.STDOUT)
213     return (res == 0)
214
215 def svn_extract(user,
216                 from_what,
217                 tag,
218                 where,
219                 logger,
220                 checkout=False,
221                 environment=None):
222     '''Extracts sources from a svn repository.
223     
224     :param user str: The user to be used.
225     :param from_what str: The remote git repository.
226     :param tag str: The tag.
227     :param where str: The path where to extract.
228     :param logger Logger: The logger instance to use.
229     :param checkout boolean: If true use checkout svn.
230     :param environment src.environment.Environ: The environment to source when
231                                                 extracting.
232     :return: True if the extraction is successful
233     :rtype: boolean
234     '''
235     if not where.exists():
236         where.make()
237
238     if checkout:
239         command = "svn checkout --username %(user)s %(remote)s %(where)s" % \
240             { 'remote': from_what, 'user' : user, 'where': str(where) }
241     else:
242         command = ""
243         if os.path.exists(str(where)):
244             command = "/bin/rm -rf %(where)s && " % \
245                 { 'remote': from_what, 'where': str(where) }
246         
247         if tag == "master":
248             command += "svn export --username %(user)s %(remote)s %(where)s" % \
249                 { 'remote': from_what, 'user' : user, 'where': str(where) }       
250         else:
251             command += "svn export -r %(tag)s --username %(user)s %(remote)s %(where)s" % \
252                 { 'tag' : tag, 'remote': from_what, 'user' : user, 'where': str(where) }
253     
254     logger.logTxtFile.write(command + "\n")
255     
256     logger.write(command + "\n", 5)
257     logger.logTxtFile.write("\n" + command + "\n")
258     logger.logTxtFile.flush()
259     res = subprocess.call(command,
260                           cwd=str(where.dir()),
261                           env=environment.environ.environ,
262                           shell=True,
263                           stdout=logger.logTxtFile,
264                           stderr=subprocess.STDOUT)
265     return (res == 0)