Completed
Pull Request — develop (#5)
by Kale
55s
created

auxlib.absdirname()   A

Complexity

Conditions 1

Size

Total Lines 2

Duplication

Lines 0
Ratio 0 %
Metric Value
cc 1
dl 0
loc 2
rs 10
1
# -*- coding: utf-8 -*-
2
from __future__ import print_function, division, absolute_import
3
import logging
4
import pkg_resources
5
import site
6
import sys
7
8
from os.path import join, exists, dirname, expanduser, abspath, expandvars, normpath
9
10
log = logging.getLogger(__name__)
11
12
13
def site_packages_paths():
14
    if hasattr(sys, 'real_prefix'):
15
        # in a virtualenv
16
        log.debug('searching virtualenv')
17
        return [p for p in sys.path if p.endswith('site-packages')]
18
    else:
19
        # not in a virtualenv
20
        log.debug('searching outside virtualenv')
21
        return site.getsitepackages()
22
23
24
class PackageFile(object):
25
26
    def __init__(self, file_path, package_name=None):
27
        self.file_path = file_path
28
        self.package_name = package_name
29
30
    def __enter__(self):
31
        self.file_handle = open_package_file(self.file_path, self.package_name)
32
        return self.file_handle
33
34
    def __exit__(self, type, value, traceback):
35
        self.file_handle.close()
36
37
38
def open_package_file(file_path, package_name):
39
    file_path = expand(file_path)
40
41
    # look for file at relative path
42
    if exists(file_path):
43
        log.info("found real file {}".format(file_path))
44
        return open(file_path)
45
46
    # look for file in package resources
47
    if package_name and pkg_resources.resource_exists(package_name, file_path):
48
        log.info("found package resource file {} for package {}".format(file_path, package_name))
49
        return pkg_resources.resource_stream(package_name, file_path)
50
51
    # look for file in site-packages
52
    package_path = package_name.replace('.', '/')
53
    for site_packages_path in site_packages_paths():
54
        test_path = join(site_packages_path, package_path, file_path)
55
        if exists(test_path):
56
            log.info("found site-package file {} for package {}".format(file_path, package_name))
57
            return open(test_path)
58
59
    msg = "file for module [{}] cannot be found at path {}".format(package_name, file_path)
60
    log.error(msg)
61
    raise IOError(msg)
62
63
64
def expand(path):
65
    return normpath(expanduser(expandvars(path)))
66
67
68
def absdirname(path):
69
    return abspath(expanduser(dirname(path)))
70