summaryrefslogtreecommitdiffstats
path: root/base/util.py
blob: b53a9187cbf5e61b3fad799104b901563c6cc865 (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
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']