Salome HOME
46d7942c3c97cfe331676889b57a90cc665f465e
[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     cmd = r"""
73 set -x
74 git clone %(remote)s %(where)s
75 """
76     cmd = cmd % {'remote': from_what, 'tag': tag, 'where': str(where)}
77   else:
78     # NOTICE: this command only works with recent version of git
79     #         because --work-tree does not work with an absolute path
80     where_git = os.path.join(str(where), ".git")
81
82     cmd = r"""
83 set -x
84 rmdir %(where)s && \
85 git clone %(remote)s %(where)s && \
86 git --git-dir=%(where_git)s --work-tree=%(where)s checkout %(tag)s
87 """
88     cmd = cmd % {'remote': from_what,
89                  'tag': tag,
90                  'where': str(where),
91                  'where_git': where_git}
92
93
94   logger.logTxtFile.write("\n" + cmd + "\n")
95   logger.logTxtFile.flush()
96
97   DBG.write("cmd", cmd)
98   rc = UTS.Popen(cmd, cwd=str(where.dir()), env=environment.environ.environ, logger=logger)
99   return rc.isOk()
100
101   """
102   res = subprocess.call(command,
103                         cwd=str(where.dir()),
104                         env=environment.environ.environ,
105                         shell=True,
106                         stdout=logger.logTxtFile,
107                         stderr=subprocess.STDOUT)
108   return (res == 0)
109   """
110
111
112
113 def git_extract_sub_dir(from_what, tag, where, sub_dir, logger, environment=None):
114   '''Extracts sources from a subtree sub_dir of a git repository.
115
116   :param from_what str: The remote git repository.
117   :param tag str: The tag.
118   :param where str: The path where to extract.
119   :param sub_dir str: The relative path of subtree to extract.
120   :param logger Logger: The logger instance to use.
121   :param environment src.environment.Environ: The environment to source when extracting.
122   :return: True if the extraction is successful
123   :rtype: boolean
124   '''
125   strWhere = str(where)
126   tmpWhere = strWhere + '_tmp'
127   parentWhere = os.path.dirname(strWhere)
128   if not os.path.exists(parentWhere):
129     logger.error("not existing directory: %s" % parentWhere)
130     return False
131   if os.path.isdir(strWhere):
132     logger.error("do not override existing directory: %s" % strWhere)
133     return False
134   aDict = {'remote': from_what,
135            'tag': tag,
136            'sub_dir': sub_dir,
137            'where': strWhere,
138            'parentWhere': parentWhere,
139            'tmpWhere': tmpWhere,
140            }
141   DBG.write("git_extract_sub_dir", aDict)
142
143   cmd = r"""
144 set -x
145 export tmpDir=%(tmpWhere)s && \
146 rm -rf $tmpDir && \
147 git clone %(remote)s $tmpDir && \
148 cd $tmpDir && \
149 git checkout %(tag)s && \
150 mv %(sub_dir)s %(where)s && \
151 git log -1 > %(where)s/README_git_log.txt && \
152 rm -rf $tmpDir
153 """ % aDict
154   DBG.write("cmd", cmd)
155   rc = UTS.Popen(cmd, cwd=parentWhere, env=environment.environ.environ, logger=logger)
156   return rc.isOk()
157
158
159 def archive_extract(from_what, where, logger):
160     '''Extracts sources from an archive.
161     
162     :param from_what str: The path to the archive.
163     :param where str: The path where to extract.
164     :param logger Logger: The logger instance to use.
165     :return: True if the extraction is successful
166     :rtype: boolean
167     '''
168     try:
169         archive = tarfile.open(from_what)
170         for i in archive.getmembers():
171             archive.extract(i, path=str(where))
172         return True, os.path.commonprefix(archive.getnames())
173     except Exception as exc:
174         logger.write("archive_extract: %s\n" % exc)
175         return False, None
176
177 def cvs_extract(protocol, user, server, base, tag, product, where,
178                 logger, checkout=False, environment=None):
179     '''Extracts sources from a cvs repository.
180     
181     :param protocol str: The cvs protocol.
182     :param user str: The user to be used.
183     :param server str: The remote cvs server.
184     :param base str: .
185     :param tag str: The tag.
186     :param product str: The product.
187     :param where str: The path where to extract.
188     :param logger Logger: The logger instance to use.
189     :param checkout boolean: If true use checkout cvs.
190     :param environment src.environment.Environ: The environment to source when
191                                                 extracting.
192     :return: True if the extraction is successful
193     :rtype: boolean
194     '''
195
196     opttag = ''
197     if tag is not None and len(tag) > 0:
198         opttag = '-r ' + tag
199
200     cmd = 'export'
201     if checkout:
202         cmd = 'checkout'
203     elif len(opttag) == 0:
204         opttag = '-DNOW'
205     
206     if len(protocol) > 0:
207         root = "%s@%s:%s" % (user, server, base)
208         command = "cvs -d :%(protocol)s:%(root)s %(command)s -d %(where)s %(tag)s %(product)s" % \
209             { 'protocol': protocol, 'root': root, 'where': str(where.base()),
210               'tag': opttag, 'product': product, 'command': cmd }
211     else:
212         command = "cvs -d %(root)s %(command)s -d %(where)s %(tag)s %(base)s/%(product)s" % \
213             { 'root': server, 'base': base, 'where': str(where.base()),
214               'tag': opttag, 'product': product, 'command': cmd }
215
216     logger.write(command + "\n", 5)
217
218     if not where.dir().exists():
219         where.dir().make()
220
221     logger.logTxtFile.write("\n" + command + "\n")
222     logger.logTxtFile.flush()        
223     res = subprocess.call(command,
224                           cwd=str(where.dir()),
225                           env=environment.environ.environ,
226                           shell=True,
227                           stdout=logger.logTxtFile,
228                           stderr=subprocess.STDOUT)
229     return (res == 0)
230
231 def svn_extract(user,
232                 from_what,
233                 tag,
234                 where,
235                 logger,
236                 checkout=False,
237                 environment=None):
238     '''Extracts sources from a svn repository.
239     
240     :param user str: The user to be used.
241     :param from_what str: The remote git repository.
242     :param tag str: The tag.
243     :param where str: The path where to extract.
244     :param logger Logger: The logger instance to use.
245     :param checkout boolean: If true use checkout svn.
246     :param environment src.environment.Environ: The environment to source when
247                                                 extracting.
248     :return: True if the extraction is successful
249     :rtype: boolean
250     '''
251     if not where.exists():
252         where.make()
253
254     if checkout:
255         command = "svn checkout --username %(user)s %(remote)s %(where)s" % \
256             { 'remote': from_what, 'user' : user, 'where': str(where) }
257     else:
258         command = ""
259         if os.path.exists(str(where)):
260             command = "/bin/rm -rf %(where)s && " % \
261                 { 'remote': from_what, 'where': str(where) }
262         
263         if tag == "master":
264             command += "svn export --username %(user)s %(remote)s %(where)s" % \
265                 { 'remote': from_what, 'user' : user, 'where': str(where) }       
266         else:
267             command += "svn export -r %(tag)s --username %(user)s %(remote)s %(where)s" % \
268                 { 'tag' : tag, 'remote': from_what, 'user' : user, 'where': str(where) }
269     
270     logger.logTxtFile.write(command + "\n")
271     
272     logger.write(command + "\n", 5)
273     logger.logTxtFile.write("\n" + command + "\n")
274     logger.logTxtFile.flush()
275     res = subprocess.call(command,
276                           cwd=str(where.dir()),
277                           env=environment.environ.environ,
278                           shell=True,
279                           stdout=logger.logTxtFile,
280                           stderr=subprocess.STDOUT)
281     return (res == 0)