summaryrefslogtreecommitdiff
path: root/lib/spack/spack/cmd/url.py
blob: 38dd6a4aeb05d1b9ad9ee0a41761ace8c741d04b (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
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
# Copyright 2013-2024 Lawrence Livermore National Security, LLC and other
# Spack Project Developers. See the top-level COPYRIGHT file for details.
#
# SPDX-License-Identifier: (Apache-2.0 OR MIT)

import urllib.parse
from collections import defaultdict

import llnl.util.tty.color as color
from llnl.util import tty

import spack.fetch_strategy as fs
import spack.repo
import spack.spec
import spack.url
import spack.util.crypto as crypto
from spack.url import (
    UndetectableNameError,
    UndetectableVersionError,
    UrlParseError,
    color_url,
    parse_name,
    parse_name_offset,
    parse_version,
    parse_version_offset,
    substitute_version,
    substitution_offsets,
)
from spack.util.naming import simplify_name

description = "debugging tool for url parsing"
section = "developer"
level = "long"


def setup_parser(subparser):
    sp = subparser.add_subparsers(metavar="SUBCOMMAND", dest="subcommand")

    # Parse
    parse_parser = sp.add_parser("parse", help="attempt to parse a url")

    parse_parser.add_argument("url", help="url to parse")
    parse_parser.add_argument(
        "-s", "--spider", action="store_true", help="spider the source page for versions"
    )

    # List
    list_parser = sp.add_parser("list", help="list urls in all packages")

    list_parser.add_argument(
        "-c",
        "--color",
        action="store_true",
        help="color the parsed version and name in the urls shown "
        "(versions will be cyan, name red)",
    )
    list_parser.add_argument(
        "-e",
        "--extrapolation",
        action="store_true",
        help="color the versions used for extrapolation as well "
        "(additional versions will be green, names magenta)",
    )

    excl_args = list_parser.add_mutually_exclusive_group()

    excl_args.add_argument(
        "-n",
        "--incorrect-name",
        action="store_true",
        help="only list urls for which the name was incorrectly parsed",
    )
    excl_args.add_argument(
        "-N",
        "--correct-name",
        action="store_true",
        help="only list urls for which the name was correctly parsed",
    )
    excl_args.add_argument(
        "-v",
        "--incorrect-version",
        action="store_true",
        help="only list urls for which the version was incorrectly parsed",
    )
    excl_args.add_argument(
        "-V",
        "--correct-version",
        action="store_true",
        help="only list urls for which the version was correctly parsed",
    )

    # Summary
    sp.add_parser("summary", help="print a summary of how well we are parsing package urls")

    # Stats
    stats_parser = sp.add_parser(
        "stats", help="print statistics on versions and checksums for all packages"
    )
    stats_parser.add_argument(
        "--show-issues",
        action="store_true",
        help="show packages with issues (md5 hashes, http urls)",
    )


def url(parser, args):
    action = {"parse": url_parse, "list": url_list, "summary": url_summary, "stats": url_stats}

    action[args.subcommand](args)


def url_parse(args):
    url = args.url

    tty.msg("Parsing URL: {0}".format(url))
    print()

    ver, vs, vl, vi, vregex = parse_version_offset(url)
    tty.msg("Matched version regex {0:>2}: r{1!r}".format(vi, vregex))

    name, ns, nl, ni, nregex = parse_name_offset(url, ver)
    tty.msg("Matched  name   regex {0:>2}: r{1!r}".format(ni, nregex))

    print()
    tty.msg("Detected:")
    try:
        print_name_and_version(url)
    except UrlParseError as e:
        tty.error(str(e))

    print("    name:    {0}".format(name))
    print("    version: {0}".format(ver))
    print()

    tty.msg("Substituting version 9.9.9b:")
    newurl = substitute_version(url, "9.9.9b")
    print_name_and_version(newurl)

    if args.spider:
        print()
        tty.msg("Spidering for versions:")
        versions = spack.url.find_versions_of_archive(url)

        if not versions:
            print("  Found no versions for {0}".format(name))
            return

        max_len = max(len(str(v)) for v in versions)

        for v in sorted(versions):
            print("{0:{1}}  {2}".format(v, max_len, versions[v]))


def url_list(args):
    urls = set()

    # Gather set of URLs from all packages
    for pkg_cls in spack.repo.PATH.all_package_classes():
        url = getattr(pkg_cls, "url", None)
        urls = url_list_parsing(args, urls, url, pkg_cls)

        for params in pkg_cls.versions.values():
            url = params.get("url", None)
            urls = url_list_parsing(args, urls, url, pkg_cls)

    # Print URLs
    for url in sorted(urls):
        if args.color or args.extrapolation:
            print(color_url(url, subs=args.extrapolation, errors=True))
        else:
            print(url)

    # Return the number of URLs that were printed, only for testing purposes
    return len(urls)


def url_summary(args):
    # Collect statistics on how many URLs were correctly parsed
    total_urls = 0
    correct_names = 0
    correct_versions = 0

    # Collect statistics on which regexes were matched and how often
    name_regex_dict = dict()
    right_name_count = defaultdict(int)
    wrong_name_count = defaultdict(int)

    version_regex_dict = dict()
    right_version_count = defaultdict(int)
    wrong_version_count = defaultdict(int)

    tty.msg("Generating a summary of URL parsing in Spack...")

    # Loop through all packages
    for pkg_cls in spack.repo.PATH.all_package_classes():
        urls = set()
        pkg = pkg_cls(spack.spec.Spec(pkg_cls.name))

        url = getattr(pkg, "url", None)
        if url:
            urls.add(url)

        for params in pkg.versions.values():
            url = params.get("url", None)
            if url:
                urls.add(url)

        # Calculate statistics
        for url in urls:
            total_urls += 1

            # Parse versions
            version = None
            try:
                version, vs, vl, vi, vregex = parse_version_offset(url)
                version_regex_dict[vi] = vregex
                if version_parsed_correctly(pkg, version):
                    correct_versions += 1
                    right_version_count[vi] += 1
                else:
                    wrong_version_count[vi] += 1
            except UndetectableVersionError:
                pass

            # Parse names
            try:
                name, ns, nl, ni, nregex = parse_name_offset(url, version)
                name_regex_dict[ni] = nregex
                if name_parsed_correctly(pkg, name):
                    correct_names += 1
                    right_name_count[ni] += 1
                else:
                    wrong_name_count[ni] += 1
            except UndetectableNameError:
                pass

    print()
    print("    Total URLs found:          {0}".format(total_urls))
    print(
        "    Names correctly parsed:    {0:>4}/{1:>4} ({2:>6.2%})".format(
            correct_names, total_urls, correct_names / total_urls
        )
    )
    print(
        "    Versions correctly parsed: {0:>4}/{1:>4} ({2:>6.2%})".format(
            correct_versions, total_urls, correct_versions / total_urls
        )
    )
    print()

    tty.msg("Statistics on name regular expressions:")

    print()
    print("    Index   Right   Wrong   Total   Regular Expression")
    for ni in sorted(name_regex_dict.keys()):
        print(
            "    {0:>5}   {1:>5}   {2:>5}   {3:>5}   r{4!r}".format(
                ni,
                right_name_count[ni],
                wrong_name_count[ni],
                right_name_count[ni] + wrong_name_count[ni],
                name_regex_dict[ni],
            )
        )
    print()

    tty.msg("Statistics on version regular expressions:")

    print()
    print("    Index   Right   Wrong   Total   Regular Expression")
    for vi in sorted(version_regex_dict.keys()):
        print(
            "    {0:>5}   {1:>5}   {2:>5}   {3:>5}   r{4!r}".format(
                vi,
                right_version_count[vi],
                wrong_version_count[vi],
                right_version_count[vi] + wrong_version_count[vi],
                version_regex_dict[vi],
            )
        )
    print()

    # Return statistics, only for testing purposes
    return (total_urls, correct_names, correct_versions, right_name_count, right_version_count)


def url_stats(args):
    # dictionary of issue type -> package -> descriptions
    issues = defaultdict(lambda: defaultdict(lambda: []))

    class UrlStats:
        def __init__(self):
            self.total = 0
            self.schemes = defaultdict(lambda: 0)
            self.checksums = defaultdict(lambda: 0)
            self.url_type = defaultdict(lambda: 0)
            self.git_type = defaultdict(lambda: 0)

        def add(self, pkg_name, fetcher):
            self.total += 1

            url_type = fetcher.url_attr
            self.url_type[url_type or "no code"] += 1

            if url_type == "url":
                digest = getattr(fetcher, "digest", None)
                if digest:
                    algo = crypto.hash_algo_for_digest(digest)
                else:
                    algo = "no checksum"
                self.checksums[algo] += 1

                if algo == "md5":
                    md5_hashes = issues["md5 hashes"]
                    md5_hashes[pkg_name].append(fetcher.url)

                # parse out the URL scheme (https/http/ftp/etc.)
                urlinfo = urllib.parse.urlparse(fetcher.url)
                self.schemes[urlinfo.scheme] += 1

                if urlinfo.scheme == "http":
                    http_urls = issues["http urls"]
                    http_urls[pkg_name].append(fetcher.url)

            elif url_type == "git":
                if getattr(fetcher, "commit", None):
                    self.git_type["commit"] += 1
                elif getattr(fetcher, "branch", None):
                    self.git_type["branch"] += 1
                elif getattr(fetcher, "tag", None):
                    self.git_type["tag"] += 1
                else:
                    self.git_type["no ref"] += 1

    npkgs = 0
    version_stats = UrlStats()
    resource_stats = UrlStats()

    for pkg_cls in spack.repo.PATH.all_package_classes():
        npkgs += 1

        for v in pkg_cls.versions:
            try:
                pkg = pkg_cls(spack.spec.Spec(pkg_cls.name))
                fetcher = fs.for_package_version(pkg, v)
            except (fs.InvalidArgsError, fs.FetcherConflict):
                continue
            version_stats.add(pkg_cls.name, fetcher)

        for _, resources in pkg_cls.resources.items():
            for resource in resources:
                resource_stats.add(pkg_cls.name, resource.fetcher)

    # print a nice summary table
    tty.msg("URL stats for %d packages:" % npkgs)

    def print_line():
        print("-" * 62)

    def print_stat(indent, name, stat_name=None):
        width = 20 - indent
        fmt = " " * indent
        fmt += "%%-%ds" % width
        if stat_name is None:
            print(fmt % name)
        else:
            fmt += "%12d%8.1f%%%12d%8.1f%%"
            v = getattr(version_stats, stat_name).get(name, 0)
            r = getattr(resource_stats, stat_name).get(name, 0)
            print(
                fmt % (name, v, v / version_stats.total * 100, r, r / resource_stats.total * 100)
            )

    print_line()
    print("%-20s%12s%9s%12s%9s" % ("stat", "versions", "%", "resources", "%"))
    print_line()
    print_stat(0, "url", "url_type")

    print_stat(4, "schemes")
    schemes = set(version_stats.schemes) | set(resource_stats.schemes)
    for scheme in schemes:
        print_stat(8, scheme, "schemes")

    print_stat(4, "checksums")
    checksums = set(version_stats.checksums) | set(resource_stats.checksums)
    for checksum in checksums:
        print_stat(8, checksum, "checksums")
    print_line()

    types = set(version_stats.url_type) | set(resource_stats.url_type)
    types -= set(["url", "git"])
    for url_type in sorted(types):
        print_stat(0, url_type, "url_type")
        print_line()

    print_stat(0, "git", "url_type")
    git_types = set(version_stats.git_type) | set(resource_stats.git_type)
    for git_type in sorted(git_types):
        print_stat(4, git_type, "git_type")
    print_line()

    if args.show_issues:
        total_issues = sum(
            len(issues) for _, pkg_issues in issues.items() for _, issues in pkg_issues.items()
        )
        print()
        tty.msg("Found %d issues." % total_issues)
        for issue_type, pkgs in issues.items():
            tty.msg("Package URLs with %s" % issue_type)
            for pkg_cls, pkg_issues in pkgs.items():
                color.cprint("    @*C{%s}" % pkg_cls)
                for issue in pkg_issues:
                    print("      %s" % issue)


def print_name_and_version(url):
    """Prints a URL. Underlines the detected name with dashes and
    the detected version with tildes.

    Args:
        url (str): The url to parse
    """
    name, ns, nl, ntup, ver, vs, vl, vtup = substitution_offsets(url)
    underlines = [" "] * max(ns + nl, vs + vl)
    for i in range(ns, ns + nl):
        underlines[i] = "-"
    for i in range(vs, vs + vl):
        underlines[i] = "~"

    print("    {0}".format(url))
    print("    {0}".format("".join(underlines)))


def url_list_parsing(args, urls, url, pkg):
    """Helper function for :func:`url_list`.

    Args:
        args (argparse.Namespace): The arguments given to ``spack url list``
        urls (set): List of URLs that have already been added
        url (str or None): A URL to potentially add to ``urls`` depending on
            ``args``
        pkg (spack.package_base.PackageBase): The Spack package

    Returns:
        set: The updated set of ``urls``
    """
    if url:
        if args.correct_name or args.incorrect_name:
            # Attempt to parse the name
            try:
                name = parse_name(url)
                if args.correct_name and name_parsed_correctly(pkg, name):
                    # Add correctly parsed URLs
                    urls.add(url)
                elif args.incorrect_name and not name_parsed_correctly(pkg, name):
                    # Add incorrectly parsed URLs
                    urls.add(url)
            except UndetectableNameError:
                if args.incorrect_name:
                    # Add incorrectly parsed URLs
                    urls.add(url)
        elif args.correct_version or args.incorrect_version:
            # Attempt to parse the version
            try:
                version = parse_version(url)
                if args.correct_version and version_parsed_correctly(pkg, version):
                    # Add correctly parsed URLs
                    urls.add(url)
                elif args.incorrect_version and not version_parsed_correctly(pkg, version):
                    # Add incorrectly parsed URLs
                    urls.add(url)
            except UndetectableVersionError:
                if args.incorrect_version:
                    # Add incorrectly parsed URLs
                    urls.add(url)
        else:
            urls.add(url)

    return urls


def name_parsed_correctly(pkg, name):
    """Determine if the name of a package was correctly parsed.

    Args:
        pkg (spack.package_base.PackageBase): The Spack package
        name (str): The name that was extracted from the URL

    Returns:
        bool: True if the name was correctly parsed, else False
    """
    pkg_name = remove_prefix(pkg.name)

    name = simplify_name(name)

    return name == pkg_name


def version_parsed_correctly(pkg, version):
    """Determine if the version of a package was correctly parsed.

    Args:
        pkg (spack.package_base.PackageBase): The Spack package
        version (str): The version that was extracted from the URL

    Returns:
        bool: True if the name was correctly parsed, else False
    """
    version = remove_separators(version)

    # If the version parsed from the URL is listed in a version()
    # directive, we assume it was correctly parsed
    for pkg_version in pkg.versions:
        pkg_version = remove_separators(pkg_version)
        if pkg_version == version:
            return True
    return False


def remove_prefix(pkg_name):
    """Remove build system prefix ('py-', 'perl-', etc.) from a package name.

    After determining a name, `spack create` determines a build system.
    Some build systems prepend a special string to the front of the name.
    Since this can't be guessed from the URL, it would be unfair to say
    that these names are incorrectly parsed, so we remove them.

    Args:
        pkg_name (str): the name of the package

    Returns:
        str: the name of the package with any build system prefix removed
    """
    prefixes = [
        "r-",
        "py-",
        "tcl-",
        "lua-",
        "perl-",
        "ruby-",
        "llvm-",
        "intel-",
        "votca-",
        "octave-",
        "gtkorvo-",
    ]

    prefix = next((p for p in prefixes if pkg_name.startswith(p)), "")

    return pkg_name[len(prefix) :]


def remove_separators(version):
    """Remove separator characters ('.', '_', and '-') from a version.

    A version like 1.2.3 may be displayed as 1_2_3 in the URL.
    Make sure 1.2.3, 1-2-3, 1_2_3, and 123 are considered equal.
    Unfortunately, this also means that 1.23 and 12.3 are equal.

    Args:
        version (str or spack.version.Version): A version

    Returns:
        str: The version with all separator characters removed
    """
    version = str(version)

    version = version.replace(".", "")
    version = version.replace("_", "")
    version = version.replace("-", "")

    return version