summaryrefslogtreecommitdiff
path: root/src/checkenv_resolver
blob: 6ebabaff6e6a92a02a0ace14bb8cc1819212ca6a (plain) (blame)
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
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
#!/usr/bin/env python
# Copyright (c) 2015, Joseph Hunkeler <jhunk at stsci.edu>
# All rights reserved.
#
# Redistribution and use in source and binary forms, with or without
# modification, are permitted provided that the following conditions are met:
#
# 1. Redistributions of source code must retain the above copyright notice, this
#   list of conditions and the following disclaimer.
# 2. Redistributions in binary form must reproduce the above copyright notice,
#   this list of conditions and the following disclaimer in the documentation
#   and/or other materials provided with the distribution.
#
# THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND
# ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
# WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
# DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR
# ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES
# (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
# LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND
# ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
# (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS
# SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
try:
    import argparse
except ImportError:
    print("Please install argparse.")
    exit(1)

import os
import sys
from string import Template


class PackageException(Exception):
    pass

class Package(object):
    def __init__(self, filename, load=True):
        self.valid_keywords = [
            'Type',
            'Requires',
            'Precedes',
            'Synopsis',
            'Description',
            'Environment',
            'LdLibrary',
            'IncPath',
            'Root',
            'Path',
            'ManPath',
            'Default',
            'Source'
        ]
        self.filename = os.path.join(ENVCONFIG_PATH, filename)
        self.exists = False
        self.name = ''
        self.name_internal = ''
        self.description = ''
        self.dependencies = []
        self.precedence = []
        self.priority = 0  # 0 - 99
        self.shell = ''
        self.env = {}
        self.script = ''
        self.invisible = False
        self.mtime = 0
        self.data = {}
        self.verbose = False

        if not load:
            return

        self.preload()

    def __repr__(self):
        return self.name

    def preload(self):
        if os.path.exists(self.filename):
            self.exists = True

        self.name = os.path.basename(self.filename.replace(' ', '_'))

        if self.filename is not None \
            and self.exists:
                self.data = self.load()
                self.get_requirements()
                self.get_precedence()

    def get_requirements(self):
        if not self.data:
            PackageException('{0}: Package data not loaded.'.format(self.name))

        if 'Requires' in self.data:
            for next_req in self.data['Requires']:
                try:
                    req = Package(next_req)
                except:
                    continue
                self.dependencies.append(req)
                if not req.exists and self.verbose:
                    print("Requirement warning, {0}: {1} does not exist".format(self.name, os.path.basename(req.filename)))

    def get_precedence(self):
        if not self.data:
            raise PackageException('{0}: Package data not loaded.'.format(self.name))

        if 'Precedes' in self.data:
            for next_req in self.data['Precedes']:
                req = Package(next_req, load=False)
                self.precedence.append(req)
                if not req.exists and self.verbose:
                    print("Precedence warning, {0}: {1} does not exist".format(self.name, os.path.basename(req.filename)))


    def load(self):
        pairs = []
        comment = '#'
        delimiter = ':'
        keyword = ''
        value = ''

        with open(self.filename, 'r') as f:
            for line in f.readlines():
                line = line.strip()
                if not line:
                    continue
                if not line.find(delimiter):
                    continue
                if line.startswith(comment):
                    continue

                keyword = line[0:line.find(delimiter)]
                if keyword not in self.valid_keywords:
                    continue
                if keyword == 'Source':
                    continue

                value = line[line.find(delimiter) + 1:].strip()
                pairs.append([keyword, value])

        # Do source block
        with open(self.filename, 'r') as f:
            value = ''
            shell_type = ''
            data_block = False

            for line in f.readlines():
                if line.startswith('Source:'):
                    data_block = True
                    shell_type = line[line.find(delimiter) + 1:line.rfind(delimiter)].strip()
                    line = line[line.rfind(delimiter) + 1:-1]
                if data_block:
                    value += line
                    if line.startswith('"') and line.endswith('\\'):
                        data_block = False

            pairs.append(['Source', value])
            pairs.append(['Shell', shell_type])

        pairs = dict(pairs)

        # Alias the filename to be the same as "Root" value
        if 'Root' in pairs:
            pairs[self.name] = pairs['Root']

        # Substitute configuration values
        for key, value in pairs.items():
            s = Template(value)
            pairs[key] = s.safe_substitute(pairs)

        if 'Requires' in pairs:
            pairs['Requires'] = str(pairs['Requires']).split()

        if 'Precedes' in pairs:
            pairs['Precedes'] = str(pairs['Precedes']).split()

        return dict(pairs)


spaces = ''
missing = ' Missing'.rjust(25, '.')
def solver(p, style='dependency'):
    ''' Recursive package dependency resolver
    '''
    flags = ''
    tree = '  \\_'
    resolver = p.dependencies

    if args.no_graphics:
        tree = ' '

    if style != 'dependency':
        resolver = p.precedence

    # Wasn't planning on using a global here, but... recursion.
    global spaces
    global missing
    for dep in resolver:
        if not dep.exists:
            flags = missing
        print('{0} {1}{2:20s} {3}'.format(spaces, tree, dep.name, flags))
        flags = ''
        if dep.dependencies:
            spaces += '    '
            # Fall back in on yourself if there are more dependencies
            # beyond the current 'dep'
            solver(dep, style)
        spaces = ''

def show_package_map(packages, style='dependency'):
    tree = '*--'
    global missing

    if args.no_graphics:
        tree = ''

    for pkg in pkgs:
        flags = ''
        if not pkg.exists:
            flags = missing
        print('{0}{1:22s} {2}'.format(tree, pkg.name, flags))
        solver(pkg, style)
    print('')


if __name__ == '__main__':
    args = None
    ENVCONFIG_PATH = os.path.abspath('/usr/local/envconfig')
    HOME = os.environ['HOME']
    ENVRC = os.path.join(HOME, '.envrc')
    pkgs = []

    parser = argparse.ArgumentParser()
    parser.add_argument('-e', '--every', action='store_true', help='Generate map for all packages')
    parser.add_argument('-r', '--requires', action='store_true', help='Omit package dependencies')
    parser.add_argument('-p', '--precedence', action='store_true', help='Omit package precedence')
    parser.add_argument('-w', '--warnings', action='store_true', help='No tree, only warnings')
    parser.add_argument('-g', '--no-graphics', action='store_true', help='No tree characters')

    args = parser.parse_args()


    if args.every:
        for r, d, fs in os.walk(ENVCONFIG_PATH):
            for f in fs:
                pkgs.append(Package(f))
    else:
        try:
            with open(ENVRC, 'r') as fp:
                for record in fp:
                    if record.startswith('#'):
                        continue

                    if record.startswith('Package:'):
                        _, _, record = record.partition(':')
                    else:
                        continue

                    record = record.strip()
                    pkgs.append(Package(record))
        except OSError as e:
            print(e.message)

    if not args.requires and not args.precedence:
        print('To see a summary of available options, issue -h or --help')
        exit(0)

    if args.warnings:
        for pkg in pkgs:
            pkg.verbose = True

            if not pkg.exists:
                # Normally the object performs its own checks to make sure
                # it can read precedence, but we're overriding that functionality.
                print('General failure, {0}: {1} does not exist'.format(pkg.name))

            if args.requires:
                pkg.get_requirements()
            if args.precedence:
                pkg.get_precedence()

        exit(0)

    if args.requires:
        print("####              ####")
        print("### Dependency Map ###")
        print("####              ####")
        show_package_map(pkgs)
        print('')

    if args.precedence:
        print("####              ####")
        print("### Precedence Map ###")
        print("####              ####")
        show_package_map(pkgs, style='precedence')
        print('')

    exit(0)