summaryrefslogtreecommitdiffstats
path: root/base/util.py
blob: e1331493e0908533f72c31d3ce8e3182cf174834 (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
# Fedora Developer Shell
#
# 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 of the License.
#
# 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
# GNU Library General Public License for more details.
#
# You should have received a copy of the GNU 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.
#
# Authors: Yaakov M. Nemoy <ynemoy@redhat.com>
#

from __future__ import with_statement

from contextlib import contextmanager
from os import chdir, getcwd, remove
from os import symlink as sym
from os.path import abspath, lexists, isdir, islink
from shutil import copyfileobj, rmtree
from shutil import move as mv

from base import log

@contextmanager
def pwd(dir):
    old_dir = getcwd()
    log.debug('changing dir to %s' % dir)
    chdir(dir)
    yield
    log.debug('changing dir to %s' % old_dir)
    chdir(old_dir)

def rm(tgt):
    if isdir(tgt):
        rmtree(tgt)
    else:
        remove(tgt)
        
def copy(src, dst):
    # we're using copyfileobj so later we can do this from a URL
    src = file(src, 'rb')
    dst = file(dst, 'wb')
    copyfileobj(src, dst)
    src.close()
    dst.close()

def symlink(src, dst):
    if lexists(dst):
        rm(dst)
    sym(abspath(src), abspath(dst))
    
def move(src, dst):
    if lexists(dst):
        rm(dst)
    mv(src, dst)

def one(l, f):
    for x in l:
        if f(x):
            return x
    
__all__ = ['pwd', 'copy', 'with_sudo', 'with_su', 'symlink', 'move']