#!/usr/bin/env bash # SPDX-License-Identifier: Apache-2.0 set -o errexit -o nounset -o pipefail NAT='0|[1-9][0-9]*' ALPHANUM='[0-9]*[A-Za-z-][0-9A-Za-z-]*' IDENT="$NAT|$ALPHANUM" FIELD='[0-9A-Za-z-]+' SEMVER_REGEX="\ ^[vV]?\ ($NAT)\\.($NAT)\\.($NAT)\ (\\-(${IDENT})(\\.(${IDENT}))*)?\ (\\+${FIELD}(\\.${FIELD})*)?$" PROG=semver PROG_VERSION="3.4.0" USAGE="\ Usage: $PROG bump major $PROG bump minor $PROG bump patch $PROG bump prerel|prerelease [] $PROG bump build $PROG bump release $PROG get major $PROG get minor $PROG get patch $PROG get prerel|prerelease $PROG get build $PROG get release $PROG compare $PROG diff $PROG validate $PROG --help $PROG --version Arguments: A version must match the following regular expression: \"${SEMVER_REGEX}\" In English: -- The version must match X.Y.Z[-PRERELEASE][+BUILD] where X, Y and Z are non-negative integers. -- PRERELEASE is a dot separated sequence of non-negative integers and/or identifiers composed of alphanumeric characters and hyphens (with at least one non-digit). Numeric identifiers must not have leading zeros. A hyphen (\"-\") introduces this optional part. -- BUILD is a dot separated sequence of identifiers composed of alphanumeric characters and hyphens. A plus (\"+\") introduces this optional part. See definition. A string as defined by PRERELEASE above. Or, it can be a PRERELEASE prototype string followed by a dot. A string as defined by BUILD above. Options: -v, --version Print the version of this tool. -h, --help Print this help message. Commands: bump Bump by one of major, minor, patch; zeroing or removing subsequent parts. \"bump prerel\" (or its synonym \"bump prerelease\") sets the PRERELEASE part and removes any BUILD part. A trailing dot in the argument introduces an incrementing numeric field which is added or bumped. If no argument is provided, an incrementing numeric field is introduced/bumped. \"bump build\" sets the BUILD part. \"bump release\" removes any PRERELEASE or BUILD parts. The bumped version is written to stdout. get Extract given part of , where part is one of major, minor, patch, prerel (alternatively: prerelease), build, or release. compare Compare with , output to stdout the following values: -1 if is newer, 0 if equal, 1 if older. The BUILD part is not used in comparisons. diff Compare with , output to stdout the difference between two versions by the release type (MAJOR, MINOR, PATCH, PRERELEASE, BUILD). validate Validate if follows the SEMVER pattern (see definition). Print 'valid' to stdout if the version is valid, otherwise print 'invalid'. See also: https://semver.org -- Semantic Versioning 2.0.0" function error { echo -e "$1" >&2 exit 1 } function usage_help { error "$USAGE" } function usage_version { echo -e "${PROG}: $PROG_VERSION" exit 0 } # normalize the "part" keywords to a canonical string. At present, # only "prerelease" is normalized to "prerel". function normalize_part { if [ "$1" == "prerelease" ] then echo "prerel" else echo "$1" fi } function validate_version { local version=$1 if [[ "$version" =~ $SEMVER_REGEX ]]; then # if a second argument is passed, store the result in var named by $2 if [ "$#" -eq "2" ]; then local major=${BASH_REMATCH[1]} local minor=${BASH_REMATCH[2]} local patch=${BASH_REMATCH[3]} local prere=${BASH_REMATCH[4]} local build=${BASH_REMATCH[8]} eval "$2=(\"$major\" \"$minor\" \"$patch\" \"$prere\" \"$build\")" else echo "$version" fi else error "version $version does not match the semver scheme 'X.Y.Z(-PRERELEASE)(+BUILD)'. See help for more information." fi } function is_nat { [[ "$1" =~ ^($NAT)$ ]] } function is_null { [ -z "$1" ] } function order_nat { [ "$1" -lt "$2" ] && { echo -1 ; return ; } [ "$1" -gt "$2" ] && { echo 1 ; return ; } echo 0 } function order_string { [[ $1 < $2 ]] && { echo -1 ; return ; } [[ $1 > $2 ]] && { echo 1 ; return ; } echo 0 } # given two (named) arrays containing NAT and/or ALPHANUM fields, compare them # one by one according to semver 2.0.0 spec. Return -1, 0, 1 if left array ($1) # is less-than, equal, or greater-than the right array ($2). The longer array # is considered greater-than the shorter if the shorter is a prefix of the longer. # function compare_fields { local l="$1[@]" local r="$2[@]" local leftfield=( "${!l}" ) local rightfield=( "${!r}" ) local left local right local i=$(( -1 )) local order=$(( 0 )) while true do [ $order -ne 0 ] && { echo $order ; return ; } : $(( i++ )) left="${leftfield[$i]}" right="${rightfield[$i]}" is_null "$left" && is_null "$right" && { echo 0 ; return ; } is_null "$left" && { echo -1 ; return ; } is_null "$right" && { echo 1 ; return ; } is_nat "$left" && is_nat "$right" && { order=$(order_nat "$left" "$right") ; continue ; } is_nat "$left" && { echo -1 ; return ; } is_nat "$right" && { echo 1 ; return ; } { order=$(order_string "$left" "$right") ; continue ; } done } # shellcheck disable=SC2206 # checked by "validate"; ok to expand prerel id's into array function compare_version { local order validate_version "$1" V validate_version "$2" V_ # compare major, minor, patch local left=( "${V[0]}" "${V[1]}" "${V[2]}" ) local right=( "${V_[0]}" "${V_[1]}" "${V_[2]}" ) order=$(compare_fields left right) [ "$order" -ne 0 ] && { echo "$order" ; return ; } # compare pre-release ids when M.m.p are equal local prerel="${V[3]:1}" local prerel_="${V_[3]:1}" local left=( ${prerel//./ } ) local right=( ${prerel_//./ } ) # if left and right have no pre-release part, then left equals right # if only one of left/right has pre-release part, that one is less than simple M.m.p [ -z "$prerel" ] && [ -z "$prerel_" ] && { echo 0 ; return ; } [ -z "$prerel" ] && { echo 1 ; return ; } [ -z "$prerel_" ] && { echo -1 ; return ; } # otherwise, compare the pre-release id's compare_fields left right } # render_prerel -- return a prerel field with a trailing numeric string # usage: render_prerel numeric [prefix-string] # function render_prerel { if [ -z "$2" ] then echo "${1}" else echo "${2}${1}" fi } # extract_prerel -- extract prefix and trailing numeric portions of a pre-release part # usage: extract_prerel prerel prerel_parts # The prefix and trailing numeric parts are returned in "prerel_parts". # PREFIX_ALPHANUM='[.0-9A-Za-z-]*[.A-Za-z-]' DIGITS='[0-9][0-9]*' EXTRACT_REGEX="^(${PREFIX_ALPHANUM})*(${DIGITS})$" function extract_prerel { local prefix; local numeric; if [[ "$1" =~ $EXTRACT_REGEX ]] then # found prefix and trailing numeric parts prefix="${BASH_REMATCH[1]}" numeric="${BASH_REMATCH[2]}" else # no numeric part prefix="${1}" numeric= fi eval "$2=(\"$prefix\" \"$numeric\")" } # bump_prerel -- return the new pre-release part based on previous pre-release part # and prototype for bump # usage: bump_prerel proto previous # function bump_prerel { local proto; local prev_prefix; local prev_numeric; # case one: no trailing dot in prototype => simply replace previous with proto if [[ ! ( "$1" =~ \.$ ) ]] then echo "$1" return fi proto="${1%.}" # discard trailing dot marker from prototype extract_prerel "${2#-}" prerel_parts # extract parts of previous pre-release # shellcheck disable=SC2154 prev_prefix="${prerel_parts[0]}" prev_numeric="${prerel_parts[1]}" # case two: bump or append numeric to previous pre-release part if [ "$proto" == "+" ] # dummy "+" indicates no prototype argument provided then if [ -n "$prev_numeric" ] then : $(( ++prev_numeric )) # previous pre-release is already numbered, bump it render_prerel "$prev_numeric" "$prev_prefix" else render_prerel 1 "$prev_prefix" # append starting number fi return fi # case three: set, bump, or append using prototype prefix if [ "$prev_prefix" != "$proto" ] then render_prerel 1 "$proto" # proto not same pre-release; set and start at '1' elif [ -n "$prev_numeric" ] then : $(( ++prev_numeric )) # pre-release is numbered; bump it render_prerel "$prev_numeric" "$prev_prefix" else render_prerel 1 "$prev_prefix" # start pre-release at number '1' fi } function command_bump { local new; local version; local sub_version; local command; command="$(normalize_part "$1")" case $# in 2) case "$command" in major|minor|patch|prerel|release) sub_version="+."; version=$2;; *) usage_help;; esac ;; 3) case "$command" in prerel|build) sub_version=$2 version=$3 ;; *) usage_help;; esac ;; *) usage_help;; esac validate_version "$version" parts # shellcheck disable=SC2154 local major="${parts[0]}" local minor="${parts[1]}" local patch="${parts[2]}" local prere="${parts[3]}" local build="${parts[4]}" case "$command" in major) new="$((major + 1)).0.0";; minor) new="${major}.$((minor + 1)).0";; patch) new="${major}.${minor}.$((patch + 1))";; release) new="${major}.${minor}.${patch}";; prerel) new=$(validate_version "${major}.${minor}.${patch}-$(bump_prerel "$sub_version" "$prere")");; build) new=$(validate_version "${major}.${minor}.${patch}${prere}+${sub_version}");; *) usage_help ;; esac echo "$new" exit 0 } function command_compare { local v; local v_; case $# in 2) v=$(validate_version "$1"); v_=$(validate_version "$2") ;; *) usage_help ;; esac set +u # need unset array element to evaluate to null compare_version "$v" "$v_" exit 0 } function command_diff { validate_version "$1" v1_parts # shellcheck disable=SC2154 local v1_major="${v1_parts[0]}" local v1_minor="${v1_parts[1]}" local v1_patch="${v1_parts[2]}" local v1_prere="${v1_parts[3]}" local v1_build="${v1_parts[4]}" validate_version "$2" v2_parts # shellcheck disable=SC2154 local v2_major="${v2_parts[0]}" local v2_minor="${v2_parts[1]}" local v2_patch="${v2_parts[2]}" local v2_prere="${v2_parts[3]}" local v2_build="${v2_parts[4]}" if [ "${v1_major}" != "${v2_major}" ]; then echo "major" elif [ "${v1_minor}" != "${v2_minor}" ]; then echo "minor" elif [ "${v1_patch}" != "${v2_patch}" ]; then echo "patch" elif [ "${v1_prere}" != "${v2_prere}" ]; then echo "prerelease" elif [ "${v1_build}" != "${v2_build}" ]; then echo "build" fi } # shellcheck disable=SC2034 function command_get { local part version if [[ "$#" -ne "2" ]] || [[ -z "$1" ]] || [[ -z "$2" ]]; then usage_help exit 0 fi part="$1" version="$2" validate_version "$version" parts local major="${parts[0]}" local minor="${parts[1]}" local patch="${parts[2]}" local prerel="${parts[3]:1}" local build="${parts[4]:1}" local release="${major}.${minor}.${patch}" part="$(normalize_part "$part")" case "$part" in major|minor|patch|release|prerel|build) echo "${!part}" ;; *) usage_help ;; esac exit 0 } function command_validate { if [[ "$#" -ne "1" ]]; then usage_help fi if [[ "$1" =~ $SEMVER_REGEX ]]; then echo "valid" else echo "invalid" fi exit 0 } case $# in 0) echo "Unknown command: $*"; usage_help;; esac case $1 in --help|-h) echo -e "$USAGE"; exit 0;; --version|-v) usage_version ;; bump) shift; command_bump "$@";; get) shift; command_get "$@";; compare) shift; command_compare "$@";; diff) shift; command_diff "$@";; validate) shift; command_validate "$@";; *) echo "Unknown arguments: $*"; usage_help;; esac > 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 573 574 575 576 577 578 579 580 581 582 583 584 585 586 587 588 589 590 591 592 593 594 595 596 597 598 599 600 601 602 603 604 605 606 607 608 609 610 611 612 613 614 615 616 617 618 619 620 621 622 623 624 625 626 627 628 629 630 631 632 633 634 635 636 637 638 639 640 641 642 643 644 645 646 647 648 649 650 651 652 653 654 655 656 657 658 659 660 661 662 663 664 665 666 667 668 669 670 671 672 673 674 675 676 677 678 679 680 681 682 683 684 685 686 687 688 689 690 691 692 693 694 695 696 697 698 699 700 701 702 703 704 705 706 707 708 709 710 711 712 713 714 715 716 717 718 719 720 721 722 723 724 725 726 727 728 729 730 731 732 733 734 735 736 737 738 739 740 741 742 743 744 745 746 747 748 749 750 751 752 753 754 755 756 757 758 759 760 761 762 763 764 765 766 767 768 769 770 771 772 773 774 775 776 777 778 779 780 781 782 783 784 785 786 787 788 789 790 791 792 793 794 795 796 797 798 799 800 801 802 803 804 805 806 807 808 809 810 811 812 813 814 815 816 817 818 819 820 821 822 823 824 825 826 827 828 829 830 831 832 833 834 835 836 837 838 839 840 841 842 843 844 845 846 847 848 849 850 851 852 853 854 855 856 857 858 859 860 861 862 863 864 865 866 867 868 869 870 871 872 873 874 875 876 877 878 879 880 881 882 883 884 885 886 887 888 889 890 891 892 893 894 895 896 897 898 899 900 901 902 903 904 905 906 907 908 909 910 911 912 913 914 915 916 917 918 919 920 921 922 923 924 925 926 927 928 929 930 931 932 933 934 935 936 937 938 939 940 941 942 943 944 945 946 947 948 949 950 951 952 953 954 955 956 957 958 959 960 961 962 963 964 965 966 967 968 969 970 971 972 973 974 975 976 977 978 979 980 981 982 983 984 985 986 987 988 989 990 991 992 993 994 995 996 997 998 999 1000 1001 1002 1003 1004 1005 1006 1007 1008 1009 1010 1011 1012 1013 1014 1015 1016 1017 1018 1019 1020 1021 1022 1023 1024 1025 1026 1027 1028 1029 1030 1031 1032 1033 1034 1035 1036 1037 1038 1039 1040 1041 1042 1043 1044 1045 1046 1047 1048 1049 1050 1051 1052 1053 1054 1055 1056 1057 1058 1059 1060 1061 1062 1063
#!/usr/bin/python3
# SPDX-License-Identifier: GPL-2.0-or-later
# Copyright (C) 2018, Google Inc.
#
# Author: Laurent Pinchart <laurent.pinchart@ideasonboard.com>
#
# checkstyle.py - A patch style checker script based on clang-format
#
# TODO:
#
# - Support other formatting tools and checkers (cppcheck, cpplint, kwstyle, ...)
# - Split large hunks to minimize context noise
# - Improve style issues counting
#

import argparse
import difflib
import fnmatch
import os.path
import re
import shutil
import subprocess
import sys

dependencies = {
    'clang-format': True,
    'git': True,
}

# ------------------------------------------------------------------------------
# Colour terminal handling
#

class Colours:
    Default = 0
    Black = 0
    Red = 31
    Green = 32
    Yellow = 33
    Blue = 34
    Magenta = 35
    Cyan = 36
    LightGrey = 37
    DarkGrey = 90
    LightRed = 91
    LightGreen = 92
    Lightyellow = 93
    LightBlue = 94
    LightMagenta = 95
    LightCyan = 96
    White = 97

    @staticmethod
    def fg(colour):
        if sys.stdout.isatty():
            return '\033[%um' % colour
        else:
            return ''

    @staticmethod
    def bg(colour):
        if sys.stdout.isatty():
            return '\033[%um' % (colour + 10)
        else:
            return ''

    @staticmethod
    def reset():
        if sys.stdout.isatty():
            return '\033[0m'
        else:
            return ''


# ------------------------------------------------------------------------------
# Diff parsing, handling and printing
#

class DiffHunkSide(object):
    """A side of a diff hunk, recording line numbers"""
    def __init__(self, start):
        self.start = start
        self.touched = []
        self.untouched = []

    def __len__(self):
        return len(self.touched) + len(self.untouched)


class DiffHunk(object):
    diff_header_regex = re.compile(r'@@ -([0-9]+),?([0-9]+)? \+([0-9]+),?([0-9]+)? @@')

    def __init__(self, line):
        match = DiffHunk.diff_header_regex.match(line)
        if not match:
            raise RuntimeError("Malformed diff hunk header '%s'" % line)

        self.__from_line = int(match.group(1))
        self.__to_line = int(match.group(3))
        self.__from = DiffHunkSide(self.__from_line)
        self.__to = DiffHunkSide(self.__to_line)

        self.lines = []

    def __repr__(self):
        s = '%s@@ -%u,%u +%u,%u @@\n' % \
                (Colours.fg(Colours.Cyan),
                 self.__from.start, len(self.__from),
                 self.__to.start, len(self.__to))

        for line in self.lines:
            if line[0] == '-':
                s += Colours.fg(Colours.Red)
            elif line[0] == '+':
                s += Colours.fg(Colours.Green)

            if line[0] == '-':
                spaces = 0
                for i in range(len(line)):
                    if line[-i-1].isspace():
                        spaces += 1
                    else:
                        break
                spaces = len(line) - spaces
                line = line[0:spaces] + Colours.bg(Colours.Red) + line[spaces:]

            s += line
            s += Colours.reset()
            s += '\n'

        return s[:-1]

    def append(self, line):
        if line[0] == ' ':
            self.__from.untouched.append(self.__from_line)
            self.__from_line += 1
            self.__to.untouched.append(self.__to_line)
            self.__to_line += 1
        elif line[0] == '-':
            self.__from.touched.append(self.__from_line)
            self.__from_line += 1
        elif line[0] == '+':
            self.__to.touched.append(self.__to_line)
            self.__to_line += 1

        self.lines.append(line.rstrip('\n'))

    def intersects(self, lines):
        for line in lines:
            if line in self.__from.touched:
                return True
        return False

    def side(self, side):
        if side == 'from':
            return self.__from
        else:
            return self.__to


def parse_diff(diff):
    hunks = []
    hunk = None
    for line in diff:
        if line.startswith('@@'):
            if hunk:
                hunks.append(hunk)
            hunk = DiffHunk(line)

        elif hunk is not None:
            hunk.append(line)

    if hunk:
        hunks.append(hunk)

    return hunks