_common.py 4.7 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160
  1. # -*- coding: UTF-8 -*-
  2. # Copyright (c) 2020 The ungoogled-chromium Authors. All rights reserved.
  3. # Use of this source code is governed by a BSD-style license that can be
  4. # found in the LICENSE file.
  5. """Common code and constants"""
  6. import argparse
  7. import enum
  8. import logging
  9. import platform
  10. from pathlib import Path
  11. # Constants
  12. ENCODING = 'UTF-8' # For config files and patches
  13. USE_REGISTRY = '_use_registry'
  14. LOGGER_NAME = 'ungoogled'
  15. # Public classes
  16. class PlatformEnum(enum.Enum):
  17. """Enum for platforms that need distinction for certain functionality"""
  18. UNIX = 'unix' # Currently covers anything that isn't Windows
  19. WINDOWS = 'windows'
  20. class ExtractorEnum: #pylint: disable=too-few-public-methods
  21. """Enum for extraction binaries"""
  22. SEVENZIP = '7z'
  23. TAR = 'tar'
  24. WINRAR = 'winrar'
  25. class SetLogLevel(argparse.Action): #pylint: disable=too-few-public-methods
  26. """Sets logging level based on command line arguments it receives"""
  27. def __init__(self, option_strings, dest, nargs=None, **kwargs):
  28. super().__init__(option_strings, dest, nargs=nargs, **kwargs)
  29. def __call__(self, parser, namespace, value, option_string=None):
  30. if option_string in ('--verbose', '-v'):
  31. value = logging.DEBUG
  32. elif option_string in ('--quiet', '-q'):
  33. value = logging.ERROR
  34. else:
  35. levels = {
  36. 'FATAL': logging.FATAL,
  37. 'ERROR': logging.ERROR,
  38. 'WARNING': logging.WARNING,
  39. 'INFO': logging.INFO,
  40. 'DEBUG': logging.DEBUG
  41. }
  42. value = levels[value]
  43. set_logging_level(value)
  44. # Public methods
  45. def get_logger(initial_level=logging.INFO):
  46. """Gets the named logger"""
  47. logger = logging.getLogger(LOGGER_NAME)
  48. if logger.level == logging.NOTSET:
  49. logger.setLevel(initial_level)
  50. if not logger.hasHandlers():
  51. console_handler = logging.StreamHandler()
  52. console_handler.setLevel(initial_level)
  53. format_string = '%(levelname)s: %(message)s'
  54. formatter = logging.Formatter(format_string)
  55. console_handler.setFormatter(formatter)
  56. logger.addHandler(console_handler)
  57. return logger
  58. def set_logging_level(logging_level):
  59. """Sets logging level of logger and all its handlers"""
  60. if not logging_level:
  61. logging_level = logging.INFO
  62. logger = get_logger()
  63. logger.setLevel(logging_level)
  64. if logger.hasHandlers():
  65. for hdlr in logger.handlers:
  66. hdlr.setLevel(logging_level)
  67. return logger
  68. def get_running_platform():
  69. """
  70. Returns a PlatformEnum value indicating the platform that utils is running on.
  71. NOTE: Platform detection should only be used when no cross-platform alternative is available.
  72. """
  73. uname = platform.uname()
  74. # detect native python and WSL
  75. if uname.system == 'Windows' or 'Microsoft' in uname.release:
  76. return PlatformEnum.WINDOWS
  77. # Only Windows and UNIX-based platforms need to be distinguished right now.
  78. return PlatformEnum.UNIX
  79. def get_chromium_version():
  80. """Returns the Chromium version."""
  81. return (Path(__file__).parent.parent / 'chromium_version.txt').read_text().strip()
  82. def parse_series(series_path):
  83. """
  84. Returns an iterator of paths over the series file
  85. series_path is a pathlib.Path to the series file
  86. """
  87. with series_path.open(encoding=ENCODING) as series_file:
  88. series_lines = series_file.read().splitlines()
  89. # Filter blank lines
  90. series_lines = filter(len, series_lines)
  91. # Filter comment lines
  92. series_lines = filter((lambda x: not x.startswith('#')), series_lines)
  93. # Strip in-line comments
  94. series_lines = map((lambda x: x.strip().split(' #')[0]), series_lines)
  95. return series_lines
  96. def add_common_params(parser):
  97. """
  98. Adds common command line arguments to a parser.
  99. """
  100. # Logging levels
  101. logging_group = parser.add_mutually_exclusive_group()
  102. logging_group.add_argument(
  103. '--log-level',
  104. action=SetLogLevel,
  105. choices=['FATAL', 'ERROR', 'WARNING', 'INFO', 'DEBUG'],
  106. help="Set logging level of current script. Only one of 'log-level', 'verbose',"
  107. " 'quiet' can be set at a time.")
  108. logging_group.add_argument(
  109. '--quiet',
  110. '-q',
  111. action=SetLogLevel,
  112. nargs=0,
  113. help="Display less outputs to console. Only one of 'log-level', 'verbose',"
  114. " 'quiet' can be set at a time.")
  115. logging_group.add_argument(
  116. '--verbose',
  117. '-v',
  118. action=SetLogLevel,
  119. nargs=0,
  120. help="Increase logging verbosity to include DEBUG messages. Only one of "
  121. "'log-level', 'verbose', 'quiet' can be set at a time.")