Skip to content
tools.py 2.33 KiB
Newer Older
Seblu's avatar
Seblu committed
#!/usr/bin/env python
# -*- coding: utf-8 -*-
# Started 26/05/2011 by Seblu <seblu@seblu.net>

'''
InstallSystems Generic Tools Library
'''

import os
import hashlib
Seblu's avatar
Seblu committed
import shutil
import urllib2
Seblu's avatar
Seblu committed

def md5sum(path):
Seblu's avatar
Seblu committed
    '''Compute md5 of a file'''
    m = hashlib.md5()
    m.update(open(path, "r").read())
    return m.hexdigest()

def copy(source, destination, uid=None, gid=None, mode=None, timeout=None):
Seblu's avatar
Seblu committed
    '''Copy a source to destination. Take care of path type'''
    stype = pathtype(source)
    dtype = pathtype(destination)
    # ensure destination is not a directory
    if dtype == "file" and os.path.isdir(destination):
        destination = os.path.join(destination, os.path.basename(source))
    # trivial case
Seblu's avatar
Seblu committed
    if stype == dtype == "file":
        shutil.copy(source, destination)
    elif stype == "http" and dtype == "file":
        f_dest = open(destination, "w")
        f_source = urllib2.urlopen(source, timeout=timeout)
        f_dest.write(f_source.read())
Seblu's avatar
Seblu committed
    elif stype == "file" and dtype == "":
Seblu's avatar
Seblu committed
        raise NotImplementedError
    else:
        raise NotImplementedError
    # setting destination file rights
    if dtype == "file":
        chrights(destination, uid, gid, mode)
Seblu's avatar
Seblu committed

def mkdir(path, uid=None, gid=None, mode=None):
    '''Create a directory and set rights'''
    os.mkdir(path)
    chrights(path, uid, gid, mode)

def chrights(path, uid=None, gid=None, mode=None):
    '''Set rights on a file'''
    if uid is not None:
        os.chown(path, uid, -1)
    if gid is not None:
        os.chown(path, -1, gid)
    if mode is not None:
        os.chmod(path, mode)

def pathtype(path):
Seblu's avatar
Seblu committed
    '''Return path type. This is usefull to know what king of path is given'''
    from installsystems.image import Image
Seblu's avatar
Seblu committed
    if path.startswith("http://") or path.startswith("https://"):
        return "http"
    elif path.startswith("ssh://"):
        return "ssh"
Seblu's avatar
Seblu committed
    elif path.startswith("file://") or path.startswith("/") or os.path.exists(path):
Seblu's avatar
Seblu committed
        return "file"
    elif Image.check_image_name(path):
        return "name"
Seblu's avatar
Seblu committed
    return None

def abspath(path):
    '''Format a path to be absolute'''
    ptype = pathtype(path)
Seblu's avatar
Seblu committed
    if ptype in ("http", "ssh"):
        return path
    elif ptype == "file":
        if path.startswith("file://"):
            path = path[len("file://")]
        return os.path.abspath(path)
    else:
        return None