license_check.py 4.4 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116
  1. # Copyright 2023 Nick Brassel (@tzarc)
  2. # SPDX-License-Identifier: GPL-2.0-or-later
  3. import re
  4. from pathlib import Path
  5. from milc import cli
  6. from qmk.constants import LICENSE_TEXTS
  7. L_PAREN = re.compile(r'\(\[\{\<')
  8. R_PAREN = re.compile(r'\)\]\}\>')
  9. PUNCTUATION = re.compile(r'[\.,;:]+')
  10. TRASH_PREFIX = re.compile(r'^(\s|/|\*|#)+')
  11. TRASH_SUFFIX = re.compile(r'(\s|/|\*|#|\\)+$')
  12. SPACE = re.compile(r'\s+')
  13. SUFFIXES = ['.c', '.h', '.cpp', '.cxx', '.hpp', '.hxx']
  14. def _simplify_text(input):
  15. lines = input.lower().split('\n')
  16. lines = [PUNCTUATION.sub('', line) for line in lines]
  17. lines = [TRASH_PREFIX.sub('', line) for line in lines]
  18. lines = [TRASH_SUFFIX.sub('', line) for line in lines]
  19. lines = [SPACE.sub(' ', line) for line in lines]
  20. lines = [L_PAREN.sub('(', line) for line in lines]
  21. lines = [R_PAREN.sub(')', line) for line in lines]
  22. lines = [line.strip() for line in lines]
  23. lines = [line for line in lines if line is not None and line != '']
  24. return ' '.join(lines)
  25. def _detect_license_from_file_contents(filename, absolute=False):
  26. data = filename.read_text(encoding='utf-8', errors='ignore')
  27. filename_out = str(filename.absolute()) if absolute else str(filename)
  28. if 'SPDX-License-Identifier:' in data:
  29. res = data.split('SPDX-License-Identifier:')
  30. license = re.split(r'\s|//|\*', res[1].strip())[0].strip()
  31. found = False
  32. for short_license, _ in LICENSE_TEXTS:
  33. if license.lower() == short_license.lower():
  34. license = short_license
  35. found = True
  36. break
  37. if not found:
  38. if cli.args.short:
  39. print(f'{filename_out} UNKNOWN')
  40. else:
  41. cli.log.error(f'{{fg_cyan}}{filename_out}{{fg_reset}} -- unknown license, or no license detected!')
  42. return False
  43. if cli.args.short:
  44. print(f'{filename_out} {license}')
  45. else:
  46. cli.log.info(f'{{fg_cyan}}{filename_out}{{fg_reset}} -- license detected: {license} (SPDX License Identifier)')
  47. return True
  48. else:
  49. simple_text = _simplify_text(data)
  50. for short_license, long_licenses in LICENSE_TEXTS:
  51. for long_license in long_licenses:
  52. if long_license in simple_text:
  53. if cli.args.short:
  54. print(f'{filename_out} {short_license}')
  55. else:
  56. cli.log.info(f'{{fg_cyan}}{filename_out}{{fg_reset}} -- license detected: {short_license} (Full text)')
  57. return True
  58. if cli.args.short:
  59. print(f'{filename_out} UNKNOWN')
  60. else:
  61. cli.log.error(f'{{fg_cyan}}{filename_out}{{fg_reset}} -- unknown license, or no license detected!')
  62. return False
  63. @cli.argument('inputs', nargs='*', arg_only=True, type=Path, help='List of input files or directories.')
  64. @cli.argument('-s', '--short', action='store_true', help='Short output.')
  65. @cli.argument('-a', '--absolute', action='store_true', help='Print absolute paths.')
  66. @cli.argument('-e', '--extension', arg_only=True, action='append', default=[], help='Override list of extensions. Can be specified multiple times for multiple extensions.')
  67. @cli.subcommand('File license check.', hidden=False if cli.config.user.developer else True)
  68. def license_check(cli):
  69. def _default_suffix_condition(s):
  70. return s in SUFFIXES
  71. conditional = _default_suffix_condition
  72. if len(cli.args.extension) > 0:
  73. suffixes = [f'.{s}' if not s.startswith('.') else s for s in cli.args.extension]
  74. def _specific_suffix_condition(s):
  75. return s in suffixes
  76. conditional = _specific_suffix_condition
  77. # Pre-format all the licenses
  78. for _, long_licenses in LICENSE_TEXTS:
  79. for i in range(len(long_licenses)):
  80. long_licenses[i] = _simplify_text(long_licenses[i])
  81. check_list = set()
  82. for filename in sorted(cli.args.inputs):
  83. if filename.is_dir():
  84. for file in sorted(filename.rglob('*')):
  85. if file.is_file() and conditional(file.suffix):
  86. check_list.add(file)
  87. elif filename.is_file():
  88. if conditional(filename.suffix):
  89. check_list.add(filename)
  90. failed = False
  91. for filename in sorted(check_list):
  92. if not _detect_license_from_file_contents(filename, absolute=cli.args.absolute):
  93. failed = True
  94. if failed:
  95. return False