2014-01-08 17:21:02 +08:00
|
|
|
##############################################################################
|
|
|
|
# Copyright (c) 2013, Lawrence Livermore National Security, LLC.
|
|
|
|
# Produced at the Lawrence Livermore National Laboratory.
|
2014-01-13 01:19:18 +08:00
|
|
|
#
|
2014-01-08 17:21:02 +08:00
|
|
|
# This file is part of Spack.
|
|
|
|
# Written by Todd Gamblin, tgamblin@llnl.gov, All rights reserved.
|
|
|
|
# LLNL-CODE-647188
|
2014-01-13 01:19:18 +08:00
|
|
|
#
|
2014-01-08 17:21:02 +08:00
|
|
|
# For details, see https://scalability-llnl.github.io/spack
|
|
|
|
# Please also see the LICENSE file for our notice and the LGPL.
|
2014-01-13 01:19:18 +08:00
|
|
|
#
|
2014-01-08 17:21:02 +08:00
|
|
|
# This program is free software; you can redistribute it and/or modify
|
|
|
|
# it under the terms of the GNU General Public License (as published by
|
|
|
|
# the Free Software Foundation) version 2.1 dated February 1999.
|
2014-01-13 01:19:18 +08:00
|
|
|
#
|
2014-01-08 17:21:02 +08:00
|
|
|
# This program is distributed in the hope that it will be useful, but
|
|
|
|
# WITHOUT ANY WARRANTY; without even the IMPLIED WARRANTY OF
|
|
|
|
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the terms and
|
|
|
|
# conditions of the GNU General Public License for more details.
|
2014-01-13 01:19:18 +08:00
|
|
|
#
|
2014-01-08 17:21:02 +08:00
|
|
|
# You should have received a copy of the GNU Lesser General Public License
|
|
|
|
# along with this program; if not, write to the Free Software Foundation,
|
|
|
|
# Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
|
|
|
|
##############################################################################
|
2014-11-06 01:54:43 +08:00
|
|
|
__all__ = ['set_install_permissions', 'install', 'expand_user', 'working_dir',
|
|
|
|
'touch', 'mkdirp', 'force_remove', 'join_path', 'ancestor',
|
2015-01-08 03:48:21 +08:00
|
|
|
'can_access', 'filter_file', 'change_sed_delimiter', 'is_exe',
|
|
|
|
'check_link_tree', 'merge_link_tree', 'unmerge_link_tree']
|
2014-06-18 08:26:45 +08:00
|
|
|
|
2013-10-08 09:54:58 +08:00
|
|
|
import os
|
2014-07-03 14:22:38 +08:00
|
|
|
import sys
|
2013-10-08 09:54:58 +08:00
|
|
|
import re
|
|
|
|
import shutil
|
2014-12-26 09:55:19 +08:00
|
|
|
import stat
|
2013-10-08 09:54:58 +08:00
|
|
|
import errno
|
2013-11-25 05:54:33 +08:00
|
|
|
import getpass
|
2013-10-08 09:54:58 +08:00
|
|
|
from contextlib import contextmanager, closing
|
2014-07-03 14:22:38 +08:00
|
|
|
from tempfile import NamedTemporaryFile
|
2013-10-08 09:54:58 +08:00
|
|
|
|
2014-03-13 10:24:47 +08:00
|
|
|
import llnl.util.tty as tty
|
2013-10-08 09:54:58 +08:00
|
|
|
from spack.util.compression import ALLOWED_ARCHIVE_TYPES
|
|
|
|
|
2013-11-25 05:54:33 +08:00
|
|
|
|
2014-09-28 11:47:38 +08:00
|
|
|
def filter_file(regex, repl, *filenames, **kwargs):
|
2014-07-03 14:22:38 +08:00
|
|
|
"""Like sed, but uses python regular expressions.
|
|
|
|
|
|
|
|
Filters every line of file through regex and replaces the file
|
|
|
|
with a filtered version. Preserves mode of filtered files.
|
|
|
|
|
|
|
|
As with re.sub, ``repl`` can be either a string or a callable.
|
|
|
|
If it is a callable, it is passed the match object and should
|
|
|
|
return a suitable replacement string. If it is a string, it
|
|
|
|
can contain ``\1``, ``\2``, etc. to represent back-substitution
|
|
|
|
as sed would allow.
|
2014-09-28 11:47:38 +08:00
|
|
|
|
|
|
|
Keyword Options:
|
|
|
|
string[=False] If True, treat regex as a plain string.
|
|
|
|
backup[=True] Make a backup files suffixed with ~
|
|
|
|
ignore_absent[=False] Ignore any files that don't exist.
|
2014-07-03 14:22:38 +08:00
|
|
|
"""
|
2014-09-28 11:47:38 +08:00
|
|
|
string = kwargs.get('string', False)
|
|
|
|
backup = kwargs.get('backup', True)
|
|
|
|
ignore_absent = kwargs.get('ignore_absent', False)
|
|
|
|
|
|
|
|
# Allow strings to use \1, \2, etc. for replacement, like sed
|
|
|
|
if not callable(repl):
|
2014-07-03 14:22:38 +08:00
|
|
|
unescaped = repl.replace(r'\\', '\\')
|
2014-12-26 08:07:39 +08:00
|
|
|
def replace_groups_with_groupid(m):
|
|
|
|
def groupid_to_group(x):
|
|
|
|
return m.group(int(x.group(1)))
|
|
|
|
return re.sub(r'\\([1-9])', groupid_to_group, unescaped)
|
|
|
|
repl = replace_groups_with_groupid
|
2014-07-03 14:22:38 +08:00
|
|
|
|
2014-09-28 11:47:38 +08:00
|
|
|
if string:
|
|
|
|
regex = re.escape(regex)
|
|
|
|
|
2014-07-03 14:22:38 +08:00
|
|
|
for filename in filenames:
|
|
|
|
backup = filename + "~"
|
2014-09-28 11:47:38 +08:00
|
|
|
|
|
|
|
if ignore_absent and not os.path.exists(filename):
|
|
|
|
continue
|
|
|
|
|
2014-07-03 14:22:38 +08:00
|
|
|
shutil.copy(filename, backup)
|
|
|
|
try:
|
|
|
|
with closing(open(backup)) as infile:
|
|
|
|
with closing(open(filename, 'w')) as outfile:
|
|
|
|
for line in infile:
|
|
|
|
foo = re.sub(regex, repl, line)
|
|
|
|
outfile.write(foo)
|
|
|
|
except:
|
|
|
|
# clean up the original file on failure.
|
|
|
|
shutil.move(backup, filename)
|
|
|
|
raise
|
|
|
|
|
2014-09-28 11:47:38 +08:00
|
|
|
finally:
|
|
|
|
if not backup:
|
|
|
|
shutil.rmtree(backup, ignore_errors=True)
|
|
|
|
|
2014-07-03 14:22:38 +08:00
|
|
|
|
|
|
|
def change_sed_delimiter(old_delim, new_delim, *filenames):
|
|
|
|
"""Find all sed search/replace commands and change the delimiter.
|
|
|
|
e.g., if the file contains seds that look like 's///', you can
|
|
|
|
call change_sed_delimeter('/', '@', file) to change the
|
|
|
|
delimiter to '@'.
|
|
|
|
|
|
|
|
NOTE that this routine will fail if the delimiter is ' or ".
|
|
|
|
Handling those is left for future work.
|
|
|
|
"""
|
|
|
|
assert(len(old_delim) == 1)
|
|
|
|
assert(len(new_delim) == 1)
|
|
|
|
|
|
|
|
# TODO: handle these cases one day?
|
|
|
|
assert(old_delim != '"')
|
|
|
|
assert(old_delim != "'")
|
|
|
|
assert(new_delim != '"')
|
|
|
|
assert(new_delim != "'")
|
|
|
|
|
|
|
|
whole_lines = "^s@([^@]*)@(.*)@[gIp]$"
|
|
|
|
whole_lines = whole_lines.replace('@', old_delim)
|
|
|
|
|
|
|
|
single_quoted = r"'s@((?:\\'|[^@'])*)@((?:\\'|[^'])*)@[gIp]?'"
|
|
|
|
single_quoted = single_quoted.replace('@', old_delim)
|
|
|
|
|
|
|
|
double_quoted = r'"s@((?:\\"|[^@"])*)@((?:\\"|[^"])*)@[gIp]?"'
|
|
|
|
double_quoted = double_quoted.replace('@', old_delim)
|
|
|
|
|
|
|
|
repl = r's@\1@\2@g'
|
|
|
|
repl = repl.replace('@', new_delim)
|
|
|
|
|
|
|
|
for f in filenames:
|
|
|
|
filter_file(whole_lines, repl, f)
|
|
|
|
filter_file(single_quoted, "'%s'" % repl, f)
|
|
|
|
filter_file(double_quoted, '"%s"' % repl, f)
|
|
|
|
|
|
|
|
|
2014-11-06 01:54:43 +08:00
|
|
|
def set_install_permissions(path):
|
|
|
|
"""Set appropriate permissions on the installed file."""
|
|
|
|
if os.path.isdir(path):
|
|
|
|
os.chmod(path, 0755)
|
|
|
|
else:
|
|
|
|
os.chmod(path, 0644)
|
|
|
|
|
|
|
|
|
2013-10-08 09:54:58 +08:00
|
|
|
def install(src, dest):
|
|
|
|
"""Manually install a file to a particular location."""
|
|
|
|
tty.info("Installing %s to %s" % (src, dest))
|
|
|
|
shutil.copy(src, dest)
|
2014-11-06 01:54:43 +08:00
|
|
|
set_install_permissions(dest)
|
2013-10-08 09:54:58 +08:00
|
|
|
|
2014-12-26 09:55:19 +08:00
|
|
|
src_mode = os.stat(src).st_mode
|
|
|
|
dest_mode = os.stat(dest).st_mode
|
|
|
|
if src_mode | stat.S_IXUSR: dest_mode |= stat.S_IXUSR
|
|
|
|
if src_mode | stat.S_IXGRP: dest_mode |= stat.S_IXGRP
|
|
|
|
if src_mode | stat.S_IXOTH: dest_mode |= stat.S_IXOTH
|
|
|
|
os.chmod(dest, dest_mode)
|
|
|
|
|
2013-10-08 09:54:58 +08:00
|
|
|
|
2015-01-23 05:52:28 +08:00
|
|
|
def is_exe(path):
|
|
|
|
"""True if path is an executable file."""
|
|
|
|
return os.path.isfile(path) and os.access(path, os.X_OK)
|
|
|
|
|
|
|
|
|
2013-11-25 05:54:33 +08:00
|
|
|
def expand_user(path):
|
|
|
|
"""Find instances of '%u' in a path and replace with the current user's
|
|
|
|
username."""
|
|
|
|
username = getpass.getuser()
|
|
|
|
if not username and '%u' in path:
|
|
|
|
tty.die("Couldn't get username to complete path '%s'" % path)
|
|
|
|
|
|
|
|
return path.replace('%u', username)
|
|
|
|
|
|
|
|
|
2014-08-01 23:33:00 +08:00
|
|
|
def mkdirp(*paths):
|
2014-10-28 05:42:48 +08:00
|
|
|
"""Creates a directory, as well as parent directories if needed."""
|
2014-08-01 23:33:00 +08:00
|
|
|
for path in paths:
|
|
|
|
if not os.path.exists(path):
|
|
|
|
os.makedirs(path)
|
|
|
|
elif not os.path.isdir(path):
|
|
|
|
raise OSError(errno.EEXIST, "File alredy exists", path)
|
|
|
|
|
|
|
|
|
2014-11-06 01:54:43 +08:00
|
|
|
def force_remove(*paths):
|
|
|
|
"""Remove files without printing errors. Like rm -f, does NOT
|
|
|
|
remove directories."""
|
|
|
|
for path in paths:
|
|
|
|
try:
|
|
|
|
os.remove(path)
|
|
|
|
except OSError, e:
|
|
|
|
pass
|
|
|
|
|
2013-10-08 09:54:58 +08:00
|
|
|
@contextmanager
|
2014-08-01 23:33:00 +08:00
|
|
|
def working_dir(dirname, **kwargs):
|
|
|
|
if kwargs.get('create', False):
|
|
|
|
mkdirp(dirname)
|
|
|
|
|
2013-10-08 09:54:58 +08:00
|
|
|
orig_dir = os.getcwd()
|
|
|
|
os.chdir(dirname)
|
|
|
|
yield
|
|
|
|
os.chdir(orig_dir)
|
|
|
|
|
|
|
|
|
2014-02-09 10:11:54 +08:00
|
|
|
def touch(path):
|
2014-10-28 05:42:48 +08:00
|
|
|
"""Creates an empty file at the specified path."""
|
2014-02-09 10:11:54 +08:00
|
|
|
with closing(open(path, 'a')) as file:
|
|
|
|
os.utime(path, None)
|
|
|
|
|
|
|
|
|
2014-03-13 10:24:47 +08:00
|
|
|
def join_path(prefix, *args):
|
2013-11-24 05:04:36 +08:00
|
|
|
path = str(prefix)
|
2013-10-08 09:54:58 +08:00
|
|
|
for elt in args:
|
|
|
|
path = os.path.join(path, str(elt))
|
|
|
|
return path
|
|
|
|
|
|
|
|
|
|
|
|
def ancestor(dir, n=1):
|
|
|
|
"""Get the nth ancestor of a directory."""
|
|
|
|
parent = os.path.abspath(dir)
|
|
|
|
for i in range(n):
|
|
|
|
parent = os.path.dirname(parent)
|
|
|
|
return parent
|
|
|
|
|
|
|
|
|
2013-12-21 06:30:45 +08:00
|
|
|
def can_access(file_name):
|
|
|
|
"""True if we have read/write access to the file."""
|
|
|
|
return os.access(file_name, os.R_OK|os.W_OK)
|
2015-01-08 03:48:21 +08:00
|
|
|
|
|
|
|
|
|
|
|
def traverse_link_tree(src_root, dest_root, follow_nonexisting=True, **kwargs):
|
|
|
|
# Yield directories before or after their contents.
|
|
|
|
order = kwargs.get('order', 'pre')
|
|
|
|
if order not in ('pre', 'post'):
|
|
|
|
raise ValueError("Order must be 'pre' or 'post'.")
|
|
|
|
|
|
|
|
# List of relative paths to ignore under the src root.
|
|
|
|
ignore = kwargs.get('ignore', None)
|
|
|
|
if isinstance(ignore, basestring):
|
|
|
|
ignore = (ignore,)
|
|
|
|
|
|
|
|
for dirpath, dirnames, filenames in os.walk(src_root):
|
|
|
|
rel_path = dirpath[len(src_root):]
|
|
|
|
rel_path = rel_path.lstrip(os.path.sep)
|
|
|
|
dest_dirpath = os.path.join(dest_root, rel_path)
|
|
|
|
|
|
|
|
# Don't descend into ignored directories
|
|
|
|
if ignore and dest_dirpath in ignore:
|
|
|
|
return
|
|
|
|
|
|
|
|
# Don't descend into dirs in dest that do not exist in src.
|
|
|
|
if not follow_nonexisting:
|
|
|
|
dirnames[:] = [
|
|
|
|
d for d in dirnames
|
|
|
|
if os.path.exists(os.path.join(dest_dirpath, d))]
|
|
|
|
|
|
|
|
# preorder yields directories before children
|
|
|
|
if order == 'pre':
|
|
|
|
yield (dirpath, dest_dirpath)
|
|
|
|
|
|
|
|
for name in filenames:
|
|
|
|
src_file = os.path.join(dirpath, name)
|
|
|
|
dest_file = os.path.join(dest_dirpath, name)
|
|
|
|
|
|
|
|
# Ignore particular paths inside the install root.
|
|
|
|
src_relpath = src_file[len(src_root):]
|
|
|
|
src_relpath = src_relpath.lstrip(os.path.sep)
|
|
|
|
if ignore and src_relpath in ignore:
|
|
|
|
continue
|
|
|
|
|
|
|
|
yield (src_file, dest_file)
|
|
|
|
|
|
|
|
# postorder yields directories after children
|
|
|
|
if order == 'post':
|
|
|
|
yield (dirpath, dest_dirpath)
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
def check_link_tree(src_root, dest_root, **kwargs):
|
|
|
|
for src, dest in traverse_link_tree(src_root, dest_root, False, **kwargs):
|
|
|
|
if os.path.exists(dest) and not os.path.isdir(dest):
|
|
|
|
return dest
|
|
|
|
return None
|
|
|
|
|
|
|
|
|
|
|
|
def merge_link_tree(src_root, dest_root, **kwargs):
|
|
|
|
kwargs['order'] = 'pre'
|
|
|
|
for src, dest in traverse_link_tree(src_root, dest_root, **kwargs):
|
|
|
|
if os.path.isdir(src):
|
|
|
|
mkdirp(dest)
|
|
|
|
else:
|
|
|
|
assert(not os.path.exists(dest))
|
|
|
|
os.symlink(src, dest)
|
|
|
|
|
|
|
|
|
|
|
|
def unmerge_link_tree(src_root, dest_root, **kwargs):
|
|
|
|
kwargs['order'] = 'post'
|
|
|
|
for src, dest in traverse_link_tree(src_root, dest_root, **kwargs):
|
|
|
|
if os.path.isdir(dest):
|
|
|
|
if not os.listdir(dest):
|
|
|
|
# TODO: what if empty directories were present pre-merge?
|
|
|
|
shutil.rmtree(dest, ignore_errors=True)
|
|
|
|
|
|
|
|
elif os.path.exists(dest):
|
|
|
|
if not os.path.islink(dest):
|
|
|
|
raise ValueError("%s is not a link tree!" % dest)
|
|
|
|
os.remove(dest)
|