3 # Copyright (C) 2010-2013 CEA/DEN
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.
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.
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
20 In this file : all functions that do a system call,
21 like open a browser or an editor, or call a git command
30 import utilsSat as UTS
33 from . import printcolors
35 def show_in_editor(editor, filePath, logger):
36 '''open filePath using editor.
38 :param editor str: The editor to use.
39 :param filePath str: The path to the file to open.
41 # default editor is vi
42 if editor is None or len(editor) == 0:
45 if '%s' not in editor:
49 # launch cmd using subprocess.Popen
50 cmd = editor % filePath
51 logger.write('Launched command:\n' + cmd + '\n', 5)
52 p = subprocess.Popen(cmd, shell=True)
55 logger.write(printcolors.printcError(_("Unable to edit file %s\n")
58 def git_describe(repo_path):
59 '''Use git describe --tags command to return tag description of the git repository"
60 :param repo_path str: The git repository to describe
62 git_cmd="cd %s;git describe --tags" % repo_path
63 p = subprocess.Popen(git_cmd, shell=True,
64 stdin=subprocess.PIPE,
65 stdout=subprocess.PIPE,
66 stderr=subprocess.PIPE)
71 tag_description=p.stdout.readlines()[0].strip()
72 # with python3 this utf8 bytes should be decoded
73 if isinstance(tag_description, bytes):
74 tag_description=tag_description.decode("utf-8", "ignore")
75 return tag_description
78 def git_extract(from_what, tag, git_options, where, logger, environment=None):
79 '''Extracts sources from a git repository.
81 :param from_what str: The remote git repository.
82 :param tag str: The tag.
83 :param git_options str: git options
84 :param where str: The path where to extract.
85 :param logger Logger: The logger instance to use.
86 :param environment src.environment.Environ: The environment to source when extracting.
87 :return: True if the extraction is successful
90 DBG.write("git_extract", [from_what, tag, str(where)])
91 if not where.exists():
93 where_git = os.path.join(str(where), ".git")
94 if tag == "master" or tag == "HEAD":
95 if src.architecture.is_windows():
96 cmd = "git clone %(git_options)s %(remote)s %(where)s"
100 git clone %(git_options)s %(remote)s %(where)s
102 if [ $res -eq 0 ]; then touch -d "$(git --git-dir=%(where_git)s log -1 --format=date_format)" %(where)s;fi
105 cmd = cmd % {'git_options': git_options, 'remote': from_what, 'tag': tag, 'where': str(where), 'where_git': where_git}
107 # NOTICE: this command only works with recent version of git
108 # because --work-tree does not work with an absolute path
109 if src.architecture.is_windows():
110 cmd = "rm -rf %(where)s && git clone %(git_options)s %(remote)s %(where)s && git --git-dir=%(where_git)s --work-tree=%(where)s checkout %(tag)s"
112 # for sat compile --update : changes the date of directory, only for branches, not tag
116 git clone %(git_options)s %(remote)s %(where)s && \
117 git --git-dir=%(where_git)s --work-tree=%(where)s checkout %(tag)s
119 git --git-dir=%(where_git)s status|grep HEAD
120 if [ $res -eq 0 -a $? -ne 0 ]; then touch -d "$(git --git-dir=%(where_git)s log -1 --format=date_format)" %(where)s;fi
123 cmd = cmd % {'git_options': git_options,
127 'where_git': where_git}
130 cmd=cmd.replace('date_format','"%ai"')
131 logger.logTxtFile.write("\n" + cmd + "\n")
132 logger.logTxtFile.flush()
134 DBG.write("cmd", cmd)
135 # git commands may fail sometimes for various raisons
136 # (big module, network troubles, tuleap maintenance)
137 # therefore we give several tries
139 max_number_of_tries = 3
140 sleep_delay = 30 # seconds
143 rc = UTS.Popen(cmd, cwd=str(where.dir()), env=environment.environ.environ, logger=logger)
144 if rc.isOk() or (i_try>=max_number_of_tries):
146 logger.write('\ngit command failed! Wait %d seconds and give an other try (%d/%d)\n' % \
147 (sleep_delay, i_try + 1, max_number_of_tries), 3)
148 time.sleep(sleep_delay) # wait a little
153 def git_extract_sub_dir(from_what, tag, git_options, where, sub_dir, logger, environment=None):
154 '''Extracts sources from a subtree sub_dir of a git repository.
156 :param from_what str: The remote git repository.
157 :param tag str: The tag.
158 :param git_options str: git options
159 :param where str: The path where to extract.
160 :param sub_dir str: The relative path of subtree to extract.
161 :param logger Logger: The logger instance to use.
162 :param environment src.environment.Environ: The environment to source when extracting.
163 :return: True if the extraction is successful
166 strWhere = str(where)
167 tmpWhere = strWhere + '_tmp'
168 parentWhere = os.path.dirname(strWhere)
169 if not os.path.exists(parentWhere):
170 logger.error("not existing directory: %s" % parentWhere)
172 if os.path.isdir(strWhere):
173 logger.error("do not override existing directory: %s" % strWhere)
175 aDict = {'git_options': git_options,
180 'parentWhere': parentWhere,
181 'tmpWhere': tmpWhere,
183 DBG.write("git_extract_sub_dir", aDict)
184 if not src.architecture.is_windows():
187 export tmpDir=%(tmpWhere)s && \
189 git clone %(git_options)s %(remote)s $tmpDir && \
191 git checkout %(tag)s && \
192 mv %(sub_dir)s %(where)s && \
193 git log -1 > %(where)s/README_git_log.txt && \
199 set tmpDir=%(tmpWhere)s && \
201 git clone %(git_options)s %(remote)s $tmpDir && \
203 git checkout %(tag)s && \
204 mv %(sub_dir)s %(where)s && \
205 git log -1 > %(where)s/README_git_log.txt && \
209 DBG.write("cmd", cmd)
211 for nbtry in range(0,3): # retries case of network problem
212 rc = UTS.Popen(cmd, cwd=parentWhere, env=environment.environ.environ, logger=logger)
214 time.sleep(30) # wait a little
218 def archive_extract(from_what, where, logger):
219 '''Extracts sources from an archive.
221 :param from_what str: The path to the archive.
222 :param where str: The path where to extract.
223 :param logger Logger: The logger instance to use.
224 :return: True if the extraction is successful
228 archive = tarfile.open(from_what)
229 for i in archive.getmembers():
230 archive.extract(i, path=str(where))
231 return True, os.path.commonprefix(archive.getnames())
232 except Exception as exc:
233 logger.write("archive_extract: %s\n" % exc)
236 def cvs_extract(protocol, user, server, base, tag, product, where,
237 logger, checkout=False, environment=None):
238 '''Extracts sources from a cvs repository.
240 :param protocol str: The cvs protocol.
241 :param user str: The user to be used.
242 :param server str: The remote cvs server.
244 :param tag str: The tag.
245 :param product str: The product.
246 :param where str: The path where to extract.
247 :param logger Logger: The logger instance to use.
248 :param checkout boolean: If true use checkout cvs.
249 :param environment src.environment.Environ: The environment to source when
251 :return: True if the extraction is successful
256 if tag is not None and len(tag) > 0:
262 elif len(opttag) == 0:
265 if len(protocol) > 0:
266 root = "%s@%s:%s" % (user, server, base)
267 command = "cvs -d :%(protocol)s:%(root)s %(command)s -d %(where)s %(tag)s %(product)s" % \
268 { 'protocol': protocol, 'root': root, 'where': str(where.base()),
269 'tag': opttag, 'product': product, 'command': cmd }
271 command = "cvs -d %(root)s %(command)s -d %(where)s %(tag)s %(base)s/%(product)s" % \
272 { 'root': server, 'base': base, 'where': str(where.base()),
273 'tag': opttag, 'product': product, 'command': cmd }
275 logger.write(command + "\n", 5)
277 if not where.dir().exists():
280 logger.logTxtFile.write("\n" + command + "\n")
281 logger.logTxtFile.flush()
282 res = subprocess.call(command,
283 cwd=str(where.dir()),
284 env=environment.environ.environ,
286 stdout=logger.logTxtFile,
287 stderr=subprocess.STDOUT)
290 def svn_extract(user,
297 '''Extracts sources from a svn repository.
299 :param user str: The user to be used.
300 :param from_what str: The remote git repository.
301 :param tag str: The tag.
302 :param where str: The path where to extract.
303 :param logger Logger: The logger instance to use.
304 :param checkout boolean: If true use checkout svn.
305 :param environment src.environment.Environ: The environment to source when
307 :return: True if the extraction is successful
310 if not where.exists():
314 command = "svn checkout --username %(user)s %(remote)s %(where)s" % \
315 { 'remote': from_what, 'user' : user, 'where': str(where) }
318 if os.path.exists(str(where)):
319 command = "/bin/rm -rf %(where)s && " % \
320 { 'remote': from_what, 'where': str(where) }
323 command += "svn export --username %(user)s %(remote)s %(where)s" % \
324 { 'remote': from_what, 'user' : user, 'where': str(where) }
326 command += "svn export -r %(tag)s --username %(user)s %(remote)s %(where)s" % \
327 { 'tag' : tag, 'remote': from_what, 'user' : user, 'where': str(where) }
329 logger.logTxtFile.write(command + "\n")
331 logger.write(command + "\n", 5)
332 logger.logTxtFile.write("\n" + command + "\n")
333 logger.logTxtFile.flush()
334 res = subprocess.call(command,
335 cwd=str(where.dir()),
336 env=environment.environ.environ,
338 stdout=logger.logTxtFile,
339 stderr=subprocess.STDOUT)
342 def get_pkg_check_cmd(dist_name):
343 '''Build the command to use for checking if a linux package is installed or not.'''
345 if dist_name in ["CO","FD","MG","MD","CO","OS"]: # linux using rpm
347 manager_msg_err="Error : command failed because sat was not able to find apt command"
350 manager_msg_err="Error : command failed because sat was not able to find rpm command"
352 # 1- search for an installed package manager (rpm on rh, apt on db)
353 cmd_which_rpm=["which", "rpm"]
354 cmd_which_apt=["which", "apt"]
355 with open(os.devnull, 'w') as devnull:
356 # 1) we search for apt (debian based systems)
357 completed=subprocess.call(cmd_which_apt,stdout=devnull, stderr=subprocess.STDOUT)
358 if completed==0 and linux=="DB":
359 cmd_is_package_installed=["apt", "list", "--installed"]
361 # 2) if apt not found search for rpm (redhat)
362 completed=subprocess.call(cmd_which_rpm,stdout=devnull, stderr=subprocess.STDOUT) # only 3.8! ,capture_output=True)
363 if completed==0 and linux=="RH":
364 cmd_is_package_installed=["rpm", "-q"]
366 # no package manager was found corresponding to dist_name
367 raise src.SatException(manager_msg_err)
368 return cmd_is_package_installed
370 def check_system_pkg(check_cmd,pkg):
371 '''Check if a package is installed
372 :param check_cmd list: the list of command to use system package manager
373 :param user str: the pkg name to check
375 :return: a string with package name with status un message
378 FNULL = open(os.devnull, 'w')
379 cmd_is_package_installed=[]
380 for cmd in check_cmd:
381 cmd_is_package_installed.append(cmd)
382 cmd_is_package_installed.append(pkg)
385 if check_cmd[0]=="apt":
386 # special treatment for apt
387 # apt output is too messy for being used
388 # some debian packages have version numbers in their name, we need to add a *
389 # also apt do not return status, we need to use grep
390 # and apt output is too messy for being used
391 cmd_is_package_installed[-1]+="*" # we don't specify in pyconf the exact name because of version numbers
392 p=subprocess.Popen(cmd_is_package_installed,
393 stdout=subprocess.PIPE,
396 output = subprocess.check_output(['grep', pkg], stdin=p.stdout)
397 msg_status=src.printcolors.printcSuccess("OK")
399 msg_status=src.printcolors.printcError("KO")
400 msg_status+=" (package is not installed!)\n"
402 p=subprocess.Popen(cmd_is_package_installed,
403 stdout=subprocess.PIPE,
405 output, err = p.communicate()
408 msg_status=src.printcolors.printcSuccess("OK")
409 # in python3 output is a byte and should be decoded
410 if isinstance(output, bytes):
411 output = output.decode("utf-8", "ignore")
412 msg_status+=" (" + output.replace('\n',' ') + ")\n" # remove output trailing \n
414 msg_status=src.printcolors.printcError("KO")
415 msg_status+=" (package is not installed!)\n"