~brian-murray/ubuntu-archive-tools/pup-raring

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
#!/usr/bin/python

# Copyright (C) 2011, 2012  Canonical Ltd.
# Author: Martin Pitt <martin.pitt@ubuntu.com>

# This program is free software: you can redistribute it and/or modify
# it under the terms of the GNU General Public License as published by
# the Free Software Foundation; version 3 of the License.
#
# This program is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
# GNU General Public License for more details.
#
# You should have received a copy of the GNU General Public License
# along with this program.  If not, see <http://www.gnu.org/licenses/>.

# Generate a HTML report of current NBS binary packages from a checkrdepends
# output directory

from __future__ import print_function

from collections import defaultdict
import os
import sys
import time


if len(sys.argv) != 2:
    print('Usage: %s <checkrdepends output dir>' % sys.argv[0],
          file=sys.stderr)
    sys.exit(1)


def parse_checkrdepends_file(path, pkgmap):
    '''Parse one checkrdepends file into the NBS map'''

    cur_component = None
    cur_arch = None

    with open(path) as f:
        for line in f:
            if line.startswith('-- '):
                (cur_component, cur_arch) = line.split('/', 1)[1].split()[:2]
                continue
            assert cur_component
            assert cur_arch

            rdep = line.strip().split()[0]
            pkgmap.setdefault(rdep, (cur_component, []))[1].append(cur_arch)


def _pkg_removable(pkg, nbs, checked_v):
    '''Recursively check if pakcage is removable.

    checked_v is the working set of already checked vertices, to avoid infinite
    loops.
    '''
    checked_v.add(pkg)
    for rdep in nbs.get(pkg, []):
        if rdep in checked_v:
            continue
        #checked_v.add(rdep)
        if not rdep in nbs:
            try:
                checked_v.remove(rdep)
            except KeyError:
                pass
            return False
        if not _pkg_removable(rdep, nbs, checked_v):
            try:
                checked_v.remove(rdep)
            except KeyError:
                pass
            return False
    return True


def get_removables(nbs):
    '''Get set of removable packages.

    This includes packages with no rdepends and disconnected subgraphs, i. e.
    clusters of NBS packages which only depend on each other.
    '''
    removable = set()

    for p in nbs:
        if p in removable:
            continue
        checked_v = set()
        if _pkg_removable(p, nbs, checked_v):
            # we can add the entire cluster here, not just p; avoids
            # re-checking the other vertices in that cluster
            removable.update(checked_v)

    return removable


def html_report(nbs, removables):
    '''Generate HTML report from NBS map.'''

    print('''\
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.1//EN"
 "http://www.w3.org/TR/xhtml11/DTD/xhtml11.dtd">
<html xmlns="http://www.w3.org/1999/xhtml" xml:lang="en">
<head>
  <meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
  <title>NBS packages</title>
  <style type="text/css">
    body { background: #CCCCB0; color: black; }
    a { text-decoration: none; }
    table { border-collapse: collapse; border-style: none none;
            margin-bottom: 3ex; empty-cells: show; }
    table th { text-align: left; border-style: solid none none none;
               border-width: 3px; padding-right: 10px; }
    table td { vertical-align:top; text-align: left; border-style: dotted none;
               border-width: 1px; padding-right: 10px; }
    .normal { }
    .removable { color: green; font-weight: bold; }
    .nbs { color: blue; }
    .componentsup { font-size: 70%; color: red; font-weight: bold; }
    .componentunsup { font-size: 70%; color: darkred; }
  </style>
</head>
<body>
<h1>NBS: Binary packages not built from any source</h1>

<h2>Archive Administrator commands</h2>
<p>Run this command to remove NBS packages which are not required any more:</p>
''')

    print('<p style="font-family: monospace">remove-package -m NBS -b -y %s'
          '</p>' % ' '.join(sorted(removables)))

    print('''
<h2>Reverse dependencies</h2>

<p><span class="nbs">Reverse dependencies which are NBS themselves</span><br/>
<span class="removable">NBS package which can be removed safely</span></p>
<table>
''')
    reverse_nbs = defaultdict(list)  # non_nbs_pkg -> [nbspkg1, ...]
    pkg_component = {}  # non_nbs_pkg -> (component, component_class)

    for pkg in sorted(nbs):
        nbsmap = nbs[pkg]
        if pkg in removables:
            cls = 'removable'
        else:
            cls = 'normal'
        print('<tr><th colspan="4"><span class="%s">%s</span></td></tr>' %
              (cls, pkg), end="")
        for rdep in sorted(nbsmap):
            (component, arches) = nbsmap[rdep]

            if component in ('main', 'restricted'):
                component_cls = 'sup'
            else:
                component_cls = 'unsup'

            if rdep in nbs:
                if rdep in removables:
                    cls = 'removable'
                else:
                    cls = 'nbs'
            else:
                cls = 'normal'
                reverse_nbs[rdep].append(pkg)
                pkg_component[rdep] = (component, component_cls)

            print('<tr><td>&nbsp; &nbsp; </td>', end='')
            print('<td><span class="%s">%s</span></td> ' % (cls, rdep), end='')
            print('<td><span class="component%s">%s</span></td>' %
                  (component_cls, component), end='')
            print('<td>%s</td></tr>' % ' '.join(arches))

    print('''</table>
<h2>Packages which depend on NBS packages</h2>
<table>''')

    def sort_rev_nbs(k1, k2):
        len_cmp = cmp(len(reverse_nbs[k1]), len(reverse_nbs[k2]))
        if len_cmp == 0:
            return cmp(k1, k2)
        else:
            return -len_cmp

    for pkg in sorted(reverse_nbs, cmp=sort_rev_nbs):
        print('<tr><td>%s</td> '
              '<td><span class="component%s">%s</span></td><td>' % (
                  pkg, pkg_component[pkg][1], pkg_component[pkg][0]), end="")
        print(" ".join(sorted(reverse_nbs[pkg])), end="")
        print('</td></tr>')

    print('</table>')
    print('<p><small>Generated at %s.</small></p>' %
          time.strftime('%Y-%m-%d %H:%M:%S %Z'))
    print('</body></html>')


#
# main
#

nbs = defaultdict(dict)  # pkg -> rdep_pkg -> (component, [arch1, arch2, ...])

for f in os.listdir(sys.argv[1]):
    if f.startswith('.') or f.endswith('.html'):
        continue
    parse_checkrdepends_file(os.path.join(sys.argv[1], f), nbs[f])

#with open('/tmp/dot', 'w') as dot:
#    print('digraph {', file=dot)
#    print('   ratio 0.1', file=dot)
#    pkgnames = set(nbs)
#    for m in nbs.itervalues():
#        pkgnames.update(m)
#    for n in pkgnames:
#        print('  %s [label="%s"' % (n.replace('-', '').replace('.', ''), n),
#              end="", file=dot)
#        if n in nbs:
#            print(', style="filled", fillcolor="lightblue"', end="", file=dot)
#        print(']', file=dot)
#    print(file=dot)
#    for pkg, map in nbs.iteritems():
#        for rd in map:
#            print('  %s -> %s' % (
#                    pkg.replace('-', '').replace('.', ''),
#                    rd.replace('-', '').replace('.', '')), file=dot)
#    print('}', file=dot)

removables = get_removables(nbs)

html_report(nbs, removables)