Repository: Venom1991/refind-btrfs Branch: master Commit: 9c567b94ab8e Files: 95 Total size: 525.9 KB Directory structure: gitextract_hh9l_b0o/ ├── .gitignore ├── .pylintrc ├── .vscode/ │ ├── launch.json │ └── settings.json ├── LICENSE.txt ├── MANIFEST.in ├── README.md ├── pyproject.toml ├── requirements.txt ├── setup.cfg ├── setup.py ├── src/ │ └── refind_btrfs/ │ ├── __init__.py │ ├── __main__.py │ ├── boot/ │ │ ├── __init__.py │ │ ├── antlr4/ │ │ │ ├── RefindConfigLexer.g4 │ │ │ ├── RefindConfigLexer.interp │ │ │ ├── RefindConfigLexer.py │ │ │ ├── RefindConfigLexer.tokens │ │ │ ├── RefindConfigParser.g4 │ │ │ ├── RefindConfigParser.interp │ │ │ ├── RefindConfigParser.py │ │ │ ├── RefindConfigParser.tokens │ │ │ ├── RefindConfigParserVisitor.py │ │ │ └── __init__.py │ │ ├── boot_options.py │ │ ├── boot_stanza.py │ │ ├── file_refind_config_provider.py │ │ ├── migrations/ │ │ │ ├── __init__.py │ │ │ ├── icon_migration_strategies.py │ │ │ ├── main_migration_strategies.py │ │ │ ├── migration.py │ │ │ └── state.py │ │ ├── refind_config.py │ │ ├── refind_listeners.py │ │ ├── refind_visitors.py │ │ └── sub_menu.py │ ├── common/ │ │ ├── __init__.py │ │ ├── abc/ │ │ │ ├── __init__.py │ │ │ ├── base_config.py │ │ │ ├── base_runner.py │ │ │ ├── commands/ │ │ │ │ ├── __init__.py │ │ │ │ ├── device_command.py │ │ │ │ ├── icon_command.py │ │ │ │ └── subvolume_command.py │ │ │ ├── factories/ │ │ │ │ ├── __init__.py │ │ │ │ ├── base_device_command_factory.py │ │ │ │ ├── base_icon_command_factory.py │ │ │ │ ├── base_logger_factory.py │ │ │ │ └── base_subvolume_command_factory.py │ │ │ └── providers/ │ │ │ ├── __init__.py │ │ │ ├── base_package_config_provider.py │ │ │ ├── base_persistence_provider.py │ │ │ └── base_refind_config_provider.py │ │ ├── boot_files_check_result.py │ │ ├── checkable_observer.py │ │ ├── configurable_mixin.py │ │ ├── constants.py │ │ ├── enums.py │ │ ├── exceptions.py │ │ └── package_config.py │ ├── console/ │ │ ├── __init__.py │ │ └── cli_runner.py │ ├── data/ │ │ ├── refind-btrfs │ │ ├── refind-btrfs.conf-sample │ │ └── refind-btrfs.service │ ├── device/ │ │ ├── __init__.py │ │ ├── block_device.py │ │ ├── filesystem.py │ │ ├── mount_options.py │ │ ├── partition.py │ │ ├── partition_table.py │ │ └── subvolume.py │ ├── service/ │ │ ├── __init__.py │ │ ├── snapshot_event_handler.py │ │ ├── snapshot_observer.py │ │ └── watchdog_runner.py │ ├── state_management/ │ │ ├── __init__.py │ │ ├── conditions.py │ │ ├── model.py │ │ └── refind_btrfs_machine.py │ ├── system/ │ │ ├── __init__.py │ │ ├── btrfsutil_command.py │ │ ├── command_factories.py │ │ ├── findmnt_command.py │ │ ├── fstab_command.py │ │ ├── lsblk_command.py │ │ └── pillow_command.py │ └── utility/ │ ├── __init__.py │ ├── file_package_config_provider.py │ ├── helpers.py │ ├── injector_modules.py │ ├── level_aware_formatter.py │ ├── logger_factories.py │ └── shelve_persistence_provider.py └── tests/ └── .keep ================================================ FILE CONTENTS ================================================ ================================================ FILE: .gitignore ================================================ # Byte-compiled / optimized / DLL files __pycache__/ *.py[cod] *$py.class # C extensions *.so # Distribution / packaging .Python build/ develop-eggs/ dist/ downloads/ eggs/ .eggs/ lib/ lib64/ parts/ sdist/ var/ wheels/ share/python-wheels/ *.egg-info/ .installed.cfg *.egg MANIFEST # PyInstaller # Usually these files are written by a python script from a template # before PyInstaller builds the exe, so as to inject date/other infos into it. *.manifest *.spec # Installer logs pip-log.txt pip-delete-this-directory.txt # Unit test / coverage reports htmlcov/ .tox/ .nox/ .coverage .coverage.* .cache nosetests.xml coverage.xml *.cover *.py,cover .hypothesis/ .pytest_cache/ cover/ # Translations *.mo *.pot # Django stuff: *.log local_settings.py db.sqlite3 db.sqlite3-journal # Flask stuff: instance/ .webassets-cache # Scrapy stuff: .scrapy # Sphinx documentation docs/_build/ # PyBuilder .pybuilder/ target/ # Jupyter Notebook .ipynb_checkpoints # IPython profile_default/ ipython_config.py # pyenv # For a library or package, you might want to ignore these files since the code is # intended to run in multiple environments; otherwise, check them in: # .python-version # pipenv # According to pypa/pipenv#598, it is recommended to include Pipfile.lock in version control. # However, in case of collaboration, if having platform-specific dependencies or dependencies # having no cross-platform support, pipenv may install dependencies that don't work, or not # install all needed dependencies. #Pipfile.lock # PEP 582; used by e.g. github.com/David-OConnor/pyflow __pypackages__/ # Celery stuff celerybeat-schedule celerybeat.pid # SageMath parsed files *.sage.py # Environments .env .venv env/ venv/ ENV/ env.bak/ venv.bak/ # Spyder project settings .spyderproject .spyproject # Rope project settings .ropeproject # mkdocs documentation /site # mypy .mypy_cache/ .dmypy.json dmypy.json # Pyre type checker .pyre/ # pytype static type analyzer .pytype/ # Cython debug symbols cython_debug/ # VS Code # .vscode/* !.vscode/tasks.json !.vscode/launch.json !.vscode/settings.json *.code-workspace # VS Code Patch # # Ignore all local history of files .history .ionide ================================================ FILE: .pylintrc ================================================ [MASTER] # A comma-separated list of package or module names from where C extensions may # be loaded. Extensions are loading into the active Python interpreter and may # run arbitrary code. extension-pkg-whitelist=btrfsutil # Specify a score threshold to be exceeded before program exits with error. fail-under=10.0 # Add files or directories to the blacklist. They should be base names, not # paths. ignore=CVS # Add files or directories matching the regex patterns to the blacklist. The # regex matches against base names, not paths. ignore-patterns= # Python code to execute, usually for sys.path manipulation such as # pygtk.require(). init-hook='import sys, os; sys.path.append(os.path.join(os.getcwd(), "src", "refind_btrfs"))' # Use multiple processes to speed up Pylint. Specifying 0 will auto-detect the # number of processors available to use. jobs=1 # Control the amount of potential inferred values when inferring a single # object. This can help the performance when dealing with large functions or # complex, nested conditions. limit-inference-results=100 # List of plugins (as comma separated values of python module names) to load, # usually to register additional checkers. load-plugins= # Pickle collected data for later comparisons. persistent=yes # When enabled, pylint would attempt to guess common misconfiguration and emit # user-friendly hints instead of false-positive error messages. suggestion-mode=yes # Allow loading of arbitrary C extensions. Extensions are imported into the # active Python interpreter and may run arbitrary code. unsafe-load-any-extension=no [MESSAGES CONTROL] # Only show warnings with the listed confidence levels. Leave empty to show # all. Valid levels: HIGH, INFERENCE, INFERENCE_FAILURE, UNDEFINED. confidence= # Disable the message, report, category or checker with the given id(s). You # can either give multiple identifiers separated by comma (,) or put this # option multiple times (only on the command line, not in the configuration # file where it should appear only once). You can also use "--disable=all" to # disable everything first and then reenable specific checks. For example, if # you want to run only the similarities checker, you can use "--disable=all # --enable=similarities". If you want to run only the classes checker, but have # no Warning level messages displayed, use "--disable=all --enable=classes # --disable=W". disable=missing-module-docstring, missing-class-docstring, missing-function-docstring, unsubscriptable-object, inherit-non-class, too-few-public-methods, broad-except, print-statement, parameter-unpacking, unpacking-in-except, old-raise-syntax, backtick, long-suffix, old-ne-operator, old-octal-literal, import-star-module-level, non-ascii-bytes-literal, raw-checker-failed, bad-inline-option, locally-disabled, file-ignored, suppressed-message, useless-suppression, deprecated-pragma, use-symbolic-message-instead, apply-builtin, basestring-builtin, buffer-builtin, cmp-builtin, coerce-builtin, execfile-builtin, file-builtin, long-builtin, raw_input-builtin, reduce-builtin, standarderror-builtin, unicode-builtin, xrange-builtin, coerce-method, delslice-method, getslice-method, setslice-method, no-absolute-import, old-division, dict-iter-method, dict-view-method, next-method-called, metaclass-assignment, indexing-exception, raising-string, reload-builtin, oct-method, hex-method, nonzero-method, cmp-method, input-builtin, round-builtin, intern-builtin, unichr-builtin, map-builtin-not-iterating, zip-builtin-not-iterating, range-builtin-not-iterating, filter-builtin-not-iterating, using-cmp-argument, eq-without-hash, div-method, idiv-method, rdiv-method, exception-message-attribute, invalid-str-codec, sys-max-int, bad-python3-import, deprecated-string-function, deprecated-str-translate-call, deprecated-itertools-function, deprecated-types-field, next-method-defined, dict-items-not-iterating, dict-keys-not-iterating, dict-values-not-iterating, deprecated-operator-function, deprecated-urllib-function, xreadlines-attribute, deprecated-sys-function, exception-escape, comprehension-escape # Enable the message, report, category or checker with the given id(s). You can # either give multiple identifier separated by comma (,) or put this option # multiple time (only on the command line, not in the configuration file where # it should appear only once). See also the "--disable" option for examples. enable=c-extension-no-member, unused-import, unused-wildcard-import [REPORTS] # Python expression which should return a score less than or equal to 10. You # have access to the variables 'error', 'warning', 'refactor', and 'convention' # which contain the number of messages in each category, as well as 'statement' # which is the total number of statements analyzed. This score is used by the # global evaluation report (RP0004). evaluation=10.0 - ((float(5 * error + warning + refactor + convention) / statement) * 10) # Template used to display messages. This is a python new-style format string # used to format the message information. See doc for all details. #msg-template= # Set the output format. Available formats are text, parseable, colorized, json # and msvs (visual studio). You can also give a reporter class, e.g. # mypackage.mymodule.MyReporterClass. output-format=text # Tells whether to display a full report or only the messages. reports=no # Activate the evaluation score. score=yes [REFACTORING] # Maximum number of nested blocks for function / method body max-nested-blocks=5 # Complete name of functions that never returns. When checking for # inconsistent-return-statements if a never returning function is called then # it will be considered as an explicit return statement and no message will be # printed. never-returning-functions=sys.exit [BASIC] # Naming style matching correct argument names. argument-naming-style=snake_case # Regular expression matching correct argument names. Overrides argument- # naming-style. #argument-rgx= # Naming style matching correct attribute names. attr-naming-style=snake_case # Regular expression matching correct attribute names. Overrides attr-naming- # style. #attr-rgx= # Bad variable names which should always be refused, separated by a comma. bad-names=foo, bar, baz, toto, tutu, tata # Bad variable names regexes, separated by a comma. If names match any regex, # they will always be refused bad-names-rgxs= # Naming style matching correct class attribute names. class-attribute-naming-style=any # Regular expression matching correct class attribute names. Overrides class- # attribute-naming-style. #class-attribute-rgx= # Naming style matching correct class names. class-naming-style=PascalCase # Regular expression matching correct class names. Overrides class-naming- # style. #class-rgx= # Naming style matching correct constant names. const-naming-style=UPPER_CASE # Regular expression matching correct constant names. Overrides const-naming- # style. #const-rgx= # Minimum line length for functions/classes that require docstrings, shorter # ones are exempt. docstring-min-length=-1 # Naming style matching correct function names. function-naming-style=snake_case # Regular expression matching correct function names. Overrides function- # naming-style. #function-rgx= # Good variable names which should always be accepted, separated by a comma. good-names=e, i, j, k, ex, Run, _ # Good variable names regexes, separated by a comma. If names match any regex, # they will always be accepted good-names-rgxs= # Include a hint for the correct naming format with invalid-name. include-naming-hint=no # Naming style matching correct inline iteration names. inlinevar-naming-style=any # Regular expression matching correct inline iteration names. Overrides # inlinevar-naming-style. #inlinevar-rgx= # Naming style matching correct method names. method-naming-style=snake_case # Regular expression matching correct method names. Overrides method-naming- # style. #method-rgx= # Naming style matching correct module names. module-naming-style=snake_case # Regular expression matching correct module names. Overrides module-naming- # style. #module-rgx= # Colon-delimited sets of names that determine each other's naming style when # the name regexes allow several styles. name-group= # Regular expression which should only match function or class names that do # not require a docstring. no-docstring-rgx=^_ # List of decorators that produce properties, such as abc.abstractproperty. Add # to this list to register other decorators that produce valid properties. # These decorators are taken in consideration only for invalid-name. property-classes=abc.abstractproperty # Naming style matching correct variable names. variable-naming-style=snake_case # Regular expression matching correct variable names. Overrides variable- # naming-style. #variable-rgx= [FORMAT] # Expected format of line ending, e.g. empty (any line ending), LF or CRLF. expected-line-ending-format= # Regexp for a line that is allowed to be longer than the limit. ignore-long-lines=^\s*(# )??$ # Number of spaces of indent required inside a hanging or continued line. indent-after-paren=4 # String used as indentation unit. This is usually " " (4 spaces) or "\t" (1 # tab). indent-string=' ' # Maximum number of characters on a single line. max-line-length=100 # Maximum number of lines in a module. max-module-lines=1000 # Allow the body of a class to be on the same line as the declaration if body # contains single statement. single-line-class-stmt=no # Allow the body of an if to be on the same line as the test if there is no # else. single-line-if-stmt=no [LOGGING] # The type of string formatting that logging methods do. `old` means using % # formatting, `new` is for `{}` formatting. logging-format-style=old # Logging modules to check that the string format arguments are in logging # function parameter format. logging-modules=logging [MISCELLANEOUS] # List of note tags to take in consideration, separated by a comma. notes=FIXME, XXX, TODO # Regular expression of note tags to take in consideration. #notes-rgx= [SIMILARITIES] # Ignore comments when computing similarities. ignore-comments=yes # Ignore docstrings when computing similarities. ignore-docstrings=yes # Ignore imports when computing similarities. ignore-imports=no # Minimum lines number of a similarity. min-similarity-lines=4 [SPELLING] # Limits count of emitted suggestions for spelling mistakes. max-spelling-suggestions=4 # Spelling dictionary name. Available dictionaries: none. To make it work, # install the python-enchant package. spelling-dict= # List of comma separated words that should not be checked. spelling-ignore-words= # A path to a file that contains the private dictionary; one word per line. spelling-private-dict-file= # Tells whether to store unknown words to the private dictionary (see the # --spelling-private-dict-file option) instead of raising a message. spelling-store-unknown-words=no [STRING] # This flag controls whether inconsistent-quotes generates a warning when the # character used as a quote delimiter is used inconsistently within a module. check-quote-consistency=no # This flag controls whether the implicit-str-concat should generate a warning # on implicit string concatenation in sequences defined over several lines. check-str-concat-over-line-jumps=no [TYPECHECK] # List of decorators that produce context managers, such as # contextlib.contextmanager. Add to this list to register other decorators that # produce valid context managers. contextmanager-decorators=contextlib.contextmanager # List of members which are set dynamically and missed by pylint inference # system, and so shouldn't trigger E1101 when accessed. Python regular # expressions are accepted. generated-members= # Tells whether missing members accessed in mixin class should be ignored. A # mixin class is detected if its name ends with "mixin" (case insensitive). ignore-mixin-members=yes # Tells whether to warn about missing members when the owner of the attribute # is inferred to be None. ignore-none=yes # This flag controls whether pylint should warn about no-member and similar # checks whenever an opaque object is returned when inferring. The inference # can return multiple potential results while evaluating a Python object, but # some branches might not be evaluated, which results in partial inference. In # that case, it might be useful to still emit no-member and other checks for # the rest of the inferred objects. ignore-on-opaque-inference=yes # List of class names for which member attributes should not be checked (useful # for classes with dynamically set attributes). This supports the use of # qualified names. ignored-classes=optparse.Values,thread._local,_thread._local # List of module names for which member attributes should not be checked # (useful for modules/projects where namespaces are manipulated during runtime # and thus existing member attributes cannot be deduced by static analysis). It # supports qualified module names, as well as Unix pattern matching. ignored-modules= # Show a hint with possible names when a member name was not found. The aspect # of finding the hint is based on edit distance. missing-member-hint=yes # The minimum edit distance a name should have in order to be considered a # similar match for a missing member name. missing-member-hint-distance=1 # The total number of similar names that should be taken in consideration when # showing a hint for a missing member. missing-member-max-choices=1 # List of decorators that change the signature of a decorated function. signature-mutators= [VARIABLES] # List of additional names supposed to be defined in builtins. Remember that # you should avoid defining new builtins when possible. additional-builtins= # Tells whether unused global variables should be treated as a violation. allow-global-unused-variables=yes # List of strings which can identify a callback function by name. A callback # name must start or end with one of those strings. callbacks=cb_, _cb # A regular expression matching the name of dummy variables (i.e. expected to # not be used). dummy-variables-rgx=_+$|(_[a-zA-Z0-9_]*[a-zA-Z0-9]+?$)|dummy|^ignored_|^unused_ # Argument names that match this expression will be ignored. Default to name # with leading underscore. ignored-argument-names=_.*|^ignored_|^unused_ # Tells whether we should check for unused import in __init__ files. init-import=no # List of qualified module names which can have objects that can redefine # builtins. redefining-builtins-modules=six.moves,past.builtins,future.builtins,builtins,io [CLASSES] # List of method names used to declare (i.e. assign) instance attributes. defining-attr-methods=__init__, __new__, setUp, __post_init__ # List of member names, which should be excluded from the protected access # warning. exclude-protected=_asdict, _fields, _replace, _source, _make # List of valid names for the first argument in a class method. valid-classmethod-first-arg=cls # List of valid names for the first argument in a metaclass class method. valid-metaclass-classmethod-first-arg=cls [DESIGN] # Maximum number of arguments for function / method. max-args=5 # Maximum number of attributes for a class (see R0902). max-attributes=7 # Maximum number of boolean expressions in an if statement (see R0916). max-bool-expr=5 # Maximum number of branch for function / method body. max-branches=12 # Maximum number of locals for function / method body. max-locals=15 # Maximum number of parents for a class (see R0901). max-parents=7 # Maximum number of public methods for a class (see R0904). max-public-methods=20 # Maximum number of return / yield for function / method body. max-returns=6 # Maximum number of statements in function / method body. max-statements=50 # Minimum number of public methods for a class (see R0903). min-public-methods=2 [IMPORTS] # List of modules that can be imported at any level, not just the top level # one. allow-any-import-level= # Allow wildcard imports from modules that define __all__. allow-wildcard-with-all=no # Analyse import fallback blocks. This can be used to support both Python 2 and # 3 compatible code, which means that the block might have code that exists # only in one or another interpreter, leading to false positives when analysed. analyse-fallback-blocks=no # Deprecated modules which should not be used, separated by a comma. deprecated-modules=optparse,tkinter.tix # Create a graph of external dependencies in the given file (report RP0402 must # not be disabled). ext-import-graph= # Create a graph of every (i.e. internal and external) dependencies in the # given file (report RP0402 must not be disabled). import-graph= # Create a graph of internal dependencies in the given file (report RP0402 must # not be disabled). int-import-graph= # Force import order to recognize a module as part of the standard # compatibility libraries. known-standard-library= # Force import order to recognize a module as part of a third party library. known-third-party=enchant # Couples of modules and preferred modules, separated by a comma. preferred-modules= [EXCEPTIONS] # Exceptions that will emit a warning when being caught. Defaults to # "BaseException, Exception". overgeneral-exceptions=BaseException, Exception ================================================ FILE: .vscode/launch.json ================================================ { "version": "0.2.0", "configurations": [ { "name": "Python: Module", "type": "debugpy", "request": "launch", "console": "integratedTerminal", "module": "refind_btrfs", "cwd": "${workspaceFolder}/src", "envFile": "${workspaceFolder}/.env", "args": [ "--run-mode", "one-time" ], "sudo": true, "justMyCode": false } ] } ================================================ FILE: .vscode/settings.json ================================================ { "antlr4.generation": { "alternativeJar": "C:\\Users\\Luka\\Projects\\Python\\antlr-4.13.1-complete.jar", "language": "Python3", "listeners": false, "mode": "external", "visitors": true }, "cSpell.words": [ "antlr", "bootable", "Bootnum", "Btrfs", "btrfsutil", "bytecode", "ELILO", "EPERM", "errno", "findmnt", "fstype", "getpid", "getuid", "groupby", "ICNS", "IMODE", "INITRD", "inplace", "ismethod", "itertools", "journalctl", "levelno", "Lsblk", "menuentry", "mtab", "nargs", "nodeps", "nofsroot", "ostype", "otime", "partuuid", "pidfile", "pidname", "PTABLE", "pttype", "ptuuid", "pycache", "pylint", "pyproject", "PYTHONPATH", "refind", "rootflags", "setuptools", "SPDX", "submenuentry", "Subobject", "suboption", "subvol", "subvolid", "subvolume", "tomlkit", "vfat" ], "code-runner.clearPreviousOutput": true, "code-runner.runInTerminal": true, "python.analysis.completeFunctionParens": true, "python.analysis.diagnosticMode": "workspace", "python.analysis.extraPaths": [ "src/refind_btrfs" ], "python.defaultInterpreterPath": "${workspaceFolder}/.venv/bin/python", "python.envFile": "${workspaceFolder}/.env", "python.formatting.provider": "black", "python.languageServer": "Pylance", "python.linting.enabled": true, "python.linting.mypyEnabled": true, "python.linting.mypyPath": "${workspaceFolder}/.venv/bin/mypy", "python.linting.pylintEnabled": true, "python.linting.pylintPath": "${workspaceFolder}/.venv/bin/pylint", "search.exclude": { "**/.venv": true }, "terminal.integrated.env.linux": { "PYTHONPATH": "${env:PYTHONPATH}:${workspaceFolder}/src" } } ================================================ FILE: LICENSE.txt ================================================ GNU GENERAL PUBLIC LICENSE Version 3, 29 June 2007 Copyright (C) 2007 Free Software Foundation, Inc. Everyone is permitted to copy and distribute verbatim copies of this license document, but changing it is not allowed. Preamble The GNU General Public License is a free, copyleft license for software and other kinds of works. The licenses for most software and other practical works are designed to take away your freedom to share and change the works. By contrast, the GNU General Public License is intended to guarantee your freedom to share and change all versions of a program--to make sure it remains free software for all its users. We, the Free Software Foundation, use the GNU General Public License for most of our software; it applies also to any other work released this way by its authors. You can apply it to your programs, too. When we speak of free software, we are referring to freedom, not price. Our General Public Licenses are designed to make sure that you have the freedom to distribute copies of free software (and charge for them if you wish), that you receive source code or can get it if you want it, that you can change the software or use pieces of it in new free programs, and that you know you can do these things. To protect your rights, we need to prevent others from denying you these rights or asking you to surrender the rights. Therefore, you have certain responsibilities if you distribute copies of the software, or if you modify it: responsibilities to respect the freedom of others. For example, if you distribute copies of such a program, whether gratis or for a fee, you must pass on to the recipients the same freedoms that you received. You must make sure that they, too, receive or can get the source code. And you must show them these terms so they know their rights. Developers that use the GNU GPL protect your rights with two steps: (1) assert copyright on the software, and (2) offer you this License giving you legal permission to copy, distribute and/or modify it. For the developers' and authors' protection, the GPL clearly explains that there is no warranty for this free software. For both users' and authors' sake, the GPL requires that modified versions be marked as changed, so that their problems will not be attributed erroneously to authors of previous versions. Some devices are designed to deny users access to install or run modified versions of the software inside them, although the manufacturer can do so. This is fundamentally incompatible with the aim of protecting users' freedom to change the software. The systematic pattern of such abuse occurs in the area of products for individuals to use, which is precisely where it is most unacceptable. Therefore, we have designed this version of the GPL to prohibit the practice for those products. If such problems arise substantially in other domains, we stand ready to extend this provision to those domains in future versions of the GPL, as needed to protect the freedom of users. Finally, every program is threatened constantly by software patents. States should not allow patents to restrict development and use of software on general-purpose computers, but in those that do, we wish to avoid the special danger that patents applied to a free program could make it effectively proprietary. To prevent this, the GPL assures that patents cannot be used to render the program non-free. The precise terms and conditions for copying, distribution and modification follow. TERMS AND CONDITIONS 0. Definitions. "This License" refers to version 3 of the GNU General Public License. "Copyright" also means copyright-like laws that apply to other kinds of works, such as semiconductor masks. "The Program" refers to any copyrightable work licensed under this License. Each licensee is addressed as "you". "Licensees" and "recipients" may be individuals or organizations. To "modify" a work means to copy from or adapt all or part of the work in a fashion requiring copyright permission, other than the making of an exact copy. The resulting work is called a "modified version" of the earlier work or a work "based on" the earlier work. A "covered work" means either the unmodified Program or a work based on the Program. To "propagate" a work means to do anything with it that, without permission, would make you directly or secondarily liable for infringement under applicable copyright law, except executing it on a computer or modifying a private copy. Propagation includes copying, distribution (with or without modification), making available to the public, and in some countries other activities as well. To "convey" a work means any kind of propagation that enables other parties to make or receive copies. Mere interaction with a user through a computer network, with no transfer of a copy, is not conveying. An interactive user interface displays "Appropriate Legal Notices" to the extent that it includes a convenient and prominently visible feature that (1) displays an appropriate copyright notice, and (2) tells the user that there is no warranty for the work (except to the extent that warranties are provided), that licensees may convey the work under this License, and how to view a copy of this License. If the interface presents a list of user commands or options, such as a menu, a prominent item in the list meets this criterion. 1. Source Code. The "source code" for a work means the preferred form of the work for making modifications to it. "Object code" means any non-source form of a work. A "Standard Interface" means an interface that either is an official standard defined by a recognized standards body, or, in the case of interfaces specified for a particular programming language, one that is widely used among developers working in that language. The "System Libraries" of an executable work include anything, other than the work as a whole, that (a) is included in the normal form of packaging a Major Component, but which is not part of that Major Component, and (b) serves only to enable use of the work with that Major Component, or to implement a Standard Interface for which an implementation is available to the public in source code form. A "Major Component", in this context, means a major essential component (kernel, window system, and so on) of the specific operating system (if any) on which the executable work runs, or a compiler used to produce the work, or an object code interpreter used to run it. The "Corresponding Source" for a work in object code form means all the source code needed to generate, install, and (for an executable work) run the object code and to modify the work, including scripts to control those activities. However, it does not include the work's System Libraries, or general-purpose tools or generally available free programs which are used unmodified in performing those activities but which are not part of the work. For example, Corresponding Source includes interface definition files associated with source files for the work, and the source code for shared libraries and dynamically linked subprograms that the work is specifically designed to require, such as by intimate data communication or control flow between those subprograms and other parts of the work. The Corresponding Source need not include anything that users can regenerate automatically from other parts of the Corresponding Source. The Corresponding Source for a work in source code form is that same work. 2. Basic Permissions. All rights granted under this License are granted for the term of copyright on the Program, and are irrevocable provided the stated conditions are met. This License explicitly affirms your unlimited permission to run the unmodified Program. The output from running a covered work is covered by this License only if the output, given its content, constitutes a covered work. This License acknowledges your rights of fair use or other equivalent, as provided by copyright law. You may make, run and propagate covered works that you do not convey, without conditions so long as your license otherwise remains in force. You may convey covered works to others for the sole purpose of having them make modifications exclusively for you, or provide you with facilities for running those works, provided that you comply with the terms of this License in conveying all material for which you do not control copyright. Those thus making or running the covered works for you must do so exclusively on your behalf, under your direction and control, on terms that prohibit them from making any copies of your copyrighted material outside their relationship with you. Conveying under any other circumstances is permitted solely under the conditions stated below. Sublicensing is not allowed; section 10 makes it unnecessary. 3. Protecting Users' Legal Rights From Anti-Circumvention Law. No covered work shall be deemed part of an effective technological measure under any applicable law fulfilling obligations under article 11 of the WIPO copyright treaty adopted on 20 December 1996, or similar laws prohibiting or restricting circumvention of such measures. When you convey a covered work, you waive any legal power to forbid circumvention of technological measures to the extent such circumvention is effected by exercising rights under this License with respect to the covered work, and you disclaim any intention to limit operation or modification of the work as a means of enforcing, against the work's users, your or third parties' legal rights to forbid circumvention of technological measures. 4. Conveying Verbatim Copies. You may convey verbatim copies of the Program's source code as you receive it, in any medium, provided that you conspicuously and appropriately publish on each copy an appropriate copyright notice; keep intact all notices stating that this License and any non-permissive terms added in accord with section 7 apply to the code; keep intact all notices of the absence of any warranty; and give all recipients a copy of this License along with the Program. You may charge any price or no price for each copy that you convey, and you may offer support or warranty protection for a fee. 5. Conveying Modified Source Versions. You may convey a work based on the Program, or the modifications to produce it from the Program, in the form of source code under the terms of section 4, provided that you also meet all of these conditions: a) The work must carry prominent notices stating that you modified it, and giving a relevant date. b) The work must carry prominent notices stating that it is released under this License and any conditions added under section 7. This requirement modifies the requirement in section 4 to "keep intact all notices". c) You must license the entire work, as a whole, under this License to anyone who comes into possession of a copy. This License will therefore apply, along with any applicable section 7 additional terms, to the whole of the work, and all its parts, regardless of how they are packaged. This License gives no permission to license the work in any other way, but it does not invalidate such permission if you have separately received it. d) If the work has interactive user interfaces, each must display Appropriate Legal Notices; however, if the Program has interactive interfaces that do not display Appropriate Legal Notices, your work need not make them do so. A compilation of a covered work with other separate and independent works, which are not by their nature extensions of the covered work, and which are not combined with it such as to form a larger program, in or on a volume of a storage or distribution medium, is called an "aggregate" if the compilation and its resulting copyright are not used to limit the access or legal rights of the compilation's users beyond what the individual works permit. Inclusion of a covered work in an aggregate does not cause this License to apply to the other parts of the aggregate. 6. Conveying Non-Source Forms. You may convey a covered work in object code form under the terms of sections 4 and 5, provided that you also convey the machine-readable Corresponding Source under the terms of this License, in one of these ways: a) Convey the object code in, or embodied in, a physical product (including a physical distribution medium), accompanied by the Corresponding Source fixed on a durable physical medium customarily used for software interchange. b) Convey the object code in, or embodied in, a physical product (including a physical distribution medium), accompanied by a written offer, valid for at least three years and valid for as long as you offer spare parts or customer support for that product model, to give anyone who possesses the object code either (1) a copy of the Corresponding Source for all the software in the product that is covered by this License, on a durable physical medium customarily used for software interchange, for a price no more than your reasonable cost of physically performing this conveying of source, or (2) access to copy the Corresponding Source from a network server at no charge. c) Convey individual copies of the object code with a copy of the written offer to provide the Corresponding Source. This alternative is allowed only occasionally and noncommercially, and only if you received the object code with such an offer, in accord with subsection 6b. d) Convey the object code by offering access from a designated place (gratis or for a charge), and offer equivalent access to the Corresponding Source in the same way through the same place at no further charge. You need not require recipients to copy the Corresponding Source along with the object code. If the place to copy the object code is a network server, the Corresponding Source may be on a different server (operated by you or a third party) that supports equivalent copying facilities, provided you maintain clear directions next to the object code saying where to find the Corresponding Source. Regardless of what server hosts the Corresponding Source, you remain obligated to ensure that it is available for as long as needed to satisfy these requirements. e) Convey the object code using peer-to-peer transmission, provided you inform other peers where the object code and Corresponding Source of the work are being offered to the general public at no charge under subsection 6d. A separable portion of the object code, whose source code is excluded from the Corresponding Source as a System Library, need not be included in conveying the object code work. A "User Product" is either (1) a "consumer product", which means any tangible personal property which is normally used for personal, family, or household purposes, or (2) anything designed or sold for incorporation into a dwelling. In determining whether a product is a consumer product, doubtful cases shall be resolved in favor of coverage. For a particular product received by a particular user, "normally used" refers to a typical or common use of that class of product, regardless of the status of the particular user or of the way in which the particular user actually uses, or expects or is expected to use, the product. A product is a consumer product regardless of whether the product has substantial commercial, industrial or non-consumer uses, unless such uses represent the only significant mode of use of the product. "Installation Information" for a User Product means any methods, procedures, authorization keys, or other information required to install and execute modified versions of a covered work in that User Product from a modified version of its Corresponding Source. The information must suffice to ensure that the continued functioning of the modified object code is in no case prevented or interfered with solely because modification has been made. If you convey an object code work under this section in, or with, or specifically for use in, a User Product, and the conveying occurs as part of a transaction in which the right of possession and use of the User Product is transferred to the recipient in perpetuity or for a fixed term (regardless of how the transaction is characterized), the Corresponding Source conveyed under this section must be accompanied by the Installation Information. But this requirement does not apply if neither you nor any third party retains the ability to install modified object code on the User Product (for example, the work has been installed in ROM). The requirement to provide Installation Information does not include a requirement to continue to provide support service, warranty, or updates for a work that has been modified or installed by the recipient, or for the User Product in which it has been modified or installed. Access to a network may be denied when the modification itself materially and adversely affects the operation of the network or violates the rules and protocols for communication across the network. Corresponding Source conveyed, and Installation Information provided, in accord with this section must be in a format that is publicly documented (and with an implementation available to the public in source code form), and must require no special password or key for unpacking, reading or copying. 7. Additional Terms. "Additional permissions" are terms that supplement the terms of this License by making exceptions from one or more of its conditions. Additional permissions that are applicable to the entire Program shall be treated as though they were included in this License, to the extent that they are valid under applicable law. If additional permissions apply only to part of the Program, that part may be used separately under those permissions, but the entire Program remains governed by this License without regard to the additional permissions. When you convey a copy of a covered work, you may at your option remove any additional permissions from that copy, or from any part of it. (Additional permissions may be written to require their own removal in certain cases when you modify the work.) You may place additional permissions on material, added by you to a covered work, for which you have or can give appropriate copyright permission. Notwithstanding any other provision of this License, for material you add to a covered work, you may (if authorized by the copyright holders of that material) supplement the terms of this License with terms: a) Disclaiming warranty or limiting liability differently from the terms of sections 15 and 16 of this License; or b) Requiring preservation of specified reasonable legal notices or author attributions in that material or in the Appropriate Legal Notices displayed by works containing it; or c) Prohibiting misrepresentation of the origin of that material, or requiring that modified versions of such material be marked in reasonable ways as different from the original version; or d) Limiting the use for publicity purposes of names of licensors or authors of the material; or e) Declining to grant rights under trademark law for use of some trade names, trademarks, or service marks; or f) Requiring indemnification of licensors and authors of that material by anyone who conveys the material (or modified versions of it) with contractual assumptions of liability to the recipient, for any liability that these contractual assumptions directly impose on those licensors and authors. All other non-permissive additional terms are considered "further restrictions" within the meaning of section 10. If the Program as you received it, or any part of it, contains a notice stating that it is governed by this License along with a term that is a further restriction, you may remove that term. If a license document contains a further restriction but permits relicensing or conveying under this License, you may add to a covered work material governed by the terms of that license document, provided that the further restriction does not survive such relicensing or conveying. If you add terms to a covered work in accord with this section, you must place, in the relevant source files, a statement of the additional terms that apply to those files, or a notice indicating where to find the applicable terms. Additional terms, permissive or non-permissive, may be stated in the form of a separately written license, or stated as exceptions; the above requirements apply either way. 8. Termination. You may not propagate or modify a covered work except as expressly provided under this License. Any attempt otherwise to propagate or modify it is void, and will automatically terminate your rights under this License (including any patent licenses granted under the third paragraph of section 11). However, if you cease all violation of this License, then your license from a particular copyright holder is reinstated (a) provisionally, unless and until the copyright holder explicitly and finally terminates your license, and (b) permanently, if the copyright holder fails to notify you of the violation by some reasonable means prior to 60 days after the cessation. Moreover, your license from a particular copyright holder is reinstated permanently if the copyright holder notifies you of the violation by some reasonable means, this is the first time you have received notice of violation of this License (for any work) from that copyright holder, and you cure the violation prior to 30 days after your receipt of the notice. Termination of your rights under this section does not terminate the licenses of parties who have received copies or rights from you under this License. If your rights have been terminated and not permanently reinstated, you do not qualify to receive new licenses for the same material under section 10. 9. Acceptance Not Required for Having Copies. You are not required to accept this License in order to receive or run a copy of the Program. Ancillary propagation of a covered work occurring solely as a consequence of using peer-to-peer transmission to receive a copy likewise does not require acceptance. However, nothing other than this License grants you permission to propagate or modify any covered work. These actions infringe copyright if you do not accept this License. Therefore, by modifying or propagating a covered work, you indicate your acceptance of this License to do so. 10. Automatic Licensing of Downstream Recipients. Each time you convey a covered work, the recipient automatically receives a license from the original licensors, to run, modify and propagate that work, subject to this License. You are not responsible for enforcing compliance by third parties with this License. An "entity transaction" is a transaction transferring control of an organization, or substantially all assets of one, or subdividing an organization, or merging organizations. If propagation of a covered work results from an entity transaction, each party to that transaction who receives a copy of the work also receives whatever licenses to the work the party's predecessor in interest had or could give under the previous paragraph, plus a right to possession of the Corresponding Source of the work from the predecessor in interest, if the predecessor has it or can get it with reasonable efforts. You may not impose any further restrictions on the exercise of the rights granted or affirmed under this License. For example, you may not impose a license fee, royalty, or other charge for exercise of rights granted under this License, and you may not initiate litigation (including a cross-claim or counterclaim in a lawsuit) alleging that any patent claim is infringed by making, using, selling, offering for sale, or importing the Program or any portion of it. 11. Patents. A "contributor" is a copyright holder who authorizes use under this License of the Program or a work on which the Program is based. The work thus licensed is called the contributor's "contributor version". A contributor's "essential patent claims" are all patent claims owned or controlled by the contributor, whether already acquired or hereafter acquired, that would be infringed by some manner, permitted by this License, of making, using, or selling its contributor version, but do not include claims that would be infringed only as a consequence of further modification of the contributor version. For purposes of this definition, "control" includes the right to grant patent sublicenses in a manner consistent with the requirements of this License. Each contributor grants you a non-exclusive, worldwide, royalty-free patent license under the contributor's essential patent claims, to make, use, sell, offer for sale, import and otherwise run, modify and propagate the contents of its contributor version. In the following three paragraphs, a "patent license" is any express agreement or commitment, however denominated, not to enforce a patent (such as an express permission to practice a patent or covenant not to sue for patent infringement). To "grant" such a patent license to a party means to make such an agreement or commitment not to enforce a patent against the party. If you convey a covered work, knowingly relying on a patent license, and the Corresponding Source of the work is not available for anyone to copy, free of charge and under the terms of this License, through a publicly available network server or other readily accessible means, then you must either (1) cause the Corresponding Source to be so available, or (2) arrange to deprive yourself of the benefit of the patent license for this particular work, or (3) arrange, in a manner consistent with the requirements of this License, to extend the patent license to downstream recipients. "Knowingly relying" means you have actual knowledge that, but for the patent license, your conveying the covered work in a country, or your recipient's use of the covered work in a country, would infringe one or more identifiable patents in that country that you have reason to believe are valid. If, pursuant to or in connection with a single transaction or arrangement, you convey, or propagate by procuring conveyance of, a covered work, and grant a patent license to some of the parties receiving the covered work authorizing them to use, propagate, modify or convey a specific copy of the covered work, then the patent license you grant is automatically extended to all recipients of the covered work and works based on it. A patent license is "discriminatory" if it does not include within the scope of its coverage, prohibits the exercise of, or is conditioned on the non-exercise of one or more of the rights that are specifically granted under this License. You may not convey a covered work if you are a party to an arrangement with a third party that is in the business of distributing software, under which you make payment to the third party based on the extent of your activity of conveying the work, and under which the third party grants, to any of the parties who would receive the covered work from you, a discriminatory patent license (a) in connection with copies of the covered work conveyed by you (or copies made from those copies), or (b) primarily for and in connection with specific products or compilations that contain the covered work, unless you entered into that arrangement, or that patent license was granted, prior to 28 March 2007. Nothing in this License shall be construed as excluding or limiting any implied license or other defenses to infringement that may otherwise be available to you under applicable patent law. 12. No Surrender of Others' Freedom. If conditions are imposed on you (whether by court order, agreement or otherwise) that contradict the conditions of this License, they do not excuse you from the conditions of this License. If you cannot convey a covered work so as to satisfy simultaneously your obligations under this License and any other pertinent obligations, then as a consequence you may not convey it at all. For example, if you agree to terms that obligate you to collect a royalty for further conveying from those to whom you convey the Program, the only way you could satisfy both those terms and this License would be to refrain entirely from conveying the Program. 13. Use with the GNU Affero General Public License. Notwithstanding any other provision of this License, you have permission to link or combine any covered work with a work licensed under version 3 of the GNU Affero General Public License into a single combined work, and to convey the resulting work. The terms of this License will continue to apply to the part which is the covered work, but the special requirements of the GNU Affero General Public License, section 13, concerning interaction through a network will apply to the combination as such. 14. Revised Versions of this License. The Free Software Foundation may publish revised and/or new versions of the GNU General Public License from time to time. Such new versions will be similar in spirit to the present version, but may differ in detail to address new problems or concerns. Each version is given a distinguishing version number. If the Program specifies that a certain numbered version of the GNU General Public License "or any later version" applies to it, you have the option of following the terms and conditions either of that numbered version or of any later version published by the Free Software Foundation. If the Program does not specify a version number of the GNU General Public License, you may choose any version ever published by the Free Software Foundation. If the Program specifies that a proxy can decide which future versions of the GNU General Public License can be used, that proxy's public statement of acceptance of a version permanently authorizes you to choose that version for the Program. Later license versions may give you additional or different permissions. However, no additional obligations are imposed on any author or copyright holder as a result of your choosing to follow a later version. 15. Disclaimer of Warranty. THERE IS NO WARRANTY FOR THE PROGRAM, TO THE EXTENT PERMITTED BY APPLICABLE LAW. EXCEPT WHEN OTHERWISE STATED IN WRITING THE COPYRIGHT HOLDERS AND/OR OTHER PARTIES PROVIDE THE PROGRAM "AS IS" WITHOUT WARRANTY OF ANY KIND, EITHER EXPRESSED OR IMPLIED, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE. THE ENTIRE RISK AS TO THE QUALITY AND PERFORMANCE OF THE PROGRAM IS WITH YOU. SHOULD THE PROGRAM PROVE DEFECTIVE, YOU ASSUME THE COST OF ALL NECESSARY SERVICING, REPAIR OR CORRECTION. 16. Limitation of Liability. IN NO EVENT UNLESS REQUIRED BY APPLICABLE LAW OR AGREED TO IN WRITING WILL ANY COPYRIGHT HOLDER, OR ANY OTHER PARTY WHO MODIFIES AND/OR CONVEYS THE PROGRAM AS PERMITTED ABOVE, BE LIABLE TO YOU FOR DAMAGES, INCLUDING ANY GENERAL, SPECIAL, INCIDENTAL OR CONSEQUENTIAL DAMAGES ARISING OUT OF THE USE OR INABILITY TO USE THE PROGRAM (INCLUDING BUT NOT LIMITED TO LOSS OF DATA OR DATA BEING RENDERED INACCURATE OR LOSSES SUSTAINED BY YOU OR THIRD PARTIES OR A FAILURE OF THE PROGRAM TO OPERATE WITH ANY OTHER PROGRAMS), EVEN IF SUCH HOLDER OR OTHER PARTY HAS BEEN ADVISED OF THE POSSIBILITY OF SUCH DAMAGES. 17. Interpretation of Sections 15 and 16. If the disclaimer of warranty and limitation of liability provided above cannot be given local legal effect according to their terms, reviewing courts shall apply local law that most closely approximates an absolute waiver of all civil liability in connection with the Program, unless a warranty or assumption of liability accompanies a copy of the Program in return for a fee. END OF TERMS AND CONDITIONS How to Apply These Terms to Your New Programs If you develop a new program, and you want it to be of the greatest possible use to the public, the best way to achieve this is to make it free software which everyone can redistribute and change under these terms. To do so, attach the following notices to the program. It is safest to attach them to the start of each source file to most effectively state the exclusion of warranty; and each file should have at least the "copyright" line and a pointer to where the full notice is found. Copyright (C) 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, either version 3 of the License, or (at your option) any later version. 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 . Also add information on how to contact you by electronic and paper mail. If the program does terminal interaction, make it output a short notice like this when it starts in an interactive mode: Copyright (C) This program comes with ABSOLUTELY NO WARRANTY; for details type `show w'. This is free software, and you are welcome to redistribute it under certain conditions; type `show c' for details. The hypothetical commands `show w' and `show c' should show the appropriate parts of the General Public License. Of course, your program's commands might be different; for a GUI interface, you would use an "about box". You should also get your employer (if you work as a programmer) or school, if any, to sign a "copyright disclaimer" for the program, if necessary. For more information on this, and how to apply and follow the GNU GPL, see . The GNU General Public License does not permit incorporating your program into proprietary programs. If your program is a subroutine library, you may consider it more useful to permit linking proprietary applications with the library. If this is what you want to do, use the GNU Lesser General Public License instead of this License. But first, please read . ================================================ FILE: MANIFEST.in ================================================ include pyproject.toml include *.md include LICENSE.txt # Include ANTLR generated files recursive-include src/refind_btrfs/boot/antlr4 *.py # Include data files recursive-include src/refind_btrfs/data * # Exclude all bytecode global-exclude *.py[cdo] ================================================ FILE: README.md ================================================ # refind-btrfs ### Table of Contents - [Description](#description) - [Prerequisites](#prerequisites) - [Installation](#installation) - [Configuration](#configuration) - [Example](#example) - [Implementation](#implementation) - [Further Efforts](#further-efforts) ## Description This tool is used to automate a few tedious tasks required to boot into [Btrfs](https://en.wikipedia.org/wiki/Btrfs) snapshots from [rEFInd](https://en.wikipedia.org/wiki/REFInd). It is to rEFInd what [grub-btrfs](https://github.com/Antynea/grub-btrfs) is to [GRUB](https://en.wikipedia.org/wiki/GNU_GRUB). What it does is the following: * Gathers information about block devices present in the system * Identifies the [ESP](https://en.wikipedia.org/wiki/EFI_system_partition) (either by GPT GUID or MBR ID) * Gathers information about mounted filesystems (from [mtab](https://en.wikipedia.org/wiki/Mtab)) which are present on all of the found block devices * Identifies the root mount point and gathers information about the subvolume which is mounted at said mount point * Searches for snapshots of the identified subvolume in the configured directory (or directories) * Searches for rEFInd's main config file on the ESP and parses it to extract [manual boot stanzas](https://www.rodsbooks.com/refind/configfile.html#stanzas) from it (included configs are also analyzed, if present) * Selects the configured number of latest snapshots and uses them as such if they are writable and if any aren't, it either (depending on the configuration): * sets their read-only flag to false, thus making them writable * creates new writable snapshots from them in the configured location * Aligns the root mount point in the [fstab](https://en.wikipedia.org/wiki/Fstab) file of each selected snapshot with the snapshot itself * Deletes outdated previously created writable snapshots (if any exist) * Generates new manual boot stanzas from identified ones where every relevant field is aligned with each selected snapshot * Finally, it saves the generated manual boot stanzas in separate config files (outputs them to a subdirectory) and includes each file in the main config file so as not to needlessly clutter it In case a separate /boot partition is detected only the fields relevant to / are modified ("subvol" and/or "subvolid") while the "loader" and "initrd" fields (the former may also be nested within the "options" field) remain unaffected. It goes without saying that the consequence of having this kind of a setup is being unable to mitigate a problematic kernel upgrade by simply booting into a snapshot. This tool will also detect a situation where / is mounted as a snapshot (which means that you've already booted into one), issue a warning and simply exit whereas, for instance, [Snapper](http://snapper.io/) will happily continue creating its snapshots, regardless. This behavior is configurable and enabled by default. ## Prerequisites The following conditions (some are probably superfluous at this point) must be satisfied in order for this tool to function correctly: * mounted ESP (no automatic discovery and/or mounting is supported) * Btrfs formatted filesystem with a subvolume mounted as / * at least one snapshot of the root subvolume * rEFInd installation present on the ESP * at least one manual boot stanza (found in rEFInd's main config file or in any of the additional config files included within it) defined such that (see the [ArchWiki](https://wiki.archlinux.org/index.php/REFInd#Manual_boot_stanza) for an example) its own "options" field or any such field belonging to at least one of its sub-menus contains definitions of the following boot loader options: * the "root" option must be matched with the root partition (by PARTUUID or PARTLABEL), its filesystem (by UUID or LABEL) or with a block device (by name) which itself represents the root partition * the "rootflags" option must define a "subvol" suboption which is matched with the root subvolume's logical path and/or a "subvolid" suboption which is matched with the root subvolume's ID ## Installation This tool is currently available only in the [AUR](https://aur.archlinux.org/packages/refind-btrfs/) which means that [Arch Linux](https://www.archlinux.org/) users (as well as users of derivative distributions, I imagine) can easily install it. It comes with a script (refind-btrfs) which can be used to perform the described steps, on-demand (root privileges are required to run it). There is also a [systemd](https://en.wikipedia.org/wiki/Systemd) service aptly named **refind-btrfs.service** which runs the tool in a background mode of operation where the described steps are performed automatically once a change (snapshot creation or deletion) happens in the watched snapshot directories which are the same ones as those in which it searches for snapshots. If you are using Snapper along with its capability to take regular snapshots on boot this service should take these into account as well because it is set to start before Snapper's relevant service does so (the one named snapper-boot.service). Before running the script for the first time or enabling and starting the service make sure to at least check and perhaps modify the config file (/etc/refind-btrfs.conf) to suit your own needs. If you wish to check the current status and log output of the running service you can do so by executing: ``` systemctl status refind-btrfs journalctl -u refind-btrfs -b ``` Alternatively, there exists a [PyPI](https://pypi.org/project/refind-btrfs/) package but bear in mind that since [libbtrfsutil](https://github.com/kdave/btrfs-progs/tree/master/libbtrfsutil) isn't available on PyPI it needs to be already present in the system site packages (its Python bindings, to be precise) because it cannot be automatically pulled in as a dependency. Chances are that it is available for your distribution of choice (search for a package named "btrfs-progs") but you most probably already have it installed as I suppose you are using Btrfs, after all. Also, every file contained in [this](https://github.com/Venom1991/refind-btrfs/tree/master/src/refind_btrfs/data) directory should be copied to the following locations: * refind-btrfs script to /usr/bin (or wherever it is you keep your system-wide executables) * refind-btrfs.conf-sample as refind-btrfs.conf (without the "-sample" suffix) to /etc * refind-btrfs.service to /usr/lib/systemd/system (if you are using systemd and wish to utilize the snapshot directory watching feature) In case the custom generated boot stanza's icon feature (explained in the next section) is desired it can initially be enabled by installing this package with the following command: ``` pip install refind-btrfs[custom_icon] ``` You should also create an empty directory named "refind-btrfs" in /var/lib as the tool expects that it is present. Additionally, if you wish to be able to use the Btrfs logo embedding mode of custom icon generation you should also copy the "[icons](https://github.com/Venom1991/refind-btrfs/tree/master/src/refind_btrfs/data/icons)" directory into the previously created one. ## Configuration The configuration file can be found at `/etc/refind-btrfs.conf`, and each option is thoroughly explained in the sample config [file](https://github.com/Venom1991/refind-btrfs/blob/master/src/refind_btrfs/data/refind-btrfs.conf-sample). In case you've opted to use the provided systemd service and wish to change the search directories (in this context, these are actually watched directories) in the config file while it is running you must restart it manually after doing so because the directory observer is started only once and an automatic restart is not performed. The default configuration is meant to enable seamless integration with Snapper simply because I'm using it but the tool itself doesn't depend on it and ought to function with different setups. Also, by default the tool is configured for creating new writable snapshots intended for booting instead of in-place modification of the found snapshots' read-only flags as I believe this is the safer (or perhaps even saner) choice. [Timeshift](https://github.com/teejee2008/timeshift) users can try setting the [default](https://github.com/Venom1991/refind-btrfs/blob/d1e3c474ed88d7b1ad3948d75bf6f167da676c5d/src/refind_btrfs/data/refind-btrfs.conf-sample#L65) snapshot search directory to "/run/timeshift/backup/timeshift-btrfs/snapshots" and the corresponding maximum search depth to three. If you're having trouble with the ESP being automatically located, the "esp_uuid" option could prove to be useful. If an actual UUID is provided (not the default, empty one), this value will be used to compare partition UUIDs (returned by lsblk) instead of comparing their types with hardcoded GPT UUID or MBR ID values. Custom generated boot stanza icon support is also implemented, by default the source boot stanza's icon is reused. It is possible to provide one's own custom icon's path or to embed the Btrfs logo (comes in two variants and three sizes per each variant) into the source boot stanza's icon instead. This combined icon is then used as the generated boot stanza's icon. In order for these two additional modes of operation (not the default one) to work an optional dependency has to be installed - namely, the [Pillow](https://python-pillow.org) library which can be installed from the official Arch Linux [repository](https://archlinux.org/packages/community/x86_64/python-pillow/) or from [PyPI](https://pypi.org/project/Pillow/). It is imperative that you don't just blindly try to boot into a given snapshot (simply because no errors were reported) before verifying the generated manual boot stanza, either by inspecting the file contents in which it was saved or by viewing the boot loader [options](https://www.rodsbooks.com/refind/using.html#boot_options) using rEFInd and also not before verifying the chosen snapshot's fstab file. ## Example Given a setup such as this one: * device /dev/nvme0n1 where: * the ESP is on /dev/nvme0n1p3 mounted at /efi * / is on /dev/nvme0n1p8 * /boot is included in /dev/nvme0n1p8 (**not** a separate partition) * the subvolume mounted as / is named @ * fstab file's root mount point: ``` UUID=95250e8a-5870-45df-a7b3-3b3ee8873c16 / btrfs rw,noatime,compress-force=zstd:2,ssd,space_cache=v2,commit=15,subvolid=256,subvol=/@ 0 0 ``` * manual boot stanza defined in the refind.conf file (rEFInd's main config file, in this case): ``` menuentry "Arch Linux - Stable" { icon /EFI/refind/icons/os_arch.png volume ARCH loader /@/boot/vmlinuz-linux initrd /@/boot/initramfs-linux.img options "root=PARTUUID=048d6fcd-c88c-504d-bd51-dfc0a5bf762d rw add_efi_memmap rootflags=subvol=@ initrd=@\boot\intel-ucode.img" submenuentry "Boot - fallback" { initrd /@/boot/initramfs-linux-fallback.img } submenuentry "Boot - terminal" { add_options "systemd.unit=multi-user.target" } } ``` * five read-only snapshots located in the /.snapshots directory where this directory is itself mounted as a subvolume named @snapper-root (this last bit isn't particularly relevant): | Absolute Path | Time of Creation | Subvolume ID | | ---------------------- | ------------------- | ------------ | | /.snapshots/1/snapshot | 10-12-2020 01:00:00 | 498 | | /.snapshots/2/snapshot | 11-12-2020 02:00:00 | 499 | | /.snapshots/3/snapshot | 12-12-2020 03:00:00 | 500 | | /.snapshots/4/snapshot | 13-12-2020 04:00:00 | 501 | | /.snapshots/5/snapshot | 14-12-2020 05:00:00 | 502 | * refind-btrfs.conf file changed such that the "selection_count" option is set to 3 instead of the default 5 When run, this tool should select the latest three snapshots (3, 4 and 5 from the list) and create new, writable ones from these in the directory configured by the "destination_dir" option where each snapshot is named by formatting the time of creation ("YYYY-mm-dd_HH-MM-SS") of the snapshot it was created from, adding a "rwsnap" prefix to it and also adding the original snapshot's subvolume ID as a suffix. In the rare case when different snapshots have identical timestamps their monotonic numerical IDs are there to ensure uniqueness. Afterwards, the resultant snapshots' generated names should look like this: * rwsnap_2020-12-12_03-00-00_ID500, * rwsnap_2020-12-13_04-00-00_ID501 and * rwsnap_2020-12-14_05-00-00_ID502 This naming scheme makes sense to me because when choosing a snapshot to boot from you most probably want to know when the original snapshot was created and not the one created from it because the time delay depends on when this tool was run and, if sufficiently large, can completely mislead you. If you've chosen to use the systemd service this delay shouldn't be significant (measuring a mere few seconds at worst, ideally). The most recent snapshot's fstab file should (after being modified) contain a root mount point which looks like this: ``` UUID=95250e8a-5870-45df-a7b3-3b3ee8873c16 / btrfs rw,noatime,compress-force=zstd:2,ssd,space_cache=v2,commit=15,subvolid=503,subvol=/@/root/.refind-btrfs/rwsnap_2020-12-14_05-00-00_ID502 0 0 ``` I'm assuming here that the next available subvolume ID was 503 (an increment of one) which implies that the writable snapshot was created immediately after the original snapshot was taken but that doesn't necessarily have to be the case and its specific value doesn't ultimately matter that much as long as it directly corresponds to the newly created snapshot which it absolutely should (otherwise, mounting it as / would fail due to the mismatch). With this setup the newly created snapshot ended up being nested under the root subvolume but you can of course make your own adjustments as you see fit. This tool will only create the destination directory in case it doesn't exist. It won't do anything other than that. I've personally created another subvolume named @rw-snapshots directly under the default filesystem subvolume (ID 5) and mounted it at /root/.refind-btrfs. In my case the logical path of rwsnap_2020-12-14_05-00-00_ID502 would be /@rw-snapshots/rwsnap_2020-12-14_05-00-00_ID502. A generated manual boot stanza's filename is formatted like "{volume}_{loader}.conf" and converted to all lowercase letters which would result in, for this example, a file named "arch_vmlinuz-linux.conf". This file is then saved in a subdirectory (relative to rEFInd's root directory) named "btrfs-snapshot-stanzas" and finally included in the main config file by appending an "include" directive which would, again for this example, look like this: "include btrfs-snapshot-stanzas/arch_vmlinuz-linux.conf". This last step is performed only once, during an initial run. Afterwards, it is detected as already being included in the main config file. You are free to rearrange the appended include directives however you want, this tool does not care about where exactly they appear in the main config file. This is particularly useful in case you've defined multiple boot stanzas (each one pointing to a different kernel image, for example) and wish to alter the order of the boot menu entries. The generated file's contents (representing the generated stanza) should look like this: ``` menuentry "Arch Linux - Stable (rwsnap_2020-12-14_05-00-00_ID502)" { icon /EFI/refind/icons/os_arch.png volume ARCH loader /@/root/.refind-btrfs/rwsnap_2020-12-14_05-00-00_ID502/boot/vmlinuz-linux initrd /@/root/.refind-btrfs/rwsnap_2020-12-14_05-00-00_ID502/boot/initramfs-linux.img options "root=PARTUUID=048d6fcd-c88c-504d-bd51-dfc0a5bf762d rw add_efi_memmap rootflags=subvol=@/root/.refind-btrfs/rwsnap_2020-12-14_05-00-00_ID502 initrd=@\root\.refind-btrfs\rwsnap_2020-12-14_05-00-00_ID502\boot\intel-ucode.img" submenuentry "Arch Linux - Stable (rwsnap_2020-12-13_04-00-00_ID501)" { loader /@/root/.refind-btrfs/rwsnap_2020-12-13_04-00-00_ID501/boot/vmlinuz-linux initrd /@/root/.refind-btrfs/rwsnap_2020-12-13_04-00-00_ID501/boot/initramfs-linux.img options "root=PARTUUID=048d6fcd-c88c-504d-bd51-dfc0a5bf762d rw add_efi_memmap rootflags=subvol=@/root/.refind-btrfs/rwsnap_2020-12-13_04-00-00_ID501 initrd=@\root\.refind-btrfs\rwsnap_2020-12-13_04-00-00_ID501\boot\intel-ucode.img" } submenuentry "Arch Linux - Stable (rwsnap_2020-12-12_03-00-00_ID500)" { loader /@/root/.refind-btrfs/rwsnap_2020-12-12_03-00-00_ID500/boot/vmlinuz-linux initrd /@/root/.refind-btrfs/rwsnap_2020-12-12_03-00-00_ID500/boot/initramfs-linux.img options "root=PARTUUID=048d6fcd-c88c-504d-bd51-dfc0a5bf762d rw add_efi_memmap rootflags=subvol=@/root/.refind-btrfs/rwsnap_2020-12-12_03-00-00_ID500 initrd=@\root\.refind-btrfs\rwsnap_2020-12-12_03-00-00_ID500\boot\intel-ucode.img" } } ``` As you've probably noticed, this tool leverages rEFInd's overriding features, that is to say "submenuentry" sections are used to incorporate successive snapshots into the stanza itself by overriding the "loader", "initrd" and "options" fields of the main boot stanza which itself represents the latest snapshot. If you've configured this tool to also take into account the original boot stanza's sub-menus the resultant generated boot stanza should look like this: ``` menuentry "Arch Linux - Stable (rwsnap_2020-12-14_05-00-00_ID502)" { icon /EFI/refind/icons/os_arch.png volume ARCH loader /@/root/.refind-btrfs/rwsnap_2020-12-14_05-00-00_ID502/boot/vmlinuz-linux initrd /@/root/.refind-btrfs/rwsnap_2020-12-14_05-00-00_ID502/boot/initramfs-linux.img options "root=PARTUUID=048d6fcd-c88c-504d-bd51-dfc0a5bf762d rw add_efi_memmap rootflags=subvol=@/root/.refind-btrfs/rwsnap_2020-12-14_05-00-00_ID502 initrd=@\root\.refind-btrfs\rwsnap_2020-12-14_05-00-00_ID502\boot\intel-ucode.img" submenuentry "Boot - fallback (rwsnap_2020-12-14_05-00-00_ID502)" { initrd /@/root/.refind-btrfs/rwsnap_2020-12-14_05-00-00_ID502/boot/initramfs-linux-fallback.img } submenuentry "Boot - terminal (rwsnap_2020-12-14_05-00-00_ID502)" { add_options "systemd.unit=multi-user.target" } submenuentry "Arch Linux - Stable (rwsnap_2020-12-13_04-00-00_ID501)" { loader /@/root/.refind-btrfs/rwsnap_2020-12-13_04-00-00_ID501/boot/vmlinuz-linux initrd /@/root/.refind-btrfs/rwsnap_2020-12-13_04-00-00_ID501/boot/initramfs-linux.img options "root=PARTUUID=048d6fcd-c88c-504d-bd51-dfc0a5bf762d rw add_efi_memmap rootflags=subvol=@/root/.refind-btrfs/rwsnap_2020-12-13_04-00-00_ID501 initrd=@\root\.refind-btrfs\rwsnap_2020-12-13_04-00-00_ID501\boot\intel-ucode.img" } submenuentry "Boot - fallback (rwsnap_2020-12-13_04-00-00_ID501)" { loader /@/root/.refind-btrfs/rwsnap_2020-12-13_04-00-00_ID501/boot/vmlinuz-linux initrd /@/root/.refind-btrfs/rwsnap_2020-12-13_04-00-00_ID501/boot/initramfs-linux-fallback.img options "root=PARTUUID=048d6fcd-c88c-504d-bd51-dfc0a5bf762d rw add_efi_memmap rootflags=subvol=@/root/.refind-btrfs/rwsnap_2020-12-13_04-00-00_ID501 initrd=@\root\.refind-btrfs\rwsnap_2020-12-13_04-00-00_ID01\boot\intel-ucode.img" } submenuentry "Boot - terminal (rwsnap_2020-12-13_04-00-00_ID501)" { loader /@/root/.refind-btrfs/rwsnap_2020-12-13_04-00-00_ID501/boot/vmlinuz-linux initrd /@/root/.refind-btrfs/rwsnap_2020-12-13_04-00-00_ID501/boot/initramfs-linux.img options "root=PARTUUID=048d6fcd-c88c-504d-bd51-dfc0a5bf762d rw add_efi_memmap rootflags=subvol=@/root/.refind-btrfs/rwsnap_2020-12-13_04-00-00_ID501 initrd=@\root\.refind-btrfs\rwsnap_2020-12-13_04-00-00_ID501\boot\intel-ucode.img systemd.unit=multi-user.target" } submenuentry "Arch Linux - Stable (rwsnap_2020-12-12_03-00-00_ID500)" { loader /@/root/.refind-btrfs/rwsnap_2020-12-12_03-00-00_ID500/boot/vmlinuz-linux initrd /@/root/.refind-btrfs/rwsnap_2020-12-12_03-00-00_ID500/boot/initramfs-linux.img options "root=PARTUUID=048d6fcd-c88c-504d-bd51-dfc0a5bf762d rw add_efi_memmap rootflags=subvol=@/root/.refind-btrfs/rwsnap_2020-12-12_03-00-00_ID500 initrd=@\root\.refind-btrfs\rwsnap_2020-12-12_03-00-00_ID500\boot\intel-ucode.img" } submenuentry "Boot - fallback (rwsnap_2020-12-12_03-00-00_ID500)" { loader /@/root/.refind-btrfs/rwsnap_2020-12-12_03-00-00_ID500/boot/vmlinuz-linux initrd /@/root/.refind-btrfs/rwsnap_2020-12-12_03-00-00_ID500/boot/initramfs-linux-fallback.img options "root=PARTUUID=048d6fcd-c88c-504d-bd51-dfc0a5bf762d rw add_efi_memmap rootflags=subvol=@/root/.refind-btrfs/rwsnap_2020-12-12_03-00-00_ID500 initrd=@\root\.refind-btrfs\rwsnap_2020-12-12_03-00-00_ID500\boot\intel-ucode.img" } submenuentry "Boot - terminal (rwsnap_2020-12-12_03-00-00_ID500)" { loader /@/root/.refind-btrfs/rwsnap_2020-12-12_03-00-00_ID500/boot/vmlinuz-linux initrd /@/root/.refind-btrfs/rwsnap_2020-12-12_03-00-00_ID500/boot/initramfs-linux.img options "root=PARTUUID=048d6fcd-c88c-504d-bd51-dfc0a5bf762d rw add_efi_memmap rootflags=subvol=@/root/.refind-btrfs/rwsnap_2020-12-12_03-00-00_ID500 initrd=@\root\.refind-btrfs\rwsnap_2020-12-12_03-00-00_ID500\boot\intel-ucode.img systemd.unit=multi-user.target" } } ``` A couple of notable details are the fact that the "add_options" field (if it exists) of any given sub-menu belonging to a successive snapshot is merged with the "options" field of the corresponding snapshot's sub-menu and also the fact that the latest snapshot's sub-menus implicitly inherit those main stanza's fields which they themselves do not override in the original boot stanza. Consequently, these sub-menus' definitions are intentionally similar to those of their counterparts found in the original boot stanza. This is how an Arch Linux installation with three different kernels (XanMod, Stable and LTS) should appear in rEFInd (the default theme is shown) after this tool has successfully completed its job: ![rEFInd Screenshot Default](src/refind_btrfs/data/images/refind_screenshot_default.png) Here, each manual boot stanza uses its own custom icon based on the default Arch Linux OS icon. The Btrfs logo is then also embedded into these icons (by setting [this](https://github.com/Venom1991/refind-btrfs/blob/4e0e629680fc581143c684e6e90958cbe26db8fc/src/refind_btrfs/data/refind-btrfs.conf-sample#L158) option to "embed_btrfs_logo") and the resultant icons are defined as part of their corresponding generated boot stanzas. By using a darker theme (such as the [Nord](https://github.com/jaltuna/refind-theme-nord) theme - shown in the following screenshot) and by using the "inverted" Btrfs logo's variant (as opposed to the "original" one, shown in the previous screenshot), the same Arch Linux installation should appear in rEFInd looking like this: ![rEFInd Screenshot Nord](src/refind_btrfs/data/images/refind_screenshot_nord.png) ## Implementation Most relevant dependencies: * block device and ESP information is gathered using [lsblk](https://man7.org/linux/man-pages/man8/lsblk.8.html) (supports JSON output) * mtab information is gathered using [findmnt](https://man7.org/linux/man-pages/man8/findmnt.8.html) (same remark applies regarding the output) * all of the mentioned subvolume and snapshot operations are performed using [libbtrfsutil](https://github.com/kdave/btrfs-progs/tree/master/libbtrfsutil) * [ANLTR4](https://github.com/antlr/antlr4) was used to generate the lexer and parser required for rEFInd config files' analyses * [Watchdog](https://github.com/gorakhargosh/watchdog) is used for the snapshot directory watching feature and is utilized in a non-recursive fashion (watches all of the configured search directories as well as directories nested under these, up to configured maximum depth reduced by one) * [python-systemd](https://github.com/systemd/python-systemd) is used for notifying systemd about the service's readiness (because its type is set to "notify") and also for logging to the journal [Shelve](https://docs.python.org/3/library/shelve.html) is used to keep track of the currently processed snapshots and also to avoid analyzing the rEFInd config file each time as it is quite an expensive task. A new analysis is performed in case the current and actual times of modification differ ([st_mtime](https://docs.python.org/3/library/os.html#os.stat_result.st_mtime) is used for that purpose) which means that simply touching the file should also trigger a new analysis (file hashes aren't computed nor consequently compared). This fact also explains the need for a directory in /var/lib as the database file resides in it. The directory watching mechanism is a bit unfortunate in a sense that it is way overkill for the task at hand. Even though Watchdog is a great, battle-tested library and many people use it, I feel that this solution isn't particularly well suited to this tool but it will simply have to suffice for now as I don't have a better idea (grub-btrfs also relies on a similar mechanism), at least not until the Btrfs authors develop [this](https://btrfs.wiki.kernel.org/index.php/Project_ideas#Send_notifications_about_important_events) useful feature or something akin to it. ## Further Efforts Currently, this tool won't clean up after itself in case, for instance, creating writable snapshots succeeds but generating a manual boot stanza from them fails (for whatever reason). The correct thing to do would be to delete these snapshots altogether (thus undoing the changes made by the previous step or roll-backing as it is often called) meaning that the whole run is considered to be successful if and only if all of the steps it performed were successful. This behavior would then be comparable with the [atomicity](https://en.wikipedia.org/wiki/Atomicity_(database_systems)) principle to which most database systems adhere. The previously mentioned scenario is covered in a different way by issuing a relevant warning on the next attempt to run the tool (because the writable snapshots already exist at this point in time and they aren't expected to) but also continuing to perform successive steps. This isn't a general solution, of course, but more of a workaround for this one possible scenario. With that said, being somehow able to preview changes proposed by this tool would also be beneficial, especially after altering its configuration. A more elaborate snapshot selection mechanism would be appreciated, comparable to what Snapper does, that is selecting a configurable number of daily, weekly, etc. snapshots to be included in the generated manual boot stanza. Generated boot stanzas' names are initialized using a hardcoded format string which is not ideal. It would be more convenient to provide a way for users to define their own format string using a combination of predefined variables (time of the source snapshot's creation, its numerical ID, etc.) along with some entirely arbitrary parts. But, before trying to implement any of these shiny features this project's source code should be properly documented and tests should be written for it because, presently, there aren't any. The latter is also a pretty considerable effort due to the sheer number of different test cases. Luckily, all of the external dependencies (OS commands, third-party library calls and similar) are abstracted away which means that no significant preparatory steps regarding the codebase to be tested are required beforehand. ================================================ FILE: pyproject.toml ================================================ [build-system] requires = ["setuptools", "wheel"] build-backend = "setuptools.build_meta" ================================================ FILE: setup.cfg ================================================ [metadata] name = refind_btrfs version = 0.6.5 description = Generate rEFInd manual boot stanzas from Btrfs snapshots long_description = file: README.md keywords = rEFInd, btrfs url = https://github.com/Venom1991/refind-btrfs author = Luka Žaja author_email = luka.zaja@protonmail.com maintainer = Luka Žaja maintainer_email = luka.zaja@protonmail.com license = GNU General Public License v3 or later (GPLv3+) license_file = LICENSE.txt platforms = Linux classifiers = Development Status :: 4 - Beta Intended Audience :: End Users/Desktop License :: OSI Approved :: GNU General Public License v3 or later (GPLv3+) Natural Language :: English Operating System :: POSIX :: Linux Programming Language :: Python :: 3.11 Topic :: System :: Boot [options] package_dir = =src packages = find: include_package_data = True install_requires = antlr4-python3-runtime injector more-itertools pid semantic-version systemd-python tomlkit transitions typeguard watchdog python_requires = >= 3.11 [options.extras_require] custom_icon = Pillow [options.entry_points] console_scripts = refind-btrfs = refind_btrfs:main [options.packages.find] where = src [bdist_wheel] universal = False ================================================ FILE: setup.py ================================================ # region Licensing # SPDX-FileCopyrightText: 2020-2024 Luka Žaja # # SPDX-License-Identifier: GPL-3.0-or-later """ refind-btrfs - Generate rEFInd manual boot stanzas from Btrfs snapshots Copyright (C) 2020-2024 Luka Žaja 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, either version 3 of the License, or (at your option) any later version. 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 . """ # endregion import setuptools with open("README.md", "r", encoding="utf-8") as readme: long_description = readme.read() setuptools.setup( name="refind-btrfs", version="0.6.5", author="Luka Žaja", author_email="luka.zaja@protonmail.com", description="Generate rEFInd manual boot stanzas from Btrfs snapshots", long_description=long_description, long_description_content_type="text/markdown", keywords="rEFInd, btrfs", url="https://github.com/Venom1991/refind-btrfs", classifiers=[ "Development Status :: 4 - Beta", "Intended Audience :: End Users/Desktop", "License :: OSI Approved :: GNU General Public License v3 or later (GPLv3+)", "Natural Language :: English", "Operating System :: POSIX :: Linux", "Programming Language :: Python :: 3.11", "Topic :: System :: Boot", ], package_dir={"": "src"}, packages=setuptools.find_packages(where="src"), include_package_data=True, install_requires=[ "antlr4-python3-runtime", "injector", "more-itertools", "pid", "semantic-version", "systemd-python", "tomlkit", "transitions", "typeguard", "watchdog", ], entry_points={ "console_scripts": [ "refind-btrfs=refind_btrfs:main", ], }, extras_require={"custom_icon": ["Pillow"]}, python_requires=">=3.11", ) ================================================ FILE: src/refind_btrfs/__init__.py ================================================ # region Licensing # SPDX-FileCopyrightText: 2020-2024 Luka Žaja # # SPDX-License-Identifier: GPL-3.0-or-later """ refind-btrfs - Generate rEFInd manual boot stanzas from Btrfs snapshots Copyright (C) 2020-2024 Luka Žaja 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, either version 3 of the License, or (at your option) any later version. 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 . """ # endregion import os from argparse import ArgumentParser from typing import Optional from injector import Injector from refind_btrfs.common import constants from refind_btrfs.common.abc import BaseRunner from refind_btrfs.common.abc.factories import BaseLoggerFactory from refind_btrfs.common.enums import RunMode from refind_btrfs.common.exceptions import PackageConfigError from refind_btrfs.utility.helpers import check_access_rights, checked_cast, none_throws from refind_btrfs.utility.injector_modules import CLIModule, WatchdogModule def initialize_injector() -> Optional[Injector]: one_time_mode = RunMode.ONE_TIME.value background_mode = RunMode.BACKGROUND.value parser = ArgumentParser( prog="refind-btrfs", usage="%(prog)s [options]", description="Generate rEFInd manual boot stanzas from Btrfs snapshots", ) parser.add_argument( "-rm", "--run-mode", help="Mode of execution", choices=[one_time_mode, background_mode], type=str, nargs="?", const=one_time_mode, default=one_time_mode, ) arguments = parser.parse_args() run_mode = checked_cast(str, none_throws(arguments.run_mode)) if run_mode == one_time_mode: return Injector(CLIModule) elif run_mode == background_mode: return Injector(WatchdogModule) return None def main() -> int: exit_code = os.EX_OK injector = none_throws(initialize_injector()) logger_factory = injector.get(BaseLoggerFactory) logger = logger_factory.logger(__name__) try: check_access_rights() runner = injector.get(BaseRunner) exit_code = runner.run() except PackageConfigError as e: exit_code = constants.EX_NOT_OK logger.error(e.formatted_message) except PermissionError as e: exit_code = e.errno logger.error(e.strerror) except Exception: exit_code = constants.EX_NOT_OK logger.exception(constants.MESSAGE_UNEXPECTED_ERROR) return exit_code ================================================ FILE: src/refind_btrfs/__main__.py ================================================ # region Licensing # SPDX-FileCopyrightText: 2020-2024 Luka Žaja # # SPDX-License-Identifier: GPL-3.0-or-later """ refind-btrfs - Generate rEFInd manual boot stanzas from Btrfs snapshots Copyright (C) 2020-2024 Luka Žaja 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, either version 3 of the License, or (at your option) any later version. 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 . """ # endregion import sys from . import main if __name__ == "__main__": sys.exit(main()) ================================================ FILE: src/refind_btrfs/boot/__init__.py ================================================ # region Licensing # SPDX-FileCopyrightText: 2020-2024 Luka Žaja # # SPDX-License-Identifier: GPL-3.0-or-later """ refind-btrfs - Generate rEFInd manual boot stanzas from Btrfs snapshots Copyright (C) 2020-2024 Luka Žaja 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, either version 3 of the License, or (at your option) any later version. 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 . """ # endregion from .boot_options import BootOptions from .boot_stanza import BootStanza from .refind_config import RefindConfig from .sub_menu import SubMenu ================================================ FILE: src/refind_btrfs/boot/antlr4/RefindConfigLexer.g4 ================================================ /* SPDX-FileCopyrightText: 2020-2024 Luka Žaja SPDX-License-Identifier: GPL-3.0-or-later refind-btrfs - Generate rEFInd manual boot stanzas from Btrfs snapshots Copyright (C) 2020-2024 Luka Žaja 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, either version 3 of the License, or (at your option) any later version. 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 . */ lexer grammar RefindConfigLexer; WHITESPACE : [ \t]+ -> skip ; NEWLINE : '\r'?'\n' -> skip ; EMPTY : WHITESPACE? NEWLINE -> skip ; COMMENT : '#' (~[\n])* NEWLINE? -> skip ; IGNORED_OPTION : ( 'also_scan_dirs' | 'also_scan_tools' | 'banner' | 'banner_scale' | 'big_icon_size' | 'csr_values' | 'default_selection' | 'don\'t_scan_dirs' | 'don\'t_scan_files' | 'don\'t_scan_firmware' | 'don\'t_scan_tools' | 'don\'t_scan_volumes' | 'dont_scan_dirs' | 'dont_scan_files' | 'dont_scan_firmware' | 'dont_scan_tools' | 'dont_scan_volumes' | 'enable_and_lock_vmx' | 'enable_mouse' | 'enable_touch' | 'extra_kernel_version_strings' | 'fold_linux_kernels' | 'follow_symlinks' | 'font' | 'hideui' | 'icons_dir' | 'linux_prefixes' | 'log_level' | 'max_tags' | 'mouse_size' | 'mouse_speed' | 'resolution' | 'scan_all_linux_kernels' | 'scan_delay' | 'scan_driver_dirs' | 'scanfor' | 'screensaver' | 'selection_big' | 'selection_small' | 'showtools' | 'shutdown_after_timeout' | 'small_icon_size' | 'spoof_osx_version' | 'support_gzipped_loaders' | 'textmode' | 'textonly' | 'timeout' | 'uefi_deep_legacy_scan' | 'use_graphics_for' | 'use_nvram' | 'windows_recovery_files' | 'write_systemd_vars' ) (~[\n])* NEWLINE? -> skip ; MENU_ENTRY : (MAIN_MENU_ENTRY | SUB_MENU_ENTRY) ; fragment MAIN_MENU_ENTRY : 'menuentry' ; fragment SUB_MENU_ENTRY : 'submenuentry' ; VOLUME : 'volume' ; LOADER : 'loader' ; INITRD : 'initrd' ; ICON : 'icon' ; OS_TYPE : 'ostype' WHITESPACE -> pushMode(STRICT_PARAMETER_MODE) ; GRAPHICS : 'graphics' WHITESPACE -> pushMode(STRICT_PARAMETER_MODE) ; BOOT_OPTIONS : 'options' ; ADD_BOOT_OPTIONS : 'add_options' ; FIRMWARE_BOOTNUM : 'firmware_bootnum' ; DISABLED : 'disabled' ; INCLUDE : 'include' ; OPEN_BRACE : '{' ; CLOSE_BRACE : '}' ; HEX_INTEGER : HEX_DIGIT+ ; fragment HEX_DIGIT: [0-9a-fA-F] ; STRING: (SINGLE_QUOTED_STRING | DOUBLE_QUOTED_STRING | UNQUOTED_STRING) ; fragment SINGLE_QUOTED_STRING : '\'' (~[\n])+ '\'' ; fragment DOUBLE_QUOTED_STRING : '"' (~[\n])+ '"' ; fragment UNQUOTED_STRING : (~[ \t\n])+ ; mode STRICT_PARAMETER_MODE; OS_TYPE_PARAMETER : ('MacOS' | 'Linux' | 'ELILO' | 'Windows' | 'XOM') -> popMode ; GRAPHICS_PARAMETER : ('on' | 'off') -> popMode ; ================================================ FILE: src/refind_btrfs/boot/antlr4/RefindConfigLexer.interp ================================================ token literal names: null null null null null null null 'volume' 'loader' 'initrd' 'icon' null null 'options' 'add_options' 'firmware_bootnum' 'disabled' 'include' '{' '}' null null null null token symbolic names: null WHITESPACE NEWLINE EMPTY COMMENT IGNORED_OPTION MENU_ENTRY VOLUME LOADER INITRD ICON OS_TYPE GRAPHICS BOOT_OPTIONS ADD_BOOT_OPTIONS FIRMWARE_BOOTNUM DISABLED INCLUDE OPEN_BRACE CLOSE_BRACE HEX_INTEGER STRING OS_TYPE_PARAMETER GRAPHICS_PARAMETER rule names: WHITESPACE NEWLINE EMPTY COMMENT IGNORED_OPTION MENU_ENTRY MAIN_MENU_ENTRY SUB_MENU_ENTRY VOLUME LOADER INITRD ICON OS_TYPE GRAPHICS BOOT_OPTIONS ADD_BOOT_OPTIONS FIRMWARE_BOOTNUM DISABLED INCLUDE OPEN_BRACE CLOSE_BRACE HEX_INTEGER HEX_DIGIT STRING SINGLE_QUOTED_STRING DOUBLE_QUOTED_STRING UNQUOTED_STRING OS_TYPE_PARAMETER GRAPHICS_PARAMETER channel names: DEFAULT_TOKEN_CHANNEL HIDDEN mode names: DEFAULT_MODE STRICT_PARAMETER_MODE atn: [4, 0, 23, 1036, 6, -1, 6, -1, 2, 0, 7, 0, 2, 1, 7, 1, 2, 2, 7, 2, 2, 3, 7, 3, 2, 4, 7, 4, 2, 5, 7, 5, 2, 6, 7, 6, 2, 7, 7, 7, 2, 8, 7, 8, 2, 9, 7, 9, 2, 10, 7, 10, 2, 11, 7, 11, 2, 12, 7, 12, 2, 13, 7, 13, 2, 14, 7, 14, 2, 15, 7, 15, 2, 16, 7, 16, 2, 17, 7, 17, 2, 18, 7, 18, 2, 19, 7, 19, 2, 20, 7, 20, 2, 21, 7, 21, 2, 22, 7, 22, 2, 23, 7, 23, 2, 24, 7, 24, 2, 25, 7, 25, 2, 26, 7, 26, 2, 27, 7, 27, 2, 28, 7, 28, 1, 0, 4, 0, 62, 8, 0, 11, 0, 12, 0, 63, 1, 0, 1, 0, 1, 1, 3, 1, 69, 8, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 2, 3, 2, 76, 8, 2, 1, 2, 1, 2, 1, 2, 1, 2, 1, 3, 1, 3, 5, 3, 84, 8, 3, 10, 3, 12, 3, 87, 9, 3, 1, 3, 3, 3, 90, 8, 3, 1, 3, 1, 3, 1, 4, 1, 4, 1, 4, 1, 4, 1, 4, 1, 4, 1, 4, 1, 4, 1, 4, 1, 4, 1, 4, 1, 4, 1, 4, 1, 4, 1, 4, 1, 4, 1, 4, 1, 4, 1, 4, 1, 4, 1, 4, 1, 4, 1, 4, 1, 4, 1, 4, 1, 4, 1, 4, 1, 4, 1, 4, 1, 4, 1, 4, 1, 4, 1, 4, 1, 4, 1, 4, 1, 4, 1, 4, 1, 4, 1, 4, 1, 4, 1, 4, 1, 4, 1, 4, 1, 4, 1, 4, 1, 4, 1, 4, 1, 4, 1, 4, 1, 4, 1, 4, 1, 4, 1, 4, 1, 4, 1, 4, 1, 4, 1, 4, 1, 4, 1, 4, 1, 4, 1, 4, 1, 4, 1, 4, 1, 4, 1, 4, 1, 4, 1, 4, 1, 4, 1, 4, 1, 4, 1, 4, 1, 4, 1, 4, 1, 4, 1, 4, 1, 4, 1, 4, 1, 4, 1, 4, 1, 4, 1, 4, 1, 4, 1, 4, 1, 4, 1, 4, 1, 4, 1, 4, 1, 4, 1, 4, 1, 4, 1, 4, 1, 4, 1, 4, 1, 4, 1, 4, 1, 4, 1, 4, 1, 4, 1, 4, 1, 4, 1, 4, 1, 4, 1, 4, 1, 4, 1, 4, 1, 4, 1, 4, 1, 4, 1, 4, 1, 4, 1, 4, 1, 4, 1, 4, 1, 4, 1, 4, 1, 4, 1, 4, 1, 4, 1, 4, 1, 4, 1, 4, 1, 4, 1, 4, 1, 4, 1, 4, 1, 4, 1, 4, 1, 4, 1, 4, 1, 4, 1, 4, 1, 4, 1, 4, 1, 4, 1, 4, 1, 4, 1, 4, 1, 4, 1, 4, 1, 4, 1, 4, 1, 4, 1, 4, 1, 4, 1, 4, 1, 4, 1, 4, 1, 4, 1, 4, 1, 4, 1, 4, 1, 4, 1, 4, 1, 4, 1, 4, 1, 4, 1, 4, 1, 4, 1, 4, 1, 4, 1, 4, 1, 4, 1, 4, 1, 4, 1, 4, 1, 4, 1, 4, 1, 4, 1, 4, 1, 4, 1, 4, 1, 4, 1, 4, 1, 4, 1, 4, 1, 4, 1, 4, 1, 4, 1, 4, 1, 4, 1, 4, 1, 4, 1, 4, 1, 4, 1, 4, 1, 4, 1, 4, 1, 4, 1, 4, 1, 4, 1, 4, 1, 4, 1, 4, 1, 4, 1, 4, 1, 4, 1, 4, 1, 4, 1, 4, 1, 4, 1, 4, 1, 4, 1, 4, 1, 4, 1, 4, 1, 4, 1, 4, 1, 4, 1, 4, 1, 4, 1, 4, 1, 4, 1, 4, 1, 4, 1, 4, 1, 4, 1, 4, 1, 4, 1, 4, 1, 4, 1, 4, 1, 4, 1, 4, 1, 4, 1, 4, 1, 4, 1, 4, 1, 4, 1, 4, 1, 4, 1, 4, 1, 4, 1, 4, 1, 4, 1, 4, 1, 4, 1, 4, 1, 4, 1, 4, 1, 4, 1, 4, 1, 4, 1, 4, 1, 4, 1, 4, 1, 4, 1, 4, 1, 4, 1, 4, 1, 4, 1, 4, 1, 4, 1, 4, 1, 4, 1, 4, 1, 4, 1, 4, 1, 4, 1, 4, 1, 4, 1, 4, 1, 4, 1, 4, 1, 4, 1, 4, 1, 4, 1, 4, 1, 4, 1, 4, 1, 4, 1, 4, 1, 4, 1, 4, 1, 4, 1, 4, 1, 4, 1, 4, 1, 4, 1, 4, 1, 4, 1, 4, 1, 4, 1, 4, 1, 4, 1, 4, 1, 4, 1, 4, 1, 4, 1, 4, 1, 4, 1, 4, 1, 4, 1, 4, 1, 4, 1, 4, 1, 4, 1, 4, 1, 4, 1, 4, 1, 4, 1, 4, 1, 4, 1, 4, 1, 4, 1, 4, 1, 4, 1, 4, 1, 4, 1, 4, 1, 4, 1, 4, 1, 4, 1, 4, 1, 4, 1, 4, 1, 4, 1, 4, 1, 4, 1, 4, 1, 4, 1, 4, 1, 4, 1, 4, 1, 4, 1, 4, 1, 4, 1, 4, 1, 4, 1, 4, 1, 4, 1, 4, 1, 4, 1, 4, 1, 4, 1, 4, 1, 4, 1, 4, 1, 4, 1, 4, 1, 4, 1, 4, 1, 4, 1, 4, 1, 4, 1, 4, 1, 4, 1, 4, 1, 4, 1, 4, 1, 4, 1, 4, 1, 4, 1, 4, 1, 4, 1, 4, 1, 4, 1, 4, 1, 4, 1, 4, 1, 4, 1, 4, 1, 4, 1, 4, 1, 4, 1, 4, 1, 4, 1, 4, 1, 4, 1, 4, 1, 4, 1, 4, 1, 4, 1, 4, 1, 4, 1, 4, 1, 4, 1, 4, 1, 4, 1, 4, 1, 4, 1, 4, 1, 4, 1, 4, 1, 4, 1, 4, 1, 4, 1, 4, 1, 4, 1, 4, 1, 4, 1, 4, 1, 4, 1, 4, 1, 4, 1, 4, 1, 4, 1, 4, 1, 4, 1, 4, 1, 4, 1, 4, 1, 4, 1, 4, 1, 4, 1, 4, 1, 4, 1, 4, 1, 4, 1, 4, 1, 4, 1, 4, 1, 4, 1, 4, 1, 4, 1, 4, 1, 4, 1, 4, 1, 4, 1, 4, 1, 4, 1, 4, 1, 4, 1, 4, 1, 4, 1, 4, 1, 4, 1, 4, 1, 4, 1, 4, 1, 4, 1, 4, 1, 4, 1, 4, 1, 4, 1, 4, 1, 4, 1, 4, 1, 4, 1, 4, 1, 4, 1, 4, 1, 4, 1, 4, 1, 4, 1, 4, 1, 4, 1, 4, 1, 4, 1, 4, 1, 4, 1, 4, 1, 4, 1, 4, 1, 4, 1, 4, 1, 4, 1, 4, 1, 4, 1, 4, 1, 4, 1, 4, 1, 4, 1, 4, 1, 4, 1, 4, 1, 4, 1, 4, 1, 4, 1, 4, 1, 4, 1, 4, 1, 4, 1, 4, 1, 4, 1, 4, 1, 4, 1, 4, 1, 4, 1, 4, 1, 4, 1, 4, 1, 4, 1, 4, 1, 4, 1, 4, 1, 4, 1, 4, 1, 4, 1, 4, 1, 4, 1, 4, 1, 4, 1, 4, 1, 4, 1, 4, 1, 4, 1, 4, 1, 4, 1, 4, 1, 4, 1, 4, 1, 4, 1, 4, 1, 4, 1, 4, 1, 4, 1, 4, 1, 4, 1, 4, 1, 4, 1, 4, 1, 4, 1, 4, 1, 4, 1, 4, 1, 4, 1, 4, 1, 4, 1, 4, 1, 4, 1, 4, 1, 4, 1, 4, 1, 4, 1, 4, 1, 4, 1, 4, 1, 4, 1, 4, 1, 4, 1, 4, 1, 4, 1, 4, 1, 4, 1, 4, 1, 4, 1, 4, 1, 4, 1, 4, 1, 4, 1, 4, 1, 4, 1, 4, 1, 4, 1, 4, 1, 4, 1, 4, 1, 4, 1, 4, 1, 4, 1, 4, 1, 4, 1, 4, 1, 4, 1, 4, 1, 4, 1, 4, 1, 4, 1, 4, 1, 4, 1, 4, 1, 4, 1, 4, 1, 4, 1, 4, 1, 4, 1, 4, 1, 4, 1, 4, 1, 4, 1, 4, 1, 4, 1, 4, 1, 4, 1, 4, 1, 4, 1, 4, 1, 4, 1, 4, 1, 4, 1, 4, 1, 4, 1, 4, 1, 4, 1, 4, 1, 4, 1, 4, 1, 4, 1, 4, 1, 4, 1, 4, 1, 4, 1, 4, 1, 4, 1, 4, 1, 4, 1, 4, 1, 4, 1, 4, 1, 4, 1, 4, 1, 4, 1, 4, 1, 4, 1, 4, 1, 4, 1, 4, 1, 4, 1, 4, 1, 4, 1, 4, 1, 4, 1, 4, 1, 4, 1, 4, 1, 4, 1, 4, 1, 4, 1, 4, 1, 4, 1, 4, 1, 4, 1, 4, 1, 4, 1, 4, 1, 4, 1, 4, 1, 4, 1, 4, 1, 4, 1, 4, 1, 4, 1, 4, 1, 4, 1, 4, 1, 4, 1, 4, 1, 4, 1, 4, 1, 4, 1, 4, 1, 4, 1, 4, 1, 4, 1, 4, 1, 4, 1, 4, 1, 4, 1, 4, 1, 4, 1, 4, 1, 4, 1, 4, 1, 4, 1, 4, 1, 4, 1, 4, 1, 4, 1, 4, 1, 4, 1, 4, 1, 4, 1, 4, 1, 4, 1, 4, 1, 4, 1, 4, 1, 4, 1, 4, 1, 4, 1, 4, 1, 4, 1, 4, 1, 4, 1, 4, 1, 4, 1, 4, 1, 4, 1, 4, 1, 4, 1, 4, 1, 4, 1, 4, 1, 4, 1, 4, 1, 4, 1, 4, 1, 4, 1, 4, 1, 4, 1, 4, 1, 4, 1, 4, 1, 4, 1, 4, 1, 4, 1, 4, 1, 4, 1, 4, 1, 4, 1, 4, 1, 4, 1, 4, 1, 4, 1, 4, 1, 4, 1, 4, 1, 4, 1, 4, 1, 4, 1, 4, 1, 4, 1, 4, 1, 4, 1, 4, 1, 4, 1, 4, 1, 4, 1, 4, 1, 4, 1, 4, 1, 4, 1, 4, 1, 4, 3, 4, 818, 8, 4, 1, 4, 5, 4, 821, 8, 4, 10, 4, 12, 4, 824, 9, 4, 1, 4, 3, 4, 827, 8, 4, 1, 4, 1, 4, 1, 5, 1, 5, 3, 5, 833, 8, 5, 1, 6, 1, 6, 1, 6, 1, 6, 1, 6, 1, 6, 1, 6, 1, 6, 1, 6, 1, 6, 1, 7, 1, 7, 1, 7, 1, 7, 1, 7, 1, 7, 1, 7, 1, 7, 1, 7, 1, 7, 1, 7, 1, 7, 1, 7, 1, 8, 1, 8, 1, 8, 1, 8, 1, 8, 1, 8, 1, 8, 1, 9, 1, 9, 1, 9, 1, 9, 1, 9, 1, 9, 1, 9, 1, 10, 1, 10, 1, 10, 1, 10, 1, 10, 1, 10, 1, 10, 1, 11, 1, 11, 1, 11, 1, 11, 1, 11, 1, 12, 1, 12, 1, 12, 1, 12, 1, 12, 1, 12, 1, 12, 1, 12, 1, 12, 1, 12, 1, 12, 1, 13, 1, 13, 1, 13, 1, 13, 1, 13, 1, 13, 1, 13, 1, 13, 1, 13, 1, 13, 1, 13, 1, 13, 1, 13, 1, 14, 1, 14, 1, 14, 1, 14, 1, 14, 1, 14, 1, 14, 1, 14, 1, 15, 1, 15, 1, 15, 1, 15, 1, 15, 1, 15, 1, 15, 1, 15, 1, 15, 1, 15, 1, 15, 1, 15, 1, 16, 1, 16, 1, 16, 1, 16, 1, 16, 1, 16, 1, 16, 1, 16, 1, 16, 1, 16, 1, 16, 1, 16, 1, 16, 1, 16, 1, 16, 1, 16, 1, 16, 1, 17, 1, 17, 1, 17, 1, 17, 1, 17, 1, 17, 1, 17, 1, 17, 1, 17, 1, 18, 1, 18, 1, 18, 1, 18, 1, 18, 1, 18, 1, 18, 1, 18, 1, 19, 1, 19, 1, 20, 1, 20, 1, 21, 4, 21, 967, 8, 21, 11, 21, 12, 21, 968, 1, 22, 1, 22, 1, 23, 1, 23, 1, 23, 3, 23, 976, 8, 23, 1, 24, 1, 24, 4, 24, 980, 8, 24, 11, 24, 12, 24, 981, 1, 24, 1, 24, 1, 25, 1, 25, 4, 25, 988, 8, 25, 11, 25, 12, 25, 989, 1, 25, 1, 25, 1, 26, 4, 26, 995, 8, 26, 11, 26, 12, 26, 996, 1, 27, 1, 27, 1, 27, 1, 27, 1, 27, 1, 27, 1, 27, 1, 27, 1, 27, 1, 27, 1, 27, 1, 27, 1, 27, 1, 27, 1, 27, 1, 27, 1, 27, 1, 27, 1, 27, 1, 27, 1, 27, 1, 27, 1, 27, 1, 27, 1, 27, 3, 27, 1024, 8, 27, 1, 27, 1, 27, 1, 28, 1, 28, 1, 28, 1, 28, 1, 28, 3, 28, 1033, 8, 28, 1, 28, 1, 28, 0, 0, 29, 2, 1, 4, 2, 6, 3, 8, 4, 10, 5, 12, 6, 14, 0, 16, 0, 18, 7, 20, 8, 22, 9, 24, 10, 26, 11, 28, 12, 30, 13, 32, 14, 34, 15, 36, 16, 38, 17, 40, 18, 42, 19, 44, 20, 46, 0, 48, 21, 50, 0, 52, 0, 54, 0, 56, 22, 58, 23, 2, 0, 1, 4, 2, 0, 9, 9, 32, 32, 1, 0, 10, 10, 3, 0, 48, 57, 65, 70, 97, 102, 2, 0, 9, 10, 32, 32, 1098, 0, 2, 1, 0, 0, 0, 0, 4, 1, 0, 0, 0, 0, 6, 1, 0, 0, 0, 0, 8, 1, 0, 0, 0, 0, 10, 1, 0, 0, 0, 0, 12, 1, 0, 0, 0, 0, 18, 1, 0, 0, 0, 0, 20, 1, 0, 0, 0, 0, 22, 1, 0, 0, 0, 0, 24, 1, 0, 0, 0, 0, 26, 1, 0, 0, 0, 0, 28, 1, 0, 0, 0, 0, 30, 1, 0, 0, 0, 0, 32, 1, 0, 0, 0, 0, 34, 1, 0, 0, 0, 0, 36, 1, 0, 0, 0, 0, 38, 1, 0, 0, 0, 0, 40, 1, 0, 0, 0, 0, 42, 1, 0, 0, 0, 0, 44, 1, 0, 0, 0, 0, 48, 1, 0, 0, 0, 1, 56, 1, 0, 0, 0, 1, 58, 1, 0, 0, 0, 2, 61, 1, 0, 0, 0, 4, 68, 1, 0, 0, 0, 6, 75, 1, 0, 0, 0, 8, 81, 1, 0, 0, 0, 10, 817, 1, 0, 0, 0, 12, 832, 1, 0, 0, 0, 14, 834, 1, 0, 0, 0, 16, 844, 1, 0, 0, 0, 18, 857, 1, 0, 0, 0, 20, 864, 1, 0, 0, 0, 22, 871, 1, 0, 0, 0, 24, 878, 1, 0, 0, 0, 26, 883, 1, 0, 0, 0, 28, 894, 1, 0, 0, 0, 30, 907, 1, 0, 0, 0, 32, 915, 1, 0, 0, 0, 34, 927, 1, 0, 0, 0, 36, 944, 1, 0, 0, 0, 38, 953, 1, 0, 0, 0, 40, 961, 1, 0, 0, 0, 42, 963, 1, 0, 0, 0, 44, 966, 1, 0, 0, 0, 46, 970, 1, 0, 0, 0, 48, 975, 1, 0, 0, 0, 50, 977, 1, 0, 0, 0, 52, 985, 1, 0, 0, 0, 54, 994, 1, 0, 0, 0, 56, 1023, 1, 0, 0, 0, 58, 1032, 1, 0, 0, 0, 60, 62, 7, 0, 0, 0, 61, 60, 1, 0, 0, 0, 62, 63, 1, 0, 0, 0, 63, 61, 1, 0, 0, 0, 63, 64, 1, 0, 0, 0, 64, 65, 1, 0, 0, 0, 65, 66, 6, 0, 0, 0, 66, 3, 1, 0, 0, 0, 67, 69, 5, 13, 0, 0, 68, 67, 1, 0, 0, 0, 68, 69, 1, 0, 0, 0, 69, 70, 1, 0, 0, 0, 70, 71, 5, 10, 0, 0, 71, 72, 1, 0, 0, 0, 72, 73, 6, 1, 0, 0, 73, 5, 1, 0, 0, 0, 74, 76, 3, 2, 0, 0, 75, 74, 1, 0, 0, 0, 75, 76, 1, 0, 0, 0, 76, 77, 1, 0, 0, 0, 77, 78, 3, 4, 1, 0, 78, 79, 1, 0, 0, 0, 79, 80, 6, 2, 0, 0, 80, 7, 1, 0, 0, 0, 81, 85, 5, 35, 0, 0, 82, 84, 8, 1, 0, 0, 83, 82, 1, 0, 0, 0, 84, 87, 1, 0, 0, 0, 85, 83, 1, 0, 0, 0, 85, 86, 1, 0, 0, 0, 86, 89, 1, 0, 0, 0, 87, 85, 1, 0, 0, 0, 88, 90, 3, 4, 1, 0, 89, 88, 1, 0, 0, 0, 89, 90, 1, 0, 0, 0, 90, 91, 1, 0, 0, 0, 91, 92, 6, 3, 0, 0, 92, 9, 1, 0, 0, 0, 93, 94, 5, 97, 0, 0, 94, 95, 5, 108, 0, 0, 95, 96, 5, 115, 0, 0, 96, 97, 5, 111, 0, 0, 97, 98, 5, 95, 0, 0, 98, 99, 5, 115, 0, 0, 99, 100, 5, 99, 0, 0, 100, 101, 5, 97, 0, 0, 101, 102, 5, 110, 0, 0, 102, 103, 5, 95, 0, 0, 103, 104, 5, 100, 0, 0, 104, 105, 5, 105, 0, 0, 105, 106, 5, 114, 0, 0, 106, 818, 5, 115, 0, 0, 107, 108, 5, 97, 0, 0, 108, 109, 5, 108, 0, 0, 109, 110, 5, 115, 0, 0, 110, 111, 5, 111, 0, 0, 111, 112, 5, 95, 0, 0, 112, 113, 5, 115, 0, 0, 113, 114, 5, 99, 0, 0, 114, 115, 5, 97, 0, 0, 115, 116, 5, 110, 0, 0, 116, 117, 5, 95, 0, 0, 117, 118, 5, 116, 0, 0, 118, 119, 5, 111, 0, 0, 119, 120, 5, 111, 0, 0, 120, 121, 5, 108, 0, 0, 121, 818, 5, 115, 0, 0, 122, 123, 5, 98, 0, 0, 123, 124, 5, 97, 0, 0, 124, 125, 5, 110, 0, 0, 125, 126, 5, 110, 0, 0, 126, 127, 5, 101, 0, 0, 127, 818, 5, 114, 0, 0, 128, 129, 5, 98, 0, 0, 129, 130, 5, 97, 0, 0, 130, 131, 5, 110, 0, 0, 131, 132, 5, 110, 0, 0, 132, 133, 5, 101, 0, 0, 133, 134, 5, 114, 0, 0, 134, 135, 5, 95, 0, 0, 135, 136, 5, 115, 0, 0, 136, 137, 5, 99, 0, 0, 137, 138, 5, 97, 0, 0, 138, 139, 5, 108, 0, 0, 139, 818, 5, 101, 0, 0, 140, 141, 5, 98, 0, 0, 141, 142, 5, 105, 0, 0, 142, 143, 5, 103, 0, 0, 143, 144, 5, 95, 0, 0, 144, 145, 5, 105, 0, 0, 145, 146, 5, 99, 0, 0, 146, 147, 5, 111, 0, 0, 147, 148, 5, 110, 0, 0, 148, 149, 5, 95, 0, 0, 149, 150, 5, 115, 0, 0, 150, 151, 5, 105, 0, 0, 151, 152, 5, 122, 0, 0, 152, 818, 5, 101, 0, 0, 153, 154, 5, 99, 0, 0, 154, 155, 5, 115, 0, 0, 155, 156, 5, 114, 0, 0, 156, 157, 5, 95, 0, 0, 157, 158, 5, 118, 0, 0, 158, 159, 5, 97, 0, 0, 159, 160, 5, 108, 0, 0, 160, 161, 5, 117, 0, 0, 161, 162, 5, 101, 0, 0, 162, 818, 5, 115, 0, 0, 163, 164, 5, 100, 0, 0, 164, 165, 5, 101, 0, 0, 165, 166, 5, 102, 0, 0, 166, 167, 5, 97, 0, 0, 167, 168, 5, 117, 0, 0, 168, 169, 5, 108, 0, 0, 169, 170, 5, 116, 0, 0, 170, 171, 5, 95, 0, 0, 171, 172, 5, 115, 0, 0, 172, 173, 5, 101, 0, 0, 173, 174, 5, 108, 0, 0, 174, 175, 5, 101, 0, 0, 175, 176, 5, 99, 0, 0, 176, 177, 5, 116, 0, 0, 177, 178, 5, 105, 0, 0, 178, 179, 5, 111, 0, 0, 179, 818, 5, 110, 0, 0, 180, 181, 5, 100, 0, 0, 181, 182, 5, 111, 0, 0, 182, 183, 5, 110, 0, 0, 183, 184, 5, 39, 0, 0, 184, 185, 5, 116, 0, 0, 185, 186, 5, 95, 0, 0, 186, 187, 5, 115, 0, 0, 187, 188, 5, 99, 0, 0, 188, 189, 5, 97, 0, 0, 189, 190, 5, 110, 0, 0, 190, 191, 5, 95, 0, 0, 191, 192, 5, 100, 0, 0, 192, 193, 5, 105, 0, 0, 193, 194, 5, 114, 0, 0, 194, 818, 5, 115, 0, 0, 195, 196, 5, 100, 0, 0, 196, 197, 5, 111, 0, 0, 197, 198, 5, 110, 0, 0, 198, 199, 5, 39, 0, 0, 199, 200, 5, 116, 0, 0, 200, 201, 5, 95, 0, 0, 201, 202, 5, 115, 0, 0, 202, 203, 5, 99, 0, 0, 203, 204, 5, 97, 0, 0, 204, 205, 5, 110, 0, 0, 205, 206, 5, 95, 0, 0, 206, 207, 5, 102, 0, 0, 207, 208, 5, 105, 0, 0, 208, 209, 5, 108, 0, 0, 209, 210, 5, 101, 0, 0, 210, 818, 5, 115, 0, 0, 211, 212, 5, 100, 0, 0, 212, 213, 5, 111, 0, 0, 213, 214, 5, 110, 0, 0, 214, 215, 5, 39, 0, 0, 215, 216, 5, 116, 0, 0, 216, 217, 5, 95, 0, 0, 217, 218, 5, 115, 0, 0, 218, 219, 5, 99, 0, 0, 219, 220, 5, 97, 0, 0, 220, 221, 5, 110, 0, 0, 221, 222, 5, 95, 0, 0, 222, 223, 5, 102, 0, 0, 223, 224, 5, 105, 0, 0, 224, 225, 5, 114, 0, 0, 225, 226, 5, 109, 0, 0, 226, 227, 5, 119, 0, 0, 227, 228, 5, 97, 0, 0, 228, 229, 5, 114, 0, 0, 229, 818, 5, 101, 0, 0, 230, 231, 5, 100, 0, 0, 231, 232, 5, 111, 0, 0, 232, 233, 5, 110, 0, 0, 233, 234, 5, 39, 0, 0, 234, 235, 5, 116, 0, 0, 235, 236, 5, 95, 0, 0, 236, 237, 5, 115, 0, 0, 237, 238, 5, 99, 0, 0, 238, 239, 5, 97, 0, 0, 239, 240, 5, 110, 0, 0, 240, 241, 5, 95, 0, 0, 241, 242, 5, 116, 0, 0, 242, 243, 5, 111, 0, 0, 243, 244, 5, 111, 0, 0, 244, 245, 5, 108, 0, 0, 245, 818, 5, 115, 0, 0, 246, 247, 5, 100, 0, 0, 247, 248, 5, 111, 0, 0, 248, 249, 5, 110, 0, 0, 249, 250, 5, 39, 0, 0, 250, 251, 5, 116, 0, 0, 251, 252, 5, 95, 0, 0, 252, 253, 5, 115, 0, 0, 253, 254, 5, 99, 0, 0, 254, 255, 5, 97, 0, 0, 255, 256, 5, 110, 0, 0, 256, 257, 5, 95, 0, 0, 257, 258, 5, 118, 0, 0, 258, 259, 5, 111, 0, 0, 259, 260, 5, 108, 0, 0, 260, 261, 5, 117, 0, 0, 261, 262, 5, 109, 0, 0, 262, 263, 5, 101, 0, 0, 263, 818, 5, 115, 0, 0, 264, 265, 5, 100, 0, 0, 265, 266, 5, 111, 0, 0, 266, 267, 5, 110, 0, 0, 267, 268, 5, 116, 0, 0, 268, 269, 5, 95, 0, 0, 269, 270, 5, 115, 0, 0, 270, 271, 5, 99, 0, 0, 271, 272, 5, 97, 0, 0, 272, 273, 5, 110, 0, 0, 273, 274, 5, 95, 0, 0, 274, 275, 5, 100, 0, 0, 275, 276, 5, 105, 0, 0, 276, 277, 5, 114, 0, 0, 277, 818, 5, 115, 0, 0, 278, 279, 5, 100, 0, 0, 279, 280, 5, 111, 0, 0, 280, 281, 5, 110, 0, 0, 281, 282, 5, 116, 0, 0, 282, 283, 5, 95, 0, 0, 283, 284, 5, 115, 0, 0, 284, 285, 5, 99, 0, 0, 285, 286, 5, 97, 0, 0, 286, 287, 5, 110, 0, 0, 287, 288, 5, 95, 0, 0, 288, 289, 5, 102, 0, 0, 289, 290, 5, 105, 0, 0, 290, 291, 5, 108, 0, 0, 291, 292, 5, 101, 0, 0, 292, 818, 5, 115, 0, 0, 293, 294, 5, 100, 0, 0, 294, 295, 5, 111, 0, 0, 295, 296, 5, 110, 0, 0, 296, 297, 5, 116, 0, 0, 297, 298, 5, 95, 0, 0, 298, 299, 5, 115, 0, 0, 299, 300, 5, 99, 0, 0, 300, 301, 5, 97, 0, 0, 301, 302, 5, 110, 0, 0, 302, 303, 5, 95, 0, 0, 303, 304, 5, 102, 0, 0, 304, 305, 5, 105, 0, 0, 305, 306, 5, 114, 0, 0, 306, 307, 5, 109, 0, 0, 307, 308, 5, 119, 0, 0, 308, 309, 5, 97, 0, 0, 309, 310, 5, 114, 0, 0, 310, 818, 5, 101, 0, 0, 311, 312, 5, 100, 0, 0, 312, 313, 5, 111, 0, 0, 313, 314, 5, 110, 0, 0, 314, 315, 5, 116, 0, 0, 315, 316, 5, 95, 0, 0, 316, 317, 5, 115, 0, 0, 317, 318, 5, 99, 0, 0, 318, 319, 5, 97, 0, 0, 319, 320, 5, 110, 0, 0, 320, 321, 5, 95, 0, 0, 321, 322, 5, 116, 0, 0, 322, 323, 5, 111, 0, 0, 323, 324, 5, 111, 0, 0, 324, 325, 5, 108, 0, 0, 325, 818, 5, 115, 0, 0, 326, 327, 5, 100, 0, 0, 327, 328, 5, 111, 0, 0, 328, 329, 5, 110, 0, 0, 329, 330, 5, 116, 0, 0, 330, 331, 5, 95, 0, 0, 331, 332, 5, 115, 0, 0, 332, 333, 5, 99, 0, 0, 333, 334, 5, 97, 0, 0, 334, 335, 5, 110, 0, 0, 335, 336, 5, 95, 0, 0, 336, 337, 5, 118, 0, 0, 337, 338, 5, 111, 0, 0, 338, 339, 5, 108, 0, 0, 339, 340, 5, 117, 0, 0, 340, 341, 5, 109, 0, 0, 341, 342, 5, 101, 0, 0, 342, 818, 5, 115, 0, 0, 343, 344, 5, 101, 0, 0, 344, 345, 5, 110, 0, 0, 345, 346, 5, 97, 0, 0, 346, 347, 5, 98, 0, 0, 347, 348, 5, 108, 0, 0, 348, 349, 5, 101, 0, 0, 349, 350, 5, 95, 0, 0, 350, 351, 5, 97, 0, 0, 351, 352, 5, 110, 0, 0, 352, 353, 5, 100, 0, 0, 353, 354, 5, 95, 0, 0, 354, 355, 5, 108, 0, 0, 355, 356, 5, 111, 0, 0, 356, 357, 5, 99, 0, 0, 357, 358, 5, 107, 0, 0, 358, 359, 5, 95, 0, 0, 359, 360, 5, 118, 0, 0, 360, 361, 5, 109, 0, 0, 361, 818, 5, 120, 0, 0, 362, 363, 5, 101, 0, 0, 363, 364, 5, 110, 0, 0, 364, 365, 5, 97, 0, 0, 365, 366, 5, 98, 0, 0, 366, 367, 5, 108, 0, 0, 367, 368, 5, 101, 0, 0, 368, 369, 5, 95, 0, 0, 369, 370, 5, 109, 0, 0, 370, 371, 5, 111, 0, 0, 371, 372, 5, 117, 0, 0, 372, 373, 5, 115, 0, 0, 373, 818, 5, 101, 0, 0, 374, 375, 5, 101, 0, 0, 375, 376, 5, 110, 0, 0, 376, 377, 5, 97, 0, 0, 377, 378, 5, 98, 0, 0, 378, 379, 5, 108, 0, 0, 379, 380, 5, 101, 0, 0, 380, 381, 5, 95, 0, 0, 381, 382, 5, 116, 0, 0, 382, 383, 5, 111, 0, 0, 383, 384, 5, 117, 0, 0, 384, 385, 5, 99, 0, 0, 385, 818, 5, 104, 0, 0, 386, 387, 5, 101, 0, 0, 387, 388, 5, 120, 0, 0, 388, 389, 5, 116, 0, 0, 389, 390, 5, 114, 0, 0, 390, 391, 5, 97, 0, 0, 391, 392, 5, 95, 0, 0, 392, 393, 5, 107, 0, 0, 393, 394, 5, 101, 0, 0, 394, 395, 5, 114, 0, 0, 395, 396, 5, 110, 0, 0, 396, 397, 5, 101, 0, 0, 397, 398, 5, 108, 0, 0, 398, 399, 5, 95, 0, 0, 399, 400, 5, 118, 0, 0, 400, 401, 5, 101, 0, 0, 401, 402, 5, 114, 0, 0, 402, 403, 5, 115, 0, 0, 403, 404, 5, 105, 0, 0, 404, 405, 5, 111, 0, 0, 405, 406, 5, 110, 0, 0, 406, 407, 5, 95, 0, 0, 407, 408, 5, 115, 0, 0, 408, 409, 5, 116, 0, 0, 409, 410, 5, 114, 0, 0, 410, 411, 5, 105, 0, 0, 411, 412, 5, 110, 0, 0, 412, 413, 5, 103, 0, 0, 413, 818, 5, 115, 0, 0, 414, 415, 5, 102, 0, 0, 415, 416, 5, 111, 0, 0, 416, 417, 5, 108, 0, 0, 417, 418, 5, 100, 0, 0, 418, 419, 5, 95, 0, 0, 419, 420, 5, 108, 0, 0, 420, 421, 5, 105, 0, 0, 421, 422, 5, 110, 0, 0, 422, 423, 5, 117, 0, 0, 423, 424, 5, 120, 0, 0, 424, 425, 5, 95, 0, 0, 425, 426, 5, 107, 0, 0, 426, 427, 5, 101, 0, 0, 427, 428, 5, 114, 0, 0, 428, 429, 5, 110, 0, 0, 429, 430, 5, 101, 0, 0, 430, 431, 5, 108, 0, 0, 431, 818, 5, 115, 0, 0, 432, 433, 5, 102, 0, 0, 433, 434, 5, 111, 0, 0, 434, 435, 5, 108, 0, 0, 435, 436, 5, 108, 0, 0, 436, 437, 5, 111, 0, 0, 437, 438, 5, 119, 0, 0, 438, 439, 5, 95, 0, 0, 439, 440, 5, 115, 0, 0, 440, 441, 5, 121, 0, 0, 441, 442, 5, 109, 0, 0, 442, 443, 5, 108, 0, 0, 443, 444, 5, 105, 0, 0, 444, 445, 5, 110, 0, 0, 445, 446, 5, 107, 0, 0, 446, 818, 5, 115, 0, 0, 447, 448, 5, 102, 0, 0, 448, 449, 5, 111, 0, 0, 449, 450, 5, 110, 0, 0, 450, 818, 5, 116, 0, 0, 451, 452, 5, 104, 0, 0, 452, 453, 5, 105, 0, 0, 453, 454, 5, 100, 0, 0, 454, 455, 5, 101, 0, 0, 455, 456, 5, 117, 0, 0, 456, 818, 5, 105, 0, 0, 457, 458, 5, 105, 0, 0, 458, 459, 5, 99, 0, 0, 459, 460, 5, 111, 0, 0, 460, 461, 5, 110, 0, 0, 461, 462, 5, 115, 0, 0, 462, 463, 5, 95, 0, 0, 463, 464, 5, 100, 0, 0, 464, 465, 5, 105, 0, 0, 465, 818, 5, 114, 0, 0, 466, 467, 5, 108, 0, 0, 467, 468, 5, 105, 0, 0, 468, 469, 5, 110, 0, 0, 469, 470, 5, 117, 0, 0, 470, 471, 5, 120, 0, 0, 471, 472, 5, 95, 0, 0, 472, 473, 5, 112, 0, 0, 473, 474, 5, 114, 0, 0, 474, 475, 5, 101, 0, 0, 475, 476, 5, 102, 0, 0, 476, 477, 5, 105, 0, 0, 477, 478, 5, 120, 0, 0, 478, 479, 5, 101, 0, 0, 479, 818, 5, 115, 0, 0, 480, 481, 5, 108, 0, 0, 481, 482, 5, 111, 0, 0, 482, 483, 5, 103, 0, 0, 483, 484, 5, 95, 0, 0, 484, 485, 5, 108, 0, 0, 485, 486, 5, 101, 0, 0, 486, 487, 5, 118, 0, 0, 487, 488, 5, 101, 0, 0, 488, 818, 5, 108, 0, 0, 489, 490, 5, 109, 0, 0, 490, 491, 5, 97, 0, 0, 491, 492, 5, 120, 0, 0, 492, 493, 5, 95, 0, 0, 493, 494, 5, 116, 0, 0, 494, 495, 5, 97, 0, 0, 495, 496, 5, 103, 0, 0, 496, 818, 5, 115, 0, 0, 497, 498, 5, 109, 0, 0, 498, 499, 5, 111, 0, 0, 499, 500, 5, 117, 0, 0, 500, 501, 5, 115, 0, 0, 501, 502, 5, 101, 0, 0, 502, 503, 5, 95, 0, 0, 503, 504, 5, 115, 0, 0, 504, 505, 5, 105, 0, 0, 505, 506, 5, 122, 0, 0, 506, 818, 5, 101, 0, 0, 507, 508, 5, 109, 0, 0, 508, 509, 5, 111, 0, 0, 509, 510, 5, 117, 0, 0, 510, 511, 5, 115, 0, 0, 511, 512, 5, 101, 0, 0, 512, 513, 5, 95, 0, 0, 513, 514, 5, 115, 0, 0, 514, 515, 5, 112, 0, 0, 515, 516, 5, 101, 0, 0, 516, 517, 5, 101, 0, 0, 517, 818, 5, 100, 0, 0, 518, 519, 5, 114, 0, 0, 519, 520, 5, 101, 0, 0, 520, 521, 5, 115, 0, 0, 521, 522, 5, 111, 0, 0, 522, 523, 5, 108, 0, 0, 523, 524, 5, 117, 0, 0, 524, 525, 5, 116, 0, 0, 525, 526, 5, 105, 0, 0, 526, 527, 5, 111, 0, 0, 527, 818, 5, 110, 0, 0, 528, 529, 5, 115, 0, 0, 529, 530, 5, 99, 0, 0, 530, 531, 5, 97, 0, 0, 531, 532, 5, 110, 0, 0, 532, 533, 5, 95, 0, 0, 533, 534, 5, 97, 0, 0, 534, 535, 5, 108, 0, 0, 535, 536, 5, 108, 0, 0, 536, 537, 5, 95, 0, 0, 537, 538, 5, 108, 0, 0, 538, 539, 5, 105, 0, 0, 539, 540, 5, 110, 0, 0, 540, 541, 5, 117, 0, 0, 541, 542, 5, 120, 0, 0, 542, 543, 5, 95, 0, 0, 543, 544, 5, 107, 0, 0, 544, 545, 5, 101, 0, 0, 545, 546, 5, 114, 0, 0, 546, 547, 5, 110, 0, 0, 547, 548, 5, 101, 0, 0, 548, 549, 5, 108, 0, 0, 549, 818, 5, 115, 0, 0, 550, 551, 5, 115, 0, 0, 551, 552, 5, 99, 0, 0, 552, 553, 5, 97, 0, 0, 553, 554, 5, 110, 0, 0, 554, 555, 5, 95, 0, 0, 555, 556, 5, 100, 0, 0, 556, 557, 5, 101, 0, 0, 557, 558, 5, 108, 0, 0, 558, 559, 5, 97, 0, 0, 559, 818, 5, 121, 0, 0, 560, 561, 5, 115, 0, 0, 561, 562, 5, 99, 0, 0, 562, 563, 5, 97, 0, 0, 563, 564, 5, 110, 0, 0, 564, 565, 5, 95, 0, 0, 565, 566, 5, 100, 0, 0, 566, 567, 5, 114, 0, 0, 567, 568, 5, 105, 0, 0, 568, 569, 5, 118, 0, 0, 569, 570, 5, 101, 0, 0, 570, 571, 5, 114, 0, 0, 571, 572, 5, 95, 0, 0, 572, 573, 5, 100, 0, 0, 573, 574, 5, 105, 0, 0, 574, 575, 5, 114, 0, 0, 575, 818, 5, 115, 0, 0, 576, 577, 5, 115, 0, 0, 577, 578, 5, 99, 0, 0, 578, 579, 5, 97, 0, 0, 579, 580, 5, 110, 0, 0, 580, 581, 5, 102, 0, 0, 581, 582, 5, 111, 0, 0, 582, 818, 5, 114, 0, 0, 583, 584, 5, 115, 0, 0, 584, 585, 5, 99, 0, 0, 585, 586, 5, 114, 0, 0, 586, 587, 5, 101, 0, 0, 587, 588, 5, 101, 0, 0, 588, 589, 5, 110, 0, 0, 589, 590, 5, 115, 0, 0, 590, 591, 5, 97, 0, 0, 591, 592, 5, 118, 0, 0, 592, 593, 5, 101, 0, 0, 593, 818, 5, 114, 0, 0, 594, 595, 5, 115, 0, 0, 595, 596, 5, 101, 0, 0, 596, 597, 5, 108, 0, 0, 597, 598, 5, 101, 0, 0, 598, 599, 5, 99, 0, 0, 599, 600, 5, 116, 0, 0, 600, 601, 5, 105, 0, 0, 601, 602, 5, 111, 0, 0, 602, 603, 5, 110, 0, 0, 603, 604, 5, 95, 0, 0, 604, 605, 5, 98, 0, 0, 605, 606, 5, 105, 0, 0, 606, 818, 5, 103, 0, 0, 607, 608, 5, 115, 0, 0, 608, 609, 5, 101, 0, 0, 609, 610, 5, 108, 0, 0, 610, 611, 5, 101, 0, 0, 611, 612, 5, 99, 0, 0, 612, 613, 5, 116, 0, 0, 613, 614, 5, 105, 0, 0, 614, 615, 5, 111, 0, 0, 615, 616, 5, 110, 0, 0, 616, 617, 5, 95, 0, 0, 617, 618, 5, 115, 0, 0, 618, 619, 5, 109, 0, 0, 619, 620, 5, 97, 0, 0, 620, 621, 5, 108, 0, 0, 621, 818, 5, 108, 0, 0, 622, 623, 5, 115, 0, 0, 623, 624, 5, 104, 0, 0, 624, 625, 5, 111, 0, 0, 625, 626, 5, 119, 0, 0, 626, 627, 5, 116, 0, 0, 627, 628, 5, 111, 0, 0, 628, 629, 5, 111, 0, 0, 629, 630, 5, 108, 0, 0, 630, 818, 5, 115, 0, 0, 631, 632, 5, 115, 0, 0, 632, 633, 5, 104, 0, 0, 633, 634, 5, 117, 0, 0, 634, 635, 5, 116, 0, 0, 635, 636, 5, 100, 0, 0, 636, 637, 5, 111, 0, 0, 637, 638, 5, 119, 0, 0, 638, 639, 5, 110, 0, 0, 639, 640, 5, 95, 0, 0, 640, 641, 5, 97, 0, 0, 641, 642, 5, 102, 0, 0, 642, 643, 5, 116, 0, 0, 643, 644, 5, 101, 0, 0, 644, 645, 5, 114, 0, 0, 645, 646, 5, 95, 0, 0, 646, 647, 5, 116, 0, 0, 647, 648, 5, 105, 0, 0, 648, 649, 5, 109, 0, 0, 649, 650, 5, 101, 0, 0, 650, 651, 5, 111, 0, 0, 651, 652, 5, 117, 0, 0, 652, 818, 5, 116, 0, 0, 653, 654, 5, 115, 0, 0, 654, 655, 5, 109, 0, 0, 655, 656, 5, 97, 0, 0, 656, 657, 5, 108, 0, 0, 657, 658, 5, 108, 0, 0, 658, 659, 5, 95, 0, 0, 659, 660, 5, 105, 0, 0, 660, 661, 5, 99, 0, 0, 661, 662, 5, 111, 0, 0, 662, 663, 5, 110, 0, 0, 663, 664, 5, 95, 0, 0, 664, 665, 5, 115, 0, 0, 665, 666, 5, 105, 0, 0, 666, 667, 5, 122, 0, 0, 667, 818, 5, 101, 0, 0, 668, 669, 5, 115, 0, 0, 669, 670, 5, 112, 0, 0, 670, 671, 5, 111, 0, 0, 671, 672, 5, 111, 0, 0, 672, 673, 5, 102, 0, 0, 673, 674, 5, 95, 0, 0, 674, 675, 5, 111, 0, 0, 675, 676, 5, 115, 0, 0, 676, 677, 5, 120, 0, 0, 677, 678, 5, 95, 0, 0, 678, 679, 5, 118, 0, 0, 679, 680, 5, 101, 0, 0, 680, 681, 5, 114, 0, 0, 681, 682, 5, 115, 0, 0, 682, 683, 5, 105, 0, 0, 683, 684, 5, 111, 0, 0, 684, 818, 5, 110, 0, 0, 685, 686, 5, 115, 0, 0, 686, 687, 5, 117, 0, 0, 687, 688, 5, 112, 0, 0, 688, 689, 5, 112, 0, 0, 689, 690, 5, 111, 0, 0, 690, 691, 5, 114, 0, 0, 691, 692, 5, 116, 0, 0, 692, 693, 5, 95, 0, 0, 693, 694, 5, 103, 0, 0, 694, 695, 5, 122, 0, 0, 695, 696, 5, 105, 0, 0, 696, 697, 5, 112, 0, 0, 697, 698, 5, 112, 0, 0, 698, 699, 5, 101, 0, 0, 699, 700, 5, 100, 0, 0, 700, 701, 5, 95, 0, 0, 701, 702, 5, 108, 0, 0, 702, 703, 5, 111, 0, 0, 703, 704, 5, 97, 0, 0, 704, 705, 5, 100, 0, 0, 705, 706, 5, 101, 0, 0, 706, 707, 5, 114, 0, 0, 707, 818, 5, 115, 0, 0, 708, 709, 5, 116, 0, 0, 709, 710, 5, 101, 0, 0, 710, 711, 5, 120, 0, 0, 711, 712, 5, 116, 0, 0, 712, 713, 5, 109, 0, 0, 713, 714, 5, 111, 0, 0, 714, 715, 5, 100, 0, 0, 715, 818, 5, 101, 0, 0, 716, 717, 5, 116, 0, 0, 717, 718, 5, 101, 0, 0, 718, 719, 5, 120, 0, 0, 719, 720, 5, 116, 0, 0, 720, 721, 5, 111, 0, 0, 721, 722, 5, 110, 0, 0, 722, 723, 5, 108, 0, 0, 723, 818, 5, 121, 0, 0, 724, 725, 5, 116, 0, 0, 725, 726, 5, 105, 0, 0, 726, 727, 5, 109, 0, 0, 727, 728, 5, 101, 0, 0, 728, 729, 5, 111, 0, 0, 729, 730, 5, 117, 0, 0, 730, 818, 5, 116, 0, 0, 731, 732, 5, 117, 0, 0, 732, 733, 5, 101, 0, 0, 733, 734, 5, 102, 0, 0, 734, 735, 5, 105, 0, 0, 735, 736, 5, 95, 0, 0, 736, 737, 5, 100, 0, 0, 737, 738, 5, 101, 0, 0, 738, 739, 5, 101, 0, 0, 739, 740, 5, 112, 0, 0, 740, 741, 5, 95, 0, 0, 741, 742, 5, 108, 0, 0, 742, 743, 5, 101, 0, 0, 743, 744, 5, 103, 0, 0, 744, 745, 5, 97, 0, 0, 745, 746, 5, 99, 0, 0, 746, 747, 5, 121, 0, 0, 747, 748, 5, 95, 0, 0, 748, 749, 5, 115, 0, 0, 749, 750, 5, 99, 0, 0, 750, 751, 5, 97, 0, 0, 751, 818, 5, 110, 0, 0, 752, 753, 5, 117, 0, 0, 753, 754, 5, 115, 0, 0, 754, 755, 5, 101, 0, 0, 755, 756, 5, 95, 0, 0, 756, 757, 5, 103, 0, 0, 757, 758, 5, 114, 0, 0, 758, 759, 5, 97, 0, 0, 759, 760, 5, 112, 0, 0, 760, 761, 5, 104, 0, 0, 761, 762, 5, 105, 0, 0, 762, 763, 5, 99, 0, 0, 763, 764, 5, 115, 0, 0, 764, 765, 5, 95, 0, 0, 765, 766, 5, 102, 0, 0, 766, 767, 5, 111, 0, 0, 767, 818, 5, 114, 0, 0, 768, 769, 5, 117, 0, 0, 769, 770, 5, 115, 0, 0, 770, 771, 5, 101, 0, 0, 771, 772, 5, 95, 0, 0, 772, 773, 5, 110, 0, 0, 773, 774, 5, 118, 0, 0, 774, 775, 5, 114, 0, 0, 775, 776, 5, 97, 0, 0, 776, 818, 5, 109, 0, 0, 777, 778, 5, 119, 0, 0, 778, 779, 5, 105, 0, 0, 779, 780, 5, 110, 0, 0, 780, 781, 5, 100, 0, 0, 781, 782, 5, 111, 0, 0, 782, 783, 5, 119, 0, 0, 783, 784, 5, 115, 0, 0, 784, 785, 5, 95, 0, 0, 785, 786, 5, 114, 0, 0, 786, 787, 5, 101, 0, 0, 787, 788, 5, 99, 0, 0, 788, 789, 5, 111, 0, 0, 789, 790, 5, 118, 0, 0, 790, 791, 5, 101, 0, 0, 791, 792, 5, 114, 0, 0, 792, 793, 5, 121, 0, 0, 793, 794, 5, 95, 0, 0, 794, 795, 5, 102, 0, 0, 795, 796, 5, 105, 0, 0, 796, 797, 5, 108, 0, 0, 797, 798, 5, 101, 0, 0, 798, 818, 5, 115, 0, 0, 799, 800, 5, 119, 0, 0, 800, 801, 5, 114, 0, 0, 801, 802, 5, 105, 0, 0, 802, 803, 5, 116, 0, 0, 803, 804, 5, 101, 0, 0, 804, 805, 5, 95, 0, 0, 805, 806, 5, 115, 0, 0, 806, 807, 5, 121, 0, 0, 807, 808, 5, 115, 0, 0, 808, 809, 5, 116, 0, 0, 809, 810, 5, 101, 0, 0, 810, 811, 5, 109, 0, 0, 811, 812, 5, 100, 0, 0, 812, 813, 5, 95, 0, 0, 813, 814, 5, 118, 0, 0, 814, 815, 5, 97, 0, 0, 815, 816, 5, 114, 0, 0, 816, 818, 5, 115, 0, 0, 817, 93, 1, 0, 0, 0, 817, 107, 1, 0, 0, 0, 817, 122, 1, 0, 0, 0, 817, 128, 1, 0, 0, 0, 817, 140, 1, 0, 0, 0, 817, 153, 1, 0, 0, 0, 817, 163, 1, 0, 0, 0, 817, 180, 1, 0, 0, 0, 817, 195, 1, 0, 0, 0, 817, 211, 1, 0, 0, 0, 817, 230, 1, 0, 0, 0, 817, 246, 1, 0, 0, 0, 817, 264, 1, 0, 0, 0, 817, 278, 1, 0, 0, 0, 817, 293, 1, 0, 0, 0, 817, 311, 1, 0, 0, 0, 817, 326, 1, 0, 0, 0, 817, 343, 1, 0, 0, 0, 817, 362, 1, 0, 0, 0, 817, 374, 1, 0, 0, 0, 817, 386, 1, 0, 0, 0, 817, 414, 1, 0, 0, 0, 817, 432, 1, 0, 0, 0, 817, 447, 1, 0, 0, 0, 817, 451, 1, 0, 0, 0, 817, 457, 1, 0, 0, 0, 817, 466, 1, 0, 0, 0, 817, 480, 1, 0, 0, 0, 817, 489, 1, 0, 0, 0, 817, 497, 1, 0, 0, 0, 817, 507, 1, 0, 0, 0, 817, 518, 1, 0, 0, 0, 817, 528, 1, 0, 0, 0, 817, 550, 1, 0, 0, 0, 817, 560, 1, 0, 0, 0, 817, 576, 1, 0, 0, 0, 817, 583, 1, 0, 0, 0, 817, 594, 1, 0, 0, 0, 817, 607, 1, 0, 0, 0, 817, 622, 1, 0, 0, 0, 817, 631, 1, 0, 0, 0, 817, 653, 1, 0, 0, 0, 817, 668, 1, 0, 0, 0, 817, 685, 1, 0, 0, 0, 817, 708, 1, 0, 0, 0, 817, 716, 1, 0, 0, 0, 817, 724, 1, 0, 0, 0, 817, 731, 1, 0, 0, 0, 817, 752, 1, 0, 0, 0, 817, 768, 1, 0, 0, 0, 817, 777, 1, 0, 0, 0, 817, 799, 1, 0, 0, 0, 818, 822, 1, 0, 0, 0, 819, 821, 8, 1, 0, 0, 820, 819, 1, 0, 0, 0, 821, 824, 1, 0, 0, 0, 822, 820, 1, 0, 0, 0, 822, 823, 1, 0, 0, 0, 823, 826, 1, 0, 0, 0, 824, 822, 1, 0, 0, 0, 825, 827, 3, 4, 1, 0, 826, 825, 1, 0, 0, 0, 826, 827, 1, 0, 0, 0, 827, 828, 1, 0, 0, 0, 828, 829, 6, 4, 0, 0, 829, 11, 1, 0, 0, 0, 830, 833, 3, 14, 6, 0, 831, 833, 3, 16, 7, 0, 832, 830, 1, 0, 0, 0, 832, 831, 1, 0, 0, 0, 833, 13, 1, 0, 0, 0, 834, 835, 5, 109, 0, 0, 835, 836, 5, 101, 0, 0, 836, 837, 5, 110, 0, 0, 837, 838, 5, 117, 0, 0, 838, 839, 5, 101, 0, 0, 839, 840, 5, 110, 0, 0, 840, 841, 5, 116, 0, 0, 841, 842, 5, 114, 0, 0, 842, 843, 5, 121, 0, 0, 843, 15, 1, 0, 0, 0, 844, 845, 5, 115, 0, 0, 845, 846, 5, 117, 0, 0, 846, 847, 5, 98, 0, 0, 847, 848, 5, 109, 0, 0, 848, 849, 5, 101, 0, 0, 849, 850, 5, 110, 0, 0, 850, 851, 5, 117, 0, 0, 851, 852, 5, 101, 0, 0, 852, 853, 5, 110, 0, 0, 853, 854, 5, 116, 0, 0, 854, 855, 5, 114, 0, 0, 855, 856, 5, 121, 0, 0, 856, 17, 1, 0, 0, 0, 857, 858, 5, 118, 0, 0, 858, 859, 5, 111, 0, 0, 859, 860, 5, 108, 0, 0, 860, 861, 5, 117, 0, 0, 861, 862, 5, 109, 0, 0, 862, 863, 5, 101, 0, 0, 863, 19, 1, 0, 0, 0, 864, 865, 5, 108, 0, 0, 865, 866, 5, 111, 0, 0, 866, 867, 5, 97, 0, 0, 867, 868, 5, 100, 0, 0, 868, 869, 5, 101, 0, 0, 869, 870, 5, 114, 0, 0, 870, 21, 1, 0, 0, 0, 871, 872, 5, 105, 0, 0, 872, 873, 5, 110, 0, 0, 873, 874, 5, 105, 0, 0, 874, 875, 5, 116, 0, 0, 875, 876, 5, 114, 0, 0, 876, 877, 5, 100, 0, 0, 877, 23, 1, 0, 0, 0, 878, 879, 5, 105, 0, 0, 879, 880, 5, 99, 0, 0, 880, 881, 5, 111, 0, 0, 881, 882, 5, 110, 0, 0, 882, 25, 1, 0, 0, 0, 883, 884, 5, 111, 0, 0, 884, 885, 5, 115, 0, 0, 885, 886, 5, 116, 0, 0, 886, 887, 5, 121, 0, 0, 887, 888, 5, 112, 0, 0, 888, 889, 5, 101, 0, 0, 889, 890, 1, 0, 0, 0, 890, 891, 3, 2, 0, 0, 891, 892, 1, 0, 0, 0, 892, 893, 6, 12, 1, 0, 893, 27, 1, 0, 0, 0, 894, 895, 5, 103, 0, 0, 895, 896, 5, 114, 0, 0, 896, 897, 5, 97, 0, 0, 897, 898, 5, 112, 0, 0, 898, 899, 5, 104, 0, 0, 899, 900, 5, 105, 0, 0, 900, 901, 5, 99, 0, 0, 901, 902, 5, 115, 0, 0, 902, 903, 1, 0, 0, 0, 903, 904, 3, 2, 0, 0, 904, 905, 1, 0, 0, 0, 905, 906, 6, 13, 1, 0, 906, 29, 1, 0, 0, 0, 907, 908, 5, 111, 0, 0, 908, 909, 5, 112, 0, 0, 909, 910, 5, 116, 0, 0, 910, 911, 5, 105, 0, 0, 911, 912, 5, 111, 0, 0, 912, 913, 5, 110, 0, 0, 913, 914, 5, 115, 0, 0, 914, 31, 1, 0, 0, 0, 915, 916, 5, 97, 0, 0, 916, 917, 5, 100, 0, 0, 917, 918, 5, 100, 0, 0, 918, 919, 5, 95, 0, 0, 919, 920, 5, 111, 0, 0, 920, 921, 5, 112, 0, 0, 921, 922, 5, 116, 0, 0, 922, 923, 5, 105, 0, 0, 923, 924, 5, 111, 0, 0, 924, 925, 5, 110, 0, 0, 925, 926, 5, 115, 0, 0, 926, 33, 1, 0, 0, 0, 927, 928, 5, 102, 0, 0, 928, 929, 5, 105, 0, 0, 929, 930, 5, 114, 0, 0, 930, 931, 5, 109, 0, 0, 931, 932, 5, 119, 0, 0, 932, 933, 5, 97, 0, 0, 933, 934, 5, 114, 0, 0, 934, 935, 5, 101, 0, 0, 935, 936, 5, 95, 0, 0, 936, 937, 5, 98, 0, 0, 937, 938, 5, 111, 0, 0, 938, 939, 5, 111, 0, 0, 939, 940, 5, 116, 0, 0, 940, 941, 5, 110, 0, 0, 941, 942, 5, 117, 0, 0, 942, 943, 5, 109, 0, 0, 943, 35, 1, 0, 0, 0, 944, 945, 5, 100, 0, 0, 945, 946, 5, 105, 0, 0, 946, 947, 5, 115, 0, 0, 947, 948, 5, 97, 0, 0, 948, 949, 5, 98, 0, 0, 949, 950, 5, 108, 0, 0, 950, 951, 5, 101, 0, 0, 951, 952, 5, 100, 0, 0, 952, 37, 1, 0, 0, 0, 953, 954, 5, 105, 0, 0, 954, 955, 5, 110, 0, 0, 955, 956, 5, 99, 0, 0, 956, 957, 5, 108, 0, 0, 957, 958, 5, 117, 0, 0, 958, 959, 5, 100, 0, 0, 959, 960, 5, 101, 0, 0, 960, 39, 1, 0, 0, 0, 961, 962, 5, 123, 0, 0, 962, 41, 1, 0, 0, 0, 963, 964, 5, 125, 0, 0, 964, 43, 1, 0, 0, 0, 965, 967, 3, 46, 22, 0, 966, 965, 1, 0, 0, 0, 967, 968, 1, 0, 0, 0, 968, 966, 1, 0, 0, 0, 968, 969, 1, 0, 0, 0, 969, 45, 1, 0, 0, 0, 970, 971, 7, 2, 0, 0, 971, 47, 1, 0, 0, 0, 972, 976, 3, 50, 24, 0, 973, 976, 3, 52, 25, 0, 974, 976, 3, 54, 26, 0, 975, 972, 1, 0, 0, 0, 975, 973, 1, 0, 0, 0, 975, 974, 1, 0, 0, 0, 976, 49, 1, 0, 0, 0, 977, 979, 5, 39, 0, 0, 978, 980, 8, 1, 0, 0, 979, 978, 1, 0, 0, 0, 980, 981, 1, 0, 0, 0, 981, 979, 1, 0, 0, 0, 981, 982, 1, 0, 0, 0, 982, 983, 1, 0, 0, 0, 983, 984, 5, 39, 0, 0, 984, 51, 1, 0, 0, 0, 985, 987, 5, 34, 0, 0, 986, 988, 8, 1, 0, 0, 987, 986, 1, 0, 0, 0, 988, 989, 1, 0, 0, 0, 989, 987, 1, 0, 0, 0, 989, 990, 1, 0, 0, 0, 990, 991, 1, 0, 0, 0, 991, 992, 5, 34, 0, 0, 992, 53, 1, 0, 0, 0, 993, 995, 8, 3, 0, 0, 994, 993, 1, 0, 0, 0, 995, 996, 1, 0, 0, 0, 996, 994, 1, 0, 0, 0, 996, 997, 1, 0, 0, 0, 997, 55, 1, 0, 0, 0, 998, 999, 5, 77, 0, 0, 999, 1000, 5, 97, 0, 0, 1000, 1001, 5, 99, 0, 0, 1001, 1002, 5, 79, 0, 0, 1002, 1024, 5, 83, 0, 0, 1003, 1004, 5, 76, 0, 0, 1004, 1005, 5, 105, 0, 0, 1005, 1006, 5, 110, 0, 0, 1006, 1007, 5, 117, 0, 0, 1007, 1024, 5, 120, 0, 0, 1008, 1009, 5, 69, 0, 0, 1009, 1010, 5, 76, 0, 0, 1010, 1011, 5, 73, 0, 0, 1011, 1012, 5, 76, 0, 0, 1012, 1024, 5, 79, 0, 0, 1013, 1014, 5, 87, 0, 0, 1014, 1015, 5, 105, 0, 0, 1015, 1016, 5, 110, 0, 0, 1016, 1017, 5, 100, 0, 0, 1017, 1018, 5, 111, 0, 0, 1018, 1019, 5, 119, 0, 0, 1019, 1024, 5, 115, 0, 0, 1020, 1021, 5, 88, 0, 0, 1021, 1022, 5, 79, 0, 0, 1022, 1024, 5, 77, 0, 0, 1023, 998, 1, 0, 0, 0, 1023, 1003, 1, 0, 0, 0, 1023, 1008, 1, 0, 0, 0, 1023, 1013, 1, 0, 0, 0, 1023, 1020, 1, 0, 0, 0, 1024, 1025, 1, 0, 0, 0, 1025, 1026, 6, 27, 2, 0, 1026, 57, 1, 0, 0, 0, 1027, 1028, 5, 111, 0, 0, 1028, 1033, 5, 110, 0, 0, 1029, 1030, 5, 111, 0, 0, 1030, 1031, 5, 102, 0, 0, 1031, 1033, 5, 102, 0, 0, 1032, 1027, 1, 0, 0, 0, 1032, 1029, 1, 0, 0, 0, 1033, 1034, 1, 0, 0, 0, 1034, 1035, 6, 28, 2, 0, 1035, 59, 1, 0, 0, 0, 18, 0, 1, 63, 68, 75, 85, 89, 817, 822, 826, 832, 968, 975, 981, 989, 996, 1023, 1032, 3, 6, 0, 0, 5, 1, 0, 4, 0, 0] ================================================ FILE: src/refind_btrfs/boot/antlr4/RefindConfigLexer.py ================================================ # Generated from c:/Users/Luka/Projects/Python/refind-btrfs/src/refind_btrfs/boot/antlr4/RefindConfigLexer.g4 by ANTLR 4.13.1 from antlr4 import * from io import StringIO import sys if sys.version_info[1] > 5: from typing import TextIO else: from typing.io import TextIO def serializedATN(): return [ 4,0,23,1036,6,-1,6,-1,2,0,7,0,2,1,7,1,2,2,7,2,2,3,7,3,2,4,7,4,2, 5,7,5,2,6,7,6,2,7,7,7,2,8,7,8,2,9,7,9,2,10,7,10,2,11,7,11,2,12,7, 12,2,13,7,13,2,14,7,14,2,15,7,15,2,16,7,16,2,17,7,17,2,18,7,18,2, 19,7,19,2,20,7,20,2,21,7,21,2,22,7,22,2,23,7,23,2,24,7,24,2,25,7, 25,2,26,7,26,2,27,7,27,2,28,7,28,1,0,4,0,62,8,0,11,0,12,0,63,1,0, 1,0,1,1,3,1,69,8,1,1,1,1,1,1,1,1,1,1,2,3,2,76,8,2,1,2,1,2,1,2,1, 2,1,3,1,3,5,3,84,8,3,10,3,12,3,87,9,3,1,3,3,3,90,8,3,1,3,1,3,1,4, 1,4,1,4,1,4,1,4,1,4,1,4,1,4,1,4,1,4,1,4,1,4,1,4,1,4,1,4,1,4,1,4, 1,4,1,4,1,4,1,4,1,4,1,4,1,4,1,4,1,4,1,4,1,4,1,4,1,4,1,4,1,4,1,4, 1,4,1,4,1,4,1,4,1,4,1,4,1,4,1,4,1,4,1,4,1,4,1,4,1,4,1,4,1,4,1,4, 1,4,1,4,1,4,1,4,1,4,1,4,1,4,1,4,1,4,1,4,1,4,1,4,1,4,1,4,1,4,1,4, 1,4,1,4,1,4,1,4,1,4,1,4,1,4,1,4,1,4,1,4,1,4,1,4,1,4,1,4,1,4,1,4, 1,4,1,4,1,4,1,4,1,4,1,4,1,4,1,4,1,4,1,4,1,4,1,4,1,4,1,4,1,4,1,4, 1,4,1,4,1,4,1,4,1,4,1,4,1,4,1,4,1,4,1,4,1,4,1,4,1,4,1,4,1,4,1,4, 1,4,1,4,1,4,1,4,1,4,1,4,1,4,1,4,1,4,1,4,1,4,1,4,1,4,1,4,1,4,1,4, 1,4,1,4,1,4,1,4,1,4,1,4,1,4,1,4,1,4,1,4,1,4,1,4,1,4,1,4,1,4,1,4, 1,4,1,4,1,4,1,4,1,4,1,4,1,4,1,4,1,4,1,4,1,4,1,4,1,4,1,4,1,4,1,4, 1,4,1,4,1,4,1,4,1,4,1,4,1,4,1,4,1,4,1,4,1,4,1,4,1,4,1,4,1,4,1,4, 1,4,1,4,1,4,1,4,1,4,1,4,1,4,1,4,1,4,1,4,1,4,1,4,1,4,1,4,1,4,1,4, 1,4,1,4,1,4,1,4,1,4,1,4,1,4,1,4,1,4,1,4,1,4,1,4,1,4,1,4,1,4,1,4, 1,4,1,4,1,4,1,4,1,4,1,4,1,4,1,4,1,4,1,4,1,4,1,4,1,4,1,4,1,4,1,4, 1,4,1,4,1,4,1,4,1,4,1,4,1,4,1,4,1,4,1,4,1,4,1,4,1,4,1,4,1,4,1,4, 1,4,1,4,1,4,1,4,1,4,1,4,1,4,1,4,1,4,1,4,1,4,1,4,1,4,1,4,1,4,1,4, 1,4,1,4,1,4,1,4,1,4,1,4,1,4,1,4,1,4,1,4,1,4,1,4,1,4,1,4,1,4,1,4, 1,4,1,4,1,4,1,4,1,4,1,4,1,4,1,4,1,4,1,4,1,4,1,4,1,4,1,4,1,4,1,4, 1,4,1,4,1,4,1,4,1,4,1,4,1,4,1,4,1,4,1,4,1,4,1,4,1,4,1,4,1,4,1,4, 1,4,1,4,1,4,1,4,1,4,1,4,1,4,1,4,1,4,1,4,1,4,1,4,1,4,1,4,1,4,1,4, 1,4,1,4,1,4,1,4,1,4,1,4,1,4,1,4,1,4,1,4,1,4,1,4,1,4,1,4,1,4,1,4, 1,4,1,4,1,4,1,4,1,4,1,4,1,4,1,4,1,4,1,4,1,4,1,4,1,4,1,4,1,4,1,4, 1,4,1,4,1,4,1,4,1,4,1,4,1,4,1,4,1,4,1,4,1,4,1,4,1,4,1,4,1,4,1,4, 1,4,1,4,1,4,1,4,1,4,1,4,1,4,1,4,1,4,1,4,1,4,1,4,1,4,1,4,1,4,1,4, 1,4,1,4,1,4,1,4,1,4,1,4,1,4,1,4,1,4,1,4,1,4,1,4,1,4,1,4,1,4,1,4, 1,4,1,4,1,4,1,4,1,4,1,4,1,4,1,4,1,4,1,4,1,4,1,4,1,4,1,4,1,4,1,4, 1,4,1,4,1,4,1,4,1,4,1,4,1,4,1,4,1,4,1,4,1,4,1,4,1,4,1,4,1,4,1,4, 1,4,1,4,1,4,1,4,1,4,1,4,1,4,1,4,1,4,1,4,1,4,1,4,1,4,1,4,1,4,1,4, 1,4,1,4,1,4,1,4,1,4,1,4,1,4,1,4,1,4,1,4,1,4,1,4,1,4,1,4,1,4,1,4, 1,4,1,4,1,4,1,4,1,4,1,4,1,4,1,4,1,4,1,4,1,4,1,4,1,4,1,4,1,4,1,4, 1,4,1,4,1,4,1,4,1,4,1,4,1,4,1,4,1,4,1,4,1,4,1,4,1,4,1,4,1,4,1,4, 1,4,1,4,1,4,1,4,1,4,1,4,1,4,1,4,1,4,1,4,1,4,1,4,1,4,1,4,1,4,1,4, 1,4,1,4,1,4,1,4,1,4,1,4,1,4,1,4,1,4,1,4,1,4,1,4,1,4,1,4,1,4,1,4, 1,4,1,4,1,4,1,4,1,4,1,4,1,4,1,4,1,4,1,4,1,4,1,4,1,4,1,4,1,4,1,4, 1,4,1,4,1,4,1,4,1,4,1,4,1,4,1,4,1,4,1,4,1,4,1,4,1,4,1,4,1,4,1,4, 1,4,1,4,1,4,1,4,1,4,1,4,1,4,1,4,1,4,1,4,1,4,1,4,1,4,1,4,1,4,1,4, 1,4,1,4,1,4,1,4,1,4,1,4,1,4,1,4,1,4,1,4,1,4,1,4,1,4,1,4,1,4,1,4, 1,4,1,4,1,4,1,4,1,4,1,4,1,4,1,4,1,4,1,4,1,4,1,4,1,4,1,4,1,4,1,4, 1,4,1,4,1,4,1,4,1,4,1,4,1,4,1,4,1,4,1,4,1,4,1,4,1,4,1,4,1,4,1,4, 1,4,1,4,1,4,1,4,1,4,1,4,1,4,1,4,1,4,1,4,1,4,1,4,1,4,1,4,1,4,1,4, 1,4,1,4,1,4,1,4,1,4,1,4,1,4,1,4,1,4,1,4,1,4,1,4,1,4,1,4,1,4,1,4, 1,4,1,4,1,4,1,4,1,4,1,4,1,4,1,4,1,4,1,4,1,4,1,4,1,4,1,4,1,4,1,4, 1,4,1,4,1,4,1,4,1,4,1,4,1,4,1,4,1,4,1,4,1,4,1,4,1,4,1,4,1,4,1,4, 1,4,1,4,1,4,1,4,1,4,1,4,1,4,1,4,1,4,1,4,1,4,1,4,1,4,1,4,1,4,1,4, 1,4,1,4,1,4,1,4,1,4,1,4,1,4,1,4,1,4,1,4,1,4,1,4,1,4,1,4,1,4,1,4, 1,4,1,4,1,4,3,4,818,8,4,1,4,5,4,821,8,4,10,4,12,4,824,9,4,1,4,3, 4,827,8,4,1,4,1,4,1,5,1,5,3,5,833,8,5,1,6,1,6,1,6,1,6,1,6,1,6,1, 6,1,6,1,6,1,6,1,7,1,7,1,7,1,7,1,7,1,7,1,7,1,7,1,7,1,7,1,7,1,7,1, 7,1,8,1,8,1,8,1,8,1,8,1,8,1,8,1,9,1,9,1,9,1,9,1,9,1,9,1,9,1,10,1, 10,1,10,1,10,1,10,1,10,1,10,1,11,1,11,1,11,1,11,1,11,1,12,1,12,1, 12,1,12,1,12,1,12,1,12,1,12,1,12,1,12,1,12,1,13,1,13,1,13,1,13,1, 13,1,13,1,13,1,13,1,13,1,13,1,13,1,13,1,13,1,14,1,14,1,14,1,14,1, 14,1,14,1,14,1,14,1,15,1,15,1,15,1,15,1,15,1,15,1,15,1,15,1,15,1, 15,1,15,1,15,1,16,1,16,1,16,1,16,1,16,1,16,1,16,1,16,1,16,1,16,1, 16,1,16,1,16,1,16,1,16,1,16,1,16,1,17,1,17,1,17,1,17,1,17,1,17,1, 17,1,17,1,17,1,18,1,18,1,18,1,18,1,18,1,18,1,18,1,18,1,19,1,19,1, 20,1,20,1,21,4,21,967,8,21,11,21,12,21,968,1,22,1,22,1,23,1,23,1, 23,3,23,976,8,23,1,24,1,24,4,24,980,8,24,11,24,12,24,981,1,24,1, 24,1,25,1,25,4,25,988,8,25,11,25,12,25,989,1,25,1,25,1,26,4,26,995, 8,26,11,26,12,26,996,1,27,1,27,1,27,1,27,1,27,1,27,1,27,1,27,1,27, 1,27,1,27,1,27,1,27,1,27,1,27,1,27,1,27,1,27,1,27,1,27,1,27,1,27, 1,27,1,27,1,27,3,27,1024,8,27,1,27,1,27,1,28,1,28,1,28,1,28,1,28, 3,28,1033,8,28,1,28,1,28,0,0,29,2,1,4,2,6,3,8,4,10,5,12,6,14,0,16, 0,18,7,20,8,22,9,24,10,26,11,28,12,30,13,32,14,34,15,36,16,38,17, 40,18,42,19,44,20,46,0,48,21,50,0,52,0,54,0,56,22,58,23,2,0,1,4, 2,0,9,9,32,32,1,0,10,10,3,0,48,57,65,70,97,102,2,0,9,10,32,32,1098, 0,2,1,0,0,0,0,4,1,0,0,0,0,6,1,0,0,0,0,8,1,0,0,0,0,10,1,0,0,0,0,12, 1,0,0,0,0,18,1,0,0,0,0,20,1,0,0,0,0,22,1,0,0,0,0,24,1,0,0,0,0,26, 1,0,0,0,0,28,1,0,0,0,0,30,1,0,0,0,0,32,1,0,0,0,0,34,1,0,0,0,0,36, 1,0,0,0,0,38,1,0,0,0,0,40,1,0,0,0,0,42,1,0,0,0,0,44,1,0,0,0,0,48, 1,0,0,0,1,56,1,0,0,0,1,58,1,0,0,0,2,61,1,0,0,0,4,68,1,0,0,0,6,75, 1,0,0,0,8,81,1,0,0,0,10,817,1,0,0,0,12,832,1,0,0,0,14,834,1,0,0, 0,16,844,1,0,0,0,18,857,1,0,0,0,20,864,1,0,0,0,22,871,1,0,0,0,24, 878,1,0,0,0,26,883,1,0,0,0,28,894,1,0,0,0,30,907,1,0,0,0,32,915, 1,0,0,0,34,927,1,0,0,0,36,944,1,0,0,0,38,953,1,0,0,0,40,961,1,0, 0,0,42,963,1,0,0,0,44,966,1,0,0,0,46,970,1,0,0,0,48,975,1,0,0,0, 50,977,1,0,0,0,52,985,1,0,0,0,54,994,1,0,0,0,56,1023,1,0,0,0,58, 1032,1,0,0,0,60,62,7,0,0,0,61,60,1,0,0,0,62,63,1,0,0,0,63,61,1,0, 0,0,63,64,1,0,0,0,64,65,1,0,0,0,65,66,6,0,0,0,66,3,1,0,0,0,67,69, 5,13,0,0,68,67,1,0,0,0,68,69,1,0,0,0,69,70,1,0,0,0,70,71,5,10,0, 0,71,72,1,0,0,0,72,73,6,1,0,0,73,5,1,0,0,0,74,76,3,2,0,0,75,74,1, 0,0,0,75,76,1,0,0,0,76,77,1,0,0,0,77,78,3,4,1,0,78,79,1,0,0,0,79, 80,6,2,0,0,80,7,1,0,0,0,81,85,5,35,0,0,82,84,8,1,0,0,83,82,1,0,0, 0,84,87,1,0,0,0,85,83,1,0,0,0,85,86,1,0,0,0,86,89,1,0,0,0,87,85, 1,0,0,0,88,90,3,4,1,0,89,88,1,0,0,0,89,90,1,0,0,0,90,91,1,0,0,0, 91,92,6,3,0,0,92,9,1,0,0,0,93,94,5,97,0,0,94,95,5,108,0,0,95,96, 5,115,0,0,96,97,5,111,0,0,97,98,5,95,0,0,98,99,5,115,0,0,99,100, 5,99,0,0,100,101,5,97,0,0,101,102,5,110,0,0,102,103,5,95,0,0,103, 104,5,100,0,0,104,105,5,105,0,0,105,106,5,114,0,0,106,818,5,115, 0,0,107,108,5,97,0,0,108,109,5,108,0,0,109,110,5,115,0,0,110,111, 5,111,0,0,111,112,5,95,0,0,112,113,5,115,0,0,113,114,5,99,0,0,114, 115,5,97,0,0,115,116,5,110,0,0,116,117,5,95,0,0,117,118,5,116,0, 0,118,119,5,111,0,0,119,120,5,111,0,0,120,121,5,108,0,0,121,818, 5,115,0,0,122,123,5,98,0,0,123,124,5,97,0,0,124,125,5,110,0,0,125, 126,5,110,0,0,126,127,5,101,0,0,127,818,5,114,0,0,128,129,5,98,0, 0,129,130,5,97,0,0,130,131,5,110,0,0,131,132,5,110,0,0,132,133,5, 101,0,0,133,134,5,114,0,0,134,135,5,95,0,0,135,136,5,115,0,0,136, 137,5,99,0,0,137,138,5,97,0,0,138,139,5,108,0,0,139,818,5,101,0, 0,140,141,5,98,0,0,141,142,5,105,0,0,142,143,5,103,0,0,143,144,5, 95,0,0,144,145,5,105,0,0,145,146,5,99,0,0,146,147,5,111,0,0,147, 148,5,110,0,0,148,149,5,95,0,0,149,150,5,115,0,0,150,151,5,105,0, 0,151,152,5,122,0,0,152,818,5,101,0,0,153,154,5,99,0,0,154,155,5, 115,0,0,155,156,5,114,0,0,156,157,5,95,0,0,157,158,5,118,0,0,158, 159,5,97,0,0,159,160,5,108,0,0,160,161,5,117,0,0,161,162,5,101,0, 0,162,818,5,115,0,0,163,164,5,100,0,0,164,165,5,101,0,0,165,166, 5,102,0,0,166,167,5,97,0,0,167,168,5,117,0,0,168,169,5,108,0,0,169, 170,5,116,0,0,170,171,5,95,0,0,171,172,5,115,0,0,172,173,5,101,0, 0,173,174,5,108,0,0,174,175,5,101,0,0,175,176,5,99,0,0,176,177,5, 116,0,0,177,178,5,105,0,0,178,179,5,111,0,0,179,818,5,110,0,0,180, 181,5,100,0,0,181,182,5,111,0,0,182,183,5,110,0,0,183,184,5,39,0, 0,184,185,5,116,0,0,185,186,5,95,0,0,186,187,5,115,0,0,187,188,5, 99,0,0,188,189,5,97,0,0,189,190,5,110,0,0,190,191,5,95,0,0,191,192, 5,100,0,0,192,193,5,105,0,0,193,194,5,114,0,0,194,818,5,115,0,0, 195,196,5,100,0,0,196,197,5,111,0,0,197,198,5,110,0,0,198,199,5, 39,0,0,199,200,5,116,0,0,200,201,5,95,0,0,201,202,5,115,0,0,202, 203,5,99,0,0,203,204,5,97,0,0,204,205,5,110,0,0,205,206,5,95,0,0, 206,207,5,102,0,0,207,208,5,105,0,0,208,209,5,108,0,0,209,210,5, 101,0,0,210,818,5,115,0,0,211,212,5,100,0,0,212,213,5,111,0,0,213, 214,5,110,0,0,214,215,5,39,0,0,215,216,5,116,0,0,216,217,5,95,0, 0,217,218,5,115,0,0,218,219,5,99,0,0,219,220,5,97,0,0,220,221,5, 110,0,0,221,222,5,95,0,0,222,223,5,102,0,0,223,224,5,105,0,0,224, 225,5,114,0,0,225,226,5,109,0,0,226,227,5,119,0,0,227,228,5,97,0, 0,228,229,5,114,0,0,229,818,5,101,0,0,230,231,5,100,0,0,231,232, 5,111,0,0,232,233,5,110,0,0,233,234,5,39,0,0,234,235,5,116,0,0,235, 236,5,95,0,0,236,237,5,115,0,0,237,238,5,99,0,0,238,239,5,97,0,0, 239,240,5,110,0,0,240,241,5,95,0,0,241,242,5,116,0,0,242,243,5,111, 0,0,243,244,5,111,0,0,244,245,5,108,0,0,245,818,5,115,0,0,246,247, 5,100,0,0,247,248,5,111,0,0,248,249,5,110,0,0,249,250,5,39,0,0,250, 251,5,116,0,0,251,252,5,95,0,0,252,253,5,115,0,0,253,254,5,99,0, 0,254,255,5,97,0,0,255,256,5,110,0,0,256,257,5,95,0,0,257,258,5, 118,0,0,258,259,5,111,0,0,259,260,5,108,0,0,260,261,5,117,0,0,261, 262,5,109,0,0,262,263,5,101,0,0,263,818,5,115,0,0,264,265,5,100, 0,0,265,266,5,111,0,0,266,267,5,110,0,0,267,268,5,116,0,0,268,269, 5,95,0,0,269,270,5,115,0,0,270,271,5,99,0,0,271,272,5,97,0,0,272, 273,5,110,0,0,273,274,5,95,0,0,274,275,5,100,0,0,275,276,5,105,0, 0,276,277,5,114,0,0,277,818,5,115,0,0,278,279,5,100,0,0,279,280, 5,111,0,0,280,281,5,110,0,0,281,282,5,116,0,0,282,283,5,95,0,0,283, 284,5,115,0,0,284,285,5,99,0,0,285,286,5,97,0,0,286,287,5,110,0, 0,287,288,5,95,0,0,288,289,5,102,0,0,289,290,5,105,0,0,290,291,5, 108,0,0,291,292,5,101,0,0,292,818,5,115,0,0,293,294,5,100,0,0,294, 295,5,111,0,0,295,296,5,110,0,0,296,297,5,116,0,0,297,298,5,95,0, 0,298,299,5,115,0,0,299,300,5,99,0,0,300,301,5,97,0,0,301,302,5, 110,0,0,302,303,5,95,0,0,303,304,5,102,0,0,304,305,5,105,0,0,305, 306,5,114,0,0,306,307,5,109,0,0,307,308,5,119,0,0,308,309,5,97,0, 0,309,310,5,114,0,0,310,818,5,101,0,0,311,312,5,100,0,0,312,313, 5,111,0,0,313,314,5,110,0,0,314,315,5,116,0,0,315,316,5,95,0,0,316, 317,5,115,0,0,317,318,5,99,0,0,318,319,5,97,0,0,319,320,5,110,0, 0,320,321,5,95,0,0,321,322,5,116,0,0,322,323,5,111,0,0,323,324,5, 111,0,0,324,325,5,108,0,0,325,818,5,115,0,0,326,327,5,100,0,0,327, 328,5,111,0,0,328,329,5,110,0,0,329,330,5,116,0,0,330,331,5,95,0, 0,331,332,5,115,0,0,332,333,5,99,0,0,333,334,5,97,0,0,334,335,5, 110,0,0,335,336,5,95,0,0,336,337,5,118,0,0,337,338,5,111,0,0,338, 339,5,108,0,0,339,340,5,117,0,0,340,341,5,109,0,0,341,342,5,101, 0,0,342,818,5,115,0,0,343,344,5,101,0,0,344,345,5,110,0,0,345,346, 5,97,0,0,346,347,5,98,0,0,347,348,5,108,0,0,348,349,5,101,0,0,349, 350,5,95,0,0,350,351,5,97,0,0,351,352,5,110,0,0,352,353,5,100,0, 0,353,354,5,95,0,0,354,355,5,108,0,0,355,356,5,111,0,0,356,357,5, 99,0,0,357,358,5,107,0,0,358,359,5,95,0,0,359,360,5,118,0,0,360, 361,5,109,0,0,361,818,5,120,0,0,362,363,5,101,0,0,363,364,5,110, 0,0,364,365,5,97,0,0,365,366,5,98,0,0,366,367,5,108,0,0,367,368, 5,101,0,0,368,369,5,95,0,0,369,370,5,109,0,0,370,371,5,111,0,0,371, 372,5,117,0,0,372,373,5,115,0,0,373,818,5,101,0,0,374,375,5,101, 0,0,375,376,5,110,0,0,376,377,5,97,0,0,377,378,5,98,0,0,378,379, 5,108,0,0,379,380,5,101,0,0,380,381,5,95,0,0,381,382,5,116,0,0,382, 383,5,111,0,0,383,384,5,117,0,0,384,385,5,99,0,0,385,818,5,104,0, 0,386,387,5,101,0,0,387,388,5,120,0,0,388,389,5,116,0,0,389,390, 5,114,0,0,390,391,5,97,0,0,391,392,5,95,0,0,392,393,5,107,0,0,393, 394,5,101,0,0,394,395,5,114,0,0,395,396,5,110,0,0,396,397,5,101, 0,0,397,398,5,108,0,0,398,399,5,95,0,0,399,400,5,118,0,0,400,401, 5,101,0,0,401,402,5,114,0,0,402,403,5,115,0,0,403,404,5,105,0,0, 404,405,5,111,0,0,405,406,5,110,0,0,406,407,5,95,0,0,407,408,5,115, 0,0,408,409,5,116,0,0,409,410,5,114,0,0,410,411,5,105,0,0,411,412, 5,110,0,0,412,413,5,103,0,0,413,818,5,115,0,0,414,415,5,102,0,0, 415,416,5,111,0,0,416,417,5,108,0,0,417,418,5,100,0,0,418,419,5, 95,0,0,419,420,5,108,0,0,420,421,5,105,0,0,421,422,5,110,0,0,422, 423,5,117,0,0,423,424,5,120,0,0,424,425,5,95,0,0,425,426,5,107,0, 0,426,427,5,101,0,0,427,428,5,114,0,0,428,429,5,110,0,0,429,430, 5,101,0,0,430,431,5,108,0,0,431,818,5,115,0,0,432,433,5,102,0,0, 433,434,5,111,0,0,434,435,5,108,0,0,435,436,5,108,0,0,436,437,5, 111,0,0,437,438,5,119,0,0,438,439,5,95,0,0,439,440,5,115,0,0,440, 441,5,121,0,0,441,442,5,109,0,0,442,443,5,108,0,0,443,444,5,105, 0,0,444,445,5,110,0,0,445,446,5,107,0,0,446,818,5,115,0,0,447,448, 5,102,0,0,448,449,5,111,0,0,449,450,5,110,0,0,450,818,5,116,0,0, 451,452,5,104,0,0,452,453,5,105,0,0,453,454,5,100,0,0,454,455,5, 101,0,0,455,456,5,117,0,0,456,818,5,105,0,0,457,458,5,105,0,0,458, 459,5,99,0,0,459,460,5,111,0,0,460,461,5,110,0,0,461,462,5,115,0, 0,462,463,5,95,0,0,463,464,5,100,0,0,464,465,5,105,0,0,465,818,5, 114,0,0,466,467,5,108,0,0,467,468,5,105,0,0,468,469,5,110,0,0,469, 470,5,117,0,0,470,471,5,120,0,0,471,472,5,95,0,0,472,473,5,112,0, 0,473,474,5,114,0,0,474,475,5,101,0,0,475,476,5,102,0,0,476,477, 5,105,0,0,477,478,5,120,0,0,478,479,5,101,0,0,479,818,5,115,0,0, 480,481,5,108,0,0,481,482,5,111,0,0,482,483,5,103,0,0,483,484,5, 95,0,0,484,485,5,108,0,0,485,486,5,101,0,0,486,487,5,118,0,0,487, 488,5,101,0,0,488,818,5,108,0,0,489,490,5,109,0,0,490,491,5,97,0, 0,491,492,5,120,0,0,492,493,5,95,0,0,493,494,5,116,0,0,494,495,5, 97,0,0,495,496,5,103,0,0,496,818,5,115,0,0,497,498,5,109,0,0,498, 499,5,111,0,0,499,500,5,117,0,0,500,501,5,115,0,0,501,502,5,101, 0,0,502,503,5,95,0,0,503,504,5,115,0,0,504,505,5,105,0,0,505,506, 5,122,0,0,506,818,5,101,0,0,507,508,5,109,0,0,508,509,5,111,0,0, 509,510,5,117,0,0,510,511,5,115,0,0,511,512,5,101,0,0,512,513,5, 95,0,0,513,514,5,115,0,0,514,515,5,112,0,0,515,516,5,101,0,0,516, 517,5,101,0,0,517,818,5,100,0,0,518,519,5,114,0,0,519,520,5,101, 0,0,520,521,5,115,0,0,521,522,5,111,0,0,522,523,5,108,0,0,523,524, 5,117,0,0,524,525,5,116,0,0,525,526,5,105,0,0,526,527,5,111,0,0, 527,818,5,110,0,0,528,529,5,115,0,0,529,530,5,99,0,0,530,531,5,97, 0,0,531,532,5,110,0,0,532,533,5,95,0,0,533,534,5,97,0,0,534,535, 5,108,0,0,535,536,5,108,0,0,536,537,5,95,0,0,537,538,5,108,0,0,538, 539,5,105,0,0,539,540,5,110,0,0,540,541,5,117,0,0,541,542,5,120, 0,0,542,543,5,95,0,0,543,544,5,107,0,0,544,545,5,101,0,0,545,546, 5,114,0,0,546,547,5,110,0,0,547,548,5,101,0,0,548,549,5,108,0,0, 549,818,5,115,0,0,550,551,5,115,0,0,551,552,5,99,0,0,552,553,5,97, 0,0,553,554,5,110,0,0,554,555,5,95,0,0,555,556,5,100,0,0,556,557, 5,101,0,0,557,558,5,108,0,0,558,559,5,97,0,0,559,818,5,121,0,0,560, 561,5,115,0,0,561,562,5,99,0,0,562,563,5,97,0,0,563,564,5,110,0, 0,564,565,5,95,0,0,565,566,5,100,0,0,566,567,5,114,0,0,567,568,5, 105,0,0,568,569,5,118,0,0,569,570,5,101,0,0,570,571,5,114,0,0,571, 572,5,95,0,0,572,573,5,100,0,0,573,574,5,105,0,0,574,575,5,114,0, 0,575,818,5,115,0,0,576,577,5,115,0,0,577,578,5,99,0,0,578,579,5, 97,0,0,579,580,5,110,0,0,580,581,5,102,0,0,581,582,5,111,0,0,582, 818,5,114,0,0,583,584,5,115,0,0,584,585,5,99,0,0,585,586,5,114,0, 0,586,587,5,101,0,0,587,588,5,101,0,0,588,589,5,110,0,0,589,590, 5,115,0,0,590,591,5,97,0,0,591,592,5,118,0,0,592,593,5,101,0,0,593, 818,5,114,0,0,594,595,5,115,0,0,595,596,5,101,0,0,596,597,5,108, 0,0,597,598,5,101,0,0,598,599,5,99,0,0,599,600,5,116,0,0,600,601, 5,105,0,0,601,602,5,111,0,0,602,603,5,110,0,0,603,604,5,95,0,0,604, 605,5,98,0,0,605,606,5,105,0,0,606,818,5,103,0,0,607,608,5,115,0, 0,608,609,5,101,0,0,609,610,5,108,0,0,610,611,5,101,0,0,611,612, 5,99,0,0,612,613,5,116,0,0,613,614,5,105,0,0,614,615,5,111,0,0,615, 616,5,110,0,0,616,617,5,95,0,0,617,618,5,115,0,0,618,619,5,109,0, 0,619,620,5,97,0,0,620,621,5,108,0,0,621,818,5,108,0,0,622,623,5, 115,0,0,623,624,5,104,0,0,624,625,5,111,0,0,625,626,5,119,0,0,626, 627,5,116,0,0,627,628,5,111,0,0,628,629,5,111,0,0,629,630,5,108, 0,0,630,818,5,115,0,0,631,632,5,115,0,0,632,633,5,104,0,0,633,634, 5,117,0,0,634,635,5,116,0,0,635,636,5,100,0,0,636,637,5,111,0,0, 637,638,5,119,0,0,638,639,5,110,0,0,639,640,5,95,0,0,640,641,5,97, 0,0,641,642,5,102,0,0,642,643,5,116,0,0,643,644,5,101,0,0,644,645, 5,114,0,0,645,646,5,95,0,0,646,647,5,116,0,0,647,648,5,105,0,0,648, 649,5,109,0,0,649,650,5,101,0,0,650,651,5,111,0,0,651,652,5,117, 0,0,652,818,5,116,0,0,653,654,5,115,0,0,654,655,5,109,0,0,655,656, 5,97,0,0,656,657,5,108,0,0,657,658,5,108,0,0,658,659,5,95,0,0,659, 660,5,105,0,0,660,661,5,99,0,0,661,662,5,111,0,0,662,663,5,110,0, 0,663,664,5,95,0,0,664,665,5,115,0,0,665,666,5,105,0,0,666,667,5, 122,0,0,667,818,5,101,0,0,668,669,5,115,0,0,669,670,5,112,0,0,670, 671,5,111,0,0,671,672,5,111,0,0,672,673,5,102,0,0,673,674,5,95,0, 0,674,675,5,111,0,0,675,676,5,115,0,0,676,677,5,120,0,0,677,678, 5,95,0,0,678,679,5,118,0,0,679,680,5,101,0,0,680,681,5,114,0,0,681, 682,5,115,0,0,682,683,5,105,0,0,683,684,5,111,0,0,684,818,5,110, 0,0,685,686,5,115,0,0,686,687,5,117,0,0,687,688,5,112,0,0,688,689, 5,112,0,0,689,690,5,111,0,0,690,691,5,114,0,0,691,692,5,116,0,0, 692,693,5,95,0,0,693,694,5,103,0,0,694,695,5,122,0,0,695,696,5,105, 0,0,696,697,5,112,0,0,697,698,5,112,0,0,698,699,5,101,0,0,699,700, 5,100,0,0,700,701,5,95,0,0,701,702,5,108,0,0,702,703,5,111,0,0,703, 704,5,97,0,0,704,705,5,100,0,0,705,706,5,101,0,0,706,707,5,114,0, 0,707,818,5,115,0,0,708,709,5,116,0,0,709,710,5,101,0,0,710,711, 5,120,0,0,711,712,5,116,0,0,712,713,5,109,0,0,713,714,5,111,0,0, 714,715,5,100,0,0,715,818,5,101,0,0,716,717,5,116,0,0,717,718,5, 101,0,0,718,719,5,120,0,0,719,720,5,116,0,0,720,721,5,111,0,0,721, 722,5,110,0,0,722,723,5,108,0,0,723,818,5,121,0,0,724,725,5,116, 0,0,725,726,5,105,0,0,726,727,5,109,0,0,727,728,5,101,0,0,728,729, 5,111,0,0,729,730,5,117,0,0,730,818,5,116,0,0,731,732,5,117,0,0, 732,733,5,101,0,0,733,734,5,102,0,0,734,735,5,105,0,0,735,736,5, 95,0,0,736,737,5,100,0,0,737,738,5,101,0,0,738,739,5,101,0,0,739, 740,5,112,0,0,740,741,5,95,0,0,741,742,5,108,0,0,742,743,5,101,0, 0,743,744,5,103,0,0,744,745,5,97,0,0,745,746,5,99,0,0,746,747,5, 121,0,0,747,748,5,95,0,0,748,749,5,115,0,0,749,750,5,99,0,0,750, 751,5,97,0,0,751,818,5,110,0,0,752,753,5,117,0,0,753,754,5,115,0, 0,754,755,5,101,0,0,755,756,5,95,0,0,756,757,5,103,0,0,757,758,5, 114,0,0,758,759,5,97,0,0,759,760,5,112,0,0,760,761,5,104,0,0,761, 762,5,105,0,0,762,763,5,99,0,0,763,764,5,115,0,0,764,765,5,95,0, 0,765,766,5,102,0,0,766,767,5,111,0,0,767,818,5,114,0,0,768,769, 5,117,0,0,769,770,5,115,0,0,770,771,5,101,0,0,771,772,5,95,0,0,772, 773,5,110,0,0,773,774,5,118,0,0,774,775,5,114,0,0,775,776,5,97,0, 0,776,818,5,109,0,0,777,778,5,119,0,0,778,779,5,105,0,0,779,780, 5,110,0,0,780,781,5,100,0,0,781,782,5,111,0,0,782,783,5,119,0,0, 783,784,5,115,0,0,784,785,5,95,0,0,785,786,5,114,0,0,786,787,5,101, 0,0,787,788,5,99,0,0,788,789,5,111,0,0,789,790,5,118,0,0,790,791, 5,101,0,0,791,792,5,114,0,0,792,793,5,121,0,0,793,794,5,95,0,0,794, 795,5,102,0,0,795,796,5,105,0,0,796,797,5,108,0,0,797,798,5,101, 0,0,798,818,5,115,0,0,799,800,5,119,0,0,800,801,5,114,0,0,801,802, 5,105,0,0,802,803,5,116,0,0,803,804,5,101,0,0,804,805,5,95,0,0,805, 806,5,115,0,0,806,807,5,121,0,0,807,808,5,115,0,0,808,809,5,116, 0,0,809,810,5,101,0,0,810,811,5,109,0,0,811,812,5,100,0,0,812,813, 5,95,0,0,813,814,5,118,0,0,814,815,5,97,0,0,815,816,5,114,0,0,816, 818,5,115,0,0,817,93,1,0,0,0,817,107,1,0,0,0,817,122,1,0,0,0,817, 128,1,0,0,0,817,140,1,0,0,0,817,153,1,0,0,0,817,163,1,0,0,0,817, 180,1,0,0,0,817,195,1,0,0,0,817,211,1,0,0,0,817,230,1,0,0,0,817, 246,1,0,0,0,817,264,1,0,0,0,817,278,1,0,0,0,817,293,1,0,0,0,817, 311,1,0,0,0,817,326,1,0,0,0,817,343,1,0,0,0,817,362,1,0,0,0,817, 374,1,0,0,0,817,386,1,0,0,0,817,414,1,0,0,0,817,432,1,0,0,0,817, 447,1,0,0,0,817,451,1,0,0,0,817,457,1,0,0,0,817,466,1,0,0,0,817, 480,1,0,0,0,817,489,1,0,0,0,817,497,1,0,0,0,817,507,1,0,0,0,817, 518,1,0,0,0,817,528,1,0,0,0,817,550,1,0,0,0,817,560,1,0,0,0,817, 576,1,0,0,0,817,583,1,0,0,0,817,594,1,0,0,0,817,607,1,0,0,0,817, 622,1,0,0,0,817,631,1,0,0,0,817,653,1,0,0,0,817,668,1,0,0,0,817, 685,1,0,0,0,817,708,1,0,0,0,817,716,1,0,0,0,817,724,1,0,0,0,817, 731,1,0,0,0,817,752,1,0,0,0,817,768,1,0,0,0,817,777,1,0,0,0,817, 799,1,0,0,0,818,822,1,0,0,0,819,821,8,1,0,0,820,819,1,0,0,0,821, 824,1,0,0,0,822,820,1,0,0,0,822,823,1,0,0,0,823,826,1,0,0,0,824, 822,1,0,0,0,825,827,3,4,1,0,826,825,1,0,0,0,826,827,1,0,0,0,827, 828,1,0,0,0,828,829,6,4,0,0,829,11,1,0,0,0,830,833,3,14,6,0,831, 833,3,16,7,0,832,830,1,0,0,0,832,831,1,0,0,0,833,13,1,0,0,0,834, 835,5,109,0,0,835,836,5,101,0,0,836,837,5,110,0,0,837,838,5,117, 0,0,838,839,5,101,0,0,839,840,5,110,0,0,840,841,5,116,0,0,841,842, 5,114,0,0,842,843,5,121,0,0,843,15,1,0,0,0,844,845,5,115,0,0,845, 846,5,117,0,0,846,847,5,98,0,0,847,848,5,109,0,0,848,849,5,101,0, 0,849,850,5,110,0,0,850,851,5,117,0,0,851,852,5,101,0,0,852,853, 5,110,0,0,853,854,5,116,0,0,854,855,5,114,0,0,855,856,5,121,0,0, 856,17,1,0,0,0,857,858,5,118,0,0,858,859,5,111,0,0,859,860,5,108, 0,0,860,861,5,117,0,0,861,862,5,109,0,0,862,863,5,101,0,0,863,19, 1,0,0,0,864,865,5,108,0,0,865,866,5,111,0,0,866,867,5,97,0,0,867, 868,5,100,0,0,868,869,5,101,0,0,869,870,5,114,0,0,870,21,1,0,0,0, 871,872,5,105,0,0,872,873,5,110,0,0,873,874,5,105,0,0,874,875,5, 116,0,0,875,876,5,114,0,0,876,877,5,100,0,0,877,23,1,0,0,0,878,879, 5,105,0,0,879,880,5,99,0,0,880,881,5,111,0,0,881,882,5,110,0,0,882, 25,1,0,0,0,883,884,5,111,0,0,884,885,5,115,0,0,885,886,5,116,0,0, 886,887,5,121,0,0,887,888,5,112,0,0,888,889,5,101,0,0,889,890,1, 0,0,0,890,891,3,2,0,0,891,892,1,0,0,0,892,893,6,12,1,0,893,27,1, 0,0,0,894,895,5,103,0,0,895,896,5,114,0,0,896,897,5,97,0,0,897,898, 5,112,0,0,898,899,5,104,0,0,899,900,5,105,0,0,900,901,5,99,0,0,901, 902,5,115,0,0,902,903,1,0,0,0,903,904,3,2,0,0,904,905,1,0,0,0,905, 906,6,13,1,0,906,29,1,0,0,0,907,908,5,111,0,0,908,909,5,112,0,0, 909,910,5,116,0,0,910,911,5,105,0,0,911,912,5,111,0,0,912,913,5, 110,0,0,913,914,5,115,0,0,914,31,1,0,0,0,915,916,5,97,0,0,916,917, 5,100,0,0,917,918,5,100,0,0,918,919,5,95,0,0,919,920,5,111,0,0,920, 921,5,112,0,0,921,922,5,116,0,0,922,923,5,105,0,0,923,924,5,111, 0,0,924,925,5,110,0,0,925,926,5,115,0,0,926,33,1,0,0,0,927,928,5, 102,0,0,928,929,5,105,0,0,929,930,5,114,0,0,930,931,5,109,0,0,931, 932,5,119,0,0,932,933,5,97,0,0,933,934,5,114,0,0,934,935,5,101,0, 0,935,936,5,95,0,0,936,937,5,98,0,0,937,938,5,111,0,0,938,939,5, 111,0,0,939,940,5,116,0,0,940,941,5,110,0,0,941,942,5,117,0,0,942, 943,5,109,0,0,943,35,1,0,0,0,944,945,5,100,0,0,945,946,5,105,0,0, 946,947,5,115,0,0,947,948,5,97,0,0,948,949,5,98,0,0,949,950,5,108, 0,0,950,951,5,101,0,0,951,952,5,100,0,0,952,37,1,0,0,0,953,954,5, 105,0,0,954,955,5,110,0,0,955,956,5,99,0,0,956,957,5,108,0,0,957, 958,5,117,0,0,958,959,5,100,0,0,959,960,5,101,0,0,960,39,1,0,0,0, 961,962,5,123,0,0,962,41,1,0,0,0,963,964,5,125,0,0,964,43,1,0,0, 0,965,967,3,46,22,0,966,965,1,0,0,0,967,968,1,0,0,0,968,966,1,0, 0,0,968,969,1,0,0,0,969,45,1,0,0,0,970,971,7,2,0,0,971,47,1,0,0, 0,972,976,3,50,24,0,973,976,3,52,25,0,974,976,3,54,26,0,975,972, 1,0,0,0,975,973,1,0,0,0,975,974,1,0,0,0,976,49,1,0,0,0,977,979,5, 39,0,0,978,980,8,1,0,0,979,978,1,0,0,0,980,981,1,0,0,0,981,979,1, 0,0,0,981,982,1,0,0,0,982,983,1,0,0,0,983,984,5,39,0,0,984,51,1, 0,0,0,985,987,5,34,0,0,986,988,8,1,0,0,987,986,1,0,0,0,988,989,1, 0,0,0,989,987,1,0,0,0,989,990,1,0,0,0,990,991,1,0,0,0,991,992,5, 34,0,0,992,53,1,0,0,0,993,995,8,3,0,0,994,993,1,0,0,0,995,996,1, 0,0,0,996,994,1,0,0,0,996,997,1,0,0,0,997,55,1,0,0,0,998,999,5,77, 0,0,999,1000,5,97,0,0,1000,1001,5,99,0,0,1001,1002,5,79,0,0,1002, 1024,5,83,0,0,1003,1004,5,76,0,0,1004,1005,5,105,0,0,1005,1006,5, 110,0,0,1006,1007,5,117,0,0,1007,1024,5,120,0,0,1008,1009,5,69,0, 0,1009,1010,5,76,0,0,1010,1011,5,73,0,0,1011,1012,5,76,0,0,1012, 1024,5,79,0,0,1013,1014,5,87,0,0,1014,1015,5,105,0,0,1015,1016,5, 110,0,0,1016,1017,5,100,0,0,1017,1018,5,111,0,0,1018,1019,5,119, 0,0,1019,1024,5,115,0,0,1020,1021,5,88,0,0,1021,1022,5,79,0,0,1022, 1024,5,77,0,0,1023,998,1,0,0,0,1023,1003,1,0,0,0,1023,1008,1,0,0, 0,1023,1013,1,0,0,0,1023,1020,1,0,0,0,1024,1025,1,0,0,0,1025,1026, 6,27,2,0,1026,57,1,0,0,0,1027,1028,5,111,0,0,1028,1033,5,110,0,0, 1029,1030,5,111,0,0,1030,1031,5,102,0,0,1031,1033,5,102,0,0,1032, 1027,1,0,0,0,1032,1029,1,0,0,0,1033,1034,1,0,0,0,1034,1035,6,28, 2,0,1035,59,1,0,0,0,18,0,1,63,68,75,85,89,817,822,826,832,968,975, 981,989,996,1023,1032,3,6,0,0,5,1,0,4,0,0 ] class RefindConfigLexer(Lexer): atn = ATNDeserializer().deserialize(serializedATN()) decisionsToDFA = [ DFA(ds, i) for i, ds in enumerate(atn.decisionToState) ] STRICT_PARAMETER_MODE = 1 WHITESPACE = 1 NEWLINE = 2 EMPTY = 3 COMMENT = 4 IGNORED_OPTION = 5 MENU_ENTRY = 6 VOLUME = 7 LOADER = 8 INITRD = 9 ICON = 10 OS_TYPE = 11 GRAPHICS = 12 BOOT_OPTIONS = 13 ADD_BOOT_OPTIONS = 14 FIRMWARE_BOOTNUM = 15 DISABLED = 16 INCLUDE = 17 OPEN_BRACE = 18 CLOSE_BRACE = 19 HEX_INTEGER = 20 STRING = 21 OS_TYPE_PARAMETER = 22 GRAPHICS_PARAMETER = 23 channelNames = [ u"DEFAULT_TOKEN_CHANNEL", u"HIDDEN" ] modeNames = [ "DEFAULT_MODE", "STRICT_PARAMETER_MODE" ] literalNames = [ "", "'volume'", "'loader'", "'initrd'", "'icon'", "'options'", "'add_options'", "'firmware_bootnum'", "'disabled'", "'include'", "'{'", "'}'" ] symbolicNames = [ "", "WHITESPACE", "NEWLINE", "EMPTY", "COMMENT", "IGNORED_OPTION", "MENU_ENTRY", "VOLUME", "LOADER", "INITRD", "ICON", "OS_TYPE", "GRAPHICS", "BOOT_OPTIONS", "ADD_BOOT_OPTIONS", "FIRMWARE_BOOTNUM", "DISABLED", "INCLUDE", "OPEN_BRACE", "CLOSE_BRACE", "HEX_INTEGER", "STRING", "OS_TYPE_PARAMETER", "GRAPHICS_PARAMETER" ] ruleNames = [ "WHITESPACE", "NEWLINE", "EMPTY", "COMMENT", "IGNORED_OPTION", "MENU_ENTRY", "MAIN_MENU_ENTRY", "SUB_MENU_ENTRY", "VOLUME", "LOADER", "INITRD", "ICON", "OS_TYPE", "GRAPHICS", "BOOT_OPTIONS", "ADD_BOOT_OPTIONS", "FIRMWARE_BOOTNUM", "DISABLED", "INCLUDE", "OPEN_BRACE", "CLOSE_BRACE", "HEX_INTEGER", "HEX_DIGIT", "STRING", "SINGLE_QUOTED_STRING", "DOUBLE_QUOTED_STRING", "UNQUOTED_STRING", "OS_TYPE_PARAMETER", "GRAPHICS_PARAMETER" ] grammarFileName = "RefindConfigLexer.g4" def __init__(self, input=None, output:TextIO = sys.stdout): super().__init__(input, output) self.checkVersion("4.13.1") self._interp = LexerATNSimulator(self, self.atn, self.decisionsToDFA, PredictionContextCache()) self._actions = None self._predicates = None ================================================ FILE: src/refind_btrfs/boot/antlr4/RefindConfigLexer.tokens ================================================ WHITESPACE=1 NEWLINE=2 EMPTY=3 COMMENT=4 IGNORED_OPTION=5 MENU_ENTRY=6 VOLUME=7 LOADER=8 INITRD=9 ICON=10 OS_TYPE=11 GRAPHICS=12 BOOT_OPTIONS=13 ADD_BOOT_OPTIONS=14 FIRMWARE_BOOTNUM=15 DISABLED=16 INCLUDE=17 OPEN_BRACE=18 CLOSE_BRACE=19 HEX_INTEGER=20 STRING=21 OS_TYPE_PARAMETER=22 GRAPHICS_PARAMETER=23 'volume'=7 'loader'=8 'initrd'=9 'icon'=10 'options'=13 'add_options'=14 'firmware_bootnum'=15 'disabled'=16 'include'=17 '{'=18 '}'=19 ================================================ FILE: src/refind_btrfs/boot/antlr4/RefindConfigParser.g4 ================================================ /* SPDX-FileCopyrightText: 2020-2024 Luka Žaja SPDX-License-Identifier: GPL-3.0-or-later refind-btrfs - Generate rEFInd manual boot stanzas from Btrfs snapshots Copyright (C) 2020-2024 Luka Žaja 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, either version 3 of the License, or (at your option) any later version. 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 . */ parser grammar RefindConfigParser; options { tokenVocab=RefindConfigLexer; } refind : config_option* EOF ; config_option : boot_stanza | include ; // "menuentry" section boot_stanza : menu_entry OPEN_BRACE main_option+ CLOSE_BRACE ; menu_entry : MENU_ENTRY STRING ; main_option : volume | loader | main_initrd | icon | os_type | graphics | main_boot_options | firmware_bootnum | disabled | sub_menu ; volume : VOLUME STRING ; loader : LOADER STRING ; main_initrd : INITRD STRING ; icon : ICON STRING ; os_type : OS_TYPE OS_TYPE_PARAMETER ; graphics : GRAPHICS GRAPHICS_PARAMETER ; main_boot_options : BOOT_OPTIONS STRING ; firmware_bootnum: FIRMWARE_BOOTNUM HEX_INTEGER ; disabled : DISABLED; // "submenuentry" section sub_menu : menu_entry OPEN_BRACE sub_option+ CLOSE_BRACE ; sub_option : loader | sub_initrd | graphics | sub_boot_options | add_boot_options | disabled ; sub_initrd : INITRD STRING? ; sub_boot_options : BOOT_OPTIONS STRING? ; add_boot_options : ADD_BOOT_OPTIONS STRING ; // "include" section include : INCLUDE STRING ; ================================================ FILE: src/refind_btrfs/boot/antlr4/RefindConfigParser.interp ================================================ token literal names: null null null null null null null 'volume' 'loader' 'initrd' 'icon' null null 'options' 'add_options' 'firmware_bootnum' 'disabled' 'include' '{' '}' null null null null token symbolic names: null WHITESPACE NEWLINE EMPTY COMMENT IGNORED_OPTION MENU_ENTRY VOLUME LOADER INITRD ICON OS_TYPE GRAPHICS BOOT_OPTIONS ADD_BOOT_OPTIONS FIRMWARE_BOOTNUM DISABLED INCLUDE OPEN_BRACE CLOSE_BRACE HEX_INTEGER STRING OS_TYPE_PARAMETER GRAPHICS_PARAMETER rule names: refind config_option boot_stanza menu_entry main_option volume loader main_initrd icon os_type graphics main_boot_options firmware_bootnum disabled sub_menu sub_option sub_initrd sub_boot_options add_boot_options include atn: [4, 1, 23, 134, 2, 0, 7, 0, 2, 1, 7, 1, 2, 2, 7, 2, 2, 3, 7, 3, 2, 4, 7, 4, 2, 5, 7, 5, 2, 6, 7, 6, 2, 7, 7, 7, 2, 8, 7, 8, 2, 9, 7, 9, 2, 10, 7, 10, 2, 11, 7, 11, 2, 12, 7, 12, 2, 13, 7, 13, 2, 14, 7, 14, 2, 15, 7, 15, 2, 16, 7, 16, 2, 17, 7, 17, 2, 18, 7, 18, 2, 19, 7, 19, 1, 0, 5, 0, 42, 8, 0, 10, 0, 12, 0, 45, 9, 0, 1, 0, 1, 0, 1, 1, 1, 1, 3, 1, 51, 8, 1, 1, 2, 1, 2, 1, 2, 4, 2, 56, 8, 2, 11, 2, 12, 2, 57, 1, 2, 1, 2, 1, 3, 1, 3, 1, 3, 1, 4, 1, 4, 1, 4, 1, 4, 1, 4, 1, 4, 1, 4, 1, 4, 1, 4, 1, 4, 3, 4, 75, 8, 4, 1, 5, 1, 5, 1, 5, 1, 6, 1, 6, 1, 6, 1, 7, 1, 7, 1, 7, 1, 8, 1, 8, 1, 8, 1, 9, 1, 9, 1, 9, 1, 10, 1, 10, 1, 10, 1, 11, 1, 11, 1, 11, 1, 12, 1, 12, 1, 12, 1, 13, 1, 13, 1, 14, 1, 14, 1, 14, 4, 14, 106, 8, 14, 11, 14, 12, 14, 107, 1, 14, 1, 14, 1, 15, 1, 15, 1, 15, 1, 15, 1, 15, 1, 15, 3, 15, 118, 8, 15, 1, 16, 1, 16, 3, 16, 122, 8, 16, 1, 17, 1, 17, 3, 17, 126, 8, 17, 1, 18, 1, 18, 1, 18, 1, 19, 1, 19, 1, 19, 1, 19, 0, 0, 20, 0, 2, 4, 6, 8, 10, 12, 14, 16, 18, 20, 22, 24, 26, 28, 30, 32, 34, 36, 38, 0, 0, 133, 0, 43, 1, 0, 0, 0, 2, 50, 1, 0, 0, 0, 4, 52, 1, 0, 0, 0, 6, 61, 1, 0, 0, 0, 8, 74, 1, 0, 0, 0, 10, 76, 1, 0, 0, 0, 12, 79, 1, 0, 0, 0, 14, 82, 1, 0, 0, 0, 16, 85, 1, 0, 0, 0, 18, 88, 1, 0, 0, 0, 20, 91, 1, 0, 0, 0, 22, 94, 1, 0, 0, 0, 24, 97, 1, 0, 0, 0, 26, 100, 1, 0, 0, 0, 28, 102, 1, 0, 0, 0, 30, 117, 1, 0, 0, 0, 32, 119, 1, 0, 0, 0, 34, 123, 1, 0, 0, 0, 36, 127, 1, 0, 0, 0, 38, 130, 1, 0, 0, 0, 40, 42, 3, 2, 1, 0, 41, 40, 1, 0, 0, 0, 42, 45, 1, 0, 0, 0, 43, 41, 1, 0, 0, 0, 43, 44, 1, 0, 0, 0, 44, 46, 1, 0, 0, 0, 45, 43, 1, 0, 0, 0, 46, 47, 5, 0, 0, 1, 47, 1, 1, 0, 0, 0, 48, 51, 3, 4, 2, 0, 49, 51, 3, 38, 19, 0, 50, 48, 1, 0, 0, 0, 50, 49, 1, 0, 0, 0, 51, 3, 1, 0, 0, 0, 52, 53, 3, 6, 3, 0, 53, 55, 5, 18, 0, 0, 54, 56, 3, 8, 4, 0, 55, 54, 1, 0, 0, 0, 56, 57, 1, 0, 0, 0, 57, 55, 1, 0, 0, 0, 57, 58, 1, 0, 0, 0, 58, 59, 1, 0, 0, 0, 59, 60, 5, 19, 0, 0, 60, 5, 1, 0, 0, 0, 61, 62, 5, 6, 0, 0, 62, 63, 5, 21, 0, 0, 63, 7, 1, 0, 0, 0, 64, 75, 3, 10, 5, 0, 65, 75, 3, 12, 6, 0, 66, 75, 3, 14, 7, 0, 67, 75, 3, 16, 8, 0, 68, 75, 3, 18, 9, 0, 69, 75, 3, 20, 10, 0, 70, 75, 3, 22, 11, 0, 71, 75, 3, 24, 12, 0, 72, 75, 3, 26, 13, 0, 73, 75, 3, 28, 14, 0, 74, 64, 1, 0, 0, 0, 74, 65, 1, 0, 0, 0, 74, 66, 1, 0, 0, 0, 74, 67, 1, 0, 0, 0, 74, 68, 1, 0, 0, 0, 74, 69, 1, 0, 0, 0, 74, 70, 1, 0, 0, 0, 74, 71, 1, 0, 0, 0, 74, 72, 1, 0, 0, 0, 74, 73, 1, 0, 0, 0, 75, 9, 1, 0, 0, 0, 76, 77, 5, 7, 0, 0, 77, 78, 5, 21, 0, 0, 78, 11, 1, 0, 0, 0, 79, 80, 5, 8, 0, 0, 80, 81, 5, 21, 0, 0, 81, 13, 1, 0, 0, 0, 82, 83, 5, 9, 0, 0, 83, 84, 5, 21, 0, 0, 84, 15, 1, 0, 0, 0, 85, 86, 5, 10, 0, 0, 86, 87, 5, 21, 0, 0, 87, 17, 1, 0, 0, 0, 88, 89, 5, 11, 0, 0, 89, 90, 5, 22, 0, 0, 90, 19, 1, 0, 0, 0, 91, 92, 5, 12, 0, 0, 92, 93, 5, 23, 0, 0, 93, 21, 1, 0, 0, 0, 94, 95, 5, 13, 0, 0, 95, 96, 5, 21, 0, 0, 96, 23, 1, 0, 0, 0, 97, 98, 5, 15, 0, 0, 98, 99, 5, 20, 0, 0, 99, 25, 1, 0, 0, 0, 100, 101, 5, 16, 0, 0, 101, 27, 1, 0, 0, 0, 102, 103, 3, 6, 3, 0, 103, 105, 5, 18, 0, 0, 104, 106, 3, 30, 15, 0, 105, 104, 1, 0, 0, 0, 106, 107, 1, 0, 0, 0, 107, 105, 1, 0, 0, 0, 107, 108, 1, 0, 0, 0, 108, 109, 1, 0, 0, 0, 109, 110, 5, 19, 0, 0, 110, 29, 1, 0, 0, 0, 111, 118, 3, 12, 6, 0, 112, 118, 3, 32, 16, 0, 113, 118, 3, 20, 10, 0, 114, 118, 3, 34, 17, 0, 115, 118, 3, 36, 18, 0, 116, 118, 3, 26, 13, 0, 117, 111, 1, 0, 0, 0, 117, 112, 1, 0, 0, 0, 117, 113, 1, 0, 0, 0, 117, 114, 1, 0, 0, 0, 117, 115, 1, 0, 0, 0, 117, 116, 1, 0, 0, 0, 118, 31, 1, 0, 0, 0, 119, 121, 5, 9, 0, 0, 120, 122, 5, 21, 0, 0, 121, 120, 1, 0, 0, 0, 121, 122, 1, 0, 0, 0, 122, 33, 1, 0, 0, 0, 123, 125, 5, 13, 0, 0, 124, 126, 5, 21, 0, 0, 125, 124, 1, 0, 0, 0, 125, 126, 1, 0, 0, 0, 126, 35, 1, 0, 0, 0, 127, 128, 5, 14, 0, 0, 128, 129, 5, 21, 0, 0, 129, 37, 1, 0, 0, 0, 130, 131, 5, 17, 0, 0, 131, 132, 5, 21, 0, 0, 132, 39, 1, 0, 0, 0, 8, 43, 50, 57, 74, 107, 117, 121, 125] ================================================ FILE: src/refind_btrfs/boot/antlr4/RefindConfigParser.py ================================================ # Generated from c:/Users/Luka/Projects/Python/refind-btrfs/src/refind_btrfs/boot/antlr4/RefindConfigParser.g4 by ANTLR 4.13.1 # encoding: utf-8 from antlr4 import * from io import StringIO import sys if sys.version_info[1] > 5: from typing import TextIO else: from typing.io import TextIO def serializedATN(): return [ 4,1,23,134,2,0,7,0,2,1,7,1,2,2,7,2,2,3,7,3,2,4,7,4,2,5,7,5,2,6,7, 6,2,7,7,7,2,8,7,8,2,9,7,9,2,10,7,10,2,11,7,11,2,12,7,12,2,13,7,13, 2,14,7,14,2,15,7,15,2,16,7,16,2,17,7,17,2,18,7,18,2,19,7,19,1,0, 5,0,42,8,0,10,0,12,0,45,9,0,1,0,1,0,1,1,1,1,3,1,51,8,1,1,2,1,2,1, 2,4,2,56,8,2,11,2,12,2,57,1,2,1,2,1,3,1,3,1,3,1,4,1,4,1,4,1,4,1, 4,1,4,1,4,1,4,1,4,1,4,3,4,75,8,4,1,5,1,5,1,5,1,6,1,6,1,6,1,7,1,7, 1,7,1,8,1,8,1,8,1,9,1,9,1,9,1,10,1,10,1,10,1,11,1,11,1,11,1,12,1, 12,1,12,1,13,1,13,1,14,1,14,1,14,4,14,106,8,14,11,14,12,14,107,1, 14,1,14,1,15,1,15,1,15,1,15,1,15,1,15,3,15,118,8,15,1,16,1,16,3, 16,122,8,16,1,17,1,17,3,17,126,8,17,1,18,1,18,1,18,1,19,1,19,1,19, 1,19,0,0,20,0,2,4,6,8,10,12,14,16,18,20,22,24,26,28,30,32,34,36, 38,0,0,133,0,43,1,0,0,0,2,50,1,0,0,0,4,52,1,0,0,0,6,61,1,0,0,0,8, 74,1,0,0,0,10,76,1,0,0,0,12,79,1,0,0,0,14,82,1,0,0,0,16,85,1,0,0, 0,18,88,1,0,0,0,20,91,1,0,0,0,22,94,1,0,0,0,24,97,1,0,0,0,26,100, 1,0,0,0,28,102,1,0,0,0,30,117,1,0,0,0,32,119,1,0,0,0,34,123,1,0, 0,0,36,127,1,0,0,0,38,130,1,0,0,0,40,42,3,2,1,0,41,40,1,0,0,0,42, 45,1,0,0,0,43,41,1,0,0,0,43,44,1,0,0,0,44,46,1,0,0,0,45,43,1,0,0, 0,46,47,5,0,0,1,47,1,1,0,0,0,48,51,3,4,2,0,49,51,3,38,19,0,50,48, 1,0,0,0,50,49,1,0,0,0,51,3,1,0,0,0,52,53,3,6,3,0,53,55,5,18,0,0, 54,56,3,8,4,0,55,54,1,0,0,0,56,57,1,0,0,0,57,55,1,0,0,0,57,58,1, 0,0,0,58,59,1,0,0,0,59,60,5,19,0,0,60,5,1,0,0,0,61,62,5,6,0,0,62, 63,5,21,0,0,63,7,1,0,0,0,64,75,3,10,5,0,65,75,3,12,6,0,66,75,3,14, 7,0,67,75,3,16,8,0,68,75,3,18,9,0,69,75,3,20,10,0,70,75,3,22,11, 0,71,75,3,24,12,0,72,75,3,26,13,0,73,75,3,28,14,0,74,64,1,0,0,0, 74,65,1,0,0,0,74,66,1,0,0,0,74,67,1,0,0,0,74,68,1,0,0,0,74,69,1, 0,0,0,74,70,1,0,0,0,74,71,1,0,0,0,74,72,1,0,0,0,74,73,1,0,0,0,75, 9,1,0,0,0,76,77,5,7,0,0,77,78,5,21,0,0,78,11,1,0,0,0,79,80,5,8,0, 0,80,81,5,21,0,0,81,13,1,0,0,0,82,83,5,9,0,0,83,84,5,21,0,0,84,15, 1,0,0,0,85,86,5,10,0,0,86,87,5,21,0,0,87,17,1,0,0,0,88,89,5,11,0, 0,89,90,5,22,0,0,90,19,1,0,0,0,91,92,5,12,0,0,92,93,5,23,0,0,93, 21,1,0,0,0,94,95,5,13,0,0,95,96,5,21,0,0,96,23,1,0,0,0,97,98,5,15, 0,0,98,99,5,20,0,0,99,25,1,0,0,0,100,101,5,16,0,0,101,27,1,0,0,0, 102,103,3,6,3,0,103,105,5,18,0,0,104,106,3,30,15,0,105,104,1,0,0, 0,106,107,1,0,0,0,107,105,1,0,0,0,107,108,1,0,0,0,108,109,1,0,0, 0,109,110,5,19,0,0,110,29,1,0,0,0,111,118,3,12,6,0,112,118,3,32, 16,0,113,118,3,20,10,0,114,118,3,34,17,0,115,118,3,36,18,0,116,118, 3,26,13,0,117,111,1,0,0,0,117,112,1,0,0,0,117,113,1,0,0,0,117,114, 1,0,0,0,117,115,1,0,0,0,117,116,1,0,0,0,118,31,1,0,0,0,119,121,5, 9,0,0,120,122,5,21,0,0,121,120,1,0,0,0,121,122,1,0,0,0,122,33,1, 0,0,0,123,125,5,13,0,0,124,126,5,21,0,0,125,124,1,0,0,0,125,126, 1,0,0,0,126,35,1,0,0,0,127,128,5,14,0,0,128,129,5,21,0,0,129,37, 1,0,0,0,130,131,5,17,0,0,131,132,5,21,0,0,132,39,1,0,0,0,8,43,50, 57,74,107,117,121,125 ] class RefindConfigParser ( Parser ): grammarFileName = "RefindConfigParser.g4" atn = ATNDeserializer().deserialize(serializedATN()) decisionsToDFA = [ DFA(ds, i) for i, ds in enumerate(atn.decisionToState) ] sharedContextCache = PredictionContextCache() literalNames = [ "", "", "", "", "", "", "", "'volume'", "'loader'", "'initrd'", "'icon'", "", "", "'options'", "'add_options'", "'firmware_bootnum'", "'disabled'", "'include'", "'{'", "'}'" ] symbolicNames = [ "", "WHITESPACE", "NEWLINE", "EMPTY", "COMMENT", "IGNORED_OPTION", "MENU_ENTRY", "VOLUME", "LOADER", "INITRD", "ICON", "OS_TYPE", "GRAPHICS", "BOOT_OPTIONS", "ADD_BOOT_OPTIONS", "FIRMWARE_BOOTNUM", "DISABLED", "INCLUDE", "OPEN_BRACE", "CLOSE_BRACE", "HEX_INTEGER", "STRING", "OS_TYPE_PARAMETER", "GRAPHICS_PARAMETER" ] RULE_refind = 0 RULE_config_option = 1 RULE_boot_stanza = 2 RULE_menu_entry = 3 RULE_main_option = 4 RULE_volume = 5 RULE_loader = 6 RULE_main_initrd = 7 RULE_icon = 8 RULE_os_type = 9 RULE_graphics = 10 RULE_main_boot_options = 11 RULE_firmware_bootnum = 12 RULE_disabled = 13 RULE_sub_menu = 14 RULE_sub_option = 15 RULE_sub_initrd = 16 RULE_sub_boot_options = 17 RULE_add_boot_options = 18 RULE_include = 19 ruleNames = [ "refind", "config_option", "boot_stanza", "menu_entry", "main_option", "volume", "loader", "main_initrd", "icon", "os_type", "graphics", "main_boot_options", "firmware_bootnum", "disabled", "sub_menu", "sub_option", "sub_initrd", "sub_boot_options", "add_boot_options", "include" ] EOF = Token.EOF WHITESPACE=1 NEWLINE=2 EMPTY=3 COMMENT=4 IGNORED_OPTION=5 MENU_ENTRY=6 VOLUME=7 LOADER=8 INITRD=9 ICON=10 OS_TYPE=11 GRAPHICS=12 BOOT_OPTIONS=13 ADD_BOOT_OPTIONS=14 FIRMWARE_BOOTNUM=15 DISABLED=16 INCLUDE=17 OPEN_BRACE=18 CLOSE_BRACE=19 HEX_INTEGER=20 STRING=21 OS_TYPE_PARAMETER=22 GRAPHICS_PARAMETER=23 def __init__(self, input:TokenStream, output:TextIO = sys.stdout): super().__init__(input, output) self.checkVersion("4.13.1") self._interp = ParserATNSimulator(self, self.atn, self.decisionsToDFA, self.sharedContextCache) self._predicates = None class RefindContext(ParserRuleContext): __slots__ = 'parser' def __init__(self, parser, parent:ParserRuleContext=None, invokingState:int=-1): super().__init__(parent, invokingState) self.parser = parser def EOF(self): return self.getToken(RefindConfigParser.EOF, 0) def config_option(self, i:int=None): if i is None: return self.getTypedRuleContexts(RefindConfigParser.Config_optionContext) else: return self.getTypedRuleContext(RefindConfigParser.Config_optionContext,i) def getRuleIndex(self): return RefindConfigParser.RULE_refind def accept(self, visitor:ParseTreeVisitor): if hasattr( visitor, "visitRefind" ): return visitor.visitRefind(self) else: return visitor.visitChildren(self) def refind(self): localctx = RefindConfigParser.RefindContext(self, self._ctx, self.state) self.enterRule(localctx, 0, self.RULE_refind) self._la = 0 # Token type try: self.enterOuterAlt(localctx, 1) self.state = 43 self._errHandler.sync(self) _la = self._input.LA(1) while _la==6 or _la==17: self.state = 40 self.config_option() self.state = 45 self._errHandler.sync(self) _la = self._input.LA(1) self.state = 46 self.match(RefindConfigParser.EOF) except RecognitionException as re: localctx.exception = re self._errHandler.reportError(self, re) self._errHandler.recover(self, re) finally: self.exitRule() return localctx class Config_optionContext(ParserRuleContext): __slots__ = 'parser' def __init__(self, parser, parent:ParserRuleContext=None, invokingState:int=-1): super().__init__(parent, invokingState) self.parser = parser def boot_stanza(self): return self.getTypedRuleContext(RefindConfigParser.Boot_stanzaContext,0) def include(self): return self.getTypedRuleContext(RefindConfigParser.IncludeContext,0) def getRuleIndex(self): return RefindConfigParser.RULE_config_option def accept(self, visitor:ParseTreeVisitor): if hasattr( visitor, "visitConfig_option" ): return visitor.visitConfig_option(self) else: return visitor.visitChildren(self) def config_option(self): localctx = RefindConfigParser.Config_optionContext(self, self._ctx, self.state) self.enterRule(localctx, 2, self.RULE_config_option) try: self.state = 50 self._errHandler.sync(self) token = self._input.LA(1) if token in [6]: self.enterOuterAlt(localctx, 1) self.state = 48 self.boot_stanza() pass elif token in [17]: self.enterOuterAlt(localctx, 2) self.state = 49 self.include() pass else: raise NoViableAltException(self) except RecognitionException as re: localctx.exception = re self._errHandler.reportError(self, re) self._errHandler.recover(self, re) finally: self.exitRule() return localctx class Boot_stanzaContext(ParserRuleContext): __slots__ = 'parser' def __init__(self, parser, parent:ParserRuleContext=None, invokingState:int=-1): super().__init__(parent, invokingState) self.parser = parser def menu_entry(self): return self.getTypedRuleContext(RefindConfigParser.Menu_entryContext,0) def OPEN_BRACE(self): return self.getToken(RefindConfigParser.OPEN_BRACE, 0) def CLOSE_BRACE(self): return self.getToken(RefindConfigParser.CLOSE_BRACE, 0) def main_option(self, i:int=None): if i is None: return self.getTypedRuleContexts(RefindConfigParser.Main_optionContext) else: return self.getTypedRuleContext(RefindConfigParser.Main_optionContext,i) def getRuleIndex(self): return RefindConfigParser.RULE_boot_stanza def accept(self, visitor:ParseTreeVisitor): if hasattr( visitor, "visitBoot_stanza" ): return visitor.visitBoot_stanza(self) else: return visitor.visitChildren(self) def boot_stanza(self): localctx = RefindConfigParser.Boot_stanzaContext(self, self._ctx, self.state) self.enterRule(localctx, 4, self.RULE_boot_stanza) self._la = 0 # Token type try: self.enterOuterAlt(localctx, 1) self.state = 52 self.menu_entry() self.state = 53 self.match(RefindConfigParser.OPEN_BRACE) self.state = 55 self._errHandler.sync(self) _la = self._input.LA(1) while True: self.state = 54 self.main_option() self.state = 57 self._errHandler.sync(self) _la = self._input.LA(1) if not ((((_la) & ~0x3f) == 0 and ((1 << _la) & 114624) != 0)): break self.state = 59 self.match(RefindConfigParser.CLOSE_BRACE) except RecognitionException as re: localctx.exception = re self._errHandler.reportError(self, re) self._errHandler.recover(self, re) finally: self.exitRule() return localctx class Menu_entryContext(ParserRuleContext): __slots__ = 'parser' def __init__(self, parser, parent:ParserRuleContext=None, invokingState:int=-1): super().__init__(parent, invokingState) self.parser = parser def MENU_ENTRY(self): return self.getToken(RefindConfigParser.MENU_ENTRY, 0) def STRING(self): return self.getToken(RefindConfigParser.STRING, 0) def getRuleIndex(self): return RefindConfigParser.RULE_menu_entry def accept(self, visitor:ParseTreeVisitor): if hasattr( visitor, "visitMenu_entry" ): return visitor.visitMenu_entry(self) else: return visitor.visitChildren(self) def menu_entry(self): localctx = RefindConfigParser.Menu_entryContext(self, self._ctx, self.state) self.enterRule(localctx, 6, self.RULE_menu_entry) try: self.enterOuterAlt(localctx, 1) self.state = 61 self.match(RefindConfigParser.MENU_ENTRY) self.state = 62 self.match(RefindConfigParser.STRING) except RecognitionException as re: localctx.exception = re self._errHandler.reportError(self, re) self._errHandler.recover(self, re) finally: self.exitRule() return localctx class Main_optionContext(ParserRuleContext): __slots__ = 'parser' def __init__(self, parser, parent:ParserRuleContext=None, invokingState:int=-1): super().__init__(parent, invokingState) self.parser = parser def volume(self): return self.getTypedRuleContext(RefindConfigParser.VolumeContext,0) def loader(self): return self.getTypedRuleContext(RefindConfigParser.LoaderContext,0) def main_initrd(self): return self.getTypedRuleContext(RefindConfigParser.Main_initrdContext,0) def icon(self): return self.getTypedRuleContext(RefindConfigParser.IconContext,0) def os_type(self): return self.getTypedRuleContext(RefindConfigParser.Os_typeContext,0) def graphics(self): return self.getTypedRuleContext(RefindConfigParser.GraphicsContext,0) def main_boot_options(self): return self.getTypedRuleContext(RefindConfigParser.Main_boot_optionsContext,0) def firmware_bootnum(self): return self.getTypedRuleContext(RefindConfigParser.Firmware_bootnumContext,0) def disabled(self): return self.getTypedRuleContext(RefindConfigParser.DisabledContext,0) def sub_menu(self): return self.getTypedRuleContext(RefindConfigParser.Sub_menuContext,0) def getRuleIndex(self): return RefindConfigParser.RULE_main_option def accept(self, visitor:ParseTreeVisitor): if hasattr( visitor, "visitMain_option" ): return visitor.visitMain_option(self) else: return visitor.visitChildren(self) def main_option(self): localctx = RefindConfigParser.Main_optionContext(self, self._ctx, self.state) self.enterRule(localctx, 8, self.RULE_main_option) try: self.state = 74 self._errHandler.sync(self) token = self._input.LA(1) if token in [7]: self.enterOuterAlt(localctx, 1) self.state = 64 self.volume() pass elif token in [8]: self.enterOuterAlt(localctx, 2) self.state = 65 self.loader() pass elif token in [9]: self.enterOuterAlt(localctx, 3) self.state = 66 self.main_initrd() pass elif token in [10]: self.enterOuterAlt(localctx, 4) self.state = 67 self.icon() pass elif token in [11]: self.enterOuterAlt(localctx, 5) self.state = 68 self.os_type() pass elif token in [12]: self.enterOuterAlt(localctx, 6) self.state = 69 self.graphics() pass elif token in [13]: self.enterOuterAlt(localctx, 7) self.state = 70 self.main_boot_options() pass elif token in [15]: self.enterOuterAlt(localctx, 8) self.state = 71 self.firmware_bootnum() pass elif token in [16]: self.enterOuterAlt(localctx, 9) self.state = 72 self.disabled() pass elif token in [6]: self.enterOuterAlt(localctx, 10) self.state = 73 self.sub_menu() pass else: raise NoViableAltException(self) except RecognitionException as re: localctx.exception = re self._errHandler.reportError(self, re) self._errHandler.recover(self, re) finally: self.exitRule() return localctx class VolumeContext(ParserRuleContext): __slots__ = 'parser' def __init__(self, parser, parent:ParserRuleContext=None, invokingState:int=-1): super().__init__(parent, invokingState) self.parser = parser def VOLUME(self): return self.getToken(RefindConfigParser.VOLUME, 0) def STRING(self): return self.getToken(RefindConfigParser.STRING, 0) def getRuleIndex(self): return RefindConfigParser.RULE_volume def accept(self, visitor:ParseTreeVisitor): if hasattr( visitor, "visitVolume" ): return visitor.visitVolume(self) else: return visitor.visitChildren(self) def volume(self): localctx = RefindConfigParser.VolumeContext(self, self._ctx, self.state) self.enterRule(localctx, 10, self.RULE_volume) try: self.enterOuterAlt(localctx, 1) self.state = 76 self.match(RefindConfigParser.VOLUME) self.state = 77 self.match(RefindConfigParser.STRING) except RecognitionException as re: localctx.exception = re self._errHandler.reportError(self, re) self._errHandler.recover(self, re) finally: self.exitRule() return localctx class LoaderContext(ParserRuleContext): __slots__ = 'parser' def __init__(self, parser, parent:ParserRuleContext=None, invokingState:int=-1): super().__init__(parent, invokingState) self.parser = parser def LOADER(self): return self.getToken(RefindConfigParser.LOADER, 0) def STRING(self): return self.getToken(RefindConfigParser.STRING, 0) def getRuleIndex(self): return RefindConfigParser.RULE_loader def accept(self, visitor:ParseTreeVisitor): if hasattr( visitor, "visitLoader" ): return visitor.visitLoader(self) else: return visitor.visitChildren(self) def loader(self): localctx = RefindConfigParser.LoaderContext(self, self._ctx, self.state) self.enterRule(localctx, 12, self.RULE_loader) try: self.enterOuterAlt(localctx, 1) self.state = 79 self.match(RefindConfigParser.LOADER) self.state = 80 self.match(RefindConfigParser.STRING) except RecognitionException as re: localctx.exception = re self._errHandler.reportError(self, re) self._errHandler.recover(self, re) finally: self.exitRule() return localctx class Main_initrdContext(ParserRuleContext): __slots__ = 'parser' def __init__(self, parser, parent:ParserRuleContext=None, invokingState:int=-1): super().__init__(parent, invokingState) self.parser = parser def INITRD(self): return self.getToken(RefindConfigParser.INITRD, 0) def STRING(self): return self.getToken(RefindConfigParser.STRING, 0) def getRuleIndex(self): return RefindConfigParser.RULE_main_initrd def accept(self, visitor:ParseTreeVisitor): if hasattr( visitor, "visitMain_initrd" ): return visitor.visitMain_initrd(self) else: return visitor.visitChildren(self) def main_initrd(self): localctx = RefindConfigParser.Main_initrdContext(self, self._ctx, self.state) self.enterRule(localctx, 14, self.RULE_main_initrd) try: self.enterOuterAlt(localctx, 1) self.state = 82 self.match(RefindConfigParser.INITRD) self.state = 83 self.match(RefindConfigParser.STRING) except RecognitionException as re: localctx.exception = re self._errHandler.reportError(self, re) self._errHandler.recover(self, re) finally: self.exitRule() return localctx class IconContext(ParserRuleContext): __slots__ = 'parser' def __init__(self, parser, parent:ParserRuleContext=None, invokingState:int=-1): super().__init__(parent, invokingState) self.parser = parser def ICON(self): return self.getToken(RefindConfigParser.ICON, 0) def STRING(self): return self.getToken(RefindConfigParser.STRING, 0) def getRuleIndex(self): return RefindConfigParser.RULE_icon def accept(self, visitor:ParseTreeVisitor): if hasattr( visitor, "visitIcon" ): return visitor.visitIcon(self) else: return visitor.visitChildren(self) def icon(self): localctx = RefindConfigParser.IconContext(self, self._ctx, self.state) self.enterRule(localctx, 16, self.RULE_icon) try: self.enterOuterAlt(localctx, 1) self.state = 85 self.match(RefindConfigParser.ICON) self.state = 86 self.match(RefindConfigParser.STRING) except RecognitionException as re: localctx.exception = re self._errHandler.reportError(self, re) self._errHandler.recover(self, re) finally: self.exitRule() return localctx class Os_typeContext(ParserRuleContext): __slots__ = 'parser' def __init__(self, parser, parent:ParserRuleContext=None, invokingState:int=-1): super().__init__(parent, invokingState) self.parser = parser def OS_TYPE(self): return self.getToken(RefindConfigParser.OS_TYPE, 0) def OS_TYPE_PARAMETER(self): return self.getToken(RefindConfigParser.OS_TYPE_PARAMETER, 0) def getRuleIndex(self): return RefindConfigParser.RULE_os_type def accept(self, visitor:ParseTreeVisitor): if hasattr( visitor, "visitOs_type" ): return visitor.visitOs_type(self) else: return visitor.visitChildren(self) def os_type(self): localctx = RefindConfigParser.Os_typeContext(self, self._ctx, self.state) self.enterRule(localctx, 18, self.RULE_os_type) try: self.enterOuterAlt(localctx, 1) self.state = 88 self.match(RefindConfigParser.OS_TYPE) self.state = 89 self.match(RefindConfigParser.OS_TYPE_PARAMETER) except RecognitionException as re: localctx.exception = re self._errHandler.reportError(self, re) self._errHandler.recover(self, re) finally: self.exitRule() return localctx class GraphicsContext(ParserRuleContext): __slots__ = 'parser' def __init__(self, parser, parent:ParserRuleContext=None, invokingState:int=-1): super().__init__(parent, invokingState) self.parser = parser def GRAPHICS(self): return self.getToken(RefindConfigParser.GRAPHICS, 0) def GRAPHICS_PARAMETER(self): return self.getToken(RefindConfigParser.GRAPHICS_PARAMETER, 0) def getRuleIndex(self): return RefindConfigParser.RULE_graphics def accept(self, visitor:ParseTreeVisitor): if hasattr( visitor, "visitGraphics" ): return visitor.visitGraphics(self) else: return visitor.visitChildren(self) def graphics(self): localctx = RefindConfigParser.GraphicsContext(self, self._ctx, self.state) self.enterRule(localctx, 20, self.RULE_graphics) try: self.enterOuterAlt(localctx, 1) self.state = 91 self.match(RefindConfigParser.GRAPHICS) self.state = 92 self.match(RefindConfigParser.GRAPHICS_PARAMETER) except RecognitionException as re: localctx.exception = re self._errHandler.reportError(self, re) self._errHandler.recover(self, re) finally: self.exitRule() return localctx class Main_boot_optionsContext(ParserRuleContext): __slots__ = 'parser' def __init__(self, parser, parent:ParserRuleContext=None, invokingState:int=-1): super().__init__(parent, invokingState) self.parser = parser def BOOT_OPTIONS(self): return self.getToken(RefindConfigParser.BOOT_OPTIONS, 0) def STRING(self): return self.getToken(RefindConfigParser.STRING, 0) def getRuleIndex(self): return RefindConfigParser.RULE_main_boot_options def accept(self, visitor:ParseTreeVisitor): if hasattr( visitor, "visitMain_boot_options" ): return visitor.visitMain_boot_options(self) else: return visitor.visitChildren(self) def main_boot_options(self): localctx = RefindConfigParser.Main_boot_optionsContext(self, self._ctx, self.state) self.enterRule(localctx, 22, self.RULE_main_boot_options) try: self.enterOuterAlt(localctx, 1) self.state = 94 self.match(RefindConfigParser.BOOT_OPTIONS) self.state = 95 self.match(RefindConfigParser.STRING) except RecognitionException as re: localctx.exception = re self._errHandler.reportError(self, re) self._errHandler.recover(self, re) finally: self.exitRule() return localctx class Firmware_bootnumContext(ParserRuleContext): __slots__ = 'parser' def __init__(self, parser, parent:ParserRuleContext=None, invokingState:int=-1): super().__init__(parent, invokingState) self.parser = parser def FIRMWARE_BOOTNUM(self): return self.getToken(RefindConfigParser.FIRMWARE_BOOTNUM, 0) def HEX_INTEGER(self): return self.getToken(RefindConfigParser.HEX_INTEGER, 0) def getRuleIndex(self): return RefindConfigParser.RULE_firmware_bootnum def accept(self, visitor:ParseTreeVisitor): if hasattr( visitor, "visitFirmware_bootnum" ): return visitor.visitFirmware_bootnum(self) else: return visitor.visitChildren(self) def firmware_bootnum(self): localctx = RefindConfigParser.Firmware_bootnumContext(self, self._ctx, self.state) self.enterRule(localctx, 24, self.RULE_firmware_bootnum) try: self.enterOuterAlt(localctx, 1) self.state = 97 self.match(RefindConfigParser.FIRMWARE_BOOTNUM) self.state = 98 self.match(RefindConfigParser.HEX_INTEGER) except RecognitionException as re: localctx.exception = re self._errHandler.reportError(self, re) self._errHandler.recover(self, re) finally: self.exitRule() return localctx class DisabledContext(ParserRuleContext): __slots__ = 'parser' def __init__(self, parser, parent:ParserRuleContext=None, invokingState:int=-1): super().__init__(parent, invokingState) self.parser = parser def DISABLED(self): return self.getToken(RefindConfigParser.DISABLED, 0) def getRuleIndex(self): return RefindConfigParser.RULE_disabled def accept(self, visitor:ParseTreeVisitor): if hasattr( visitor, "visitDisabled" ): return visitor.visitDisabled(self) else: return visitor.visitChildren(self) def disabled(self): localctx = RefindConfigParser.DisabledContext(self, self._ctx, self.state) self.enterRule(localctx, 26, self.RULE_disabled) try: self.enterOuterAlt(localctx, 1) self.state = 100 self.match(RefindConfigParser.DISABLED) except RecognitionException as re: localctx.exception = re self._errHandler.reportError(self, re) self._errHandler.recover(self, re) finally: self.exitRule() return localctx class Sub_menuContext(ParserRuleContext): __slots__ = 'parser' def __init__(self, parser, parent:ParserRuleContext=None, invokingState:int=-1): super().__init__(parent, invokingState) self.parser = parser def menu_entry(self): return self.getTypedRuleContext(RefindConfigParser.Menu_entryContext,0) def OPEN_BRACE(self): return self.getToken(RefindConfigParser.OPEN_BRACE, 0) def CLOSE_BRACE(self): return self.getToken(RefindConfigParser.CLOSE_BRACE, 0) def sub_option(self, i:int=None): if i is None: return self.getTypedRuleContexts(RefindConfigParser.Sub_optionContext) else: return self.getTypedRuleContext(RefindConfigParser.Sub_optionContext,i) def getRuleIndex(self): return RefindConfigParser.RULE_sub_menu def accept(self, visitor:ParseTreeVisitor): if hasattr( visitor, "visitSub_menu" ): return visitor.visitSub_menu(self) else: return visitor.visitChildren(self) def sub_menu(self): localctx = RefindConfigParser.Sub_menuContext(self, self._ctx, self.state) self.enterRule(localctx, 28, self.RULE_sub_menu) self._la = 0 # Token type try: self.enterOuterAlt(localctx, 1) self.state = 102 self.menu_entry() self.state = 103 self.match(RefindConfigParser.OPEN_BRACE) self.state = 105 self._errHandler.sync(self) _la = self._input.LA(1) while True: self.state = 104 self.sub_option() self.state = 107 self._errHandler.sync(self) _la = self._input.LA(1) if not ((((_la) & ~0x3f) == 0 and ((1 << _la) & 94976) != 0)): break self.state = 109 self.match(RefindConfigParser.CLOSE_BRACE) except RecognitionException as re: localctx.exception = re self._errHandler.reportError(self, re) self._errHandler.recover(self, re) finally: self.exitRule() return localctx class Sub_optionContext(ParserRuleContext): __slots__ = 'parser' def __init__(self, parser, parent:ParserRuleContext=None, invokingState:int=-1): super().__init__(parent, invokingState) self.parser = parser def loader(self): return self.getTypedRuleContext(RefindConfigParser.LoaderContext,0) def sub_initrd(self): return self.getTypedRuleContext(RefindConfigParser.Sub_initrdContext,0) def graphics(self): return self.getTypedRuleContext(RefindConfigParser.GraphicsContext,0) def sub_boot_options(self): return self.getTypedRuleContext(RefindConfigParser.Sub_boot_optionsContext,0) def add_boot_options(self): return self.getTypedRuleContext(RefindConfigParser.Add_boot_optionsContext,0) def disabled(self): return self.getTypedRuleContext(RefindConfigParser.DisabledContext,0) def getRuleIndex(self): return RefindConfigParser.RULE_sub_option def accept(self, visitor:ParseTreeVisitor): if hasattr( visitor, "visitSub_option" ): return visitor.visitSub_option(self) else: return visitor.visitChildren(self) def sub_option(self): localctx = RefindConfigParser.Sub_optionContext(self, self._ctx, self.state) self.enterRule(localctx, 30, self.RULE_sub_option) try: self.state = 117 self._errHandler.sync(self) token = self._input.LA(1) if token in [8]: self.enterOuterAlt(localctx, 1) self.state = 111 self.loader() pass elif token in [9]: self.enterOuterAlt(localctx, 2) self.state = 112 self.sub_initrd() pass elif token in [12]: self.enterOuterAlt(localctx, 3) self.state = 113 self.graphics() pass elif token in [13]: self.enterOuterAlt(localctx, 4) self.state = 114 self.sub_boot_options() pass elif token in [14]: self.enterOuterAlt(localctx, 5) self.state = 115 self.add_boot_options() pass elif token in [16]: self.enterOuterAlt(localctx, 6) self.state = 116 self.disabled() pass else: raise NoViableAltException(self) except RecognitionException as re: localctx.exception = re self._errHandler.reportError(self, re) self._errHandler.recover(self, re) finally: self.exitRule() return localctx class Sub_initrdContext(ParserRuleContext): __slots__ = 'parser' def __init__(self, parser, parent:ParserRuleContext=None, invokingState:int=-1): super().__init__(parent, invokingState) self.parser = parser def INITRD(self): return self.getToken(RefindConfigParser.INITRD, 0) def STRING(self): return self.getToken(RefindConfigParser.STRING, 0) def getRuleIndex(self): return RefindConfigParser.RULE_sub_initrd def accept(self, visitor:ParseTreeVisitor): if hasattr( visitor, "visitSub_initrd" ): return visitor.visitSub_initrd(self) else: return visitor.visitChildren(self) def sub_initrd(self): localctx = RefindConfigParser.Sub_initrdContext(self, self._ctx, self.state) self.enterRule(localctx, 32, self.RULE_sub_initrd) self._la = 0 # Token type try: self.enterOuterAlt(localctx, 1) self.state = 119 self.match(RefindConfigParser.INITRD) self.state = 121 self._errHandler.sync(self) _la = self._input.LA(1) if _la==21: self.state = 120 self.match(RefindConfigParser.STRING) except RecognitionException as re: localctx.exception = re self._errHandler.reportError(self, re) self._errHandler.recover(self, re) finally: self.exitRule() return localctx class Sub_boot_optionsContext(ParserRuleContext): __slots__ = 'parser' def __init__(self, parser, parent:ParserRuleContext=None, invokingState:int=-1): super().__init__(parent, invokingState) self.parser = parser def BOOT_OPTIONS(self): return self.getToken(RefindConfigParser.BOOT_OPTIONS, 0) def STRING(self): return self.getToken(RefindConfigParser.STRING, 0) def getRuleIndex(self): return RefindConfigParser.RULE_sub_boot_options def accept(self, visitor:ParseTreeVisitor): if hasattr( visitor, "visitSub_boot_options" ): return visitor.visitSub_boot_options(self) else: return visitor.visitChildren(self) def sub_boot_options(self): localctx = RefindConfigParser.Sub_boot_optionsContext(self, self._ctx, self.state) self.enterRule(localctx, 34, self.RULE_sub_boot_options) self._la = 0 # Token type try: self.enterOuterAlt(localctx, 1) self.state = 123 self.match(RefindConfigParser.BOOT_OPTIONS) self.state = 125 self._errHandler.sync(self) _la = self._input.LA(1) if _la==21: self.state = 124 self.match(RefindConfigParser.STRING) except RecognitionException as re: localctx.exception = re self._errHandler.reportError(self, re) self._errHandler.recover(self, re) finally: self.exitRule() return localctx class Add_boot_optionsContext(ParserRuleContext): __slots__ = 'parser' def __init__(self, parser, parent:ParserRuleContext=None, invokingState:int=-1): super().__init__(parent, invokingState) self.parser = parser def ADD_BOOT_OPTIONS(self): return self.getToken(RefindConfigParser.ADD_BOOT_OPTIONS, 0) def STRING(self): return self.getToken(RefindConfigParser.STRING, 0) def getRuleIndex(self): return RefindConfigParser.RULE_add_boot_options def accept(self, visitor:ParseTreeVisitor): if hasattr( visitor, "visitAdd_boot_options" ): return visitor.visitAdd_boot_options(self) else: return visitor.visitChildren(self) def add_boot_options(self): localctx = RefindConfigParser.Add_boot_optionsContext(self, self._ctx, self.state) self.enterRule(localctx, 36, self.RULE_add_boot_options) try: self.enterOuterAlt(localctx, 1) self.state = 127 self.match(RefindConfigParser.ADD_BOOT_OPTIONS) self.state = 128 self.match(RefindConfigParser.STRING) except RecognitionException as re: localctx.exception = re self._errHandler.reportError(self, re) self._errHandler.recover(self, re) finally: self.exitRule() return localctx class IncludeContext(ParserRuleContext): __slots__ = 'parser' def __init__(self, parser, parent:ParserRuleContext=None, invokingState:int=-1): super().__init__(parent, invokingState) self.parser = parser def INCLUDE(self): return self.getToken(RefindConfigParser.INCLUDE, 0) def STRING(self): return self.getToken(RefindConfigParser.STRING, 0) def getRuleIndex(self): return RefindConfigParser.RULE_include def accept(self, visitor:ParseTreeVisitor): if hasattr( visitor, "visitInclude" ): return visitor.visitInclude(self) else: return visitor.visitChildren(self) def include(self): localctx = RefindConfigParser.IncludeContext(self, self._ctx, self.state) self.enterRule(localctx, 38, self.RULE_include) try: self.enterOuterAlt(localctx, 1) self.state = 130 self.match(RefindConfigParser.INCLUDE) self.state = 131 self.match(RefindConfigParser.STRING) except RecognitionException as re: localctx.exception = re self._errHandler.reportError(self, re) self._errHandler.recover(self, re) finally: self.exitRule() return localctx ================================================ FILE: src/refind_btrfs/boot/antlr4/RefindConfigParser.tokens ================================================ WHITESPACE=1 NEWLINE=2 EMPTY=3 COMMENT=4 IGNORED_OPTION=5 MENU_ENTRY=6 VOLUME=7 LOADER=8 INITRD=9 ICON=10 OS_TYPE=11 GRAPHICS=12 BOOT_OPTIONS=13 ADD_BOOT_OPTIONS=14 FIRMWARE_BOOTNUM=15 DISABLED=16 INCLUDE=17 OPEN_BRACE=18 CLOSE_BRACE=19 HEX_INTEGER=20 STRING=21 OS_TYPE_PARAMETER=22 GRAPHICS_PARAMETER=23 'volume'=7 'loader'=8 'initrd'=9 'icon'=10 'options'=13 'add_options'=14 'firmware_bootnum'=15 'disabled'=16 'include'=17 '{'=18 '}'=19 ================================================ FILE: src/refind_btrfs/boot/antlr4/RefindConfigParserVisitor.py ================================================ # Generated from c:/Users/Luka/Projects/Python/refind-btrfs/src/refind_btrfs/boot/antlr4/RefindConfigParser.g4 by ANTLR 4.13.1 from antlr4 import * if "." in __name__: from .RefindConfigParser import RefindConfigParser else: from RefindConfigParser import RefindConfigParser # This class defines a complete generic visitor for a parse tree produced by RefindConfigParser. class RefindConfigParserVisitor(ParseTreeVisitor): # Visit a parse tree produced by RefindConfigParser#refind. def visitRefind(self, ctx:RefindConfigParser.RefindContext): return self.visitChildren(ctx) # Visit a parse tree produced by RefindConfigParser#config_option. def visitConfig_option(self, ctx:RefindConfigParser.Config_optionContext): return self.visitChildren(ctx) # Visit a parse tree produced by RefindConfigParser#boot_stanza. def visitBoot_stanza(self, ctx:RefindConfigParser.Boot_stanzaContext): return self.visitChildren(ctx) # Visit a parse tree produced by RefindConfigParser#menu_entry. def visitMenu_entry(self, ctx:RefindConfigParser.Menu_entryContext): return self.visitChildren(ctx) # Visit a parse tree produced by RefindConfigParser#main_option. def visitMain_option(self, ctx:RefindConfigParser.Main_optionContext): return self.visitChildren(ctx) # Visit a parse tree produced by RefindConfigParser#volume. def visitVolume(self, ctx:RefindConfigParser.VolumeContext): return self.visitChildren(ctx) # Visit a parse tree produced by RefindConfigParser#loader. def visitLoader(self, ctx:RefindConfigParser.LoaderContext): return self.visitChildren(ctx) # Visit a parse tree produced by RefindConfigParser#main_initrd. def visitMain_initrd(self, ctx:RefindConfigParser.Main_initrdContext): return self.visitChildren(ctx) # Visit a parse tree produced by RefindConfigParser#icon. def visitIcon(self, ctx:RefindConfigParser.IconContext): return self.visitChildren(ctx) # Visit a parse tree produced by RefindConfigParser#os_type. def visitOs_type(self, ctx:RefindConfigParser.Os_typeContext): return self.visitChildren(ctx) # Visit a parse tree produced by RefindConfigParser#graphics. def visitGraphics(self, ctx:RefindConfigParser.GraphicsContext): return self.visitChildren(ctx) # Visit a parse tree produced by RefindConfigParser#main_boot_options. def visitMain_boot_options(self, ctx:RefindConfigParser.Main_boot_optionsContext): return self.visitChildren(ctx) # Visit a parse tree produced by RefindConfigParser#firmware_bootnum. def visitFirmware_bootnum(self, ctx:RefindConfigParser.Firmware_bootnumContext): return self.visitChildren(ctx) # Visit a parse tree produced by RefindConfigParser#disabled. def visitDisabled(self, ctx:RefindConfigParser.DisabledContext): return self.visitChildren(ctx) # Visit a parse tree produced by RefindConfigParser#sub_menu. def visitSub_menu(self, ctx:RefindConfigParser.Sub_menuContext): return self.visitChildren(ctx) # Visit a parse tree produced by RefindConfigParser#sub_option. def visitSub_option(self, ctx:RefindConfigParser.Sub_optionContext): return self.visitChildren(ctx) # Visit a parse tree produced by RefindConfigParser#sub_initrd. def visitSub_initrd(self, ctx:RefindConfigParser.Sub_initrdContext): return self.visitChildren(ctx) # Visit a parse tree produced by RefindConfigParser#sub_boot_options. def visitSub_boot_options(self, ctx:RefindConfigParser.Sub_boot_optionsContext): return self.visitChildren(ctx) # Visit a parse tree produced by RefindConfigParser#add_boot_options. def visitAdd_boot_options(self, ctx:RefindConfigParser.Add_boot_optionsContext): return self.visitChildren(ctx) # Visit a parse tree produced by RefindConfigParser#include. def visitInclude(self, ctx:RefindConfigParser.IncludeContext): return self.visitChildren(ctx) del RefindConfigParser ================================================ FILE: src/refind_btrfs/boot/antlr4/__init__.py ================================================ # region Licensing # SPDX-FileCopyrightText: 2020-2024 Luka Žaja # # SPDX-License-Identifier: GPL-3.0-or-later """ refind-btrfs - Generate rEFInd manual boot stanzas from Btrfs snapshots Copyright (C) 2020-2024 Luka Žaja 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, either version 3 of the License, or (at your option) any later version. 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 . """ # endregion from .RefindConfigLexer import RefindConfigLexer from .RefindConfigParser import RefindConfigParser from .RefindConfigParserVisitor import RefindConfigParserVisitor ================================================ FILE: src/refind_btrfs/boot/boot_options.py ================================================ # region Licensing # SPDX-FileCopyrightText: 2020-2024 Luka Žaja # # SPDX-License-Identifier: GPL-3.0-or-later """ refind-btrfs - Generate rEFInd manual boot stanzas from Btrfs snapshots Copyright (C) 2020-2024 Luka Žaja 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, either version 3 of the License, or (at your option) any later version. 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 . """ # endregion from __future__ import annotations from typing import Iterable, Optional, Self from more_itertools import last from refind_btrfs.common import constants from refind_btrfs.common.exceptions import RefindConfigError from refind_btrfs.device import BlockDevice, MountOptions, Subvolume from refind_btrfs.utility.helpers import ( has_items, is_none_or_whitespace, none_throws, replace_root_part_in, strip_quotes, ) class BootOptions: def __init__(self, raw_options: Optional[str]) -> None: root_location: Optional[tuple[int, str]] = None root_mount_options: Optional[tuple[int, MountOptions]] = None initrd_options: list[tuple[int, str]] = [] other_options: list[tuple[int, str]] = [] if not is_none_or_whitespace(raw_options): split_options = strip_quotes(raw_options).split() for position, option in enumerate(split_options): if not is_none_or_whitespace(option): if option.startswith(constants.ROOT_PREFIX): normalized_option = option.removeprefix(constants.ROOT_PREFIX) if root_location is not None: root_option = constants.ROOT_PREFIX.rstrip( constants.PARAMETERIZED_OPTION_SEPARATOR ) raise RefindConfigError( f"The '{root_option}' boot option " f"cannot be defined multiple times!" ) root_location = (position, normalized_option) elif option.startswith(constants.ROOTFLAGS_PREFIX): normalized_option = option.removeprefix( constants.ROOTFLAGS_PREFIX ) if root_mount_options is not None: rootflags_option = constants.ROOTFLAGS_PREFIX.rstrip( constants.PARAMETERIZED_OPTION_SEPARATOR ) raise RefindConfigError( f"The '{rootflags_option}' boot option " f"cannot be defined multiple times!" ) root_mount_options = (position, MountOptions(normalized_option)) elif option.startswith(constants.INITRD_PREFIX): normalized_option = option.removeprefix(constants.INITRD_PREFIX) initrd_options.append((position, normalized_option)) else: other_options.append((position, option)) self._root_location = root_location self._root_mount_options = root_mount_options self._initrd_options = initrd_options self._other_options = other_options def __str__(self) -> str: root_location = self._root_location root_mount_options = self._root_mount_options initrd_options = self._initrd_options other_options = self._other_options result: list[str] = [constants.EMPTY_STR] * ( sum((len(initrd_options), len(other_options))) + (1 if root_location is not None else 0) + (1 if root_mount_options is not None else 0) ) if root_location is not None: result[root_location[0]] = constants.ROOT_PREFIX + root_location[1] if root_mount_options is not None: result[root_mount_options[0]] = constants.ROOTFLAGS_PREFIX + str( root_mount_options[1] ) if has_items(initrd_options): for initrd_option in initrd_options: result[initrd_option[0]] = constants.INITRD_PREFIX + initrd_option[1] if has_items(other_options): for other_option in other_options: result[other_option[0]] = other_option[1] if has_items(result): joined_options = constants.BOOT_OPTION_SEPARATOR.join(result) return constants.DOUBLE_QUOTE + joined_options + constants.DOUBLE_QUOTE return constants.EMPTY_STR def is_matched_with(self, block_device: BlockDevice) -> bool: if block_device.has_root(): root_location = self.root_location if root_location is not None: root_partition = none_throws(block_device.root) filesystem = none_throws(root_partition.filesystem) normalized_root_location = last( strip_quotes(root_location).split( constants.PARAMETERIZED_OPTION_SEPARATOR ) ) root_location_comparers = [ root_partition.label, root_partition.uuid, filesystem.label, filesystem.uuid, ] if ( normalized_root_location in root_location_comparers or block_device.is_matched_with(normalized_root_location) ): root_mount_options = self.root_mount_options subvolume = none_throws(filesystem.subvolume) return ( root_mount_options.is_matched_with(subvolume) if root_mount_options is not None else False ) return False def migrate_from_to( self, source_subvolume: Subvolume, destination_subvolume: Subvolume, include_paths: bool, ) -> None: root_mount_options = self.root_mount_options if root_mount_options is not None: root_mount_options.migrate_from_to(source_subvolume, destination_subvolume) if include_paths: initrd_options = self._initrd_options if has_items(initrd_options): source_logical_path = source_subvolume.logical_path destination_logical_path = destination_subvolume.logical_path self._initrd_options = [ ( initrd_option[0], replace_root_part_in( initrd_option[1], source_logical_path, destination_logical_path, ( constants.FORWARD_SLASH, constants.BACKSLASH, ), ), ) for initrd_option in initrd_options ] @classmethod def merge(cls, all_boot_options: Iterable[BootOptions]) -> Self: all_boot_options_str = [ strip_quotes(str(boot_options)) for boot_options in all_boot_options ] return cls(constants.SPACE.join(all_boot_options_str).strip()) @property def root_location(self) -> Optional[str]: root_location = self._root_location if root_location is not None: return root_location[1] return None @property def root_mount_options(self) -> Optional[MountOptions]: root_mount_options = self._root_mount_options if root_mount_options is not None: return root_mount_options[1] return None @property def initrd_options(self) -> list[str]: return [initrd_option[1] for initrd_option in self._initrd_options] @property def other_options(self) -> list[str]: return [other_option[1] for other_option in self._other_options] ================================================ FILE: src/refind_btrfs/boot/boot_stanza.py ================================================ # region Licensing # SPDX-FileCopyrightText: 2020-2024 Luka Žaja # # SPDX-License-Identifier: GPL-3.0-or-later """ refind-btrfs - Generate rEFInd manual boot stanzas from Btrfs snapshots Copyright (C) 2020-2024 Luka Žaja 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, either version 3 of the License, or (at your option) any later version. 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 . """ # endregion from __future__ import annotations import inspect import re from collections import defaultdict from functools import cached_property, singledispatchmethod from itertools import chain from typing import Any, DefaultDict, Iterable, Iterator, Optional, Self, Set from pathlib import Path from more_itertools import always_iterable, last from refind_btrfs.common import BootFilesCheckResult, constants from refind_btrfs.common.enums import ( BootFilePathSource, BootStanzaIconGenerationMode, GraphicsParameter, RefindOption, ) from refind_btrfs.common.exceptions import RefindConfigError from refind_btrfs.device import BlockDevice, Subvolume from refind_btrfs.utility.helpers import ( has_items, is_none_or_whitespace, none_throws, normalize_dir_separators_in, replace_root_part_in, strip_quotes, ) from .boot_options import BootOptions from .sub_menu import SubMenu class BootStanza: def __init__( self, name: str, volume: Optional[str], loader_path: Optional[str], initrd_path: Optional[str], icon_path: Optional[str], os_type: Optional[str], graphics: Optional[bool], boot_options: BootOptions, firmware_bootnum: Optional[int], is_disabled: bool, ) -> None: self._name = name self._volume = volume self._loader_path = loader_path self._initrd_path = initrd_path self._icon_path = icon_path self._os_type = os_type self._graphics = graphics self._boot_options = boot_options self._firmware_bootnum = firmware_bootnum self._is_disabled = is_disabled self._boot_files_check_result: Optional[BootFilesCheckResult] = None self._sub_menus: Optional[list[SubMenu]] = None def __eq__(self, other: object) -> bool: if self is other: return True if isinstance(other, BootStanza): self_boot_options = self.boot_options other_boot_options = other.boot_options return ( self.volume == other.volume and self.loader_path == other.loader_path and str(self_boot_options) == str(other_boot_options) ) return False def __hash__(self): boot_options = self.boot_options return hash((self.volume, self.loader_path, str(boot_options))) def __str__(self) -> str: result: list[str] = [] main_indent = constants.EMPTY_STR option_indent = constants.TAB name = self.name result.append(f"{main_indent}{RefindOption.MENU_ENTRY.value} {name} {{") icon_path = self.icon_path if not is_none_or_whitespace(icon_path): result.append(f"{option_indent}{RefindOption.ICON.value} {icon_path}") volume = self.volume if not is_none_or_whitespace(volume): result.append(f"{option_indent}{RefindOption.VOLUME.value} {volume}") loader_path = self.loader_path if not is_none_or_whitespace(loader_path): result.append(f"{option_indent}{RefindOption.LOADER.value} {loader_path}") initrd_path = self.initrd_path if not is_none_or_whitespace(initrd_path): result.append(f"{option_indent}{RefindOption.INITRD.value} {initrd_path}") os_type = self.os_type if not is_none_or_whitespace(os_type): result.append(f"{option_indent}{RefindOption.OS_TYPE.value} {os_type}") graphics = self.graphics if graphics is not None: graphics_parameter = ( GraphicsParameter.ON if graphics else GraphicsParameter.OFF ) result.append( f"{option_indent}{RefindOption.GRAPHICS.value} {graphics_parameter.value}" ) boot_options_str = str(self.boot_options) if not is_none_or_whitespace(boot_options_str): result.append( f"{option_indent}{RefindOption.BOOT_OPTIONS.value} {boot_options_str}" ) firmware_bootnum = self.firmware_bootnum if firmware_bootnum is not None: result.append( f"{option_indent}{RefindOption.FIRMWARE_BOOTNUM.value} {firmware_bootnum:04x}" ) sub_menus = self.sub_menus if has_items(sub_menus): result.extend(str(sub_menu) for sub_menu in none_throws(sub_menus)) is_disabled = self.is_disabled if is_disabled: result.append(f"{option_indent}{RefindOption.DISABLED.value}") result.append(f"{main_indent}}}") return constants.NEWLINE.join(result) def with_boot_files_check_result( self, subvolume: Subvolume, include_sub_menus: bool ) -> Self: normalized_name = self.normalized_name all_boot_file_paths = self.all_boot_file_paths logical_path = subvolume.logical_path matched_boot_files: list[str] = [] unmatched_boot_files: list[str] = [] sources = [BootFilePathSource.BOOT_STANZA] if include_sub_menus: sources.append(BootFilePathSource.SUB_MENU) for source in sources: boot_file_paths = always_iterable(all_boot_file_paths.get(source)) for boot_file_path in boot_file_paths: # Handle both paths with subvolume prefix (/@/boot/...) and without (/boot/...) replaced_path_str = replace_root_part_in( boot_file_path, logical_path, str(subvolume.filesystem_path) ) if replaced_path_str == boot_file_path: replaced_file_path = subvolume.filesystem_path / Path(boot_file_path).relative_to('/') else: replaced_file_path = Path(replaced_path_str) if replaced_file_path.exists(): matched_boot_files.append(boot_file_path) else: unmatched_boot_files.append(boot_file_path) self._boot_files_check_result = BootFilesCheckResult( normalized_name, logical_path, matched_boot_files, unmatched_boot_files ) return self def with_sub_menus(self, sub_menus: Iterable[SubMenu]) -> Self: self._sub_menus = list(sub_menus) return self @singledispatchmethod def is_matched_with(self, argument: Any) -> bool: frame = none_throws(inspect.currentframe()) raise NotImplementedError( f"Cannot call the '{inspect.getframeinfo(frame).function}' method " f"for parameter of type '{type(argument).__name__}'!" ) def has_unmatched_boot_files(self) -> bool: boot_files_check_result = self.boot_files_check_result if boot_files_check_result is not None: return boot_files_check_result.has_unmatched_boot_files() return False def has_sub_menus(self) -> bool: return has_items(self.sub_menus) def can_be_used_for_bootable_snapshot(self) -> bool: volume = self.volume loader_path = self.loader_path initrd_path = self.initrd_path is_disabled = self.is_disabled return ( not is_none_or_whitespace(volume) and not is_none_or_whitespace(loader_path) and not is_none_or_whitespace(initrd_path) and not is_disabled ) def validate_boot_files_check_result(self) -> None: if self.has_unmatched_boot_files(): boot_files_check_result = none_throws(self.boot_files_check_result) boot_stanza_name = boot_files_check_result.required_by_boot_stanza_name logical_path = boot_files_check_result.expected_logical_path unmatched_boot_files = boot_files_check_result.unmatched_boot_files raise RefindConfigError( f"Detected boot files required by the '{boot_stanza_name}' boot " f"stanza which are not matched with the '{logical_path}' subvolume: " f"{constants.DEFAULT_ITEMS_SEPARATOR.join(unmatched_boot_files)}!" ) def validate_icon_path( self, icon_generation_mode: BootStanzaIconGenerationMode ) -> None: if icon_generation_mode != BootStanzaIconGenerationMode.DEFAULT: normalized_name = self.normalized_name icon_path = self.icon_path if is_none_or_whitespace(icon_path): raise RefindConfigError( f"The '{normalized_name}' boot stanza is missing the " f"'{RefindOption.ICON.value}' option which must be defined in case " f"'{icon_generation_mode.value}' is the selected mode of boot stanza " "icon generation!" ) @is_matched_with.register(BlockDevice) def _is_matched_with_block_device(self, block_device: BlockDevice) -> bool: if self.can_be_used_for_bootable_snapshot(): boot_options = self.boot_options if boot_options.is_matched_with(block_device): return True else: sub_menus = self.sub_menus if has_items(sub_menus): return any( sub_menu.is_matched_with(block_device) for sub_menu in none_throws(sub_menus) ) return False @is_matched_with.register(str) def _is_matched_with_loader_filename(self, loader_filename: str) -> bool: return self._loader_filename == loader_filename def _get_all_boot_file_paths( self, ) -> Iterator[tuple[BootFilePathSource, str]]: source = BootFilePathSource.BOOT_STANZA is_disabled = self.is_disabled if not is_disabled: loader_path = self.loader_path initrd_path = self.initrd_path boot_options = self.boot_options if not is_none_or_whitespace(loader_path): yield (source, none_throws(loader_path)) if not is_none_or_whitespace(initrd_path): yield (source, none_throws(initrd_path)) yield from ( (source, initrd_option) for initrd_option in boot_options.initrd_options ) sub_menus = self.sub_menus if has_items(sub_menus): yield from chain.from_iterable( sub_menu.all_boot_file_paths for sub_menu in none_throws(sub_menus) ) @property def name(self) -> str: return self._name @property def normalized_name(self) -> str: return strip_quotes(self.name) @property def volume(self) -> Optional[str]: return self._volume @property def normalized_volume(self) -> Optional[str]: volume = self.volume if not is_none_or_whitespace(volume): whitespace_pattern = re.compile(constants.WHITESPACE_PATTERN) stripped_volume = strip_quotes(volume) return whitespace_pattern.sub("_", stripped_volume) return None @property def loader_path(self) -> Optional[str]: return self._loader_path @property def initrd_path(self) -> Optional[str]: return self._initrd_path @property def icon_path(self) -> Optional[str]: return self._icon_path @property def os_type(self) -> Optional[str]: return self._os_type @property def graphics(self) -> Optional[bool]: return self._graphics @property def boot_options(self) -> BootOptions: return self._boot_options @property def firmware_bootnum(self) -> Optional[int]: return self._firmware_bootnum @property def is_disabled(self) -> bool: return self._is_disabled @property def boot_files_check_result(self) -> Optional[BootFilesCheckResult]: return self._boot_files_check_result @property def sub_menus(self) -> Optional[list[SubMenu]]: return self._sub_menus @cached_property def filename(self) -> str: if self.can_be_used_for_bootable_snapshot(): normalized_volume = self.normalized_volume loader_filename = self._loader_filename extension = constants.CONFIG_FILE_EXTENSION return f"{normalized_volume}_{loader_filename}{extension}".lower() return constants.EMPTY_STR @cached_property def all_boot_file_paths(self) -> DefaultDict[BootFilePathSource, Set[str]]: result = defaultdict(set) all_boot_file_paths = self._get_all_boot_file_paths() for boot_file_path_tuple in all_boot_file_paths: key = boot_file_path_tuple[0] value = normalize_dir_separators_in(boot_file_path_tuple[1]) result[key].add(value) return result @cached_property def _loader_filename(self) -> str: loader_path = self.loader_path if not is_none_or_whitespace(loader_path): dir_separator_pattern = re.compile(constants.DIR_SEPARATOR_PATTERN) split_loader_path = dir_separator_pattern.split( none_throws(self.loader_path) ) return last(split_loader_path) return constants.EMPTY_STR ================================================ FILE: src/refind_btrfs/boot/file_refind_config_provider.py ================================================ # region Licensing # SPDX-FileCopyrightText: 2020-2024 Luka Žaja # # SPDX-License-Identifier: GPL-3.0-or-later """ refind-btrfs - Generate rEFInd manual boot stanzas from Btrfs snapshots Copyright (C) 2020-2024 Luka Žaja 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, either version 3 of the License, or (at your option) any later version. 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 . """ # endregion import re from pathlib import Path from typing import Iterable, Iterator from antlr4 import CommonTokenStream, FileStream from injector import inject from more_itertools import last, one from refind_btrfs.common import constants from refind_btrfs.common.abc.factories import BaseLoggerFactory from refind_btrfs.common.abc.providers import ( BasePackageConfigProvider, BasePersistenceProvider, BaseRefindConfigProvider, ) from refind_btrfs.common.enums import ConfigInitializationType, RefindOption from refind_btrfs.common.exceptions import RefindConfigError, RefindSyntaxError from refind_btrfs.device import Partition from refind_btrfs.utility.helpers import ( checked_cast, has_items, is_none_or_whitespace, is_singleton, item_count_suffix, none_throws, ) from .antlr4 import RefindConfigLexer, RefindConfigParser from .boot_stanza import BootStanza from .refind_config import RefindConfig from .refind_listeners import RefindErrorListener from .refind_visitors import BootStanzaVisitor, IncludeVisitor class FileRefindConfigProvider(BaseRefindConfigProvider): all_config_file_paths: dict[Partition, Path] = {} @inject def __init__( self, logger_factory: BaseLoggerFactory, package_config_provider: BasePackageConfigProvider, persistence_provider: BasePersistenceProvider, ) -> None: self._logger = logger_factory.logger(__name__) self._package_config_provider = package_config_provider self._persistence_provider = persistence_provider self._refind_configs: dict[Path, RefindConfig] = {} def get_config(self, partition: Partition) -> RefindConfig: logger = self._logger config_file_path = FileRefindConfigProvider.all_config_file_paths.get(partition) should_begin_search = config_file_path is None or not config_file_path.exists() if should_begin_search: package_config_provider = self._package_config_provider package_config = package_config_provider.get_config() boot_stanza_generation = package_config.boot_stanza_generation refind_config_file = boot_stanza_generation.refind_config logger.info( f"Searching for the '{refind_config_file}' file on '{partition.name}'." ) refind_config_search_result = partition.search_paths_for(refind_config_file) if not has_items(refind_config_search_result): raise RefindConfigError( f"Could not find the '{refind_config_file}' file!" ) if not is_singleton(refind_config_search_result): raise RefindConfigError( f"Found multiple '{refind_config_file}' files (at most one is expected)!" ) config_file_path = one(none_throws(refind_config_search_result)).resolve() FileRefindConfigProvider.all_config_file_paths[partition] = config_file_path return self._read_config_from(none_throws(config_file_path)) def save_config(self, config: RefindConfig) -> None: logger = self._logger persistence_provider = self._persistence_provider boot_stanzas = config.boot_stanzas if has_items(boot_stanzas): config_file_path = config.file_path destination_directory = config_file_path.parent refind_directory = destination_directory.parent if not destination_directory.exists(): logger.info( "Creating the " f"'{destination_directory.relative_to(refind_directory)}' " "destination directory." ) destination_directory.mkdir() try: logger.info( f"Writing to the '{config_file_path.relative_to(refind_directory)}' file." ) with config_file_path.open("w") as config_file: lines_for_writing: list[str] = [] lines_for_writing.append( constants.NEWLINE.join( str(boot_stanza) for boot_stanza in none_throws(boot_stanzas) ) ) lines_for_writing.append(constants.NEWLINE) config_file.writelines(lines_for_writing) except OSError as e: logger.exception("Path.open('w') call failed!") raise RefindConfigError( f"Could not write to the '{config_file_path.name}' file!" ) from e config.refresh_file_stat() persistence_provider.save_refind_config(config) def append_to_config(self, config: RefindConfig) -> None: logger = self._logger persistence_provider = self._persistence_provider config_file_path = config.file_path actual_config = persistence_provider.get_refind_config(config_file_path) if actual_config is not None: new_included_configs = config.get_included_configs_difference_from( actual_config ) if has_items(new_included_configs): included_configs_for_appending = none_throws(new_included_configs) try: with config_file_path.open("r") as config_file: all_lines = config_file.readlines() last_line = last(all_lines) except OSError as e: logger.exception("Path.open('r') call failed!") raise RefindConfigError( f"Could not read from the '{config_file_path}' file!" ) from e else: include_option = RefindOption.INCLUDE.value suffix = item_count_suffix(included_configs_for_appending) try: logger.info( f"Appending {len(included_configs_for_appending)} '{include_option}' " f"directive{suffix} to the '{config_file_path.name}' file." ) with config_file_path.open("a") as config_file: lines_for_appending: list[str] = [] should_prepend_newline = False if not is_none_or_whitespace(last_line): include_option_pattern = re.compile( constants.INCLUDE_OPTION_PATTERN, re.DOTALL ) should_prepend_newline = ( not include_option_pattern.match(last_line) ) if should_prepend_newline: lines_for_appending.append(constants.NEWLINE) destination_directory = config_file_path.parent for included_config in included_configs_for_appending: included_config_relative_file_path = ( included_config.file_path.relative_to( destination_directory ) ) lines_for_appending.append( f"{include_option} {included_config_relative_file_path}" f"{constants.NEWLINE}" ) config_file.writelines(lines_for_appending) except OSError as e: logger.exception("Path.open('a') call failed!") raise RefindConfigError( f"Could not append to the '{config_file_path.name}' file!" ) from e config.refresh_file_stat() persistence_provider.save_refind_config(config) def _read_config_from(self, config_file_path: Path) -> RefindConfig: persistence_provider = self._persistence_provider persisted_refind_config = persistence_provider.get_refind_config( config_file_path ) current_refind_config = self._refind_configs.get(config_file_path) if persisted_refind_config is None: logger = self._logger logger.info(f"Analyzing the '{config_file_path.name}' file.") try: input_stream = FileStream(str(config_file_path), encoding="utf-8") lexer = RefindConfigLexer(input_stream) token_stream = CommonTokenStream(lexer) parser = RefindConfigParser(token_stream) error_listener = RefindErrorListener() parser.removeErrorListeners() parser.addErrorListener(error_listener) refind_context = parser.refind() except RefindSyntaxError as e: logger.exception( f"Error while parsing the '{config_file_path.name}' file!" ) raise RefindConfigError( "Could not load rEFInd configuration from file!" ) from e else: config_option_contexts = checked_cast( list[RefindConfigParser.Config_optionContext], refind_context.config_option(), ) boot_stanzas = FileRefindConfigProvider._map_to_boot_stanzas( config_option_contexts ) includes = FileRefindConfigProvider._map_to_includes( config_option_contexts ) included_configs = self._read_included_configs_from( config_file_path.parent, includes ) current_refind_config = ( RefindConfig(config_file_path) .with_boot_stanzas(boot_stanzas) .with_included_configs(included_configs) .with_initialization_type(ConfigInitializationType.PARSED) ) persistence_provider.save_refind_config(current_refind_config) elif current_refind_config is None: current_refind_config = persisted_refind_config.with_initialization_type( ConfigInitializationType.PERSISTED ) if current_refind_config.has_included_configs(): current_included_configs = none_throws( current_refind_config.included_configs ) actual_included_configs = [ self._read_config_from(included_config.file_path) for included_config in current_included_configs if included_config.file_path.exists() ] current_refind_config = current_refind_config.with_included_configs( actual_included_configs ) self._refind_configs[config_file_path] = current_refind_config return current_refind_config def _read_included_configs_from( self, root_directory: Path, includes: Iterable[str] ) -> Iterator[RefindConfig]: logger = self._logger for include in includes: included_config_file_path = root_directory / include if included_config_file_path.exists(): yield self._read_config_from(included_config_file_path.resolve()) else: logger.warning( f"The included config file '{included_config_file_path.name}' does not exist." ) @staticmethod def _map_to_boot_stanzas( config_option_contexts: list[RefindConfigParser.Config_optionContext], ) -> Iterator[BootStanza]: if has_items(config_option_contexts): boot_stanza_visitor = BootStanzaVisitor() for config_option_context in config_option_contexts: boot_stanza_context = config_option_context.boot_stanza() if boot_stanza_context is not None: yield checked_cast( BootStanza, boot_stanza_context.accept(boot_stanza_visitor) ) @staticmethod def _map_to_includes( config_option_contexts: list[RefindConfigParser.Config_optionContext], ) -> Iterator[str]: if has_items(config_option_contexts): include_visitor = IncludeVisitor() for config_option_context in config_option_contexts: include_context = config_option_context.include() if include_context is not None: yield checked_cast(str, include_context.accept(include_visitor)) ================================================ FILE: src/refind_btrfs/boot/migrations/__init__.py ================================================ # region Licensing # SPDX-FileCopyrightText: 2020-2024 Luka Žaja # # SPDX-License-Identifier: GPL-3.0-or-later """ refind-btrfs - Generate rEFInd manual boot stanzas from Btrfs snapshots Copyright (C) 2020-2024 Luka Žaja 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, either version 3 of the License, or (at your option) any later version. 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 . """ # endregion from .migration import Migration ================================================ FILE: src/refind_btrfs/boot/migrations/icon_migration_strategies.py ================================================ # region Licensing # SPDX-FileCopyrightText: 2020-2024 Luka Žaja # # SPDX-License-Identifier: GPL-3.0-or-later """ refind-btrfs - Generate rEFInd manual boot stanzas from Btrfs snapshots Copyright (C) 2020-2024 Luka Žaja 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, either version 3 of the License, or (at your option) any later version. 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 . """ # endregion from abc import ABC, abstractmethod from pathlib import Path from refind_btrfs.common import BtrfsLogo, Icon from refind_btrfs.common.abc.commands import IconCommand from refind_btrfs.common.enums import BootStanzaIconGenerationMode class BaseIconMigrationStrategy(ABC): def __init__( self, icon_command: IconCommand, refind_config_path: Path, source_icon: str ) -> None: self._icon_command = icon_command self._refind_config_path = refind_config_path self._source_icon_path = Path(source_icon) @abstractmethod def migrate(self) -> str: pass class DefaultMigrationStrategy(BaseIconMigrationStrategy): def migrate(self) -> str: return str(self._source_icon_path) class CustomMigrationStrategy(BaseIconMigrationStrategy): def __init__( self, icon_command: IconCommand, refind_config_path: Path, source_icon: str, custom_icon_path: Path, ) -> None: super().__init__(icon_command, refind_config_path, source_icon) self._custom_icon_path = custom_icon_path def migrate(self) -> str: icon_command = self._icon_command refind_config_path = self._refind_config_path source_icon_path = self._source_icon_path custom_icon_path = self._custom_icon_path destination_icon_relative_path = icon_command.validate_custom_icon( refind_config_path, source_icon_path, custom_icon_path ) return str(destination_icon_relative_path) class EmbedBtrfsLogoStrategy(BaseIconMigrationStrategy): def __init__( self, icon_command: IconCommand, refind_config_path: Path, source_icon: str, btrfs_logo: BtrfsLogo, ) -> None: super().__init__(icon_command, refind_config_path, source_icon) self._btrfs_logo = btrfs_logo def migrate(self) -> str: icon_command = self._icon_command refind_config_path = self._refind_config_path source_icon_path = self._source_icon_path btrfs_logo = self._btrfs_logo destination_icon_relative_path = icon_command.embed_btrfs_logo_into_source_icon( refind_config_path, source_icon_path, btrfs_logo ) return str(destination_icon_relative_path) class IconMigrationFactory: @staticmethod def migration_strategy( icon_command: IconCommand, refind_config_path: Path, source_icon: str, icon: Icon, ) -> BaseIconMigrationStrategy: mode = icon.mode if mode == BootStanzaIconGenerationMode.DEFAULT: return DefaultMigrationStrategy( icon_command, refind_config_path, source_icon ) if mode == BootStanzaIconGenerationMode.CUSTOM: custom_icon_path = icon.path return CustomMigrationStrategy( icon_command, refind_config_path, source_icon, custom_icon_path ) if mode == BootStanzaIconGenerationMode.EMBED_BTRFS_LOGO: btrfs_logo = icon.btrfs_logo return EmbedBtrfsLogoStrategy( icon_command, refind_config_path, source_icon, btrfs_logo ) raise ValueError( "The 'icon' parameter's 'mode' property contains an unexpected value!" ) ================================================ FILE: src/refind_btrfs/boot/migrations/main_migration_strategies.py ================================================ # region Licensing # SPDX-FileCopyrightText: 2020-2024 Luka Žaja # # SPDX-License-Identifier: GPL-3.0-or-later """ refind-btrfs - Generate rEFInd manual boot stanzas from Btrfs snapshots Copyright (C) 2020-2024 Luka Žaja 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, either version 3 of the License, or (at your option) any later version. 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 . """ # endregion import re from abc import ABC, abstractmethod from copy import deepcopy from functools import singledispatchmethod from pathlib import Path from typing import Any, Optional from refind_btrfs.common import BootStanzaGeneration, Icon, constants from refind_btrfs.common.abc.commands import IconCommand from refind_btrfs.device import Subvolume from refind_btrfs.utility.helpers import ( default_if_none, is_none_or_whitespace, none_throws, replace_root_part_in, ) from ..boot_options import BootOptions from ..boot_stanza import BootStanza from ..sub_menu import SubMenu from .icon_migration_strategies import IconMigrationFactory from .state import State class BaseMainMigrationStrategy(ABC): def __init__( self, is_latest: bool, refind_config_path: Path, current_state: State, source_subvolume: Subvolume, destination_subvolume: Subvolume, boot_stanza_generation: BootStanzaGeneration, ) -> None: self._is_latest = is_latest self._refind_config_path = refind_config_path self._current_state = current_state self._source_subvolume = source_subvolume self._destination_subvolume = destination_subvolume self._boot_stanza_generation = boot_stanza_generation @abstractmethod def migrate(self) -> State: pass @property def destination_name(self) -> str: destination_subvolume = self._destination_subvolume if not destination_subvolume.is_named(): raise ValueError("The 'destination_subvolume' instance must be named!") current_name = self._current_state.name destination_subvolume_name = none_throws(destination_subvolume.name) subvolume_name_pattern = re.compile(rf"\({constants.SUBVOLUME_NAME_PATTERN}\)") match = subvolume_name_pattern.search(current_name) if match: destination_name = subvolume_name_pattern.sub( f"({destination_subvolume_name})", current_name ) else: destination_name = f"{current_name} ({destination_subvolume_name})" return f"{constants.DOUBLE_QUOTE}{destination_name}{constants.DOUBLE_QUOTE}" @property def destination_loader_path(self) -> Optional[str]: current_loader_path = self._current_state.loader_path if not is_none_or_whitespace(current_loader_path): return replace_root_part_in( none_throws(current_loader_path), self._source_subvolume.logical_path, self._destination_subvolume.logical_path, ) return None @property def destination_initrd_path(self) -> Optional[str]: current_initrd_path = self._current_state.initrd_path if not is_none_or_whitespace(current_initrd_path): return replace_root_part_in( none_throws(current_initrd_path), self._source_subvolume.logical_path, self._destination_subvolume.logical_path, ) return None @property def destination_boot_options(self) -> Optional[BootOptions]: current_boot_options = self._current_state.boot_options if current_boot_options is not None: destination_boot_options = deepcopy(current_boot_options) include_paths = self.include_paths destination_boot_options.migrate_from_to( self._source_subvolume, self._destination_subvolume, include_paths, ) return destination_boot_options return None @property def destination_add_boot_options(self) -> Optional[BootOptions]: current_add_boot_options = self._current_state.add_boot_options if current_add_boot_options is not None: destination_add_boot_options = deepcopy(current_add_boot_options) include_paths = self.include_paths destination_add_boot_options.migrate_from_to( self._source_subvolume, self._destination_subvolume, include_paths, ) return destination_add_boot_options return None @property def include_paths(self) -> bool: return self._boot_stanza_generation.include_paths @property def icon(self) -> Icon: return self._boot_stanza_generation.icon class BootStanzaMigrationStrategy(BaseMainMigrationStrategy): def __init__( self, is_latest: bool, refind_config_path: Path, boot_stanza: BootStanza, source_subvolume: Subvolume, destination_subvolume: Subvolume, boot_stanza_generation: BootStanzaGeneration, icon_command: IconCommand, ) -> None: super().__init__( is_latest, refind_config_path, State( boot_stanza.normalized_name, boot_stanza.loader_path, boot_stanza.initrd_path, boot_stanza.icon_path, boot_stanza.boot_options, None, ), source_subvolume, destination_subvolume, boot_stanza_generation, ) self._icon_command = icon_command def migrate(self) -> State: include_paths = self.include_paths is_latest = self._is_latest current_state = self._current_state destination_loader_path = constants.EMPTY_STR destination_initrd_path = constants.EMPTY_STR if is_latest: destination_loader_path = none_throws(current_state.loader_path) destination_initrd_path = none_throws(current_state.initrd_path) if include_paths: destination_loader_path = none_throws(self.destination_loader_path) destination_initrd_path_candidate = self.destination_initrd_path if not is_none_or_whitespace(destination_initrd_path_candidate): destination_initrd_path = none_throws(destination_initrd_path_candidate) icon_migration_strategy = IconMigrationFactory.migration_strategy( self._icon_command, self._refind_config_path, default_if_none(current_state.icon_path, constants.EMPTY_STR), self.icon, ) destination_icon_path = icon_migration_strategy.migrate() return State( self.destination_name, destination_loader_path, destination_initrd_path, destination_icon_path, self.destination_boot_options, None, ) class SubMenuMigrationStrategy(BaseMainMigrationStrategy): def __init__( self, is_latest: bool, refind_config_path: Path, sub_menu: SubMenu, source_subvolume: Subvolume, destination_subvolume: Subvolume, boot_stanza_generation: BootStanzaGeneration, inherit_from_state: State, ) -> None: super().__init__( is_latest, refind_config_path, State( sub_menu.normalized_name, sub_menu.loader_path, sub_menu.initrd_path, None, sub_menu.boot_options, sub_menu.add_boot_options, ), source_subvolume, destination_subvolume, boot_stanza_generation, ) self._inherit_from_state = inherit_from_state def migrate(self) -> State: include_paths = self.include_paths is_latest = self._is_latest current_state = self._current_state inherit_from_state = self._inherit_from_state destination_loader_path = current_state.loader_path destination_initrd_path = current_state.initrd_path destination_boot_options: Optional[BootOptions] = None destination_add_boot_options = self.destination_add_boot_options if not is_latest: if include_paths: destination_loader_path = inherit_from_state.loader_path destination_initrd_path = inherit_from_state.initrd_path destination_boot_options = BootOptions.merge( ( none_throws(inherit_from_state.boot_options), none_throws(destination_add_boot_options), ) ) destination_add_boot_options = BootOptions(constants.EMPTY_STR) if include_paths: destination_loader_path_candidate = self.destination_loader_path destination_initrd_path_candidate = self.destination_initrd_path if not is_none_or_whitespace(destination_loader_path_candidate): destination_loader_path = destination_loader_path_candidate if not is_none_or_whitespace(destination_initrd_path_candidate): destination_initrd_path = destination_initrd_path_candidate return State( self.destination_name, destination_loader_path, destination_initrd_path, None, destination_boot_options, destination_add_boot_options, ) class MainMigrationFactory: # pylint: disable=unused-argument @singledispatchmethod @staticmethod def migration_strategy( argument: Any, is_latest: bool, refind_config_path: Path, source_subvolume: Subvolume, destination_subvolume: Subvolume, boot_stanza_generation: BootStanzaGeneration, icon_command: Optional[IconCommand] = None, inherit_from_state: Optional[State] = None, ) -> BaseMainMigrationStrategy: raise NotImplementedError( "Cannot instantiate the main migration strategy " f"for parameter of type '{type(argument).__name__}'!" ) # pylint: disable=unused-argument @migration_strategy.register(BootStanza) @staticmethod def _boot_stanza_overload( boot_stanza: BootStanza, is_latest: bool, refind_config_path: Path, source_subvolume: Subvolume, destination_subvolume: Subvolume, boot_stanza_generation: BootStanzaGeneration, icon_command: Optional[IconCommand] = None, inherit_from_state: Optional[State] = None, ) -> BaseMainMigrationStrategy: return BootStanzaMigrationStrategy( is_latest, refind_config_path, boot_stanza, source_subvolume, destination_subvolume, boot_stanza_generation, none_throws(icon_command), ) # pylint: disable=unused-argument @migration_strategy.register(SubMenu) @staticmethod def _sub_menu_overload( sub_menu: SubMenu, is_latest: bool, refind_config_path: Path, source_subvolume: Subvolume, destination_subvolume: Subvolume, boot_stanza_generation: BootStanzaGeneration, icon_command: Optional[IconCommand] = None, inherit_from_state: Optional[State] = None, ) -> BaseMainMigrationStrategy: return SubMenuMigrationStrategy( is_latest, refind_config_path, sub_menu, source_subvolume, destination_subvolume, boot_stanza_generation, none_throws(inherit_from_state), ) ================================================ FILE: src/refind_btrfs/boot/migrations/migration.py ================================================ # region Licensing # SPDX-FileCopyrightText: 2020-2024 Luka Žaja # # SPDX-License-Identifier: GPL-3.0-or-later """ refind-btrfs - Generate rEFInd manual boot stanzas from Btrfs snapshots Copyright (C) 2020-2024 Luka Žaja 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, either version 3 of the License, or (at your option) any later version. 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 . """ # endregion from pathlib import Path from typing import Collection, Iterator, Optional from more_itertools import first from refind_btrfs.common import BootStanzaGeneration, constants from refind_btrfs.common.abc.commands import IconCommand from refind_btrfs.common.exceptions import RefindConfigError from refind_btrfs.device import BlockDevice, Subvolume from refind_btrfs.utility.helpers import has_items, none_throws from ..boot_options import BootOptions from ..boot_stanza import BootStanza from ..sub_menu import SubMenu from .main_migration_strategies import MainMigrationFactory from .state import State class Migration: def __init__( self, boot_stanza: BootStanza, block_device: BlockDevice, bootable_snapshots: Collection[Subvolume], ) -> None: assert has_items( bootable_snapshots ), "Parameter 'bootable_snapshots' must contain at least one item!" if not boot_stanza.is_matched_with(block_device): raise RefindConfigError("Boot stanza is not matched with the partition!") root_partition = none_throws(block_device.root) filesystem = none_throws(root_partition.filesystem) source_subvolume = none_throws(filesystem.subvolume) self._boot_stanza = boot_stanza self._source_subvolume = source_subvolume self._bootable_snapshots = list(bootable_snapshots) def migrate( self, refind_config_path: Path, boot_stanza_generation: BootStanzaGeneration, icon_command: IconCommand, ) -> BootStanza: boot_stanza = self._boot_stanza source_subvolume = self._source_subvolume bootable_snapshots = self._bootable_snapshots include_sub_menus = boot_stanza_generation.include_sub_menus latest_migration_result: Optional[State] = None result_sub_menus: list[SubMenu] = [] for destination_subvolume in bootable_snapshots: is_latest = self._is_latest_snapshot(destination_subvolume) boot_stanza_migration_strategy = MainMigrationFactory.migration_strategy( boot_stanza, is_latest, refind_config_path, source_subvolume, destination_subvolume, boot_stanza_generation, icon_command=icon_command, ) migration_result = boot_stanza_migration_strategy.migrate() if is_latest: latest_migration_result = migration_result else: result_sub_menus.append( SubMenu( migration_result.name, migration_result.loader_path, migration_result.initrd_path, boot_stanza.graphics, migration_result.boot_options, BootOptions(constants.EMPTY_STR), boot_stanza.is_disabled, ) ) if include_sub_menus: migrated_sub_menus = self._migrate_sub_menus( refind_config_path, source_subvolume, destination_subvolume, migration_result, boot_stanza_generation, ) result_sub_menus.extend(list(migrated_sub_menus)) boot_stanza_migration_result = none_throws(latest_migration_result) return BootStanza( boot_stanza_migration_result.name, boot_stanza.volume, boot_stanza_migration_result.loader_path, boot_stanza_migration_result.initrd_path, boot_stanza_migration_result.icon_path, boot_stanza.os_type, boot_stanza.graphics, none_throws(boot_stanza_migration_result.boot_options), boot_stanza.firmware_bootnum, boot_stanza.is_disabled, ).with_sub_menus(result_sub_menus) def _migrate_sub_menus( self, refind_config_path: Path, source_subvolume: Subvolume, destination_subvolume: Subvolume, boot_stanza_result: State, boot_stanza_generation: BootStanzaGeneration, ) -> Iterator[SubMenu]: boot_stanza = self._boot_stanza if not boot_stanza.has_sub_menus(): return current_sub_menus = none_throws(boot_stanza.sub_menus) is_latest = self._is_latest_snapshot(destination_subvolume) for sub_menu in current_sub_menus: if sub_menu.can_be_used_for_bootable_snapshot(): sub_menu_migration_strategy = MainMigrationFactory.migration_strategy( sub_menu, is_latest, refind_config_path, source_subvolume, destination_subvolume, boot_stanza_generation, inherit_from_state=boot_stanza_result, ) migration_result = sub_menu_migration_strategy.migrate() yield SubMenu( migration_result.name, migration_result.loader_path, migration_result.initrd_path, sub_menu.graphics, migration_result.boot_options, none_throws(migration_result.add_boot_options), sub_menu.is_disabled, ) def _is_latest_snapshot(self, snapshot: Subvolume) -> bool: bootable_snapshots = self._bootable_snapshots latest_snapshot = first(bootable_snapshots) return snapshot == latest_snapshot ================================================ FILE: src/refind_btrfs/boot/migrations/state.py ================================================ # region Licensing # SPDX-FileCopyrightText: 2020-2024 Luka Žaja # # SPDX-License-Identifier: GPL-3.0-or-later """ refind-btrfs - Generate rEFInd manual boot stanzas from Btrfs snapshots Copyright (C) 2020-2024 Luka Žaja 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, either version 3 of the License, or (at your option) any later version. 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 . """ # endregion from typing import NamedTuple, Optional from ..boot_options import BootOptions class State(NamedTuple): name: str loader_path: Optional[str] initrd_path: Optional[str] icon_path: Optional[str] boot_options: Optional[BootOptions] add_boot_options: Optional[BootOptions] ================================================ FILE: src/refind_btrfs/boot/refind_config.py ================================================ # region Licensing # SPDX-FileCopyrightText: 2020-2024 Luka Žaja # # SPDX-License-Identifier: GPL-3.0-or-later """ refind-btrfs - Generate rEFInd manual boot stanzas from Btrfs snapshots Copyright (C) 2020-2024 Luka Žaja 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, either version 3 of the License, or (at your option) any later version. 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 . """ # endregion from __future__ import annotations from copy import copy from itertools import chain from pathlib import Path from typing import Collection, Iterable, Iterator, Optional, Self from more_itertools import always_iterable from refind_btrfs.common import BootStanzaGeneration, constants from refind_btrfs.common.abc import BaseConfig from refind_btrfs.common.abc.factories import BaseIconCommandFactory from refind_btrfs.common.enums import ConfigInitializationType from refind_btrfs.device import BlockDevice, Subvolume from refind_btrfs.utility.helpers import ( has_items, is_none_or_whitespace, none_throws, replace_item_in, ) from .boot_stanza import BootStanza from .migrations import Migration class RefindConfig(BaseConfig): def __init__(self, file_path: Path) -> None: super().__init__(file_path) self._boot_stanzas: Optional[list[BootStanza]] = None self._included_configs: Optional[list[RefindConfig]] = None def with_boot_stanzas(self, boot_stanzas: Iterable[BootStanza]) -> Self: self._boot_stanzas = list(boot_stanzas) return self def with_included_configs(self, include_configs: Iterable[RefindConfig]) -> Self: self._included_configs = list(include_configs) return self def get_boot_stanzas_matched_with( self, block_device: BlockDevice ) -> Iterator[BootStanza]: if self.has_boot_stanzas(): yield from ( boot_stanza for boot_stanza in none_throws(self.boot_stanzas) if boot_stanza.is_matched_with(block_device) ) if self.has_included_configs(): yield from chain.from_iterable( config.get_boot_stanzas_matched_with(block_device) for config in none_throws(self.included_configs) ) def get_included_configs_difference_from( self, other: RefindConfig ) -> Optional[Collection[RefindConfig]]: if self.has_included_configs(): self_included_configs = none_throws(self.included_configs) if not other.has_included_configs(): return self_included_configs other_included_configs = none_throws(other.included_configs) return set( included_config for included_config in self_included_configs if included_config not in other_included_configs ) return None def generate_new_from( self, block_device: BlockDevice, boot_stanzas_with_snapshots: dict[BootStanza, list[Subvolume]], boot_stanza_generation: BootStanzaGeneration, icon_command_factory: BaseIconCommandFactory, ) -> Iterator[RefindConfig]: file_path = self.file_path boot_stanzas = copy(none_throws(self.boot_stanzas)) parent_directory = file_path.parent included_configs: list[RefindConfig] = ( none_throws(self.included_configs) if self.has_included_configs() else [] ) boot_stanzas.extend( chain.from_iterable( ( none_throws(included_config.boot_stanzas) for included_config in included_configs if included_config.has_boot_stanzas() ) ) ) icon_command = icon_command_factory.icon_command() for boot_stanza in boot_stanzas: bootable_snapshots = boot_stanzas_with_snapshots.get(boot_stanza) if has_items(bootable_snapshots): sorted_bootable_snapshots = sorted( none_throws(bootable_snapshots), reverse=True ) migration = Migration( boot_stanza, block_device, sorted_bootable_snapshots ) migrated_boot_stanza = migration.migrate( file_path, boot_stanza_generation, icon_command ) boot_stanza_filename = migrated_boot_stanza.filename if not is_none_or_whitespace(boot_stanza_filename): destination_directory = ( parent_directory / constants.SNAPSHOT_STANZAS_DIR_NAME ) boot_stanza_config_file_path = ( destination_directory / boot_stanza_filename ) boot_stanza_config = RefindConfig( boot_stanza_config_file_path.resolve() ).with_boot_stanzas(always_iterable(migrated_boot_stanza)) if boot_stanza_config not in included_configs: included_configs.append(boot_stanza_config) else: replace_item_in(included_configs, boot_stanza_config) yield boot_stanza_config self._included_configs = included_configs def has_boot_stanzas(self) -> bool: return has_items(self.boot_stanzas) def has_included_configs(self) -> bool: return has_items(self.included_configs) def is_of_initialization_type( self, initialization_type: ConfigInitializationType ) -> bool: if super().is_of_initialization_type(initialization_type): return True if self.has_included_configs(): nongenerated_included_configs = ( included_config for included_config in none_throws(self.included_configs) if not included_config.is_generated() ) return any( included_config.is_of_initialization_type(initialization_type) for included_config in nongenerated_included_configs ) return False def is_generated(self) -> bool: file_path = self.file_path parent_directory = file_path.parent return parent_directory.name == constants.SNAPSHOT_STANZAS_DIR_NAME @property def boot_stanzas(self) -> Optional[list[BootStanza]]: return self._boot_stanzas @property def included_configs(self) -> Optional[list[RefindConfig]]: return self._included_configs ================================================ FILE: src/refind_btrfs/boot/refind_listeners.py ================================================ # region Licensing # SPDX-FileCopyrightText: 2020-2024 Luka Žaja # # SPDX-License-Identifier: GPL-3.0-or-later """ refind-btrfs - Generate rEFInd manual boot stanzas from Btrfs snapshots Copyright (C) 2020-2024 Luka Žaja 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, either version 3 of the License, or (at your option) any later version. 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 . """ # endregion from antlr4.error.ErrorListener import ErrorListener from refind_btrfs.common.exceptions import RefindSyntaxError class RefindErrorListener(ErrorListener): # pylint: disable=unused-argument def syntaxError(self, recognizer, offendingSymbol, line, column, msg, e): raise RefindSyntaxError(line, column, msg) ================================================ FILE: src/refind_btrfs/boot/refind_visitors.py ================================================ # region Licensing # SPDX-FileCopyrightText: 2020-2024 Luka Žaja # # SPDX-License-Identifier: GPL-3.0-or-later """ refind-btrfs - Generate rEFInd manual boot stanzas from Btrfs snapshots Copyright (C) 2020-2024 Luka Žaja 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, either version 3 of the License, or (at your option) any later version. 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 . """ # endregion from collections import defaultdict from typing import Any, Callable, DefaultDict, Iterable, NamedTuple, Optional from antlr4 import ParserRuleContext from more_itertools import always_iterable, only from refind_btrfs.common import constants from refind_btrfs.common.enums import GraphicsParameter, OSTypeParameter, RefindOption from refind_btrfs.common.exceptions import RefindConfigError from refind_btrfs.utility.helpers import checked_cast, try_parse_int from .antlr4 import RefindConfigParser, RefindConfigParserVisitor from .boot_options import BootOptions from .boot_stanza import BootStanza from .sub_menu import SubMenu class ContextWithVisitor(NamedTuple): child_context_func: Callable[[ParserRuleContext], ParserRuleContext] visitor_func: Callable[[], RefindConfigParserVisitor] class BootStanzaVisitor(RefindConfigParserVisitor): def visitBoot_stanza( self, ctx: RefindConfigParser.Boot_stanzaContext ) -> BootStanza: menu_entry_context = ctx.menu_entry() menu_entry = menu_entry_context.accept(MenuEntryVisitor()) main_options = OptionVisitor.map_to_options_dict( checked_cast(list[ParserRuleContext], ctx.main_option()) ) volume = only(always_iterable(main_options.get(RefindOption.VOLUME))) loader = only(always_iterable(main_options.get(RefindOption.LOADER))) initrd = only(always_iterable(main_options.get(RefindOption.INITRD))) icon = only(always_iterable(main_options.get(RefindOption.ICON))) os_type = only(always_iterable(main_options.get(RefindOption.OS_TYPE))) graphics = only(always_iterable(main_options.get(RefindOption.GRAPHICS))) boot_options = only( always_iterable(main_options.get(RefindOption.BOOT_OPTIONS)) ) firmware_bootnum = only( always_iterable(main_options.get(RefindOption.FIRMWARE_BOOTNUM)) ) disabled = only( always_iterable(main_options.get(RefindOption.DISABLED)), default=False ) sub_menus = always_iterable(main_options.get(RefindOption.SUB_MENU_ENTRY)) return BootStanza( menu_entry, volume, loader, initrd, icon, os_type, graphics, BootOptions(boot_options), firmware_bootnum, disabled, ).with_sub_menus(sub_menus) class MenuEntryVisitor(RefindConfigParserVisitor): def visitMenu_entry(self, ctx: RefindConfigParser.Menu_entryContext) -> str: token = ctx.STRING() return token.getText() class OptionVisitor(RefindConfigParserVisitor): def __init__(self) -> None: self._main_option_mappings = { RefindOption.VOLUME: ContextWithVisitor( RefindConfigParser.Main_optionContext.volume, VolumeVisitor ), RefindOption.LOADER: ContextWithVisitor( RefindConfigParser.Main_optionContext.loader, LoaderVisitor ), RefindOption.INITRD: ContextWithVisitor( RefindConfigParser.Main_optionContext.main_initrd, InitrdVisitor ), RefindOption.ICON: ContextWithVisitor( RefindConfigParser.Main_optionContext.icon, IconVisitor ), RefindOption.OS_TYPE: ContextWithVisitor( RefindConfigParser.Main_optionContext.os_type, OsTypeVisitor ), RefindOption.GRAPHICS: ContextWithVisitor( RefindConfigParser.Main_optionContext.graphics, GraphicsVisitor ), RefindOption.BOOT_OPTIONS: ContextWithVisitor( RefindConfigParser.Main_optionContext.main_boot_options, BootOptionsVisitor, ), RefindOption.FIRMWARE_BOOTNUM: ContextWithVisitor( RefindConfigParser.Main_optionContext.firmware_bootnum, FirmwareBootnumVisitor, ), RefindOption.DISABLED: ContextWithVisitor( RefindConfigParser.Main_optionContext.disabled, DisabledVisitor ), RefindOption.SUB_MENU_ENTRY: ContextWithVisitor( RefindConfigParser.Main_optionContext.sub_menu, SubMenuVisitor ), } self._sub_option_mappings = { RefindOption.LOADER: ContextWithVisitor( RefindConfigParser.Sub_optionContext.loader, LoaderVisitor ), RefindOption.INITRD: ContextWithVisitor( RefindConfigParser.Sub_optionContext.sub_initrd, InitrdVisitor ), RefindOption.GRAPHICS: ContextWithVisitor( RefindConfigParser.Sub_optionContext.graphics, GraphicsVisitor ), RefindOption.BOOT_OPTIONS: ContextWithVisitor( RefindConfigParser.Sub_optionContext.sub_boot_options, BootOptionsVisitor, ), RefindOption.ADD_BOOT_OPTIONS: ContextWithVisitor( RefindConfigParser.Sub_optionContext.add_boot_options, BootOptionsVisitor, ), RefindOption.DISABLED: ContextWithVisitor( RefindConfigParser.Sub_optionContext.disabled, DisabledVisitor ), } @classmethod def map_to_options_dict( cls, option_contexts: Iterable[ParserRuleContext] ) -> DefaultDict[RefindOption, list[Any]]: option_visitor = cls() result = defaultdict(list) for option_context in option_contexts: option_tuple = option_context.accept(option_visitor) if option_tuple is not None: key = checked_cast(RefindOption, option_tuple[0]) value = option_tuple[1] result[key].append(value) return result def visitMain_option( self, ctx: RefindConfigParser.Main_optionContext ) -> Optional[tuple[RefindOption, Any]]: return OptionVisitor._map_to_option_tuple(ctx, self._main_option_mappings) def visitSub_option( self, ctx: RefindConfigParser.Sub_optionContext ) -> Optional[tuple[RefindOption, Any]]: return OptionVisitor._map_to_option_tuple(ctx, self._sub_option_mappings) @staticmethod def _map_to_option_tuple( ctx: ParserRuleContext, mappings: dict[RefindOption, ContextWithVisitor] ) -> Optional[tuple[RefindOption, Any]]: for key, value in mappings.items(): option_context = value.child_context_func(ctx) if option_context is not None: visitor = value.visitor_func() return key, option_context.accept(visitor) return None class SubMenuVisitor(RefindConfigParserVisitor): def visitSub_menu(self, ctx: RefindConfigParser.Sub_menuContext) -> SubMenu: menu_entry_context = ctx.menu_entry() menu_entry = menu_entry_context.accept(MenuEntryVisitor()) sub_options = OptionVisitor.map_to_options_dict( checked_cast(list[ParserRuleContext], ctx.sub_option()) ) loader = only(always_iterable(sub_options.get(RefindOption.LOADER))) initrd = only(always_iterable(sub_options.get(RefindOption.INITRD))) graphics = only(always_iterable(sub_options.get(RefindOption.GRAPHICS))) boot_options = only(always_iterable(sub_options.get(RefindOption.BOOT_OPTIONS))) add_boot_options = only( always_iterable(sub_options.get(RefindOption.ADD_BOOT_OPTIONS)) ) disabled = only( always_iterable(sub_options.get(RefindOption.DISABLED)), default=False ) return SubMenu( menu_entry, loader, initrd, graphics, BootOptions(boot_options) if boot_options is not None else None, BootOptions(add_boot_options), disabled, ) class VolumeVisitor(RefindConfigParserVisitor): def visitVolume(self, ctx: RefindConfigParser.VolumeContext) -> str: if ctx is not None: token = ctx.STRING() return token.getText() return None class LoaderVisitor(RefindConfigParserVisitor): def visitLoader(self, ctx: RefindConfigParser.LoaderContext) -> str: token = ctx.STRING() return token.getText() class InitrdVisitor(RefindConfigParserVisitor): def visitMain_initrd(self, ctx: RefindConfigParser.Main_initrdContext) -> str: token = ctx.STRING() return token.getText() def visitSub_initrd(self, ctx: RefindConfigParser.Sub_initrdContext) -> str: token = ctx.STRING() if token is not None: return token.getText() return constants.EMPTY_STR class IconVisitor(RefindConfigParserVisitor): def visitIcon(self, ctx: RefindConfigParser.IconContext) -> str: token = ctx.STRING() return token.getText() class OsTypeVisitor(RefindConfigParserVisitor): def visitOs_type(self, ctx: RefindConfigParser.Os_typeContext) -> str: token = ctx.OS_TYPE_PARAMETER() text = token.getText() os_type_options = [ os_type_parameter.value for os_type_parameter in OSTypeParameter ] if text not in os_type_options: raise RefindConfigError(f"Unexpected 'os_type' option - '{text}'!") return text class GraphicsVisitor(RefindConfigParserVisitor): def visitGraphics(self, ctx: RefindConfigParser.GraphicsContext) -> bool: token = ctx.GRAPHICS_PARAMETER() text = token.getText() if text == GraphicsParameter.ON.value: return True if text == GraphicsParameter.OFF.value: return False raise RefindConfigError(f"Unexpected 'graphics' option - '{text}'!") class BootOptionsVisitor(RefindConfigParserVisitor): def visitMain_boot_options( self, ctx: RefindConfigParser.Main_boot_optionsContext ) -> str: token = ctx.STRING() return token.getText() def visitSub_boot_options( self, ctx: RefindConfigParser.Sub_boot_optionsContext ) -> str: token = ctx.STRING() if token is not None: return token.getText() return constants.EMPTY_STR def visitAdd_boot_options( self, ctx: RefindConfigParser.Add_boot_optionsContext ) -> str: token = ctx.STRING() return token.getText() class FirmwareBootnumVisitor(RefindConfigParserVisitor): def visitFirmware_bootnum( self, ctx: RefindConfigParser.Firmware_bootnumContext ) -> int: token = ctx.HEX_INTEGER() text = token.getText() firmware_bootnum = try_parse_int(text, 16) if firmware_bootnum is None: raise RefindConfigError(f"Unexpected 'firmware_bootnum' option - '{text}'!") return firmware_bootnum class DisabledVisitor(RefindConfigParserVisitor): def visitDisabled(self, ctx: RefindConfigParser.DisabledContext) -> bool: return True class IncludeVisitor(RefindConfigParserVisitor): def visitInclude(self, ctx: RefindConfigParser.IncludeContext) -> str: token = ctx.STRING() return token.getText() ================================================ FILE: src/refind_btrfs/boot/sub_menu.py ================================================ # region Licensing # SPDX-FileCopyrightText: 2020-2024 Luka Žaja # # SPDX-License-Identifier: GPL-3.0-or-later """ refind-btrfs - Generate rEFInd manual boot stanzas from Btrfs snapshots Copyright (C) 2020-2024 Luka Žaja 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, either version 3 of the License, or (at your option) any later version. 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 . """ # endregion from functools import cached_property from typing import Iterator, Optional, Set from refind_btrfs.common import constants from refind_btrfs.common.enums import ( BootFilePathSource, GraphicsParameter, RefindOption, ) from refind_btrfs.device import BlockDevice from refind_btrfs.utility.helpers import ( is_empty, is_none_or_whitespace, none_throws, strip_quotes, ) from .boot_options import BootOptions class SubMenu: def __init__( self, name: str, loader_path: Optional[str], initrd_path: Optional[str], graphics: Optional[bool], boot_options: Optional[BootOptions], add_boot_options: BootOptions, is_disabled: bool, ) -> None: self._name = name self._loader_path = loader_path self._initrd_path = initrd_path self._graphics = graphics self._boot_options = boot_options self._add_boot_options = add_boot_options self._is_disabled = is_disabled def __str__(self) -> str: main_indent = constants.TAB option_indent = main_indent * 2 result: list[str] = [] name = self.name result.append(f"{main_indent}{RefindOption.SUB_MENU_ENTRY.value} {name} {{") loader_path = self.loader_path if not is_none_or_whitespace(loader_path): result.append(f"{option_indent}{RefindOption.LOADER.value} {loader_path}") initrd_path = self.initrd_path if not is_none_or_whitespace(initrd_path): result.append(f"{option_indent}{RefindOption.INITRD.value} {initrd_path}") graphics = self.graphics if graphics is not None: value = ( GraphicsParameter.ON.value if graphics else GraphicsParameter.OFF.value ) result.append(f"{option_indent}{RefindOption.GRAPHICS.value} {value}") boot_options = self.boot_options if not boot_options is None: boot_options_str = str(boot_options) if not is_none_or_whitespace(boot_options_str): result.append( f"{option_indent}{RefindOption.BOOT_OPTIONS.value} {boot_options_str}" ) add_boot_options_str = str(self.add_boot_options) if not is_none_or_whitespace(add_boot_options_str): result.append( f"{option_indent}{RefindOption.ADD_BOOT_OPTIONS.value} {add_boot_options_str}" ) is_disabled = self.is_disabled if is_disabled: result.append(f"{option_indent}{RefindOption.DISABLED.value}") result.append(f"{main_indent}}}") return constants.NEWLINE.join(result) def is_matched_with(self, block_device: BlockDevice) -> bool: boot_options = self.boot_options return ( boot_options.is_matched_with(block_device) if boot_options is not None else False ) def can_be_used_for_bootable_snapshot(self) -> bool: loader_path = self.loader_path initrd_path = self.initrd_path boot_options = self.boot_options is_disabled = self.is_disabled return ( is_none_or_whitespace(loader_path) and (initrd_path is None or not is_empty(initrd_path)) and boot_options is None and not is_disabled ) def _get_all_boot_file_paths( self, ) -> Iterator[tuple[BootFilePathSource, str]]: source = BootFilePathSource.SUB_MENU is_disabled = self.is_disabled if not is_disabled: loader_path = self.loader_path initrd_path = self.initrd_path boot_options = self.boot_options add_boot_options = self.add_boot_options if not is_none_or_whitespace(loader_path): yield (source, none_throws(loader_path)) if not is_none_or_whitespace(initrd_path): yield (source, none_throws(initrd_path)) if not boot_options is None: yield from ( (source, initrd_option) for initrd_option in boot_options.initrd_options ) yield from ( (source, initrd_option) for initrd_option in add_boot_options.initrd_options ) @property def name(self) -> str: return self._name @property def normalized_name(self) -> str: return strip_quotes(self.name) @property def loader_path(self) -> Optional[str]: return self._loader_path @property def initrd_path(self) -> Optional[str]: return self._initrd_path @property def graphics(self) -> Optional[bool]: return self._graphics @property def boot_options(self) -> Optional[BootOptions]: return self._boot_options @property def add_boot_options(self) -> BootOptions: return self._add_boot_options @property def is_disabled(self) -> bool: return self._is_disabled @cached_property def all_boot_file_paths(self) -> Set[tuple[BootFilePathSource, str]]: return set(self._get_all_boot_file_paths()) ================================================ FILE: src/refind_btrfs/common/__init__.py ================================================ # region Licensing # SPDX-FileCopyrightText: 2020-2024 Luka Žaja # # SPDX-License-Identifier: GPL-3.0-or-later """ refind-btrfs - Generate rEFInd manual boot stanzas from Btrfs snapshots Copyright (C) 2020-2024 Luka Žaja 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, either version 3 of the License, or (at your option) any later version. 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 . """ # endregion from .boot_files_check_result import BootFilesCheckResult from .checkable_observer import CheckableObserver from .configurable_mixin import ConfigurableMixin from .package_config import ( BootStanzaGeneration, BtrfsLogo, Icon, PackageConfig, SnapshotManipulation, SnapshotSearch, ) ================================================ FILE: src/refind_btrfs/common/abc/__init__.py ================================================ # region Licensing # SPDX-FileCopyrightText: 2020-2024 Luka Žaja # # SPDX-License-Identifier: GPL-3.0-or-later """ refind-btrfs - Generate rEFInd manual boot stanzas from Btrfs snapshots Copyright (C) 2020-2024 Luka Žaja 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, either version 3 of the License, or (at your option) any later version. 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 . """ # endregion from .base_config import BaseConfig from .base_runner import BaseRunner ================================================ FILE: src/refind_btrfs/common/abc/base_config.py ================================================ # region Licensing # SPDX-FileCopyrightText: 2020-2024 Luka Žaja # # SPDX-License-Identifier: GPL-3.0-or-later """ refind-btrfs - Generate rEFInd manual boot stanzas from Btrfs snapshots Copyright (C) 2020-2024 Luka Žaja 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, either version 3 of the License, or (at your option) any later version. 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 . """ # endregion from __future__ import annotations from abc import ABC from os import stat_result from pathlib import Path from typing import Any, Optional, Self from refind_btrfs.common.enums import ConfigInitializationType from refind_btrfs.utility.helpers import checked_cast, none_throws class BaseConfig(ABC): def __init__(self, file_path: Path) -> None: self._file_path = file_path self._file_stat: Optional[stat_result] = None self._initialization_type: Optional[ConfigInitializationType] = None self.refresh_file_stat() def __eq__(self, other: object) -> bool: if self is other: return True if isinstance(other, BaseConfig): self_file_path_resolved = self.file_path.resolve() other_file_path_resolved = other.file_path.resolve() return self_file_path_resolved == other_file_path_resolved return False def __hash__(self) -> int: return hash(self.file_path.resolve()) def __getstate__(self) -> dict[str, Any]: state = self.__dict__.copy() initialization_type_key = "_initialization_type" if initialization_type_key in state: del state[initialization_type_key] return state def with_initialization_type( self, initialization_type: ConfigInitializationType ) -> Self: self._initialization_type = initialization_type return self def refresh_file_stat(self): file_path = self.file_path if file_path.exists(): self._file_stat = file_path.stat() def is_modified(self, actual_file_path: Path) -> bool: current_file_path = self.file_path if current_file_path != actual_file_path: return True current_file_stat = none_throws(self.file_stat) if actual_file_path.exists(): actual_file_stat = actual_file_path.stat() return current_file_stat.st_mtime != actual_file_stat.st_mtime return True def is_of_initialization_type( self, initialization_type: ConfigInitializationType ) -> bool: return self.initialization_type == initialization_type @property def file_path(self) -> Path: return self._file_path @property def file_stat(self) -> Optional[stat_result]: return self._file_stat @property def initialization_type(self) -> Optional[ConfigInitializationType]: return self._initialization_type ================================================ FILE: src/refind_btrfs/common/abc/base_runner.py ================================================ # region Licensing # SPDX-FileCopyrightText: 2020-2024 Luka Žaja # # SPDX-License-Identifier: GPL-3.0-or-later """ refind-btrfs - Generate rEFInd manual boot stanzas from Btrfs snapshots Copyright (C) 2020-2024 Luka Žaja 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, either version 3 of the License, or (at your option) any later version. 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 . """ # endregion from abc import ABC, abstractmethod class BaseRunner(ABC): @abstractmethod def run(self) -> int: pass ================================================ FILE: src/refind_btrfs/common/abc/commands/__init__.py ================================================ # region Licensing # SPDX-FileCopyrightText: 2020-2024 Luka Žaja # # SPDX-License-Identifier: GPL-3.0-or-later """ refind-btrfs - Generate rEFInd manual boot stanzas from Btrfs snapshots Copyright (C) 2020-2024 Luka Žaja 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, either version 3 of the License, or (at your option) any later version. 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 . """ # endregion from .device_command import DeviceCommand from .icon_command import IconCommand from .subvolume_command import SubvolumeCommand ================================================ FILE: src/refind_btrfs/common/abc/commands/device_command.py ================================================ # region Licensing # SPDX-FileCopyrightText: 2020-2024 Luka Žaja # # SPDX-License-Identifier: GPL-3.0-or-later """ refind-btrfs - Generate rEFInd manual boot stanzas from Btrfs snapshots Copyright (C) 2020-2024 Luka Žaja 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, either version 3 of the License, or (at your option) any later version. 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 . """ # endregion from abc import ABC, abstractmethod from functools import singledispatchmethod from typing import Any, Iterator from refind_btrfs.device import BlockDevice, PartitionTable, Subvolume class DeviceCommand(ABC): @abstractmethod def get_block_devices(self) -> Iterator[BlockDevice]: pass @singledispatchmethod def get_partition_table_for(self, argument: Any) -> PartitionTable: raise NotImplementedError( f"Cannot get the partition table for parameter of type '{type(argument).__name__}'!" ) @abstractmethod def save_partition_table(self, partition_table: PartitionTable) -> None: pass @get_partition_table_for.register(BlockDevice) def _block_device_overload(self, block_device: BlockDevice) -> PartitionTable: return self._block_device_partition_table(block_device) @get_partition_table_for.register(Subvolume) def _subvolume_overload(self, subvolume: Subvolume) -> PartitionTable: return self._subvolume_partition_table(subvolume) @abstractmethod def _block_device_partition_table( self, block_device: BlockDevice ) -> PartitionTable: pass @abstractmethod def _subvolume_partition_table(self, subvolume: Subvolume) -> PartitionTable: pass ================================================ FILE: src/refind_btrfs/common/abc/commands/icon_command.py ================================================ # region Licensing # SPDX-FileCopyrightText: 2020-2024 Luka Žaja # # SPDX-License-Identifier: GPL-3.0-or-later """ refind-btrfs - Generate rEFInd manual boot stanzas from Btrfs snapshots Copyright (C) 2020-2024 Luka Žaja 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, either version 3 of the License, or (at your option) any later version. 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 . """ # endregion from abc import ABC, abstractmethod from pathlib import Path from refind_btrfs.common import BtrfsLogo class IconCommand(ABC): @abstractmethod def validate_custom_icon( self, refind_config_path: Path, source_icon_path: Path, custom_icon_path: Path ) -> Path: pass @abstractmethod def embed_btrfs_logo_into_source_icon( self, refind_config_path: Path, source_icon_path: Path, btrfs_logo: BtrfsLogo ) -> Path: pass ================================================ FILE: src/refind_btrfs/common/abc/commands/subvolume_command.py ================================================ # region Licensing # SPDX-FileCopyrightText: 2020-2024 Luka Žaja # # SPDX-License-Identifier: GPL-3.0-or-later """ refind-btrfs - Generate rEFInd manual boot stanzas from Btrfs snapshots Copyright (C) 2020-2024 Luka Žaja 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, either version 3 of the License, or (at your option) any later version. 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 . """ # endregion from abc import ABC, abstractmethod from pathlib import Path from typing import Iterator, Optional from refind_btrfs.device import Subvolume class SubvolumeCommand(ABC): @abstractmethod def get_subvolume_from(self, filesystem_path: Path) -> Optional[Subvolume]: pass @abstractmethod def get_all_source_snapshots_for(self, parent: Subvolume) -> Iterator[Subvolume]: pass @abstractmethod def get_all_destination_snapshots(self) -> Iterator[Subvolume]: pass @abstractmethod def get_bootable_snapshot_from(self, source: Subvolume) -> Subvolume: pass @abstractmethod def delete_snapshot(self, snapshot: Subvolume) -> None: pass ================================================ FILE: src/refind_btrfs/common/abc/factories/__init__.py ================================================ # region Licensing # SPDX-FileCopyrightText: 2020-2024 Luka Žaja # # SPDX-License-Identifier: GPL-3.0-or-later """ refind-btrfs - Generate rEFInd manual boot stanzas from Btrfs snapshots Copyright (C) 2020-2024 Luka Žaja 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, either version 3 of the License, or (at your option) any later version. 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 . """ # endregion from .base_device_command_factory import BaseDeviceCommandFactory from .base_icon_command_factory import BaseIconCommandFactory from .base_logger_factory import BaseLoggerFactory from .base_subvolume_command_factory import BaseSubvolumeCommandFactory ================================================ FILE: src/refind_btrfs/common/abc/factories/base_device_command_factory.py ================================================ # region Licensing # SPDX-FileCopyrightText: 2020-2024 Luka Žaja # # SPDX-License-Identifier: GPL-3.0-or-later """ refind-btrfs - Generate rEFInd manual boot stanzas from Btrfs snapshots Copyright (C) 2020-2024 Luka Žaja 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, either version 3 of the License, or (at your option) any later version. 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 . """ # endregion from __future__ import annotations from abc import ABC, abstractmethod from typing import TYPE_CHECKING if TYPE_CHECKING: from ..commands import DeviceCommand class BaseDeviceCommandFactory(ABC): @abstractmethod def physical_device_command(self) -> DeviceCommand: pass @abstractmethod def live_device_command(self) -> DeviceCommand: pass @abstractmethod def static_device_command(self) -> DeviceCommand: pass ================================================ FILE: src/refind_btrfs/common/abc/factories/base_icon_command_factory.py ================================================ # region Licensing # SPDX-FileCopyrightText: 2020-2024 Luka Žaja # # SPDX-License-Identifier: GPL-3.0-or-later """ refind-btrfs - Generate rEFInd manual boot stanzas from Btrfs snapshots Copyright (C) 2020-2024 Luka Žaja 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, either version 3 of the License, or (at your option) any later version. 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 . """ # endregion from __future__ import annotations from abc import ABC, abstractmethod from typing import TYPE_CHECKING if TYPE_CHECKING: from ..commands import IconCommand class BaseIconCommandFactory(ABC): @abstractmethod def icon_command(self) -> IconCommand: pass ================================================ FILE: src/refind_btrfs/common/abc/factories/base_logger_factory.py ================================================ # region Licensing # SPDX-FileCopyrightText: 2020-2024 Luka Žaja # # SPDX-License-Identifier: GPL-3.0-or-later """ refind-btrfs - Generate rEFInd manual boot stanzas from Btrfs snapshots Copyright (C) 2020-2024 Luka Žaja 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, either version 3 of the License, or (at your option) any later version. 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 . """ # endregion import logging from abc import ABC, abstractmethod from logging import Handler, Logger from refind_btrfs.utility import LevelAwareFormatter class BaseLoggerFactory(ABC): def logger(self, name: str) -> Logger: logger = logging.getLogger(name) if not logger.hasHandlers(): logging_handler = self.get_handler() formatter = LevelAwareFormatter() logger.propagate = False logger.setLevel(logging.INFO) logging_handler.setLevel(logging.INFO) logging_handler.setFormatter(formatter) logger.addHandler(logging_handler) return logger @abstractmethod def get_handler(self) -> Handler: pass ================================================ FILE: src/refind_btrfs/common/abc/factories/base_subvolume_command_factory.py ================================================ # region Licensing # SPDX-FileCopyrightText: 2020-2024 Luka Žaja # # SPDX-License-Identifier: GPL-3.0-or-later """ refind-btrfs - Generate rEFInd manual boot stanzas from Btrfs snapshots Copyright (C) 2020-2024 Luka Žaja 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, either version 3 of the License, or (at your option) any later version. 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 . """ # endregion from __future__ import annotations from abc import ABC, abstractmethod from typing import TYPE_CHECKING if TYPE_CHECKING: from ..commands import SubvolumeCommand class BaseSubvolumeCommandFactory(ABC): @abstractmethod def subvolume_command(self) -> SubvolumeCommand: pass ================================================ FILE: src/refind_btrfs/common/abc/providers/__init__.py ================================================ # region Licensing # SPDX-FileCopyrightText: 2020-2024 Luka Žaja # # SPDX-License-Identifier: GPL-3.0-or-later """ refind-btrfs - Generate rEFInd manual boot stanzas from Btrfs snapshots Copyright (C) 2020-2024 Luka Žaja 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, either version 3 of the License, or (at your option) any later version. 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 . """ # endregion from .base_package_config_provider import BasePackageConfigProvider from .base_persistence_provider import BasePersistenceProvider from .base_refind_config_provider import BaseRefindConfigProvider ================================================ FILE: src/refind_btrfs/common/abc/providers/base_package_config_provider.py ================================================ # region Licensing # SPDX-FileCopyrightText: 2020-2024 Luka Žaja # # SPDX-License-Identifier: GPL-3.0-or-later """ refind-btrfs - Generate rEFInd manual boot stanzas from Btrfs snapshots Copyright (C) 2020-2024 Luka Žaja 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, either version 3 of the License, or (at your option) any later version. 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 . """ # endregion from __future__ import annotations from abc import ABC, abstractmethod from typing import TYPE_CHECKING if TYPE_CHECKING: from refind_btrfs.common import PackageConfig class BasePackageConfigProvider(ABC): @abstractmethod def get_config(self) -> PackageConfig: pass ================================================ FILE: src/refind_btrfs/common/abc/providers/base_persistence_provider.py ================================================ # region Licensing # SPDX-FileCopyrightText: 2020-2024 Luka Žaja # # SPDX-License-Identifier: GPL-3.0-or-later """ refind-btrfs - Generate rEFInd manual boot stanzas from Btrfs snapshots Copyright (C) 2020-2024 Luka Žaja 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, either version 3 of the License, or (at your option) any later version. 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 . """ # endregion from __future__ import annotations from abc import ABC, abstractmethod from pathlib import Path from typing import TYPE_CHECKING, Optional if TYPE_CHECKING: from refind_btrfs.boot import RefindConfig from refind_btrfs.common import PackageConfig from refind_btrfs.state_management.model import ProcessingResult class BasePersistenceProvider(ABC): @abstractmethod def get_package_config(self) -> Optional[PackageConfig]: pass @abstractmethod def save_package_config(self, value: PackageConfig) -> None: pass @abstractmethod def get_refind_config(self, file_path: Path) -> Optional[RefindConfig]: pass @abstractmethod def save_refind_config(self, value: RefindConfig) -> None: pass @abstractmethod def get_previous_run_result(self) -> ProcessingResult: pass @abstractmethod def save_current_run_result(self, value: ProcessingResult) -> None: pass ================================================ FILE: src/refind_btrfs/common/abc/providers/base_refind_config_provider.py ================================================ # region Licensing # SPDX-FileCopyrightText: 2020-2024 Luka Žaja # # SPDX-License-Identifier: GPL-3.0-or-later """ refind-btrfs - Generate rEFInd manual boot stanzas from Btrfs snapshots Copyright (C) 2020-2024 Luka Žaja 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, either version 3 of the License, or (at your option) any later version. 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 . """ # endregion from __future__ import annotations from abc import ABC, abstractmethod from typing import TYPE_CHECKING if TYPE_CHECKING: from refind_btrfs.boot import RefindConfig from refind_btrfs.device import Partition class BaseRefindConfigProvider(ABC): @abstractmethod def get_config(self, partition: Partition) -> RefindConfig: pass @abstractmethod def save_config(self, config: RefindConfig) -> None: pass @abstractmethod def append_to_config(self, config: RefindConfig) -> None: pass ================================================ FILE: src/refind_btrfs/common/boot_files_check_result.py ================================================ # region Licensing # SPDX-FileCopyrightText: 2020-2024 Luka Žaja # # SPDX-License-Identifier: GPL-3.0-or-later """ refind-btrfs - Generate rEFInd manual boot stanzas from Btrfs snapshots Copyright (C) 2020-2024 Luka Žaja 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, either version 3 of the License, or (at your option) any later version. 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 . """ # endregion from typing import NamedTuple from refind_btrfs.utility.helpers import has_items class BootFilesCheckResult(NamedTuple): required_by_boot_stanza_name: str expected_logical_path: str matched_boot_files: list[str] unmatched_boot_files: list[str] def has_unmatched_boot_files(self) -> bool: return has_items(self.unmatched_boot_files) ================================================ FILE: src/refind_btrfs/common/checkable_observer.py ================================================ # region Licensing # SPDX-FileCopyrightText: 2020-2024 Luka Žaja # # SPDX-License-Identifier: GPL-3.0-or-later """ refind-btrfs - Generate rEFInd manual boot stanzas from Btrfs snapshots Copyright (C) 2020-2024 Luka Žaja 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, either version 3 of the License, or (at your option) any later version. 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 . """ # endregion from typing import Optional from watchdog.observers import Observer from watchdog.observers.api import DEFAULT_OBSERVER_TIMEOUT class CheckableObserver(Observer): def __init__(self): super().__init__(timeout=DEFAULT_OBSERVER_TIMEOUT) self._exception: Optional[Exception] = None # pylint: disable=raising-bad-type def check(self) -> None: exception = self._exception if exception is not None: raise exception ================================================ FILE: src/refind_btrfs/common/configurable_mixin.py ================================================ # region Licensing # SPDX-FileCopyrightText: 2020-2024 Luka Žaja # # SPDX-License-Identifier: GPL-3.0-or-later """ refind-btrfs - Generate rEFInd manual boot stanzas from Btrfs snapshots Copyright (C) 2020-2024 Luka Žaja 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, either version 3 of the License, or (at your option) any later version. 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 . """ # endregion from __future__ import annotations from typing import TYPE_CHECKING from refind_btrfs.common.abc.providers import BasePackageConfigProvider if TYPE_CHECKING: from refind_btrfs.common import PackageConfig class ConfigurableMixin: def __init__(self, package_config_provider: BasePackageConfigProvider) -> None: self._package_config_provider = package_config_provider @property def package_config(self) -> PackageConfig: package_config_provider = self._package_config_provider return package_config_provider.get_config() ================================================ FILE: src/refind_btrfs/common/constants.py ================================================ # region Licensing # SPDX-FileCopyrightText: 2020-2024 Luka Žaja # # SPDX-License-Identifier: GPL-3.0-or-later """ refind-btrfs - Generate rEFInd manual boot stanzas from Btrfs snapshots Copyright (C) 2020-2024 Luka Žaja 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, either version 3 of the License, or (at your option) any later version. 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 . """ # endregion from pathlib import Path from uuid import UUID PACKAGE_NAME = "refind-btrfs" ROOT_UID = 0 EX_NOT_OK = 1 EX_CTRL_C_INTERRUPT = 130 NOTIFICATION_READY = "READY=1" NOTIFICATION_STOPPING = "STOPPING=1" NOTIFICATION_STATUS = "STATUS={0}" NOTIFICATION_ERRNO = "ERRNO={0}" MESSAGE_CTRL_C_INTERRUPT = "Ctrl+C interrupt detected, exiting..." MESSAGE_UNEXPECTED_ERROR = "An unexpected error happened, exiting..." WATCH_TIMEOUT = 1 BACKGROUND_MODE_PID_NAME = f"{PACKAGE_NAME}-watchdog" MTAB_PT_TYPE = "mtab" FSTAB_PT_TYPE = "fstab" ESP_PART_TYPE_CODE = 0xEF ESP_PART_TYPE_UUID = UUID(hex="c12a7328-f81f-11d2-ba4b-00a0c93ec93b") ESP_FS_TYPE = "vfat" BTRFS_TYPE = "btrfs" SNAPSHOT_SELECTION_COUNT_INFINITY = "inf" SNAPSHOTS_ROOT_DIR_PERMISSIONS = 0o750 PARAMETERIZED_OPTION_SEPARATOR = "=" BOOT_OPTION_SEPARATOR = " " COLUMN_SEPARATOR = "," ROOT_PREFIX = f"root{PARAMETERIZED_OPTION_SEPARATOR}" ROOTFLAGS_PREFIX = f"rootflags{PARAMETERIZED_OPTION_SEPARATOR}" INITRD_PREFIX = f"initrd{PARAMETERIZED_OPTION_SEPARATOR}" SUBVOL_OPTION = "subvol" SUBVOLID_OPTION = "subvolid" SPACE = " " TAB = SPACE * 4 SINGLE_QUOTE = "'" DOUBLE_QUOTE = '"' BACKSLASH = "\\" FORWARD_SLASH = "/" NEWLINE = "\n" EMPTY_STR = "" EMPTY_HEX_UUID = "00000000-0000-0000-0000-000000000000" EMPTY_UUID = UUID(hex=EMPTY_HEX_UUID) EMPTY_PATH = Path(".") DEFAULT_ITEMS_SEPARATOR = COLUMN_SEPARATOR + SPACE DEFAULT_DIR_SEPARATOR_REPLACEMENT: tuple[str, str] = (BACKSLASH, FORWARD_SLASH) WHITESPACE_PATTERN = r"\s+" INCLUDE_OPTION_PATTERN = r"^include .+$" PARAMETERIZED_OPTION_PREFIX_PATTERN = r"^\S+=" DIR_SEPARATOR_PATTERN = f"({BACKSLASH * 2}|{FORWARD_SLASH})" SUBVOLUME_NAME_PATTERN = ( r"((rw|ro)(subvol|snap))_\d{4}-\d{2}-\d{2}_\d{2}-\d{2}-\d{2}_ID\d+" ) CONFIG_FILE_EXTENSION = ".conf" CONFIG_FILENAME = PACKAGE_NAME + CONFIG_FILE_EXTENSION SNAPSHOT_STANZAS_DIR_NAME = "btrfs-snapshot-stanzas" ICONS_DIR = "icons" ROOT_DIR = Path("/") BOOT_DIR = Path("boot") ETC_DIR = Path("etc") VAR_DIR = Path("var") LIB_DIR = Path("lib") FSTAB_FILE = ETC_DIR / "fstab" PACKAGE_CONFIG_FILE = ROOT_DIR / ETC_DIR / CONFIG_FILENAME PACKAGE_LIB_DIR = ROOT_DIR / VAR_DIR / LIB_DIR / PACKAGE_NAME BTRFS_LOGOS_DIR = PACKAGE_LIB_DIR / ICONS_DIR / "btrfs_logo" DB_FILE = PACKAGE_LIB_DIR / "local_db" DB_ITEM_VERSION_SUFFIX = "version" ================================================ FILE: src/refind_btrfs/common/enums.py ================================================ # region Licensing # SPDX-FileCopyrightText: 2020-2024 Luka Žaja # # SPDX-License-Identifier: GPL-3.0-or-later """ refind-btrfs - Generate rEFInd manual boot stanzas from Btrfs snapshots Copyright (C) 2020-2024 Luka Žaja 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, either version 3 of the License, or (at your option) any later version. 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 . """ # endregion from enum import Enum, auto, unique from typing import Any class AutoNameToLower(Enum): # pylint: disable=arguments-differ, unused-argument @staticmethod def _generate_next_value_( name: str, start: int, count: int, last_values: list[Any] ) -> Any: return name.lower() @unique class RunMode(AutoNameToLower): ONE_TIME = "one-time" BACKGROUND = auto() @unique class LsblkJsonKey(AutoNameToLower): BLOCKDEVICES = auto() CHILDREN = auto() @unique class LsblkColumn(Enum): DEVICE_NAME = "name" DEVICE_TYPE = "type" MAJOR_MINOR = "maj:min" PTABLE_UUID = "ptuuid" PTABLE_TYPE = "pttype" PART_UUID = "partuuid" PART_TYPE = "parttype" PART_LABEL = "partlabel" FS_UUID = "uuid" FS_TYPE = "fstype" FS_LABEL = "label" FS_MOUNT_POINT = "mountpoint" @unique class FindmntJsonKey(AutoNameToLower): FILESYSTEMS = auto() @unique class FindmntColumn(Enum): DEVICE_NAME = "source" PART_UUID = "partuuid" PART_LABEL = "partlabel" FS_UUID = "uuid" FS_TYPE = "fstype" FS_LABEL = "label" FS_MOUNT_POINT = "target" FS_MOUNT_OPTIONS = "options" @unique class FstabColumn(Enum): DEVICE_NAME = 0 FS_MOUNT_POINT = 1 FS_TYPE = 2 FS_MOUNT_OPTIONS = 3 FS_DUMP = 4 FS_FSCK = 5 @unique class PathRelation(Enum): UNRELATED = 0 SAME = 1 FIRST_NESTED_IN_SECOND = 2 SECOND_NESTED_IN_FIRST = 3 @unique class ConfigInitializationType(Enum): PARSED = 0 PERSISTED = 1 @unique class TopLevelConfigKey(AutoNameToLower): EXIT_IF_ROOT_IS_SNAPSHOT = auto() EXIT_IF_NO_CHANGES_ARE_DETECTED = auto() ESP_UUID = auto() SNAPSHOT_SEARCH = "snapshot-search" SNAPSHOT_MANIPULATION = "snapshot-manipulation" BOOT_STANZA_GENERATION = "boot-stanza-generation" @unique class SnapshotSearchConfigKey(AutoNameToLower): DIRECTORY = auto() IS_NESTED = auto() MAX_DEPTH = auto() @unique class SnapshotManipulationConfigKey(AutoNameToLower): SELECTION_COUNT = auto() MODIFY_READ_ONLY_FLAG = auto() DESTINATION_DIRECTORY = auto() CLEANUP_EXCLUSION = auto() @unique class BootStanzaGenerationConfigKey(AutoNameToLower): REFIND_CONFIG = auto() INCLUDE_PATHS = auto() INCLUDE_SUB_MENUS = auto() SOURCE_EXCLUSION = auto() ICON = auto() @unique class IconConfigKey(AutoNameToLower): MODE = auto() PATH = auto() BTRFS_LOGO = "btrfs-logo" @unique class BootStanzaIconGenerationMode(AutoNameToLower): DEFAULT = auto() CUSTOM = auto() EMBED_BTRFS_LOGO = auto() @unique class BtrfsLogoConfigKey(AutoNameToLower): VARIANT = auto() SIZE = auto() HORIZONTAL_ALIGNMENT = auto() VERTICAL_ALIGNMENT = auto() @unique class BtrfsLogoVariant(AutoNameToLower): ORIGINAL = auto() INVERTED = auto() @unique class BtrfsLogoSize(AutoNameToLower): SMALL = auto() MEDIUM = auto() LARGE = auto() @unique class BtrfsLogoHorizontalAlignment(AutoNameToLower): LEFT = auto() CENTER = auto() RIGHT = auto() @unique class BtrfsLogoVerticalAlignment(AutoNameToLower): TOP = auto() CENTER = auto() BOTTOM = auto() @unique class LocalDbKey(AutoNameToLower): PACKAGE_CONFIG = auto() REFIND_CONFIGS = auto() PROCESSING_RESULT = auto() @unique class RefindOption(Enum): ADD_BOOT_OPTIONS = "add_options" BOOT_OPTIONS = "options" DISABLED = "disabled" FIRMWARE_BOOTNUM = "firmware_bootnum" GRAPHICS = "graphics" ICON = "icon" INCLUDE = "include" INITRD = "initrd" LOADER = "loader" MENU_ENTRY = "menuentry" OS_TYPE = "ostype" SUB_MENU_ENTRY = "submenuentry" VOLUME = "volume" @unique class OSTypeParameter(Enum): MAC_OS = "MacOS" LINUX = "Linux" ELILO = "ELILO" WINDOWS = "Windows" XOM = "XOM" @unique class GraphicsParameter(AutoNameToLower): ON = auto() OFF = auto() @unique class BootFilePathSource(Enum): BOOT_STANZA = 0 SUB_MENU = 1 @unique class StateNames(AutoNameToLower): INITIAL = auto() INITIALIZE_BLOCK_DEVICES = auto() INITIALIZE_ROOT_SUBVOLUME = auto() INITIALIZE_MATCHED_BOOT_STANZAS = auto() INITIALIZE_PREPARED_SNAPSHOTS = auto() COMBINE_BOOT_STANZAS_WITH_SNAPSHOTS = auto() PROCESS_CHANGES = auto() FINAL = auto() ================================================ FILE: src/refind_btrfs/common/exceptions.py ================================================ # region Licensing # SPDX-FileCopyrightText: 2020-2024 Luka Žaja # # SPDX-License-Identifier: GPL-3.0-or-later """ refind-btrfs - Generate rEFInd manual boot stanzas from Btrfs snapshots Copyright (C) 2020-2024 Luka Žaja 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, either version 3 of the License, or (at your option) any later version. 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 . """ # endregion from more_itertools import first_true from refind_btrfs.common import constants from refind_btrfs.utility.helpers import checked_cast class RefindBtrfsError(Exception): def __init__(self, *args: object) -> None: super().__init__(args) if args is not None: self._message = checked_cast( str, first_true( args, pred=lambda arg: isinstance(arg, str), default=constants.EMPTY_STR, ), ) else: self._message = constants.EMPTY_STR def __str__(self) -> str: return f"{self.error_type_name}: {self.formatted_message}" @property def formatted_message(self) -> str: return self._message @property def error_type_name(self) -> str: return type(self).__name__ class PartitionError(RefindBtrfsError): pass class SubvolumeError(RefindBtrfsError): pass class SnapshotMountedAsRootError(SubvolumeError): pass class SnapshotExcludedFromDeletionError(SubvolumeError): pass class PackageConfigError(RefindBtrfsError): pass class RefindConfigError(RefindBtrfsError): pass class RefindSyntaxError(RefindBtrfsError): def __init__(self, line: int, column: int, message: str) -> None: super().__init__(message) self._line = line self._column = column @property def formatted_message(self) -> str: return ( f"line - {self._line}, column - {self._column}, message - '{self._message}'" ) class NoChangesDetectedError(RefindBtrfsError): pass ================================================ FILE: src/refind_btrfs/common/package_config.py ================================================ # region Licensing # SPDX-FileCopyrightText: 2020-2024 Luka Žaja # # SPDX-License-Identifier: GPL-3.0-or-later """ refind-btrfs - Generate rEFInd manual boot stanzas from Btrfs snapshots Copyright (C) 2020-2024 Luka Žaja 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, either version 3 of the License, or (at your option) any later version. 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 . """ # endregion from __future__ import annotations from functools import cached_property from pathlib import Path from typing import Iterable, Iterator, NamedTuple, Optional, Self, Set from uuid import UUID from refind_btrfs.common import constants from refind_btrfs.common.abc import BaseConfig from refind_btrfs.common.enums import ( BootStanzaIconGenerationMode, BtrfsLogoHorizontalAlignment, BtrfsLogoSize, BtrfsLogoVariant, BtrfsLogoVerticalAlignment, ) from refind_btrfs.device import BlockDevice, Subvolume from refind_btrfs.utility.helpers import find_all_directories_in, has_items class SnapshotSearch(NamedTuple): directory: Path is_nested: bool max_depth: int def __eq__(self, other: object) -> bool: if self is other: return True if isinstance(other, SnapshotSearch): self_directory_resolved = self.directory.resolve() other_directory_resolved = other.directory.resolve() return self_directory_resolved == other_directory_resolved return False class SnapshotManipulation(NamedTuple): selection_count: int modify_read_only_flag: bool destination_directory: Path cleanup_exclusion: Set[Subvolume] class BtrfsLogo(NamedTuple): variant: BtrfsLogoVariant size: BtrfsLogoSize horizontal_alignment: BtrfsLogoHorizontalAlignment vertical_alignment: BtrfsLogoVerticalAlignment class Icon(NamedTuple): mode: BootStanzaIconGenerationMode path: Path btrfs_logo: BtrfsLogo class BootStanzaGeneration(NamedTuple): refind_config: str include_paths: bool include_sub_menus: bool source_exclusion: Set[str] icon: Icon def with_include_paths(self, boot_device: Optional[BlockDevice]) -> Self: include_paths = self.include_paths if include_paths: include_paths = boot_device is None return BootStanzaGeneration( self.refind_config, include_paths, self.include_sub_menus, self.source_exclusion, self.icon, ) class PackageConfig(BaseConfig): def __init__( self, esp_uuid: UUID, exit_if_root_is_snapshot: bool, exit_if_no_changes_are_detected: bool, snapshot_searches: Iterable[SnapshotSearch], snapshot_manipulation: SnapshotManipulation, boot_stanza_generation: BootStanzaGeneration, ) -> None: super().__init__(constants.PACKAGE_CONFIG_FILE) self._esp_uuid = esp_uuid self._exit_if_root_is_snapshot = exit_if_root_is_snapshot self._exit_if_no_changes_are_detected = exit_if_no_changes_are_detected self._snapshot_searches = list(snapshot_searches) self._snapshot_manipulation = snapshot_manipulation self._boot_stanza_generation = boot_stanza_generation def _get_directories_for_watch(self) -> Iterator[Path]: snapshot_searches = self.snapshot_searches if has_items(snapshot_searches): for snapshot_search in snapshot_searches: directory = snapshot_search.directory max_depth = snapshot_search.max_depth - 1 yield from find_all_directories_in(directory, max_depth) @property def esp_uuid(self) -> UUID: return self._esp_uuid @property def exit_if_root_is_snapshot(self) -> bool: return self._exit_if_root_is_snapshot @property def exit_if_no_changes_are_detected(self) -> bool: return self._exit_if_no_changes_are_detected @property def snapshot_searches(self) -> list[SnapshotSearch]: return self._snapshot_searches @property def snapshot_manipulation(self) -> SnapshotManipulation: return self._snapshot_manipulation @property def boot_stanza_generation(self) -> BootStanzaGeneration: return self._boot_stanza_generation @cached_property def directories_for_watch(self) -> Set[Path]: return set(self._get_directories_for_watch()) ================================================ FILE: src/refind_btrfs/console/__init__.py ================================================ # region Licensing # SPDX-FileCopyrightText: 2020-2024 Luka Žaja # # SPDX-License-Identifier: GPL-3.0-or-later """ refind-btrfs - Generate rEFInd manual boot stanzas from Btrfs snapshots Copyright (C) 2020-2024 Luka Žaja 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, either version 3 of the License, or (at your option) any later version. 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 . """ # endregion from .cli_runner import CLIRunner ================================================ FILE: src/refind_btrfs/console/cli_runner.py ================================================ # region Licensing # SPDX-FileCopyrightText: 2020-2024 Luka Žaja # # SPDX-License-Identifier: GPL-3.0-or-later """ refind-btrfs - Generate rEFInd manual boot stanzas from Btrfs snapshots Copyright (C) 2020-2024 Luka Žaja 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, either version 3 of the License, or (at your option) any later version. 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 . """ # endregion import os from injector import inject from refind_btrfs.common import constants from refind_btrfs.common.abc import BaseRunner from refind_btrfs.common.abc.factories import BaseLoggerFactory from refind_btrfs.common.exceptions import SnapshotMountedAsRootError from refind_btrfs.state_management import RefindBtrfsMachine class CLIRunner(BaseRunner): @inject def __init__( self, logger_factory: BaseLoggerFactory, machine: RefindBtrfsMachine ) -> None: self._logger = logger_factory.logger(__name__) self._machine = machine def run(self) -> int: logger = self._logger machine = self._machine exit_code = os.EX_OK try: if not machine.run(): exit_code = constants.EX_NOT_OK except SnapshotMountedAsRootError as e: logger.warning(e.formatted_message) except KeyboardInterrupt: exit_code = constants.EX_CTRL_C_INTERRUPT logger.warning(constants.MESSAGE_CTRL_C_INTERRUPT) return exit_code ================================================ FILE: src/refind_btrfs/data/refind-btrfs ================================================ #!/bin/bash python -m refind_btrfs --run-mode one-time ================================================ FILE: src/refind_btrfs/data/refind-btrfs.conf-sample ================================================ ####################### ## refind-btrfs.conf ## ####################### # TOML syntax # esp_uuid = ## Explicitly defined ESP's Part-UUID which can be used in case the ESP itself ## cannot be automatically located on the system (for whatever reason). ## This option is, by default, defined as an empty UUID which means that it is ## ignored. esp_uuid = "00000000-0000-0000-0000-000000000000" # exit_if_root_is_snapshot = ## Whether to issue a warning and prematurely exit in case the root partition ## is already mounted as a snapshot. ## WARNING: Disabling this option is considered experimental and may result in ## unstable and/or erroneous behavior. exit_if_root_is_snapshot = true # exit_if_no_changes_are_detected = ## Whether to issue a warning and prematurely exit in case no changes were ## detected by comparing the preparation results of the current run with those ## of the previous run (if it exists). ## Changes are considered to be detected in case any of the following ## conditions are satisfied: ## • this configuration file was modified ## • rEFInd's configuration file (main or included) was modified ## • at least one snapshot was found (either for addition or removal) ## The time of last modification (st_mtime) is used to detect file changes ## instead of comparing their contents. exit_if_no_changes_are_detected = true # [[snapshot-search]] ## Array of objects used to configure the behavior of searching for snapshots. ## The directory (or directories) listed in this array (including nested ## directories, up to "max_depth" - 1) are also watched for changes by the ## background running mode. # # directory = ## Directory in which to search for snapshots (absolute filesystem path). ## WARNING: This directory must not be the same as or nested in the directory ## defined by the "destination_dir" option (shown further below). # # is_nested = ## Whether to search for snapshots nested within another snapshot. Only one ## level of nesting is supported and a search is performed in the same ## directory (if it exists) that is, in this context, relative to the found ## snapshot's root directory instead of the system's root directory. The same ## maximum search depth is used, as well. ## Setting this option to "false" potentially also means stopping the search ## prematurely (i.e., before the maximum search depth was ever reached) in ## those branches in which a snapshot was found. # # max_depth = ## Maximum search depth relative to the search directory. ## WARNING: Defining a large value can seriously impact performance (of both ## searching for snapshots and watching for directory changes) in case the tree ## (whose root is the search directory) is sufficiently large (deep and/or ## wide). [[snapshot-search]] directory = "/.snapshots" is_nested = false max_depth = 2 # [snapshot-manipulation] ## Object used to configure the behavior of preparatory steps required ## to enable booting into snapshots as well as deleting those that aren't ## needed anymore. # # selection_count = or ## Number of snapshots (sorted descending by creation time) to include or ## "inf" to always include every currently present snapshot. # # modify_read_only_flag = ## Whether to change the read-only flag of a snapshot instead of creating ## a new writable snapshot from it. This option has no meaning for those ## snapshots that are already writable. # # destination_directory = ## Directory in which writable snapshots are to be placed (absolute filesystem ## path). This option has no meaning in case the "modify_read_only_flag" option ## is set to "true". It needn't exist beforehand as it is created in case it ## doesn't (including its missing parents, if any). ## WARNING: This directory must not be the same as or nested in an ony of the ## snapshot search directories. # # cleanup_exclusion = > ## Array comprised of UUIDs (duplicates are ignored) of previously ## created writable snapshots that are to be excluded during automatic cleanup. ## These snapshots will not be deleted and should always appear as part of a ## generated boot stanza. ## See the output of "btrfs subvolume show " for ## the expected format (shown in the "UUID" column). Same remark applies here ## with regards to the "modify_read_only_flag" option. [snapshot-manipulation] selection_count = 5 modify_read_only_flag = false destination_directory = "/root/.refind-btrfs" cleanup_exclusion = [] # [boot-stanza-generation] ## Object used to configure the process of combining the source boot stanza ## with previously prepared snapshots into a generated boot stanza. # # refind_config = ## Name of rEFInd's main configuration file which must reside somewhere on ## the ESP. This option must not be defined as a path (neither absolute nor ## relative). # # include_paths = ## Whether to adjust the "loader" and "initrd" paths found in the source boot ## stanza. Setting this option to "true" while having a separate /boot ## partition has no meaning and is ignored. # # include_sub_menus = ## Whether to include sub-menus ("submenuentry") defined as part of the source ## boot stanza in the generated boot stanza. If set to "true", only those ## sub-menus which do not override the main stanza's "loader" and "options" ## fields and which do not delete (i.e., set it to nothing) its "initrd" field ## are taken into consideration. ## WARNING: Enabling this option in combination with setting a large ## "selection_count" value (greater than 10, for example) or, worse yet, by ## setting it to "inf" can potentially result in an overcrowded "Boot Options" ## menu. # ## source_exclusion = > ## Array comprised of loader filenames ("loader") with which the matched source ## boot stanzas can be arbitrarily excluded from processing, i.e., these boot ## stanzas will not be taken into account during the generation phase. ## For example, it can be defined as: ["vmlinuz-linux", "vmlinuz-linux-lts"]. ## WARNING: This array must not contain all of the matched source boot stanza's ## loader filenames. If it does, an error is issued and a premature exit is ## performed. ## Also, a manual cleanup of the generated boot stanza (or stanzas) and its ## inclusion within the rEFInd's main configuration file is required in case ## the array's members were defined after the fact. [boot-stanza-generation] refind_config = "refind.conf" include_paths = true include_sub_menus = false source_exclusion = [] # [boot-stanza-generation.icon] ## Subobject used to configure the process of defining the generated boot ## stanza's icon. # # mode = ## Selected mode of icon generation which can be defined as one of: ## • "default" - the source boot stanza's icon is reused, as is ## • "custom" - a user provided image file path is used as the icon ## • "embed_btrfs_logo" - the Btrfs logo is embedded into the source boot ## stanza's icon # ## path = ## Path of the user provided image file, relative to whichever directory the ## file defined by the "refind_config" option was found. This option is taken ## into consideration in case the "mode" option is set to "custom" but is ## otherwise ignored. ## WARNING: The format of the image located at this path must be one of those ## which rEFInd itself supports, that is one of the following: PNG, JPEG, BMP ## or ICNS. [boot-stanza-generation.icon] mode = "default" path = "btrfs-snapshot-stanzas/icons/sample_icon.png" # [boot-stanza-generation.icon.btrfs-logo] ## Subobject used to configure the behavior of embedding the Btrfs logo into ## the source boot stanza's icon. It is taken into consideration in case the ## "mode" option is set to "embed_btrfs_logo" but is otherwise ignored. ## WARNING: The source boot stanza icon's format must be PNG and its dimensions ## (width or height) must exceed those defined by the "size" option. # # variant = ## Btrfs logo variant to be used for embedding which can be defined as one of: ## • "original" - dark variant, suitable for light themes (including the ## default theme) ## • "inverted" - light variant created by inverting the original logo's ## pixels' color values, suitable for dark themes # # size = ## Size of the chosen Btrfs logo's variant defined by the "type" option. Both ## variants come in three different sizes which should be a sufficiently ## flexible choice and as such suitable for a decent number of different OS ## icons, both default and custom. It can be defined as one of: ## • "small" - 32x20 pixels ## • "medium" - 48x30 pixels ## • "large" - 64x40 pixels # # horizontal_alignment = ## Horizontal alignment (x-axis) of the embedded Btrfs logo which can be ## defined as one of: ## • "left" ## • "center" ## • "right" # # vertical_alignment = ## Vertical alignment (y-axis) of the embedded Btrfs logo which can be defined ## as one of: ## • "top" ## • "center" ## • "bottom" [boot-stanza-generation.icon.btrfs-logo] variant = "original" size = "medium" horizontal_alignment = "center" vertical_alignment = "center" ================================================ FILE: src/refind_btrfs/data/refind-btrfs.service ================================================ [Unit] Description=Generate rEFInd manual boot stanzas from Btrfs snapshots After=multi-user.target Before=snapper-boot.service [Service] Type=notify NotifyAccess=main KillMode=mixed KillSignal=SIGTERM RestartKillSignal=SIGTERM ExecStart=/usr/bin/python -m refind_btrfs --run-mode background [Install] WantedBy=multi-user.target ================================================ FILE: src/refind_btrfs/device/__init__.py ================================================ # region Licensing # SPDX-FileCopyrightText: 2020-2024 Luka Žaja # # SPDX-License-Identifier: GPL-3.0-or-later """ refind-btrfs - Generate rEFInd manual boot stanzas from Btrfs snapshots Copyright (C) 2020-2024 Luka Žaja 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, either version 3 of the License, or (at your option) any later version. 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 . """ # endregion from .block_device import BlockDevice from .filesystem import Filesystem from .mount_options import MountOptions from .partition import Partition from .partition_table import PartitionTable from .subvolume import NumIdRelation, Subvolume, UuidRelation ================================================ FILE: src/refind_btrfs/device/block_device.py ================================================ # region Licensing # SPDX-FileCopyrightText: 2020-2024 Luka Žaja # # SPDX-License-Identifier: GPL-3.0-or-later """ refind-btrfs - Generate rEFInd manual boot stanzas from Btrfs snapshots Copyright (C) 2020-2024 Luka Žaja 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, either version 3 of the License, or (at your option) any later version. 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 . """ # endregion from __future__ import annotations import re from typing import Iterable, Optional, Self, Union from refind_btrfs.common.abc.factories import BaseDeviceCommandFactory from refind_btrfs.utility.helpers import has_items, none_throws from .partition import Partition from .partition_table import PartitionTable class BlockDevice: def __init__(self, name: str, d_type: str, major_minor: str) -> None: self._name = name self._d_type = d_type major_minor_parsed = BlockDevice.try_parse_major_minor(major_minor) self._major_number = major_minor_parsed[0] self._minor_number = major_minor_parsed[1] self._physical_partition_table: Optional[PartitionTable] = None self._live_partition_table: Optional[PartitionTable] = None self._dependencies: Optional[list[BlockDevice]] = None def with_dependencies(self, dependencies: Iterable[BlockDevice]) -> Self: self._dependencies = list(dependencies) return self def initialize_partition_tables_using( self, device_command_factory: BaseDeviceCommandFactory, ) -> None: if not self.has_physical_partition_table(): physical_device_command = device_command_factory.physical_device_command() self._physical_partition_table = ( physical_device_command.get_partition_table_for(self) ) if not self.has_live_partition_table(): live_device_command = device_command_factory.live_device_command() self._live_partition_table = live_device_command.get_partition_table_for( self ) def is_matched_with(self, name: str) -> bool: if self.name == name: return True else: dependencies = self.dependencies if has_items(dependencies): return any( dependency.is_matched_with(name) for dependency in none_throws(dependencies) ) return False def has_physical_partition_table(self) -> bool: return self.physical_partition_table is not None def has_live_partition_table(self) -> bool: return self.live_partition_table is not None def has_esp(self) -> bool: return self.esp is not None def has_root(self) -> bool: return self.root is not None def has_boot(self) -> bool: return self.boot is not None @staticmethod def try_parse_major_minor(value: str) -> Union[list[int], list[None]]: match = re.fullmatch(r"\d+:\d+", value) if match: return [int(split_number) for split_number in match.group().split(":")] return [None, None] @property def name(self) -> str: return self._name @property def d_type(self) -> str: return self._d_type @property def major_number(self) -> Optional[int]: return self._major_number @property def minor_number(self) -> Optional[int]: return self._minor_number @property def physical_partition_table( self, ) -> Optional[PartitionTable]: return self._physical_partition_table @property def live_partition_table( self, ) -> Optional[PartitionTable]: return self._live_partition_table @property def dependencies(self) -> Optional[list[BlockDevice]]: return self._dependencies @property def esp(self) -> Optional[Partition]: if self.has_physical_partition_table(): return none_throws(self.physical_partition_table).esp return None @property def root(self) -> Optional[Partition]: if self.has_live_partition_table(): return none_throws(self.live_partition_table).root return None @property def boot(self) -> Optional[Partition]: if self.has_live_partition_table(): return none_throws(self.live_partition_table).boot return None ================================================ FILE: src/refind_btrfs/device/filesystem.py ================================================ # region Licensing # SPDX-FileCopyrightText: 2020-2024 Luka Žaja # # SPDX-License-Identifier: GPL-3.0-or-later """ refind-btrfs - Generate rEFInd manual boot stanzas from Btrfs snapshots Copyright (C) 2020-2024 Luka Žaja 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, either version 3 of the License, or (at your option) any later version. 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 . """ # endregion from __future__ import annotations from pathlib import Path from typing import Optional, Self from refind_btrfs.common.abc.factories import BaseSubvolumeCommandFactory from refind_btrfs.utility.helpers import is_none_or_whitespace from .mount_options import MountOptions from .subvolume import Subvolume class Filesystem: def __init__(self, uuid: str, label: str, fs_type: str, mount_point: str) -> None: self._uuid = uuid self._label = label self._fs_type = fs_type self._mount_point = mount_point self._dump: Optional[int] = None self._fsck: Optional[int] = None self._mount_options: Optional[MountOptions] = None self._subvolume: Optional[Subvolume] = None def with_dump_and_fsck(self, dump: int, fsck: int) -> Self: self._dump = dump self._fsck = fsck return self def with_mount_options(self, raw_mount_options: str) -> Self: self._mount_options = ( MountOptions(raw_mount_options) if not is_none_or_whitespace(raw_mount_options) else None ) return self def initialize_subvolume_using( self, subvolume_command_factory: BaseSubvolumeCommandFactory ) -> None: if not self.has_subvolume(): filesystem_path = Path(self.mount_point) subvolume_command = subvolume_command_factory.subvolume_command() subvolume = subvolume_command.get_subvolume_from(filesystem_path) if subvolume is not None: snapshots = subvolume_command.get_all_source_snapshots_for(subvolume) self._subvolume = subvolume.with_snapshots(snapshots) def is_of_type(self, fs_type: str) -> bool: return self.fs_type == fs_type def is_mounted(self) -> bool: return not is_none_or_whitespace(self.mount_point) def is_mounted_at(self, path: Path) -> bool: return self.is_mounted() and Path(self.mount_point) == path def has_subvolume(self) -> bool: return self.subvolume is not None @property def uuid(self) -> str: return self._uuid @property def label(self) -> str: return self._label @property def fs_type(self) -> str: return self._fs_type @property def mount_point(self) -> str: return self._mount_point @property def dump(self) -> Optional[int]: return self._dump @property def fsck(self) -> Optional[int]: return self._fsck @property def mount_options(self) -> Optional[MountOptions]: return self._mount_options @property def subvolume(self) -> Optional[Subvolume]: return self._subvolume ================================================ FILE: src/refind_btrfs/device/mount_options.py ================================================ # region Licensing # SPDX-FileCopyrightText: 2020-2024 Luka Žaja # # SPDX-License-Identifier: GPL-3.0-or-later """ refind-btrfs - Generate rEFInd manual boot stanzas from Btrfs snapshots Copyright (C) 2020-2024 Luka Žaja 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, either version 3 of the License, or (at your option) any later version. 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 . """ # endregion import re from refind_btrfs.common import constants from refind_btrfs.common.exceptions import PartitionError from refind_btrfs.utility.helpers import ( checked_cast, has_items, is_none_or_whitespace, try_parse_int, ) from .subvolume import Subvolume class MountOptions: def __init__(self, raw_mount_options: str) -> None: split_mount_options = [ option.strip() for option in raw_mount_options.split(constants.COLUMN_SEPARATOR) ] simple_options: list[tuple[int, str]] = [] parameterized_options: dict[str, tuple[int, str]] = {} parameterized_option_prefix_pattern = re.compile( constants.PARAMETERIZED_OPTION_PREFIX_PATTERN ) for position, option in enumerate(split_mount_options): if not is_none_or_whitespace(option): if parameterized_option_prefix_pattern.match(option): split_parameterized_option = option.split( constants.PARAMETERIZED_OPTION_SEPARATOR ) option_name = checked_cast(str, split_parameterized_option[0]) option_value = checked_cast(str, split_parameterized_option[1]) if option_name in parameterized_options: raise PartitionError( f"The '{option_name}' mount option " f"cannot be defined multiple times!" ) parameterized_options[option_name] = (position, option_value) else: simple_options.append((position, option)) self._simple_options = simple_options self._parameterized_options = parameterized_options def __str__(self) -> str: simple_options = self._simple_options parameterized_options = self._parameterized_options result: list[str] = [constants.EMPTY_STR] * sum( (len(simple_options), len(parameterized_options)) ) if has_items(simple_options): for simple_option in simple_options: result[simple_option[0]] = simple_option[1] if has_items(parameterized_options): for option_name, option_value in parameterized_options.items(): result[option_value[0]] = constants.PARAMETERIZED_OPTION_SEPARATOR.join( (option_name, option_value[1]) ) if has_items(result): return constants.COLUMN_SEPARATOR.join(result) return constants.EMPTY_STR def is_matched_with(self, subvolume: Subvolume) -> bool: parameterized_options = self._parameterized_options subvol_tuple = parameterized_options.get(constants.SUBVOL_OPTION) subvolid_tuple = parameterized_options.get(constants.SUBVOLID_OPTION) subvol_matched = False subvolid_matched = False if subvol_tuple is not None: subvol_value = subvol_tuple[1] logical_path = subvolume.logical_path subvol_prefix_pattern = re.compile(f"^{constants.DIR_SEPARATOR_PATTERN}") subvol_matched = subvol_prefix_pattern.sub( constants.EMPTY_STR, subvol_value ) == subvol_prefix_pattern.sub(constants.EMPTY_STR, logical_path) if subvolid_tuple is not None: subvolid_value = subvolid_tuple[1] num_id = subvolume.num_id subvolid_matched = try_parse_int(subvolid_value) == num_id return subvol_matched or subvolid_matched def migrate_from_to( self, source_subvolume: Subvolume, destination_subvolume: Subvolume ) -> None: if not self.is_matched_with(source_subvolume): raise PartitionError( "The mount options are not matched with the " "'source_subvolume' parameter (by 'subvol' or 'subvolid')!" ) parameterized_options = self._parameterized_options subvol_tuple = parameterized_options.get(constants.SUBVOL_OPTION) subvolid_tuple = parameterized_options.get(constants.SUBVOLID_OPTION) if subvol_tuple is not None: subvol_value = subvol_tuple[1] source_logical_path = source_subvolume.logical_path destination_logical_path = destination_subvolume.logical_path subvol_pattern = re.compile( rf"(?P^{constants.DIR_SEPARATOR_PATTERN}?){source_logical_path}$" ) parameterized_options[constants.SUBVOL_OPTION] = ( subvol_tuple[0], subvol_pattern.sub( rf"\g{destination_logical_path}", subvol_value ), ) if subvolid_tuple is not None: num_id = destination_subvolume.num_id parameterized_options[constants.SUBVOLID_OPTION] = ( subvolid_tuple[0], str(num_id), ) @property def simple_options(self) -> list[str]: return [simple_option[1] for simple_option in self._simple_options] @property def parameterized_options(self) -> dict[str, str]: return { option_name: option_value[1] for option_name, option_value in self._parameterized_options.items() } ================================================ FILE: src/refind_btrfs/device/partition.py ================================================ # region Licensing # SPDX-FileCopyrightText: 2020-2024 Luka Žaja # # SPDX-License-Identifier: GPL-3.0-or-later """ refind-btrfs - Generate rEFInd manual boot stanzas from Btrfs snapshots Copyright (C) 2020-2024 Luka Žaja 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, either version 3 of the License, or (at your option) any later version. 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 . """ # endregion from __future__ import annotations from pathlib import Path from typing import Optional, Self from uuid import UUID from refind_btrfs.common import constants from refind_btrfs.utility.helpers import ( find_all_matched_files_in, is_none_or_whitespace, none_throws, try_parse_int, try_parse_uuid, ) from .filesystem import Filesystem class Partition: def __init__(self, uuid: str, name: str, label: str) -> None: self._uuid = uuid self._name = name self._label = label self._part_type_code: Optional[int] = None self._part_type_uuid: Optional[UUID] = None self._filesystem: Optional[Filesystem] = None def __eq__(self, other: object) -> bool: if self is other: return True if isinstance(other, Partition): return self.uuid == other.uuid return False def __hash__(self) -> int: return hash(self.uuid) def with_part_type(self, part_type: str) -> Self: self._part_type_code = try_parse_int(part_type, base=16) self._part_type_uuid = try_parse_uuid(part_type) return self def with_filesystem(self, filesystem: Filesystem) -> Self: self._filesystem = filesystem return self def is_esp(self, uuid: UUID) -> bool: filesystem = self.filesystem if filesystem is not None: if uuid == constants.EMPTY_UUID: is_matched = ( self.part_type_code == constants.ESP_PART_TYPE_CODE or self.part_type_uuid == constants.ESP_PART_TYPE_UUID ) else: parsed_uuid = try_parse_uuid(self.uuid) is_matched = uuid == parsed_uuid return ( is_matched and filesystem.is_mounted() and filesystem.is_of_type(constants.ESP_FS_TYPE) ) return False def is_root(self) -> bool: filesystem = self.filesystem if filesystem is not None: directory = constants.ROOT_DIR return filesystem.is_mounted_at(directory) return False def is_boot(self) -> bool: filesystem = self.filesystem if filesystem is not None: directory = constants.ROOT_DIR / constants.BOOT_DIR return filesystem.is_mounted_at(directory) return False def search_paths_for(self, filename: str) -> Optional[list[Path]]: if is_none_or_whitespace(filename): raise ValueError("The 'filename' parameter must be initialized!") filesystem = none_throws(self.filesystem) if filesystem.is_mounted(): search_directory = Path(filesystem.mount_point) all_matches = find_all_matched_files_in(search_directory, filename) return list(all_matches) return None @property def uuid(self) -> str: return self._uuid @property def name(self) -> str: return self._name @property def label(self) -> str: return self._label @property def part_type_code(self) -> Optional[int]: return self._part_type_code @property def part_type_uuid(self) -> Optional[UUID]: return self._part_type_uuid @property def filesystem(self) -> Optional[Filesystem]: return self._filesystem ================================================ FILE: src/refind_btrfs/device/partition_table.py ================================================ # region Licensing # SPDX-FileCopyrightText: 2020-2024 Luka Žaja # # SPDX-License-Identifier: GPL-3.0-or-later """ refind-btrfs - Generate rEFInd manual boot stanzas from Btrfs snapshots Copyright (C) 2020-2024 Luka Žaja 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, either version 3 of the License, or (at your option) any later version. 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 . """ # endregion from __future__ import annotations import re from functools import cached_property from pathlib import Path from typing import Iterable, Optional, Self from uuid import UUID from more_itertools import only, take from refind_btrfs.common import constants from refind_btrfs.common.enums import FstabColumn from refind_btrfs.utility.helpers import has_items, is_none_or_whitespace, none_throws from .partition import Partition from .subvolume import Subvolume class PartitionTable: def __init__(self, uuid: str, pt_type: str) -> None: self._uuid = uuid self._pt_type = pt_type self._esp_uuid = constants.EMPTY_UUID self._fstab_file_path: Optional[Path] = None self._partitions: Optional[list[Partition]] = None def __eq__(self, other: object) -> bool: if self is other: return True if isinstance(other, PartitionTable): return self.uuid == other.uuid return False def __hash__(self) -> int: return hash(self.uuid) def with_esp_uuid(self, esp_uuid: UUID) -> Self: self._esp_uuid = esp_uuid return self def with_fstab_file_path(self, fstab_file_path: Path) -> Self: self._fstab_file_path = fstab_file_path return self def with_partitions(self, partitions: Iterable[Partition]) -> Self: self._partitions = list(partitions) return self def is_matched_with(self, subvolume: Subvolume) -> bool: root = self.root if root is not None: filesystem = none_throws(root.filesystem) mount_options = none_throws(filesystem.mount_options) return mount_options.is_matched_with(subvolume) return False def has_partitions(self) -> bool: return has_items(self.partitions) def migrate_from_to( self, source_subvolume: Subvolume, destination_subvolume: Subvolume ) -> None: root = none_throws(self.root) filesystem = none_throws(root.filesystem) mount_options = none_throws(filesystem.mount_options) destination_filesystem_path = destination_subvolume.filesystem_path mount_options.migrate_from_to(source_subvolume, destination_subvolume) self._fstab_file_path = destination_filesystem_path / constants.FSTAB_FILE def transform_fstab_line(self, fstab_line: str) -> str: if PartitionTable.is_valid_fstab_entry(fstab_line): root = none_throws(self.root) filesystem = none_throws(root.filesystem) root_mount_point = filesystem.mount_point split_fstab_entry = fstab_line.split() fstab_mount_point = split_fstab_entry[FstabColumn.FS_MOUNT_POINT.value] if root_mount_point == fstab_mount_point: fstab_mount_options = split_fstab_entry[ FstabColumn.FS_MOUNT_OPTIONS.value ] pattern = re.compile( r"(?P\s+)" f"{fstab_mount_options}" r"(?P\s+)" ) root_mount_options = str(filesystem.mount_options) return pattern.sub( r"\g" f"{root_mount_options}" r"\g", fstab_line, ) return fstab_line @staticmethod def is_valid_fstab_entry(value: Optional[str]) -> bool: if is_none_or_whitespace(value): return False fstab_line = none_throws(value) comment_pattern = re.compile(r"^\s*#.*") if not comment_pattern.match(fstab_line): columns_count = len(FstabColumn) split_fstab_entry = take(columns_count, fstab_line.split()) return ( has_items(split_fstab_entry) and len(split_fstab_entry) == columns_count ) return False @property def uuid(self) -> str: return self._uuid @property def pt_type(self) -> str: return self._pt_type @property def esp_uuid(self) -> UUID: return self._esp_uuid @property def fstab_file_path(self) -> Optional[Path]: return self._fstab_file_path @property def partitions(self) -> Optional[list[Partition]]: return self._partitions @cached_property def esp(self) -> Optional[Partition]: if self.has_partitions(): return only( partition for partition in none_throws(self.partitions) if partition.is_esp(self.esp_uuid) ) return None @cached_property def root(self) -> Optional[Partition]: if self.has_partitions(): return only( partition for partition in none_throws(self.partitions) if partition.is_root() ) return None @cached_property def boot(self) -> Optional[Partition]: if self.has_partitions(): return only( partition for partition in none_throws(self.partitions) if partition.is_boot() ) return None ================================================ FILE: src/refind_btrfs/device/subvolume.py ================================================ # region Licensing # SPDX-FileCopyrightText: 2020-2024 Luka Žaja # # SPDX-License-Identifier: GPL-3.0-or-later """ refind-btrfs - Generate rEFInd manual boot stanzas from Btrfs snapshots Copyright (C) 2020-2024 Luka Žaja 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, either version 3 of the License, or (at your option) any later version. 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 . """ # endregion from __future__ import annotations from copy import deepcopy from datetime import datetime from pathlib import Path from typing import TYPE_CHECKING, Iterable, NamedTuple, Optional, Self, Set from uuid import UUID from more_itertools import take from refind_btrfs.common import BootFilesCheckResult, constants from refind_btrfs.common.abc.factories import BaseDeviceCommandFactory from refind_btrfs.common.enums import PathRelation from refind_btrfs.common.exceptions import SubvolumeError from refind_btrfs.utility.helpers import ( discern_path_relation_of, has_items, is_none_or_whitespace, none_throws, replace_root_part_in, ) if TYPE_CHECKING: from refind_btrfs.boot import BootStanza from .partition_table import PartitionTable class NumIdRelation(NamedTuple): self_id: int parent_id: int class UuidRelation(NamedTuple): self_uuid: UUID parent_uuid: UUID class Subvolume: def __init__( self, filesystem_path: Path, logical_path: str, time_created: datetime, uuid_relation: UuidRelation, num_id_relation: NumIdRelation, is_read_only: bool, ) -> None: self._name: Optional[str] = None self._filesystem_path = filesystem_path self._logical_path = logical_path self._time_created = time_created self._uuid = uuid_relation.self_uuid self._parent_uuid = uuid_relation.parent_uuid self._num_id = num_id_relation.self_id self._parent_num_id = num_id_relation.parent_id self._is_read_only = is_read_only self._created_from: Optional[Subvolume] = None self._static_partition_table: Optional[PartitionTable] = None self._boot_files_check_result: Optional[BootFilesCheckResult] = None self._snapshots: Optional[Set[Subvolume]] = None def __eq__(self, other: object) -> bool: if self is other: return True if isinstance(other, Subvolume): return self.uuid == other.uuid return False def __hash__(self) -> int: return hash(self.uuid) def __lt__(self, other: object) -> bool: if isinstance(other, Subvolume): attributes_for_comparison = [ none_throws(subvolume.created_from).time_created if subvolume.is_newly_created() else subvolume.time_created for subvolume in (self, other) ] return attributes_for_comparison[0] < attributes_for_comparison[1] return False def with_boot_files_check_result(self, boot_stanza: BootStanza) -> Self: boot_stanza_check_result = boot_stanza.boot_files_check_result if boot_stanza_check_result is not None: self_filesystem_path_str = str(self.filesystem_path) self_logical_path = self.logical_path boot_stanza_name = boot_stanza_check_result.required_by_boot_stanza_name expected_logical_path = boot_stanza_check_result.expected_logical_path required_file_paths = boot_stanza_check_result.matched_boot_files matched_boot_files: list[str] = [] unmatched_boot_files: list[str] = [] for file_path in required_file_paths: replaced_file_path = Path( replace_root_part_in( file_path, expected_logical_path, self_filesystem_path_str ) ) append_func = ( matched_boot_files.append if replaced_file_path.exists() else unmatched_boot_files.append ) append_func(replaced_file_path.name) self._boot_files_check_result = BootFilesCheckResult( boot_stanza_name, self_logical_path, matched_boot_files, unmatched_boot_files, ) return self def with_snapshots(self, snapshots: Iterable[Subvolume]) -> Self: self._snapshots = set(snapshots) return self def as_named(self) -> Self: type_prefix = "ro" if self.is_read_only else "rw" type_prefix += "snap" if self.is_snapshot() else "subvol" if self.is_newly_created(): created_from = none_throws(self.created_from) time_created = created_from.time_created num_id = created_from.num_id else: time_created = self.time_created num_id = self.num_id formatted_time_created = time_created.strftime("%Y-%m-%d_%H-%M-%S") self._name = f"{type_prefix}_{formatted_time_created}_ID{num_id}" return self def as_located_in(self, parent_directory: Path) -> Self: if not self.is_named(): raise ValueError("The '_name' attribute must be initialized!") name = none_throws(self.name) self._filesystem_path = parent_directory / name return self def as_writable(self) -> Self: self._is_read_only = False return self def as_newly_created_from(self, other: Subvolume) -> Self: self._created_from = other if other.has_static_partition_table(): self._static_partition_table = deepcopy( none_throws(other.static_partition_table) ) return self def to_destination(self, directory: Path) -> Self: return ( Subvolume( constants.EMPTY_PATH, constants.EMPTY_STR, datetime.min, UuidRelation(constants.EMPTY_UUID, self.uuid), NumIdRelation(0, self.num_id), False, ) .as_newly_created_from(self) .as_named() .as_located_in(directory) ) def initialize_partition_table_using( self, device_command_factory: BaseDeviceCommandFactory ) -> None: if not self.has_static_partition_table(): static_device_command = device_command_factory.static_device_command() self._static_partition_table = ( static_device_command.get_partition_table_for(self) ) def is_named(self) -> bool: return not is_none_or_whitespace(self.name) def is_snapshot(self) -> bool: return self.parent_uuid != constants.EMPTY_UUID def is_snapshot_of(self, subvolume: Subvolume) -> bool: return self.is_snapshot() and self.parent_uuid == subvolume.uuid def is_located_in(self, parent_directory: Path) -> bool: if self.is_newly_created(): created_from = none_throws(self.created_from) filesystem_path = created_from.filesystem_path else: filesystem_path = self.filesystem_path path_relation = discern_path_relation_of((parent_directory, filesystem_path)) expected_results: list[PathRelation] = [ PathRelation.SAME, PathRelation.SECOND_NESTED_IN_FIRST, ] return path_relation in expected_results def is_newly_created(self) -> bool: return self.created_from is not None def is_static_partition_table_matched_with(self, subvolume: Subvolume) -> bool: if self.has_static_partition_table(): static_partition_table = none_throws(self.static_partition_table) return static_partition_table.is_matched_with(subvolume) return False def has_static_partition_table(self) -> bool: return self.static_partition_table is not None def has_unmatched_boot_files(self) -> bool: boot_files_check_result = self.boot_files_check_result if boot_files_check_result is not None: return boot_files_check_result.has_unmatched_boot_files() return False def has_snapshots(self) -> bool: return has_items(self.snapshots) def can_be_added(self, comparison_iterable: Iterable[Subvolume]) -> bool: if self not in comparison_iterable: return not any( subvolume.is_newly_created() and subvolume.is_snapshot_of(self) for subvolume in comparison_iterable ) return False def can_be_removed( self, parent_directory: Path, comparison_iterable: Iterable[Subvolume] ) -> bool: if self not in comparison_iterable: if self.is_newly_created() or self.is_located_in(parent_directory): return not any( self.is_snapshot_of(subvolume) for subvolume in comparison_iterable ) return True return False def select_snapshots(self, count: int) -> Optional[list[Subvolume]]: if self.has_snapshots(): snapshots = none_throws(self.snapshots) return take(count, sorted(snapshots, reverse=True)) return None def modify_partition_table_using( self, source_subvolume: Subvolume, device_command_factory: BaseDeviceCommandFactory, ) -> None: self.initialize_partition_table_using(device_command_factory) static_partition_table = none_throws(self.static_partition_table) if not static_partition_table.is_matched_with(self): static_device_command = device_command_factory.static_device_command() static_partition_table.migrate_from_to(source_subvolume, self) static_device_command.save_partition_table(static_partition_table) def validate_static_partition_table(self, subvolume: Subvolume) -> None: logical_path = self.logical_path if not self.has_static_partition_table(): raise SubvolumeError( f"The '{logical_path}' subvolume's static " "partition table is not initialized!" ) static_partition_table = none_throws(self.static_partition_table) root = static_partition_table.root if root is None: raise SubvolumeError( f"Could not find the root partition in the '{logical_path}' " "subvolume's static partition table!" ) if not static_partition_table.is_matched_with(subvolume): raise SubvolumeError( f"The '{logical_path}' subvolume's static partition table is not " "matched with the root subvolume (by 'subvol' or 'subvolid')!" ) def validate_boot_files_check_result(self) -> None: if self.has_unmatched_boot_files(): boot_files_check_result = none_throws(self.boot_files_check_result) boot_stanza_name = boot_files_check_result.required_by_boot_stanza_name logical_path = boot_files_check_result.expected_logical_path unmatched_boot_files = boot_files_check_result.unmatched_boot_files raise SubvolumeError( f"Detected boot files required by the '{boot_stanza_name}' boot " f"stanza which do not exist in the '{logical_path}' subvolume: " f"{constants.DEFAULT_ITEMS_SEPARATOR.join(unmatched_boot_files)}!" ) @property def name(self) -> Optional[str]: return self._name @property def filesystem_path(self) -> Path: return self._filesystem_path @property def logical_path(self) -> str: return self._logical_path @property def time_created(self) -> datetime: return self._time_created @property def uuid(self) -> UUID: return self._uuid @property def parent_uuid(self) -> UUID: return self._parent_uuid @property def num_id(self) -> int: return self._num_id @property def parent_num_id(self) -> int: return self._parent_num_id @property def is_read_only(self) -> bool: return self._is_read_only @property def created_from(self) -> Optional[Subvolume]: return self._created_from @property def static_partition_table(self) -> Optional[PartitionTable]: return self._static_partition_table @property def boot_files_check_result(self) -> Optional[BootFilesCheckResult]: return self._boot_files_check_result @property def snapshots(self) -> Optional[Set[Subvolume]]: return self._snapshots ================================================ FILE: src/refind_btrfs/service/__init__.py ================================================ # region Licensing # SPDX-FileCopyrightText: 2020-2024 Luka Žaja # # SPDX-License-Identifier: GPL-3.0-or-later """ refind-btrfs - Generate rEFInd manual boot stanzas from Btrfs snapshots Copyright (C) 2020-2024 Luka Žaja 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, either version 3 of the License, or (at your option) any later version. 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 . """ # endregion from .snapshot_event_handler import SnapshotEventHandler from .snapshot_observer import SnapshotObserver from .watchdog_runner import WatchdogRunner ================================================ FILE: src/refind_btrfs/service/snapshot_event_handler.py ================================================ # region Licensing # SPDX-FileCopyrightText: 2020-2024 Luka Žaja # # SPDX-License-Identifier: GPL-3.0-or-later """ refind-btrfs - Generate rEFInd manual boot stanzas from Btrfs snapshots Copyright (C) 2020-2024 Luka Žaja 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, either version 3 of the License, or (at your option) any later version. 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 . """ # endregion from pathlib import Path from threading import Lock from typing import Set from injector import inject from more_itertools import only from watchdog.events import ( EVENT_TYPE_CREATED, EVENT_TYPE_DELETED, DirCreatedEvent, DirDeletedEvent, FileSystemEvent, FileSystemEventHandler, ) from refind_btrfs.common import ConfigurableMixin from refind_btrfs.common.abc.factories import ( BaseLoggerFactory, BaseSubvolumeCommandFactory, ) from refind_btrfs.common.abc.providers import ( BasePackageConfigProvider, BasePersistenceProvider, ) from refind_btrfs.common.exceptions import SnapshotExcludedFromDeletionError from refind_btrfs.device import Subvolume from refind_btrfs.state_management import RefindBtrfsMachine from refind_btrfs.utility.helpers import ( checked_cast, discern_distance_between, has_items, ) class SnapshotEventHandler(FileSystemEventHandler, ConfigurableMixin): @inject def __init__( self, logger_factory: BaseLoggerFactory, subvolume_command_factory: BaseSubvolumeCommandFactory, package_config_provider: BasePackageConfigProvider, persistence_provider: BasePersistenceProvider, machine: RefindBtrfsMachine, ) -> None: ConfigurableMixin.__init__(self, package_config_provider) self._logger = logger_factory.logger(__name__) self._subvolume_command_factory = subvolume_command_factory self._persistence_provider = persistence_provider self._machine = machine self._deleted_snapshots: Set[Subvolume] = set() self._deletion_lock = Lock() self._event_lock = Lock() def on_created(self, event: FileSystemEvent) -> None: is_dir_created_event = ( event.event_type == EVENT_TYPE_CREATED and event.is_directory ) if is_dir_created_event: dir_created_event = checked_cast(DirCreatedEvent, event) logger = self._logger created_directory = Path(dir_created_event.src_path) if self._is_snapshot_created(created_directory): machine = self._machine logger.info(f"The '{created_directory}' snapshot has been created.") with self._event_lock: machine.run() def on_deleted(self, event: FileSystemEvent) -> None: is_dir_deleted_event = ( event.event_type == EVENT_TYPE_DELETED and event.is_directory ) if is_dir_deleted_event: dir_deleted_event = checked_cast(DirDeletedEvent, event) logger = self._logger deleted_directory = Path(dir_deleted_event.src_path) try: if self._is_snapshot_deleted(deleted_directory): machine = self._machine logger.info(f"The '{deleted_directory}' snapshot has been deleted.") with self._event_lock: machine.run() except SnapshotExcludedFromDeletionError as e: logger.warning(e.formatted_message) def _is_snapshot_created(self, created_directory: Path) -> bool: snapshot_searches = self.package_config.snapshot_searches parents = created_directory.parents for snapshot_search in snapshot_searches: search_directory = snapshot_search.directory if snapshot_search.directory in parents: distance = discern_distance_between( (search_directory, created_directory) ) if distance is not None: max_depth = snapshot_search.max_depth - distance if self._is_or_contains_snapshot(created_directory, max_depth): return True return False def _is_snapshot_deleted(self, deleted_directory: Path) -> bool: persistence_provider = self._persistence_provider previous_run_result = persistence_provider.get_previous_run_result() bootable_snapshots = previous_run_result.bootable_snapshots if has_items(bootable_snapshots): deleted_snapshot = only( snapshot for snapshot in bootable_snapshots if snapshot.is_located_in(deleted_directory) ) if deleted_snapshot is not None: deleted_snapshots = self._deleted_snapshots deletion_lock = self._deletion_lock with deletion_lock: if deleted_snapshot not in deleted_snapshots: snapshot_manipulation = ( self.package_config.snapshot_manipulation ) cleanup_exclusion = snapshot_manipulation.cleanup_exclusion deleted_snapshots.add(deleted_snapshot) if deleted_snapshot in cleanup_exclusion: raise SnapshotExcludedFromDeletionError( f"The deleted snapshot ('{deleted_directory}') " "is explicitly excluded from cleanup!" ) return True return False def _is_or_contains_snapshot( self, directory: Path, max_depth: int, current_depth: int = 0 ) -> bool: if current_depth <= max_depth: subvolume_command = self._subvolume_command_factory.subvolume_command() resolved_path = directory.resolve() subvolume = subvolume_command.get_subvolume_from(resolved_path) is_snapshot = subvolume is not None and subvolume.is_snapshot() if is_snapshot: return True subdirectories = (child for child in directory.iterdir() if child.is_dir()) if any( self._is_or_contains_snapshot( subdirectory, max_depth, current_depth + 1 ) for subdirectory in subdirectories ): return True return False ================================================ FILE: src/refind_btrfs/service/snapshot_observer.py ================================================ # region Licensing # SPDX-FileCopyrightText: 2020-2024 Luka Žaja # # SPDX-License-Identifier: GPL-3.0-or-later """ refind-btrfs - Generate rEFInd manual boot stanzas from Btrfs snapshots Copyright (C) 2020-2024 Luka Žaja 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, either version 3 of the License, or (at your option) any later version. 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 . """ # endregion import queue from injector import inject from refind_btrfs.common import CheckableObserver, constants from refind_btrfs.common.abc.factories import BaseLoggerFactory from refind_btrfs.common.exceptions import SnapshotMountedAsRootError class SnapshotObserver(CheckableObserver): @inject def __init__(self, logger_factory: BaseLoggerFactory): super().__init__() self._logger = logger_factory.logger(__name__) def run(self) -> None: logger = self._logger while self.should_keep_running(): try: self.dispatch_events(self.event_queue) except queue.Empty: continue except SnapshotMountedAsRootError as e: logger.warning(e.formatted_message) self._exception = e self.stop() except Exception as e: logger.exception(constants.MESSAGE_UNEXPECTED_ERROR) self._exception = e self.stop() ================================================ FILE: src/refind_btrfs/service/watchdog_runner.py ================================================ # region Licensing # SPDX-FileCopyrightText: 2020-2024 Luka Žaja # # SPDX-License-Identifier: GPL-3.0-or-later """ refind-btrfs - Generate rEFInd manual boot stanzas from Btrfs snapshots Copyright (C) 2020-2024 Luka Žaja 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, either version 3 of the License, or (at your option) any later version. 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 . """ # endregion import os import signal from signal import signal as register_signal_handler from types import FrameType from typing import Optional import systemd.daemon as systemd_daemon from injector import inject from pid import PidFile, PidFileAlreadyRunningError from watchdog.events import FileSystemEventHandler from refind_btrfs.common import CheckableObserver, constants from refind_btrfs.common.abc import BaseRunner from refind_btrfs.common.abc.factories import BaseLoggerFactory from refind_btrfs.common.abc.providers import BasePackageConfigProvider from refind_btrfs.common.exceptions import SnapshotMountedAsRootError from refind_btrfs.utility.helpers import checked_cast class WatchdogRunner(BaseRunner): @inject def __init__( self, logger_factory: BaseLoggerFactory, package_config_provider: BasePackageConfigProvider, observer: CheckableObserver, event_handler: FileSystemEventHandler, ) -> None: self._logger = logger_factory.logger(__name__) self._package_config_provider = package_config_provider self._observer = observer self._snapshot_event_handler = event_handler self._current_pid = os.getpid() register_signal_handler(signal.SIGTERM, self._terminate) def run(self) -> int: logger = self._logger package_config_provider = self._package_config_provider observer = self._observer event_handler = self._snapshot_event_handler current_pid = self._current_pid exit_code = os.EX_OK try: with PidFile( pidname=constants.BACKGROUND_MODE_PID_NAME, lock_pidfile=False ) as pid_file: current_pid = pid_file.pid package_config = package_config_provider.get_config() directories_for_watch = [ str(directory) for directory in sorted(package_config.directories_for_watch) ] logger.info( "Scheduling watch for directories: " f"{constants.DEFAULT_ITEMS_SEPARATOR.join(directories_for_watch)}." ) for directory in directories_for_watch: observer.schedule( event_handler, directory, recursive=False, ) logger.info(f"Starting the observer with PID {current_pid}.") observer.start() systemd_daemon.notify(constants.NOTIFICATION_READY, pid=current_pid) while observer.is_alive(): observer.join(constants.WATCH_TIMEOUT) observer.join() except PidFileAlreadyRunningError as e: exit_code = constants.EX_NOT_OK running_pid = checked_cast(int, e.pid) logger.error(e.message) systemd_daemon.notify( constants.NOTIFICATION_STATUS.format( f"Detected an attempt to run subsequently with PID {current_pid}." ), pid=running_pid, ) else: try: observer.check() except SnapshotMountedAsRootError: pass except Exception: exit_code = constants.EX_NOT_OK if exit_code != os.EX_OK: systemd_daemon.notify( constants.NOTIFICATION_ERRNO.format(exit_code), pid=current_pid ) return exit_code # pylint: disable=unused-argument def _terminate(self, signal_number: int, frame: Optional[FrameType]) -> None: logger = self._logger observer = self._observer current_pid = self._current_pid logger.info( f"Received terminating signal {signal_number}, stopping the observer..." ) systemd_daemon.notify(constants.NOTIFICATION_STOPPING, pid=current_pid) if observer.is_alive(): observer.stop() observer.join() ================================================ FILE: src/refind_btrfs/state_management/__init__.py ================================================ # region Licensing # SPDX-FileCopyrightText: 2020-2024 Luka Žaja # # SPDX-License-Identifier: GPL-3.0-or-later """ refind-btrfs - Generate rEFInd manual boot stanzas from Btrfs snapshots Copyright (C) 2020-2024 Luka Žaja 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, either version 3 of the License, or (at your option) any later version. 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 . """ # endregion from .model import Model from .refind_btrfs_machine import RefindBtrfsMachine, States ================================================ FILE: src/refind_btrfs/state_management/conditions.py ================================================ # region Licensing # SPDX-FileCopyrightText: 2020-2024 Luka Žaja # # SPDX-License-Identifier: GPL-3.0-or-later """ refind-btrfs - Generate rEFInd manual boot stanzas from Btrfs snapshots Copyright (C) 2020-2024 Luka Žaja 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, either version 3 of the License, or (at your option) any later version. 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 . """ # endregion from __future__ import annotations from itertools import groupby from typing import TYPE_CHECKING from refind_btrfs.common import constants from refind_btrfs.common.abc.factories import BaseLoggerFactory from refind_btrfs.common.enums import ConfigInitializationType from refind_btrfs.common.exceptions import ( NoChangesDetectedError, RefindConfigError, SnapshotMountedAsRootError, SubvolumeError, ) from refind_btrfs.utility.helpers import ( has_items, is_singleton, item_count_suffix, none_throws, ) if TYPE_CHECKING: from .model import Model class Conditions: def __init__(self, logger_factory: BaseLoggerFactory, model: Model) -> None: self._logger = logger_factory.logger(__name__) self._model = model def check_filtered_block_devices(self) -> bool: logger = self._logger model = self._model esp_device = model.esp_device if esp_device is None: logger.error("Could not find the ESP!") return False esp = model.esp esp_filesystem = none_throws(esp.filesystem) logger.info( f"Found the ESP mounted at '{esp_filesystem.mount_point}' on '{esp.name}'." ) root_device = model.root_device if root_device is None: logger.error("Could not find the root partition!") return False root_partition = model.root_partition root_filesystem = none_throws(root_partition.filesystem) logger.info(f"Found the root partition on '{root_partition.name}'.") btrfs_type = constants.BTRFS_TYPE if not root_filesystem.is_of_type(btrfs_type): logger.error(f"The root partition's filesystem is not '{btrfs_type}'!") return False boot_device = model.boot_device if boot_device is not None: boot = none_throws(esp_device.boot) logger.info(f"Found a separate boot partition on '{boot.name}'.") return True def check_root_subvolume(self) -> bool: logger = self._logger model = self._model root_partition = model.root_partition filesystem = none_throws(root_partition.filesystem) if not filesystem.has_subvolume(): logger.error("The root partition is not mounted as a subvolume!") return False subvolume = none_throws(filesystem.subvolume) logical_path = subvolume.logical_path logger.info(f"Found subvolume '{logical_path}' mounted as the root partition.") if subvolume.is_snapshot(): package_config = model.package_config if package_config.exit_if_root_is_snapshot: parent_uuid = subvolume.parent_uuid raise SnapshotMountedAsRootError( f"Subvolume '{logical_path}' is itself a snapshot " f"(parent UUID - '{parent_uuid}'), exiting..." ) if not subvolume.has_snapshots(): logger.error(f"No snapshots of the '{logical_path}' subvolume were found!") return False snapshots = none_throws(subvolume.snapshots) suffix = item_count_suffix(snapshots) logger.info( f"Found {len(snapshots)} snapshot{suffix} of the '{logical_path}' subvolume." ) return True def check_matched_boot_stanzas(self) -> bool: logger = self._logger model = self._model matched_boot_stanzas = model.matched_boot_stanzas if not has_items(matched_boot_stanzas): logger.error( "Could not find a boot stanza matched with the root partition!" ) return False suffix = item_count_suffix(matched_boot_stanzas) logger.info( f"Found {len(matched_boot_stanzas)} boot " f"stanza{suffix} matched with the root partition." ) grouping_result = groupby(matched_boot_stanzas) for key, grouper in grouping_result: grouped_boot_stanzas = list(grouper) if not is_singleton(grouped_boot_stanzas): volume = key.volume loader_path = key.loader_path logger.error( f"Found {len(grouped_boot_stanzas)} boot stanzas defined with " f"the same volume ('{volume}') and loader ('{loader_path}') options!" ) return False package_config = model.package_config boot_stanza_generation = package_config.boot_stanza_generation icon_generation_mode = boot_stanza_generation.icon.mode for boot_stanza in matched_boot_stanzas: try: boot_stanza.validate_boot_files_check_result() except RefindConfigError as e: logger.warning(e.formatted_message) boot_stanza.validate_icon_path(icon_generation_mode) usable_boot_stanzas = model.usable_boot_stanzas if not has_items(usable_boot_stanzas): logger.error("None of the matched boot stanzas are usable!") return False return True def check_prepared_snapshots(self) -> bool: logger = self._logger model = self._model prepared_snapshots = model.prepared_snapshots snapshots_for_addition = prepared_snapshots.snapshots_for_addition snapshots_for_removal = prepared_snapshots.snapshots_for_removal if has_items(snapshots_for_addition): subvolume = model.root_subvolume suffix = item_count_suffix(snapshots_for_addition) logger.info( f"Found {len(snapshots_for_addition)} snapshot{suffix} for addition." ) for snapshot in snapshots_for_addition: try: snapshot.validate_static_partition_table(subvolume) except SubvolumeError as e: logger.warning(e.formatted_message) usable_snapshots_for_addition = model.usable_snapshots_for_addition if not has_items(usable_snapshots_for_addition): logger.warning("None of the snapshots for addition are usable!") if has_items(snapshots_for_removal): suffix = item_count_suffix(snapshots_for_removal) logger.info( f"Found {len(snapshots_for_removal)} snapshot{suffix} for removal." ) return True def check_boot_stanzas_with_snapshots(self) -> bool: logger = self._logger model = self._model boot_stanzas_with_snapshots = model.boot_stanzas_with_snapshots excluded_boot_stanzas_count = len( list(item for item in boot_stanzas_with_snapshots if item.is_excluded) ) if len(boot_stanzas_with_snapshots) == excluded_boot_stanzas_count: logger.error( "All of the matched boot stanzas are " "explicitly excluded from processing!" ) return False for item in boot_stanzas_with_snapshots: boot_stanza = item.boot_stanza normalized_name = boot_stanza.normalized_name if item.is_excluded: logger.info( f"Skipping the '{normalized_name}' boot stanza " "because it is explicitly excluded from processing." ) elif item.has_unmatched_snapshots(): unmatched_snapshots = item.unmatched_snapshots for snapshot in unmatched_snapshots: try: snapshot.validate_boot_files_check_result() except SubvolumeError as e: logger.warning(e.formatted_message) if not item.has_matched_snapshots(): logger.warning( "None of the prepared snapshots are matched " f"with the '{normalized_name}' boot stanza!" ) usable_boot_stanzas_with_snapshots = model.usable_boot_stanzas_with_snapshots if not has_items(usable_boot_stanzas_with_snapshots): logger.error( "None of the matched boot stanzas can be " "combined with any of the prepared snapshots!" ) return False package_config = model.package_config if package_config.exit_if_no_changes_are_detected: refind_config = model.refind_config prepared_snapshots = model.prepared_snapshots has_changes = ( package_config.is_of_initialization_type( ConfigInitializationType.PARSED ) or refind_config.is_of_initialization_type( ConfigInitializationType.PARSED ) or prepared_snapshots.has_changes() ) if not has_changes: raise NoChangesDetectedError("No changes were detected, aborting...") return True ================================================ FILE: src/refind_btrfs/state_management/model.py ================================================ # region Licensing # SPDX-FileCopyrightText: 2020-2024 Luka Žaja # # SPDX-License-Identifier: GPL-3.0-or-later """ refind-btrfs - Generate rEFInd manual boot stanzas from Btrfs snapshots Copyright (C) 2020-2024 Luka Žaja 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, either version 3 of the License, or (at your option) any later version. 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 . """ # endregion from __future__ import annotations from itertools import chain from typing import Callable, NamedTuple, Optional, Self from injector import inject from more_itertools import only from refind_btrfs.boot import BootStanza, RefindConfig from refind_btrfs.common import ConfigurableMixin from refind_btrfs.common.abc.factories import ( BaseDeviceCommandFactory, BaseIconCommandFactory, BaseLoggerFactory, BaseSubvolumeCommandFactory, ) from refind_btrfs.common.abc.providers import ( BasePackageConfigProvider, BasePersistenceProvider, BaseRefindConfigProvider, ) from refind_btrfs.device import BlockDevice, Partition, Subvolume from refind_btrfs.utility.helpers import has_items, none_throws, replace_item_in from .conditions import Conditions # region Helper Tuples class BlockDevices(NamedTuple): esp_device: Optional[BlockDevice] root_device: Optional[BlockDevice] boot_device: Optional[BlockDevice] @classmethod def none(cls) -> Self: return cls(None, None, None) class PreparedSnapshots(NamedTuple): snapshots_for_addition: list[Subvolume] snapshots_for_removal: list[Subvolume] def has_changes(self) -> bool: return has_items(self.snapshots_for_addition) or has_items( self.snapshots_for_removal ) class BootStanzaWithSnapshots(NamedTuple): boot_stanza: BootStanza is_excluded: bool matched_snapshots: list[Subvolume] unmatched_snapshots: list[Subvolume] def has_matched_snapshots(self) -> bool: return has_items(self.matched_snapshots) def has_unmatched_snapshots(self) -> bool: return has_items(self.unmatched_snapshots) def is_usable(self) -> bool: return not self.is_excluded and self.has_matched_snapshots() def replace_matched_snapshot( self, current_snapshot: Subvolume, replacement_snapshot: Subvolume ) -> None: matched_snapshots = self.matched_snapshots replace_item_in(matched_snapshots, current_snapshot, replacement_snapshot) class ProcessingResult(NamedTuple): bootable_snapshots: list[Subvolume] @classmethod def none(cls) -> Self: return cls([]) def has_bootable_snapshots(self) -> bool: return has_items(self.bootable_snapshots) # endregion class Model(ConfigurableMixin): @inject def __init__( self, logger_factory: BaseLoggerFactory, device_command_factory: BaseDeviceCommandFactory, subvolume_command_factory: BaseSubvolumeCommandFactory, icon_command_factory: BaseIconCommandFactory, package_config_provider: BasePackageConfigProvider, refind_config_provider: BaseRefindConfigProvider, persistence_provider: BasePersistenceProvider, ) -> None: ConfigurableMixin.__init__(self, package_config_provider) self._device_command_factory = device_command_factory self._subvolume_command_factory = subvolume_command_factory self._icon_command_factory = icon_command_factory self._refind_config_provider = refind_config_provider self._persistence_provider = persistence_provider self._conditions = Conditions(logger_factory, self) self._filtered_block_devices: Optional[BlockDevices] = None self._matched_boot_stanzas: Optional[list[BootStanza]] = None self._prepared_snapshots: Optional[PreparedSnapshots] = None self._boot_stanzas_with_snapshots: Optional[ list[BootStanzaWithSnapshots] ] = None def initialize_block_devices(self) -> None: device_command_factory = self._device_command_factory physical_device_command = device_command_factory.physical_device_command() all_block_devices = list(physical_device_command.get_block_devices()) if has_items(all_block_devices): for block_device in all_block_devices: block_device.initialize_partition_tables_using(device_command_factory) def block_device_filter( filter_func: Callable[[BlockDevice], bool], ) -> Optional[BlockDevice]: return only( block_device for block_device in all_block_devices if filter_func(block_device) ) filtered_block_devices = BlockDevices( block_device_filter(BlockDevice.has_esp), block_device_filter(BlockDevice.has_root), block_device_filter(BlockDevice.has_boot), ) else: filtered_block_devices = BlockDevices.none() self._filtered_block_devices = filtered_block_devices def initialize_root_subvolume(self) -> None: subvolume_command_factory = self._subvolume_command_factory root_partition = self.root_partition filesystem = none_throws(root_partition.filesystem) filesystem.initialize_subvolume_using(subvolume_command_factory) def initialize_matched_boot_stanzas(self) -> None: refind_config = self.refind_config include_paths = self._should_include_paths_during_generation() root_device = none_throws(self.root_device) matched_boot_stanzas = refind_config.get_boot_stanzas_matched_with(root_device) if include_paths: subvolume = self.root_subvolume include_sub_menus = self._should_include_sub_menus_during_generation() self._matched_boot_stanzas = [ boot_stanza.with_boot_files_check_result(subvolume, include_sub_menus) for boot_stanza in matched_boot_stanzas ] else: self._matched_boot_stanzas = list(matched_boot_stanzas) def initialize_prepared_snapshots(self) -> None: persistence_provider = self._persistence_provider snapshot_manipulation = self.package_config.snapshot_manipulation subvolume = self.root_subvolume previous_run_result = persistence_provider.get_previous_run_result() selected_snapshots = none_throws( subvolume.select_snapshots(snapshot_manipulation.selection_count) ) destination_directory = snapshot_manipulation.destination_directory snapshots_union = snapshot_manipulation.cleanup_exclusion.union( selected_snapshots ) if previous_run_result.has_bootable_snapshots(): bootable_snapshots = previous_run_result.bootable_snapshots snapshots_for_addition = [ snapshot for snapshot in selected_snapshots if snapshot.can_be_added(bootable_snapshots) ] snapshots_for_removal = [ snapshot for snapshot in bootable_snapshots if snapshot.can_be_removed(destination_directory, snapshots_union) ] else: destination_snapshots = self.destination_snapshots snapshots_for_addition = selected_snapshots snapshots_for_removal = [ snapshot for snapshot in destination_snapshots.difference(snapshots_union) if snapshot.can_be_removed(destination_directory, selected_snapshots) ] if has_items(snapshots_for_addition): device_command_factory = self._device_command_factory for snapshot in snapshots_for_addition: snapshot.initialize_partition_table_using(device_command_factory) self._prepared_snapshots = PreparedSnapshots( snapshots_for_addition, snapshots_for_removal ) def combine_boot_stanzas_with_snapshots(self) -> None: usable_boot_stanzas = self.usable_boot_stanzas actual_bootable_snapshots = self.actual_bootable_snapshots boot_stanza_generation = self.package_config.boot_stanza_generation include_paths = self._should_include_paths_during_generation() boot_stanza_preparation_results: list[BootStanzaWithSnapshots] = [] for boot_stanza in usable_boot_stanzas: is_excluded = any( boot_stanza.is_matched_with(loader_filename) for loader_filename in boot_stanza_generation.source_exclusion ) matched_snapshots: list[Subvolume] = [] unmatched_snapshots: list[Subvolume] = [] if include_paths: checked_bootable_snapshots = ( snapshot.with_boot_files_check_result(boot_stanza) for snapshot in actual_bootable_snapshots ) for snapshot in checked_bootable_snapshots: append_func = ( unmatched_snapshots.append if snapshot.has_unmatched_boot_files() else matched_snapshots.append ) append_func(snapshot) else: matched_snapshots.extend(actual_bootable_snapshots) boot_stanza_preparation_results.append( BootStanzaWithSnapshots( boot_stanza, is_excluded, matched_snapshots, unmatched_snapshots ) ) self._boot_stanzas_with_snapshots = boot_stanza_preparation_results def process_changes(self) -> None: persistence_provider = self._persistence_provider bootable_snapshots = self._process_snapshots() self._process_boot_stanzas() persistence_provider.save_current_run_result( ProcessingResult(bootable_snapshots) ) def _process_snapshots(self) -> list[Subvolume]: subvolume_command_factory = self._subvolume_command_factory actual_bootable_snapshots = self.actual_bootable_snapshots usable_snapshots_for_addition = self.usable_snapshots_for_addition subvolume_command = subvolume_command_factory.subvolume_command() if has_items(usable_snapshots_for_addition): device_command_factory = self._device_command_factory subvolume = self.root_subvolume boot_stanzas_with_snapshots = self.boot_stanzas_with_snapshots all_usable_snapshots = set( chain.from_iterable(self.usable_boot_stanzas_with_snapshots.values()) ) for addition in usable_snapshots_for_addition: if addition in all_usable_snapshots: bootable_snapshot = subvolume_command.get_bootable_snapshot_from( addition ) bootable_snapshot.modify_partition_table_using( subvolume, device_command_factory ) replace_item_in( actual_bootable_snapshots, addition, bootable_snapshot ) for item in boot_stanzas_with_snapshots: item.replace_matched_snapshot(addition, bootable_snapshot) else: actual_bootable_snapshots.remove(addition) prepared_snapshots = self.prepared_snapshots snapshots_for_removal = prepared_snapshots.snapshots_for_removal if has_items(snapshots_for_removal): for removal in snapshots_for_removal: subvolume_command.delete_snapshot(removal) return actual_bootable_snapshots def _process_boot_stanzas(self) -> None: refind_config = self.refind_config root_device = none_throws(self.root_device) boot_device = self.boot_device usable_boot_stanzas_with_snapshots = self.usable_boot_stanzas_with_snapshots boot_stanza_generation = ( self.package_config.boot_stanza_generation.with_include_paths(boot_device) ) icon_command_factory = self._icon_command_factory generated_refind_configs = refind_config.generate_new_from( root_device, usable_boot_stanzas_with_snapshots, boot_stanza_generation, icon_command_factory, ) refind_config_provider = self._refind_config_provider for generated_refind_config in generated_refind_configs: refind_config_provider.save_config(generated_refind_config) refind_config_provider.append_to_config(refind_config) def _should_include_paths_during_generation(self) -> bool: boot_stanza_generation = self.package_config.boot_stanza_generation if boot_stanza_generation.include_paths: return self.boot_device is None return False def _should_include_sub_menus_during_generation(self) -> bool: boot_stanza_generation = self.package_config.boot_stanza_generation return boot_stanza_generation.include_sub_menus @property def conditions(self) -> list[Callable[[], bool]]: conditions = self._conditions always_true_func = lambda: True return [ always_true_func, conditions.check_filtered_block_devices, conditions.check_root_subvolume, conditions.check_matched_boot_stanzas, conditions.check_prepared_snapshots, conditions.check_boot_stanzas_with_snapshots, always_true_func, ] @property def refind_config(self) -> RefindConfig: refind_config_provider = self._refind_config_provider esp = self.esp return refind_config_provider.get_config(esp) @property def esp_device(self) -> Optional[BlockDevice]: return none_throws(self._filtered_block_devices).esp_device @property def esp(self) -> Partition: esp_device = none_throws(self.esp_device) return none_throws(esp_device.esp) @property def root_device(self) -> Optional[BlockDevice]: return none_throws(self._filtered_block_devices).root_device @property def root_partition(self) -> Partition: root_device = none_throws(self.root_device) return none_throws(root_device.root) @property def root_subvolume(self) -> Subvolume: root_partition = self.root_partition filesystem = none_throws(root_partition.filesystem) return none_throws(filesystem.subvolume) @property def boot_device(self) -> Optional[BlockDevice]: return none_throws(self._filtered_block_devices).boot_device @property def matched_boot_stanzas(self) -> list[BootStanza]: return none_throws(self._matched_boot_stanzas) @property def usable_boot_stanzas(self) -> list[BootStanza]: matched_boot_stanzas = self.matched_boot_stanzas return [ boot_stanza for boot_stanza in matched_boot_stanzas if not boot_stanza.has_unmatched_boot_files() ] @property def prepared_snapshots(self) -> PreparedSnapshots: return none_throws(self._prepared_snapshots) @property def destination_snapshots(self) -> set[Subvolume]: subvolume_command_factory = self._subvolume_command_factory subvolume_command = subvolume_command_factory.subvolume_command() destination_snapshots = sorted( subvolume_command.get_all_destination_snapshots(), reverse=True ) return set(destination_snapshots) @property def usable_snapshots_for_addition(self) -> list[Subvolume]: subvolume = self.root_subvolume prepared_snapshots = self.prepared_snapshots snapshots_for_addition = prepared_snapshots.snapshots_for_addition return [ snapshot for snapshot in snapshots_for_addition if snapshot.is_static_partition_table_matched_with(subvolume) ] @property def actual_bootable_snapshots(self) -> list[Subvolume]: persistence_provider = self._persistence_provider prepared_snapshots = self.prepared_snapshots usable_snapshots_for_addition = self.usable_snapshots_for_addition previous_run_result = persistence_provider.get_previous_run_result() snapshots_for_removal = prepared_snapshots.snapshots_for_removal bootable_snapshots = set(previous_run_result.bootable_snapshots) if has_items(usable_snapshots_for_addition): bootable_snapshots |= set(usable_snapshots_for_addition) if has_items(snapshots_for_removal): bootable_snapshots -= set(snapshots_for_removal) return list(bootable_snapshots) @property def boot_stanzas_with_snapshots(self) -> list[BootStanzaWithSnapshots]: return none_throws(self._boot_stanzas_with_snapshots) @property def usable_boot_stanzas_with_snapshots(self) -> dict[BootStanza, list[Subvolume]]: boot_stanzas_with_snapshots = self.boot_stanzas_with_snapshots return { item.boot_stanza: item.matched_snapshots for item in boot_stanzas_with_snapshots if item.is_usable() } ================================================ FILE: src/refind_btrfs/state_management/refind_btrfs_machine.py ================================================ # region Licensing # SPDX-FileCopyrightText: 2020-2024 Luka Žaja # # SPDX-License-Identifier: GPL-3.0-or-later """ refind-btrfs - Generate rEFInd manual boot stanzas from Btrfs snapshots Copyright (C) 2020-2024 Luka Žaja 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, either version 3 of the License, or (at your option) any later version. 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 . """ # endregion from typing import Collection from injector import inject from more_itertools import first, last from transitions import Machine, State from refind_btrfs.common.abc.factories import BaseLoggerFactory from refind_btrfs.common.enums import StateNames from refind_btrfs.common.exceptions import ( NoChangesDetectedError, PartitionError, RefindConfigError, SubvolumeError, ) from refind_btrfs.utility.helpers import checked_cast, has_items, is_singleton from .model import Model States = Collection[State] class RefindBtrfsMachine(Machine): @inject def __init__( self, logger_factory: BaseLoggerFactory, model: Model, states: States, ): self._logger = logger_factory.logger(__name__) if not has_items(states) or is_singleton(states): raise ValueError( "The 'states' collection must be initialized and contain at least two items!" ) initial = checked_cast(State, first(states)) expected_initial_name = StateNames.INITIAL.value if initial.name != expected_initial_name: raise ValueError( "The first item of the 'states' collection must " f"be a state named '{expected_initial_name}'!" ) final = checked_cast(State, last(states)) expected_final_name = StateNames.FINAL.value if final.name != expected_final_name: raise ValueError( "The last item of the 'states' collection must " f"be a state named '{expected_final_name}'!" ) conditions = model.conditions super().__init__( model=model, states=list(states), initial=initial, auto_transitions=False, name=__name__, ) self.add_ordered_transitions( loop=False, conditions=conditions, ) self._initial_state = initial def run(self) -> bool: logger = self._logger model = self.model initial_state = self._initial_state self.set_state(initial_state) try: while model.next_state(): if model.is_final(): return True except NoChangesDetectedError as e: logger.warning(e.formatted_message) return True except ( PartitionError, SubvolumeError, RefindConfigError, ) as e: logger.error(e.formatted_message) return False ================================================ FILE: src/refind_btrfs/system/__init__.py ================================================ # region Licensing # SPDX-FileCopyrightText: 2020-2024 Luka Žaja # # SPDX-License-Identifier: GPL-3.0-or-later """ refind-btrfs - Generate rEFInd manual boot stanzas from Btrfs snapshots Copyright (C) 2020-2024 Luka Žaja 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, either version 3 of the License, or (at your option) any later version. 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 . """ # endregion from .command_factories import ( BtrfsUtilSubvolumeCommandFactory, PillowIconCommandFactory, SystemDeviceCommandFactory, ) ================================================ FILE: src/refind_btrfs/system/btrfsutil_command.py ================================================ # region Licensing # SPDX-FileCopyrightText: 2020-2024 Luka Žaja # # SPDX-License-Identifier: GPL-3.0-or-later """ refind-btrfs - Generate rEFInd manual boot stanzas from Btrfs snapshots Copyright (C) 2020-2024 Luka Žaja 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, either version 3 of the License, or (at your option) any later version. 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 . """ # endregion from datetime import datetime from pathlib import Path from typing import Iterator, Optional, Set import btrfsutil from refind_btrfs.common import ConfigurableMixin, constants from refind_btrfs.common.abc.commands import SubvolumeCommand from refind_btrfs.common.abc.factories import BaseLoggerFactory from refind_btrfs.common.abc.providers import BasePackageConfigProvider from refind_btrfs.common.exceptions import SubvolumeError from refind_btrfs.device import NumIdRelation, Subvolume, UuidRelation from refind_btrfs.utility.helpers import ( checked_cast, default_if_none, none_throws, try_convert_bytes_to_uuid, ) class BtrfsUtilCommand(SubvolumeCommand, ConfigurableMixin): def __init__( self, logger_factory: BaseLoggerFactory, package_config_provider: BasePackageConfigProvider, ) -> None: ConfigurableMixin.__init__(self, package_config_provider) self._logger = logger_factory.logger(__name__) self._searched_directories: Set[Path] = set() def get_subvolume_from(self, filesystem_path: Path) -> Optional[Subvolume]: logger = self._logger if not filesystem_path.exists(): raise SubvolumeError(f"The '{filesystem_path}' path does not exist!") if not filesystem_path.is_dir(): raise SubvolumeError( f"The '{filesystem_path}' path does not represent a directory!" ) try: filesystem_path_str = str(filesystem_path) if btrfsutil.is_subvolume(filesystem_path_str): subvolume_id = btrfsutil.subvolume_id(filesystem_path_str) subvolume_path = btrfsutil.subvolume_path( filesystem_path_str, subvolume_id ) subvolume_read_only = btrfsutil.get_subvolume_read_only( filesystem_path_str ) subvolume_info = btrfsutil.subvolume_info( filesystem_path_str, subvolume_id ) self_uuid = default_if_none( try_convert_bytes_to_uuid(subvolume_info.uuid), constants.EMPTY_UUID, ) parent_uuid = default_if_none( try_convert_bytes_to_uuid(subvolume_info.parent_uuid), constants.EMPTY_UUID, ) return Subvolume( filesystem_path, subvolume_path, datetime.fromtimestamp(subvolume_info.otime), UuidRelation(self_uuid, parent_uuid), NumIdRelation(subvolume_info.id, subvolume_info.parent_id), subvolume_read_only, ) except btrfsutil.BtrfsUtilError as e: logger.exception("btrfsutil call failed!") raise SubvolumeError( f"Could not initialize the subvolume for '{filesystem_path}'!" ) from e return None def get_all_source_snapshots_for(self, parent: Subvolume) -> Iterator[Subvolume]: self._searched_directories.clear() snapshot_searches = self.package_config.snapshot_searches for snapshot_search in snapshot_searches: directory = snapshot_search.directory is_nested = snapshot_search.is_nested max_depth = snapshot_search.max_depth search_result = self._search_for_snapshots_in( directory, max_depth, parent=parent ) if is_nested: root_directory = directory.root for snapshot in search_result: filesystem_path = snapshot.filesystem_path nested_directory = filesystem_path / directory.relative_to( root_directory ) if nested_directory.exists(): yield from self._search_for_snapshots_in( nested_directory, max_depth, parent=parent ) yield snapshot else: yield from search_result def get_all_destination_snapshots(self) -> Iterator[Subvolume]: snapshot_manipulation = self.package_config.snapshot_manipulation destination_directory = snapshot_manipulation.destination_directory if destination_directory.exists(): yield from self._search_for_snapshots_in(destination_directory, 1) def get_bootable_snapshot_from(self, source: Subvolume) -> Subvolume: if source.is_read_only: snapshot_manipulation = self.package_config.snapshot_manipulation modify_read_only_flag = snapshot_manipulation.modify_read_only_flag if modify_read_only_flag: destination = self._modify_read_only_flag_for(source) else: destination = self._create_writable_snapshot_from(source) else: destination = source return destination.as_named() def delete_snapshot(self, snapshot: Subvolume) -> None: logger = self._logger filesystem_path = snapshot.filesystem_path logical_path = snapshot.logical_path try: filesystem_path_str = str(filesystem_path) is_subvolume = filesystem_path.exists() and btrfsutil.is_subvolume( filesystem_path_str ) if is_subvolume: root_dir_str = str(constants.ROOT_DIR) num_id = snapshot.num_id deleted_subvolumes = checked_cast( list[int], btrfsutil.deleted_subvolumes(root_dir_str) ) if num_id not in deleted_subvolumes: logger.info(f"Deleting the '{logical_path}' snapshot.") btrfsutil.delete_subvolume(filesystem_path_str) else: logger.warning( f"The '{logical_path}' snapshot has already " "been deleted but not yet cleaned up." ) else: logger.warning(f"The '{filesystem_path}' directory is not a subvolume.") except btrfsutil.BtrfsUtilError as e: logger.exception("btrfsutil call failed!") raise SubvolumeError( f"Could not delete the '{logical_path}' snapshot!" ) from e def _search_for_snapshots_in( self, directory: Path, max_depth: int, current_depth: int = 0, parent: Optional[Subvolume] = None, ) -> Iterator[Subvolume]: if current_depth > max_depth: return logger = self._logger is_initial_call = not bool(current_depth) resolved_path = directory.resolve() if is_initial_call: if parent is None: logger.info(f"Getting all snapshots in the '{directory}' directory.") else: logical_path = parent.logical_path logger.info( f"Searching for snapshots of the '{logical_path}' " f"subvolume in the '{directory}' directory." ) searched_directories = self._searched_directories if resolved_path not in searched_directories: subvolume = self.get_subvolume_from(resolved_path) can_subvolume_be_yielded = False if subvolume is not None: can_subvolume_be_yielded = ( subvolume.is_snapshot_of(parent) if parent is not None else subvolume.is_snapshot() ) searched_directories.add(resolved_path) if can_subvolume_be_yielded: yield none_throws(subvolume) else: subdirectories = ( child for child in directory.iterdir() if child.is_dir() ) for subdirectory in subdirectories: yield from self._search_for_snapshots_in( subdirectory, max_depth, current_depth + 1, parent ) def _modify_read_only_flag_for(self, source: Subvolume) -> Subvolume: logger = self._logger source_logical_path = source.logical_path try: logger.info( f"Modifying the '{source_logical_path}' snapshot's read-only flag." ) source_filesystem_path_str = str(source.filesystem_path) btrfsutil.set_subvolume_read_only(source_filesystem_path_str, False) except btrfsutil.BtrfsUtilError as e: logger.exception("btrfsutil call failed!") raise SubvolumeError( f"Could not modify the '{source_logical_path}' snapshot's read-only flag!" ) from e return source.as_writable() def _create_writable_snapshot_from(self, source: Subvolume) -> Subvolume: logger = self._logger snapshot_manipulation = self.package_config.snapshot_manipulation destination_directory = snapshot_manipulation.destination_directory if not destination_directory.exists(): directory_permissions = constants.SNAPSHOTS_ROOT_DIR_PERMISSIONS octal_permissions = "{0:o}".format(directory_permissions) try: logger.info( f"Creating the '{destination_directory}' destination " f"directory with {octal_permissions} permissions." ) destination_directory.mkdir(mode=directory_permissions, parents=True) except OSError as e: logger.exception("Path.mkdir() call failed!") raise SubvolumeError( f"Could not create the '{destination_directory}' destination directory!" ) from e destination = source.to_destination(destination_directory) source_logical_path = source.logical_path snapshot_directory = destination.filesystem_path try: logger.info( "Creating a new writable snapshot from the read-only " f"'{source_logical_path}' snapshot at '{snapshot_directory}'." ) snapshot_directory_str = str(snapshot_directory) is_subvolume = snapshot_directory.exists() and btrfsutil.is_subvolume( snapshot_directory_str ) if not is_subvolume: source_filesystem_path_str = str(source.filesystem_path) btrfsutil.create_snapshot( source_filesystem_path_str, snapshot_directory_str, read_only=False ) else: logger.warning( f"The '{snapshot_directory}' directory is already a subvolume." ) except btrfsutil.BtrfsUtilError as e: logger.exception("btrfsutil call failed!") raise SubvolumeError( f"Could not create a new writable snapshot at '{snapshot_directory}'!" ) from e writable_snapshot = self.get_subvolume_from(snapshot_directory) return none_throws(writable_snapshot).as_newly_created_from(source) ================================================ FILE: src/refind_btrfs/system/command_factories.py ================================================ # region Licensing # SPDX-FileCopyrightText: 2020-2024 Luka Žaja # # SPDX-License-Identifier: GPL-3.0-or-later """ refind-btrfs - Generate rEFInd manual boot stanzas from Btrfs snapshots Copyright (C) 2020-2024 Luka Žaja 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, either version 3 of the License, or (at your option) any later version. 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 . """ # endregion from injector import inject from refind_btrfs.common.abc.commands import ( DeviceCommand, IconCommand, SubvolumeCommand, ) from refind_btrfs.common.abc.factories import ( BaseDeviceCommandFactory, BaseIconCommandFactory, BaseLoggerFactory, BaseSubvolumeCommandFactory, ) from refind_btrfs.common.abc.providers import BasePackageConfigProvider from .btrfsutil_command import BtrfsUtilCommand from .findmnt_command import FindmntCommand from .fstab_command import FstabCommand from .lsblk_command import LsblkCommand from .pillow_command import PillowCommand class SystemDeviceCommandFactory(BaseDeviceCommandFactory): @inject def __init__( self, logger_factory: BaseLoggerFactory, package_config_provider: BasePackageConfigProvider, ) -> None: self._logger_factory = logger_factory self._package_config_provider = package_config_provider def physical_device_command(self) -> DeviceCommand: return LsblkCommand(self._logger_factory, self._package_config_provider) def live_device_command(self) -> DeviceCommand: return FindmntCommand(self._logger_factory) def static_device_command(self) -> DeviceCommand: return FstabCommand(self._logger_factory) class BtrfsUtilSubvolumeCommandFactory(BaseSubvolumeCommandFactory): @inject def __init__( self, logger_factory: BaseLoggerFactory, package_config_provider: BasePackageConfigProvider, ) -> None: self._logger_factory = logger_factory self._package_config_provider = package_config_provider def subvolume_command(self) -> SubvolumeCommand: return BtrfsUtilCommand(self._logger_factory, self._package_config_provider) class PillowIconCommandFactory(BaseIconCommandFactory): @inject def __init__(self, logger_factory: BaseLoggerFactory) -> None: self._logger_factory = logger_factory def icon_command(self) -> IconCommand: return PillowCommand(self._logger_factory) ================================================ FILE: src/refind_btrfs/system/findmnt_command.py ================================================ # region Licensing # SPDX-FileCopyrightText: 2020-2024 Luka Žaja # # SPDX-License-Identifier: GPL-3.0-or-later """ refind-btrfs - Generate rEFInd manual boot stanzas from Btrfs snapshots Copyright (C) 2020-2024 Luka Žaja 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, either version 3 of the License, or (at your option) any later version. 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 . """ # endregion import json import subprocess from subprocess import CalledProcessError from typing import Any, Iterable, Iterator from more_itertools import always_iterable from refind_btrfs.common import constants from refind_btrfs.common.abc.commands import DeviceCommand from refind_btrfs.common.abc.factories import BaseLoggerFactory from refind_btrfs.common.enums import FindmntColumn, FindmntJsonKey from refind_btrfs.common.exceptions import PartitionError from refind_btrfs.device import ( BlockDevice, Filesystem, Partition, PartitionTable, Subvolume, ) from refind_btrfs.utility.helpers import ( checked_cast, default_if_none, is_none_or_whitespace, ) class FindmntCommand(DeviceCommand): def __init__(self, logger_factory: BaseLoggerFactory) -> None: self._logger = logger_factory.logger(__name__) def get_block_devices(self) -> Iterator[BlockDevice]: raise NotImplementedError( f"Class '{FindmntCommand.__name__}' does not implement the " f"'{DeviceCommand.get_block_devices.__name__}' method!" ) # pylint: disable=unused-argument def save_partition_table(self, partition_table: PartitionTable) -> None: raise NotImplementedError( f"Class '{FindmntCommand.__name__}' does not implement the " f"'{DeviceCommand.save_partition_table.__name__}' method!" ) def _block_device_partition_table( self, block_device: BlockDevice ) -> PartitionTable: logger = self._logger findmnt_columns = [ FindmntColumn.PART_UUID, FindmntColumn.PART_LABEL, FindmntColumn.FS_UUID, FindmntColumn.DEVICE_NAME, FindmntColumn.FS_TYPE, FindmntColumn.FS_LABEL, FindmntColumn.FS_MOUNT_POINT, FindmntColumn.FS_MOUNT_OPTIONS, ] device_name = block_device.name output = constants.COLUMN_SEPARATOR.join( [findmnt_column_key.value.upper() for findmnt_column_key in findmnt_columns] ) findmnt_command = f"findmnt --json --mtab --real --nofsroot --uniq --output {output}" try: logger.info( f"Initializing the live partition table for device '{device_name}' using findmnt." ) logger.debug(f"Running command '{findmnt_command}'.") findmnt_process = subprocess.run( findmnt_command.split(), capture_output=True, check=True, text=True ) except CalledProcessError as e: stderr = checked_cast(str, e.stderr) if is_none_or_whitespace(stderr): message = "findmnt execution failed!" else: message = f"findmnt execution failed: '{stderr.rstrip()}'!" logger.exception(message) raise PartitionError( f"Could not initialize the live partition table for '{device_name}'!" ) from e findmnt_parsed_output = json.loads(findmnt_process.stdout) findmnt_partitions = ( findmnt_partition for findmnt_partition in always_iterable( findmnt_parsed_output.get(FindmntJsonKey.FILESYSTEMS.value) ) if block_device.is_matched_with( default_if_none( findmnt_partition.get(FindmntColumn.DEVICE_NAME.value), constants.EMPTY_STR, ) ) ) return PartitionTable( constants.EMPTY_HEX_UUID, constants.MTAB_PT_TYPE ).with_partitions(FindmntCommand._map_to_partitions(findmnt_partitions)) def _subvolume_partition_table(self, subvolume: Subvolume) -> PartitionTable: raise NotImplementedError( f"Class '{FindmntCommand.__name__}' does not implement the " f"'{DeviceCommand._subvolume_partition_table.__name__}' method!" ) @staticmethod def _map_to_partitions( findmnt_partitions: Iterable[Any], ) -> Iterator[Partition]: for findmnt_partition in findmnt_partitions: findmnt_part_columns = [ default_if_none( findmnt_partition.get(findmnt_column_key.value), constants.EMPTY_STR ) for findmnt_column_key in [ FindmntColumn.PART_UUID, FindmntColumn.DEVICE_NAME, FindmntColumn.PART_LABEL, ] ] findmnt_fs_columns = [ default_if_none( findmnt_partition.get(findmnt_column_key.value), constants.EMPTY_STR ) for findmnt_column_key in [ FindmntColumn.FS_UUID, FindmntColumn.FS_LABEL, FindmntColumn.FS_TYPE, FindmntColumn.FS_MOUNT_POINT, ] ] yield ( Partition(*findmnt_part_columns).with_filesystem( Filesystem(*findmnt_fs_columns).with_mount_options( default_if_none( findmnt_partition.get(FindmntColumn.FS_MOUNT_OPTIONS.value), constants.EMPTY_STR, ) ) ) ) ================================================ FILE: src/refind_btrfs/system/fstab_command.py ================================================ # region Licensing # SPDX-FileCopyrightText: 2020-2024 Luka Žaja # # SPDX-License-Identifier: GPL-3.0-or-later """ refind-btrfs - Generate rEFInd manual boot stanzas from Btrfs snapshots Copyright (C) 2020-2024 Luka Žaja 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, either version 3 of the License, or (at your option) any later version. 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 . """ # endregion import fileinput from typing import Iterator, TextIO from refind_btrfs.common import constants from refind_btrfs.common.abc.commands import DeviceCommand from refind_btrfs.common.abc.factories import BaseLoggerFactory from refind_btrfs.common.enums import FstabColumn from refind_btrfs.common.exceptions import PartitionError from refind_btrfs.device import ( BlockDevice, Filesystem, Partition, PartitionTable, Subvolume, ) from refind_btrfs.utility.helpers import ( default_if_none, none_throws, try_parse_int, ) class FstabCommand(DeviceCommand): def __init__(self, logger_factory: BaseLoggerFactory) -> None: self._logger = logger_factory.logger(__name__) def get_block_devices(self) -> Iterator[BlockDevice]: raise NotImplementedError( f"Class '{FstabCommand.__name__}' does not implement the " f"'{DeviceCommand.get_block_devices.__name__}' method!" ) def _block_device_partition_table( self, block_device: BlockDevice ) -> PartitionTable: raise NotImplementedError( f"Class '{FstabCommand.__name__}' does not implement the " f"'{DeviceCommand._block_device_partition_table.__name__}' method!" ) def save_partition_table(self, partition_table: PartitionTable) -> None: logger = self._logger fstab_file_path = none_throws(partition_table.fstab_file_path) try: logger.info(f"Modifying the '{fstab_file_path}' file.") with fileinput.input(str(fstab_file_path), inplace=True) as fstab_file: for fstab_line in fstab_file: transformed_fstab_line = partition_table.transform_fstab_line( fstab_line ) print(transformed_fstab_line, end=constants.EMPTY_STR) except OSError as e: logger.exception("fileinput.input() call failed!") raise PartitionError( f"Could not modify the '{fstab_file_path}' file!" ) from e def _subvolume_partition_table(self, subvolume: Subvolume) -> PartitionTable: filesystem_path = subvolume.filesystem_path fstab_file_path = filesystem_path / constants.FSTAB_FILE if not fstab_file_path.exists(): raise PartitionError(f"The '{fstab_file_path}' file does not exist!") logger = self._logger logical_path = subvolume.logical_path try: logger.info( "Initializing the static partition table for " f"subvolume '{logical_path}' from its fstab file." ) with fstab_file_path.open("r") as fstab_file: return ( PartitionTable(constants.EMPTY_HEX_UUID, constants.FSTAB_PT_TYPE) .with_fstab_file_path(fstab_file_path) .with_partitions(FstabCommand._map_to_partitions(fstab_file)) ) except OSError as e: logger.exception("Path.open('r') call failed!") raise PartitionError( f"Could not read from the '{fstab_file_path}' file!" ) from e @staticmethod def _map_to_partitions( fstab_file: TextIO, ) -> Iterator[Partition]: for fstab_line in fstab_file: if PartitionTable.is_valid_fstab_entry(fstab_line): split_fstab_entry = fstab_line.split() fs_dump = try_parse_int(split_fstab_entry[FstabColumn.FS_DUMP.value]) fs_fsck = try_parse_int(split_fstab_entry[FstabColumn.FS_FSCK.value]) filesystem = ( Filesystem( constants.EMPTY_STR, constants.EMPTY_STR, split_fstab_entry[FstabColumn.FS_TYPE.value], split_fstab_entry[FstabColumn.FS_MOUNT_POINT.value], ) .with_dump_and_fsck( default_if_none(fs_dump, 0), default_if_none(fs_fsck, 0), ) .with_mount_options( split_fstab_entry[FstabColumn.FS_MOUNT_OPTIONS.value] ) ) partition = Partition( constants.EMPTY_STR, split_fstab_entry[FstabColumn.DEVICE_NAME.value], constants.EMPTY_STR, ).with_filesystem(filesystem) yield partition ================================================ FILE: src/refind_btrfs/system/lsblk_command.py ================================================ # region Licensing # SPDX-FileCopyrightText: 2020-2024 Luka Žaja # # SPDX-License-Identifier: GPL-3.0-or-later """ refind-btrfs - Generate rEFInd manual boot stanzas from Btrfs snapshots Copyright (C) 2020-2024 Luka Žaja 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, either version 3 of the License, or (at your option) any later version. 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 . """ # endregion import json import subprocess from subprocess import CalledProcessError from typing import Any, Iterable, Iterator from more_itertools import always_iterable, one from refind_btrfs.common import ConfigurableMixin, constants from refind_btrfs.common.abc.commands import DeviceCommand from refind_btrfs.common.abc.factories import BaseLoggerFactory from refind_btrfs.common.abc.providers import BasePackageConfigProvider from refind_btrfs.common.enums import LsblkColumn, LsblkJsonKey from refind_btrfs.common.exceptions import PartitionError from refind_btrfs.device import ( BlockDevice, Filesystem, Partition, PartitionTable, Subvolume, ) from refind_btrfs.utility.helpers import ( checked_cast, default_if_none, is_none_or_whitespace, ) class LsblkCommand(DeviceCommand, ConfigurableMixin): def __init__( self, logger_factory: BaseLoggerFactory, package_config_provider: BasePackageConfigProvider, ) -> None: ConfigurableMixin.__init__(self, package_config_provider) self._logger = logger_factory.logger(__name__) def get_block_devices(self) -> Iterator[BlockDevice]: logger = self._logger lsblk_columns = [ LsblkColumn.DEVICE_NAME, LsblkColumn.DEVICE_TYPE, LsblkColumn.MAJOR_MINOR, ] output = constants.COLUMN_SEPARATOR.join( [lsblk_column_key.value.upper() for lsblk_column_key in lsblk_columns] ) lsblk_command = f"lsblk --json --merge --paths --output {output}" try: logger.info("Initializing the block devices using lsblk.") logger.debug(f"Running command '{lsblk_command}'.") lsblk_process = subprocess.run( lsblk_command.split(), capture_output=True, check=True, text=True ) except CalledProcessError as e: stderr = checked_cast(str, e.stderr) if is_none_or_whitespace(stderr): message = "lsblk execution failed!" else: message = f"lsblk execution failed: '{stderr.rstrip()}'!" logger.exception(message) raise PartitionError("Could not initialize the block devices!") from e lsblk_parsed_output = json.loads(lsblk_process.stdout) lsblk_blockdevices = always_iterable( lsblk_parsed_output.get(LsblkJsonKey.BLOCKDEVICES.value) ) yield from LsblkCommand._map_to_block_devices(lsblk_blockdevices) # pylint: disable=unused-argument def save_partition_table(self, partition_table: PartitionTable) -> None: raise NotImplementedError( f"Class '{LsblkCommand.__name__}' does not implement the " f"'{DeviceCommand.save_partition_table.__name__}' method!" ) def _block_device_partition_table( self, block_device: BlockDevice ) -> PartitionTable: logger = self._logger lsblk_columns = [ LsblkColumn.PTABLE_UUID, LsblkColumn.PTABLE_TYPE, LsblkColumn.PART_UUID, LsblkColumn.PART_TYPE, LsblkColumn.PART_LABEL, LsblkColumn.FS_UUID, LsblkColumn.DEVICE_NAME, LsblkColumn.FS_TYPE, LsblkColumn.FS_LABEL, LsblkColumn.FS_MOUNT_POINT, ] device_name = block_device.name output = constants.COLUMN_SEPARATOR.join( [lsblk_column_key.value.upper() for lsblk_column_key in lsblk_columns] ) lsblk_command = f"lsblk {device_name} --json --paths --tree --output {output}" try: logger.info( f"Initializing the physical partition table for device '{device_name}' using lsblk." ) logger.debug(f"Running command '{lsblk_command}'.") lsblk_process = subprocess.run( lsblk_command.split(), check=True, capture_output=True, text=True ) except CalledProcessError as e: stderr = checked_cast(str, e.stderr) if is_none_or_whitespace(stderr): message = "lsblk execution failed!" else: message = f"lsblk execution failed: '{stderr.rstrip()}'!" logger.exception(message) raise PartitionError( f"Could not initialize the physical partition table for '{device_name}'!" ) from e lsblk_parsed_output = json.loads(lsblk_process.stdout) lsblk_blockdevice = one( lsblk_parsed_output.get(LsblkJsonKey.BLOCKDEVICES.value) ) lsblk_partition_table_columns = [ default_if_none( lsblk_blockdevice.get(lsblk_column_key.value), constants.EMPTY_STR ) for lsblk_column_key in [ LsblkColumn.PTABLE_UUID, LsblkColumn.PTABLE_TYPE, ] ] esp_uuid = self.package_config.esp_uuid lsblk_partitions = always_iterable( lsblk_blockdevice.get(LsblkJsonKey.CHILDREN.value) ) return ( PartitionTable(*lsblk_partition_table_columns) .with_esp_uuid(esp_uuid) .with_partitions(LsblkCommand._map_to_partitions(lsblk_partitions)) ) def _subvolume_partition_table(self, subvolume: Subvolume) -> PartitionTable: raise NotImplementedError( f"Class '{LsblkCommand.__name__}' does not implement the " f"'{DeviceCommand._subvolume_partition_table.__name__}' method!" ) @staticmethod def _map_to_block_devices( lsblk_blockdevices: Iterable[Any], ) -> Iterator[BlockDevice]: for lsblk_blockdevice in lsblk_blockdevices: lsblk_blockdevice_columns = [ default_if_none( lsblk_blockdevice.get(lsblk_column_key.value), constants.EMPTY_STR ) for lsblk_column_key in [ LsblkColumn.DEVICE_NAME, LsblkColumn.DEVICE_TYPE, LsblkColumn.MAJOR_MINOR, ] ] lsblk_dependencies = always_iterable( lsblk_blockdevice.get(LsblkJsonKey.CHILDREN.value) ) yield ( BlockDevice(*lsblk_blockdevice_columns).with_dependencies( LsblkCommand._map_to_block_devices(lsblk_dependencies) ) ) @staticmethod def _map_to_partitions( lsblk_partitions: Iterable[Any], ) -> Iterator[Partition]: for lsblk_partition in lsblk_partitions: lsblk_part_columns = [ default_if_none( lsblk_partition.get(lsblk_column_key.value), constants.EMPTY_STR ) for lsblk_column_key in [ LsblkColumn.PART_UUID, LsblkColumn.DEVICE_NAME, LsblkColumn.PART_LABEL, ] ] lsblk_fs_columns = [ default_if_none( lsblk_partition.get(lsblk_column_key.value), constants.EMPTY_STR ) for lsblk_column_key in [ LsblkColumn.FS_UUID, LsblkColumn.FS_LABEL, LsblkColumn.FS_TYPE, LsblkColumn.FS_MOUNT_POINT, ] ] yield ( Partition(*lsblk_part_columns) .with_part_type( default_if_none( lsblk_partition.get(LsblkColumn.PART_TYPE.value), constants.EMPTY_STR, ) ) .with_filesystem(Filesystem(*lsblk_fs_columns)) ) lsblk_nested_partitions = always_iterable( lsblk_partition.get(LsblkJsonKey.CHILDREN.value) ) yield from LsblkCommand._map_to_partitions(lsblk_nested_partitions) ================================================ FILE: src/refind_btrfs/system/pillow_command.py ================================================ # region Licensing # SPDX-FileCopyrightText: 2020-2024 Luka Žaja # # SPDX-License-Identifier: GPL-3.0-or-later """ refind-btrfs - Generate rEFInd manual boot stanzas from Btrfs snapshots Copyright (C) 2020-2024 Luka Žaja 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, either version 3 of the License, or (at your option) any later version. 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 . """ # endregion from pathlib import Path from typing import Callable, Set, Tuple, Union from refind_btrfs.common import BtrfsLogo, constants from refind_btrfs.common.abc.commands import IconCommand from refind_btrfs.common.abc.factories import BaseLoggerFactory from refind_btrfs.common.enums import ( BtrfsLogoHorizontalAlignment, BtrfsLogoVerticalAlignment, ) from refind_btrfs.common.exceptions import RefindConfigError class PillowCommand(IconCommand): def __init__( self, logger_factory: BaseLoggerFactory, ) -> None: minimum_offset: Callable[[int], int] = lambda _: 0 medium_offset: Callable[[int], int] = lambda delta: delta // 2 maximum_offset: Callable[[int], int] = lambda delta: delta self._logger = logger_factory.logger(__name__) self._validated_icons: Set[Path] = set() self._embed_offset_initializers: dict[ Union[BtrfsLogoHorizontalAlignment, BtrfsLogoVerticalAlignment], Callable[[int], int], ] = { BtrfsLogoHorizontalAlignment.LEFT: minimum_offset, BtrfsLogoHorizontalAlignment.CENTER: medium_offset, BtrfsLogoHorizontalAlignment.RIGHT: maximum_offset, BtrfsLogoVerticalAlignment.TOP: minimum_offset, BtrfsLogoVerticalAlignment.CENTER: medium_offset, BtrfsLogoVerticalAlignment.BOTTOM: maximum_offset, } def validate_custom_icon( self, refind_config_path: Path, source_icon_path: Path, custom_icon_path: Path ) -> Path: custom_icon_absolute_path = refind_config_path.parent / custom_icon_path if not custom_icon_absolute_path.exists(): raise RefindConfigError( f"The '{custom_icon_absolute_path}' path does not exist!" ) validated_icons = self._validated_icons if custom_icon_absolute_path not in validated_icons: refind_directory = refind_config_path.parent logger = self._logger try: # pylint: disable=import-outside-toplevel from PIL import Image logger.info( "Validating the " f"'{custom_icon_absolute_path.relative_to(refind_directory)}' file." ) with Image.open(custom_icon_absolute_path, "r") as custom_icon_image: expected_formats = ["PNG", "JPEG", "BMP", "ICNS"] custom_icon_image_format = custom_icon_image.format if custom_icon_image_format not in expected_formats: raise RefindConfigError( f"The '{custom_icon_absolute_path.name}' image's " f"format ('{custom_icon_image_format}') is not supported!" ) except OSError as e: logger.exception("Image.open('r') call failed!") raise RefindConfigError( f"Could not read the '{custom_icon_absolute_path}' file!" ) from e validated_icons.add(custom_icon_absolute_path) return PillowCommand._discern_destination_icon_relative_path( refind_config_path, source_icon_path, custom_icon_absolute_path ) def embed_btrfs_logo_into_source_icon( self, refind_config_path: Path, source_icon_path: Path, btrfs_logo: BtrfsLogo ) -> Path: source_icon_absolute_path = PillowCommand._discern_source_icon_absolute_path( refind_config_path, source_icon_path ) absolute_paths = PillowCommand._discern_absolute_paths_for_btrfs_logo_embedding( refind_config_path, source_icon_absolute_path, btrfs_logo ) btrfs_logo_absolute_path = absolute_paths[0] destination_icon_absolute_path = absolute_paths[1] if not destination_icon_absolute_path.exists(): logger = self._logger refind_directory = refind_config_path.parent try: # pylint: disable=import-outside-toplevel from PIL import Image logger.info( "Embedding " f"the '{btrfs_logo_absolute_path.name}' " "logo into " f"the '{source_icon_absolute_path.relative_to(refind_directory)}' icon." ) with Image.open( btrfs_logo_absolute_path ) as btrfs_logo_image, Image.open( source_icon_absolute_path ) as source_icon_image: expected_format = "PNG" source_icon_image_format = source_icon_image.format if source_icon_image_format != expected_format: raise RefindConfigError( f"The '{source_icon_absolute_path.name}' image's " f"format ('{source_icon_image_format}') is not supported!" ) btrfs_logo_image_width = btrfs_logo_image.width source_icon_image_width = source_icon_image.width if source_icon_image_width < btrfs_logo_image_width: raise RefindConfigError( f"The '{source_icon_absolute_path.name}' image's width " f"({source_icon_image_width} px) is less than " "the selected Btrfs logo's width!" ) btrfs_logo_image_height = btrfs_logo_image.height source_icon_image_height = source_icon_image.height if source_icon_image_height < btrfs_logo_image_height: raise RefindConfigError( f"The '{source_icon_absolute_path.name}' image's height " f"({source_icon_image_height} px) is less than " "the selected Btrfs logo's height!" ) try: horizontal_alignment = btrfs_logo.horizontal_alignment x_delta = source_icon_image_width - btrfs_logo_image_width x_offset = self._embed_offset_initializers[ horizontal_alignment ](x_delta) vertical_alignment = btrfs_logo.vertical_alignment y_delta = source_icon_image_height - btrfs_logo_image_height y_offset = self._embed_offset_initializers[vertical_alignment]( y_delta ) resized_btrfs_logo_image = Image.new( btrfs_logo_image.mode, source_icon_image.size ) resized_btrfs_logo_image.paste( btrfs_logo_image, ( x_offset, y_offset, ), ) destination_icon_image = Image.alpha_composite( source_icon_image, resized_btrfs_logo_image ) destination_directory = ( refind_directory / constants.SNAPSHOT_STANZAS_DIR_NAME / constants.ICONS_DIR ) if not destination_directory.exists(): logger.info( "Creating the " f"'{destination_directory.relative_to(refind_directory)}' " "destination directory." ) destination_directory.mkdir(parents=True) logger.info( "Saving the " f"'{destination_icon_absolute_path.relative_to(refind_directory)}' " "file." ) destination_icon_image.save(destination_icon_absolute_path) except OSError as e: logger.exception("Image.save() call failed!") raise RefindConfigError( f"Could not save the '{e.filename}' file!" ) from e except OSError as e: logger.exception("Image.open('r') call failed!") raise RefindConfigError( f"Could not read the '{e.filename}' file!" ) from e return PillowCommand._discern_destination_icon_relative_path( refind_config_path, source_icon_path, destination_icon_absolute_path ) @staticmethod def _discern_source_icon_absolute_path( refind_config_path: Path, icon_path: Path ) -> Path: refind_config_path_parents = refind_config_path.parents icon_path_parts = icon_path.parts for parent in refind_config_path_parents: if parent.name not in icon_path_parts: return parent / str(icon_path).removeprefix(constants.FORWARD_SLASH) raise RefindConfigError( f"Could not discern the '{icon_path.name}' file's absolute path!" ) @staticmethod def _discern_destination_icon_relative_path( refind_config_path: Path, source_icon_path: Path, destination_icon_path: Path, ) -> Path: source_icon_path_parts = source_icon_path.parts refind_config_path_parents = refind_config_path.parents for parent in refind_config_path_parents: if parent.name not in source_icon_path_parts: return constants.ROOT_DIR / destination_icon_path.relative_to(parent) raise RefindConfigError( f"Could not discern the '{destination_icon_path.name}' file's relative path!" ) @staticmethod def _discern_absolute_paths_for_btrfs_logo_embedding( refind_config_path: Path, source_icon_absolute_path: Path, btrfs_logo: BtrfsLogo ) -> Tuple[Path, Path]: variant = btrfs_logo.variant size = btrfs_logo.size horizontal_alignment = btrfs_logo.horizontal_alignment vertical_alignment = btrfs_logo.vertical_alignment btrfs_logos_directory = constants.BTRFS_LOGOS_DIR btrfs_logo_name = f"{variant.value}_{size.value}.png" btrfs_logo_absolute_path = btrfs_logos_directory / btrfs_logo_name refind_directory = refind_config_path.parent destination_directory = ( refind_directory / constants.SNAPSHOT_STANZAS_DIR_NAME / constants.ICONS_DIR ) destination_icon_name = ( f"{source_icon_absolute_path.stem}_{btrfs_logo_absolute_path.stem}_" f"h-{horizontal_alignment.value}_v-{vertical_alignment.value}.png" ) destination_icon_absolute_path = destination_directory / destination_icon_name return (btrfs_logo_absolute_path, destination_icon_absolute_path) ================================================ FILE: src/refind_btrfs/utility/__init__.py ================================================ # region Licensing # SPDX-FileCopyrightText: 2020-2024 Luka Žaja # # SPDX-License-Identifier: GPL-3.0-or-later """ refind-btrfs - Generate rEFInd manual boot stanzas from Btrfs snapshots Copyright (C) 2020-2024 Luka Žaja 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, either version 3 of the License, or (at your option) any later version. 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 . """ # endregion from .level_aware_formatter import LevelAwareFormatter ================================================ FILE: src/refind_btrfs/utility/file_package_config_provider.py ================================================ # region Licensing # SPDX-FileCopyrightText: 2020-2024 Luka Žaja # # SPDX-License-Identifier: GPL-3.0-or-later """ refind-btrfs - Generate rEFInd manual boot stanzas from Btrfs snapshots Copyright (C) 2020-2024 Luka Žaja 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, either version 3 of the License, or (at your option) any later version. 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 . """ # endregion import sys from datetime import datetime from importlib.util import find_spec from pathlib import Path from typing import Any, Callable, Iterator, Optional, Type, TypeVar, cast from uuid import UUID from injector import inject from more_itertools import one, unique_everseen from tomlkit.exceptions import TOMLKitError from tomlkit.items import AoT, Table from tomlkit.toml_document import TOMLDocument from tomlkit.toml_file import TOMLFile from refind_btrfs.common import ( BootStanzaGeneration, BtrfsLogo, Icon, PackageConfig, SnapshotManipulation, SnapshotSearch, constants, ) from refind_btrfs.common.abc.factories import BaseLoggerFactory from refind_btrfs.common.abc.providers import ( BasePackageConfigProvider, BasePersistenceProvider, ) from refind_btrfs.common.enums import ( BootStanzaGenerationConfigKey, BootStanzaIconGenerationMode, BtrfsLogoConfigKey, BtrfsLogoHorizontalAlignment, BtrfsLogoSize, BtrfsLogoVariant, BtrfsLogoVerticalAlignment, ConfigInitializationType, IconConfigKey, PathRelation, SnapshotManipulationConfigKey, SnapshotSearchConfigKey, TopLevelConfigKey, ) from refind_btrfs.common.exceptions import PackageConfigError from refind_btrfs.device import NumIdRelation, Subvolume, UuidRelation from .helpers import ( checked_cast, discern_path_relation_of, has_items, none_throws, try_convert_str_to_enum, try_parse_uuid, ) TSourceValue = TypeVar("TSourceValue") TDestinationValue = TypeVar("TDestinationValue") class FilePackageConfigProvider(BasePackageConfigProvider): default_package_config = PackageConfig( constants.EMPTY_UUID, True, True, [SnapshotSearch(Path("/.snapshots"), False, 2)], SnapshotManipulation(5, False, Path("/root/.refind-btrfs"), set()), BootStanzaGeneration( "refind.conf", True, False, set(), Icon( BootStanzaIconGenerationMode.DEFAULT, Path("btrfs-snapshot-stanzas/icons/sample_icon.png"), BtrfsLogo( BtrfsLogoVariant.ORIGINAL, BtrfsLogoSize.MEDIUM, BtrfsLogoHorizontalAlignment.CENTER, BtrfsLogoVerticalAlignment.CENTER, ), ), ), ) @inject def __init__( self, logger_factory: BaseLoggerFactory, persistence_provider: BasePersistenceProvider, ) -> None: self._logger = logger_factory.logger(__name__) self._persistence_provider = persistence_provider self._package_config: Optional[PackageConfig] = None def get_config(self) -> PackageConfig: persistence_provider = self._persistence_provider persisted_package_config = persistence_provider.get_package_config() current_package_config = self._package_config if persisted_package_config is None: logger = self._logger config_file_path = constants.PACKAGE_CONFIG_FILE if not config_file_path.exists(): raise PackageConfigError( f"The '{config_file_path}' path does not exist!" ) if not config_file_path.is_file(): raise PackageConfigError( f"The '{config_file_path}' does not represent a file!" ) logger.info(f"Analyzing the '{config_file_path.name}' file.") try: toml_file = TOMLFile(str(config_file_path)) toml_document = toml_file.read() except TOMLKitError as e: logger.exception( f"Error while parsing the '{config_file_path.name}' file" ) raise PackageConfigError( "Could not load the package configuration from file'!" ) from e else: current_package_config = FilePackageConfigProvider._read_config_from( toml_document ).with_initialization_type(ConfigInitializationType.PARSED) persistence_provider.save_package_config( none_throws(current_package_config) ) elif current_package_config is None: current_package_config = persisted_package_config.with_initialization_type( ConfigInitializationType.PERSISTED ) self._package_config = current_package_config return none_throws(current_package_config) @staticmethod def _read_config_from(toml_document: TOMLDocument): container = cast(dict, toml_document) default_package_config = FilePackageConfigProvider.default_package_config esp_uuid = FilePackageConfigProvider._get_config_value( container, TopLevelConfigKey.ESP_UUID.value, str, default_package_config, (UUID, try_parse_uuid), ) exit_if_root_is_snapshot = FilePackageConfigProvider._get_config_value( container, TopLevelConfigKey.EXIT_IF_ROOT_IS_SNAPSHOT.value, bool, default_package_config, ) exit_if_no_changes_are_detected = FilePackageConfigProvider._get_config_value( container, TopLevelConfigKey.EXIT_IF_NO_CHANGES_ARE_DETECTED.value, bool, default_package_config, ) snapshot_searches_key = TopLevelConfigKey.SNAPSHOT_SEARCH.value default_snapshot_searches = default_package_config.snapshot_searches if snapshot_searches_key in container: snapshot_searches = list( unique_everseen( FilePackageConfigProvider._map_to_snapshot_searches( checked_cast(AoT, container[snapshot_searches_key]), one(default_snapshot_searches), ) ) ) else: snapshot_searches = default_snapshot_searches snapshot_manipulation_key = TopLevelConfigKey.SNAPSHOT_MANIPULATION.value if snapshot_manipulation_key in container: snapshot_manipulation = ( FilePackageConfigProvider._map_to_snapshot_manipulation( checked_cast( Table, container[snapshot_manipulation_key], ), default_package_config.snapshot_manipulation, ) ) else: snapshot_manipulation = default_package_config.snapshot_manipulation destination_directory = snapshot_manipulation.destination_directory for snapshot_search in snapshot_searches: search_directory = snapshot_search.directory path_relation = discern_path_relation_of( (destination_directory, search_directory) ) if path_relation == PathRelation.SAME: raise PackageConfigError( "The search and destination directories cannot be the same!" ) if path_relation == PathRelation.FIRST_NESTED_IN_SECOND: raise PackageConfigError( f"The '{destination_directory}' destination directory is nested in " f"the '{search_directory}' search directory!" ) if path_relation == PathRelation.SECOND_NESTED_IN_FIRST: raise PackageConfigError( f"The '{search_directory}' search directory is nested in " f"the '{destination_directory}' destination directory!" ) boot_stanza_generation_key = TopLevelConfigKey.BOOT_STANZA_GENERATION.value if boot_stanza_generation_key in container: boot_stanza_generation = ( FilePackageConfigProvider._map_to_boot_stanza_generation( checked_cast(Table, container[boot_stanza_generation_key]), default_package_config.boot_stanza_generation, ) ) else: boot_stanza_generation = default_package_config.boot_stanza_generation return PackageConfig( esp_uuid, exit_if_root_is_snapshot, exit_if_no_changes_are_detected, snapshot_searches, snapshot_manipulation, boot_stanza_generation, ) @staticmethod def _map_to_snapshot_searches( snapshot_search_values: AoT, default_snapshot_search: SnapshotSearch ) -> Iterator[SnapshotSearch]: max_depth_key = SnapshotSearchConfigKey.MAX_DEPTH.value for snapshot_search_value in snapshot_search_values.body: container = cast(dict, snapshot_search_value) directory = cast( Path, FilePackageConfigProvider._get_config_value( container, SnapshotSearchConfigKey.DIRECTORY.value, str, default_snapshot_search, (Path, None), ), ) if not directory.exists(): raise PackageConfigError(f"The '{directory}' path does not exist!") if not directory.is_dir(): raise PackageConfigError( f"The '{directory}' path does not represent a directory!" ) is_nested = FilePackageConfigProvider._get_config_value( container, SnapshotSearchConfigKey.IS_NESTED.value, bool, default_snapshot_search, ) max_depth = cast( int, FilePackageConfigProvider._get_config_value( container, max_depth_key, int, default_snapshot_search ), ) if max_depth <= 0: raise PackageConfigError( f"The '{max_depth_key}' option must be greater than zero!" ) yield SnapshotSearch(directory, is_nested, max_depth) @staticmethod def _map_to_snapshot_manipulation( snapshot_manipulation_value: Table, default_snapshot_manipulation: SnapshotManipulation, ) -> SnapshotManipulation: container = cast(dict, snapshot_manipulation_value) selection_count_key = SnapshotManipulationConfigKey.SELECTION_COUNT.value if selection_count_key in container: selection_count_value = container[selection_count_key] if isinstance(selection_count_value, int): selection_count = int(selection_count_value) if selection_count <= 0: raise PackageConfigError( f"The '{selection_count_key}' option must be greater than zero!" ) elif isinstance(selection_count_value, str): actual_string = str(selection_count_value).strip() expected_string = constants.SNAPSHOT_SELECTION_COUNT_INFINITY if actual_string != expected_string: raise PackageConfigError( f"In case the '{selection_count_key}' option is a string " f"it can only be set to '{expected_string}'!" ) selection_count = sys.maxsize else: raise PackageConfigError( f"The '{selection_count_key}' option must be either an integer or a string!" ) else: selection_count = default_snapshot_manipulation.selection_count modify_read_only_flag = FilePackageConfigProvider._get_config_value( container, SnapshotManipulationConfigKey.MODIFY_READ_ONLY_FLAG.value, bool, default_snapshot_manipulation, ) destination_directory = FilePackageConfigProvider._get_config_value( container, SnapshotManipulationConfigKey.DESTINATION_DIRECTORY.value, str, default_snapshot_manipulation, (Path, None), ) cleanup_exclusion_key = SnapshotManipulationConfigKey.CLEANUP_EXCLUSION.value cleanup_exclusion = cast( list, FilePackageConfigProvider._get_config_value( container, cleanup_exclusion_key, list, default_snapshot_manipulation, ), ) uuids: list[UUID] = [] if has_items(cleanup_exclusion): for item in cleanup_exclusion: if not isinstance(item, str): raise PackageConfigError( f"Every member of the '{cleanup_exclusion_key}' array must be a string!" ) uuid = try_parse_uuid(item) type_name = UUID.__name__ if uuid is None: raise PackageConfigError( f"Could not convert '{item}' to expected type ('{type_name}')!" ) if uuid == constants.EMPTY_UUID: raise PackageConfigError( f"The '{cleanup_exclusion_key}' array must " f"not contain empty '{type_name}' values!" ) uuids.append(uuid) return SnapshotManipulation( selection_count, modify_read_only_flag, destination_directory, set( Subvolume( constants.EMPTY_PATH, constants.EMPTY_STR, datetime.min, UuidRelation(uuid, constants.EMPTY_UUID), NumIdRelation(0, 0), False, ) for uuid in uuids ), ) @staticmethod def _map_to_boot_stanza_generation( boot_stanza_generation_value: Table, default_boot_stanza_generation: BootStanzaGeneration, ) -> BootStanzaGeneration: container = cast(dict, boot_stanza_generation_value) refind_config = FilePackageConfigProvider._get_config_value( container, BootStanzaGenerationConfigKey.REFIND_CONFIG.value, str, default_boot_stanza_generation, ) include_paths = FilePackageConfigProvider._get_config_value( container, BootStanzaGenerationConfigKey.INCLUDE_PATHS.value, bool, default_boot_stanza_generation, ) include_sub_menus = FilePackageConfigProvider._get_config_value( container, BootStanzaGenerationConfigKey.INCLUDE_SUB_MENUS.value, bool, default_boot_stanza_generation, ) source_exclusion_key = BootStanzaGenerationConfigKey.SOURCE_EXCLUSION.value source_exclusion = cast( list, FilePackageConfigProvider._get_config_value( container, source_exclusion_key, list, default_boot_stanza_generation, ), ) if has_items(source_exclusion): for item in source_exclusion: if not isinstance(item, str): raise PackageConfigError( f"Every member of the '{source_exclusion_key}' array must be a string!" ) icon_key = BootStanzaGenerationConfigKey.ICON.value if icon_key in container: icon = FilePackageConfigProvider._map_to_icon( checked_cast(Table, container[icon_key]), default_boot_stanza_generation.icon, ) else: icon = default_boot_stanza_generation.icon return BootStanzaGeneration( refind_config, include_paths, include_sub_menus, set(cast(str, loader_filename) for loader_filename in source_exclusion), icon, ) @staticmethod def _map_to_icon(icon_value: Table, default_icon: Icon) -> Icon: container = cast(dict, icon_value) mode = FilePackageConfigProvider._get_config_value( container, IconConfigKey.MODE.value, str, default_icon, ( BootStanzaIconGenerationMode, lambda value: try_convert_str_to_enum( value, BootStanzaIconGenerationMode ), ), ) if mode != BootStanzaIconGenerationMode.DEFAULT: pil_spec = find_spec("PIL") if pil_spec is None: raise PackageConfigError( f"The '{mode.value}' mode of boot stanza icon " "generation requires that the 'Pillow' package is installed!" ) path = FilePackageConfigProvider._get_config_value( container, IconConfigKey.PATH.value, str, default_icon, (Path, None), ) btrfs_logo_key = IconConfigKey.BTRFS_LOGO.value if btrfs_logo_key in container: btrfs_logo = FilePackageConfigProvider._map_to_btrfs_logo( checked_cast(Table, container[btrfs_logo_key]), default_icon.btrfs_logo, ) else: btrfs_logo = default_icon.btrfs_logo return Icon(mode, path, btrfs_logo) @staticmethod def _map_to_btrfs_logo( btrfs_logo_value: Table, default_btrfs_logo: BtrfsLogo ) -> BtrfsLogo: container = cast(dict, btrfs_logo_value) variant = FilePackageConfigProvider._get_config_value( container, BtrfsLogoConfigKey.VARIANT.value, str, default_btrfs_logo, ( BtrfsLogoVariant, lambda value: try_convert_str_to_enum(value, BtrfsLogoVariant), ), ) size = FilePackageConfigProvider._get_config_value( container, BtrfsLogoConfigKey.SIZE.value, str, default_btrfs_logo, ( BtrfsLogoSize, lambda value: try_convert_str_to_enum(value, BtrfsLogoSize), ), ) horizontal_alignment = FilePackageConfigProvider._get_config_value( container, BtrfsLogoConfigKey.HORIZONTAL_ALIGNMENT.value, str, default_btrfs_logo, ( BtrfsLogoHorizontalAlignment, lambda value: try_convert_str_to_enum( value, BtrfsLogoHorizontalAlignment ), ), ) vertical_alignment = FilePackageConfigProvider._get_config_value( container, BtrfsLogoConfigKey.VERTICAL_ALIGNMENT.value, str, default_btrfs_logo, ( BtrfsLogoVerticalAlignment, lambda value: try_convert_str_to_enum( value, BtrfsLogoVerticalAlignment ), ), ) return BtrfsLogo(variant, size, horizontal_alignment, vertical_alignment) @staticmethod def _get_config_value( container: dict, key: str, source_type: Type[TSourceValue], default_config: object, value_conversion: Optional[ tuple[Type[TDestinationValue], Optional[Callable[[TSourceValue], Any]]] ] = None, ) -> Any: if key in container: source_value = container[key] if not isinstance(source_value, source_type): raise PackageConfigError( f"The '{key}' option must be of type '{source_type.__name__}'!" ) if value_conversion is not None: destination_type = value_conversion[0] converter_func = value_conversion[1] if converter_func is None: converter_func = cast( Callable[[TSourceValue], Any], destination_type ) destination_value = converter_func(source_value) if destination_value is None: raise PackageConfigError( f"Could not convert '{source_value}' to " f"expected type ('{destination_type.__name__}')!" ) return checked_cast(destination_type, destination_value) return checked_cast(source_type, source_value) return getattr(default_config, key) ================================================ FILE: src/refind_btrfs/utility/helpers.py ================================================ # region Licensing # SPDX-FileCopyrightText: 2020-2024 Luka Žaja # # SPDX-License-Identifier: GPL-3.0-or-later """ refind-btrfs - Generate rEFInd manual boot stanzas from Btrfs snapshots Copyright (C) 2020-2024 Luka Žaja 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, either version 3 of the License, or (at your option) any later version. 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 . """ # endregion import errno import os import re from enum import Enum from inspect import ismethod from pathlib import Path from typing import Any, Iterator, Optional, Sized, Type, TypeVar, cast from uuid import UUID from more_itertools import first from typeguard import check_type from refind_btrfs.common import constants from refind_btrfs.common.enums import PathRelation TParam = TypeVar("TParam") def check_access_rights() -> None: if os.getuid() != constants.ROOT_UID: error_code = errno.EPERM raise PermissionError(error_code, os.strerror(error_code)) def try_parse_int(value: str, base: int = 10) -> Optional[int]: try: return int(value, base) except ValueError: return None def try_parse_uuid(value: str) -> Optional[UUID]: try: return UUID(hex=value) except ValueError: return None def try_convert_str_to_enum(value: str, enum_type: Type[Enum]) -> Optional[Enum]: upper_value = value.upper() member_names = [member.name for member in enum_type] if upper_value in member_names: return enum_type[upper_value] return None def try_convert_bytes_to_uuid(value: bytes) -> Optional[UUID]: try: return UUID(bytes=value) except ValueError: return None def is_empty(value: Optional[str]) -> bool: if value is None: return False return value == constants.EMPTY_STR def is_none_or_whitespace(value: Optional[str]) -> bool: if value is None: return True return is_empty(value) or value.isspace() def strip_quotes(value: Optional[str]) -> str: if not is_none_or_whitespace(value): return ( none_throws(value) .strip(constants.SINGLE_QUOTE) .strip(constants.DOUBLE_QUOTE) ) return constants.EMPTY_STR def has_method(obj: Any, method_name: str) -> bool: if hasattr(obj, method_name): attr = getattr(obj, method_name) return ismethod(attr) return False def has_items(value: Optional[Sized]) -> bool: return value is not None and len(value) > 0 def is_singleton(value: Optional[Sized]) -> bool: return value is not None and len(value) == 1 def item_count_suffix(value: Sized) -> str: assert has_items( value ), "The 'value' parameter must be initialized and contain least one item!" return constants.EMPTY_STR if is_singleton(value) else "s" def find_all_matched_files_in(root_directory: Path, filename: str) -> Iterator[Path]: if root_directory.exists() and root_directory.is_dir(): children = root_directory.iterdir() for child in children: if child.is_file(): if child.name == filename: yield child elif child.is_dir(): yield from find_all_matched_files_in(child, filename) def find_all_directories_in( root_directory: Path, max_depth: int, current_depth: int = 0 ) -> Iterator[Path]: if current_depth > max_depth: return if root_directory.exists() and root_directory.is_dir(): yield root_directory.resolve() subdirectories = (child for child in root_directory.iterdir() if child.is_dir()) for subdirectory in subdirectories: yield from find_all_directories_in( subdirectory, max_depth, current_depth + 1 ) def discern_path_relation_of(path_pair: tuple[Path, Path]) -> PathRelation: first_resolved = path_pair[0].resolve() second_resolved = path_pair[1].resolve() if first_resolved == second_resolved: return PathRelation.SAME first_parents = first_resolved.parents if second_resolved in first_parents: return PathRelation.FIRST_NESTED_IN_SECOND second_parents = second_resolved.parents if first_resolved in second_parents: return PathRelation.SECOND_NESTED_IN_FIRST return PathRelation.UNRELATED def discern_distance_between(path_pair: tuple[Path, Path]) -> Optional[int]: path_relation = discern_path_relation_of(path_pair) if path_relation != PathRelation.UNRELATED: distance = 0 if path_relation != PathRelation.SAME: if path_relation == PathRelation.FIRST_NESTED_IN_SECOND: first_parts = path_pair[0].parts second_stem = path_pair[1].stem for part in reversed(first_parts): if part != second_stem: distance += 1 else: break elif path_relation == PathRelation.SECOND_NESTED_IN_FIRST: first_stem = path_pair[0].stem second_parts = path_pair[1].parts for part in reversed(second_parts): if part != first_stem: distance += 1 else: break return distance return None def normalize_dir_separators_in( path: str, separator_replacement: tuple[ str, str ] = constants.DEFAULT_DIR_SEPARATOR_REPLACEMENT, ) -> str: path_with_replaced_separators = path.replace(*separator_replacement) pattern = re.compile(rf"(?P^({constants.DIR_SEPARATOR_PATTERN}){{2,}})") match = pattern.match(path_with_replaced_separators) if match: prefix = match.group("prefix") path_with_replaced_separators = path_with_replaced_separators.removeprefix( first(prefix) * (len(prefix) - 1) ) return path_with_replaced_separators def replace_root_part_in( full_path: str, current_root_part: str, replacement_root_part: str, separator_replacement: tuple[ str, str ] = constants.DEFAULT_DIR_SEPARATOR_REPLACEMENT, ) -> str: pattern = re.compile( rf"(?P^{constants.DIR_SEPARATOR_PATTERN}?)" f"{current_root_part}" rf"(?P{constants.DIR_SEPARATOR_PATTERN})" ) substituted_full_path = pattern.sub( rf"\g{replacement_root_part}\g", full_path ) return normalize_dir_separators_in(substituted_full_path, separator_replacement) def replace_item_in( items_list: list[TParam], current: TParam, replacement: Optional[TParam] = None ) -> None: if not has_items(items_list): return if current in items_list: index = items_list.index(current) if replacement is None: replacement = current items_list[index] = replacement def none_throws(value: Optional[TParam], message: str = "Unexpected 'None'") -> TParam: if value is None: raise AssertionError(message) return value def default_if_none(value: Optional[TParam], default: TParam) -> TParam: if value is None: return default return value def checked_cast(destination_type: Type[TParam], value: Any) -> TParam: check_type(value, destination_type) return cast(TParam, value) ================================================ FILE: src/refind_btrfs/utility/injector_modules.py ================================================ # region Licensing # SPDX-FileCopyrightText: 2020-2024 Luka Žaja # # SPDX-License-Identifier: GPL-3.0-or-later """ refind-btrfs - Generate rEFInd manual boot stanzas from Btrfs snapshots Copyright (C) 2020-2024 Luka Žaja 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, either version 3 of the License, or (at your option) any later version. 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 . """ # endregion from typing import Iterator from injector import Binder, Module, SingletonScope, multiprovider from transitions.core import State from watchdog.events import FileSystemEventHandler from refind_btrfs.boot.file_refind_config_provider import FileRefindConfigProvider from refind_btrfs.common import CheckableObserver from refind_btrfs.common.abc import BaseRunner from refind_btrfs.common.abc.factories import ( BaseDeviceCommandFactory, BaseIconCommandFactory, BaseLoggerFactory, BaseSubvolumeCommandFactory, ) from refind_btrfs.common.abc.providers import ( BasePackageConfigProvider, BasePersistenceProvider, BaseRefindConfigProvider, ) from refind_btrfs.common.enums import StateNames from refind_btrfs.console import CLIRunner from refind_btrfs.service import SnapshotEventHandler, SnapshotObserver, WatchdogRunner from refind_btrfs.state_management import Model, States from refind_btrfs.system import ( BtrfsUtilSubvolumeCommandFactory, PillowIconCommandFactory, SystemDeviceCommandFactory, ) from refind_btrfs.utility.helpers import has_method from .file_package_config_provider import FilePackageConfigProvider from .logger_factories import StreamLoggerFactory, SystemdLoggerFactory from .shelve_persistence_provider import ShelvePersistenceProvider class CommonModule(Module): def configure(self, binder: Binder) -> None: binder.bind(BaseDeviceCommandFactory, to=SystemDeviceCommandFactory) binder.bind(BaseSubvolumeCommandFactory, to=BtrfsUtilSubvolumeCommandFactory) binder.bind(BaseIconCommandFactory, to=PillowIconCommandFactory) # singletons binder.bind( BasePackageConfigProvider, to=FilePackageConfigProvider, scope=SingletonScope, ) binder.bind( BaseRefindConfigProvider, to=FileRefindConfigProvider, scope=SingletonScope ) binder.bind( BasePersistenceProvider, to=ShelvePersistenceProvider, scope=SingletonScope ) @multiprovider def provide_states(self, model: Model) -> States: return list(self._get_all_states_for(model)) def _get_all_states_for(self, model: Model) -> Iterator[State]: for state_name in StateNames: value: str = state_name.value arguments = [value] if has_method(model, value): arguments *= 2 yield State(*arguments) class WatchdogModule(CommonModule): def configure(self, binder: Binder) -> None: super().configure(binder) binder.bind(BaseRunner, to=WatchdogRunner) binder.bind(CheckableObserver, to=SnapshotObserver) binder.bind(FileSystemEventHandler, to=SnapshotEventHandler) binder.bind(BaseLoggerFactory, to=SystemdLoggerFactory) class CLIModule(CommonModule): def configure(self, binder: Binder) -> None: super().configure(binder) binder.bind(BaseRunner, to=CLIRunner) binder.bind(BaseLoggerFactory, to=StreamLoggerFactory) ================================================ FILE: src/refind_btrfs/utility/level_aware_formatter.py ================================================ # region Licensing # SPDX-FileCopyrightText: 2020-2024 Luka Žaja # # SPDX-License-Identifier: GPL-3.0-or-later """ refind-btrfs - Generate rEFInd manual boot stanzas from Btrfs snapshots Copyright (C) 2020-2024 Luka Žaja 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, either version 3 of the License, or (at your option) any later version. 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 . """ # endregion import logging from logging import Formatter, LogRecord from refind_btrfs.common import constants class LevelAwareFormatter(Formatter): def format(self, record: LogRecord) -> str: levelno = record.levelno fmt = constants.EMPTY_STR if levelno == logging.INFO: fmt = "%(message)s" elif levelno == logging.WARNING: fmt = "%(levelname)s: %(message)s" else: fmt = "%(levelname)s (%(name)s/%(filename)s/%(funcName)s): %(message)s" formatter = Formatter(fmt) return formatter.format(record) ================================================ FILE: src/refind_btrfs/utility/logger_factories.py ================================================ # region Licensing # SPDX-FileCopyrightText: 2020-2024 Luka Žaja # # SPDX-License-Identifier: GPL-3.0-or-later """ refind-btrfs - Generate rEFInd manual boot stanzas from Btrfs snapshots Copyright (C) 2020-2024 Luka Žaja 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, either version 3 of the License, or (at your option) any later version. 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 . """ # endregion import sys from logging import Handler, NullHandler, StreamHandler from systemd.journal import JournalHandler from refind_btrfs.common.abc.factories import BaseLoggerFactory class NullLoggerFactory(BaseLoggerFactory): def get_handler(self) -> Handler: return NullHandler() class StreamLoggerFactory(BaseLoggerFactory): def get_handler(self) -> Handler: return StreamHandler(sys.stdout) class SystemdLoggerFactory(BaseLoggerFactory): def get_handler(self) -> Handler: return JournalHandler() ================================================ FILE: src/refind_btrfs/utility/shelve_persistence_provider.py ================================================ # region Licensing # SPDX-FileCopyrightText: 2020-2024 Luka Žaja # # SPDX-License-Identifier: GPL-3.0-or-later """ refind-btrfs - Generate rEFInd manual boot stanzas from Btrfs snapshots Copyright (C) 2020-2024 Luka Žaja 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, either version 3 of the License, or (at your option) any later version. 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 . """ # endregion import shelve from pathlib import Path from shelve import Shelf from typing import Any, Optional, TypeVar, cast from semantic_version import Version from refind_btrfs.boot import RefindConfig from refind_btrfs.common import PackageConfig, constants from refind_btrfs.common.abc.providers import BasePersistenceProvider from refind_btrfs.common.enums import LocalDbKey from refind_btrfs.state_management.model import ProcessingResult from refind_btrfs.utility.helpers import checked_cast TItem = TypeVar("TItem") class ShelvePersistenceProvider(BasePersistenceProvider): def __init__(self) -> None: version_suffix = constants.DB_ITEM_VERSION_SUFFIX self._db_filename = str(constants.DB_FILE) self._current_versions = { f"{LocalDbKey.PACKAGE_CONFIG.value}_{version_suffix}": Version("1.3.0"), f"{LocalDbKey.REFIND_CONFIGS.value}_{version_suffix}": Version("1.0.0"), f"{LocalDbKey.PROCESSING_RESULT.value}_{version_suffix}": Version("1.1.0"), } def get_package_config(self) -> Optional[PackageConfig]: db_key = LocalDbKey.PACKAGE_CONFIG.value with shelve.open(self._db_filename) as local_db: item = self._get_item(db_key, local_db) if item is not None: package_config = checked_cast(PackageConfig, item) if not package_config.is_modified(constants.PACKAGE_CONFIG_FILE): return package_config return None def save_package_config(self, value: PackageConfig) -> None: db_key = LocalDbKey.PACKAGE_CONFIG.value with shelve.open(self._db_filename) as local_db: self._save_item(value, db_key, local_db) def get_refind_config(self, file_path: Path) -> Optional[RefindConfig]: db_key = LocalDbKey.REFIND_CONFIGS.value with shelve.open(self._db_filename) as local_db: item = self._get_item(db_key, local_db) if item is not None: all_refind_configs = checked_cast(dict[Path, RefindConfig], item) refind_config = all_refind_configs.get(file_path) if refind_config is not None: if refind_config.is_modified(file_path): del all_refind_configs[file_path] self._save_item(all_refind_configs, db_key, local_db) else: return refind_config return None def save_refind_config(self, value: RefindConfig) -> None: db_key = LocalDbKey.REFIND_CONFIGS.value with shelve.open(self._db_filename) as local_db: item = self._get_item(db_key, local_db) all_refind_configs: Optional[dict[Path, RefindConfig]] = None if item is not None: all_refind_configs = checked_cast(dict[Path, RefindConfig], item) else: all_refind_configs = {} file_path = value.file_path all_refind_configs[file_path] = value self._save_item(all_refind_configs, db_key, local_db) def get_previous_run_result(self) -> ProcessingResult: db_key = LocalDbKey.PROCESSING_RESULT.value with shelve.open(self._db_filename) as local_db: item = self._get_item(db_key, local_db) if item is not None: return cast(ProcessingResult, item) return ProcessingResult.none() def save_current_run_result(self, value: ProcessingResult) -> None: db_key = LocalDbKey.PROCESSING_RESULT.value with shelve.open(self._db_filename) as local_db: self._save_item(value, db_key, local_db) def _get_item(self, value_key: str, local_db: Shelf) -> Optional[Any]: version_key = f"{value_key}_{constants.DB_ITEM_VERSION_SUFFIX}" default_version = Version("0.0.0") current_version = self._current_versions[version_key] actual_version = ( checked_cast(Version, local_db[version_key]) if version_key in local_db else default_version ) return local_db.get(value_key) if actual_version >= current_version else None def _save_item(self, item: TItem, value_key: str, local_db: Shelf) -> None: version_key = f"{value_key}_{constants.DB_ITEM_VERSION_SUFFIX}" current_version = self._current_versions[version_key] local_db[value_key] = item local_db[version_key] = current_version ================================================ FILE: tests/.keep ================================================