summaryrefslogtreecommitdiffstats
path: root/make/lib/hb_distfile.py
blob: 28b0706a7da6f2a750c7b90c352ea221194540a8 (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
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
###############################################################################
##
## Coded for minimum version of Python 2.7 .
##
## Python3 is incompatible.
##
## Authors: konablend
##
###############################################################################

import json
import os
import random
import re
import string
import sys
import traceback

from optparse import OptionParser

###############################################################################

class Tool(object):
    LOG_QUIET   = 0
    LOG_INFO    = 1
    LOG_VERBOSE = 2
    LOG_DEBUG   = 3

    def __init__(self):
        self.name = os.path.splitext(os.path.basename(sys.argv[0]))[0]
        self.parser = OptionParser()
        self.parser.add_option('-v', '--verbose', default=Tool.LOG_INFO, action='count', dest='verbosity', help='increase verbosity')
        self.parser.add_option('--config', default=None, action='callback', metavar='FILE', type='str', callback=self._load_config, help='specify configuration file')

    def _parse(self):
        (self.options,self.args) = self.parser.parse_args()

    ## be sure not to use any methods referencing self.options as we are still parsing args
    def _load_config(self, option, opt, value, parser):
        with open(value, 'r') as file:
            data = json.load(file)
        parser.values.verbosity = data['verbosity']
        extend = getattr(self, '_load_config2', None)
        if extend:
            extend(parser, data)

    ## newline not required
    def errln(self, format, *args, **kwargs):
        s = (format % args)
        if re.match('^.*[!?:;.]$', s):
            if kwargs.get('exit', None) != None:
                sys.stderr.write('ERROR: %s stop.\n' % (s))
                sys.exit(1)
            sys.stderr.write('ERROR: %s continuing\n' % (s))
        else:
            if kwargs.get('exit', None) != None:
                sys.stderr.write('ERROR: %s; stop.\n' % (s))
                sys.exit(1)
            sys.stderr.write('ERROR: %s; continuing.\n' % (s))

    ## newline not required
    def warnln(self, format, *args):
        s = (format % args)
        if re.match( '^.*[!?:;.]$', s ):
            sys.stdout.write('WARNING: %s continuing.\n' % (s))
        else:
            sys.stdout.write('WARNING: %s; continuing.\n' % (s))

    ## newline required
    def infof(self, format, *args):
        if self.options.verbosity >= Tool.LOG_INFO:
            sys.stdout.write(format % args)

    ## newline not required
    def progressf(self, percent, format, *args):
        if self.options.verbosity >= Tool.LOG_INFO:
            sys.stdout.write(format % args)
            if percent >= 0:
                sys.stdout.write("  [%-20s] %.1f%%" % ('='*int(percent*20), percent*100))
            sys.stdout.write('\n')      # needed to flush on some systems
            if self.options.jobs == 1 and os.name != 'nt':
                sys.stdout.write('\033[F')  # reuse line
            sys.stdout.flush()

    ## newline required
    def verbosef(self, format, *args):
        if self.options.verbosity >= Tool.LOG_VERBOSE:
            sys.stdout.write(format % args)

    ## newline required
    def debugf(self, format, *args):
        if self.options.verbosity >= Tool.LOG_DEBUG:
            sys.stdout.write(format % args)

    def debug_exception(self, xinfo=None):
        if self.options.verbosity >= Tool.LOG_DEBUG:
            if not xinfo:
                xinfo = sys.exc_info()
            traceback.print_exception(*xinfo)

    ## generate a temporary filename - not worried about race conditions
    def mktmpname(self, filename):
        return filename + '.' + ''.join(random.choice(string.ascii_lowercase + string.digits) for _ in range(8)) + '.tmp'

###############################################################################

class ToolError(Exception):
    def __init__(self, op='unknown', text=None):
        self.op = op
        self.text = text

    def __call__(self, text):
        self.text = text
        return self

    def __str__(self):
        return self.text